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.ContainerSchemaNode;
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.SchemaPath;
51 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
52 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
53 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
55 final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D,SchemaContext> {
57 private final LoadingCache<Class<?>, DataContainerCodecContext<?,?>> childrenByClass = CacheBuilder.newBuilder()
58 .build(new CacheLoader<Class<?>, DataContainerCodecContext<?,?>>() {
60 public DataContainerCodecContext<?,?> load(final Class<?> key) {
61 return createDataTreeChildContext(key);
65 private final LoadingCache<Class<? extends Action<?, ?, ?>>, ActionCodecContext> actionsByClass = CacheBuilder
66 .newBuilder().build(new CacheLoader<Class<? extends Action<?, ?, ?>>, ActionCodecContext>() {
68 public ActionCodecContext load(final Class<? extends Action<?, ?, ?>> key) {
69 return createActionContext(key);
73 private final LoadingCache<Class<?>, ContainerNodeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder().build(
74 new CacheLoader<Class<?>, ContainerNodeCodecContext<?>>() {
76 public ContainerNodeCodecContext<?> load(final Class<?> key) {
77 return createRpcDataContext(key);
81 private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
82 .build(new CacheLoader<Class<?>, NotificationCodecContext<?>>() {
84 public NotificationCodecContext<?> load(final Class<?> key) {
85 return createNotificationDataContext(key);
89 private final LoadingCache<Class<? extends DataObject>, ChoiceNodeCodecContext<?>> choicesByClass =
90 CacheBuilder.newBuilder().build(new CacheLoader<Class<? extends DataObject>, ChoiceNodeCodecContext<?>>() {
92 public ChoiceNodeCodecContext<?> load(final Class<? extends DataObject> key) {
93 return createChoiceDataContext(key);
97 private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName = CacheBuilder.newBuilder().build(
98 new CacheLoader<QName, DataContainerCodecContext<?,?>>() {
100 public DataContainerCodecContext<?,?> load(final QName qname) {
101 final DataSchemaNode childSchema = getSchema().getDataChildByName(qname);
102 childNonNull(childSchema, qname,"Argument %s is not valid child of %s", qname,getSchema());
103 if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
104 @SuppressWarnings("unchecked")
105 final Class<? extends DataObject> childCls = (Class<? extends DataObject>)
106 factory().getRuntimeContext().getClassForSchema(childSchema);
107 return streamChild(childCls);
110 throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
114 private final LoadingCache<Absolute, RpcInputCodec<?>> rpcDataByPath = CacheBuilder.newBuilder().build(
115 new CacheLoader<Absolute, RpcInputCodec<?>>() {
117 public RpcInputCodec<?> load(final Absolute key) {
118 final ContainerSchemaNode schema = SchemaContextUtil.getRpcDataSchema(getSchema(), key.asSchemaPath());
119 @SuppressWarnings("unchecked")
120 final Class<? extends DataContainer> cls = (Class<? extends DataContainer>)
121 factory().getRuntimeContext().getClassForSchema(schema);
126 private final LoadingCache<Absolute, NotificationCodecContext<?>> notificationsByPath = CacheBuilder.newBuilder()
127 .build(new CacheLoader<Absolute, NotificationCodecContext<?>>() {
129 public NotificationCodecContext<?> load(final Absolute key) {
130 final NotificationDefinition schema = SchemaContextUtil.getNotificationSchema(getSchema(),
131 // FIXME: do not convert here!
133 @SuppressWarnings("unchecked")
134 final Class<? extends Notification> clz = (Class<? extends Notification>)
135 factory().getRuntimeContext().getClassForSchema(schema);
136 return getNotification(clz);
140 private SchemaRootCodecContext(final DataContainerCodecPrototype<SchemaContext> dataPrototype) {
141 super(dataPrototype);
145 * Creates RootNode from supplied CodecContextFactory.
148 * CodecContextFactory
149 * @return A new root node
151 static SchemaRootCodecContext<?> create(final CodecContextFactory factory) {
152 final DataContainerCodecPrototype<SchemaContext> prototype = DataContainerCodecPrototype.rootPrototype(factory);
153 return new SchemaRootCodecContext<>(prototype);
157 @SuppressWarnings("unchecked")
159 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
160 /* FIXME: This is still not solved for RPCs
161 * TODO: Probably performance wise RPC, Data and Notification loading cache
162 * should be merge for performance resons. Needs microbenchmark to
163 * determine which is faster (keeping them separate or in same cache).
165 if (Notification.class.isAssignableFrom(childClass)) {
166 return (DataContainerCodecContext<C, ?>) getNotification((Class<? extends Notification>)childClass);
168 return (DataContainerCodecContext<C, ?>) getOrRethrow(childrenByClass,childClass);
172 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
173 final Class<C> childClass) {
174 throw new UnsupportedOperationException("Not supported");
178 public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
179 return getOrRethrow(childrenByQName, arg.getNodeType());
183 public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
184 throw new UnsupportedOperationException("Could not create Binding data representation for root");
187 ActionCodecContext getAction(final Class<? extends Action<?, ?, ?>> action) {
188 return getOrRethrow(actionsByClass, action);
191 NotificationCodecContext<?> getNotification(final Class<? extends Notification> notification) {
192 return getOrRethrow(notificationsByClass, notification);
195 NotificationCodecContext<?> getNotification(final Absolute notification) {
196 return getOrRethrow(notificationsByPath, notification);
199 ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
200 return getOrRethrow(rpcDataByClass, rpcInputOrOutput);
203 RpcInputCodec<?> getRpc(final Absolute containerPath) {
204 return getOrRethrow(rpcDataByPath, containerPath);
207 DataContainerCodecContext<?,?> createDataTreeChildContext(final Class<?> key) {
208 final QName qname = BindingReflections.findQName(key);
209 final DataSchemaNode childSchema = childNonNull(getSchema().getDataChildByName(qname), key,
210 "%s is not top-level item.", key);
211 return DataContainerCodecPrototype.from(key, childSchema, factory()).get();
214 ActionCodecContext createActionContext(final Class<? extends Action<?, ?, ?>> action) {
215 if (KeyedListAction.class.isAssignableFrom(action)) {
216 return prepareActionContext(2, 3, 4, action, KeyedListAction.class);
217 } else if (Action.class.isAssignableFrom(action)) {
218 return prepareActionContext(1, 2, 3, action, Action.class);
220 throw new IllegalArgumentException("The specific action type does not exist for action " + action.getName());
223 private ActionCodecContext prepareActionContext(final int inputOffset, final int outputOffset,
224 final int expectedArgsLength, final Class<? extends Action<?, ?, ?>> action, final Class<?> actionType) {
225 final Optional<ParameterizedType> optParamType = ClassLoaderUtils.findParameterizedType(action, actionType);
226 checkState(optParamType.isPresent(), "%s does not specialize %s", action, actionType);
228 final ParameterizedType paramType = optParamType.get();
229 final Type[] args = paramType.getActualTypeArguments();
230 checkArgument(args.length == expectedArgsLength, "Unexpected (%s) Action generatic arguments", args.length);
231 final ActionDefinition schema = factory().getRuntimeContext().getActionDefinition(action);
232 return new ActionCodecContext(
233 DataContainerCodecPrototype.from(asClass(args[inputOffset], RpcInput.class), schema.getInput(),
235 DataContainerCodecPrototype.from(asClass(args[outputOffset], RpcOutput.class), schema.getOutput(),
239 private static <T extends DataObject> Class<? extends T> asClass(final Type type, final Class<T> target) {
240 verify(type instanceof Class, "Type %s is not a class", type);
241 return ((Class<?>) type).asSubclass(target);
244 ContainerNodeCodecContext<?> createRpcDataContext(final Class<?> key) {
245 checkArgument(DataContainer.class.isAssignableFrom(key));
246 final QName qname = BindingReflections.findQName(key);
247 final QNameModule qnameModule = qname.getModule();
248 final Module module = getSchema().findModule(qnameModule)
249 .orElseThrow(() -> new IllegalArgumentException("Failed to find module for " + qnameModule));
250 final String className = BindingMapping.getClassName(qname);
252 for (final RpcDefinition potential : module.getRpcs()) {
253 final QName potentialQName = potential.getQName();
255 * Check if rpc and class represents data from same module and then checks if rpc local name produces same
256 * class name as class name appended with Input/Output based on QName associated with binding class.
258 * FIXME: Rework this to have more precise logic regarding Binding Specification.
260 if (key.getSimpleName().equals(BindingMapping.getClassName(potentialQName) + className)) {
261 final ContainerSchemaNode schema = SchemaNodeUtils.getRpcDataSchema(potential, qname);
262 checkArgument(schema != null, "Schema for %s does not define input / output.", potential.getQName());
263 return (ContainerNodeCodecContext<?>) DataContainerCodecPrototype.from(key, schema, factory()).get();
267 throw new IllegalArgumentException("Supplied class " + key + " is not valid RPC class.");
270 NotificationCodecContext<?> createNotificationDataContext(final Class<?> notificationType) {
271 checkArgument(Notification.class.isAssignableFrom(notificationType));
272 checkArgument(notificationType.isInterface(), "Supplied class must be interface.");
273 final QName qname = BindingReflections.findQName(notificationType);
275 * FIXME: After Lithium cleanup of yang-model-api, use direct call on schema context
276 * to retrieve notification via index.
278 final NotificationDefinition schema = SchemaContextUtil.getNotificationSchema(getSchema(),
279 SchemaPath.create(true, qname));
280 checkArgument(schema != null, "Supplied %s is not valid notification", notificationType);
282 return new NotificationCodecContext<>(notificationType, schema, factory());
285 ChoiceNodeCodecContext<?> createChoiceDataContext(final Class<? extends DataObject> caseType) {
286 final Class<?> choiceClass = findCaseChoice(caseType);
287 checkArgument(choiceClass != null, "Class %s is not a valid case representation", caseType);
288 final DataSchemaNode schema = factory().getRuntimeContext().getSchemaDefinition(choiceClass);
289 checkArgument(schema instanceof ChoiceSchemaNode, "Class %s does not refer to a choice", caseType);
291 final DataContainerCodecContext<?, ChoiceSchemaNode> choice = DataContainerCodecPrototype.from(choiceClass,
292 (ChoiceSchemaNode)schema, factory()).get();
293 Verify.verify(choice instanceof ChoiceNodeCodecContext);
294 return (ChoiceNodeCodecContext<?>) choice;
298 protected Object deserializeObject(final NormalizedNode<?, ?> normalizedNode) {
299 throw new UnsupportedOperationException("Unable to deserialize root");
303 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
304 checkArgument(arg == null);
309 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
310 checkArgument(arg == null);
315 public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
316 final List<PathArgument> builder) {
317 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
318 if (caseType.isPresent()) {
319 // XXX: we use two caseType.get()s because of https://bugs.openjdk.java.net/browse/JDK-8144185,
320 // which makes JaCoCo blow up if we try using @NonNull on the local variable.
321 final ChoiceNodeCodecContext<?> choice = choicesByClass.getUnchecked(caseType.get());
322 choice.addYangPathArgument(arg, builder);
323 final DataContainerCodecContext<?, ?> caze = choice.streamChild(caseType.get());
324 caze.addYangPathArgument(arg, builder);
325 return caze.bindingPathArgumentChild(arg, builder);
328 return super.bindingPathArgumentChild(arg, builder);
331 private static Class<?> findCaseChoice(final Class<? extends DataObject> caseClass) {
332 for (Type type : caseClass.getGenericInterfaces()) {
333 if (type instanceof Class) {
334 final Class<?> typeClass = (Class<?>) type;
335 if (ChoiceIn.class.isAssignableFrom(typeClass)) {
336 return typeClass.asSubclass(ChoiceIn.class);
344 private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
346 return cache.getUnchecked(key);
347 } catch (final UncheckedExecutionException e) {
348 final Throwable cause = e.getCause();
350 Throwables.throwIfUnchecked(cause);