BUG-1281: optimize JSON codec 83/8583/3
authorRobert Varga <rovarga@cisco.com>
Wed, 2 Jul 2014 19:14:47 +0000 (21:14 +0200)
committerTony Tkacik <ttkacik@cisco.com>
Thu, 3 Jul 2014 11:54:52 +0000 (11:54 +0000)
Multiple optimizations made in one go:

- do not use string concatenation for LOG.debug()
- do not use string concatenation in Preconditions.checkState()
- methods which do not need state are made static
- use chars instead of strings where possible
- do not instantiate ArrayList needlessly to access first element in a set
- optimize namespace/localname parsing by not using String.split()
- use Charset constant instead of charset name

Change-Id: If1c4ea50d7d1d2aae4f52d1dc68ff79b901208b0
Signed-off-by: Robert Varga <rovarga@cisco.com>
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonReader.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfDocumentedExceptionMapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToJsonProvider.java

index 696bf715355e402a0932532a36cde8e795a08236..85b4b2dee071aff3be08fb82b11690a8793d7014 100644 (file)
@@ -11,13 +11,16 @@ import static com.google.common.base.Preconditions.checkNotNull;
 
 import com.google.common.base.Preconditions;
 import com.google.gson.stream.JsonWriter;
+
 import java.io.IOException;
 import java.net.URI;
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
+
 import javax.activation.UnsupportedDataTypeException;
+
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO;
@@ -50,16 +53,18 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 class JsonMapper {
+    private static final Logger LOG = LoggerFactory.getLogger(JsonMapper.class);
+    private final MountInstance mountPoint;
 
-    private MountInstance mountPoint;
-    private final Logger logger = LoggerFactory.getLogger(JsonMapper.class);
+    public JsonMapper(final MountInstance mountPoint) {
+        this.mountPoint = mountPoint;
+    }
 
-    public void write(final JsonWriter writer, final CompositeNode data, final DataNodeContainer schema, final MountInstance mountPoint)
+    public void write(final JsonWriter writer, final CompositeNode data, final DataNodeContainer schema)
             throws IOException {
         Preconditions.checkNotNull(writer);
         Preconditions.checkNotNull(data);
         Preconditions.checkNotNull(schema);
-        this.mountPoint = mountPoint;
 
         writer.beginObject();
 
@@ -82,73 +87,68 @@ class JsonMapper {
         final Set<QName> foundLists = new HashSet<>();
 
         Set<DataSchemaNode> parentSchemaChildNodes = parentSchema == null ?
-                                   Collections.<DataSchemaNode>emptySet() : parentSchema.getChildNodes();
+                Collections.<DataSchemaNode>emptySet() : parentSchema.getChildNodes();
 
 
-        for (Node<?> child : parent.getValue()) {
-            DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes);
+                for (Node<?> child : parent.getValue()) {
+                    DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes);
 
-            if (childSchema == null) {
-                // Node may not conform to schema or allows "anyxml" - we'll process it.
+                    if (childSchema == null) {
+                        // Node may not conform to schema or allows "anyxml" - we'll process it.
 
-                logger.debug( "No schema found for data node \"" + child.getNodeType() );
+                        LOG.debug("No schema found for data node \"{}\"", child.getNodeType());
 
-                if( !foundLists.contains( child.getNodeType() ) ) {
-                    handleNoSchemaFound( writer, child, parent );
+                        if( !foundLists.contains( child.getNodeType() ) ) {
+                            handleNoSchemaFound( writer, child, parent );
 
-                    // Since we don't have a schema, we don't know which nodes are supposed to be
-                    // lists so treat every one as a potential list to avoid outputting duplicates.
+                            // Since we don't have a schema, we don't know which nodes are supposed to be
+                            // lists so treat every one as a potential list to avoid outputting duplicates.
 
-                    foundLists.add( child.getNodeType() );
-                }
-            }
-            else if (childSchema instanceof ContainerSchemaNode) {
-                Preconditions.checkState(child instanceof CompositeNode,
-                        "Data representation of Container should be CompositeNode - " + child.getNodeType());
-                writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema);
-            } else if (childSchema instanceof ListSchemaNode) {
-                if (!foundLists.contains( child.getNodeType() ) ) {
-                    Preconditions.checkState(child instanceof CompositeNode,
-                            "Data representation of List should be CompositeNode - " + child.getNodeType());
-                    foundLists.add( child.getNodeType() );
-                    writeList(writer, parent, (CompositeNode) child, (ListSchemaNode) childSchema);
-                }
-            } else if (childSchema instanceof LeafListSchemaNode) {
-                if (!foundLists.contains( child.getNodeType() ) ) {
-                    Preconditions.checkState(child instanceof SimpleNode<?>,
-                            "Data representation of LeafList should be SimpleNode - " + child.getNodeType());
-                    foundLists.add( child.getNodeType() );
-                    writeLeafList(writer, parent, (SimpleNode<?>) child, (LeafListSchemaNode) childSchema);
-                }
-            } else if (childSchema instanceof LeafSchemaNode) {
-                Preconditions.checkState(child instanceof SimpleNode<?>,
-                        "Data representation of LeafList should be SimpleNode - " + child.getNodeType());
-                writeLeaf(writer, (SimpleNode<?>) child, (LeafSchemaNode) childSchema);
-            } else if (childSchema instanceof AnyXmlSchemaNode) {
-                if( child instanceof CompositeNode ) {
-                    writeContainer(writer, (CompositeNode) child, null);
-                }
-                else {
-                    handleNoSchemaFound( writer, child, parent );
+                            foundLists.add( child.getNodeType() );
+                        }
+                    }
+                    else if (childSchema instanceof ContainerSchemaNode) {
+                        Preconditions.checkState(child instanceof CompositeNode,
+                                "Data representation of Container should be CompositeNode - %s", child.getNodeType());
+                        writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema);
+                    } else if (childSchema instanceof ListSchemaNode) {
+                        if (!foundLists.contains( child.getNodeType() ) ) {
+                            Preconditions.checkState(child instanceof CompositeNode,
+                                    "Data representation of List should be CompositeNode - %s", child.getNodeType());
+                            foundLists.add( child.getNodeType() );
+                            writeList(writer, parent, (CompositeNode) child, (ListSchemaNode) childSchema);
+                        }
+                    } else if (childSchema instanceof LeafListSchemaNode) {
+                        if (!foundLists.contains( child.getNodeType() ) ) {
+                            Preconditions.checkState(child instanceof SimpleNode<?>,
+                                    "Data representation of LeafList should be SimpleNode - %s", child.getNodeType());
+                            foundLists.add( child.getNodeType() );
+                            writeLeafList(writer, parent, (SimpleNode<?>) child, (LeafListSchemaNode) childSchema);
+                        }
+                    } else if (childSchema instanceof LeafSchemaNode) {
+                        Preconditions.checkState(child instanceof SimpleNode<?>,
+                                "Data representation of LeafList should be SimpleNode - %s", child.getNodeType());
+                        writeLeaf(writer, (SimpleNode<?>) child, (LeafSchemaNode) childSchema);
+                    } else if (childSchema instanceof AnyXmlSchemaNode) {
+                        if( child instanceof CompositeNode ) {
+                            writeContainer(writer, (CompositeNode) child, null);
+                        }
+                        else {
+                            handleNoSchemaFound( writer, child, parent );
+                        }
+                    } else {
+                        throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, "
+                                + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet.");
+                    }
                 }
-            } else {
-                throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, "
-                        + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet.");
-            }
-        }
     }
 
-    private void writeValue( final JsonWriter writer, Object value ) throws IOException {
-        if( value != null ) {
-            writer.value( String.valueOf( value ) );
-        }
-        else {
-            writer.value( "" );
-        }
+    private static void writeValue(final JsonWriter writer, final Object value) throws IOException {
+        writer.value(value == null ? "" : String.valueOf(value));
     }
 
     private void handleNoSchemaFound( final JsonWriter writer, final Node<?> node,
-                                      final CompositeNode parent ) throws IOException {
+            final CompositeNode parent ) throws IOException {
         if( node instanceof SimpleNode<?> ) {
             List<SimpleNode<?>> nodeLeafList = parent.getSimpleNodesByName( node.getNodeType() );
             if( nodeLeafList.size() == 1 ) {
@@ -166,7 +166,7 @@ class JsonMapper {
             }
         } else { // CompositeNode
             Preconditions.checkState( node instanceof CompositeNode,
-                    "Data representation of Container should be CompositeNode - " + node.getNodeType() );
+                    "Data representation of Container should be CompositeNode - %s", node.getNodeType());
 
             List<CompositeNode> nodeList = parent.getCompositesByName( node.getNodeType() );
             if( nodeList.size() == 1 ) {
@@ -178,11 +178,12 @@ class JsonMapper {
         }
     }
 
-    private DataSchemaNode findFirstSchemaForNode(final Node<?> node, final Set<DataSchemaNode> dataSchemaNode) {
+    private static DataSchemaNode findFirstSchemaForNode(final Node<?> node, final Set<DataSchemaNode> dataSchemaNode) {
         for (DataSchemaNode dsn : dataSchemaNode) {
             if (node.getNodeType().equals(dsn.getQName())) {
                 return dsn;
-            } else if (dsn instanceof ChoiceNode) {
+            }
+            if (dsn instanceof ChoiceNode) {
                 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
                     DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
                     if (foundDsn != null) {
@@ -245,8 +246,8 @@ class JsonMapper {
         TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(type);
 
         if (node.getValue() == null && !(baseType instanceof EmptyTypeDefinition)) {
-            logger.debug("While generationg JSON output null value was found for type "
-                    + baseType.getClass().getSimpleName() + ".");
+            LOG.debug("While generationg JSON output null value was found for type {}.",
+                    baseType.getClass().getSimpleName());
         }
 
         if (baseType instanceof IdentityrefTypeDefinition) {
@@ -291,25 +292,24 @@ class JsonMapper {
         }
     }
 
-    private void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO) throws IOException {
+    private static void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO) throws IOException {
         StringBuilder result = new StringBuilder();
         for (IdentityValue identityValue : valueDTO.getValuesWithNamespaces()) {
-            result.append("/");
+            result.append('/');
 
             writeModuleNameAndIdentifier(result, identityValue);
             if (identityValue.getPredicates() != null && !identityValue.getPredicates().isEmpty()) {
                 for (Predicate predicate : identityValue.getPredicates()) {
                     IdentityValue identityValuePredicate = predicate.getName();
-                    result.append("[");
+                    result.append('[');
                     if (identityValuePredicate == null) {
-                        result.append(".");
+                        result.append('.');
                     } else {
                         writeModuleNameAndIdentifier(result, identityValuePredicate);
                     }
                     result.append("='");
                     result.append(predicate.getValue());
-                    result.append("'");
-                    result.append("]");
+                    result.append("']");
                 }
             }
         }
@@ -317,21 +317,22 @@ class JsonMapper {
         writer.value(result.toString());
     }
 
-    private void writeModuleNameAndIdentifier(final StringBuilder result, final IdentityValue identityValue) {
+    private static void writeModuleNameAndIdentifier(final StringBuilder result, final IdentityValue identityValue) {
         String moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
                 URI.create(identityValue.getNamespace()));
         if (moduleName != null && !moduleName.isEmpty()) {
             result.append(moduleName);
-            result.append(":");
+            result.append(':');
         }
         result.append(identityValue.getValue());
     }
 
-    private void writeStringRepresentation(final JsonWriter writer, final SimpleNode<?> node, final TypeDefinition<?> baseType,
+    private static void writeStringRepresentation(final JsonWriter writer, final SimpleNode<?> node, final TypeDefinition<?> baseType,
             final Class<?> requiredType) throws IOException {
         Object value = node.getValue();
-        logger.debug("Value of " + baseType.getQName().getNamespace() + ":" + baseType.getQName().getLocalName()
-                + " is not instance of " + requiredType.getClass() + " but is " + node.getValue().getClass());
+        LOG.debug("Value of {}:{} is not instance of {} but is {}",
+                baseType.getQName().getNamespace(), baseType.getQName().getLocalName(),
+                requiredType.getClass(), node.getValue().getClass());
         if (value == null) {
             writer.value("");
         } else {
@@ -358,7 +359,7 @@ class JsonMapper {
             if (moduleName != null) {
                 nameForOutput = moduleName.toString();
             } else {
-                logger.info("Module '{}' was not found in schema from mount point", schema.getQName());
+                LOG.info("Module '{}' was not found in schema from mount point", schema.getQName());
             }
         }
         writer.name(nameForOutput);
index 1f7b061e921cd057d13ece0002e998973fb66db2..e94554061800cb8ae918dc59a598fea980cac972 100644 (file)
@@ -7,9 +7,17 @@
  */
 package org.opendaylight.controller.sal.rest.impl;
 
+import com.google.common.base.Splitter;
+import com.google.common.collect.Iterators;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonPrimitive;
+
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.net.URI;
+import java.util.Iterator;
 import java.util.Map.Entry;
 import java.util.Set;
 
@@ -18,21 +26,22 @@ import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
 import org.opendaylight.controller.sal.restconf.impl.EmptyNodeWrapper;
 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO;
 import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
-import com.google.common.collect.Lists;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonPrimitive;
+final class JsonReader {
+    private static final Logger LOG = LoggerFactory.getLogger(JsonReader.class);
+    private static final Splitter COLON_SPLITTER = Splitter.on(':');
+
+    private JsonReader() {
 
-class JsonReader {
+    }
 
-    public CompositeNodeWrapper read(InputStream entityStream) throws UnsupportedFormatException {
+    public static CompositeNodeWrapper read(final InputStream entityStream) throws UnsupportedFormatException {
         JsonParser parser = new JsonParser();
 
         JsonElement rootElement = parser.parse(new InputStreamReader(entityStream));
-        if( rootElement.isJsonNull() )
-        {
+        if (rootElement.isJsonNull()) {
             //no content, so return null to indicate no input
             return null;
         }
@@ -44,29 +53,31 @@ class JsonReader {
         Set<Entry<String, JsonElement>> entrySetsOfRootJsonObject = rootElement.getAsJsonObject().entrySet();
         if (entrySetsOfRootJsonObject.size() != 1) {
             throw new UnsupportedFormatException("Json Object should contain one element");
-        } else {
-            Entry<String, JsonElement> childEntry = Lists.newArrayList(entrySetsOfRootJsonObject).get(0);
-            String firstElementName = childEntry.getKey();
-            JsonElement firstElementType = childEntry.getValue();
-            if (firstElementType.isJsonObject()) { // container in yang
-                return createStructureWithRoot(firstElementName, firstElementType.getAsJsonObject());
-            }
-            if (firstElementType.isJsonArray()) { // list in yang
-                if (firstElementType.getAsJsonArray().size() == 1) {
-                    JsonElement firstElementInArray = firstElementType.getAsJsonArray().get(0);
-                    if (firstElementInArray.isJsonObject()) {
-                        return createStructureWithRoot(firstElementName, firstElementInArray.getAsJsonObject());
-                    }
-                    throw new UnsupportedFormatException(
-                            "Array as the first element in Json Object can have only Object element");
+        }
+
+        Entry<String, JsonElement> childEntry = entrySetsOfRootJsonObject.iterator().next();
+        String firstElementName = childEntry.getKey();
+        JsonElement firstElementType = childEntry.getValue();
+        if (firstElementType.isJsonObject()) {
+            // container in yang
+            return createStructureWithRoot(firstElementName, firstElementType.getAsJsonObject());
+        }
+        if (firstElementType.isJsonArray()) {
+            // list in yang
+            if (firstElementType.getAsJsonArray().size() == 1) {
+                JsonElement firstElementInArray = firstElementType.getAsJsonArray().get(0);
+                if (firstElementInArray.isJsonObject()) {
+                    return createStructureWithRoot(firstElementName, firstElementInArray.getAsJsonObject());
                 }
+                throw new UnsupportedFormatException(
+                        "Array as the first element in Json Object can have only Object element");
             }
-            throw new UnsupportedFormatException(
-                    "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet.");
         }
+        throw new UnsupportedFormatException(
+                "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet.");
     }
 
-    private CompositeNodeWrapper createStructureWithRoot(String rootObjectName, JsonObject rootObject) {
+    private static CompositeNodeWrapper createStructureWithRoot(final String rootObjectName, final JsonObject rootObject) {
         CompositeNodeWrapper firstNode = new CompositeNodeWrapper(getNamespaceFor(rootObjectName),
                 getLocalNameFor(rootObjectName));
         for (Entry<String, JsonElement> childOfFirstNode : rootObject.entrySet()) {
@@ -75,7 +86,7 @@ class JsonReader {
         return firstNode;
     }
 
-    private void addChildToParent(String childName, JsonElement childType, CompositeNodeWrapper parent) {
+    private static void addChildToParent(final String childName, final JsonElement childType, final CompositeNodeWrapper parent) {
         if (childType.isJsonObject()) {
             CompositeNodeWrapper child = new CompositeNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName));
             parent.addValue(child);
@@ -85,7 +96,6 @@ class JsonReader {
         } else if (childType.isJsonArray()) {
             if (childType.getAsJsonArray().size() == 1 && childType.getAsJsonArray().get(0).isJsonNull()) {
                 parent.addValue(new EmptyNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName)));
-
             } else {
                 for (JsonElement childOfChildType : childType.getAsJsonArray()) {
                     addChildToParent(childName, childOfChildType, parent);
@@ -96,35 +106,42 @@ class JsonReader {
             String value = childPrimitive.getAsString().trim();
             parent.addValue(new SimpleNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName),
                     resolveValueOfElement(value)));
+        } else {
+            LOG.debug("Ignoring unhandled child type {}", childType);
         }
     }
 
-    private URI getNamespaceFor(String jsonElementName) {
-        String[] moduleNameAndLocalName = jsonElementName.split(":");
-        // it is not "moduleName:localName"
-        if (moduleNameAndLocalName.length != 2) {
-            return null;
+    private static URI getNamespaceFor(final String jsonElementName) {
+        final Iterator<String> it = COLON_SPLITTER.split(jsonElementName).iterator();
+
+        // The string needs to me in form "moduleName:localName"
+        if (it.hasNext()) {
+            final String maybeURI = it.next();
+            if (Iterators.size(it) == 1) {
+                return URI.create(maybeURI);
+            }
         }
-        return URI.create(moduleNameAndLocalName[0]);
+
+        return null;
     }
 
-    private String getLocalNameFor(String jsonElementName) {
-        String[] moduleNameAndLocalName = jsonElementName.split(":");
-        // it is not "moduleName:localName"
-        if (moduleNameAndLocalName.length != 2) {
-            return jsonElementName;
-        }
-        return moduleNameAndLocalName[1];
+    private static String getLocalNameFor(final String jsonElementName) {
+        final Iterator<String> it = COLON_SPLITTER.split(jsonElementName).iterator();
+
+        // The string needs to me in form "moduleName:localName"
+        final String ret = Iterators.get(it, 1, null);
+        return ret != null && !it.hasNext() ? ret : jsonElementName;
     }
 
-    private Object resolveValueOfElement(String value) {
+    private static Object resolveValueOfElement(final String value) {
         // it could be instance-identifier Built-In Type
-        if (value.startsWith("/")) {
+        if (!value.isEmpty() && value.charAt(0) == '/') {
             IdentityValuesDTO resolvedValue = RestUtil.asInstanceIdentifier(value, new PrefixMapingFromJson());
             if (resolvedValue != null) {
                 return resolvedValue;
             }
         }
+
         // it could be identityref Built-In Type
         URI namespace = getNamespaceFor(value);
         if (namespace != null) {
index 856e09fabd21a1083cbe716890ba22ae3b2d5bc6..9e6966540534c9c79d2a120f89c35ebf603d956d 100644 (file)
@@ -30,29 +30,28 @@ import org.slf4j.LoggerFactory;
 
 @Provider
 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON,
-        MediaType.APPLICATION_JSON })
+    MediaType.APPLICATION_JSON })
 public enum JsonToCompositeNodeProvider implements MessageBodyReader<CompositeNode> {
     INSTANCE;
 
     private final static Logger LOG = LoggerFactory.getLogger( JsonToCompositeNodeProvider.class );
 
     @Override
-    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
+    public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
         return true;
     }
 
     @Override
-    public CompositeNode readFrom(Class<CompositeNode> type, Type genericType, Annotation[] annotations,
-            MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
-            throws IOException, WebApplicationException {
-        JsonReader jsonReader = new JsonReader();
+    public CompositeNode readFrom(final Class<CompositeNode> type, final Type genericType, final Annotation[] annotations,
+            final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
+                    throws IOException, WebApplicationException {
         try {
-            return jsonReader.read(entityStream);
+            return JsonReader.read(entityStream);
         } catch (Exception e) {
-            LOG.debug( "Error parsing json input", e );
+            LOG.debug( "Error parsing json input", e);
             throw new RestconfDocumentedException(
-                            "Error parsing input: " + e.getMessage(),
-                            ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE );
+                    "Error parsing input: " + e.getMessage(),
+                    ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
         }
     }
 
index 5f6909cea8e3e15d2b7887fe975d2d3e613163b5..0854ca71673465e76e7659bfa9479afc3fb1962f 100644 (file)
@@ -17,6 +17,11 @@ import static org.opendaylight.controller.sal.rest.api.Draft02.RestConfModule.ER
 import static org.opendaylight.controller.sal.rest.api.Draft02.RestConfModule.ERROR_TYPE_QNAME;
 import static org.opendaylight.controller.sal.rest.api.Draft02.RestConfModule.NAMESPACE;
 
+import com.google.common.base.Charsets;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.gson.stream.JsonWriter;
+
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.OutputStreamWriter;
@@ -57,10 +62,6 @@ import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 import org.xml.sax.InputSource;
 
-import com.google.common.base.Strings;
-import com.google.common.collect.ImmutableList;
-import com.google.gson.stream.JsonWriter;
-
 /**
  * This class defines an ExceptionMapper that handles RestconfDocumentedExceptions thrown by
  * resource implementations and translates appropriately to restconf error response as defined in
@@ -139,20 +140,19 @@ public class RestconfDocumentedExceptionMapper implements ExceptionMapper<Restco
     private Object toJsonResponseBody( final ImmutableCompositeNode errorsNode,
             final DataNodeContainer errorsSchemaNode ) {
 
-        JsonMapper jsonMapper = new JsonMapper();
+        JsonMapper jsonMapper = new JsonMapper(null);
 
         Object responseBody = null;
         try {
             ByteArrayOutputStream outStream = new ByteArrayOutputStream();
-            JsonWriter writer = new JsonWriter( new OutputStreamWriter( outStream, "UTF-8" ) );
+            JsonWriter writer = new JsonWriter(new OutputStreamWriter( outStream, Charsets.UTF_8));
             writer.setIndent( "    " );
 
-            jsonMapper.write( writer, errorsNode, errorsSchemaNode, null );
+            jsonMapper.write( writer, errorsNode, errorsSchemaNode);
             writer.flush();
 
             responseBody = outStream.toString( "UTF-8" );
-        }
-        catch( IOException e ) {
+        } catch( IOException e ) {
             LOG.error( "Error writing error response body", e );
         }
 
@@ -239,13 +239,11 @@ public class RestconfDocumentedExceptionMapper implements ExceptionMapper<Restco
         try {
             doc = factory.newDocumentBuilder().parse(
                     new InputSource( new StringReader( errorInfoWithRoot ) ) );
-        }
-        catch( Exception e ) {
+        } catch( Exception e ) {
             // TODO: what if the content is text that happens to contain invalid markup? Could
             // wrap in CDATA and try again.
 
-            LOG.warn( "Error parsing restconf error-info, \"" + errorInfo + "\", as XML: " +
-                    e.toString() );
+            LOG.warn( "Error parsing restconf error-info, \"{}\", as XML", errorInfo, e);
             return null;
         }
 
index 422cf04cca82f7d0bf5d2f535df40a6f7688215e..1c2e9c5009897f741efaa6a1320665d7ba2a4b0a 100644 (file)
@@ -7,6 +7,9 @@
  */
 package org.opendaylight.controller.sal.rest.impl;
 
+import com.google.common.base.Charsets;
+import com.google.gson.stream.JsonWriter;
+
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.OutputStreamWriter;
@@ -28,37 +31,35 @@ import org.opendaylight.controller.sal.restconf.impl.StructuredData;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 
-import com.google.gson.stream.JsonWriter;
-
 @Provider
 @Produces({ Draft02.MediaTypes.API + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON,
-        Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON })
+    Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON })
 public enum StructuredDataToJsonProvider implements MessageBodyWriter<StructuredData> {
     INSTANCE;
 
     @Override
-    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
+    public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
         return type.equals( StructuredData.class );
     }
 
     @Override
-    public long getSize(StructuredData t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
+    public long getSize(final StructuredData t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
         return -1;
     }
 
     @Override
-    public void writeTo(StructuredData t, Class<?> type, Type genericType, Annotation[] annotations,
-            MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
-            throws IOException, WebApplicationException {
+    public void writeTo(final StructuredData t, final Class<?> type, final Type genericType, final Annotation[] annotations,
+            final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream)
+                    throws IOException, WebApplicationException {
         CompositeNode data = t.getData();
         if (data == null) {
             throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
         }
 
-        JsonWriter writer = new JsonWriter(new OutputStreamWriter(entityStream, "UTF-8"));
+        JsonWriter writer = new JsonWriter(new OutputStreamWriter(entityStream, Charsets.UTF_8));
         writer.setIndent("    ");
-        JsonMapper jsonMapper = new JsonMapper();
-        jsonMapper.write(writer, data, (DataNodeContainer) t.getSchema(), t.getMountPoint());
+        JsonMapper jsonMapper = new JsonMapper(t.getMountPoint());
+        jsonMapper.write(writer, data, (DataNodeContainer) t.getSchema());
         writer.flush();
     }