aboutsummaryrefslogtreecommitdiffstats
path: root/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoCassandraImpl.java
blob: f02ea89e345ad2f715024c16ab5e4ce234de4d2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.sdc.versioning.dao.impl;

import com.datastax.driver.core.ColumnDefinitions;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.mapping.UDTMapper;
import org.openecomp.core.nosqldb.api.NoSqlDb;
import org.openecomp.core.nosqldb.factory.NoSqlDbFactory;
import org.openecomp.core.util.UniqueValueUtil;
import org.openecomp.core.utilities.CommonMethods;
import org.openecomp.sdc.versioning.dao.VersionableEntityDao;
import org.openecomp.sdc.versioning.dao.types.Version;
import org.openecomp.sdc.versioning.types.UniqueValueMetadata;
import org.openecomp.sdc.versioning.types.VersionableEntityMetadata;

import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

class VersionableEntityDaoCassandraImpl implements VersionableEntityDao {

  private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface();
  private static org.slf4j.Logger Logger =
      LoggerFactory.getLogger(VersionableEntityDaoCassandraImpl.class);
  private static UDTMapper<Version> versionMapper =
      noSqlDb.getMappingManager().udtMapper(Version.class);

  private static String commaSeparatedQuestionMarks(int size) {
    StringBuilder sb = new StringBuilder(size * 2 - 1);
    for (int i = 0; i < size; i++) {
      if (i > 0) {
        sb.append(',');
      }
      sb.append('?');
    }
    return sb.toString();

  }

  @Override
  public void initVersion(VersionableEntityMetadata metadata, String entityId, Version baseVersion,
                          Version newVersion) {
    ResultSet rows = loadVersionRows(metadata, entityId, baseVersion);
    List<String> columnNames =
        rows.getColumnDefinitions().asList().stream().map(ColumnDefinitions.Definition::getName)
            .collect(Collectors.toList());

    String insertCql = String.format("insert into %s (%s) values (%s)", metadata.getName(),
        CommonMethods.listToSeparatedString(columnNames, ','),
        commaSeparatedQuestionMarks(columnNames.size()));
    Logger.debug("insertCql", insertCql);

    for (Row row : rows) {
      List<Object> columnValues = new ArrayList<>();
      Map<String, Object> columnNameToValue = new HashMap<>();

      for (String columnName : columnNames) {
        if (metadata.getVersionIdentifierName().equals(columnName)) {
          columnValues.add(versionMapper.toUDT(newVersion));
          columnNameToValue.put(columnName, newVersion.toString());
        } else {
          Object value = row.getObject(columnName);
          columnValues.add(value);
          columnNameToValue.put(columnName, value);
        }
      }

      initRowUniqueValues(metadata.getUniqueValuesMetadata(), columnNameToValue);

      noSqlDb.execute(insertCql, columnValues.toArray());
    }
  }

  private ResultSet loadVersionRows(VersionableEntityMetadata metadata, String entityId,
                                    Version version) {
    String selectCql = String.format("select * from %s where %s=? and %s=?", metadata.getName(),
        metadata.getIdentifierName(), metadata.getVersionIdentifierName());
    Logger.debug("selectCql", selectCql);
    Logger.debug("entityId", entityId);
    Logger.debug("version", version);

    return noSqlDb.execute(selectCql, entityId, versionMapper.toUDT(version));
  }

  @Override
  public void deleteVersion(VersionableEntityMetadata metadata, String entityId,
                            Version versionToDelete) {
    deleteRowsUniqueValues(metadata, entityId, versionToDelete);

    String deleteCql = String.format("delete from %s where %s=? and %s=?", metadata.getName(),
        metadata.getIdentifierName(), metadata.getVersionIdentifierName());
    noSqlDb.execute(deleteCql, entityId, versionMapper.toUDT(versionToDelete));
  }

  private void initRowUniqueValues(List<UniqueValueMetadata> metadata,
                                   Map<String, Object> columnNameToValue) {
    for (UniqueValueMetadata uniqueMetadata : metadata) {
      List<String> uniqueValueCombination = uniqueMetadata.getUniqueConstraintIdentifiers().stream()
          .map(colName -> (String) columnNameToValue.get(colName)).collect(Collectors.toList());
      UniqueValueUtil.createUniqueValue(uniqueMetadata.getType(),
          uniqueValueCombination.toArray(new String[uniqueValueCombination.size()]));
    }
  }

  private void deleteRowUniqueValues(List<UniqueValueMetadata> metadata,
                                     Map<String, Object> columnNameToValue) {
    for (UniqueValueMetadata uniqueMetadata : metadata) {
      List<String> uniqueValueCombination = uniqueMetadata.getUniqueConstraintIdentifiers().stream()
          .map(colName -> (String) columnNameToValue.get(colName)).collect(Collectors.toList());
      UniqueValueUtil.deleteUniqueValue(uniqueMetadata.getType(),
          uniqueValueCombination.toArray(new String[uniqueValueCombination.size()]));
    }
  }

  private void deleteRowsUniqueValues(VersionableEntityMetadata metadata, String entityId,
                                      Version version) {
    if (metadata.getUniqueValuesMetadata().isEmpty()) {
      return;
    }
    ResultSet rows = loadVersionRows(metadata, entityId, version);
    List<String> columnNames =
        rows.getColumnDefinitions().asList().stream().map(ColumnDefinitions.Definition::getName)
            .collect(Collectors.toList());

    for (Row row : rows) {
      Map<String, Object> columnNameToValue =
          columnNames.stream().filter(name -> row.getObject(name) != null).collect(Collectors
              .toMap(Function.identity(),
                  columnName -> metadata.getVersionIdentifierName().equals(columnName) ? version
                      .toString() : row.getObject(columnName)));
      deleteRowUniqueValues(metadata.getUniqueValuesMetadata(), columnNameToValue);
    }
  }
}