push addional code
[sdc.git] / openecomp-be / lib / openecomp-sdc-versioning-lib / openecomp-sdc-versioning-core / src / main / java / org / openecomp / sdc / versioning / dao / impl / VersionableEntityDaoCassandraImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. 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
21 package org.openecomp.sdc.versioning.dao.impl;
22
23 import com.datastax.driver.core.ColumnDefinitions;
24 import com.datastax.driver.core.ResultSet;
25 import com.datastax.driver.core.Row;
26 import com.datastax.driver.mapping.UDTMapper;
27 import org.openecomp.core.nosqldb.api.NoSqlDb;
28 import org.openecomp.core.nosqldb.factory.NoSqlDbFactory;
29 import org.openecomp.core.util.UniqueValueUtil;
30 import org.openecomp.core.utilities.CommonMethods;
31 import org.openecomp.sdc.versioning.dao.VersionableEntityDao;
32 import org.openecomp.sdc.versioning.dao.types.Version;
33 import org.openecomp.sdc.versioning.types.UniqueValueMetadata;
34 import org.openecomp.sdc.versioning.types.VersionableEntityMetadata;
35
36 import org.slf4j.LoggerFactory;
37
38 import java.util.ArrayList;
39 import java.util.HashMap;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.function.Function;
43 import java.util.stream.Collectors;
44
45 class VersionableEntityDaoCassandraImpl implements VersionableEntityDao {
46
47   private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface();
48   private static org.slf4j.Logger Logger =
49       LoggerFactory.getLogger(VersionableEntityDaoCassandraImpl.class);
50   private static UDTMapper<Version> versionMapper =
51       noSqlDb.getMappingManager().udtMapper(Version.class);
52
53   private static String commaSeparatedQuestionMarks(int size) {
54     StringBuilder sb = new StringBuilder(size * 2 - 1);
55     for (int i = 0; i < size; i++) {
56       if (i > 0) {
57         sb.append(',');
58       }
59       sb.append('?');
60     }
61     return sb.toString();
62
63   }
64
65   @Override
66   public void initVersion(VersionableEntityMetadata metadata, String entityId, Version baseVersion,
67                           Version newVersion) {
68     ResultSet rows = loadVersionRows(metadata, entityId, baseVersion);
69     List<String> columnNames =
70         rows.getColumnDefinitions().asList().stream().map(ColumnDefinitions.Definition::getName)
71             .collect(Collectors.toList());
72
73     String insertCql = String.format("insert into %s (%s) values (%s)", metadata.getName(),
74         CommonMethods.listToSeparatedString(columnNames, ','),
75         commaSeparatedQuestionMarks(columnNames.size()));
76     Logger.debug("insertCql", insertCql);
77
78     for (Row row : rows) {
79       List<Object> columnValues = new ArrayList<>();
80       Map<String, Object> columnNameToValue = new HashMap<>();
81
82       for (String columnName : columnNames) {
83         if (metadata.getVersionIdentifierName().equals(columnName)) {
84           columnValues.add(versionMapper.toUDT(newVersion));
85           columnNameToValue.put(columnName, newVersion.toString());
86         } else {
87           Object value = row.getObject(columnName);
88           columnValues.add(value);
89           columnNameToValue.put(columnName, value);
90         }
91       }
92
93       initRowUniqueValues(metadata.getUniqueValuesMetadata(), columnNameToValue);
94
95       noSqlDb.execute(insertCql, columnValues.toArray());
96     }
97   }
98
99   private ResultSet loadVersionRows(VersionableEntityMetadata metadata, String entityId,
100                                     Version version) {
101     String selectCql = String.format("select * from %s where %s=? and %s=?", metadata.getName(),
102         metadata.getIdentifierName(), metadata.getVersionIdentifierName());
103     Logger.debug("selectCql", selectCql);
104     Logger.debug("entityId", entityId);
105     Logger.debug("version", version);
106
107     return noSqlDb.execute(selectCql, entityId, versionMapper.toUDT(version));
108   }
109
110   @Override
111   public void deleteVersion(VersionableEntityMetadata metadata, String entityId,
112                             Version versionToDelete) {
113     deleteRowsUniqueValues(metadata, entityId, versionToDelete);
114
115     String deleteCql = String.format("delete from %s where %s=? and %s=?", metadata.getName(),
116         metadata.getIdentifierName(), metadata.getVersionIdentifierName());
117     noSqlDb.execute(deleteCql, entityId, versionMapper.toUDT(versionToDelete));
118   }
119
120   private void initRowUniqueValues(List<UniqueValueMetadata> metadata,
121                                    Map<String, Object> columnNameToValue) {
122     for (UniqueValueMetadata uniqueMetadata : metadata) {
123       List<String> uniqueValueCombination = uniqueMetadata.getUniqueConstraintIdentifiers().stream()
124           .map(colName -> (String) columnNameToValue.get(colName)).collect(Collectors.toList());
125       UniqueValueUtil.createUniqueValue(uniqueMetadata.getType(),
126           uniqueValueCombination.toArray(new String[uniqueValueCombination.size()]));
127     }
128   }
129
130   private void deleteRowUniqueValues(List<UniqueValueMetadata> metadata,
131                                      Map<String, Object> columnNameToValue) {
132     for (UniqueValueMetadata uniqueMetadata : metadata) {
133       List<String> uniqueValueCombination = uniqueMetadata.getUniqueConstraintIdentifiers().stream()
134           .map(colName -> (String) columnNameToValue.get(colName)).collect(Collectors.toList());
135       UniqueValueUtil.deleteUniqueValue(uniqueMetadata.getType(),
136           uniqueValueCombination.toArray(new String[uniqueValueCombination.size()]));
137     }
138   }
139
140   private void deleteRowsUniqueValues(VersionableEntityMetadata metadata, String entityId,
141                                       Version version) {
142     if (metadata.getUniqueValuesMetadata().isEmpty()) {
143       return;
144     }
145     ResultSet rows = loadVersionRows(metadata, entityId, version);
146     List<String> columnNames =
147         rows.getColumnDefinitions().asList().stream().map(ColumnDefinitions.Definition::getName)
148             .collect(Collectors.toList());
149
150     for (Row row : rows) {
151       Map<String, Object> columnNameToValue =
152           columnNames.stream().filter(name -> row.getObject(name) != null).collect(Collectors
153               .toMap(Function.identity(),
154                   columnName -> metadata.getVersionIdentifierName().equals(columnName) ? version
155                       .toString() : row.getObject(columnName)));
156       deleteRowUniqueValues(metadata.getUniqueValuesMetadata(), columnNameToValue);
157     }
158   }
159 }