- Fix checkstyle issues and activate enforcement.
Change-Id: I9857df844aba6bee4ddc729fb8246a2d8a085ad5
Signed-off-by: Jie Han <han.jie@zte.com.cn>
</instructions>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
</plugins>
</build>
* obtain augmentations from proxy implementations of {@link Augmentable}
* object.
*
+ * <p>
* If implemented proxy does not implement this interface, its augmentations are
* not properly serialized / deserialized.
*/
/**
* Caching variant of Binding to Normalized Node codec.
*
+ * <p>
* Caching may introduce performance penalty to serialization / deserialization
* but may decrease use of heap for repetitive objects.
*
* Invoking close will invalidate this codec and any of its child codecs and
* will invalidate cache.
*
+ * <p>
* Any subsequent calls to this codec will fail with
* {@link IllegalStateException} thrown.
*/
/**
* Navigable tree representing hierarchy of Binding to Normalized Node codecs.
*
+ * <p>
* This navigable tree is associated to concrete set of YANG models, represented
* by SchemaContext and provides access to subtree specific serialization
* context.
/**
* Returns codec which uses caches serialization / deserialization results.
*
+ * <p>
* Caching may introduce performance penalty to serialization /
* deserialization but may decrease use of heap for repetitive objects.
*
* Creates a {@link BindingStreamEventWriter} for data tree path which will
* translate to NormalizedNode model and invoke proper events on supplied
* {@link NormalizedNodeStreamWriter}.
+ *
* <p>
* Also provides translation of supplied Instance Identifier to
* {@link YangInstanceIdentifier} so client code, does not need to translate
* that separately.
+ *
* <p>
* If {@link YangInstanceIdentifier} is not needed, please use
* {@link #newWriter(InstanceIdentifier, NormalizedNodeStreamWriter)} method
* Creates a {@link BindingStreamEventWriter} for data tree path which will
* translate to NormalizedNode model and invoke proper events on supplied
* {@link NormalizedNodeStreamWriter}.
- * <p>
*
+ * <p>
* This variation does not provide YANG instance identifier and is useful
* for use-cases, where {@link InstanceIdentifier} translation is done in
* other way, or YANG instance identifier is unnecessary (e.g.
import com.google.common.base.Preconditions;
/**
- * Definition of static property for Binding objects
+ * Definition of static property for Binding objects.
+ *
* <p>
* This definition consists of
* <ul>
* {@link TreeNodeSerializerImplementation} interface and are used to serialize
* Binding {@link TreeNode}.
*
+ * <p>
* Actual implementation of codecs is done via static methods, which allows for
* static wiring of codecs. Choice codec and Augmentable codecs are static
* properties of parent codec and stateless implementations are used (
}
@Override
- public void serialize(final TreeNodeSerializerRegistry reg, final TreeNode obj, final BindingStreamEventWriter stream)
- throws IOException {
+ public void serialize(final TreeNodeSerializerRegistry reg, final TreeNode obj,
+ final BindingStreamEventWriter stream) throws IOException {
throw new UnsupportedOperationException("Prototype body, this code should never be invoked.");
}
* - data tree class
* @return serializer class name
*/
- public abstract String loadSerializerFor(final Class<?> cls);
+ public abstract String loadSerializerFor(Class<?> cls);
}
* fix the static declared fields to final once we initialize them. If
* we cannot get access, that's fine, too.
*/
- Field f = null;
+ Field field = null;
try {
- f = Field.class.getDeclaredField("modifiers");
- f.setAccessible(true);
+ field = Field.class.getDeclaredField("modifiers");
+ field.setAccessible(true);
} catch (NoSuchFieldException | SecurityException e) {
LOG.warn("Could not get Field modifiers field, serializers run at decreased efficiency", e);
}
- FIELD_MODIFIERS = f;
+ FIELD_MODIFIERS = field;
}
protected AbstractStreamWriterGenerator(final JavassistUtils utils) {
try {
product = javassist.instantiatePrototype(TreeNodeSerializerPrototype.class.getName(), serializerName,
- cls -> {
- // Generate any static fields
- for (final StaticBindingProperty def : source.getStaticConstants()) {
- final CtField field = new CtField(javassist.asCtClass(def.getType()), def.getName(), cls);
- field.setModifiers(Modifier.PRIVATE + Modifier.STATIC);
- cls.addField(field);
- }
-
- // Replace serialize() -- may reference static fields
- final CtMethod serializeTo = cls.getDeclaredMethod(SERIALIZE_METHOD_NAME, serializeArguments);
- serializeTo.setBody(body);
-
- // The prototype is not visible, so we need to take care
- // of that
- cls.setModifiers(Modifier.setPublic(cls.getModifiers()));
- });
+ cls -> {
+ // Generate any static fields
+ for (final StaticBindingProperty def : source.getStaticConstants()) {
+ final CtField field = new CtField(javassist.asCtClass(def.getType()), def.getName(), cls);
+ field.setModifiers(Modifier.PRIVATE + Modifier.STATIC);
+ cls.addField(field);
+ }
+
+ // Replace serialize() -- may reference static fields
+ final CtMethod serializeTo = cls.getDeclaredMethod(SERIALIZE_METHOD_NAME, serializeArguments);
+ serializeTo.setBody(body);
+
+ // The prototype is not visible, so we need to take care
+ // of that
+ cls.setModifiers(Modifier.setPublic(cls.getModifiers()));
+ });
} catch (final NotFoundException e) {
LOG.error("Failed to instatiate serializer {}", source, e);
throw new LinkageError("Unexpected instantation problem: serializer prototype not found", e);
* Generates serializer source code for supplied container node, which will
* read supplied binding type and invoke proper methods on supplied
* {@link BindingStreamEventWriter}.
+ *
* <p>
* Implementation is required to recursively invoke events for all reachable
* binding objects.
* Generates serializer source for supplied case node, which will read
* supplied binding type and invoke proper methods on supplied
* {@link BindingStreamEventWriter}.
+ *
* <p>
* Implementation is required to recursively invoke events for all reachable
* binding objects.
* Generates serializer source for supplied list node, which will read
* supplied binding type and invoke proper methods on supplied
* {@link BindingStreamEventWriter}.
+ *
* <p>
* Implementation is required to recursively invoke events for all reachable
* binding objects.
* @param node - schema of list
* @return source for list node writer
*/
- protected abstract AbstractTreeNodeSerializerSource generateMapEntrySerializer(GeneratedType type, ListSchemaNode node);
+ protected abstract AbstractTreeNodeSerializerSource generateMapEntrySerializer(GeneratedType type,
+ ListSchemaNode node);
/**
* Generates serializer source for supplied list node, which will read
* supplied binding type and invoke proper methods on supplied
* {@link BindingStreamEventWriter}.
+ *
* <p>
* Implementation is required to recursively invoke events for all reachable
* binding objects.
* Generates serializer source for supplied augmentation node, which will
* read supplied binding type and invoke proper methods on supplied
* {@link BindingStreamEventWriter}.
+ *
* <p>
* Implementation is required to recursively invoke events for all reachable
* binding objects.
* @param schema - schema of augmentation
* @return source for augmentation node writer
*/
- protected abstract AbstractTreeNodeSerializerSource generateSerializer(GeneratedType type, AugmentationSchema schema);
+ protected abstract AbstractTreeNodeSerializerSource generateSerializer(GeneratedType type,
+ AugmentationSchema schema);
/**
* Generates serializer source for notification node, which will read
* supplied binding type and invoke proper methods on supplied
* {@link BindingStreamEventWriter}.
+ *
* <p>
* Implementation is required to recursively invoke events for all reachable
* binding objects.
}
@Override
- protected void emitAfterBody(final StringBuilder b) {
- b.append(statement(invoke(AUGMENTABLE_SERIALIZER, "serialize", REGISTRY, INPUT, STREAM)));
+ protected void emitAfterBody(final StringBuilder builder) {
+ builder.append(statement(invoke(AUGMENTABLE_SERIALIZER, "serialize", REGISTRY, INPUT, STREAM)));
}
}
@Override
public CharSequence getSerializerBody() {
- final StringBuilder b = new StringBuilder();
- b.append("{\n");
- b.append(statement(assign(TreeNodeSerializerRegistry.class.getName(), REGISTRY, "$1")));
- b.append(statement(assign(dtoType.getFullyQualifiedName(), INPUT,
+ final StringBuilder builder = new StringBuilder();
+ builder.append("{\n");
+ builder.append(statement(assign(TreeNodeSerializerRegistry.class.getName(), REGISTRY, "$1")));
+ builder.append(statement(assign(dtoType.getFullyQualifiedName(), INPUT,
cast(dtoType.getFullyQualifiedName(), "$2"))));
- b.append(statement(assign(BindingStreamEventWriter.class.getName(), STREAM, cast(BindingStreamEventWriter.class.getName(), "$3"))));
- b.append(statement(assign(BindingSerializer.class.getName(), SERIALIZER, null)));
- b.append("if (");
- b.append(STREAM);
- b.append(" instanceof ");
- b.append(BindingSerializer.class.getName());
- b.append(") {");
- b.append(statement(assign(SERIALIZER, cast(BindingSerializer.class.getName(), STREAM))));
- b.append('}');
- b.append(statement(emitStartEvent()));
-
- emitBody(b);
- emitAfterBody(b);
- b.append(statement(endNode()));
- b.append(statement("return null"));
- b.append('}');
- return b;
+ builder.append(statement(assign(BindingStreamEventWriter.class.getName(), STREAM,
+ cast(BindingStreamEventWriter.class.getName(), "$3"))));
+ builder.append(statement(assign(BindingSerializer.class.getName(), SERIALIZER, null)));
+ builder.append("if (");
+ builder.append(STREAM);
+ builder.append(" instanceof ");
+ builder.append(BindingSerializer.class.getName());
+ builder.append(") {");
+ builder.append(statement(assign(SERIALIZER, cast(BindingSerializer.class.getName(), STREAM))));
+ builder.append('}');
+ builder.append(statement(emitStartEvent()));
+
+ emitBody(builder);
+ emitAfterBody(builder);
+ builder.append(statement(endNode()));
+ builder.append(statement("return null"));
+ builder.append('}');
+ return builder;
}
/**
* Allows for customization of emitting code, which is processed after
* normal DataNodeContainer body. Ideal for augmentations or others.
*/
- protected void emitAfterBody(final StringBuilder b) {
+ protected void emitAfterBody(final StringBuilder builder) {
}
private static Map<String, Type> collectAllProperties(final GeneratedType type, final Map<String, Type> hashMap) {
} else {
prefix = "get";
}
- return prefix + JavaIdentifierNormalizer.normalizeSpecificIdentifier(node.getQName().getLocalName(), JavaIdentifier.CLASS);
+ return prefix + JavaIdentifierNormalizer.normalizeSpecificIdentifier(node.getQName().getLocalName(),
+ JavaIdentifier.CLASS);
}
- private void emitBody(final StringBuilder b) {
+ private void emitBody(final StringBuilder builder) {
final Map<String, Type> getterToType = collectAllProperties(dtoType, new HashMap<String, Type>());
for (final DataSchemaNode schemaChild : schemaNode.getChildNodes()) {
if (!schemaChild.isAugmenting()) {
// FIXME AnyXml nodes are ignored, since their type cannot be found in generated bindnig
// Bug-706 https://bugs.opendaylight.org/show_bug.cgi?id=706
if (schemaChild instanceof AnyXmlSchemaNode) {
- LOG.warn("Node {} will be ignored. AnyXml is not yet supported from binding aware code." +
- "Binding Independent code can be used to serialize anyXml nodes.", schemaChild.getPath());
+ LOG.warn("Node {} will be ignored. AnyXml is not yet supported from binding aware code."
+ + "Binding Independent code can be used to serialize anyXml nodes.", schemaChild.getPath());
continue;
}
String.format("Unable to find type for child node %s. Expected child nodes: %s",
schemaChild.getPath(), getterToType));
}
- emitChild(b, getter, childType, schemaChild);
+ emitChild(builder, getter, childType, schemaChild);
}
}
}
- private void emitChild(final StringBuilder b, final String getterName, final Type childType,
+ private void emitChild(final StringBuilder builder, final String getterName, final Type childType,
final DataSchemaNode schemaChild) {
- b.append(statement(assign(childType, getterName, cast(childType, invoke(INPUT, getterName)))));
+ builder.append(statement(assign(childType, getterName, cast(childType, invoke(INPUT, getterName)))));
- b.append("if (").append(getterName).append(" != null) {\n");
- emitChildInner(b, getterName, childType, schemaChild);
- b.append("}\n");
+ builder.append("if (").append(getterName).append(" != null) {\n");
+ emitChildInner(builder, getterName, childType, schemaChild);
+ builder.append("}\n");
}
- private void emitChildInner(final StringBuilder b, final String getterName, final Type childType,
+ private void emitChildInner(final StringBuilder builder, final String getterName, final Type childType,
final DataSchemaNode child) {
if (child instanceof LeafSchemaNode) {
- b.append(statement(leafNode(child.getQName().getLocalName(), getterName)));
+ builder.append(statement(leafNode(child.getQName().getLocalName(), getterName)));
} else if (child instanceof AnyXmlSchemaNode) {
- b.append(statement(anyxmlNode(child.getQName().getLocalName(), getterName)));
+ builder.append(statement(anyxmlNode(child.getQName().getLocalName(), getterName)));
} else if (child instanceof LeafListSchemaNode) {
final CharSequence startEvent;
if (((LeafListSchemaNode) child).isUserOrdered()) {
- startEvent = startOrderedLeafSet(child.getQName().getLocalName(),invoke(getterName, "size"));
+ startEvent = startOrderedLeafSet(child.getQName().getLocalName(),
+ invoke(getterName, "size"));
} else {
startEvent = startLeafSet(child.getQName().getLocalName(),invoke(getterName, "size"));
}
- b.append(statement(startEvent));
+ builder.append(statement(startEvent));
final Type valueType = ((ParameterizedType) childType).getActualTypeArguments()[0];
- b.append(forEach(getterName, valueType, statement(leafSetEntryNode(CURRENT))));
- b.append(statement(endNode()));
+ builder.append(forEach(getterName, valueType, statement(leafSetEntryNode(CURRENT))));
+ builder.append(statement(endNode()));
} else if (child instanceof ListSchemaNode) {
final Type valueType = ((ParameterizedType) childType).getActualTypeArguments()[0];
final ListSchemaNode casted = (ListSchemaNode) child;
- emitList(b, getterName, valueType, casted);
+ emitList(builder, getterName, valueType, casted);
} else if (child instanceof ContainerSchemaNode) {
- b.append(tryToUseCacheElse(getterName,statement(staticInvokeEmitter(childType, getterName))));
+ builder.append(tryToUseCacheElse(getterName,statement(staticInvokeEmitter(childType, getterName))));
} else if (child instanceof ChoiceSchemaNode) {
final String propertyName = CHOICE_PREFIX + childType.getName();
- staticConstant(propertyName, TreeNodeSerializerImplementation.class, ChoiceDispatchSerializer.from(loadClass(childType)));
- b.append(tryToUseCacheElse(getterName,statement(invoke(propertyName, StreamWriterGenerator.SERIALIZE_METHOD_NAME, REGISTRY, cast(TreeNode.class.getName(),getterName), STREAM))));
+ staticConstant(propertyName, TreeNodeSerializerImplementation.class,
+ ChoiceDispatchSerializer.from(loadClass(childType)));
+ builder.append(tryToUseCacheElse(getterName,statement(invoke(propertyName,
+ StreamWriterGenerator.SERIALIZE_METHOD_NAME, REGISTRY, cast(TreeNode.class.getName(),getterName),
+ STREAM))));
}
}
return b;
}
- private void emitList(final StringBuilder b, final String getterName, final Type valueType,
+ private void emitList(final StringBuilder builer, final String getterName, final Type valueType,
final ListSchemaNode child) {
final CharSequence startEvent;
- b.append(statement(assign("int", "_count", invoke(getterName, "size"))));
+ builer.append(statement(assign("int", "_count", invoke(getterName, "size"))));
if (child.getKeyDefinition().isEmpty()) {
startEvent = startUnkeyedList(classReference(valueType), "_count");
} else if (child.isUserOrdered()) {
} else {
startEvent = startMapNode(classReference(valueType), "_count");
}
- b.append(statement(startEvent));
- b.append(forEach(getterName, valueType, tryToUseCacheElse(CURRENT,statement(staticInvokeEmitter(valueType, CURRENT)))));
- b.append(statement(endNode()));
+ builer.append(statement(startEvent));
+ builer.append(forEach(getterName, valueType, tryToUseCacheElse(CURRENT,
+ statement(staticInvokeEmitter(valueType, CURRENT)))));
+ builer.append(statement(endNode()));
}
}
return cast(type.getFullyQualifiedName(), value);
}
+ /**
+ * Cast value to specific type.
+ *
+ * @param type
+ * - specific type
+ * @param value
+ * - value for cast
+ * @return casted value to specifc type as char sequence
+ */
+ static final CharSequence cast(final String type, final CharSequence value) {
+ return "((" + type + ") " + value + ')';
+ }
+
/**
* Create loop through iterable object with specific body.
*
return sb.append("\n}\n");
}
- /**
- * Cast value to specific type.
- *
- * @param type
- * - specific type
- * @param value
- * - value for cast
- * @return casted value to specifc type as char sequence
- */
- static final CharSequence cast(final String type, final CharSequence value) {
- return "((" + type + ") " + value + ')';
- }
-
/**
* Create new Java statement.
*
import org.slf4j.LoggerFactory;
/**
- * Serializing and deserializing Binding and DOM data
+ * Serializing and deserializing Binding and DOM data.
*/
@Beta
public class BindingNormalizedNodeCodecRegistry implements TreeNodeSerializerRegistry, BindingTreeCodecFactory,
}
@Override
+ @SuppressWarnings("checkstyle:illegalCatch")
public BindingCodecContext create(final SchemaContext context, final Class<?>... bindingClasses) {
final ModuleInfoBackedContext strategy = ModuleInfoBackedContext.create();
for (final Class<?> bindingCls : bindingClasses) {
* - Binding Instance Identifier
* @return DOM Instance Identifier
*/
- public YangInstanceIdentifier toYangInstanceIdentifierBlocking(final InstanceIdentifier<? extends TreeNode> binding) {
+ public YangInstanceIdentifier toYangInstanceIdentifierBlocking(
+ final InstanceIdentifier<? extends TreeNode> binding) {
try {
return codecRegistry.toYangInstanceIdentifier(binding);
} catch (final MissingSchemaException e) {
* - DOM object
* @return Binding object
* @throws DeserializationException
+ * If fail to deserialize
*/
@SuppressWarnings("unchecked")
public Optional<Entry<InstanceIdentifier<? extends TreeNode>, TreeNode>>
}
@Override
+ @SuppressWarnings("checkstyle:illegalCatch")
public IdentifiableItem<?, ?> deserialize(final NodeIdentifierWithPredicates input) {
final Object[] bindingValues = new Object[keysInBindingOrder.size()];
int offset = 0;
@SuppressWarnings("unchecked")
private static Constructor<? extends Identifier> getConstructor(final Class<? extends Identifier> clazz) {
- for (@SuppressWarnings("rawtypes")
- final Constructor constr : clazz.getConstructors()) {
+ for (@SuppressWarnings("rawtypes") final Constructor constr : clazz.getConstructors()) {
final Class<?>[] parameters = constr.getParameterTypes();
if (!clazz.equals(parameters[0])) {
// It is not copy constructor;
}
public static void checkModulePresent(final SchemaContext schemaContext, final QName name) {
- if(schemaContext.findModuleByNamespaceAndRevision(name.getNamespace(), name.getRevision()) == null) {
+ if (schemaContext.findModuleByNamespaceAndRevision(name.getNamespace(), name.getRevision()) == null) {
throw MissingSchemaException.create("Module %s is not present in current schema context.",name.getModule());
}
}
}
private static QName extractName(final PathArgument child) {
- if(child instanceof YangInstanceIdentifier.AugmentationIdentifier) {
+ if (child instanceof YangInstanceIdentifier.AugmentationIdentifier) {
final Set<QName> children = ((YangInstanceIdentifier.AugmentationIdentifier) child).getPossibleChildNames();
Preconditions.checkArgument(!children.isEmpty(),"Augmentation without childs must not be used in data");
return children.iterator().next();
* to mark both {@link UnmappedOperationInputCodec} and ContainerNodeCodecContext, which results in bimorphic
* invocation in BindingNormalizedNodeCodecRegistry.
*
+ * <p>
* Without this interface we could end up with megamorphic invocation, as the two implementations cannot share
* class hierarchy.
*
/**
* Returns cached NormalizedNode representation of TreeNode.
*
+ * <p>
* If representation is not cached, serializes TreeNode and updates cache
* with representation.
*
@SuppressWarnings("unchecked")
@Nonnull
@Override
- public <DV extends TreeNode> DataContainerCodecContext<DV, ?> streamChild(@Nonnull final Class<DV> childClass) {
+ public <C extends TreeNode> DataContainerCodecContext<C, ?> streamChild(@Nonnull final Class<C> childClass) {
final DataContainerCodecPrototype<?> child = byClass.get(childClass);
- return (DataContainerCodecContext<DV,
+ return (DataContainerCodecContext<C,
?>) childNonNull(child, childClass, "Supplied class %s is not valid case", childClass).get();
}
@SuppressWarnings("unchecked")
@Override
- public <DV extends TreeNode> Optional<DataContainerCodecContext<DV, ?>>
- possibleStreamChild(@Nonnull final Class<DV> childClass) {
+ public <C extends TreeNode> Optional<DataContainerCodecContext<C, ?>>
+ possibleStreamChild(@Nonnull final Class<C> childClass) {
final DataContainerCodecPrototype<?> child = byClass.get(childClass);
if (child != null) {
- return Optional.of((DataContainerCodecContext<DV, ?>) child.get());
+ return Optional.of((DataContainerCodecContext<C, ?>) child.get());
}
return Optional.absent();
}
return null;
}
+ private ContainerSchemaNode getOperationDataSchema(final OperationDefinition operation, final QName qname) {
+ Preconditions.checkNotNull(operation, "Operation Schema must not be null.");
+ Preconditions.checkNotNull(qname, "QName must not be null.");
+ switch (qname.getLocalName()) {
+ case "input":
+ return operation.getInput();
+ case "output":
+ return operation.getOutput();
+ default:
+ throw new IllegalArgumentException(
+ "Supplied qname " + qname + " does not represent operation input or output.");
+ }
+ }
+
private final LoadingCache<SchemaPath, NotificationCodecContext<?>> notificationsByPath =
CacheBuilder.newBuilder().build(new CacheLoader<SchemaPath, NotificationCodecContext<?>>() {
@SuppressWarnings({ "unchecked", "rawtypes" })
@Nonnull
@Override
- public <DV extends TreeNode> DataContainerCodecContext<DV, ?> streamChild(@Nonnull final Class<DV> childClass)
+ public <C extends TreeNode> DataContainerCodecContext<C, ?> streamChild(@Nonnull final Class<C> childClass)
throws IllegalArgumentException {
/*
* FIXME: This is still not solved for operations TODO: Probably performance wise operations, Data and
* determine which is faster (keeping them separate or in same cache).
*/
if (Notification.class.isAssignableFrom(childClass)) {
- return (DataContainerCodecContext<DV, ?>) getNotification((Class<? extends Notification>) childClass);
+ return (DataContainerCodecContext<C, ?>) getNotification((Class<? extends Notification>) childClass);
}
- return (DataContainerCodecContext<DV, ?>) getOrRethrow(childrenByClass, childClass);
+ return (DataContainerCodecContext<C, ?>) getOrRethrow(childrenByClass, childClass);
}
@Override
return getOrRethrow(operationDataByClass, operationInputOrOutput);
}
+ /**
+ * Get operation input as binding object according to schema path of operation.
+ *
+ * @param operation
+ * - schema path of operation
+ * @return operation input codec of operation
+ */
+ public OperationInputCodec<?> getOperation(final SchemaPath operation) {
+ return getOrRethrow(operationDataByPath, operation);
+ }
+
/**
* Get notification as binding object of binding class.
*
return getOrRethrow(notificationsByPath, notification);
}
- /**
- * Get operation input as binding object according to schema path of operation.
- *
- * @param operation
- * - schema path of operation
- * @return operation input codec of operation
- */
- public OperationInputCodec<?> getOperation(final SchemaPath operation) {
- return getOrRethrow(operationDataByPath, operation);
- }
+
private DataContainerCodecContext<?, ?> createDataTreeChildContext(final Class<?> key) {
final QName qname = BindingReflections.findQName(key);
if ((operation = findPotentialOperation(schemaContext.getOperations(), module, key, qname)) == null) {
operation = findPotentialOperation(schemaContext.getActions(), module, key, qname);
}
- Preconditions.checkArgument(operation != null, "Supplied class %s is not valid operation class.", key);
- final ContainerSchemaNode schema = getOperationDataSchema(operation, qname);// SchemaNodeUtils.getRpcDataSchema(operation,
- // qname);
+ Preconditions.checkArgument(operation != null,
+ "Supplied class %s is not valid operation class.", key);
+ final ContainerSchemaNode schema = getOperationDataSchema(operation, qname);// SchemaNodeUtils
+ // .getRpcDataSchema(operation, qname);
Preconditions.checkArgument(schema != null, "Schema for %s does not define input / output.",
operation.getQName());
return (ContainerNodeCodecContext<?>) DataContainerCodecPrototype.from(key, schema, factory()).get();
}
- private ContainerSchemaNode getOperationDataSchema(final OperationDefinition operation, final QName qname) {
- Preconditions.checkNotNull(operation, "Operation Schema must not be null.");
- Preconditions.checkNotNull(qname, "QName must not be null.");
- switch (qname.getLocalName()) {
- case "input":
- return operation.getInput();
- case "output":
- return operation.getOutput();
- default:
- throw new IllegalArgumentException(
- "Supplied qname " + qname + " does not represent operation input or output.");
- }
- }
-
private OperationDefinition findPotentialOperation(final Set<? extends OperationDefinition> set,
final QNameModule module, final Class<?> key, final QName qname) {
OperationDefinition operation = null;
* - input object for deserializing
* @return deserialized union binding type object
*/
+ @SuppressWarnings("checkstyle:illegalCatch")
public Object deserializeUnion(final Object input) {
// Side-step potential exceptions by checking the type if it is available
if (codec instanceof EncapsulatedValueCodec && !((EncapsulatedValueCodec) codec).canAcceptObject(input)) {
}
}
+ @SuppressWarnings("checkstyle:illegalCatch")
private Object getValueFrom(final Object input) {
try {
return getter.invokeExact(input);
try {
getter = MethodHandles.publicLookup().unreflect(identifier.getMethod(getterName)).asType(OBJECT_METHOD);
} catch (IllegalAccessException | NoSuchMethodException | SecurityException e) {
- throw new IllegalStateException(String.format("Cannot find method %s in class %s", getterName, identifier), e);
+ throw new IllegalStateException(
+ String.format("Cannot find method %s in class %s", getterName, identifier), e);
}
this.identifier = identifier;
codec = leaf.getValueCodec();
* - input object
* @return serialized invoked object
*/
+ @SuppressWarnings("checkstyle:illegalCatch")
public Object getAndSerialize(final Object obj) {
final Object value;
try {
return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
}
- private static String getGetterName(final QName qName, final TypeDefinition<?> typeDef) {
+ private static String getGetterName(final QName qname, final TypeDefinition<?> typeDef) {
final String suffix =
- JavaIdentifierNormalizer.normalizeSpecificIdentifier(qName.getLocalName(), JavaIdentifier.CLASS);
+ JavaIdentifierNormalizer.normalizeSpecificIdentifier(qname.getLocalName(), JavaIdentifier.CLASS);
if (typeDef instanceof BooleanTypeDefinition || typeDef instanceof EmptyTypeDefinition) {
return "is" + suffix;
}
return ValueTypeCodec.NOOP_CODEC;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private Codec<Object, Object> getCodecForBindingClass(final Class<?> valueType, final TypeDefinition<?> typeDef) {
if (typeDef instanceof IdentityrefTypeDefinition) {
return ValueTypeCodec.encapsulatedValueCodecFor(valueType, identityCodec);
}
/**
- * Returns nested node context using supplied YANG Instance Identifier
+ * Returns nested node context using supplied YANG Instance Identifier.
*
* @param arg Yang Instance Identifier Argument
* @return Context of child
*/
@Nonnull
@Override
- public abstract NodeCodecContext<?> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg);
+ public abstract NodeCodecContext<?> yangPathArgumentChild(YangInstanceIdentifier.PathArgument arg);
/**
* Returns nested node context using supplied Binding Instance Identifier
*/
@Nonnull
@Override
- public abstract <DV extends TreeNode> DataContainerCodecContext<DV,?> streamChild(@Nonnull final Class<DV> childClass) throws IllegalArgumentException;
+ public abstract <C extends TreeNode> DataContainerCodecContext<C,?> streamChild(@Nonnull Class<C> childClass)
+ throws IllegalArgumentException;
/**
* Returns child context as if it was walked by {@link BindingStreamEventWriter}. This means that to enter
* @return Context of child or Optional absent is supplied class is not applicable in context.
*/
@Override
- public abstract <DV extends TreeNode> Optional<DataContainerCodecContext<DV, ?>> possibleStreamChild(@Nonnull
- final Class<DV> childClass);
+ public abstract <C extends TreeNode> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(@Nonnull
+ Class<C> childClass);
@Override
public String toString() {
}
public TreeNodeSerializer eventStreamSerializer() {
- if(eventStreamSerializer == null) {
+ if (eventStreamSerializer == null) {
eventStreamSerializer = factory().getEventStreamSerializer(getBindingClass());
}
return eventStreamSerializer;
private volatile DataContainerCodecContext<?,T> instance = null;
@SuppressWarnings({"rawtypes", "unchecked"})
- private DataContainerCodecPrototype(final Class<?> cls, final YangInstanceIdentifier.PathArgument arg, final T nodeSchema,
- final CodecContextFactory factory) {
+ private DataContainerCodecPrototype(final Class<?> cls, final YangInstanceIdentifier.PathArgument arg,
+ final T nodeSchema, final CodecContextFactory factory) {
this.bindingClass = Preconditions.checkNotNull(cls);
this.yangArg = Preconditions.checkNotNull(arg);
this.schema = Preconditions.checkNotNull(nodeSchema);
this.bindingArg = new Item(bindingClass);
if (arg instanceof AugmentationIdentifier) {
- this.namespace = Iterables.getFirst(((AugmentationIdentifier) arg).getPossibleChildNames(), null).getModule();
+ this.namespace = Iterables.getFirst(
+ ((AugmentationIdentifier) arg).getPossibleChildNames(), null).getModule();
} else {
this.namespace = arg.getNodeType().getModule();
}
return new DataContainerCodecPrototype(cls, NodeIdentifier.create(schema.getQName()), schema, factory);
}
- public static DataContainerCodecPrototype<SchemaContext> rootPrototype(final CodecContextFactory factory) {
- final SchemaContext schema = factory.getRuntimeContext().getSchemaContext();
- final NodeIdentifier arg = NodeIdentifier.create(schema.getQName());
- return new DataContainerCodecPrototype<>(TreeRoot.class, arg, schema, factory);
- }
-
@SuppressWarnings({ "rawtypes", "unchecked" })
static DataContainerCodecPrototype<?> from(final Class<?> augClass, final AugmentationIdentifier arg,
final AugmentationSchema schema, final CodecContextFactory factory) {
return new DataContainerCodecPrototype(augClass, arg, schema, factory);
}
+
public static DataContainerCodecPrototype<NotificationDefinition> from(final Class<?> augClass,
final NotificationDefinition schema, final CodecContextFactory factory) {
final PathArgument arg = NodeIdentifier.create(schema.getQName());
return new DataContainerCodecPrototype<>(augClass, arg, schema, factory);
}
+ public static DataContainerCodecPrototype<SchemaContext> rootPrototype(final CodecContextFactory factory) {
+ final SchemaContext schema = factory.getRuntimeContext().getSchemaContext();
+ final NodeIdentifier arg = NodeIdentifier.create(schema.getQName());
+ return new DataContainerCodecPrototype<>(TreeRoot.class, arg, schema, factory);
+ }
+
public T getSchema() {
return schema;
}
if (!Arrays.equals((byte[]) thisValue, (byte[]) otherValue)) {
return false;
}
- } else if (!Objects.equals(thisValue, otherValue)){
+ } else if (!Objects.equals(thisValue, otherValue)) {
return false;
}
}
private static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentations(final Object dataObject) {
if (dataObject instanceof AugmentationReader) {
return ((AugmentationReader) dataObject).getAugmentations(dataObject);
- } else if (dataObject instanceof Augmentable<?>){
+ } else if (dataObject instanceof Augmentable<?>) {
return BindingReflections.getAugmentations((Augmentable<?>) dataObject);
}
Preconditions.checkNotNull(cls,"Supplied augmentation must not be null.");
@SuppressWarnings({"unchecked","rawtypes"})
- final Optional<DataContainerCodecContext<?,?>> augCtx= context.possibleStreamChild((Class) cls);
- if(augCtx.isPresent()) {
+ final Optional<DataContainerCodecContext<?,?>> augCtx = context.possibleStreamChild((Class) cls);
+ if (augCtx.isPresent()) {
final Optional<NormalizedNode<?, ?>> augData = data.getChild(augCtx.get().getDomPathArgument());
if (augData.isPresent()) {
return augCtx.get().deserialize(augData.get());
return qnameDomValueFromString(codec, schema, (String) defaultValue, schemaContext);
}
return domValueFromString(codec, type, defaultValue);
- }
- else {
+ } else {
while (type.getBaseType() != null && type.getDefaultValue() == null) {
type = type.getBaseType();
}
return this;
}
- public final Method getGetter() {
+ public Method getGetter() {
return getter;
}
* Thrown when Java Binding class was used in data for which codec does not
* have schema.
*
+ * <p>
* By serialization / deserialization of this exception {@link #getBindingClass()}
* will return null.
*/
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
/**
- *
* Location specific context for schema nodes, which contains codec specific
* information to properly serialize / deserialize from Java YANG Binding data
* to NormalizedNode data.
*
+ * <p>
* Two core subtypes of codec context are available:
* <ul>
* <li>{@link LeafNodeCodecContext} - Context for nodes, which does not contain
@Beta
public abstract class NodeCodecContext<D extends TreeNode> implements BindingTreeNodeCodec<D> {
/**
- * Returns Yang Instance Identifier Path Argument of current node
+ * Returns Yang Instance Identifier Path Argument of current node.
*
* @return DOM Path Argument of node
*/
public abstract YangInstanceIdentifier.PathArgument getDomPathArgument();
/**
- *
* Immutable factory, which provides access to runtime context,
* create leaf nodes and provides path argument codecs.
+ *
* <p>
* During lifetime of factory all calls for same arguments to method must return
* equal result (not necessary same instance of result).
ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(Class<?> type, DataNodeContainer schema);
/**
- * Returns Path argument codec for list item
+ * Returns Path argument codec for list item.
*
* @param type Type of list item
* @param schema Schema of list item
* @return Path argument codec for supplied list item.
*/
Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(Class<?> type,
- ListSchemaNode schema);
+ ListSchemaNode schema);
TreeNodeSerializer getEventStreamSerializer(Class<?> type);
}
/**
- *
* Serializes supplied Binding Path Argument
* and adds all necessary YANG instance identifiers to supplied list.
*
}
reloadAllAugmentations();
- final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(), new Class[] { getBindingClass(), AugmentationHolder.class });
+ final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(),
+ new Class[] { getBindingClass(), AugmentationHolder.class });
try {
proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
.asType(TREENODE_TYPE);
@Nonnull
@SuppressWarnings("unchecked")
@Override
- public <DV extends TreeNode> DataContainerCodecContext<DV, ?> streamChild(@Nonnull final Class<DV> childClass) {
+ public <C extends TreeNode> DataContainerCodecContext<C, ?> streamChild(@Nonnull final Class<C> childClass) {
final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
- return (DataContainerCodecContext<DV, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
+ return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
childClass).get();
}
- private final DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
+ private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
if (childProto != null) {
return childProto;
@SuppressWarnings("unchecked")
@Override
- public <DV extends TreeNode> Optional<DataContainerCodecContext<DV, ?>> possibleStreamChild(
- @Nonnull final Class<DV> childClass) {
+ public <C extends TreeNode> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
+ @Nonnull final Class<C> childClass) {
final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
if (childProto != null) {
- return Optional.of((DataContainerCodecContext<DV,?>) childProto.get());
+ return Optional.of((DataContainerCodecContext<C,?>) childProto.get());
}
return Optional.absent();
}
}
@Nullable
- private final DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(@Nonnull final Class<?> childClass) {
+ private DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(@Nonnull final Class<?> childClass) {
final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
if (childProto != null) {
return childProto;
}
}
+ @SuppressWarnings("checkstyle:illegalCatch")
protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
try {
return (D) proxyConstructor.invokeExact((InvocationHandler) new LazyTreeNode<>(this, node));
* Serializer of Binding objects to Normalized Node which uses
* {@link BindingNormalizedNodeCache} to cache already serialized values.
*
+ * <p>
* This serializer implements {@link BindingStreamEventWriter} along with
* {@link BindingSerializer}.
*
/**
* Serializes input if it is cached, returns null otherwise.
*
+ * <p>
* If input is cached it uses
* {@link NormalizedNodeWithAddChildWriter#addChild(NormalizedNode)} to
* provide already serialized value to underlying NormalizedNodeWriter in
* order to reuse value instead of creating new one using Normalized Node
* stream APIs.
*
+ * <p>
* Note that this optional is serialization of child node invoked from
* {@link TreeNodeSerializer}, which may opt-out from streaming of data when
* non-null result is returned.
return null;
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private BindingNormalizedNodeCache getCacheSerializer(final Class type) {
- if (cacheHolder.isCached(type)) {
- final DataContainerCodecContext<?, ?> currentCtx = (DataContainerCodecContext<?, ?>) delegate.current();
- if (type.equals(currentCtx.getBindingClass())) {
- return cacheHolder.getCachingSerializer(currentCtx);
- }
- return cacheHolder.getCachingSerializer(currentCtx.streamChild(type));
- }
- return null;
- }
-
/**
* Serializes supplied data using stream writer with child cache enabled or
* using cache directly if cache is avalaible also for supplied Codec node.
return serializeUsingStreamWriter(cacheHolder, subtreeRoot, data);
}
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private BindingNormalizedNodeCache getCacheSerializer(final Class type) {
+ if (cacheHolder.isCached(type)) {
+ final DataContainerCodecContext<?, ?> currentCtx = (DataContainerCodecContext<?, ?>) delegate.current();
+ if (type.equals(currentCtx.getBindingClass())) {
+ return cacheHolder.getCachingSerializer(currentCtx);
+ }
+ return cacheHolder.getCachingSerializer(currentCtx.streamChild(type));
+ }
+ return null;
+ }
+
/**
* Serializes supplied data using stream writer with child cache enabled.
*
}
@Override
+ @SuppressWarnings("checkstyle:illegalCatch")
public Object deserialize(Object input) {
Preconditions.checkArgument(input instanceof Set);
@SuppressWarnings("unchecked")
* This means we will construct correct array for construction
* of bits object.
*/
- final Boolean args[] = new Boolean[ctorArgs.size()];
+ final Boolean[] args = new Boolean[ctorArgs.size()];
int currentArg = 0;
for (String value : ctorArgs) {
args[currentArg++] = casted.contains(value);
}
@Override
+ @SuppressWarnings("checkstyle:illegalCatch")
public Object deserialize(final Object input) {
try {
return constructor.invokeExact(input);
}
@Override
+ @SuppressWarnings("checkstyle:illegalCatch")
public Object serialize(final Object input) {
try {
return getter.invokeExact(input);
@Beta
public abstract class ValueTypeCodec implements Codec<Object, Object> {
- private static final Cache<Class<?>, SchemaUnawareCodec> staticCodecs = CacheBuilder.newBuilder().weakKeys()
+ private static final Cache<Class<?>, SchemaUnawareCodec> STATIC_CODECS = CacheBuilder.newBuilder().weakKeys()
.build();
/**
}
/**
- *
* No-op Codec, Java YANG Binding uses same types as NormalizedNode model
* for base YANG types, representing numbers, binary and strings.
*/
return def instanceof EmptyTypeDefinition ? EMPTY_CODEC : NOOP_CODEC;
}
- private static SchemaUnawareCodec getCachedSchemaUnawareCodec(final Class<?> typeClz, final Callable<? extends SchemaUnawareCodec> loader) {
+ private static SchemaUnawareCodec getCachedSchemaUnawareCodec(final Class<?> typeClz,
+ final Callable<? extends SchemaUnawareCodec> loader) {
try {
- return staticCodecs.get(typeClz, loader);
+ return STATIC_CODECS.get(typeClz, loader);
} catch (final ExecutionException e) {
throw new IllegalStateException(e);
}
}
- private static Callable<? extends SchemaUnawareCodec> getCodecLoader(final Class<?> typeClz, final TypeDefinition<?> def) {
-
+ private static Callable<? extends SchemaUnawareCodec> getCodecLoader(final Class<?> typeClz,
+ final TypeDefinition<?> def) {
TypeDefinition<?> rootType = def;
while (rootType.getBaseType() != null) {
rootType = rootType.getBaseType();
@SuppressWarnings("rawtypes")
public static ValueTypeCodec encapsulatedValueCodecFor(final Class<?> typeClz, final Codec delegate) {
- final SchemaUnawareCodec extractor = getCachedSchemaUnawareCodec(typeClz, EncapsulatedValueCodec.loader(typeClz));
+ final SchemaUnawareCodec extractor = getCachedSchemaUnawareCodec(typeClz,
+ EncapsulatedValueCodec.loader(typeClz));
return new CompositeValueCodec(extractor, delegate);
}
}
\ No newline at end of file