diff options
author | Zhuoyao Huang <10112215@zte.com.cn> | 2017-09-23 14:43:23 +0800 |
---|---|---|
committer | Zhuoyao Huang <10112215@zte.com.cn> | 2017-09-23 14:45:49 +0800 |
commit | 8de219f6b04458d40d4229c7ec2beda7e3f262b3 (patch) | |
tree | 74f770787244837a56924e1d5307cfd9be287e85 /common/src/main/java/org | |
parent | 3069884affc18e293686692c291fcb21f2ddf024 (diff) |
Yang decoder
Change-Id: I4e264c33915969f883ebc3721e7020fb1256682c
Issue-ID: SO-88
Signed-off-by: Zhuoyao Huang <10112215@zte.com.cn>
description: It could help SO to use the restconf interface which is generated by yang-tools in SDN-C directly.
Diffstat (limited to 'common/src/main/java/org')
21 files changed, 1666 insertions, 0 deletions
diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/base/DataBrokerTestCustomizer.java b/common/src/main/java/org/openecomp/mso/yangDecoder/base/DataBrokerTestCustomizer.java new file mode 100644 index 0000000000..f442372dcd --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/base/DataBrokerTestCustomizer.java @@ -0,0 +1,121 @@ +package org.openecomp.mso.yangDecoder.base; + +import com.google.common.collect.ImmutableMap; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import javassist.ClassPool; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.binding.api.NotificationPublishService; +import org.opendaylight.mdsal.binding.api.NotificationService; +import org.opendaylight.mdsal.binding.dom.adapter.BindingDOMDataBrokerAdapter; +import org.opendaylight.mdsal.binding.dom.adapter.BindingDOMNotificationPublishServiceAdapter; +import org.opendaylight.mdsal.binding.dom.adapter.BindingDOMNotificationServiceAdapter; +import org.opendaylight.mdsal.binding.dom.adapter.BindingToNormalizedNodeCodec; +import org.opendaylight.mdsal.common.api.LogicalDatastoreType; +import org.opendaylight.mdsal.dom.api.DOMDataBroker; +import org.opendaylight.mdsal.dom.api.DOMSchemaService; +import org.opendaylight.mdsal.dom.broker.DOMNotificationRouter; +import org.opendaylight.mdsal.dom.broker.SerializedDOMDataBroker; +import org.opendaylight.mdsal.dom.spi.store.DOMStore; +import org.opendaylight.mdsal.dom.store.inmemory.InMemoryDOMDataStore; +import org.opendaylight.yangtools.binding.data.codec.gen.impl.DataObjectSerializerGenerator; +import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator; +import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry; +import org.opendaylight.mdsal.binding.generator.impl.GeneratedClassLoadingStrategy; +import org.opendaylight.mdsal.binding.generator.util.JavassistUtils; +import org.opendaylight.yangtools.yang.model.api.SchemaContext; + +public class DataBrokerTestCustomizer { + + private DOMDataBroker domDataBroker; + private final DOMNotificationRouter domNotificationRouter; + private final MockSchemaService schemaService; + private ImmutableMap<LogicalDatastoreType, DOMStore> datastores; + private final BindingToNormalizedNodeCodec bindingToNormalized; + + public ImmutableMap<LogicalDatastoreType, DOMStore> createDatastores() { + return ImmutableMap.<LogicalDatastoreType, DOMStore>builder() + .put(LogicalDatastoreType.OPERATIONAL, createOperationalDatastore()) + .put(LogicalDatastoreType.CONFIGURATION,createConfigurationDatastore()) + .build(); + } + + public DataBrokerTestCustomizer() { + schemaService = new MockSchemaService(); + final ClassPool pool = ClassPool.getDefault(); + final DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool)); + final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator); + final GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(); + bindingToNormalized = new BindingToNormalizedNodeCodec(loading, codecRegistry); + schemaService.registerSchemaContextListener(bindingToNormalized); + domNotificationRouter = DOMNotificationRouter.create(16); + } + + public DOMStore createConfigurationDatastore() { + final InMemoryDOMDataStore store = new InMemoryDOMDataStore("CFG", MoreExecutors.sameThreadExecutor()); + schemaService.registerSchemaContextListener(store); + return store; + } + + public DOMStore createOperationalDatastore() { + final InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor()); + schemaService.registerSchemaContextListener(store); + return store; + } + + public DOMDataBroker createDOMDataBroker() { + return new SerializedDOMDataBroker(getDatastores(), getCommitCoordinatorExecutor()); + } + + public NotificationService createNotificationService() { + return new BindingDOMNotificationServiceAdapter(bindingToNormalized.getCodecRegistry(), domNotificationRouter); + } + + public NotificationPublishService createNotificationPublishService() { + return new BindingDOMNotificationPublishServiceAdapter(bindingToNormalized, domNotificationRouter); + } + + + public ListeningExecutorService getCommitCoordinatorExecutor() { + return MoreExecutors.sameThreadExecutor(); + } + + public DataBroker createDataBroker() { + return new BindingDOMDataBrokerAdapter(getDOMDataBroker(), bindingToNormalized); + } + + public BindingToNormalizedNodeCodec getBindingToNormalized() { + return bindingToNormalized; + } + + public DOMSchemaService getSchemaService() { + return schemaService; + } + + private DOMDataBroker getDOMDataBroker() { + if(domDataBroker == null) { + domDataBroker = createDOMDataBroker(); + } + return domDataBroker; + } + + private synchronized ImmutableMap<LogicalDatastoreType, DOMStore> getDatastores() { + if (datastores == null) { + datastores = createDatastores(); + } + return datastores; + } + + public void updateSchema(final SchemaContext ctx) { + schemaService.changeSchema(ctx); + } + + public DOMNotificationRouter getDomNotificationRouter() { + return domNotificationRouter; + } + public void close() + { + if(bindingToNormalized!=null)bindingToNormalized.close(); + if(domNotificationRouter!=null)domNotificationRouter.close(); + } +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/base/MockSchemaService.java b/common/src/main/java/org/openecomp/mso/yangDecoder/base/MockSchemaService.java new file mode 100644 index 0000000000..f869a3c600 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/base/MockSchemaService.java @@ -0,0 +1,42 @@ +package org.openecomp.mso.yangDecoder.base; +import org.opendaylight.mdsal.dom.api.DOMSchemaService; +import org.opendaylight.yangtools.concepts.ListenerRegistration; +import org.opendaylight.yangtools.util.ListenerRegistry; +import org.opendaylight.yangtools.yang.model.api.SchemaContext; +import org.opendaylight.yangtools.yang.model.api.SchemaContextListener; +import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; + +public final class MockSchemaService implements DOMSchemaService, SchemaContextProvider { + + private SchemaContext schemaContext; + + ListenerRegistry<SchemaContextListener> listeners = ListenerRegistry.create(); + + @Override + public synchronized SchemaContext getGlobalContext() { + return schemaContext; + } + + @Override + public synchronized SchemaContext getSessionContext() { + return schemaContext; + } + + @Override + public ListenerRegistration<SchemaContextListener> registerSchemaContextListener( + final SchemaContextListener listener) { + return listeners.register(listener); + } + + @Override + public synchronized SchemaContext getSchemaContext() { + return schemaContext; + } + + public synchronized void changeSchema(final SchemaContext newContext) { + schemaContext = newContext; + for (ListenerRegistration<SchemaContextListener> listener : listeners) { + listener.getInstance().onGlobalContextUpdated(schemaContext); + } + } +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/base/TYangJsonXmlBase.java b/common/src/main/java/org/openecomp/mso/yangDecoder/base/TYangJsonXmlBase.java new file mode 100644 index 0000000000..5167d9de8d --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/base/TYangJsonXmlBase.java @@ -0,0 +1,87 @@ +package org.openecomp.mso.yangDecoder.base; + +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.dom.api.DOMDataBroker; +import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext; +import org.opendaylight.yangtools.yang.binding.YangModuleInfo; +import org.opendaylight.yangtools.yang.binding.util.BindingReflections; +import org.opendaylight.yangtools.yang.model.api.SchemaContext; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; + +//-- + +public abstract class TYangJsonXmlBase { + + private Iterable<YangModuleInfo> moduleInfos; + protected SchemaContext schemaContext; +//---------- + private DataBrokerTestCustomizer testCustomizer; + private DataBroker dataBroker; + private DOMDataBroker domBroker; + + protected Iterable<YangModuleInfo> getModuleInfos() throws Exception { + return BindingReflections.loadModuleInfos(); + } + public static void writefile(String confname, String strx) + { + final String outd="outdir"; + File dir = new File(outd); + dir.mkdir(); + String fn = outd+File.separatorChar+confname; + try(FileWriter fw = new FileWriter(fn); BufferedWriter writer = new BufferedWriter(fw)) + { + // FileWriter fw = new FileWriter(fn); + // BufferedWriter writer = new BufferedWriter(fw); + writer.write(strx); + // writer.close(); + // fw.close(); + } + catch (Exception e) + { + } + } + + public final void setup() throws Exception { + moduleInfos = getModuleInfos(); + ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create(); + moduleContext.addModuleInfos(moduleInfos); + schemaContext = moduleContext.tryToCreateSchemaContext().get(); + setupWithSchema(schemaContext); + } + + /** + * Setups test with Schema context. + * + * @param context schema context + */ + protected void setupWithSchema(SchemaContext context){ + testCustomizer = createDataBrokerTestCustomizer(); + dataBroker = testCustomizer.createDataBroker(); + domBroker = testCustomizer.createDOMDataBroker(); + testCustomizer.updateSchema(context); + setupWithDataBroker(dataBroker); + } + protected void setupWithDataBroker(final DataBroker dataBroker) { + // Intentionally left No-op, subclasses may customize it + } + + protected DataBrokerTestCustomizer createDataBrokerTestCustomizer() { + return new DataBrokerTestCustomizer(); + } + + public DataBroker getDataBroker() { + return dataBroker; + } + + public DOMDataBroker getDomBroker() { + return domBroker; + } + public void close() + { + //domBroker. + testCustomizer.close(); + } +}
\ No newline at end of file diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/base/TYangJsonXmlOSGIBase.java b/common/src/main/java/org/openecomp/mso/yangDecoder/base/TYangJsonXmlOSGIBase.java new file mode 100644 index 0000000000..34d3735b08 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/base/TYangJsonXmlOSGIBase.java @@ -0,0 +1,16 @@ +package org.openecomp.mso.yangDecoder.base; + +import org.openecomp.mso.yangDecoder.transform.api.ITransformJava2StringService; +import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer; + +public interface TYangJsonXmlOSGIBase { + + public abstract void init(BindingNormalizedNodeSerializer mappingService) + throws Exception; + + public abstract ITransformJava2StringService getJava2StringService( + String jsonorxml); + + public abstract void close(); + +}
\ No newline at end of file diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/api/ITransformJava2StringService.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/api/ITransformJava2StringService.java new file mode 100644 index 0000000000..93e16772d3 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/api/ITransformJava2StringService.java @@ -0,0 +1,27 @@ +package org.openecomp.mso.yangDecoder.transform.api; + +import org.opendaylight.yangtools.yang.binding.DataObject; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.Notification; + +/** + * Created by Administrator on 2017/3/21. + */ +public interface ITransformJava2StringService { + //following function encode + <T extends DataObject> + String transformContrainerDataObjectToString(InstanceIdentifier<T> instanceIdentifier, String uriPath, T dataObject) + throws Exception; + <T extends Notification> + String transformNotificationToString(String uriPath, T notification) throws Exception; + <T extends DataObject> + String transformRpcDataObjectToString(String uriPath, T dataObject) throws Exception; + + //following function decode + //for container + DataObject transformContrainerDataObjectFromString(String uriPath, String sxml, boolean ispost) throws Exception; + //notification + Notification transformNotificationFromString(String notficationName, String sxml) throws Exception; + //for rpc + DataObject transformRpcDataObjectFromString(String rpcName, String sxml) throws Exception; +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/api/NormalizedNodeVisitor.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/api/NormalizedNodeVisitor.java new file mode 100644 index 0000000000..2a893b0a9e --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/api/NormalizedNodeVisitor.java @@ -0,0 +1,6 @@ +package org.openecomp.mso.yangDecoder.transform.api; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; + +public interface NormalizedNodeVisitor { + void visitNode(int var1, String var2, NormalizedNode<?, ?> var3, boolean start); +}
\ No newline at end of file diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/JsonParserStream.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/JsonParserStream.java new file mode 100644 index 0000000000..c9e4c1dbae --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/JsonParserStream.java @@ -0,0 +1,24 @@ +package org.openecomp.mso.yangDecoder.transform.impl; + +import com.google.common.base.Preconditions; +import org.opendaylight.yangtools.yang.data.util.RpcAsContainer; +import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; +import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; +import org.opendaylight.yangtools.yang.model.api.RpcDefinition; +import org.opendaylight.yangtools.yang.model.api.SchemaNode; + +/** + * Created by 10112215 on 2017/9/17. + */ +public class JsonParserStream { + public static DataSchemaNode getWrapSchemaNode(SchemaNode parentNode) { + if(parentNode instanceof RpcDefinition) { + return new RpcAsContainer((RpcDefinition)parentNode); + } else if(parentNode instanceof NotificationDefinition) { + return new NotificationAsContainer((NotificationDefinition)parentNode); + } else { + Preconditions.checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited."); + return (DataSchemaNode)parentNode; + } + } +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/NormalizedNodeNavigator.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/NormalizedNodeNavigator.java new file mode 100644 index 0000000000..c585529cf2 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/NormalizedNodeNavigator.java @@ -0,0 +1,91 @@ +package org.openecomp.mso.yangDecoder.transform.impl; + +import com.google.common.base.Preconditions; +import org.openecomp.mso.yangDecoder.transform.api.NormalizedNodeVisitor; +import org.opendaylight.yangtools.yang.data.api.schema.*; + +import java.util.Collection; +import java.util.Iterator; + +/** + * Created by 10036837 on 16-7-22. + */ +public class NormalizedNodeNavigator { + private final NormalizedNodeVisitor visitor; + + public NormalizedNodeNavigator(NormalizedNodeVisitor visitor) { + Preconditions.checkNotNull(visitor, "visitor should not be null"); + this.visitor = visitor; + } + + public void navigate(String parentPath, NormalizedNode<?, ?> normalizedNode) { + if (parentPath == null) { + parentPath = ""; + } + + this.navigateNormalizedNode(0, parentPath, normalizedNode); + + } + + private void navigateDataContainerNode(int level, String parentPath, DataContainerNode<?> dataContainerNode) { + this.visitor.visitNode(level, parentPath, dataContainerNode, true); + String newParentPath = parentPath + "/" + dataContainerNode.getIdentifier().toString(); + Collection value = dataContainerNode.getValue(); + Iterator var6 = value.iterator(); + + while (var6.hasNext()) { + NormalizedNode node = (NormalizedNode) var6.next(); + if (node instanceof MixinNode && node instanceof NormalizedNodeContainer) { + this.navigateNormalizedNodeContainerMixin(level, newParentPath, (NormalizedNodeContainer) node); + } else { + this.navigateNormalizedNode(level, newParentPath, node); + } + } + this.visitor.visitNode(level, parentPath, dataContainerNode, false); + } + + private void navigateOrderedNodeContainer(int level, String parentPath, OrderedNodeContainer<?> node) { + String newParentPath = parentPath + "/" + node.getIdentifier().toString(); + Collection value = node.getValue(); + Iterator var6 = value.iterator(); + + while (var6.hasNext()) { + NormalizedNode normalizedNode = (NormalizedNode) var6.next(); + if (normalizedNode instanceof OrderedNodeContainer) { + this.navigateOrderedNodeContainer(level, newParentPath, (OrderedNodeContainer) normalizedNode); + } else { + this.navigateNormalizedNode(level, newParentPath, normalizedNode); + } + } + + } + + private void navigateNormalizedNodeContainerMixin(int level, String parentPath, NormalizedNodeContainer<?, ?, ?> node) { + + String newParentPath = parentPath + "/" + node.getIdentifier().toString(); + Collection value = node.getValue(); + Iterator var6 = value.iterator(); + + while (var6.hasNext()) { + NormalizedNode normalizedNode = (NormalizedNode) var6.next(); + if (normalizedNode instanceof MixinNode && normalizedNode instanceof NormalizedNodeContainer) { + this.navigateNormalizedNodeContainerMixin(level, newParentPath, (NormalizedNodeContainer) normalizedNode); + } else { + this.navigateNormalizedNode(level, newParentPath, normalizedNode); + } + } + + } + + private void navigateNormalizedNode(int level, String parentPath, NormalizedNode<?, ?> normalizedNode) { + if (normalizedNode instanceof DataContainerNode) { + DataContainerNode dataContainerNode = (DataContainerNode) normalizedNode; + this.navigateDataContainerNode(level+1, parentPath, dataContainerNode); + } else if (normalizedNode instanceof OrderedNodeContainer) { + this.navigateOrderedNodeContainer(level, parentPath, (OrderedNodeContainer) normalizedNode); + } else { + this.visitor.visitNode(level + 1, parentPath, normalizedNode, false); + } + + } +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/NormalizedNodePrinter.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/NormalizedNodePrinter.java new file mode 100644 index 0000000000..6b2c7dfbff --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/NormalizedNodePrinter.java @@ -0,0 +1,93 @@ +package org.openecomp.mso.yangDecoder.transform.impl; +import org.openecomp.mso.yangDecoder.transform.api.NormalizedNodeVisitor; +import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.data.api.schema.LeafNode; +import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; + + +/** + * Created by 10036837 on 16-7-21. + */ +public class NormalizedNodePrinter implements NormalizedNodeVisitor { + StringBuilder result; + private static final String CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + public NormalizedNodePrinter(StringBuilder result) { + this.result = result; + } + private final static String endl=System.getProperty("line.separator"); + public final static String getEndl(){ + return endl; + } + private static String spaces(int n) { + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < n; i++) { + builder.append(' '); + } + return builder.toString(); + } + + @Override + public void visitNode(int level, String parentPath, NormalizedNode<?, ?> normalizedNode, boolean start) { + if(normalizedNode == null) + { + return; + } + if(normalizedNode.getNodeType() == null) + { + return; + } + + String localName = normalizedNode.getNodeType().getLocalName(); + if (normalizedNode instanceof LeafNode || normalizedNode instanceof LeafSetEntryNode) { + if(normalizedNode.getValue() instanceof byte[]){ + result.append(spaces((level-1) * 4) + "<" + localName + ">" + (normalizedNode.getValue() == null ? "" : base64Encode((byte[]) normalizedNode.getValue())) + "</" + localName + ">"+endl); + } + else { + String svalue=normalizedNode.getValue().toString(); + if(normalizedNode.getValue() instanceof QName){ + QName qn=(QName)normalizedNode.getValue(); + svalue= qn.getLocalName(); + } + result.append(spaces((level - 1) * 4) + "<" + localName + ">" + (normalizedNode.getValue() == null ? "" :svalue) + "</" + localName + ">"+endl); + } + } else { + if (start) { + if (level == 1) { + result.append(spaces((level-1) * 4) + "<" + localName + " xmlns=\"" + normalizedNode.getNodeType().getNamespace() + "\">"+endl); + } else { + result.append(spaces((level-1) * 4) + "<" + localName + ">"+endl); + } + } else { + result.append(spaces((level-1) * 4) + "</" + localName + ">"+endl); + } + } + } + private String base64Encode(byte[] in) { + StringBuilder out = new StringBuilder((in.length * 4) / 3); + int b; + for (int i = 0; i < in.length; i += 3) { + b = (in[i] & 0xFC) >> 2; + out.append(CODES.charAt(b)); + b = (in[i] & 0x03) << 4; + if (i + 1 < in.length) { + b |= (in[i + 1] & 0xF0) >> 4; + out.append(CODES.charAt(b)); + b = (in[i + 1] & 0x0F) << 2; + if (i + 2 < in.length) { + b |= (in[i + 2] & 0xC0) >> 6; + out.append(CODES.charAt(b)); + b = in[i + 2] & 0x3F; + out.append(CODES.charAt(b)); + } else { + out.append(CODES.charAt(b)); + out.append('='); + } + } else { + out.append(CODES.charAt(b)); + out.append("=="); + } + } + return out.toString(); + } +}
\ No newline at end of file diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/NotificationAsContainer.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/NotificationAsContainer.java new file mode 100644 index 0000000000..31c894e6fb --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/NotificationAsContainer.java @@ -0,0 +1,129 @@ +package org.openecomp.mso.yangDecoder.transform.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.model.api.AugmentationSchema; +import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition; +import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; +import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; +import org.opendaylight.yangtools.yang.model.api.GroupingDefinition; +import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; +import org.opendaylight.yangtools.yang.model.api.SchemaPath; +import org.opendaylight.yangtools.yang.model.api.Status; +import org.opendaylight.yangtools.yang.model.api.TypeDefinition; +import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode; +import org.opendaylight.yangtools.yang.model.api.UsesNode; + +final class NotificationAsContainer implements ContainerSchemaNode { + private final NotificationDefinition delegate; + + public String getDescription() { + return this.delegate.getDescription(); + } + + public String getReference() { + return this.delegate.getReference(); + } + + public Set<TypeDefinition<?>> getTypeDefinitions() { + return this.delegate.getTypeDefinitions(); + } + + public Set<GroupingDefinition> getGroupings() { + return this.delegate.getGroupings(); + } + + public Status getStatus() { + return this.delegate.getStatus(); + } + + public ContainerSchemaNode getInput() { + return null; + } + + public ContainerSchemaNode getOutput() { + return null; + } + + NotificationAsContainer(NotificationDefinition parentNode) { + this.delegate = parentNode; + } + + public QName getQName() { + return this.delegate.getQName(); + } + + public SchemaPath getPath() { + return this.delegate.getPath(); + } + + public List<UnknownSchemaNode> getUnknownSchemaNodes() { + return Collections.emptyList(); + } + + public DataSchemaNode getDataChildByName(QName name) { + return this.getDataChildByName(name.getLocalName()); + } + + public DataSchemaNode getDataChildByName(String name) { + byte var3 = -1; + switch(name.hashCode()) { + case -1005512447: + if(name.equals("output")) { + var3 = 1; + } + break; + case 100358090: + if(name.equals("input")) { + var3 = 0; + } + } + + switch(var3) { + case 0: + return null; + case 1: + return null; + default: + return null; + } + } + + public Set<UsesNode> getUses() { + return Collections.emptySet(); + } + + public Set<AugmentationSchema> getAvailableAugmentations() { + return Collections.emptySet(); + } + + public boolean isPresenceContainer() { + return false; + } + + public Collection<DataSchemaNode> getChildNodes() { + ArrayList ret = new ArrayList(); + ret.addAll(this.delegate.getChildNodes()); + return ret; + } + + public boolean isAugmenting() { + return false; + } + + public boolean isAddedByUses() { + return false; + } + + public boolean isConfiguration() { + return false; + } + + public ConstraintDefinition getConstraints() { + return null; + } +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransformJava2JsonFactory.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransformJava2JsonFactory.java new file mode 100644 index 0000000000..647b3038bb --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransformJava2JsonFactory.java @@ -0,0 +1,63 @@ +package org.openecomp.mso.yangDecoder.transform.impl; + +import javassist.ClassPool; +import org.openecomp.mso.yangDecoder.base.TYangJsonXmlBase; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.binding.dom.adapter.BindingToNormalizedNodeCodec; +import org.opendaylight.netconf.sal.restconf.impl.ControllerContext; +import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator; +import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry; +import org.opendaylight.mdsal.binding.generator.impl.GeneratedClassLoadingStrategy; +import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext; +import org.opendaylight.mdsal.binding.generator.util.JavassistUtils; +import org.opendaylight.yangtools.yang.binding.YangModuleInfo; + +/** + * Created by 10112215 on 2017/3/26. + */ +public class TransformJava2JsonFactory extends TYangJsonXmlBase { + BindingToNormalizedNodeCodec mappingservice; + ModuleInfoBackedContext moduleInfoBackedContext; + protected final static ControllerContext controllerContext = ControllerContext.getInstance(); + + public TransformJava2JsonServiceImpl getJava2jsonService() { + if (java2jsonService == null) { + try { + setup2(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + return java2jsonService; + } + + TransformJava2JsonServiceImpl java2jsonService; + + @Override + protected void setupWithDataBroker(final DataBroker dataBroker) { + // Intentionally left No-op, subclasses may customize it + mappingservice = new BindingToNormalizedNodeCodec(GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(), + new BindingNormalizedNodeCodecRegistry(StreamWriterGenerator.create(JavassistUtils.forClassPool(ClassPool.getDefault())))); + moduleInfoBackedContext = ModuleInfoBackedContext.create(); + // moduleInfoBackedContext.registerModuleInfo(BindingReflections.getModuleInfo(SncTunnels.class)); + + try { + for (YangModuleInfo yangModuleInfo : getModuleInfos()) { + moduleInfoBackedContext.registerModuleInfo(yangModuleInfo); + } + } catch (Exception e) { + e.printStackTrace(); + } + schemaContext = moduleInfoBackedContext.tryToCreateSchemaContext().get(); + mappingservice.onGlobalContextUpdated(schemaContext); + controllerContext.setSchemas(schemaContext); + + } + + public final void setup2() throws Exception { + super.setup(); + if(java2jsonService==null) + java2jsonService = new TransformJava2JsonServiceImpl(mappingservice, schemaContext); + } +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransformJava2JsonServiceImpl.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransformJava2JsonServiceImpl.java new file mode 100644 index 0000000000..2009cff7de --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransformJava2JsonServiceImpl.java @@ -0,0 +1,93 @@ +package org.openecomp.mso.yangDecoder.transform.impl; + +import org.openecomp.mso.yangDecoder.transform.api.ITransformJava2StringService; +import org.opendaylight.netconf.sal.restconf.impl.ControllerContext; +import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext; +import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext; +import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer; +import org.opendaylight.yangtools.yang.binding.DataObject; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.Notification; +import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.model.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by Administrator on 2017/3/20. + */ +public class TransformJava2JsonServiceImpl implements ITransformJava2StringService { + private static final Logger LOG = LoggerFactory.getLogger(TransformJava2JsonServiceImpl.class); + BindingNormalizedNodeSerializer mappingservice; + SchemaContext schemaContext; + YangDataTransformNN2JsonServiceImpl nn2jsonService; + YangDataTransformJava2NNServiceImpl java2nnService; + public TransformJava2JsonServiceImpl(BindingNormalizedNodeSerializer mappingservice, SchemaContext schemaContext){ + this.mappingservice=mappingservice; + this.schemaContext=schemaContext; + nn2jsonService=new YangDataTransformNN2JsonServiceImpl(); + java2nnService=new YangDataTransformJava2NNServiceImpl(mappingservice); + } + @Override + public <T extends DataObject> String transformContrainerDataObjectToString(InstanceIdentifier<T> instanceIdentifier, String uriPath,T dataObject) throws Exception { + // TODO Auto-generated method stub + NormalizedNode nn = java2nnService.yangDataObjecttoNN(instanceIdentifier, dataObject); + NormalizedNodeContext nnc = java2nnService.yangNNtoNNC(nn, uriPath); + String sjson = nn2jsonService.transformNNCToString(nnc); + return sjson; + } + @Override + public <T extends Notification> String transformNotificationToString(String uriPath,T notification)throws Exception { + NormalizedNode nn = mappingservice.toNormalizedNodeNotification(notification); + NormalizedNodeContext nnc = java2nnService.yangNNtoNNC(nn, uriPath); + String sjson = nn2jsonService.transformNNCToString(nnc); + return sjson; + } + @Override + public <T extends DataObject> String transformRpcDataObjectToString(String uriPath,T dataObject) throws Exception { + NormalizedNode nn = mappingservice.toNormalizedNodeRpcData(dataObject); + NormalizedNodeContext nnc = java2nnService.yangNNtoNNC(nn, uriPath); + String sjson = nn2jsonService.transformNNCToString(nnc); + return sjson; + } + @Override + public DataObject transformContrainerDataObjectFromString(String uriPath,String sjson,boolean ispost) throws Exception { + NormalizedNodeContext nnc= nn2jsonService.transformDataObjectNNCFromString(uriPath,sjson,ispost); + return java2nnService.yangDataObjectfromNNC(nnc); + } + @Override + public Notification transformNotificationFromString(String notficationName,String sjson) throws Exception { + final InstanceIdentifierContext<?> iicontext = ControllerContext.getInstance().toInstanceIdentifier(notficationName); + NormalizedNodeContext nnc= nn2jsonService.transformNotficationNNCFromString(notficationName,sjson); + ContainerNode contn= (ContainerNode)nnc.getData(); + return mappingservice.fromNormalizedNodeNotification(iicontext.getSchemaNode().getPath(),contn); + } + @Override + public DataObject transformRpcDataObjectFromString(String rpcName,String sjson) throws Exception { + final InstanceIdentifierContext<?> iicontext = ControllerContext.getInstance().toInstanceIdentifier(rpcName); + NormalizedNodeContext nnc= nn2jsonService.transformRPCNNCFromString(rpcName,sjson); + return java2nnService.yangRpcDatafromNN(iicontext,nnc.getData()); + /* ContainerNode contn= (ContainerNode)nnc.getData(); + DataSchemaNode schemaNode; + final SchemaNode schemaNode0 = iicontext.getSchemaNode(); + boolean isInput = false; + if (schemaNode0 instanceof RpcDefinition) { + if (contn.getNodeType().getLocalName().contains("output")) { + schemaNode = ((RpcDefinition) schemaNode0).getOutput(); + isInput = false; + } else { + schemaNode = ((RpcDefinition) schemaNode0).getInput(); + isInput = true; + } + + } else if (schemaNode0 instanceof DataSchemaNode) { + schemaNode = (DataSchemaNode) schemaNode0; + } else { + throw new IllegalStateException("Unknow SchemaNode"); + } + return mappingservice.fromNormalizedNodeRpcData(schemaNode.getPath(),contn); */ + //return mappingservice.toNormalizedNodeRpcData((DataContainer) nnc.getData()); + // return java2nnService.yangDataObjectfromNNC(nnc); + } +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransformJava2XMLFactory.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransformJava2XMLFactory.java new file mode 100644 index 0000000000..5e5511b5e7 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransformJava2XMLFactory.java @@ -0,0 +1,64 @@ +package org.openecomp.mso.yangDecoder.transform.impl; + +import javassist.ClassPool; +import org.openecomp.mso.yangDecoder.base.TYangJsonXmlBase; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.binding.dom.adapter.BindingToNormalizedNodeCodec; +import org.opendaylight.netconf.sal.restconf.impl.ControllerContext; +import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator; +import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry; +import org.opendaylight.mdsal.binding.generator.impl.GeneratedClassLoadingStrategy; +import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext; +import org.opendaylight.mdsal.binding.generator.util.JavassistUtils; +import org.opendaylight.yangtools.yang.binding.YangModuleInfo; + +/** + * Created by 10112215 on 2017/3/26. + */ +public class TransformJava2XMLFactory extends TYangJsonXmlBase { + BindingToNormalizedNodeCodec mappingservice; + ModuleInfoBackedContext moduleInfoBackedContext; + protected final static ControllerContext controllerContext = ControllerContext.getInstance(); + + public TransformJava2XMLServiceImpl getJava2xmlService() { + if (java2xmlService == null) { + try { + setup2(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + return java2xmlService; + } + + TransformJava2XMLServiceImpl java2xmlService; + + @Override + protected void setupWithDataBroker(final DataBroker dataBroker) { + // Intentionally left No-op, subclasses may customize it + mappingservice = new BindingToNormalizedNodeCodec(GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(), + new BindingNormalizedNodeCodecRegistry(StreamWriterGenerator.create(JavassistUtils.forClassPool(ClassPool.getDefault())))); + moduleInfoBackedContext = ModuleInfoBackedContext.create(); + // moduleInfoBackedContext.registerModuleInfo(BindingReflections.getModuleInfo(SncTunnels.class)); + try { + for (YangModuleInfo yangModuleInfo : getModuleInfos()) { + moduleInfoBackedContext.registerModuleInfo(yangModuleInfo); + } + } catch (Exception e) { + e.printStackTrace(); + } + schemaContext = moduleInfoBackedContext.tryToCreateSchemaContext().get(); + mappingservice.onGlobalContextUpdated(schemaContext); + controllerContext.setSchemas(schemaContext); + + } + + public final void setup2() throws Exception { + super.setup(); + if(java2xmlService==null) + java2xmlService = new TransformJava2XMLServiceImpl(mappingservice, schemaContext); + } + + +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransformJava2XMLServiceImpl.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransformJava2XMLServiceImpl.java new file mode 100644 index 0000000000..2ee7b5cfab --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransformJava2XMLServiceImpl.java @@ -0,0 +1,114 @@ +package org.openecomp.mso.yangDecoder.transform.impl; + +import org.openecomp.mso.yangDecoder.transform.api.ITransformJava2StringService; +import org.opendaylight.netconf.sal.restconf.impl.ControllerContext; +import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext; +import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext; +import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer; +import org.opendaylight.yangtools.yang.binding.DataObject; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.Notification; +import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; +import org.opendaylight.yangtools.yang.model.api.SchemaContext; +import org.opendaylight.yangtools.yang.model.api.SchemaNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Map; + +/** + * Created by Administrator on 2017/3/20. + */ +public class TransformJava2XMLServiceImpl implements ITransformJava2StringService { + private static final Logger LOG = LoggerFactory.getLogger(TransformJava2XMLServiceImpl.class); + BindingNormalizedNodeSerializer mappingservice; + SchemaContext schemaContext; + YangDataTransformJava2NNServiceImpl java2nnService; + YangDataTransformNN2XMLServiceImpl nn2xmlService; + YangOdlNN2XMLImpl yangODLnn2xml; + public TransformJava2XMLServiceImpl(BindingNormalizedNodeSerializer mappingService, SchemaContext schemaContext){ + this.mappingservice=mappingService; + this.schemaContext=schemaContext; + java2nnService=new YangDataTransformJava2NNServiceImpl(mappingService); + nn2xmlService=new YangDataTransformNN2XMLServiceImpl(mappingService,schemaContext); + yangODLnn2xml=new YangOdlNN2XMLImpl(schemaContext); + } + @Override + public <T extends DataObject> String transformContrainerDataObjectToString(InstanceIdentifier<T> instanceIdentifier, String uriPath, T dataObject) + throws Exception { + // TODO Auto-generated method stub + NormalizedNode nn=java2nnService.yangDataObjecttoNN(instanceIdentifier,dataObject); + return yangODLnn2xml.yangNNtoXML(uriPath,nn); + } + @Override + public <T extends Notification> String transformNotificationToString(String uriPath, T notification) + throws Exception { + NormalizedNode nn= mappingservice.toNormalizedNodeNotification(notification); + return yangODLnn2xml.yangNNtoXML(uriPath,nn); + } + @Override + public <T extends DataObject> String transformRpcDataObjectToString(String uriPath, T dataObject) + throws Exception { + NormalizedNode nn=mappingservice.toNormalizedNodeRpcData(dataObject); + return yangODLnn2xml.yangNNtoXML(uriPath,nn); + } + //for container + public <T extends DataObject> String transformContrainerDataObjectToString(InstanceIdentifier<T> instanceIdentifier, T dataObject) { + // TODO Auto-generated method stub + NormalizedNode nn=java2nnService.yangDataObjecttoNN(instanceIdentifier,dataObject); + return nn2xmlService.transformNNToString(nn); + } + + public <T extends Notification> String transformNotificationToString(T notification) { + NormalizedNode nn= mappingservice.toNormalizedNodeNotification(notification); + return nn2xmlService.transformNNToString(nn); + } + + //for rpc + public <T extends DataObject> String transformRpcDataObjectToString(T dataObject) { + NormalizedNode nn=mappingservice.toNormalizedNodeRpcData(dataObject); + return nn2xmlService.transformNNToString(nn); + } + + //for container + @Override + public DataObject transformContrainerDataObjectFromString(String uriPath, String sxml,boolean ispost) throws Exception { + // TODO Auto-generated method stub + if(ispost) + { + NormalizedNodeContext nnc=YangOdlNNC2XMLImpl.fromXML(uriPath,sxml, ispost); + final InstanceIdentifierContext<?> iicontext=nnc.getInstanceIdentifierContext(); + Map.Entry<InstanceIdentifier<?>, DataObject> temp = mappingservice.fromNormalizedNode(iicontext.getInstanceIdentifier(),nnc.getData()); + return (DataObject)temp.getValue(); + } + final InstanceIdentifierContext<?> iicontext = ControllerContext.getInstance().toInstanceIdentifier(uriPath); + NormalizedNode nn =nn2xmlService.transformNNFromString(sxml); + Map.Entry<InstanceIdentifier<?>, DataObject> temp = mappingservice.fromNormalizedNode(iicontext.getInstanceIdentifier(),nn); + if (null == temp) { + return null; + } else { + return temp.getValue(); + } + } + @Override + public Notification transformNotificationFromString(String notficationName, String sxml) throws Exception { + + final InstanceIdentifierContext<?> iicontext = ControllerContext.getInstance().toInstanceIdentifier(notficationName); + NormalizedNode nn = nn2xmlService.transformNotificationStringtoNN(sxml, notficationName); + ContainerNode noti = (ContainerNode) nn; + SchemaNode snode=iicontext.getSchemaNode() ; + Notification obj = mappingservice.fromNormalizedNodeNotification(snode.getPath(), noti); + return obj; + } + //for rpc + @Override + public DataObject transformRpcDataObjectFromString(String rpcName, String sxml) throws Exception { + final InstanceIdentifierContext<?> iicontext = ControllerContext.getInstance().toInstanceIdentifier(rpcName); + Map.Entry<DataSchemaNode, NormalizedNode> nnentry = nn2xmlService.transformRpcNNEntryfromString(sxml,iicontext); + ContainerNode rpc = (ContainerNode) nnentry.getValue(); + DataObject rpcdata= mappingservice.fromNormalizedNodeRpcData(nnentry.getKey().getPath(),rpc); + return rpcdata; + } +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransfromJava2StringFactory.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransfromJava2StringFactory.java new file mode 100644 index 0000000000..e5e5d65606 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/TransfromJava2StringFactory.java @@ -0,0 +1,55 @@ +package org.openecomp.mso.yangDecoder.transform.impl; + +import org.dom4j.DocumentException; +import org.dom4j.DocumentHelper; +import org.openecomp.mso.yangDecoder.transform.api.ITransformJava2StringService; + +/** + * Created by 10112215 on 2017/3/24. + */ +public class TransfromJava2StringFactory { + + private static TransformJava2JsonServiceImpl java2jsonService = (new TransformJava2JsonFactory()).getJava2jsonService(); + + private static TransformJava2XMLServiceImpl java2XMLService/* = (new TransformJava2XMLFactory()).getJava2xmlService()*/; + + public static boolean isXML(String value) { + try { + DocumentHelper.parseText(value); + } catch (DocumentException e) { + return false; + } + return true; + } + + public static ITransformJava2StringService getJava2StringService(String input) throws Exception { + ITransformJava2StringService java2jsonService; + if (isXML(input)) { + java2jsonService = getJava2XMLService(); + } else { + java2jsonService = getJava2jsonService(); + } + return java2jsonService; + } + + public static void init() { + // do no shit for static initialization + } + + public static ITransformJava2StringService getJava2jsonService() throws Exception { + if (java2jsonService == null) { + TransformJava2JsonFactory transformJava2JsonFactory = new TransformJava2JsonFactory(); + java2jsonService = transformJava2JsonFactory.getJava2jsonService(); + } + return java2jsonService; + } + + public static ITransformJava2StringService getJava2XMLService() throws Exception { + if (java2XMLService == null) { + TransformJava2XMLFactory transformJava2XMLFactory = new TransformJava2XMLFactory(); + java2XMLService = transformJava2XMLFactory.getJava2xmlService(); + } + return java2XMLService; + } + +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/XmlNormalizedNodeBodyReaderUmeImpl.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/XmlNormalizedNodeBodyReaderUmeImpl.java new file mode 100644 index 0000000000..e1ebf95a06 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/XmlNormalizedNodeBodyReaderUmeImpl.java @@ -0,0 +1,24 @@ +package org.openecomp.mso.yangDecoder.transform.impl; + +import org.opendaylight.netconf.sal.rest.impl.XmlNormalizedNodeBodyReader; +import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext; + +public class XmlNormalizedNodeBodyReaderUmeImpl extends + XmlNormalizedNodeBodyReader { + InstanceIdentifierContext<?> iic; + boolean ispost=false; + @Override + protected InstanceIdentifierContext<?> getInstanceIdentifierContext() { + return iic; + } + @Override + protected boolean isPost() { + return ispost; + } + public void Set(InstanceIdentifierContext<?> iic,boolean ispost) + { + this.iic=iic; + this.ispost=ispost; + } + +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangDataTransformJava2NNServiceImpl.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangDataTransformJava2NNServiceImpl.java new file mode 100644 index 0000000000..ba82aa5539 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangDataTransformJava2NNServiceImpl.java @@ -0,0 +1,144 @@ +package org.openecomp.mso.yangDecoder.transform.impl; + +//import org.opendaylight.mdsal.binding.dom.adapter.BindingToNormalizedNodeCodec; + +import org.opendaylight.netconf.sal.restconf.impl.ControllerContext; +import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext; +import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext; +import org.opendaylight.netconf.sal.restconf.impl.WriterParameters; +import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer; +import org.opendaylight.yangtools.yang.binding.DataContainer; +import org.opendaylight.yangtools.yang.binding.DataObject; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.model.api.*; + +import java.util.Map; + +/** + * Created by Administrator on 2017/3/17. + */ +public class YangDataTransformJava2NNServiceImpl { + BindingNormalizedNodeSerializer mappingService; + public YangDataTransformJava2NNServiceImpl(BindingNormalizedNodeSerializer mappingService) + { + this.mappingService=mappingService; + } + public <T extends DataObject> NormalizedNodeContext yangDataObjecttoNNC(InstanceIdentifier<T> identifier, String uri, T dobj) + { + final InstanceIdentifierContext<?> iiContext = ControllerContext.getInstance().toInstanceIdentifier(uri); + Map.Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> temp = mappingService.toNormalizedNode(identifier, dobj); + WriterParameters.WriterParametersBuilder aa=new WriterParameters.WriterParametersBuilder(); + aa.setPrettyPrint(true); + return new NormalizedNodeContext( iiContext, temp.getValue() ,aa.build()); + } + public <T extends DataObject> NormalizedNode yangDataObjecttoNN( InstanceIdentifier<T> identifier,T dobj) { + Map.Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> temp = mappingService.toNormalizedNode(identifier, dobj); + if (null == temp) { + return null; + } else { + return temp.getValue(); + } + } + public NormalizedNodeContext yangNNtoNNC(NormalizedNode nn, String uri){ + final InstanceIdentifierContext<?> iiContext = ControllerContext.getInstance().toInstanceIdentifier(uri); + WriterParameters.WriterParametersBuilder aa=new WriterParameters.WriterParametersBuilder(); + aa.setPrettyPrint(true); + return new NormalizedNodeContext(iiContext, nn,aa.build()); + } + public <T extends DataObject> T yangDataObjectfromNN(YangInstanceIdentifier identifier,NormalizedNode node) { + Map.Entry<InstanceIdentifier<?>, DataObject> temp = mappingService.fromNormalizedNode(identifier, node); + if (null == temp) { + return null; + } else { + return (T) temp.getValue(); + } + } + public <T extends DataObject> T yangDataObjectfromNNC(NormalizedNodeContext nnc) + { + return yangDataObjectfromNN(nnc.getInstanceIdentifierContext().getInstanceIdentifier(),nnc.getData()); + } + public ContainerNode yangRpcDatatoNN(final DataContainer rpcdata){ + return mappingService.toNormalizedNodeRpcData(rpcdata); + } + public DataObject yangRpcDatafromNN(SchemaPath path, final ContainerNode data) + { + return mappingService.fromNormalizedNodeRpcData(path,data); + } + public static DataSchemaNode findDataSchemaNode(String uriPath,String inputoroutput) + { + final InstanceIdentifierContext<?> iicontext = ControllerContext.getInstance().toInstanceIdentifier(uriPath); + DataSchemaNode dsn=JsonParserStream.getWrapSchemaNode( iicontext.getSchemaNode()); + return dsn; + } + public static SchemaNode findSchemaNode(final InstanceIdentifierContext<?> iicontext ,String inputoroutput) + { + SchemaNode schemaNode; + + final SchemaNode schemaNode0 = iicontext.getSchemaNode(); + if (schemaNode0 instanceof RpcDefinition) { + if (inputoroutput.contains("output")) { + schemaNode = ((RpcDefinition) schemaNode0).getOutput(); + } else { + schemaNode = ((RpcDefinition) schemaNode0).getInput(); + } + + } else if(schemaNode0 instanceof NotificationDefinition) + { + schemaNode=schemaNode0; + } + else if (schemaNode0 instanceof DataSchemaNode) { + schemaNode = schemaNode0; + } else { + throw new IllegalStateException("Unknow SchemaNode"); + } + return schemaNode; + } + + public static DataSchemaNode findRpcSchemaNode(final InstanceIdentifierContext<?> iicontext,String inputoroutput) + { + DataSchemaNode schemaNode; + final SchemaNode schemaNode0 = iicontext.getSchemaNode(); + boolean isInput = false; + if (schemaNode0 instanceof RpcDefinition) { + if (inputoroutput.contains("output")) { + schemaNode = ((RpcDefinition) schemaNode0).getOutput(); + isInput = false; + } else { + schemaNode = ((RpcDefinition) schemaNode0).getInput(); + isInput = true; + } + + } else if (schemaNode0 instanceof DataSchemaNode) { + schemaNode = (DataSchemaNode) schemaNode0; + } else { + throw new IllegalStateException("Unknow SchemaNode"); + } + return schemaNode; + } + public DataObject yangRpcDatafromNN(final InstanceIdentifierContext<?> iicontext , final NormalizedNode data) { + // final InstanceIdentifierContext<?> iicontext = ControllerContext.getInstance().toInstanceIdentifier(uriPath); + ContainerNode contn= (ContainerNode)data; + DataSchemaNode schemaNode= findRpcSchemaNode(iicontext,contn.getNodeType().getLocalName());; + /* final SchemaNode schemaNode0 = iicontext.getSchemaNode(); + boolean isInput = false; + if (schemaNode0 instanceof RpcDefinition) { + if (contn.getNodeType().getLocalName().contains("output")) { + schemaNode = ((RpcDefinition) schemaNode0).getOutput(); + isInput = false; + } else { + schemaNode = ((RpcDefinition) schemaNode0).getInput(); + isInput = true; + } + + } else if (schemaNode0 instanceof DataSchemaNode) { + schemaNode = (DataSchemaNode) schemaNode0; + } else { + throw new IllegalStateException("Unknow SchemaNode"); + }*/ + SchemaPath path=schemaNode.getPath(); + return mappingService.fromNormalizedNodeRpcData(path,contn); + } +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangDataTransformNN2JsonServiceImpl.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangDataTransformNN2JsonServiceImpl.java new file mode 100644 index 0000000000..dba4a0dea5 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangDataTransformNN2JsonServiceImpl.java @@ -0,0 +1,50 @@ +package org.openecomp.mso.yangDecoder.transform.impl; + +import com.google.common.base.Charsets; +import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader; +import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter; +import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.core.MediaType; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.annotation.Annotation; + +/** + * Created by Administrator on 2017/3/17. + */ +public class YangDataTransformNN2JsonServiceImpl { + private static final Logger LOG = LoggerFactory.getLogger(YangDataTransformNN2JsonServiceImpl.class); + private static final Annotation[] EMPTY_ANNOTATIONS = new Annotation[0]; + + public NormalizedNodeContext transformNNCFromString(String uriPath,String jsonpayload,boolean isPost){ + + InputStream entityStream = new ByteArrayInputStream(jsonpayload.getBytes(Charsets.UTF_8)); + NormalizedNodeContext normalnodes3 = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, isPost); + return normalnodes3; + } + public String transformNNCToString(NormalizedNodeContext readData) throws IOException { + NormalizedNodeJsonBodyWriter writer = new NormalizedNodeJsonBodyWriter(); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + //readData.getWriterParameters().isPrettyPrint() + writer.writeTo(readData, NormalizedNodeContext.class, null, EMPTY_ANNOTATIONS, + MediaType.APPLICATION_JSON_TYPE, null, outputStream ); + return outputStream.toString(Charsets.UTF_8.name()); + } + public NormalizedNodeContext transformRPCNNCFromString(String uriPath,String jsonpayload) + { + return transformNNCFromString(uriPath,jsonpayload,true); + } + public NormalizedNodeContext transformDataObjectNNCFromString(String uriPath,String jsonpayload,boolean ispost) + { + return transformNNCFromString(uriPath,jsonpayload,ispost); + } + public NormalizedNodeContext transformNotficationNNCFromString(String uriPath,String jsonpayload) + { + return transformNNCFromString(uriPath,jsonpayload,true); + } +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangDataTransformNN2XMLServiceImpl.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangDataTransformNN2XMLServiceImpl.java new file mode 100644 index 0000000000..d147a803cc --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangDataTransformNN2XMLServiceImpl.java @@ -0,0 +1,253 @@ +package org.openecomp.mso.yangDecoder.transform.impl; + +import com.google.common.base.Charsets; +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import org.opendaylight.netconf.sal.restconf.impl.ControllerContext; +import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext; +import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils; +import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory; +import org.opendaylight.yangtools.yang.model.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.stream.XMLOutputFactory; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.AbstractMap.SimpleEntry; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static org.openecomp.mso.yangDecoder.transform.impl.JsonParserStream.getWrapSchemaNode; + +public class YangDataTransformNN2XMLServiceImpl { + private static final XMLOutputFactory XML_FACTORY; + private static final DocumentBuilderFactory BUILDERFACTORY; + static { + XML_FACTORY = XMLOutputFactory.newFactory(); + XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false); + final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + factory.setCoalescing(true); + factory.setIgnoringElementContentWhitespace(true); + factory.setIgnoringComments(true); + BUILDERFACTORY = factory; + } + BindingNormalizedNodeSerializer mappingservice; + SchemaContext schemaContext; + private static final Logger LOG = LoggerFactory.getLogger(YangDataTransformNN2XMLServiceImpl.class); + + public YangDataTransformNN2XMLServiceImpl(BindingNormalizedNodeSerializer mappingservice, SchemaContext context ) { + + this.schemaContext = context; + this.mappingservice=mappingservice; + } + + public String transformNNToString(NormalizedNode nn) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(YangOdlNNC2XMLImpl.getXMLHeader()); + new NormalizedNodeNavigator(new NormalizedNodePrinter(stringBuilder)).navigate(null, nn); + return stringBuilder.toString(); + } + + + public static DataSchemaNode getSchemaNodebyNs(final SchemaContext context, final String ns, final String childNodeName) { + for (Module module : context.getModules()) { + if (module.getNamespace().toString().equals(ns)) { + DataSchemaNode found = findChildNode(module.getChildNodes(), childNodeName); + Preconditions.checkState(found != null, "Unable to find %s", childNodeName); + return found; + } + } + throw new IllegalStateException("Unable to find child node " + childNodeName); + } + private static DataSchemaNode findChildNode(final Iterable<DataSchemaNode> children, final String name) { + List<DataNodeContainer> containers = Lists.newArrayList(); + + for (DataSchemaNode dataSchemaNode : children) { + if (dataSchemaNode.getQName().getLocalName().equals(name)) { + return dataSchemaNode; + } + if (dataSchemaNode instanceof DataNodeContainer) { + containers.add((DataNodeContainer) dataSchemaNode); + } else if (dataSchemaNode instanceof ChoiceSchemaNode) { + containers.addAll(((ChoiceSchemaNode) dataSchemaNode).getCases()); + } + } + + for (DataNodeContainer container : containers) { + DataSchemaNode retVal = findChildNode(container.getChildNodes(), name); + if (retVal != null) { + return retVal; + } + } + + return null; + } + public NormalizedNode transformNNFromString(String sxml) throws Exception { + InputStream in_nocode = new ByteArrayInputStream(sxml.getBytes(Charsets.UTF_8));//.getBytes("UTF-8") + //xml2nn + final Document docxml = readXmlToDocument(in_nocode); + Element element0 = docxml.getDocumentElement(); + String localname = element0.getNodeName(); + String ns = element0.getAttribute("xmlns"); + // final ContainerSchemaNode containerNodex = (ContainerSchemaNode)null; + final DataSchemaNode dsn=getSchemaNodebyNs(schemaContext, ns, localname); + //cn.getNodeType().getNamespace().toString(), cn.getNodeType().getLocalName()); + DomToNormalizedNodeParserFactory parserFactory =DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider(), schemaContext); + NormalizedNode parsed = null; + final List<Element> elements = Collections.singletonList(docxml.getDocumentElement()); + if (dsn instanceof ContainerSchemaNode) { + parsed= parserFactory.getContainerNodeParser().parse(elements, (ContainerSchemaNode)dsn); + }else if (dsn instanceof ListSchemaNode) { + final ListSchemaNode casted = (ListSchemaNode) dsn; + parsed=parserFactory.getMapEntryNodeParser().parse(elements, casted); + } + return parsed; + + } + + + + public NormalizedNode transformNotificationNNfromString(String sxml, final InstanceIdentifierContext<?> iicontext) throws Exception + { + SchemaNode schemaNode = getWrapSchemaNode(iicontext.getSchemaNode()); + InputStream in_nocode = new ByteArrayInputStream(sxml.getBytes(Charsets.UTF_8));//.getBytes("UTF-8") + //xml2nn + final Document docxml = readXmlToDocument(in_nocode); + Element element0 = docxml.getDocumentElement(); + String localname = element0.getNodeName(); + String ns = element0.getAttribute("xmlns"); + // final ContainerSchemaNode containerNodex = (ContainerSchemaNode)null; + // final DataSchemaNode dsn=(DataSchemaNode)schemaNode;/*getSchemaNodebyNs(schemaContext, ns, localname);*/ + //cn.getNodeType().getNamespace().toString(), cn.getNodeType().getLocalName()); + DomToNormalizedNodeParserFactory parserFactory =DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider(), schemaContext); + NormalizedNode parsed = null; + final List<Element> elements = Collections.singletonList(docxml.getDocumentElement()); + if (schemaNode instanceof ContainerSchemaNode) { + parsed= parserFactory.getContainerNodeParser().parse(elements, (ContainerSchemaNode)schemaNode); + }else if (schemaNode instanceof ListSchemaNode) { + final ListSchemaNode casted = (ListSchemaNode) schemaNode; + parsed=parserFactory.getMapEntryNodeParser().parse(elements, casted); + } + return parsed; + } + public NormalizedNode transformNotificationStringtoNN(String sxml,String notficationName) throws Exception { + final InstanceIdentifierContext<?> iicontext= ControllerContext.getInstance().toInstanceIdentifier(notficationName); + return transformNotificationNNfromString(sxml,iicontext); + } + public Map.Entry<DataSchemaNode, NormalizedNode> transformRpcNNEntryfromString(String sxml, final InstanceIdentifierContext<?> iirpccontext) throws Exception{ + InputStream in_nocode = new ByteArrayInputStream(sxml.getBytes(Charsets.UTF_8));//.getBytes("UTF-8") + //xml2nn + final Document docxml = readXmlToDocument(in_nocode); + Element element0 = docxml.getDocumentElement(); + String localname = element0.getNodeName(); + String ns = element0.getAttribute("xmlns"); + DataSchemaNode schemaNode; + final SchemaNode schemaNode0 = iirpccontext.getSchemaNode(); + boolean isInput = false; + if (schemaNode0 instanceof RpcDefinition) { + if (docxml.getDocumentElement().getLocalName().contains("output")) { + schemaNode = ((RpcDefinition) schemaNode0).getOutput(); + isInput = false; + } else { + schemaNode = ((RpcDefinition) schemaNode0).getInput(); + isInput = true; + } + + } else if (docxml instanceof DataSchemaNode) { + schemaNode = (DataSchemaNode) docxml; + } else { + throw new IllegalStateException("Unknow SchemaNode"); + } + + final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>(); + InstanceIdentifierContext<? extends SchemaNode> outIIContext; + // final ContainerSchemaNode containerNodex = (ContainerSchemaNode)null; + // final DataSchemaNode dsn=(DataSchemaNode)schemaNode;/*getSchemaNodebyNs(schemaContext, ns, localname);*/ + //cn.getNodeType().getNamespace().toString(), cn.getNodeType().getLocalName()); + DomToNormalizedNodeParserFactory parserFactory =DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider(), schemaContext); + NormalizedNode parsed = null; + final List<Element> elements = Collections.singletonList(docxml.getDocumentElement()); + if (schemaNode instanceof ContainerSchemaNode) { + parsed= parserFactory.getContainerNodeParser().parse(elements, (ContainerSchemaNode)schemaNode); + }else if (schemaNode instanceof ListSchemaNode) { + final ListSchemaNode casted = (ListSchemaNode) schemaNode; + parsed=parserFactory.getMapEntryNodeParser().parse(elements, casted); + } + return new SimpleEntry<DataSchemaNode, NormalizedNode>(schemaNode,parsed); + } + public NormalizedNode transformRpcNNfromString(String sxml, final InstanceIdentifierContext<?> iirpccontext) throws Exception{ + + InputStream in_nocode = new ByteArrayInputStream(sxml.getBytes(Charsets.UTF_8));//.getBytes("UTF-8") + //xml2nn + final Document docxml = readXmlToDocument(in_nocode); + Element element0 = docxml.getDocumentElement(); + String localname = element0.getNodeName(); + String ns = element0.getAttribute("xmlns"); + DataSchemaNode schemaNode; + final SchemaNode schemaNode0 = iirpccontext.getSchemaNode(); + boolean isInput = false; + if (schemaNode0 instanceof RpcDefinition) { + if (docxml.getDocumentElement().getLocalName().contains("output")) { + schemaNode = ((RpcDefinition) schemaNode0).getOutput(); + isInput = false; + } else { + schemaNode = ((RpcDefinition) schemaNode0).getInput(); + isInput = true; + } + + } else if (docxml instanceof DataSchemaNode) { + schemaNode = (DataSchemaNode) docxml; + } else { + throw new IllegalStateException("Unknow SchemaNode"); + } + + final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>(); + InstanceIdentifierContext<? extends SchemaNode> outIIContext; + // final ContainerSchemaNode containerNodex = (ContainerSchemaNode)null; + // final DataSchemaNode dsn=(DataSchemaNode)schemaNode;/*getSchemaNodebyNs(schemaContext, ns, localname);*/ + //cn.getNodeType().getNamespace().toString(), cn.getNodeType().getLocalName()); + DomToNormalizedNodeParserFactory parserFactory =DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider(), schemaContext); + NormalizedNode parsed = null; + final List<Element> elements = Collections.singletonList(docxml.getDocumentElement()); + if (schemaNode instanceof ContainerSchemaNode) { + parsed= parserFactory.getContainerNodeParser().parse(elements, (ContainerSchemaNode)schemaNode); + }else if (schemaNode instanceof ListSchemaNode) { + final ListSchemaNode casted = (ListSchemaNode) schemaNode; + parsed=parserFactory.getMapEntryNodeParser().parse(elements, casted); + } + return parsed; + } + public NormalizedNode transformRpcNNfromString(String sxml, String rpcName) throws Exception { + final InstanceIdentifierContext<?> iicontext= ControllerContext.getInstance().toInstanceIdentifier(rpcName); + return this.transformRpcNNfromString(sxml,iicontext); + + } + public static Document readXmlToDocument(final InputStream xmlContent) throws IOException, SAXException { + final DocumentBuilder dBuilder; + try { + dBuilder = BUILDERFACTORY.newDocumentBuilder(); + } catch (final ParserConfigurationException e) { + throw new RuntimeException("Failed to parse XML document", e); + } + final Document doc = dBuilder.parse(xmlContent); + + doc.getDocumentElement().normalize(); + return doc; + } + +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangOdlNN2XMLImpl.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangOdlNN2XMLImpl.java new file mode 100644 index 0000000000..96cd840d44 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangOdlNN2XMLImpl.java @@ -0,0 +1,106 @@ +package org.openecomp.mso.yangDecoder.transform.impl; + +import org.opendaylight.netconf.sal.restconf.impl.ControllerContext; +import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter; +import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter; +import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter; +import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils; +import org.opendaylight.yangtools.yang.model.api.SchemaContext; +import org.opendaylight.yangtools.yang.model.api.SchemaNode; +import org.opendaylight.yangtools.yang.model.api.SchemaPath; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; +import javax.xml.transform.*; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.IOException; +import java.io.StringWriter; + +/** + * Created by Administrator on 2017/3/21. + */ +public class YangOdlNN2XMLImpl { + private static final XMLOutputFactory XML_FACTORY; + static { + XML_FACTORY = XMLOutputFactory.newFactory(); + XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false); + } + SchemaContext schemaContext; + public YangOdlNN2XMLImpl(SchemaContext schemaContext){ + this.schemaContext=schemaContext; + } + //general for contain/listitem/rpc/notification + public String yangNNtoXML(String uriPath,NormalizedNode nn) throws Exception { + final InstanceIdentifierContext<?> iicontext = ControllerContext.getInstance().toInstanceIdentifier(uriPath); + SchemaNode snode = YangDataTransformJava2NNServiceImpl.findSchemaNode(iicontext, nn.getNodeType().getLocalName()); + String strx = snode.toString(); + SchemaPath path = snode.getPath(); + int it=uriPath.lastIndexOf("/"); + if (strx.contains("container ")&&(it<0)) { + // path = SchemaPath.create(true); + } + String sxml =writeNormalizedNodetoXml(nn,path,schemaContext); + return sxml; + } + public static String writeNormalizedNodetoXml(final NormalizedNode<?, ?> cn, + final SchemaPath schemaPath, final SchemaContext schemaContext) + { + + String serializationResultXMLString = null; + try { + //nn2xml + final Document doc = XmlDocumentUtils.getDocument(); + final DOMResult serializationResult = new DOMResult(doc); + writeNormalizedNode(cn,serializationResult,schemaPath, schemaContext); + serializationResultXMLString = toString(serializationResult.getNode()); + } catch (IOException |XMLStreamException e) { + e.printStackTrace(); + } + return serializationResultXMLString; + } + public static void writeNormalizedNode(final NormalizedNode<?, ?> normalized, final DOMResult result, + final SchemaPath schemaPath, final SchemaContext context) throws IOException, XMLStreamException { + NormalizedNodeWriter normalizedNodeWriter = null; + NormalizedNodeStreamWriter normalizedNodeStreamWriter = null; + XMLStreamWriter writer = null; + try { + writer = XML_FACTORY.createXMLStreamWriter(result); + normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath); + normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter); + + normalizedNodeWriter.write(normalized); + + normalizedNodeWriter.flush(); + } finally { + if (normalizedNodeWriter != null) { + normalizedNodeWriter.close(); + } + if (normalizedNodeStreamWriter != null) { + normalizedNodeStreamWriter.close(); + } + if (writer != null) { + writer.close(); + } + } + } + public static String toString(final Node xml) { + try { + final Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); + final StreamResult result = new StreamResult(new StringWriter()); + final DOMSource source = new DOMSource(xml); + transformer.transform(source, result); + return result.getWriter().toString(); + } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) { + throw new RuntimeException("Unable to serialize xml element " + xml, e); + } + } +} diff --git a/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangOdlNNC2XMLImpl.java b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangOdlNNC2XMLImpl.java new file mode 100644 index 0000000000..8db6cd954c --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/yangDecoder/transform/impl/YangOdlNNC2XMLImpl.java @@ -0,0 +1,64 @@ +package org.openecomp.mso.yangDecoder.transform.impl; + +import com.google.common.base.Charsets; +import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeXmlBodyWriter; +import org.opendaylight.netconf.sal.restconf.impl.ControllerContext; +import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext; +import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext; +import org.opendaylight.netconf.sal.restconf.impl.WriterParameters; + +import javax.ws.rs.core.MediaType; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Field; + +public class YangOdlNNC2XMLImpl { + final static MediaType mediaType=getMediaType(); + static protected MediaType getMediaType() { + return new MediaType(MediaType.APPLICATION_XML, null); + } + static Field requestField=getprettyPrintField(); + + private static Field getprettyPrintField( ) + { + Field rf=null; + try { + rf = WriterParameters.class.getDeclaredField("prettyPrint"); + rf.setAccessible(true); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return rf; + } + public static String getXMLHeader() + { + return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"+NormalizedNodePrinter.getEndl(); + } + public static String toXML(final NormalizedNodeContext normalizedNodeContext) throws Exception + { + final NormalizedNodeXmlBodyWriter xmlBodyWriter = new NormalizedNodeXmlBodyWriter(); + final OutputStream output = new ByteArrayOutputStream(); + requestField.set(normalizedNodeContext.getWriterParameters(), true); + output.write(getXMLHeader().getBytes(Charsets.UTF_8)); + xmlBodyWriter.writeTo(normalizedNodeContext, null, null, null, + mediaType, null, output); + final String outputXML = output.toString(); + return outputXML; + } + + public static NormalizedNodeContext fromXML(String uriPath,final String xmlpayload,boolean ispost) throws Exception + { + final InstanceIdentifierContext<?> iicontext = ControllerContext.getInstance().toInstanceIdentifier(uriPath); + InputStream inputStream = new ByteArrayInputStream(xmlpayload.getBytes(Charsets.UTF_8)); + XmlNormalizedNodeBodyReaderUmeImpl xmlBodyReader = new XmlNormalizedNodeBodyReaderUmeImpl(); + xmlBodyReader.Set(iicontext, ispost); +// final NormalizedNodeContext returnValue = xmlBodyReader.readFrom(iicontext, inputStream); + final NormalizedNodeContext returnValue = xmlBodyReader.readFrom(null, + null, null, mediaType, null, inputStream); + return returnValue; + } + +} |