Fix NPE in toJsonString()
[ccsdk/sli/core.git] / sli / common / src / main / java / org / onap / ccsdk / sli / core / sli / SvcLogicLoader.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : SDN-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              reserved.
7  * ================================================================================
8  * Modifications Copyright (C) 2018 IBM.
9  * ================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  * 
14  *      http://www.apache.org/licenses/LICENSE-2.0
15  * 
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.ccsdk.sli.core.sli;
25
26 import java.io.BufferedReader;
27 import java.io.File;
28 import java.io.IOException;
29 import java.nio.charset.StandardCharsets;
30 import java.nio.file.Files;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.util.ArrayList;
34 import java.util.Iterator;
35 import java.util.LinkedList;
36 import java.util.List;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public class SvcLogicLoader {
41     private static final Logger LOGGER = LoggerFactory.getLogger(SvcLogicLoader.class);
42     protected SvcLogicStore store;
43     protected String directoryRoot;
44     protected SvcLogicParser parser;
45
46     public SvcLogicLoader(String directoryRoot, SvcLogicStore store) {
47         this.store = store;
48         this.directoryRoot = directoryRoot;
49         this.parser = new SvcLogicParser();
50     }
51     
52     public SvcLogicLoader(String directoryRoot, String propFile) {
53         this.store = SvcLogicParser.getStore(propFile);
54         this.directoryRoot = directoryRoot;
55         this.parser = new SvcLogicParser();
56     }
57
58     public void loadAndActivate() throws IOException {
59         SvcLogicCrawler slc = new SvcLogicCrawler();
60         Files.walkFileTree(Paths.get(directoryRoot), slc);
61         loadGraphs(slc.getGraphPaths(), directoryRoot);
62         List<ActivationEntry> activationEntries = processActivationFiles(slc.getActivationPaths());
63         activateGraphs(activationEntries);
64     }
65
66     protected List<ActivationEntry> processActivationFiles(List<Path> activationPaths) {
67         List<ActivationEntry> activationEntries = new ArrayList<>();
68         for (Path activationFile : activationPaths) {
69             activationEntries.addAll(getActivationEntries(activationFile));
70         }
71         return activationEntries;
72     }
73
74     protected void activateGraphs(List<ActivationEntry> activationEntries) {
75         for (ActivationEntry entry : activationEntries) {
76             try {
77                 if (store.hasGraph(entry.module, entry.rpc, entry.version, entry.mode)) {
78                     LOGGER.info("Activating SvcLogicGraph [module=" + entry.module + ", rpc=" + entry.rpc + ", mode="
79                             + entry.mode + ", version=" + entry.version + "]");
80                     store.activate(entry.module, entry.rpc, entry.version, entry.mode);
81                 } else {
82                     LOGGER.error("hasGraph returned false for " + entry.toString());
83                 }
84             } catch (SvcLogicException e) {
85                 LOGGER.error("Failed to call hasGraph for " + entry.toString(), e);
86             }
87         }
88     }
89
90     protected List<ActivationEntry> getActivationEntries(Path activationFilePath) {
91         List<ActivationEntry> activationEntries = new ArrayList<>();
92         int lineNumber = 1;
93         try (BufferedReader br = Files.newBufferedReader(activationFilePath, StandardCharsets.US_ASCII)) {
94             String fileRead = br.readLine();
95             while (fileRead != null) {
96                 String[] fields = fileRead.split("\\s");
97                 if (fields.length == 4) {
98                     activationEntries.add(parseActivationEntry(fields));
99                 } else {
100                     LOGGER.error("Activation entry [" + fileRead + "] is declared at line number " + lineNumber
101                             + " in the file " + activationFilePath + " and is invalid.");
102                 }
103                 fileRead = br.readLine();
104                 lineNumber++;
105             }
106             return activationEntries;
107         } catch (IOException ioe) {
108             LOGGER.error("Couldn't read the activation file at " + activationFilePath, ioe);
109             return new ArrayList<>();
110         }
111     }
112
113     protected void loadGraphs(List<Path> graphPaths, String directoryRoot) {
114         for (Path graphPath : graphPaths) {
115             try {
116                 saveGraph(graphPath.toString());
117             } catch (Exception e) {
118                 LOGGER.error("Couldn't load graph at " + graphPath, e);
119             }
120         }
121     }
122
123     protected void saveGraph(String xmlFile) throws SvcLogicException {
124         File f = new File(xmlFile);
125         if (!f.canRead()) {
126             throw new ConfigurationException("Cannot read xml file (" + xmlFile + ")");
127         }
128
129         LinkedList<SvcLogicGraph> graphs = null;
130
131         try {
132             graphs = parser.parse(xmlFile);
133         } catch (Exception e) {
134             throw new SvcLogicException(e.getMessage(), e);
135         }
136
137         if (graphs == null) {
138             throw new SvcLogicException("Could not parse " + xmlFile);
139         }
140
141         for (Iterator<SvcLogicGraph> iter = graphs.iterator(); iter.hasNext();) {
142             SvcLogicGraph graph = iter.next();
143             try {
144                 LOGGER.info("Saving " + graph.toString() + " to database");
145                 store.store(graph);
146             } catch (Exception e) {
147                 throw new SvcLogicException(e.getMessage(), e);
148             }
149         }
150     }
151
152     protected ActivationEntry parseActivationEntry(String[] fileInput) {
153         return new ActivationEntry(fileInput[0], fileInput[1], fileInput[2], fileInput[3]);
154     }
155
156     protected String getValue(String raw, String attributeName) {
157         raw = raw.substring(attributeName.length() + 1);
158         if (raw.contains(">")) {
159             raw = raw.substring(0, raw.lastIndexOf('>'));
160         }
161         if (raw.endsWith("'")) {
162             raw = raw.substring(0, raw.lastIndexOf('\''));
163         }
164         if (raw.endsWith("\"")) {
165             raw = raw.substring(0, raw.lastIndexOf('"'));
166         }
167         return raw;
168     }
169     
170     public void bulkActivate() {
171         Path activationFile = Paths.get(directoryRoot);
172         List<Path> pathList = new ArrayList<>(1);
173         pathList.add(activationFile);
174         List<ActivationEntry> activationEntries = processActivationFiles(pathList);
175         activateGraphs(activationEntries);
176     }
177
178 }