Consolidation of the GNPy module
[transportpce.git] / pce / src / main / java / org / opendaylight / transportpce / pce / gnpy / ServiceDataStoreOperationsImpl.java
1 /*
2  * Copyright © 2018 Orange, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.transportpce.pce.gnpy;
10
11 import com.google.common.base.Function;
12 import com.google.common.collect.FluentIterable;
13
14 import java.io.BufferedWriter;
15 import java.io.FileWriter;
16 import java.io.IOException;
17 import java.io.StringWriter;
18 import java.io.Writer;
19 import java.util.Collections;
20 import java.util.Optional;
21
22 import org.opendaylight.mdsal.binding.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
23 import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
24 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
25 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
26 import org.opendaylight.transportpce.common.DataStoreContext;
27 import org.opendaylight.transportpce.common.converter.XMLDataObjectConverter;
28 import org.opendaylight.transportpce.common.network.NetworkTransactionService;
29 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.OrgOpenroadmDevice;
30 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
31 import org.opendaylight.yangtools.yang.binding.DataObject;
32 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
33 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
38 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
39 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
40 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
41 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
42 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
43 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 public class ServiceDataStoreOperationsImpl implements ServiceDataStoreOperations {
49
50     private static final Logger LOG = LoggerFactory.getLogger(ServiceDataStoreOperationsImpl.class);
51
52     public ServiceDataStoreOperationsImpl(NetworkTransactionService networkTransactionService) {
53     }
54
55     public void createXMLFromDevice(DataStoreContext dataStoreContextUtil, OrgOpenroadmDevice device, String output)
56         throws GnpyException {
57
58         if (device != null) {
59             Optional<NormalizedNode<?, ?>> transformIntoNormalizedNode = null;
60             XMLDataObjectConverter cwDsU = XMLDataObjectConverter.createWithDataStoreUtil(dataStoreContextUtil);
61             transformIntoNormalizedNode = cwDsU.toNormalizedNodes(device, OrgOpenroadmDevice.class);
62             if (!transformIntoNormalizedNode.isPresent()) {
63                 throw new GnpyException(String.format(
64                     "In ServiceDataStoreOperationsImpl: Cannot transform the device %s into normalized nodes",
65                     device.toString()));
66             }
67             Writer writerFromDataObject =
68                 cwDsU.writerFromDataObject(device, OrgOpenroadmDevice.class,cwDsU.dataContainer());
69             try {
70                 BufferedWriter writer = new BufferedWriter(new FileWriter(output));
71                 writer.write(writerFromDataObject.toString());
72                 writer.close();
73             } catch (IOException e) {
74                 throw new GnpyException(
75                     String.format("In ServiceDataStoreOperationsImpl : Bufferwriter error"),e);
76             }
77             LOG.debug("GNPy: device xml : {}", writerFromDataObject.toString());
78         }
79     }
80
81     public String createJsonStringFromDataObject(final InstanceIdentifier<?> id, DataObject object)
82         throws GnpyException, Exception {
83
84         final SchemaPath scPath = SchemaPath
85                 .create(FluentIterable.from(id.getPathArguments()).transform(new Function<PathArgument, QName>() {
86                     @Override
87                     public QName apply(final PathArgument input) {
88                         return BindingReflections.findQName(input.getType());
89                     }
90                 }), true);
91         final Writer writer = new StringWriter();
92         NormalizedNodeStreamWriter domWriter;
93
94         try {
95             // Prepare the variables
96             final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
97             Iterable<? extends YangModuleInfo> moduleInfos = Collections
98                     .singleton(BindingReflections.getModuleInfo(object.getClass()));
99             moduleContext.addModuleInfos(moduleInfos);
100             SchemaContext schemaContext = moduleContext.tryToCreateSchemaContext().get();
101             BindingRuntimeContext bindingContext;
102             bindingContext = BindingRuntimeContext.create(moduleContext, schemaContext);
103             final BindingNormalizedNodeCodecRegistry codecRegistry =
104                 new BindingNormalizedNodeCodecRegistry(bindingContext);
105
106             /*
107              * This function needs : - context - scPath.getParent() -
108              * scPath.getLastComponent().getNamespace(), -
109              * JsonWriterFactory.createJsonWriter(writer)
110              */
111             domWriter = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
112                 JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.createSimple(schemaContext),
113                 scPath.getParent(), scPath.getLastComponent().getNamespace(),
114                 JsonWriterFactory.createJsonWriter(writer, 2));
115             // The write part
116             final BindingStreamEventWriter bindingWriter = codecRegistry.newWriter(id, domWriter);
117             codecRegistry.getSerializer(id.getTargetType()).serialize(object, bindingWriter);
118             domWriter.close();
119             writer.close();
120         } catch (IOException | YangSyntaxErrorException | ReactorException e) {
121             throw new GnpyException("In ServiceDataStoreOperationsImpl: exception during json file creation",e);
122         }
123         return writer.toString();
124     }
125
126     // Write the json as a string in a file
127     public void writeStringFile(String jsonString, String fileName) throws GnpyException {
128         try {
129             FileWriter file = new FileWriter(fileName);
130             file.write(jsonString);
131             file.close();
132         } catch (IOException e) {
133             throw new GnpyException("In ServiceDataStoreOperationsImpl : exception during file writing",e);
134         }
135     }
136 }