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