Added oparent to sdc main
[sdc.git] / openecomp-be / tools / zusammen-tools / src / main / java / org / openecomp / core / tools / exportinfo / ExportSerializer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 European Support Limited. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.core.tools.exportinfo;
21
22 import static org.openecomp.core.tools.exportinfo.ExportDataCommand.NULL_REPRESENTATION;
23 import static org.openecomp.core.tools.importinfo.ImportSingleTable.dataTypesMap;
24
25 import com.datastax.driver.core.DataType.Name;
26 import com.datastax.driver.core.ResultSet;
27 import com.datastax.driver.core.Row;
28 import com.google.gson.JsonElement;
29 import com.google.gson.JsonParser;
30 import com.google.gson.JsonSyntaxException;
31 import java.io.File;
32 import java.io.IOException;
33 import java.nio.ByteBuffer;
34 import java.nio.file.Paths;
35 import java.util.*;
36 import java.util.stream.Collectors;
37 import org.apache.commons.lang3.StringUtils;
38 import org.codehaus.jackson.map.ObjectMapper;
39 import org.openecomp.core.tools.importinfo.ImportProperties;
40 import org.openecomp.core.tools.model.ColumnDefinition;
41 import org.openecomp.core.tools.model.TableData;
42 import org.openecomp.core.tools.util.Utils;
43 import org.openecomp.sdc.logging.api.Logger;
44 import org.openecomp.sdc.logging.api.LoggerFactory;
45
46 public class ExportSerializer {
47
48     private static final Logger logger = LoggerFactory.getLogger(ExportSerializer.class);
49     private static final String ELEMENT_TABLE_NAME = "element";
50     private static final String ELEMENT_INFO_COLUMN_NAME = "info";
51
52
53     public void serializeResult(final ResultSet resultSet, final Set<String> filteredItems, final String filteredColumn, Set<String> vlms) {
54         try {
55             TableData tableData = new TableData();
56             tableData.definitions = resultSet.getColumnDefinitions().asList().stream().map(ColumnDefinition::new).collect(Collectors.toList());
57             String table = tableData.definitions.iterator().next().getTable();
58             boolean isElementTable = table.equals(ELEMENT_TABLE_NAME);
59             Iterator<Row> iterator = resultSet.iterator();
60             iterator.forEachRemaining(row -> {
61                 if (!filteredItems.contains(row.getString(filteredColumn))) {
62                     return;
63                 }
64                 List<String> rowData = new ArrayList<>();
65                 for (int i = 0; i < tableData.definitions.size(); i++) {
66                     ColumnDefinition columnDefinition = tableData.definitions.get(i);
67                     Name name = dataTypesMap.get(columnDefinition.getType());
68                     boolean checkForVLM = isElementTable && columnDefinition.getName().equals(ELEMENT_INFO_COLUMN_NAME);
69                     Object data = convertByType(vlms, row, i, name, checkForVLM);
70                     rowData.add(data.toString());
71                 }
72                 tableData.rows.add(rowData);
73             });
74             ObjectMapper objectMapper = new ObjectMapper();
75             String fileName = ImportProperties.ROOT_DIRECTORY + File.separator + table + "_" + System.currentTimeMillis() + ".json";
76             objectMapper.writeValue(Paths.get(fileName).toFile(), tableData);
77             Utils.printMessage(logger, "File exported is :" + fileName);
78
79         } catch (IOException e) {
80             Utils.logError(logger, e);
81             System.exit(1);
82         }
83     }
84
85     private Object convertByType(Set<String> vlms, Row row, int i, Name name, boolean checkForVLM) {
86         Object data;
87         switch (name) {
88             case VARCHAR:
89             case TEXT:
90             case ASCII:
91                 String string = row.getString(i);
92                 if (string == null) {
93                     string = NULL_REPRESENTATION;
94                 }
95                 if (checkForVLM && vlms != null) {
96                     String vlm = extractVlm(string);
97                     if (vlm != null) {
98                         vlms.add(vlm);
99                     }
100                 }
101                 data = Base64.getEncoder().encodeToString(string.getBytes());
102                 break;
103             case BLOB:
104                 ByteBuffer bytes = row.getBytes(i);
105                 if (bytes == null) {
106                     bytes = ByteBuffer.wrap("".getBytes());
107                 }
108                 data = Base64.getEncoder().encodeToString(bytes.array());
109                 break;
110             case TIMESTAMP:
111                 Date rowDate = row.getTimestamp(i);
112                 if (rowDate != null) {
113                     data = rowDate.getTime();
114                 } else {
115                     data = "";
116                 }
117                 break;
118             case BOOLEAN:
119                 data = row.getBool(i);
120                 break;
121             case COUNTER:
122                 data = row.getLong(i);
123                 break;
124             case INT:
125                 data = row.getInt(i);
126                 break;
127             case FLOAT:
128                 data = row.getFloat(i);
129                 break;
130             case SET:
131                 Set<Object> set = (Set<Object>) row.getObject(i);
132                 Object joined = set.stream().map(Object::toString).collect(Collectors.joining(ExportDataCommand.JOIN_DELIMITER));
133                 data = Base64.getEncoder().encodeToString(joined.toString().getBytes());
134                 break;
135             case MAP:
136                 Map<Object, Object> map = (Map<Object, Object>) row.getObject(i);
137                 Set<Map.Entry<Object, Object>> entrySet = map.entrySet();
138                 Object mapAsString = entrySet.parallelStream().map(entry -> entry.getKey().toString() + ExportDataCommand.MAP_DELIMITER + entry.getValue().toString())
139                         .collect(Collectors.joining(ExportDataCommand.JOIN_DELIMITER));
140                 data = Base64.getEncoder().encodeToString(mapAsString.toString().getBytes());
141                 break;
142             default:
143                 throw new UnsupportedOperationException("Name is not supported :" + name);
144         }
145         return data;
146     }
147
148     protected String extractVlm(String inJson) {
149         if (StringUtils.isEmpty(inJson.trim())) {
150             return null;
151         }
152         JsonElement root;
153         try {
154             root = new JsonParser().parse(inJson);
155         } catch (JsonSyntaxException e) {
156             Utils.logError(logger, "Failed to parse json " + inJson, e);
157             return null;
158         }
159         if (root == null) {
160             return null;
161         }
162         JsonElement properties = root.getAsJsonObject().get("properties");
163         if (properties == null) {
164             return null;
165         }
166         JsonElement vendorId = properties.getAsJsonObject().get("vendorId");
167         if (vendorId == null) {
168             return null;
169         }
170         return vendorId.getAsString();
171     }
172 }