import java.io.InputStreamReader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
final JsonParserStream jsonParser = JsonParserStream.create(writer,
JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(path.getSchemaContext()), parentSchema);
- final JsonReader reader = new JsonReader(new InputStreamReader(nonEmptyInputStreamOptional.get()));
+ final JsonReader reader = new JsonReader(new InputStreamReader(nonEmptyInputStreamOptional.get(),
+ StandardCharsets.UTF_8));
jsonParser.parse(reader);
NormalizedNode<?, ?> result = resultHolder.getResult();
import java.io.StringReader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
+import java.util.Locale;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.ws.rs.Consumes;
return new PatchContext(path, null, null);
}
- final JsonReader jsonReader = new JsonReader(new InputStreamReader(nonEmptyInputStreamOptional.get()));
+ final JsonReader jsonReader = new JsonReader(new InputStreamReader(nonEmptyInputStreamOptional.get(),
+ StandardCharsets.UTF_8));
final List<PatchEntity> resultList = read(jsonReader, path);
jsonReader.close();
edit.setId(in.nextString());
break;
case "operation" :
- edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase()));
+ edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase(Locale.ROOT)));
break;
case "target" :
// target can be specified completely in request URI
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
LOG.debug("In toResponse: {}", exception.getMessage());
final List<MediaType> accepts = headers.getAcceptableMediaTypes();
- accepts.remove(MediaType.WILDCARD_TYPE);
+ if (accepts != null) {
+ accepts.remove(MediaType.WILDCARD_TYPE);
+ }
LOG.debug("Accept headers: {}", accepts);
LOG.warn("Error writing error response body", e);
}
- return outStream.toString();
-
+ try {
+ return outStream.toString(StandardCharsets.UTF_8.name());
+ } catch (UnsupportedEncodingException e) {
+ // Shouldn't happen
+ return "Failure encoding error response: " + e;
+ }
}
private static Object toXMLResponseBody(final NormalizedNodeContext errorsNode,
LOG.warn("Error writing error response body.", e);
}
- return outStream.toString();
+ try {
+ return outStream.toString(StandardCharsets.UTF_8.name());
+ } catch (UnsupportedEncodingException e) {
+ // Shouldn't happen
+ return "Failure encoding error response: " + e;
+ }
}
private static void writeRootElement(final XMLStreamWriter xmlWriter, final NormalizedNodeWriter nnWriter,
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
+import java.util.Locale;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.ws.rs.Consumes;
DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
final Element element = (Element) editNodes.item(i);
final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
- final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase());
+ final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase(Locale.ROOT));
final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
+import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
final ListenableFuture<Boolean> f = readTx.exists(datastore, path);
Futures.addCallback(f, new FutureCallback<Boolean>() {
@Override
- public void onSuccess(final Boolean result) {
+ public void onSuccess(@Nonnull final Boolean result) {
ret.complete(path, result.booleanValue());
}
@Override
+ @SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE")
public void onFailure(final Throwable throwable) {
final Exception e;
if (throwable instanceof Exception) {
}
break;
case DELETE:
- if (withoutError) {
- try {
- deleteDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity
- .getTargetNode());
- editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
- } catch (final RestconfDocumentedException e) {
- LOG.error("Error call http Patch operation {} on target {}",
- operation,
- patchEntity.getTargetNode().toString());
-
- editErrors = new ArrayList<>();
- editErrors.addAll(e.getErrors());
- editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), false, editErrors));
- withoutError = false;
- }
- }
- break;
case REMOVE:
if (withoutError) {
try {
if (outputContext.getData() != null) {
output = toJson(outputContext);
}
- } catch (final Exception e) {
+ } catch (final RuntimeException | IOException e) {
propagateExceptionAs(uriPath, e, "RPC");
}
String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
if (!Strings.isNullOrEmpty(param) && !"unbounded".equals(param)) {
try {
- final int depth = Integer.valueOf(param);
+ final int depth = Integer.parseInt(param);
if (depth < 1) {
throw new RestconfDocumentedException(
new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.netconf.sal.rest.impl.StringModuleInstanceIdentifierCodec;
import org.opendaylight.restconf.common.util.IdentityValuesDTO;
private static List<Predicate> keyValuesToPredicateList(final Map<QName, Object> keyValues) {
final List<Predicate> result = new ArrayList<>();
- for (final QName qualifiedName : keyValues.keySet()) {
- final Object value = keyValues.get(qualifiedName);
+ for (final Entry<QName, Object> entry : keyValues.entrySet()) {
+ final QName qualifiedName = entry.getKey();
+ final Object value = entry.getValue();
result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
}
return result;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
final DOMRpcResult result = checkRpcResponse(response);
RpcDefinition resultNodeSchema = null;
- final NormalizedNode<?, ?> resultData = result.getResult();
+ final NormalizedNode<?, ?> resultData;
if (result != null && result.getResult() != null) {
+ resultData = result.getResult();
resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
+ } else {
+ resultData = null;
}
return new NormalizedNodeContext(
}
try {
final DOMRpcResult retValue = response.get();
- if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
+ if (retValue.getErrors().isEmpty()) {
return retValue;
}
LOG.debug("RpcError message", retValue.getErrors());
}
boolean tagged = false;
if (withDefaUsed) {
- if (withDefa.equals("report-all-tagged")) {
+ if ("report-all-tagged".equals(withDefa)) {
tagged = true;
withDefa = null;
}
- if (withDefa.equals("report-all")) {
+ if ("report-all".equals(withDefa)) {
withDefa = null;
}
}
String insert = null;
String point = null;
- for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
- switch (entry.getKey()) {
- case "insert":
- if (!insertUsed) {
- insertUsed = true;
- insert = entry.getValue().iterator().next();
- } else {
- throw new RestconfDocumentedException("Insert parameter can be used only once.");
- }
- break;
- case "point":
- if (!pointUsed) {
- pointUsed = true;
- point = entry.getValue().iterator().next();
- } else {
- throw new RestconfDocumentedException("Point parameter can be used only once.");
- }
- break;
- default:
- throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
+ if (uriInfo != null) {
+ for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
+ switch (entry.getKey()) {
+ case "insert":
+ if (!insertUsed) {
+ insertUsed = true;
+ insert = entry.getValue().iterator().next();
+ } else {
+ throw new RestconfDocumentedException("Insert parameter can be used only once.");
+ }
+ break;
+ case "point":
+ if (!pointUsed) {
+ pointUsed = true;
+ point = entry.getValue().iterator().next();
+ } else {
+ throw new RestconfDocumentedException("Point parameter can be used only once.");
+ }
+ break;
+ default:
+ throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
+ }
}
}
return responseBuilder.build();
}
- // FIXME create RestconfIdetifierHelper and move this method there
- private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
- Preconditions.checkArgument(payload != null);
- Preconditions.checkArgument(payload.getData() != null);
- Preconditions.checkArgument(payload.getData().getNodeType() != null);
- Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
- Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
-
- final QName payloadNodeQname = payload.getData().getNodeType();
- final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
- if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
- return yangIdent;
- }
- final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
- final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
- if (parentSchemaNode instanceof DataNodeContainer) {
- final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
- for (final DataSchemaNode child : cast.getChildNodes()) {
- if (payloadNodeQname.compareTo(child.getQName()) == 0) {
- return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
- }
- }
- }
- if (parentSchemaNode instanceof RpcDefinition) {
- return yangIdent;
- }
- final String errMsg = "Error parsing input: DataSchemaNode has not children ";
- LOG.info(errMsg + yangIdent);
- throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
- }
-
@SuppressWarnings("checkstyle:IllegalCatch")
private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
final YangInstanceIdentifier normalizedII) {
final List<SchemaPath> paths = new ArrayList<>();
String streamName = CREATE_NOTIFICATION_STREAM + "/";
+ StringBuilder streamNameBuilder = new StringBuilder(streamName);
final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
while (iterator.hasNext()) {
final QName valueQName = QName.create((String) iterator.next().getValue());
Preconditions.checkNotNull(notifiDef,
"Notification " + valueQName + "doesn't exist in module " + moduleName);
paths.add(notifiDef.getPath());
- streamName = streamName + moduleName + ":" + valueQName.getLocalName();
+ streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
if (iterator.hasNext()) {
- streamName = streamName + ",";
+ streamNameBuilder.append(',');
}
}
+ streamName = streamNameBuilder.toString();
+
final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
final QName outputQname = QName.create(rpcQName, "output");
final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
+import java.util.Map.Entry;
import javax.annotation.Nonnull;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.dom.DOMResult;
writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType());
if (pathArgument instanceof NodeIdentifierWithPredicates) {
final Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
- for (final QName keyValue : predicates.keySet()) {
- final String predicateValue = String.valueOf(predicates.get(keyValue));
+ for (final Entry<QName, Object> entry : predicates.entrySet()) {
+ final QName keyValue = entry.getKey();
+ final String predicateValue = String.valueOf(entry.getValue());
textContent.append("[");
writeIdentifierWithNamespacePrefix(element, textContent, keyValue);
textContent.append("='");
}
} else if (streamName.contains(RestconfImpl.NOTIFICATION_STREAM)) {
final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
- if (!listeners.isEmpty() && (listeners != null)) {
+ if (listeners != null && !listeners.isEmpty()) {
for (final NotificationListenerAdapter listener : listeners) {
listener.addSubscriber(ctx.channel());
LOG.debug("Subscriber successfully registered.");
// Send the response and close the connection if necessary.
final ChannelFuture f = ctx.channel().writeAndFlush(res);
- if (!isKeepAlive(req) || (res.getStatus().code() != 200)) {
+ if (!isKeepAlive(req) || res.getStatus().code() != 200) {
f.addListener(ChannelFutureListener.CLOSE);
}
}
if (listener != null) {
listener.removeSubscriber(ctx.channel());
LOG.debug("Subscriber successfully registered.");
+
+ Notificator.removeListenerIfNoSubscriberExists(listener);
}
- Notificator.removeListenerIfNoSubscriberExists(listener);
} else if (streamName.contains(RestconfImpl.NOTIFICATION_STREAM)) {
final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
- if (!listeners.isEmpty() && (listeners != null)) {
+ if (listeners != null && !listeners.isEmpty()) {
for (final NotificationListenerAdapter listener : listeners) {
listener.removeSubscriber(ctx.channel());
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
- if (!(cause instanceof java.nio.channels.ClosedChannelException)) {
- // LOG.info("Not expected error cause: ", cause.toString());
- }
ctx.close();
}