2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
14 import com.google.common.base.Throwables;
15 import com.google.common.base.Verify;
16 import com.google.common.cache.CacheBuilder;
17 import com.google.common.cache.CacheLoader;
18 import com.google.common.cache.LoadingCache;
19 import com.google.common.util.concurrent.UncheckedExecutionException;
20 import java.lang.reflect.ParameterizedType;
21 import java.lang.reflect.Type;
22 import java.util.List;
23 import java.util.Optional;
24 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
25 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
26 import org.opendaylight.yangtools.util.ClassLoaderUtils;
27 import org.opendaylight.yangtools.yang.binding.Action;
28 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
29 import org.opendaylight.yangtools.yang.binding.DataContainer;
30 import org.opendaylight.yangtools.yang.binding.DataObject;
31 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
32 import org.opendaylight.yangtools.yang.binding.KeyedListAction;
33 import org.opendaylight.yangtools.yang.binding.Notification;
34 import org.opendaylight.yangtools.yang.binding.RpcInput;
35 import org.opendaylight.yangtools.yang.binding.RpcOutput;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.common.QNameModule;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
41 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
42 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
44 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.Module;
47 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
48 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
50 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
51 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
52 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
54 final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D,SchemaContext> {
56 private final LoadingCache<Class<?>, DataContainerCodecContext<?,?>> childrenByClass = CacheBuilder.newBuilder()
57 .build(new CacheLoader<Class<?>, DataContainerCodecContext<?,?>>() {
59 public DataContainerCodecContext<?,?> load(final Class<?> key) {
60 return createDataTreeChildContext(key);
64 private final LoadingCache<Class<? extends Action<?, ?, ?>>, ActionCodecContext> actionsByClass = CacheBuilder
65 .newBuilder().build(new CacheLoader<Class<? extends Action<?, ?, ?>>, ActionCodecContext>() {
67 public ActionCodecContext load(final Class<? extends Action<?, ?, ?>> key) {
68 return createActionContext(key);
72 private final LoadingCache<Class<?>, ContainerNodeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder().build(
73 new CacheLoader<Class<?>, ContainerNodeCodecContext<?>>() {
75 public ContainerNodeCodecContext<?> load(final Class<?> key) {
76 return createRpcDataContext(key);
80 private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
81 .build(new CacheLoader<Class<?>, NotificationCodecContext<?>>() {
83 public NotificationCodecContext<?> load(final Class<?> key) {
84 return createNotificationDataContext(key);
88 private final LoadingCache<Class<? extends DataObject>, ChoiceNodeCodecContext<?>> choicesByClass =
89 CacheBuilder.newBuilder().build(new CacheLoader<Class<? extends DataObject>, ChoiceNodeCodecContext<?>>() {
91 public ChoiceNodeCodecContext<?> load(final Class<? extends DataObject> key) {
92 return createChoiceDataContext(key);
96 private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName = CacheBuilder.newBuilder().build(
97 new CacheLoader<QName, DataContainerCodecContext<?,?>>() {
99 public DataContainerCodecContext<?,?> load(final QName qname) {
100 final DataSchemaNode childSchema = getSchema().getDataChildByName(qname);
101 childNonNull(childSchema, qname,"Argument %s is not valid child of %s", qname,getSchema());
102 if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
103 @SuppressWarnings("unchecked")
104 final Class<? extends DataObject> childCls = (Class<? extends DataObject>)
105 factory().getRuntimeContext().getClassForSchema(childSchema);
106 return streamChild(childCls);
109 throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
113 private final LoadingCache<Absolute, RpcInputCodec<?>> rpcDataByPath = CacheBuilder.newBuilder().build(
114 new CacheLoader<Absolute, RpcInputCodec<?>>() {
116 public RpcInputCodec<?> load(final Absolute key) {
117 final ContainerLike schema = SchemaContextUtil.getRpcDataSchema(getSchema(), key.asSchemaPath());
118 @SuppressWarnings("unchecked")
119 final Class<? extends DataContainer> cls = (Class<? extends DataContainer>)
120 factory().getRuntimeContext().getClassForSchema(schema);
125 private final LoadingCache<Absolute, NotificationCodecContext<?>> notificationsByPath = CacheBuilder.newBuilder()
126 .build(new CacheLoader<Absolute, NotificationCodecContext<?>>() {
128 public NotificationCodecContext<?> load(final Absolute key) {
129 final NotificationDefinition schema = SchemaContextUtil.getNotificationSchema(getSchema(),
130 // FIXME: do not convert here!
132 @SuppressWarnings("unchecked")
133 final Class<? extends Notification> clz = (Class<? extends Notification>)
134 factory().getRuntimeContext().getClassForSchema(schema);
135 return getNotification(clz);
139 private SchemaRootCodecContext(final DataContainerCodecPrototype<SchemaContext> dataPrototype) {
140 super(dataPrototype);
144 * Creates RootNode from supplied CodecContextFactory.
147 * CodecContextFactory
148 * @return A new root node
150 static SchemaRootCodecContext<?> create(final CodecContextFactory factory) {
151 final DataContainerCodecPrototype<SchemaContext> prototype = DataContainerCodecPrototype.rootPrototype(factory);
152 return new SchemaRootCodecContext<>(prototype);
156 @SuppressWarnings("unchecked")
158 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
159 /* FIXME: This is still not solved for RPCs
160 * TODO: Probably performance wise RPC, Data and Notification loading cache
161 * should be merge for performance resons. Needs microbenchmark to
162 * determine which is faster (keeping them separate or in same cache).
164 if (Notification.class.isAssignableFrom(childClass)) {
165 return (DataContainerCodecContext<C, ?>) getNotification((Class<? extends Notification>)childClass);
167 return (DataContainerCodecContext<C, ?>) getOrRethrow(childrenByClass,childClass);
171 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
172 final Class<C> childClass) {
173 throw new UnsupportedOperationException("Not supported");
177 public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
178 return getOrRethrow(childrenByQName, arg.getNodeType());
182 public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
183 throw new UnsupportedOperationException("Could not create Binding data representation for root");
186 ActionCodecContext getAction(final Class<? extends Action<?, ?, ?>> action) {
187 return getOrRethrow(actionsByClass, action);
190 NotificationCodecContext<?> getNotification(final Class<? extends Notification> notification) {
191 return getOrRethrow(notificationsByClass, notification);
194 NotificationCodecContext<?> getNotification(final Absolute notification) {
195 return getOrRethrow(notificationsByPath, notification);
198 ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
199 return getOrRethrow(rpcDataByClass, rpcInputOrOutput);
202 RpcInputCodec<?> getRpc(final Absolute containerPath) {
203 return getOrRethrow(rpcDataByPath, containerPath);
206 DataContainerCodecContext<?,?> createDataTreeChildContext(final Class<?> key) {
207 final QName qname = BindingReflections.findQName(key);
208 final DataSchemaNode childSchema = childNonNull(getSchema().getDataChildByName(qname), key,
209 "%s is not top-level item.", key);
210 return DataContainerCodecPrototype.from(key, childSchema, factory()).get();
213 ActionCodecContext createActionContext(final Class<? extends Action<?, ?, ?>> action) {
214 if (KeyedListAction.class.isAssignableFrom(action)) {
215 return prepareActionContext(2, 3, 4, action, KeyedListAction.class);
216 } else if (Action.class.isAssignableFrom(action)) {
217 return prepareActionContext(1, 2, 3, action, Action.class);
219 throw new IllegalArgumentException("The specific action type does not exist for action " + action.getName());
222 private ActionCodecContext prepareActionContext(final int inputOffset, final int outputOffset,
223 final int expectedArgsLength, final Class<? extends Action<?, ?, ?>> action, final Class<?> actionType) {
224 final Optional<ParameterizedType> optParamType = ClassLoaderUtils.findParameterizedType(action, actionType);
225 checkState(optParamType.isPresent(), "%s does not specialize %s", action, actionType);
227 final ParameterizedType paramType = optParamType.get();
228 final Type[] args = paramType.getActualTypeArguments();
229 checkArgument(args.length == expectedArgsLength, "Unexpected (%s) Action generatic arguments", args.length);
230 final ActionDefinition schema = factory().getRuntimeContext().getActionDefinition(action);
231 return new ActionCodecContext(
232 DataContainerCodecPrototype.from(asClass(args[inputOffset], RpcInput.class), schema.getInput(),
234 DataContainerCodecPrototype.from(asClass(args[outputOffset], RpcOutput.class), schema.getOutput(),
238 private static <T extends DataObject> Class<? extends T> asClass(final Type type, final Class<T> target) {
239 verify(type instanceof Class, "Type %s is not a class", type);
240 return ((Class<?>) type).asSubclass(target);
243 ContainerNodeCodecContext<?> createRpcDataContext(final Class<?> key) {
244 checkArgument(DataContainer.class.isAssignableFrom(key));
245 final QName qname = BindingReflections.findQName(key);
246 final QNameModule qnameModule = qname.getModule();
247 final Module module = getSchema().findModule(qnameModule)
248 .orElseThrow(() -> new IllegalArgumentException("Failed to find module for " + qnameModule));
249 final String className = BindingMapping.getClassName(qname);
251 for (final RpcDefinition potential : module.getRpcs()) {
252 final QName potentialQName = potential.getQName();
254 * Check if rpc and class represents data from same module and then checks if rpc local name produces same
255 * class name as class name appended with Input/Output based on QName associated with binding class.
257 * FIXME: Rework this to have more precise logic regarding Binding Specification.
259 if (key.getSimpleName().equals(BindingMapping.getClassName(potentialQName) + className)) {
260 final ContainerLike schema = SchemaNodeUtils.getRpcDataSchema(potential, qname);
261 checkArgument(schema != null, "Schema for %s does not define input / output.", potential.getQName());
262 return (ContainerNodeCodecContext<?>) DataContainerCodecPrototype.from(key, schema, factory()).get();
266 throw new IllegalArgumentException("Supplied class " + key + " is not valid RPC class.");
269 NotificationCodecContext<?> createNotificationDataContext(final Class<?> notificationType) {
270 checkArgument(Notification.class.isAssignableFrom(notificationType));
271 checkArgument(notificationType.isInterface(), "Supplied class must be interface.");
272 final QName qname = BindingReflections.findQName(notificationType);
273 final NotificationDefinition schema = getSchema().findNotification(qname).orElseThrow(
274 () -> new IllegalArgumentException("Supplied " + notificationType + " is not valid notification"));
275 return new NotificationCodecContext<>(notificationType, schema, factory());
278 ChoiceNodeCodecContext<?> createChoiceDataContext(final Class<? extends DataObject> caseType) {
279 final Class<?> choiceClass = findCaseChoice(caseType);
280 checkArgument(choiceClass != null, "Class %s is not a valid case representation", caseType);
281 final DataSchemaNode schema = factory().getRuntimeContext().getSchemaDefinition(choiceClass);
282 checkArgument(schema instanceof ChoiceSchemaNode, "Class %s does not refer to a choice", caseType);
284 final DataContainerCodecContext<?, ChoiceSchemaNode> choice = DataContainerCodecPrototype.from(choiceClass,
285 (ChoiceSchemaNode)schema, factory()).get();
286 Verify.verify(choice instanceof ChoiceNodeCodecContext);
287 return (ChoiceNodeCodecContext<?>) choice;
291 protected Object deserializeObject(final NormalizedNode<?, ?> normalizedNode) {
292 throw new UnsupportedOperationException("Unable to deserialize root");
296 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
297 checkArgument(arg == null);
302 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
303 checkArgument(arg == null);
308 public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
309 final List<PathArgument> builder) {
310 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
311 if (caseType.isPresent()) {
312 // XXX: we use two caseType.get()s because of https://bugs.openjdk.java.net/browse/JDK-8144185,
313 // which makes JaCoCo blow up if we try using @NonNull on the local variable.
314 final ChoiceNodeCodecContext<?> choice = choicesByClass.getUnchecked(caseType.get());
315 choice.addYangPathArgument(arg, builder);
316 final DataContainerCodecContext<?, ?> caze = choice.streamChild(caseType.get());
317 caze.addYangPathArgument(arg, builder);
318 return caze.bindingPathArgumentChild(arg, builder);
321 return super.bindingPathArgumentChild(arg, builder);
324 private static Class<?> findCaseChoice(final Class<? extends DataObject> caseClass) {
325 for (Type type : caseClass.getGenericInterfaces()) {
326 if (type instanceof Class) {
327 final Class<?> typeClass = (Class<?>) type;
328 if (ChoiceIn.class.isAssignableFrom(typeClass)) {
329 return typeClass.asSubclass(ChoiceIn.class);
337 private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
339 return cache.getUnchecked(key);
340 } catch (final UncheckedExecutionException e) {
341 final Throwable cause = e.getCause();
343 Throwables.throwIfUnchecked(cause);