596c7025b67e28228b05ce12369872d0402392fe
[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 //false positive in SpotBug -> cannot be used with FluentIterable...
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.nio.charset.StandardCharsets;
20 import java.util.Collections;
21 import java.util.Optional;
22
23 import org.opendaylight.mdsal.binding.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
24 import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
25 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
26 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
27 import org.opendaylight.transportpce.common.DataStoreContext;
28 import org.opendaylight.transportpce.common.converter.XMLDataObjectConverter;
29 import org.opendaylight.transportpce.common.network.NetworkTransactionService;
30 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.OrgOpenroadmDevice;
31 import org.opendaylight.yangtools.yang.binding.DataObject;
32 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
33 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
36 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
37 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
38 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 public class ServiceDataStoreOperationsImpl implements ServiceDataStoreOperations {
45
46     private static final Logger LOG = LoggerFactory.getLogger(ServiceDataStoreOperationsImpl.class);
47
48     public ServiceDataStoreOperationsImpl(NetworkTransactionService networkTransactionService) {
49     }
50
51     @Override
52     public void createXMLFromDevice(DataStoreContext dataStoreContextUtil, OrgOpenroadmDevice device, String output)
53         throws GnpyException {
54
55         if (device != null) {
56             Optional<NormalizedNode<?, ?>> transformIntoNormalizedNode = null;
57             XMLDataObjectConverter cwDsU = XMLDataObjectConverter.createWithDataStoreUtil(dataStoreContextUtil);
58             transformIntoNormalizedNode = cwDsU.toNormalizedNodes(device, OrgOpenroadmDevice.class);
59             if (!transformIntoNormalizedNode.isPresent()) {
60                 throw new GnpyException(String.format(
61                     "In ServiceDataStoreOperationsImpl: Cannot transform the device %s into normalized nodes",
62                     device.toString()));
63             }
64             Writer writerFromDataObject =
65                 cwDsU.writerFromDataObject(device, OrgOpenroadmDevice.class,cwDsU.dataContainer());
66             try (BufferedWriter writer = new BufferedWriter(new FileWriter(output,StandardCharsets.UTF_8))) {
67                 writer.write(writerFromDataObject.toString());
68             } catch (IOException e) {
69                 throw new GnpyException(
70                     String.format("In ServiceDataStoreOperationsImpl : Bufferwriter error %s",e));
71             }
72             LOG.debug("GNPy: device xml : {}", writerFromDataObject);
73         }
74     }
75
76     @Override
77     public String createJsonStringFromDataObject(final InstanceIdentifier<?> id, DataObject object)
78         throws GnpyException, Exception {
79
80         final SchemaPath scPath = SchemaPath.create(FluentIterable
81                 .from(id.getPathArguments())
82                 .transform(input -> BindingReflections.findQName(input.getType())), true);
83
84         // Prepare the variables
85         final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
86         Iterable<? extends YangModuleInfo> moduleInfos = Collections
87                 .singleton(BindingReflections.getModuleInfo(object.getClass()));
88         moduleContext.addModuleInfos(moduleInfos);
89         SchemaContext schemaContext = moduleContext.tryToCreateSchemaContext().get();
90         BindingRuntimeContext bindingContext;
91         bindingContext = BindingRuntimeContext.create(moduleContext, schemaContext);
92         final BindingNormalizedNodeCodecRegistry codecRegistry =
93             new BindingNormalizedNodeCodecRegistry(bindingContext);
94
95         /*
96          * This function needs : - context - scPath.getParent() -
97          * scPath.getLastComponent().getNamespace(), -
98          * JsonWriterFactory.createJsonWriter(writer)
99          */
100         final Writer writer = new StringWriter();
101
102         try (NormalizedNodeStreamWriter domWriter = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
103                 JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.createSimple(schemaContext),
104                 scPath.getParent(), scPath.getLastComponent().getNamespace(),
105                 JsonWriterFactory.createJsonWriter(writer, 2));) {
106             // The write part
107             codecRegistry.getSerializer(id.getTargetType()).serialize(object, codecRegistry.newWriter(id, domWriter));
108         } catch (IOException e) {
109             throw new GnpyException("In ServiceDataStoreOperationsImpl: exception during json file creation",e);
110         }
111         return writer.toString();
112     }
113
114     // Write the json as a string in a file
115     @Override
116     public void writeStringFile(String jsonString, String fileName) throws GnpyException {
117         try (FileWriter file = new FileWriter(fileName,StandardCharsets.UTF_8)) {
118             file.write(jsonString);
119         } catch (IOException e) {
120             throw new GnpyException("In ServiceDataStoreOperationsImpl : exception during file writing",e);
121         }
122     }
123 }