summaryrefslogtreecommitdiffstats
path: root/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportSingleTable.java
blob: 3cac0e789222508a054a30455b1d994b00c22640 (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
package org.openecomp.core.tools.importinfo;

import static org.openecomp.core.tools.exportinfo.ExportDataCommand.NULL_REPRESENTATION;

import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.DataType.Name;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.Session;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.Sets;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.openecomp.core.nosqldb.impl.cassandra.CassandraSessionFactory;
import org.openecomp.core.tools.exportinfo.ExportDataCommand;
import org.openecomp.core.tools.model.ColumnDefinition;
import org.openecomp.core.tools.model.TableData;
import org.openecomp.core.tools.util.Utils;
import org.openecomp.sdc.logging.api.Logger;
import org.openecomp.sdc.logging.api.LoggerFactory;

public class ImportSingleTable {

    private static final Logger logger = LoggerFactory.getLogger(ImportSingleTable.class);

    private static final String INSERT_INTO = "INSERT INTO ";
    private static final String VALUES = " VALUES ";
    private static final Map<String, PreparedStatement> statementsCache = new HashMap<>();

    public void importFile(Path file) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            TableData tableData = objectMapper.readValue(file.toFile(), TableData.class);
            Session session = CassandraSessionFactory.getSession();
            PreparedStatement ps = getPrepareStatement(tableData, session);
            tableData.rows.forEach(row -> executeQuery(session, ps, tableData.definitions, row));
        } catch (IOException e) {
            Utils.logError(logger, e);
        }

    }

    private PreparedStatement getPrepareStatement(TableData tableData, Session session) {
        String query = createQuery(tableData);
        if (statementsCache.containsKey(query)) {
            return statementsCache.get(query);
        }
        PreparedStatement preparedStatement = session.prepare(query);
        statementsCache.put(query, preparedStatement);
        return preparedStatement;
    }

    private void executeQuery(Session session, PreparedStatement ps, List<ColumnDefinition> definitions, List<String> rows) {
        BoundStatement bind = ps.bind();
        for (int i = 0; i < definitions.size(); i++) {
            ColumnDefinition columnDefinition = definitions.get(i);
            String rowData = rows.get(i);
            Name name = dataTypesMap.get(columnDefinition.getType());
            handleByType(bind, i, rowData, name);
        }
        session.execute(bind);
    }

    private void handleByType(BoundStatement bind, int i, String rowData, Name name) {
        switch (name) {
            case VARCHAR:
            case TEXT:
            case ASCII:
                String string = new String(Base64.getDecoder().decode(rowData));
                bind.setString(i, NULL_REPRESENTATION.equals(string) ? null : string);
                break;
            case BLOB:
                bind.setBytes(i, ByteBuffer.wrap(Base64.getDecoder().decode(rowData.getBytes())));
                break;
            case TIMESTAMP:
                if (StringUtils.isEmpty(rowData)){
                    bind.setTimestamp(i, null);
                } else {
                    bind.setTimestamp(i, new Date(Long.parseLong(rowData)));
                }
                break;
            case BOOLEAN:
                bind.setBool(i, Boolean.parseBoolean(rowData));
                break;
            case COUNTER:
                bind.setLong(i, Long.parseLong(rowData));
                break;
            case INT:
                bind.setInt(i, Integer.parseInt(rowData));
                break;
            case FLOAT:
                bind.setFloat(i, Float.parseFloat(rowData));
                break;
            case SET:
                byte[] decoded = Base64.getDecoder().decode(rowData);
                String decodedStr = new String(decoded);
                if (!StringUtils.isEmpty(decodedStr)) {
                    String[] splitted = decodedStr.split(ExportDataCommand.JOIN_DELIMITER_SPLITTER);
                    Set set = Sets.newHashSet(splitted);
                    set.remove("");
                    bind.setSet(i, set);
                } else {
                    bind.setSet(i, null);
                }
                break;
            case MAP:
                byte[] decodedMap = Base64.getDecoder().decode(rowData);
                String mapStr = new String(decodedMap);
                if (!StringUtils.isEmpty(mapStr)) {
                    String[] splittedMap = mapStr.split(ExportDataCommand.JOIN_DELIMITER_SPLITTER);
                    Map<String, String> map = new HashMap<>();
                    for (String keyValue : splittedMap) {
                        String[] split = keyValue.split(ExportDataCommand.MAP_DELIMITER_SPLITTER);
                        map.put(split[0], split[1]);
                    }
                    bind.setMap(i, map);
                } else {
                    bind.setMap(i, null);
                }
                break;
            default:
                throw new UnsupportedOperationException("Name is not supported :" + name);

        }
    }

    private String createQuery(TableData tableData) {
        ColumnDefinition def = tableData.definitions.iterator().next();
        StringBuilder sb = new StringBuilder();
        sb.append(INSERT_INTO).append(def.getKeyspace()).append(".").append(def.getTable());
        sb.append(tableData.definitions.stream().map(ColumnDefinition::getName).collect(Collectors.joining(" , ", " ( ", " ) ")));
        sb.append(VALUES).append(tableData.definitions.stream().map(definition -> "?").collect(Collectors.joining(" , ", " ( ", " ) "))).append(";");
        return sb.toString();
    }

    public static final ImmutableMap<String, Name> dataTypesMap;

    static {
        Builder<String, Name> builder = ImmutableMap.builder();
        Name[] values = Name.values();
        for (Name name : values) {
            builder.put(name.name().toLowerCase(), name);
        }
        dataTypesMap = builder.build();
    }

}