import java.io.DataOutputStream;
import java.io.IOException;
import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
// look for the Base64 encoded part of the line to decode
// both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes
- bytes = Base64.getDecoder().decode(keyLine.getBytes());
+ bytes = Base64.getDecoder().decode(keyLine.getBytes(StandardCharsets.UTF_8));
if (bytes.length == 0) {
throw new IllegalArgumentException("No Base64 part to decode in " + keyLine);
}
private String decodeType() {
int len = decodeInt();
- String type = new String(bytes, pos, len);
+ String type = new String(bytes, pos, len, StandardCharsets.UTF_8);
pos += len;
return type;
}
}
public static String encodePublicKey(final PublicKey publicKey) throws IOException {
- String publicKeyEncoded;
ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
- if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_RSA)) {
+ if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_RSA) && publicKey instanceof RSAPublicKey) {
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
DataOutputStream dout = new DataOutputStream(byteOs);
- dout.writeInt(KEY_TYPE_RSA.getBytes().length);
- dout.write(KEY_TYPE_RSA.getBytes());
+ dout.writeInt(KEY_TYPE_RSA.getBytes(StandardCharsets.UTF_8).length);
+ dout.write(KEY_TYPE_RSA.getBytes(StandardCharsets.UTF_8));
dout.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length);
dout.write(rsaPublicKey.getPublicExponent().toByteArray());
dout.writeInt(rsaPublicKey.getModulus().toByteArray().length);
dout.write(rsaPublicKey.getModulus().toByteArray());
- } else if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_DSA)) {
+ } else if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_DSA) && publicKey instanceof DSAPublicKey) {
DSAPublicKey dsaPublicKey = (DSAPublicKey) publicKey;
DSAParams dsaParams = dsaPublicKey.getParams();
DataOutputStream dout = new DataOutputStream(byteOs);
- dout.writeInt(KEY_TYPE_DSA.getBytes().length);
- dout.write(KEY_TYPE_DSA.getBytes());
+ dout.writeInt(KEY_TYPE_DSA.getBytes(StandardCharsets.UTF_8).length);
+ dout.write(KEY_TYPE_DSA.getBytes(StandardCharsets.UTF_8));
dout.writeInt(dsaParams.getP().toByteArray().length);
dout.write(dsaParams.getP().toByteArray());
dout.writeInt(dsaParams.getQ().toByteArray().length);
dout.write(dsaParams.getG().toByteArray());
dout.writeInt(dsaPublicKey.getY().toByteArray().length);
dout.write(dsaPublicKey.getY().toByteArray());
- } else if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_ECDSA)) {
+ } else if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_ECDSA) && publicKey instanceof BCECPublicKey) {
BCECPublicKey ecPublicKey = (BCECPublicKey) publicKey;
DataOutputStream dout = new DataOutputStream(byteOs);
- dout.writeInt(KEY_TYPE_ECDSA.getBytes().length);
- dout.write(KEY_TYPE_ECDSA.getBytes());
- dout.writeInt(ECDSA_SUPPORTED_CURVE_NAME.getBytes().length);
- dout.write(ECDSA_SUPPORTED_CURVE_NAME.getBytes());
+ dout.writeInt(KEY_TYPE_ECDSA.getBytes(StandardCharsets.UTF_8).length);
+ dout.write(KEY_TYPE_ECDSA.getBytes(StandardCharsets.UTF_8));
+ dout.writeInt(ECDSA_SUPPORTED_CURVE_NAME.getBytes(StandardCharsets.UTF_8).length);
+ dout.write(ECDSA_SUPPORTED_CURVE_NAME.getBytes(StandardCharsets.UTF_8));
byte[] coordX = ecPublicKey.getQ().getAffineXCoord().getEncoded();
byte[] coordY = ecPublicKey.getQ().getAffineYCoord().getEncoded();
} else {
throw new IllegalArgumentException("Unknown public key encoding: " + publicKey.getAlgorithm());
}
- publicKeyEncoded = new String(Base64.getEncoder().encodeToString(byteOs.toByteArray()));
- return publicKeyEncoded;
+ return Base64.getEncoder().encodeToString(byteOs.toByteArray());
}
}
import org.opendaylight.netconf.topology.api.SchemaRepositoryProvider;
abstract class BaseCallHomeTopology extends AbstractNetconfTopology {
-
- protected DOMMountPointService mountPointService = null;
-
BaseCallHomeTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher,
final EventExecutor eventExecutor,
final ScheduledThreadPool keepaliveExecutor,
super(topologyId, clientDispatcher, eventExecutor, keepaliveExecutor,
processingExecutor, schemaRepositoryProvider, dataBroker, mountPointService,
encryptionService);
- this.mountPointService = mountPointService;
}
}
return remoteAddress.toString();
}
- private class DeviceConfig implements DataTreeChangeListener<Device> {
+ private static class DeviceConfig implements DataTreeChangeListener<Device> {
private final AuthorizedKeysDecoder keyDecoder = new AuthorizedKeysDecoder();
}
}
- private class DeviceOp implements DataTreeChangeListener<Device> {
+ private static class DeviceOp implements DataTreeChangeListener<Device> {
private final ConcurrentMap<String, Device> byPublicKey = new ConcurrentHashMap<>();
}
}
- private class GlobalConfig implements DataTreeChangeListener<Global> {
+ private static class GlobalConfig implements DataTreeChangeListener<Global> {
private volatile Global current = null;
}
}
- private final String path;
private Properties properties;
public Configuration() {
- path = "<no-path>";
properties = new Properties();
}
public Configuration(final String path) throws ConfigurationException {
- this.path = path;
try {
this.properties = readFromPath(path);
} catch (IOException ioe) {
@Nullable
private NormalizedNode<?, ?> rpcToNNode(final XmlElement element, @Nullable final ContainerSchemaNode input)
throws DocumentedException {
- if (input.getChildNodes().isEmpty()) {
+ if (input == null || input.getChildNodes().isEmpty()) {
return null;
}
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.regex.Pattern;
.put(cntr.getNotificationUrnPrefix(), cntr);
Map<String, Stream> availableStreams = getAvailableStreams();
LOG.debug("Stream configuration compare...");
- for (String urnPrefix : this.urnPrefixToStreamMap.keySet()) {
- final String streamName = this.urnPrefixToStreamMap.get(urnPrefix);
+ for (Entry<String, String> entry : this.urnPrefixToStreamMap.entrySet()) {
+ String urnPrefix = entry.getKey();
+ final String streamName = entry.getValue();
LOG.debug("urnPrefix: {} streamName: {}", urnPrefix, streamName);
if (availableStreams.containsKey(streamName)) {
LOG.debug("Stream containig on device");
}
}
- private void nodeUpdated(final InstanceIdentifier<?> key, final Node node) {
- Preconditions.checkNotNull(key);
- if (!validateNode(node)) {
- LOG.warn("NodeUpdated event : Node [{}] is null or not valid.", key.toString());
- return;
- }
-
- LOG.info("Netconf event source [{}] is updating...", key.toString());
- NetconfEventSourceRegistration nesr = registrationMap.get(key);
- if (nesr != null) {
- nesr.updateStatus();
- } else {
- nodeCreated(key, node);
- }
- }
-
private void nodeRemoved(final InstanceIdentifier<?> key) {
Preconditions.checkNotNull(key);
LOG.info("Netconf event source [{}] is removing...", key.toString());
package org.opendaylight.netconf.api;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Map;
import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.w3c.dom.Document;
super(message, cause, errorType, errorTag, errorSeverity, errorInfo);
}
+ @SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE")
public NetconfDocumentedException(final DocumentedException exception) {
super(exception.getMessage(), (Exception) exception.getCause(), exception.getErrorType(),
exception.getErrorTag(), exception.getErrorSeverity(), exception.getErrorInfo());
package org.opendaylight.netconf.api.util;
-import com.google.common.collect.Sets;
+import com.google.common.collect.ImmutableSet;
import java.util.Set;
/**
public static final String NETCONF_MONITORING = "ietf-netconf-monitoring";
public static final String NETCONF_NOTIFICATION = "ietf-netconf-notifications";
- public static final Set<String> CONFIG_SERVICE_MARKERS = Sets.newHashSet(SERVICE_NAME, CONFIG_NETCONF_CONNECTOR,
+ public static final Set<String> CONFIG_SERVICE_MARKERS = ImmutableSet.of(SERVICE_NAME, CONFIG_NETCONF_CONNECTOR,
NETCONF_MONITORING, NETCONF_NOTIFICATION);
private NetconfConstants() {
import io.netty.channel.EventLoopGroup;
import io.netty.util.Timer;
import io.netty.util.concurrent.Future;
-import java.io.Closeable;
import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
import org.opendaylight.protocol.framework.AbstractDispatcher;
import org.slf4j.LoggerFactory;
public class NetconfClientDispatcherImpl extends AbstractDispatcher<NetconfClientSession, NetconfClientSessionListener>
- implements NetconfClientDispatcher, Closeable {
+ implements NetconfClientDispatcher {
private static final Logger LOG = LoggerFactory.getLogger(NetconfClientDispatcherImpl.class);
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
}
@Override
+ @SuppressFBWarnings("BC_UNCONFIRMED_CAST")
protected void handleMessage(final NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
final NetconfClientSession session = getSessionForHelloMessage(netconfMessage);
replaceHelloMessageInboundHandler(session);
// If exi should be used, try to initiate exi communication
// Call negotiationSuccessFul after exi negotiation is finished successfully or not
- if (shouldUseExi(netconfMessage)) {
+ final NetconfMessage startExiMessage = sessionPreferences.getStartExiMessage();
+ if (shouldUseExi(netconfMessage) && startExiMessage instanceof NetconfStartExiMessage) {
LOG.debug("Netconf session {} should use exi.", session);
- NetconfStartExiMessage startExiMessage = (NetconfStartExiMessage) sessionPreferences.getStartExiMessage();
- tryToInitiateExi(session, startExiMessage);
+ tryToInitiateExi(session, (NetconfStartExiMessage) startExiMessage);
} else {
// Exi is not supported, release session immediately
LOG.debug("Netconf session {} isn't capable of using exi.", session);
});
}
+ @SuppressFBWarnings("BC_UNCONFIRMED_CAST")
private boolean shouldUseExi(final NetconfHelloMessage helloMsg) {
return containsExi10Capability(helloMsg.getDocument())
&& containsExi10Capability(sessionPreferences.getHelloMessage().getDocument());
}
}
- return Long.valueOf(textContent);
+ return Long.parseLong(textContent);
}
private static String getSessionIdWithXPath(final Document doc, final XPathExpression sessionIdXPath) {
package org.opendaylight.netconf.client;
import com.google.common.base.Preconditions;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.concurrent.Promise;
private NetconfClientSession clientSession;
@GuardedBy("this")
+ @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED")
private void dispatchRequest() {
while (!requests.isEmpty()) {
final RequestEntry e = requests.peek();
negotiationFutureListener = future -> {
if (future.isSuccess()) {
- connectPromise.setSuccess();
+ channelPromise.setSuccess();
}
};
//complete connection promise with netconf negotiation future
negotiationFuture.addListener(negotiationFutureListener);
} else {
- connectPromise.setFailure(future.cause());
+ channelPromise.setFailure(future.cause());
}
});
ctx.connect(remoteAddress, localAddress, tcpConnectFuture);
@Override
public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
+ if (connectPromise == null) {
+ return;
+ }
+
// If we have already succeeded and the session was dropped after, we need to fire inactive to notify
// reconnect logic
if (connectPromise.isSuccess()) {
return sslHandlerFactory;
}
- @SuppressWarnings("checkstyle:FallThrough")
private void validateConfiguration() {
Preconditions.checkNotNull(clientProtocol, " ");
switch (clientProtocol) {
case TLS:
+ validateTlsConfiguration();
+ validateTcpConfiguration();
+ break;
case SSH:
- if (clientProtocol == NetconfClientProtocol.SSH) {
- validateSshConfiguration();
- } else {
- validateTlsConfiguration();
- }
- // Fall through intentional (ssh or tls validation is a superset of tcp validation)
+ validateSshConfiguration();
+ validateTcpConfiguration();
+ break;
case TCP:
validateTcpConfiguration();
break;
public enum NetconfClientProtocol {
TCP, SSH, TLS
}
-}
\ No newline at end of file
+}
table.column(NetconfConsoleConstants.NETCONF_PORT).alignLeft();
table.column(NetconfConsoleConstants.STATUS).alignLeft();
- for (final String nodeIds : allDevices.keySet()) {
- final Map<String, String> attributes = allDevices.get(nodeIds);
+ for (final Map<String, String> attributes : allDevices.values()) {
table.addRow().addContent(attributes.get(NetconfConsoleConstants.NETCONF_ID),
attributes.get(NetconfConsoleConstants.NETCONF_IP),
attributes.get(NetconfConsoleConstants.NETCONF_PORT),
import com.google.common.base.Strings;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import javax.annotation.Nonnull;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
}
if (!NetconfCommandUtils.isIpValid(deviceIp)
- || (devicePort != null && !NetconfCommandUtils.isPortValid(devicePort))) {
+ || devicePort != null && !NetconfCommandUtils.isPortValid(devicePort)) {
return "Invalid IP:" + deviceIp + " or Port:" + devicePort + "Please enter a valid entry to proceed.";
}
table.column(NetconfConsoleConstants.STATUS).alignLeft();
table.column(NetconfConsoleConstants.AVAILABLE_CAPABILITIES).alignLeft();
- for (final String nodeId : devices.keySet()) {
- final Map<String, List<String>> device = devices.get(nodeId);
+ for (final Entry<String, Map<String, List<String>>> entry : devices.entrySet()) {
+ final String nodeId = entry.getKey();
+ final Map<String, List<String>> device = entry.getValue();
table.addRow().addContent(nodeId,
device.get(NetconfConsoleConstants.NETCONF_IP).get(NetconfConsoleConstants.DEFAULT_INDEX),
device.get(NetconfConsoleConstants.NETCONF_PORT).get(NetconfConsoleConstants.DEFAULT_INDEX),
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
attributes.put(NetconfConsoleConstants.NETCONF_IP,
netconfNode.getHost().getIpAddress().getIpv4Address().getValue());
attributes.put(NetconfConsoleConstants.NETCONF_PORT, netconfNode.getPort().getValue().toString());
- attributes.put(NetconfConsoleConstants.STATUS, netconfNode.getConnectionStatus().name().toLowerCase());
+ attributes.put(NetconfConsoleConstants.STATUS, netconfNode.getConnectionStatus().name()
+ .toLowerCase(Locale.ROOT));
netconfNodes.put(node.getNodeId().getValue(), attributes);
}
return netconfNodes;
package org.opendaylight.netconf.impl;
import com.google.common.base.Optional;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.channel.Channel;
import io.netty.channel.local.LocalAddress;
import io.netty.util.Timer;
}
@Override
+ @SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE")
protected NetconfServerSession getSession(
NetconfServerSessionListener sessionListener, Channel channel,
NetconfHelloMessage message) {
int msgLength = out.readableBytes();
int chunkCount = msgLength / ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE;
- if ((msgLength % ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE) != 0) {
+ if (msgLength % ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE != 0) {
chunkCount++;
}
+
+ byte[] endOfChunkBytes = NetconfMessageConstants.END_OF_CHUNK.getBytes(StandardCharsets.UTF_8);
for (int i = 1; i <= chunkCount; i++) {
ByteBuf recievedOutbound = (ByteBuf) messages.poll();
int exptHeaderLength = ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE;
if (i == chunkCount) {
- exptHeaderLength = msgLength - (ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE * (i - 1));
- byte[] eom = new byte[NetconfMessageConstants.END_OF_CHUNK.length];
- recievedOutbound
- .getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_CHUNK.length, eom);
- assertArrayEquals(NetconfMessageConstants.END_OF_CHUNK, eom);
+ exptHeaderLength = msgLength - ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE * (i - 1);
+ byte[] eom = new byte[endOfChunkBytes.length];
+ recievedOutbound.getBytes(recievedOutbound.readableBytes() - endOfChunkBytes.length, eom);
+ assertArrayEquals(endOfChunkBytes, eom);
}
byte[] header = new byte[String.valueOf(exptHeaderLength).length()
testChunkChannel.writeOutbound(this.msg);
ByteBuf recievedOutbound = (ByteBuf) testChunkChannel.readOutbound();
- byte[] eom = new byte[NetconfMessageConstants.END_OF_MESSAGE.length];
- recievedOutbound.getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_MESSAGE.length,
- eom);
- assertArrayEquals(NetconfMessageConstants.END_OF_MESSAGE, eom);
+ byte[] endOfMsgBytes = NetconfMessageConstants.END_OF_MESSAGE.getBytes(StandardCharsets.UTF_8);
+ byte[] eom = new byte[endOfMsgBytes.length];
+ recievedOutbound.getBytes(recievedOutbound.readableBytes() - endOfMsgBytes.length, eom);
+ assertArrayEquals(endOfMsgBytes, eom);
testChunkChannel.writeInbound(recievedOutbound);
NetconfMessage receivedMessage = (NetconfMessage) testChunkChannel.readInbound();
@XmlElement(name = "namespace")
public String getNamespace() {
- return schema.getNamespace().getValue().toString();
+ return schema.getNamespace().getValue();
}
@XmlElement(name = "location")
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import java.nio.charset.StandardCharsets;
-import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf> {
public static final int DEFAULT_CHUNK_SIZE = 8192;
do {
final int xfer = Math.min(chunkSize, msg.readableBytes());
- out.writeBytes(NetconfMessageConstants.START_OF_CHUNK);
+ out.writeBytes(MessageParts.START_OF_CHUNK);
out.writeBytes(String.valueOf(xfer).getBytes(StandardCharsets.US_ASCII));
out.writeByte('\n');
out.writeBytes(msg, xfer);
} while (msg.isReadable());
- out.writeBytes(NetconfMessageConstants.END_OF_CHUNK);
+ out.writeBytes(MessageParts.END_OF_CHUNK);
}
}
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
-import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
public class EOMFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf> {
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) {
out.writeBytes(msg);
- out.writeBytes(NetconfMessageConstants.END_OF_MESSAGE);
+ out.writeBytes(MessageParts.END_OF_MESSAGE);
}
}
--- /dev/null
+/*
+ * Copyright (c) 2018 Inocybe Technologies and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.netconf.nettyutil.handler;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
+
+/**
+ * netconf message part constants as bytes.
+ *
+ * @author Thomas Pantelis
+ */
+interface MessageParts {
+ byte[] END_OF_MESSAGE = NetconfMessageConstants.END_OF_MESSAGE.getBytes(UTF_8);
+ byte[] START_OF_CHUNK = NetconfMessageConstants.START_OF_CHUNK.getBytes(UTF_8);
+ byte[] END_OF_CHUNK = NetconfMessageConstants.END_OF_CHUNK.getBytes(UTF_8);
+}
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
-import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
public class NetconfEOMAggregator extends DelimiterBasedFrameDecoder {
- public static final ByteBuf DELIMITER = Unpooled.wrappedBuffer(NetconfMessageConstants.END_OF_MESSAGE);
+ public static final ByteBuf DELIMITER = Unpooled.wrappedBuffer(MessageParts.END_OF_MESSAGE);
public NetconfEOMAggregator() {
super(Integer.MAX_VALUE, DELIMITER);
session = future.getSession();
final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
+ final ClientSession localSession = session;
authenticateFuture.addListener(future1 -> {
if (future1.isSuccess()) {
- handleSshAuthenticated(session, ctx);
+ handleSshAuthenticated(localSession, ctx);
} else {
// Exception does not have to be set in the future, add simple exception in such case
final Throwable exception = future1.getException() == null
// TODO we should also read from error stream and at least log from that
+ ClientChannel localChannel = channel;
sshReadAsyncListener = new AsyncSshHandlerReader(() -> AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()),
- msg -> ctx.fireChannelRead(msg), channel.toString(), channel.getAsyncOut());
+ msg -> ctx.fireChannelRead(msg), localChannel.toString(), localChannel.getAsyncOut());
// if readAsyncListener receives immediate close,
// it will close this handler and closing this handler sets channel variable to null
this.connectPromise = promise;
if (negotiationFuture != null) {
-
negotiationFutureListener = future -> {
if (future.isSuccess()) {
- connectPromise.setSuccess();
+ promise.setSuccess();
}
};
//complete connection promise with netconf negotiation future
if (session != null && !session.isClosed() && !session.isClosing()) {
session.close(false).addListener(future -> {
- if (!future.isClosed()) {
- session.close(true);
+ synchronized (this) {
+ if (!future.isClosed()) {
+ session.close(true);
+ }
+ session = null;
}
- session = null;
});
}
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.Test;
-import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
public class EOMFramingMechanismEncoderTest {
final ByteBuf destination = Unpooled.buffer();
new EOMFramingMechanismEncoder().encode(null, source, destination);
- assertEquals(Unpooled.wrappedBuffer(source.array(), NetconfMessageConstants.END_OF_MESSAGE), destination);
+ assertEquals(Unpooled.wrappedBuffer(source.array(), MessageParts.END_OF_MESSAGE), destination);
}
-}
\ No newline at end of file
+}
package org.opendaylight.netconf.notifications;
import com.google.common.base.Preconditions;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.text.ParsePosition;
import java.time.Instant;
import java.time.LocalDateTime;
/**
* Create new notification with provided timestamp.
*/
+ @SuppressFBWarnings("EI_EXPOSE_REP2") // stores a reference to an externally mutable Date object
public NetconfNotification(final Document notificationContent, final Date eventTime) {
super(wrapNotification(notificationContent, eventTime));
this.eventTime = eventTime;
*
* @return notification event time
*/
+ @SuppressFBWarnings("EI_EXPOSE_REP")
public Date getEventTime() {
return eventTime;
}
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
import java.io.IOException;
private static RpcDefinition findCreateSubscriptionRpc() {
return Iterables.getFirst(Collections2.filter(NOTIFICATIONS_SCHEMA_CTX.getOperations(),
- new Predicate<RpcDefinition>() {
- @Override
- public boolean apply(final RpcDefinition input) {
- return input.getQName().getLocalName().equals(CreateSubscription.CREATE_SUBSCRIPTION);
- }
- }), null);
+ input -> input.getQName().getLocalName().equals(CreateSubscription.CREATE_SUBSCRIPTION)), null);
}
/**
<propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
</configuration>
</plugin>
-<!--
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<failOnError>true</failOnError>
</configuration>
</plugin>
--->
</plugins>
</build>
</project>
package org.opendaylight.netconf.ssh;
-import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
+import java.nio.charset.StandardCharsets;
import org.apache.sshd.common.io.IoInputStream;
import org.apache.sshd.common.io.IoOutputStream;
import org.apache.sshd.server.ExitCallback;
writeAdditionalHeader(ctx);
asyncSshHandlerWriter = new AsyncSshHandlerWriter(out);
- asyncSshHandlerReader = new AsyncSshHandlerReader(new AutoCloseable() {
- @Override
- public void close() throws Exception {
- // Close both sessions (delegate server and remote client)
- ctx.fireChannelInactive();
- ctx.disconnect();
- ctx.close();
- asyncSshHandlerReader.close();
- asyncSshHandlerWriter.close();
- }
- }, new AsyncSshHandlerReader.ReadMsgHandler() {
- @Override
- public void onMessageRead(final ByteBuf msg) {
- if (LOG.isTraceEnabled()) {
- LOG.trace("Forwarding message for client: {} on channel: {}, message: {}",
- netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel(),
- AsyncSshHandlerWriter.byteBufToString(msg));
- }
- // Just forward to delegate
- ctx.writeAndFlush(msg);
+ asyncSshHandlerReader = new AsyncSshHandlerReader(() -> {
+ // Close both sessions (delegate server and remote client)
+ ctx.fireChannelInactive();
+ ctx.disconnect();
+ ctx.close();
+ asyncSshHandlerReader.close();
+ asyncSshHandlerWriter.close();
+ }, msg -> {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Forwarding message for client: {} on channel: {}, message: {}",
+ netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel(),
+ AsyncSshHandlerWriter.byteBufToString(msg));
}
+ // Just forward to delegate
+ ctx.writeAndFlush(msg);
}, "ssh" + netconfHelloMessageAdditionalHeader.getAddress(), in);
}
private void writeAdditionalHeader(final ChannelHandlerContext ctx) {
- ctx.writeAndFlush(Unpooled.copiedBuffer(netconfHelloMessageAdditionalHeader.toFormattedString().getBytes()));
+ ctx.writeAndFlush(Unpooled.copiedBuffer(netconfHelloMessageAdditionalHeader.toFormattedString()
+ .getBytes(StandardCharsets.UTF_8)));
}
@Override
import io.netty.channel.EventLoopGroup;
import java.io.IOException;
import java.nio.channels.AsynchronousChannelGroup;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
sshServer.start();
}
- private static Map<String, String> getProperties(final SshProxyServerConfiguration sshProxyServerConfiguration) {
- final Map<String, String> ret = new HashMap<>();
- ret.put(ServerFactoryManager.IDLE_TIMEOUT, String.valueOf(sshProxyServerConfiguration.getIdleTimeout()));
- // TODO make auth timeout configurable on its own
- ret.put(ServerFactoryManager.AUTH_TIMEOUT, String.valueOf(sshProxyServerConfiguration.getIdleTimeout()));
-
- return ret;
- }
-
@Override
public void close() throws IOException {
try {
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
private NetconfNodeManager netconfNodeManager;
private ActorRef masterActorRef;
private boolean finalClose = false;
- private boolean closed = false;
+ private final AtomicBoolean closed = new AtomicBoolean(false);
private boolean isMaster;
NetconfTopologyContext(final NetconfTopologySetup netconfTopologyDeviceSetup,
}
}
- private synchronized void stopDeviceConnectorAndActor() {
- if (closed) {
+ private void stopDeviceConnectorAndActor() {
+ if (!closed.compareAndSet(false, true)) {
return;
}
if (remoteDeviceConnector != null) {
netconfTopologyDeviceSetup.getActorSystem().stop(masterActorRef);
masterActorRef = null;
}
- closed = true;
}
}
NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node,
final ActorRef deviceContextActorRef) {
//setup default values since default value is not supported in mdsal
- final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
+ final long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
? NetconfTopologyUtils.DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
- final Long keepaliveDelay = node.getKeepaliveDelay() == null
+ final long keepaliveDelay = node.getKeepaliveDelay() == null
? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
- final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
+ final boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
RemoteDeviceHandler<NetconfSessionPreferences> salFacade = new MasterSalFacade(remoteDeviceId,
@Override
public ReconnectStrategy createReconnectStrategy() {
- final Long maxSleep = null;
- final Long deadline = null;
-
return new TimedReconnectStrategy(executor, minSleep,
- minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
+ minSleep, sleepFactor, null /*maxSleep*/, connectionAttempts, null /*deadline*/);
}
}
}
Futures.addCallback(remoteSchemaContext, new FutureCallback<SchemaContext>() {
@Override
- public void onSuccess(final SchemaContext result) {
+ public void onSuccess(@Nonnull final SchemaContext result) {
LOG.info("{}: Schema context resolved: {}", id, result.getModules());
slaveSalManager.registerSlaveMountPoint(result, deviceRpcService, masterReference);
}
Futures.addCallback(read, new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
@Override
- public void onSuccess(final Optional<NormalizedNode<?, ?>> result) {
+ public void onSuccess(@Nonnull final Optional<NormalizedNode<?, ?>> result) {
if (!result.isPresent()) {
sender.tell(new EmptyReadResponse(), self);
return;
package org.opendaylight.netconf.topology.singleton.messages;
-import java.io.Serializable;
import java.util.List;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
/**
* Master sends this message to the own actor to set necessary parameters.
*/
-public class CreateInitialMasterActorData implements Serializable {
- private static final long serialVersionUID = 1L;
-
+public class CreateInitialMasterActorData {
private final DOMDataBroker deviceDataBroker;
private final List<SourceIdentifier> allSourceIdentifiers;
private final DOMRpcService deviceRpc;
package org.opendaylight.netconf.topology.singleton.messages;
-import java.io.Serializable;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
/**
* Master sends this message to the own actor to refresh setup data.
*/
-public class RefreshSetupMasterActorData implements Serializable {
- private static final long serialVersionUID = 1L;
-
+public class RefreshSetupMasterActorData {
private final NetconfTopologySetup netconfTopologyDeviceSetup;
private final RemoteDeviceId remoteDeviceId;
package org.opendaylight.netconf.topology.singleton.messages;
import akka.util.Timeout;
-import java.io.Serializable;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
-public class RefreshSlaveActor implements Serializable {
+public class RefreshSlaveActor {
private final SchemaRepository schemaRepository;
private final RemoteDeviceId id;
package org.opendaylight.netconf.topology.singleton.messages;
import com.google.common.collect.Iterables;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
public class SchemaPathMessage implements Serializable {
private static final long serialVersionUID = 1L;
- private SchemaPath schemaPath;
+ @SuppressFBWarnings("SE_BAD_FIELD")
+ private final SchemaPath schemaPath;
public SchemaPathMessage(final SchemaPath schemaPath) {
this.schemaPath = schemaPath;
private SchemaPathMessage schemaPathMessage;
- Proxy() {
+ @SuppressWarnings("checkstyle:RedundantModifier")
+ public Proxy() {
//due to Externalizable
}
private InvokeRpcMessage invokeRpcMessage;
- Proxy() {
+ @SuppressWarnings("checkstyle:RedundantModifier")
+ public Proxy() {
//due to Externalizable
}
package org.opendaylight.netconf.topology.singleton.messages.rpc;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
public class InvokeRpcMessageReply implements Serializable {
private static final long serialVersionUID = 1L;
+ @SuppressFBWarnings("SE_BAD_FIELD")
private final Collection<RpcError> rpcErrors;
private final NormalizedNodeMessage normalizedNodeMessage;
private InvokeRpcMessageReply invokeRpcMessageReply;
- Proxy() {
+ @SuppressWarnings("checkstyle:RedundantModifier")
+ public Proxy() {
//due to Externalizable
}
import java.io.Serializable;
public class NewReadTransactionReply implements Serializable {
+ private static final long serialVersionUID = 1L;
private final ActorRef txActor;
import java.io.Serializable;
public class NewReadTransactionRequest implements Serializable {
+ private static final long serialVersionUID = 1L;
}
import java.io.Serializable;
public class NewReadWriteTransactionReply implements Serializable {
+ private static final long serialVersionUID = 1L;
private final ActorRef txActor;
import java.io.Serializable;
public class NewWriteTransactionReply implements Serializable {
+ private static final long serialVersionUID = 1L;
private final ActorRef txActor;
import java.io.Serializable;
public class NewWriteTransactionRequest implements Serializable {
+ private static final long serialVersionUID = 1L;
}
protected NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId,
final NetconfNode node) {
//setup default values since default value is not supported in mdsal
- final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
+ final long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
? DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
- final Long keepaliveDelay = node.getKeepaliveDelay() == null
+ final long keepaliveDelay = node.getKeepaliveDelay() == null
? DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
- final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
+ final boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
? DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
final IpAddress ipAddress = node.getHost().getIpAddress();
@Override
public ReconnectStrategy createReconnectStrategy() {
- final Long maxSleep = null;
- final Long deadline = null;
-
return new TimedReconnectStrategy(executor, minSleep,
- minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
+ minSleep, sleepFactor, null /*maxSleep*/, connectionAttempts, null /*deadline*/);
}
}
package org.opendaylight.netconf.util.messages;
-import static java.nio.charset.StandardCharsets.UTF_8;
-
-public final class NetconfMessageConstants {
-
- private NetconfMessageConstants(){}
+public interface NetconfMessageConstants {
/**
* The NETCONF 1.0 old-style message separator. This is framing mechanism
* is used by default.
*/
- public static final byte[] END_OF_MESSAGE = "]]>]]>".getBytes(UTF_8);
+ String END_OF_MESSAGE = "]]>]]>";
// bytes
- public static final int MIN_HEADER_LENGTH = 4;
+ int MIN_HEADER_LENGTH = 4;
// bytes
- public static final int MAX_HEADER_LENGTH = 13;
-
- public static final byte[] START_OF_CHUNK = "\n#".getBytes(UTF_8);
- public static final byte[] END_OF_CHUNK = "\n##\n".getBytes(UTF_8);
+ int MAX_HEADER_LENGTH = 13;
+ String START_OF_CHUNK = "\n#";
+ String END_OF_CHUNK = "\n##\n";
}
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
+import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.Collections;
+import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
import javax.xml.transform.dom.DOMSource;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
+import org.xml.sax.SAXException;
/**
* Holds URLs with YANG schema resources for all yang modules reported in
if (connection instanceof HttpURLConnection) {
connection.setRequestProperty("Accept", "application/xml");
final String userpass = username + ":" + password;
- final String basicAuth = "Basic " + printBase64Binary(userpass.getBytes());
+ final String basicAuth = "Basic " + printBase64Binary(userpass.getBytes(StandardCharsets.UTF_8));
connection.setRequestProperty("Authorization", basicAuth);
}
String extension = "";
final int i = fileName.lastIndexOf(46);
if (i != -1) {
- extension = fileName.substring(i).toLowerCase();
+ extension = fileName.substring(i).toLowerCase(Locale.ROOT);
}
return extension.equals(".json");
final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
final JsonParserStream jsonParser = JsonParserStream.create(writer, LIBRARY_CONTEXT);
- final JsonReader reader = new JsonReader(new InputStreamReader(in));
+ final JsonReader reader = new JsonReader(new InputStreamReader(in, Charset.defaultCharset()));
jsonParser.parse(reader);
return resultHolder.isFinished() ? Optional.of(resultHolder.getResult()) : Optional.empty();
}
- @SuppressWarnings("checkstyle:IllegalCatch")
private static Optional<NormalizedNode<?, ?>> readXml(final InputStream in) {
try {
final DocumentBuilder docBuilder = UntrustedXML.newDocumentBuilder();
xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
final NormalizedNode<?, ?> parsed = resultHolder.getResult();
return Optional.of(parsed);
- } catch (final Exception e) {
+ } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException
+ | SAXException e) {
LOG.warn("Unable to parse yang library xml content", e);
}
private static Optional<String> getValueOfSimpleNode(
final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
- final Object value = node.getValue();
- return value == null || Strings.isNullOrEmpty(value.toString()) ? Optional.empty()
- : Optional.of(value.toString().trim());
+ final String valueStr = node.getValue().toString();
+ return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
}
@Override
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
+import javax.annotation.Nonnull;
import javax.annotation.concurrent.GuardedBy;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
@Override
- public void onSuccess(final DeviceSources result) {
+ public void onSuccess(@Nonnull final DeviceSources result) {
addProvidedSourcesToSchemaRegistry(result);
setUpSchema(result);
}
updateTransformer(null);
}
- private void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
+ private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
messageTransformer = transformer;
}
if (cause instanceof MissingSchemaSourceException) {
requiredSources = handleMissingSchemaSourceException(
- requiredSources, (MissingSchemaSourceException) e.getCause());
+ requiredSources, (MissingSchemaSourceException) cause);
continue;
}
if (cause instanceof SchemaResolutionException) {
private static Optional<String> getValueOfSimpleNode(
final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
- final Object value = node.getValue();
- return value == null || Strings.isNullOrEmpty(value.toString())
- ? Optional.empty() : Optional.of(value.toString().trim());
+ final String valueStr = node.getValue().toString();
+ return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
}
@Override
try {
request = requests.peek();
if (request != null && request.future.isUncancellable()) {
- requests.poll();
+ request = requests.poll();
// we have just removed one request from the queue
// we can also release one permit
if (semaphore != null) {
@Override
public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
sessionLock.lock();
-
- if (semaphore != null && !semaphore.tryAcquire()) {
- LOG.warn("Limit of concurrent rpc messages was reached (limit :"
- + concurentRpcMsgs + "). Rpc reply message is needed. Discarding request of Netconf device with id"
- + id.getName());
- sessionLock.unlock();
- return Futures.immediateFailedFuture(new NetconfDocumentedException(
- "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs
- + ") waiting for emptying the queue of Netconf device with id" + id.getName()));
- }
-
try {
+ if (semaphore != null && !semaphore.tryAcquire()) {
+ LOG.warn("Limit of concurrent rpc messages was reached (limit :" + concurentRpcMsgs
+ + "). Rpc reply message is needed. Discarding request of Netconf device with id" + id.getName());
+ return Futures.immediateFailedFuture(new NetconfDocumentedException(
+ "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs
+ + ") waiting for emptying the queue of Netconf device with id" + id.getName()));
+ }
+
return sendRequestWithLock(message, rpc);
} finally {
sessionLock.unlock();
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.AbstractFuture;
import javax.annotation.Nullable;
-import javax.annotation.concurrent.GuardedBy;
final class UncancellableFuture<V> extends AbstractFuture<V> {
- @GuardedBy("this")
- private boolean uncancellable = false;
+ private volatile boolean uncancellable = false;
UncancellableFuture(final boolean uncancellable) {
this.uncancellable = uncancellable;
}
- public synchronized boolean setUncancellable() {
+ public boolean setUncancellable() {
if (isCancelled()) {
return false;
}
return true;
}
- public synchronized boolean isUncancellable() {
+ public boolean isUncancellable() {
return uncancellable;
}
@Override
- public synchronized boolean cancel(final boolean mayInterruptIfRunning) {
+ public boolean cancel(final boolean mayInterruptIfRunning) {
return !uncancellable && super.cancel(mayInterruptIfRunning);
}
@Override
- public synchronized boolean set(@Nullable final V value) {
+ public boolean set(@Nullable final V value) {
Preconditions.checkState(uncancellable);
return super.set(value);
}
if (result != null && result.getResult() != null) {
LOG.debug("{}: Keepalive RPC successful with response: {}", id, result.getResult());
scheduleKeepalive();
- } else if (result != null && result.getErrors() != null) {
+ } else if (result != null && !result.getErrors().isEmpty()) {
LOG.warn("{}: Keepalive RPC failed with error: {}", id, result.getErrors());
scheduleKeepalive();
} else {
- LOG.warn("{} Keepalive RPC returned null with response: {}. Reconnecting netconf session", id, result);
+ LOG.warn("{} Keepalive RPC returned null with response. Reconnecting netconf session", id);
reconnect();
}
}
public static final class KeepaliveDOMRpcService implements DOMRpcService {
private final DOMRpcService deviceRpc;
- private ResetKeepalive resetKeepaliveTask;
+ private final ResetKeepalive resetKeepaliveTask;
private final long defaultRequestTimeoutMillis;
private final ScheduledExecutorService executor;
*/
package org.opendaylight.netconf.sal.connect.netconf.sal;
-import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
}
}, MoreExecutors.directExecutor());
- return Futures.makeChecked(transformed, new Function<Exception, DOMRpcException>() {
- @Nullable
- @Override
- public DOMRpcException apply(@Nullable final Exception exception) {
- return new DOMRpcImplementationNotAvailableException(exception, "Unable to invoke rpc %s", type);
- }
- });
+ return Futures.makeChecked(transformed, exception ->
+ new DOMRpcImplementationNotAvailableException(exception, "Unable to invoke rpc %s", type));
}
@Nonnull
}, MoreExecutors.directExecutor());
}
- private static Node getNodeWithId(final RemoteDeviceId id) {
- final NodeBuilder builder = getNodeIdBuilder(id);
- return builder.build();
- }
-
private static NodeBuilder getNodeIdBuilder(final RemoteDeviceId id) {
final NodeBuilder nodeBuilder = new NodeBuilder();
nodeBuilder.setKey(new NodeKey(new NodeId(id.getName())));
import com.google.common.util.concurrent.SettableFuture;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
-import javax.annotation.Nullable;
+import javax.annotation.Nonnull;
import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
protected final List<ListenableFuture<DOMRpcResult>> resultsFutures;
private final List<TxListener> listeners = new CopyOnWriteArrayList<>();
// Allow commit to be called only once
- protected boolean finished = false;
+ protected volatile boolean finished = false;
public AbstractWriteTx(final NetconfBaseOps netOps, final RemoteDeviceId id, final boolean rollbackSupport) {
this.netOps = netOps;
final ListenableFuture<RpcResult<Void>> result = performCommit();
Futures.addCallback(result, new FutureCallback<RpcResult<Void>>() {
@Override
- public void onSuccess(@Nullable final RpcResult<Void> result) {
- if (result != null && result.isSuccessful()) {
+ public void onSuccess(@Nonnull final RpcResult<Void> rpcResult) {
+ if (rpcResult.isSuccessful()) {
listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
} else {
final TransactionCommitFailedException cause =
new TransactionCommitFailedException("Transaction failed",
- result.getErrors().toArray(new RpcError[result.getErrors().size()]));
+ rpcResult.getErrors().toArray(new RpcError[rpcResult.getErrors().size()]));
listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, cause));
}
}
Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
@Override
- public void onSuccess(final List<DOMRpcResult> domRpcResults) {
+ public void onSuccess(@Nonnull final List<DOMRpcResult> domRpcResults) {
domRpcResults.forEach(domRpcResult -> {
if (!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
final NetconfDocumentedException exception =
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
+import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
private void lock() {
final FutureCallback<DOMRpcResult> lockCandidateCallback = new FutureCallback<DOMRpcResult>() {
@Override
- public void onSuccess(final DOMRpcResult result) {
+ public void onSuccess(@Nonnull final DOMRpcResult result) {
if (isSuccess(result)) {
if (LOG.isTraceEnabled()) {
LOG.trace("Lock candidate successful");
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
+import javax.annotation.Nonnull;
import javax.xml.transform.dom.DOMSource;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
}
@Override
- public YangTextSchemaSource apply(final DOMRpcResult input) {
+ public YangTextSchemaSource apply(@Nonnull final DOMRpcResult input) {
if (input.getErrors().isEmpty()) {
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
+import java.nio.charset.Charset;
import java.util.Map;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
private ListenableFuture<? extends YangTextSchemaSource> download(final SourceIdentifier sourceIdentifier) {
final URL url = availableSources.get(sourceIdentifier);
try (InputStream in = url.openStream()) {
- final String schemaContent = new String(ByteStreams.toByteArray(in));
+ final String schemaContent = new String(ByteStreams.toByteArray(in), Charset.defaultCharset());
final NetconfRemoteSchemaYangSourceProvider.NetconfYangTextSchemaSource yangSource =
new NetconfRemoteSchemaYangSourceProvider
.NetconfYangTextSchemaSource(id, sourceIdentifier, Optional.of(schemaContent));
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import java.io.IOException;
+import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import javax.annotation.Nonnull;
+import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
+import org.xml.sax.SAXException;
public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
this.strictParsing = strictParsing;
}
- @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public synchronized DOMNotification toNotification(final NetconfMessage message) {
final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
notificationAsContainerSchemaNode, strictParsing);
xmlParser.traverse(new DOMSource(element));
content = (ContainerNode) resultHolder.getResult();
- } catch (final Exception e) {
+ } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException
+ | SAXException | UnsupportedOperationException e) {
throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
}
return new NetconfDeviceNotification(content, stripped.getKey());
|| rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
}
- @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
final NormalizedNode<?, ?> normalizedNode;
strictParsing);
xmlParser.traverse(new DOMSource(xmlData));
dataNode = (ContainerNode) resultHolder.getResult();
- } catch (final Exception e) {
+ } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException
+ | SAXException e) {
throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
}
rpcDefinition.getOutput(), strictParsing);
xmlParser.traverse(new DOMSource(element));
normalizedNode = resultHolder.getResult();
- } catch (final Exception e) {
+ } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException
+ | SAXException e) {
throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
}
}
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
+import java.util.Locale;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade.KeepaliveDOMRpcService;
// Default operation
if (defaultOperation.isPresent()) {
- final String opString = defaultOperation.get().name().toLowerCase();
+ final String opString = defaultOperation.get().name().toLowerCase(Locale.ROOT);
editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_DEFAULT_OPERATION_QNAME))
.withValue(opString).build());
}
package org.opendaylight.netconf.sal.connect.netconf.util;
import com.google.common.util.concurrent.FutureCallback;
+import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.slf4j.Logger;
}
@Override
- public void onSuccess(final DOMRpcResult result) {
+ public void onSuccess(@Nonnull final DOMRpcResult result) {
if (result.getErrors().isEmpty()) {
LOG.trace("{}: {} invoked successfully", id, type);
} else {
import com.google.common.base.Preconditions;
import java.util.Collections;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
+import java.util.Map.Entry;
import javax.xml.transform.dom.DOMSource;
import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.opendaylight.controller.config.util.xml.XmlElement;
final YangInstanceIdentifier.NodeIdentifierWithPredicates keyedId =
(YangInstanceIdentifier.NodeIdentifierWithPredicates) lastPathArgument;
final Map<QName, Object> keyValues = keyedId.getKeyValues();
- for (QName qualifiedName : keyValues.keySet()) {
+ for (Entry<QName, Object> entry : keyValues.entrySet()) {
+ QName qualifiedName = entry.getKey();
final List<XmlElement> key =
dataElement.getChildElementsWithinNamespace(qualifiedName.getLocalName(),
qualifiedName.getNamespace().toString());
} catch (DocumentedException e) {
throw new IllegalStateException("Key value not present in key element", e);
}
- if (!keyValues.get(qualifiedName).equals(textContent)) {
+ if (!entry.getValue().equals(textContent)) {
throw new IllegalStateException("Key value in path not equal to key value in xml");
}
}
}
private static String toOperationString(final ModifyAction operation) {
- return operation.name().toLowerCase();
+ return operation.name().toLowerCase(Locale.ROOT);
}
private static Element getSourceElement(final DOMSource source) {
import com.google.common.collect.Sets;
import java.util.Collections;
import java.util.Set;
+import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.netconf.api.monitoring.NetconfManagementSession;
public class DummyMonitoringService implements NetconfMonitoringService {
private static final Sessions EMPTY_SESSIONS = new SessionsBuilder().setSession(Collections.emptyList()).build();
- private static final Function<Capability, Uri> CAPABILITY_URI_FUNCTION = new Function<Capability, Uri>() {
- @Nullable
- @Override
- public Uri apply(Capability capability) {
- return new Uri(capability.getCapabilityUri());
- }
- };
+ private static final Function<Capability, Uri> CAPABILITY_URI_FUNCTION =
+ capability -> new Uri(capability.getCapabilityUri());
private static final Function<Capability, Schema> CAPABILITY_SCHEMA_FUNCTION = new Function<Capability, Schema>() {
@Nullable
@Override
- public Schema apply(@Nullable Capability capability) {
+ public Schema apply(@Nonnull Capability capability) {
return new SchemaBuilder()
.setIdentifier(capability.getModuleName().get())
.setNamespace(new Uri(capability.getModuleNamespace().get()))
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.HttpResponseStatus;
-import com.ning.http.client.ListenableFuture;
import com.ning.http.client.Realm;
import com.ning.http.client.Request;
import com.ning.http.client.Response;
}
private void invokeAsync() {
- final ArrayList<ListenableFuture<Response>> futures = new ArrayList<>();
LOG.info("Begin sending async requests");
for (final Request request : payloads) {
} catch (InterruptedException e) {
LOG.warn("Semaphore acquire interrupted");
}
- futures.add(asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<Response>() {
+ asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<Response>() {
@Override
public STATE onStatusReceived(HttpResponseStatus status) throws Exception {
super.onStatusReceived(status);
semaphore.release();
return response;
}
- }));
+ });
}
LOG.info("Requests sent, waiting for responses");
import com.google.common.io.ByteStreams;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@SuppressFBWarnings("DM_DEFAULT_ENCODING")
public final class Main {
private static final Logger LOG = LoggerFactory.getLogger(Main.class);
}
@SuppressWarnings("checkstyle:IllegalCatch")
+ @SuppressFBWarnings({"UW_UNCOND_WAIT", "WA_NOT_IN_LOOP"})
public static void main(final String[] args) {
final TesttoolParameters params = TesttoolParameters.parseArgs(args, TesttoolParameters.getParser());
params.validate();
} else {
try {
future.get();
- } catch (final ExecutionException e) {
+ } catch (final ExecutionException | InterruptedException e) {
LOG.info("{}. thread failed.", threadNum, e);
}
}
configGenerator.updateFeatureFile(generated);
configGenerator.changeLoadOrder();
}
- } catch (final Exception e) {
+ } catch (RuntimeException | InterruptedException e) {
LOG.error("Unhandled exception", e);
netconfDeviceSimulator.close();
System.exit(1);
Preconditions.checkState(configDir.mkdirs(), "Unable to create directory " + configDir);
}
- for (final File file : configDir.listFiles(pathname ->
- !pathname.isDirectory() && pathname.getName().startsWith(SIM_DEVICE_CFG_PREFIX))) {
- Preconditions.checkState(file.delete(), "Unable to clean previous generated file %s", file);
+ final File[] files = configDir.listFiles(pathname ->
+ !pathname.isDirectory() && pathname.getName().startsWith(SIM_DEVICE_CFG_PREFIX));
+ if (files != null) {
+ for (final File file : files) {
+ Preconditions.checkState(file.delete(), "Unable to clean previous generated file %s", file);
+ }
}
try (InputStream stream = Main.class.getResourceAsStream(NETCONF_CONNECTOR_XML)) {
String configContent = String.format(
middleBlueprint, name, address, String.valueOf(openDevice), String.valueOf(!useSsh));
configContent = String.format(
- "%s%s%d%s\n%s\n", configContent, "<connection-timeout-millis>",
+ "%s%s%d%s%n%s%n", configContent, "<connection-timeout-millis>",
generateConfigsTimeout, "</connection-timeout-millis>", "</module>");
builder.append(configContent);
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.local.LocalAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@SuppressFBWarnings("DM_DEFAULT_ENCODING")
public class NetconfDeviceSimulator implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
import com.ning.http.client.AsyncHttpClientConfig.Builder;
import com.ning.http.client.Request;
import com.ning.http.client.Response;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
import org.opendaylight.netconf.test.tool.config.Configuration;
import org.opendaylight.netconf.test.tool.config.ConfigurationBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@SuppressFBWarnings({"DM_EXIT", "DM_DEFAULT_ENCODING"})
public final class ScaleUtil {
private static final ScheduledExecutorService EXECUTOR = new LoggingWrapperExecutor(4);
private static final Semaphore SEMAPHORE = new Semaphore(0);
root.error("Failed to start any simulated devices, exiting...");
System.exit(1);
}
- if (params.distroFolder != null) {
- final Main.ConfigGenerator configGenerator = new Main.ConfigGenerator(
- params.distroFolder, openDevices);
- final List<File> generated = configGenerator.generate(
- params.ssh, params.generateConfigBatchSize,
- params.generateConfigsTimeout, params.generateConfigsAddress,
- params.devicesPerPort);
- configGenerator.updateFeatureFile(generated);
- configGenerator.changeLoadOrder();
+
+ if (params.distroFolder == null) {
+ root.error("Distro folder is not set, exiting...");
+ System.exit(1);
}
+
+ final Main.ConfigGenerator configGenerator = new Main.ConfigGenerator(
+ params.distroFolder, openDevices);
+ final List<File> generated = configGenerator.generate(
+ params.ssh, params.generateConfigBatchSize,
+ params.generateConfigsTimeout, params.generateConfigsAddress,
+ params.devicesPerPort);
+ configGenerator.updateFeatureFile(generated);
+ configGenerator.changeLoadOrder();
} catch (final Exception e) {
root.error("Unhandled exception", e);
netconfDeviceSimulator.close();
if (f.isDirectory()) {
deleteFolder(f);
} else {
- f.delete();
+ if (!f.delete()) {
+ root.warn("Failed to delete {}", f);
+ }
}
}
}
- folder.delete();
- }
-
- private static TesttoolParameters parseArgs(final String[] args, final ArgumentParser parser) {
- final TesttoolParameters parameters = new TesttoolParameters();
- try {
- parser.parseArgs(args, parameters);
- return parameters;
- } catch (ArgumentParserException e) {
- parser.handleError(e);
+ if (!folder.delete()) {
+ root.warn("Failed to delete {}", folder);
}
-
- System.exit(1);
- return null;
}
private static class ScaleVerifyCallable implements Callable {
return new LogOnExceptionCallable(callable);
}
- private class LogOnExceptionCallable implements Callable {
- private Callable theCallable;
+ private static class LogOnExceptionCallable implements Callable {
+ private final Callable theCallable;
LogOnExceptionCallable(Callable theCallable) {
this.theCallable = theCallable;
import com.google.common.base.Preconditions;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.StringJoiner;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
+@SuppressFBWarnings({"DM_EXIT", "DM_DEFAULT_ENCODING"})
public class TesttoolParameters {
private static final String HOST_KEY = "{HOST}";
checkArgument(schemasDir.isDirectory(), "Schemas dir has to be a directory");
checkArgument(schemasDir.canRead(), "Schemas dir has to be readable");
- final List<File> files = Arrays.asList(schemasDir.listFiles());
+ final File[] filesArray = schemasDir.listFiles();
+ final List<File> files = filesArray != null ? Arrays.asList(filesArray) : Collections.emptyList();
for (final File file : files) {
final Matcher matcher = YANG_FILENAME_PATTERN.matcher(file.getName());
if (!matcher.matches()) {
- final BufferedReader reader;
- try {
- reader = new BufferedReader(new FileReader(file));
+ try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line = reader.readLine();
while (!DATE_PATTERN.matcher(line).find()) {
line = reader.readLine();
final String revision = m.group(1);
final String correctName = moduleName + "@" + revision + ".yang";
final File correctNameFile = new File(correctName);
- file.renameTo(correctNameFile);
+ if (!file.renameTo(correctNameFile)) {
+ System.err.println("Failed to rename " + file);
+ }
}
} catch (final IOException e) {
// print error to console (test tool is running from console)
final int batchedRequests = openDevices.size() / generateConfigBatchSize;
final int batchedRequestsPerThread = batchedRequests / threadAmount;
- final int leftoverBatchedRequests = (batchedRequests) % threadAmount;
- final int leftoverRequests = openDevices.size() - (batchedRequests * generateConfigBatchSize);
+ final int leftoverBatchedRequests = batchedRequests % threadAmount;
+ final int leftoverRequests = openDevices.size() - batchedRequests * generateConfigBatchSize;
final StringBuilder destBuilder = new StringBuilder(DEST);
destBuilder.replace(destBuilder.indexOf(ADDRESS_PORT),
controllerDestination);
for (int l = 0; l < threadAmount; l++) {
- from = l * (batchedRequests * batchedRequestsPerThread);
- to = from + (batchedRequests * batchedRequestsPerThread);
+ from = l * batchedRequests * batchedRequestsPerThread;
+ to = from + batchedRequests * batchedRequestsPerThread;
iterator = openDevices.subList(from, to).iterator();
allThreadsPayloads.add(createBatchedPayloads(batchedRequestsPerThread, iterator, editContentString,
destBuilder.toString()));
}
ArrayList<Execution.DestToPayload> payloads = null;
if (leftoverBatchedRequests > 0) {
- from = threadAmount * (batchedRequests * batchedRequestsPerThread);
- to = from + (batchedRequests * batchedRequestsPerThread);
+ from = threadAmount * batchedRequests * batchedRequestsPerThread;
+ to = from + batchedRequests * batchedRequestsPerThread;
iterator = openDevices.subList(from, to).iterator();
payloads = createBatchedPayloads(leftoverBatchedRequests, iterator, editContentString,
destBuilder.toString());
}
if (leftoverRequests > 0) {
- from = (threadAmount) * requestPerThreads;
+ from = threadAmount * requestPerThreads;
to = from + leftoverRequests;
iterator = openDevices.subList(from, to).iterator();
allThreadsPayloads.add(createPayloads(iterator, editContentString));
final ArrayList<Execution.DestToPayload> payloads = new ArrayList<>();
for (int i = 0; i < batchedRequestsCount; i++) {
- String payload = "";
+ StringBuilder payload = new StringBuilder();
for (int j = 0; j < generateConfigBatchSize; j++) {
final StringBuilder payloadBuilder = new StringBuilder(
prepareMessage(openDevices.next(), editContentString));
- payload += modifyMessage(payloadBuilder, j, generateConfigBatchSize);
+ payload.append(modifyMessage(payloadBuilder, j, generateConfigBatchSize));
}
- payloads.add(new Execution.DestToPayload(destination, payload));
+ payloads.add(new Execution.DestToPayload(destination, payload.toString()));
}
return payloads;
}
import com.ning.http.client.AsyncCompletionHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.HttpResponseStatus;
-import com.ning.http.client.ListenableFuture;
import com.ning.http.client.Request;
import com.ning.http.client.Response;
import java.util.ArrayList;
@Override
public void invoke() {
- final ArrayList<ListenableFuture<Response>> futures = new ArrayList<>();
LOG.info("Begin sending async requests");
for (final Request request : payloads) {
} catch (InterruptedException e) {
LOG.warn("Semaphore acquire interrupted");
}
- futures.add(asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<Response>() {
+ asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<Response>() {
@Override
public STATE onStatusReceived(HttpResponseStatus status) throws Exception {
super.onStatusReceived(status);
semaphore.release();
return response;
}
- }));
+ });
}
LOG.info("Requests sent, waiting for responses");
import com.google.common.base.Stopwatch;
import com.google.common.io.Files;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@SuppressFBWarnings("DM_EXIT")
public final class RestPerfClient {
private static final Logger LOG = LoggerFactory.getLogger(RestPerfClient.class);
// and do not log it
if (allThreadsCompleted) {
LOG.info(
- "Requests per second: {}", (parameters.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));
+ "Requests per second: {}", parameters.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS));
}
System.exit(0);
}
import ch.qos.logback.classic.Level;
import com.google.common.base.Stopwatch;
import com.google.common.io.Files;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
+@SuppressFBWarnings("DM_EXIT")
public final class StressClient {
private static final Logger LOG = LoggerFactory.getLogger(StressClient.class);
started.stop();
LOG.info("FINISHED. Execution time: {}", started);
- LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));
+ LOG.info("Requests per second: {}", params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS));
// Cleanup
timer.stop();
}
}
- if (e1Children.isEmpty() && e1Children.isEmpty()) {
+ if (e1Children.isEmpty() && e2Children.isEmpty()) {
try {
return e1.getTextContent().equals(e2.getTextContent());
} catch (final DocumentedException e) {
import com.google.common.base.Optional;
import java.io.File;
import java.io.IOException;
-import java.util.Collections;
import java.util.List;
import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.opendaylight.controller.config.util.xml.XmlElement;
private static DataList loadInitialConfigXMLFile(final File file) {
LOG.info("Loading initial config xml file: {}", file.getName());
DataList configData = new DataList();
- List<XmlElement> xmlElementList = Collections.emptyList();
try {
Element element = XmlUtil.readXmlToElement(file);
XmlElement xmlElement = XmlElement.fromDomElement(element);
- xmlElementList = xmlElement.getChildElements();
+ List<XmlElement> xmlElementList = xmlElement.getChildElements();
configData.setConfigList(xmlElementList);
} catch (IOException e) {
LOG.info("IO exception loading xml file: {} ", e.getMessage());
package org.opendaylight.netconf.test.tool.scale.util;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.File;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.annotation.Arg;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
+@SuppressFBWarnings("DM_EXIT")
public class ScaleUtilParameters {
@Arg(dest = "distro-folder")
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
return sourceIdentifier.getRevision().map(rev -> new OptionalRevision(new RevisionIdentifier(rev.toString())))
.orElse(NO_REVISION);
}
-
- private <T> T getObjectFromBundleContext(final Class<T> type, final String serviceRefName) {
- final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
- final ServiceReference<?> serviceReference = bundleContext.getServiceReference(serviceRefName);
- return (T) bundleContext.getService(serviceReference);
- }
}
import com.google.common.io.ByteStreams;
import com.google.common.util.concurrent.ListenableFuture;
import java.io.IOException;
+import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import org.opendaylight.yanglib.api.YangLibService;
import org.opendaylight.yangtools.yang.common.Revision;
try {
final YangTextSchemaSource source = sourceFuture.get();
- return new String(ByteStreams.toByteArray(source.openStream()));
+ return new String(ByteStreams.toByteArray(source.openStream()), Charset.defaultCharset());
} catch (InterruptedException | ExecutionException | IOException e) {
throw new IllegalStateException("Unable to get schema " + sourceId, e);
}