aboutsummaryrefslogtreecommitdiffstats
path: root/mdbc-server/src/main/java/org/onap/music/mdbc/MDBCUtils.java
blob: b60062e23e12214d35ab4bdc8cadd735e173123a (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
/*
 * ============LICENSE_START====================================================
 * org.onap.music.mdbc
 * =============================================================================
 * Copyright (C) 2018 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.onap.music.mdbc;

import java.io.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;

import org.onap.music.logging.EELFLoggerDelegate;
import org.onap.music.logging.format.AppMessages;
import org.onap.music.logging.format.ErrorSeverity;
import org.onap.music.logging.format.ErrorTypes;
import org.onap.music.mdbc.mixins.MusicMixin;
import org.onap.music.mdbc.mixins.Utils;
import org.onap.music.mdbc.query.SQLOperation;
import org.onap.music.mdbc.query.SQLOperationType;
import org.onap.music.mdbc.tables.Operation;
import org.onap.music.mdbc.tables.StagingTable;

import com.datastax.driver.core.utils.UUIDs;

import org.apache.commons.lang3.tuple.Pair;
import org.json.JSONObject;

public class MDBCUtils {

    public static void saveToFile(String serializedContent, String filename, EELFLoggerDelegate logger) throws IOException {
        try (PrintWriter fout = new PrintWriter(filename)) {
            fout.println(serializedContent);
        } catch (FileNotFoundException e) {
            if(logger!=null){
                logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.IOERROR, ErrorTypes.UNKNOWN, ErrorSeverity.CRITICAL);
            }
            else {
                e.printStackTrace();
            }
            throw e;
        }
    }

	/**
	 * This functions is used to generate cassandra uuid
	 * @return a random UUID that can be used for fields of type uuid
	 */
	public static UUID generateUniqueKey() {
		return UUIDs.random();
	}

    /**
     *  This function is used to generate time based cassandra uuid
     * @return a timebased UUID that can be used for fields of type uuid in MUSIC/Cassandra
     */
	public static UUID generateTimebasedUniqueKey() {return UUIDs.timeBased();}

	public static Properties getMdbcProperties() {
		Properties prop = new Properties();
		InputStream input = null;
		try {
			input = Utils.class.getClassLoader().getResourceAsStream("mdbc.properties");
			prop.load(input);
		} catch (Exception e) {
			Utils.logger.warn(EELFLoggerDelegate.applicationLogger, "Could not load mdbc.properties."
					+ "Proceeding with defaults " + e.getMessage());
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					Utils.logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
				}
			}
		}
		return prop;
	}

	public static Set<Range> getTables(Map<String,List<SQLOperation>> queryParsed){
		return getTables(null, queryParsed);
	}

	public static Set<Range> getTables(String defaultDatabaseName, Map<String,List<SQLOperation>> queryParsed){
	    Set<Range> ranges = new HashSet<>();
	    for(String table: queryParsed.keySet()){
	        String[] parts = table.split("\\.");
	        if(parts.length==2){
				ranges.add(new Range(table));
			}
			else if(parts.length==1 && defaultDatabaseName!=null){
				ranges.add(new Range(defaultDatabaseName+"."+table));
	        }
	        else{
	        	throw new IllegalArgumentException("Table should either have only one '.' or none at all, the table "
					+ "received is "+table);
			}

		}
	    return ranges;
    }

    /**
     * determine the type of operation contained in the table to query map
     * 
     * @param tableToQueryType
     * @return write if any table has a write query. Read otherwise
     */
    public static SQLOperationType getOperationType(Map<String, List<SQLOperation>> tableToQueryType) {
        for (List<org.onap.music.mdbc.query.SQLOperation> tablesOps : tableToQueryType.values()) {
            for (org.onap.music.mdbc.query.SQLOperation op : tablesOps) {
                if (op.getOperationType() != SQLOperationType.READ) {
                    return SQLOperationType.WRITE;
                }
            }
        }
        return SQLOperationType.READ;
    }
}