MUSIC-ORM-Implemetation
[music.git] / src / main / java / org / onap / music / datastore / jsonobjects / JsonSelect.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  *  Modifications Copyright (C) 2019 IBM 
7  * ===================================================================
8  *  Licensed under the Apache License, Version 2.0 (the "License");
9  *  you may not use this file except in compliance with the License.
10  *  You may obtain a copy of the License at
11  * 
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  *  Unless required by applicable law or agreed to in writing, software
15  *  distributed under the License is distributed on an "AS IS" BASIS,
16  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  See the License for the specific language governing permissions and
18  *  limitations under the License.
19  * 
20  * ============LICENSE_END=============================================
21  * ====================================================================
22  */
23
24 package org.onap.music.datastore.jsonobjects;
25
26 import java.io.ByteArrayOutputStream;
27 import java.io.IOException;
28 import java.io.ObjectOutput;
29 import java.io.ObjectOutputStream;
30 import java.io.Serializable;
31 import java.util.List;
32 import java.util.Map;
33
34 import javax.ws.rs.core.MultivaluedMap;
35 import javax.ws.rs.core.Response.Status;
36
37 import org.onap.music.datastore.MusicDataStoreHandle;
38 import org.onap.music.datastore.PreparedQueryObject;
39 import org.onap.music.eelf.logging.EELFLoggerDelegate;
40 import org.onap.music.eelf.logging.format.AppMessages;
41 import org.onap.music.eelf.logging.format.ErrorSeverity;
42 import org.onap.music.eelf.logging.format.ErrorTypes;
43 import org.onap.music.exceptions.MusicQueryException;
44 import org.onap.music.exceptions.MusicServiceException;
45 import org.onap.music.main.MusicUtil;
46
47 import com.datastax.driver.core.DataType;
48 import com.datastax.driver.core.TableMetadata;
49 import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
50
51 @JsonIgnoreProperties(ignoreUnknown = true)
52 public class JsonSelect implements Serializable {
53     private Map<String, String> consistencyInfo;
54     private String keyspaceName;
55     private String tableName;
56     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonSelect.class);
57
58
59
60     public Map<String, String> getConsistencyInfo() {
61         return consistencyInfo;
62     }
63
64     public void setConsistencyInfo(Map<String, String> consistencyInfo) {
65         this.consistencyInfo = consistencyInfo;
66     }
67     
68     public String getKeyspaceName() {
69         return keyspaceName;
70     }
71
72     public void setKeyspaceName(String keyspaceName) {
73         this.keyspaceName = keyspaceName;
74     }
75
76     public String getTableName() {
77         return tableName;
78     }
79
80     public void setTableName(String tableName) {
81         this.tableName = tableName;
82     }
83
84     public byte[] serialize() {
85         ByteArrayOutputStream bos = new ByteArrayOutputStream();
86         ObjectOutput out = null;
87         try {
88             out = new ObjectOutputStream(bos);
89             out.writeObject(this);
90         } catch (IOException e) {
91             logger.error("IOException occured {}",e.getMessage());
92         }
93         return bos.toByteArray();
94     }
95     
96     /**
97      * genSelectQuery
98      * 
99      * @return
100      * @throws MusicQueryException 
101      */
102     public PreparedQueryObject genSelectQuery(MultivaluedMap<String, String> rowParams) throws MusicQueryException {
103         
104         if((this.getKeyspaceName() == null || this.getKeyspaceName().isEmpty()) 
105                 || (this.getTableName() == null || this.getTableName().isEmpty())){
106             throw new MusicQueryException("one or more path parameters are not set, please check and try again",
107                      Status.BAD_REQUEST.getStatusCode());
108         }
109         EELFLoggerDelegate.mdcPut("keyspace", "( " + this.getKeyspaceName() + " ) ");
110         PreparedQueryObject queryObject = new PreparedQueryObject();
111
112         if (rowParams.isEmpty()) { // select all
113             queryObject.appendQueryString("SELECT *  FROM " + this.getKeyspaceName() + "." + this.getTableName() + ";");
114         } else {
115             int limit = -1; // do not limit the number of results
116             try {
117                 queryObject = selectSpecificQuery(this.getKeyspaceName(), this.getTableName(), rowParams, limit);
118             } catch (MusicServiceException ex) {
119                 logger.error(EELFLoggerDelegate.errorLogger, ex, AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN,
120                     ErrorTypes.GENERALSERVICEERROR, ex);
121                 
122                 throw new MusicQueryException(ex.getMessage(), Status.BAD_REQUEST.getStatusCode());
123             }
124         }
125
126         return queryObject;
127     }
128     
129     public PreparedQueryObject selectSpecificQuery(String keyspace,
130             String tablename, MultivaluedMap<String, String> rowParams, int limit)
131             throws MusicServiceException {
132             PreparedQueryObject queryObject = new PreparedQueryObject();
133             StringBuilder rowIdString = getRowIdentifier(keyspace, 
134                 tablename,rowParams,queryObject).rowIdString;
135             queryObject.appendQueryString(
136                 "SELECT *  FROM " + keyspace + "." + tablename + " WHERE " + rowIdString);
137             if (limit != -1) {
138                 queryObject.appendQueryString(" LIMIT " + limit);
139             }
140             queryObject.appendQueryString(";");
141             return queryObject;
142     }
143     
144     private class RowIdentifier {
145         public String primarKeyValue;
146         public StringBuilder rowIdString;
147         @SuppressWarnings("unused")
148         public PreparedQueryObject queryObject; // the string with all the row
149                                                 // identifiers separated by AND
150
151         public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString,
152                         PreparedQueryObject queryObject) {
153             this.primarKeyValue = primaryKeyValue;
154             this.rowIdString = rowIdString;
155             this.queryObject = queryObject;
156         }
157     }
158     
159     /**
160     *
161     * @param keyspace
162     * @param tablename
163     * @param rowParams
164     * @param queryObject
165     * @return
166     * @throws MusicServiceException
167     */
168    private RowIdentifier getRowIdentifier(String keyspace, String tablename,
169        MultivaluedMap<String, String> rowParams, PreparedQueryObject queryObject)
170        throws MusicServiceException {
171        StringBuilder rowSpec = new StringBuilder();
172        int counter = 0;
173        TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename);
174        if (tableInfo == null) {
175            logger.error(EELFLoggerDelegate.errorLogger,
176                "Table information not found. Please check input for table name= "
177                + keyspace + "." + tablename);
178            throw new MusicServiceException(
179                "Table information not found. Please check input for table name= "
180                + keyspace + "." + tablename);
181        }
182        StringBuilder primaryKey = new StringBuilder();
183        for (MultivaluedMap.Entry<String, List<String>> entry : rowParams.entrySet()) {
184            String keyName = entry.getKey();
185            List<String> valueList = entry.getValue();
186            String indValue = valueList.get(0);
187            DataType colType = null;
188            Object formattedValue = null;
189            try {
190                colType = tableInfo.getColumn(entry.getKey()).getType();
191                formattedValue = MusicUtil.convertToActualDataType(colType, indValue);
192            } catch (Exception e) {
193                logger.error(EELFLoggerDelegate.errorLogger,e);
194            }
195            if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) {
196                primaryKey.append(indValue);
197            }
198            rowSpec.append(keyName + "= ?");
199            queryObject.addValue(formattedValue);
200            if (counter != rowParams.size() - 1) {
201                rowSpec.append(" AND ");
202            }
203            counter = counter + 1;
204        }
205        return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject);
206     }
207
208 }