diff options
Diffstat (limited to 'src/main/java/org/onap/music/rest')
7 files changed, 74 insertions, 870 deletions
diff --git a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java index 0e365650..90436499 100755 --- a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java @@ -23,17 +23,10 @@ package org.onap.music.rest; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.List; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.util.ArrayList; import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; import java.util.UUID; - import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.POST; @@ -45,47 +38,23 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; -import org.codehaus.jackson.map.ObjectMapper; import org.mindrot.jbcrypt.BCrypt; import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.datastore.jsonobjects.JSONCallbackResponse; import org.onap.music.datastore.jsonobjects.JSONObject; -import org.onap.music.datastore.jsonobjects.JsonCallback; -import org.onap.music.datastore.jsonobjects.JsonNotification; -import org.onap.music.datastore.jsonobjects.JsonNotifyClientResponse; import org.onap.music.datastore.jsonobjects.JsonOnboard; import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.eelf.logging.format.AppMessages; import org.onap.music.eelf.logging.format.ErrorSeverity; import org.onap.music.eelf.logging.format.ErrorTypes; -//import org.onap.music.main.CacheAccess; import org.onap.music.main.CachingUtil; import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; -import org.onap.music.main.ReturnType; -import org.onap.music.response.jsonobjects.JsonResponse; - import com.datastax.driver.core.DataType; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; -import com.datastax.driver.core.exceptions.InvalidQueryException; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.Base64; - import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import com.datastax.driver.core.TableMetadata; - -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import com.datastax.driver.core.ColumnDefinitions; -import com.datastax.driver.core.ColumnDefinitions.Definition; -import com.datastax.driver.core.TableMetadata; -//import java.util.Base64.Encoder; -//import java.util.Base64.Decoder; @Path("/v2/admin") // @Path("/v{version: [0-9]+}/admin") @@ -94,6 +63,7 @@ import com.datastax.driver.core.TableMetadata; public class RestMusicAdminAPI { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class); + /* * API to onboard an application with MUSIC. This is the mandatory first step. * @@ -175,7 +145,7 @@ public class RestMusicAdminAPI { ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); resultMap.put("Exception", "Unauthorized: Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF."); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + return Response.status(Status.UNAUTHORIZED).entity(resultMap).build(); } PreparedQueryObject pQuery = new PreparedQueryObject(); @@ -189,8 +159,9 @@ public class RestMusicAdminAPI { if (cql.endsWith("AND ")) cql = cql.trim().substring(0, cql.length() - 4); - logger.info("Query in callback is: " + cql); + System.out.println("Query is: " + cql); cql = cql + " allow filtering"; + System.out.println("Get OnboardingInfo CQL: " + cql); pQuery.appendQueryString(cql); if (appName != null) pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); @@ -399,447 +370,14 @@ public class RestMusicAdminAPI { return Response.status(Status.OK).entity(resultMap).build(); } - - Client client = Client.create(); - ObjectMapper mapper = new ObjectMapper(); - - @POST - @Path("/callbackOps") - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - public Response callbackOps(final JSONObject inputJsonObj) { - // {"keyspace":"conductor","full_table":"conductor.plans","changeValue":{"conductor.plans.status":"Who??","position":"3"},"operation":"update","table_name":"plans","primary_key":"3"} - Map<String, Object> resultMap = new HashMap<>(); - new Thread(new Runnable() { - public void run() { - makeAsyncCall(inputJsonObj); - } - }).start(); - - return Response.status(Status.OK).entity(resultMap).build(); - } - - private Response makeAsyncCall(JSONObject inputJsonObj) { - - Map<String, Object> resultMap = new HashMap<>(); - try { - logger.info(EELFLoggerDelegate.applicationLogger, "Got notification: " + inputJsonObj.getData()); - String dataStr = inputJsonObj.getData(); - JSONCallbackResponse jsonResponse = mapper.readValue(dataStr, JSONCallbackResponse.class); - String operation = jsonResponse.getOperation(); - Map<String, String> changeValueMap = jsonResponse.getChangeValue(); - String primaryKey = jsonResponse.getPrimary_key(); - String ksTableName = jsonResponse.getFull_table(); //conductor.plans - if(ksTableName.equals("admin.notification_master")) { - CachingUtil.updateCallbackNotifyList(new ArrayList<String>()); - return Response.status(Status.OK).entity(resultMap).build(); - } - List<String> inputUpdateList = jsonResponse.getUpdateList(); - /*String field_value = changeValueMap.get("field_value"); - if(field_value == null) - field_value = jsonResponse.getFull_table();*/ - String field_value = null; - List<String> notifiyList = CachingUtil.getCallbackNotifyList(); - if(notifiyList == null || notifiyList.isEmpty()) { - logger.info("Is cache empty? reconstructing Object from cache.."); - constructJsonCallbackFromCache(); - /*notifiyList = CachingUtil.getCallbackNotifyList(); - if("update".equals(operation)) { - List<String> updateList = jsonResponse.getUpdateList(); - //logger.info("update list from trigger: "+updateList); - for(String element : updateList) { - logger.info("element: "+element); - logger.info("notifiyList: "+notifiyList); - if(notifiyList.contains(element)) { - logger.info("Found the notifyOn property: "+element); - field_value = element; - } - } - } - - baseRequestObj = CachingUtil.getCallBackCache(field_value); - logger.info("Reconstructing Object from cache is Successful.."+baseRequestObj);*/ - } - notifiyList = CachingUtil.getCallbackNotifyList(); - JsonCallback baseRequestObj = null; - - if("update".equals(operation)) { - for(String element: inputUpdateList) { - baseRequestObj = CachingUtil.getCallBackCache(element); - if(baseRequestObj != null) { - logger.info("Found the element that was changed... "+element); - break; - } - } - - List<String> updateList = jsonResponse.getUpdateList(); - //logger.info("update list from trigger: "+updateList); - for(String element : updateList) { - if(notifiyList.contains(element)) { - logger.info("Found the notifyOn property: "+element); - field_value = element; - break; - } - } - if(baseRequestObj == null || field_value == null) { - for(String element: inputUpdateList) { - String[] elementArr = element.split(":"); - String newElement = null; - if(elementArr.length >= 2) { - newElement = elementArr[0]+":"+elementArr[1]; - } - baseRequestObj = CachingUtil.getCallBackCache(newElement); - if(baseRequestObj != null) { - logger.info("Found the element that was changed... "+newElement); - break; - } - } - for(String element : updateList) { - String[] elementArr = element.split(":"); - String newElement = null; - if(elementArr.length >= 2) { - newElement = elementArr[0]+":"+elementArr[1]; - } - if(notifiyList.contains(newElement)) { - logger.info("Found the notifyOn property: "+newElement); - field_value = newElement; - break; - } - } - } - } else { - field_value = jsonResponse.getFull_table(); - baseRequestObj = CachingUtil.getCallBackCache(field_value); - } - - if(baseRequestObj == null) { - resultMap.put("Exception", - "Oops. Something went wrong. Please make sure Callback properties are onboarded."); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - logger.info("Going through list: "+operation+ " && List: "+jsonResponse.getUpdateList()); - - String key = "admin" + "." + "notification_master" + "." + baseRequestObj.getUuid(); - String lockId = MusicCore.createLockReference(key); - ReturnType lockAcqResult = MusicCore.acquireLock(key, lockId); - if(! lockAcqResult.getResult().toString().equals("SUCCESS")) { - logger.error(EELFLoggerDelegate.errorLogger, "Some other node is notifying the caller..: "); - } - - logger.info(operation+ ": Operation :: changeValue: "+changeValueMap); - if(operation.equals("update")) { - String notifyWhenChangeIn = baseRequestObj.getNotifyWhenChangeIn(); // conductor.plans.status - if(null!=field_value) { - if(field_value.equals(notifyWhenChangeIn)) { - notifyCallBackAppl(jsonResponse, baseRequestObj); - } - } - } else if(operation.equals("delete")) { - String notifyWhenDeletesIn = baseRequestObj.getNotifyWhenDeletesIn(); // conductor.plans.status - if(null!=field_value) { - if(field_value.equals(notifyWhenDeletesIn)) { - notifyCallBackAppl(jsonResponse, baseRequestObj); - } - } - } else if(operation.equals("insert")) { - String notifyWhenInsertsIn = baseRequestObj.getNotifyWhenInsertsIn(); // conductor.plans.status - if(null!=field_value) { - if(field_value.equals(notifyWhenInsertsIn)) { - notifyCallBackAppl(jsonResponse, baseRequestObj); - } - } - } - MusicCore.releaseLock(lockId, true); - } catch(Exception e) { - e.printStackTrace(); - logger.info("Exception..."); - } - logger.info(EELFLoggerDelegate.applicationLogger, "callback is completed. Notification was sent from Music..."); - return Response.status(Status.OK).entity(resultMap).build(); - } - - private void notifyCallBackAppl(JSONCallbackResponse jsonResponse, JsonCallback baseRequestObj) { - int notifytimeout = MusicUtil.getNotifyTimeout(); - int notifyinterval = MusicUtil.getNotifyInterval(); - String endpoint = baseRequestObj.getApplicationNotificationEndpoint(); - String username = baseRequestObj.getApplicationUsername(); - String password = baseRequestObj.getApplicationPassword(); - JsonNotification jsonNotification = constructJsonNotification(jsonResponse, baseRequestObj); - jsonNotification.setOperation_type(jsonResponse.getOperation()); - logger.info(EELFLoggerDelegate.applicationLogger, "Notification Response sent is: "+jsonNotification); - WebResource webResource = client.resource(endpoint); - String authData = username+":"+password; - byte[] plainCredsBytes = authData.getBytes(); - byte[] base64CredsBytes = Base64.encode(plainCredsBytes); - String base64Creds = new String(base64CredsBytes); - Map<String, String> response_body = baseRequestObj.getResponseBody(); - ClientResponse response = null; - try { - response = webResource.header("Authorization", "Basic " + base64Creds).accept("application/json").type("application/json") - .post(ClientResponse.class, jsonNotification); - } catch (com.sun.jersey.api.client.ClientHandlerException chf) { - boolean ok = false; - logger.info(EELFLoggerDelegate.applicationLogger, "Is Service down?"); - long now= System.currentTimeMillis(); - long end = now+notifytimeout; - while(! ok) { - logger.info(EELFLoggerDelegate.applicationLogger, "retrying since error in notifying callback.."); - try { - response = webResource.header("Authorization", "Basic " + base64Creds).accept("application/json").type("application/json") - .post(ClientResponse.class, jsonNotification); - if(response.getStatus() == 200) ok = true; - }catch (Exception e) { - logger.info(EELFLoggerDelegate.applicationLogger, "Retry until "+(end-System.currentTimeMillis())); - if(response == null && System.currentTimeMillis() < end) ok = false; - else ok = true; - try{ Thread.sleep(notifyinterval); } catch(Exception e1) {} - } - } - } - if(response == null) { - logger.error(EELFLoggerDelegate.errorLogger, "Can NOT notify the caller as caller failed to respond.."); - return; - } - JsonNotifyClientResponse responseStr = response.getEntity(JsonNotifyClientResponse.class); - logger.info(EELFLoggerDelegate.applicationLogger, "Response from Notified client: "+responseStr); - - if(response.getStatus() != 200){ - long now= System.currentTimeMillis(); - long end = now+30000; - while(response.getStatus() != 200 && System.currentTimeMillis() < end) { - logger.info(EELFLoggerDelegate.applicationLogger, "retrying since error in notifying callback.."); - response = webResource.header("Authorization", "Basic " + base64Creds).accept("application/json").type("application/json") - .post(ClientResponse.class, jsonNotification); - } - logger.info(EELFLoggerDelegate.applicationLogger, "Exception while notifying.. "+response.getStatus()); - } - } - - private JsonNotification constructJsonNotification(JSONCallbackResponse jsonResponse, JsonCallback baseRequestObj) { - - JsonNotification jsonNotification = new JsonNotification(); - try { - jsonNotification.setNotify_field(baseRequestObj.getNotifyOn()); - jsonNotification.setEndpoint(baseRequestObj.getApplicationNotificationEndpoint()); - jsonNotification.setUsername(baseRequestObj.getApplicationUsername()); - jsonNotification.setPassword(baseRequestObj.getApplicationPassword()); - String pkValue = jsonResponse.getPrimary_key(); - - String[] fullNotifyArr = baseRequestObj.getNotifyOn().split(":"); - - String[] tableArr = fullNotifyArr[0].split("\\."); - TableMetadata tableInfo = MusicCore.returnColumnMetadata(tableArr[0], tableArr[1]); - DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType(); - String primaryId = tableInfo.getPrimaryKey().get(0).getName(); - - Map<String, String> responseBodyMap = baseRequestObj.getResponseBody(); - Map<String, String> newMap = new HashMap<>(); - if(responseBodyMap.size() == 1 && responseBodyMap.containsKey("")) { - jsonNotification.setResponse_body(newMap); - } else { - for (Entry<String, String> entry : new HashSet<>(responseBodyMap.entrySet())) { - String trimmed = entry.getKey().trim(); - if (!trimmed.equals(entry.getKey())) { - responseBodyMap.remove(entry.getKey()); - responseBodyMap.put(trimmed, entry.getValue()); - } - } - - Set<String> keySet = responseBodyMap.keySet(); - String cql = "select *"; - /*for(String keys: keySet) { - cql = cql + keys + ","; - }*/ - //cql = cql.substring(0, cql.length()-1); - cql = cql + " FROM "+fullNotifyArr[0]+" WHERE "+primaryId+" = ?"; - logger.info("CQL in constructJsonNotification: "+cql); - PreparedQueryObject pQuery = new PreparedQueryObject(); - pQuery.appendQueryString(cql); - pQuery.addValue(MusicUtil.convertToActualDataType(primaryIdType, pkValue)); - Row row = MusicCore.get(pQuery).one(); - if(row != null) { - ColumnDefinitions colInfo = row.getColumnDefinitions(); - for (Definition definition : colInfo) { - String colName = definition.getName(); - if(keySet.contains(colName)) { - DataType colType = definition.getType(); - Object valueObj = MusicCore.getDSHandle().getColValue(row, colName, colType); - Object valueString = MusicUtil.convertToActualDataType(colType, valueObj); - logger.info(colName+" : "+valueString); - newMap.put(colName, valueString.toString()); - keySet.remove(colName); - } - } - } - if(! keySet.isEmpty()) { - Iterator<String> iterator = keySet.iterator(); - while (iterator.hasNext()) { - String element = iterator.next(); - if(element != null && element.length() > 0) - newMap.put(element,"COLUMN_NOT_FOUND"); - } - } - - if("delete".equals(jsonResponse.getOperation()) || newMap.isEmpty()) { - newMap.put(primaryId, pkValue); - } - jsonNotification.setResponse_body(newMap); - } - } catch(Exception e) { - e.printStackTrace(); - } - return jsonNotification; - } - - private void constructJsonCallbackFromCache() throws Exception{ - PreparedQueryObject pQuery = new PreparedQueryObject(); - JsonCallback jsonCallback = null; - List<String> notifyList = new java.util.ArrayList<>(); - String cql = - "select id, endpoint_userid, endpoint_password, notify_to_endpoint, notify_insert_on," - + " notify_delete_on, notify_update_on, request, notifyon from admin.notification_master allow filtering"; - pQuery.appendQueryString(cql); - //pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), fullTable)); - logger.info("Query: "+pQuery.getQuery()); - - ResultSet rs = MusicCore.get(pQuery); - Iterator<Row> it = rs.iterator(); - while (it.hasNext()) { - Row row = (Row) it.next(); - String endpoint = row.getString("notify_to_endpoint"); - String username = row.getString("endpoint_userid"); - ByteBuffer passwordBytes = row.getBytes("endpoint_password"); - String insert = row.getString("notify_insert_on"); - String delete = row.getString("notify_delete_on"); - String update = row.getString("notify_update_on"); - String request = row.getString("request"); - String notifyon = row.getString("notifyon"); - String uuid = row.getUUID("id").toString(); - notifyList.add(notifyon); - jsonCallback = new JsonCallback(); - jsonCallback.setApplicationNotificationEndpoint(endpoint); - - Charset charset = Charset.forName("ISO-8859-1"); - String decodedPwd = charset.decode(passwordBytes).toString(); - jsonCallback.setApplicationPassword(decodedPwd); - jsonCallback.setApplicationUsername(username); - jsonCallback.setNotifyOn(notifyon); - jsonCallback.setNotifyWhenInsertsIn(insert); - jsonCallback.setNotifyWhenDeletesIn(delete); - jsonCallback.setNotifyWhenChangeIn(update); - jsonCallback.setUuid(uuid); - logger.info("From DB. Saved request_body: "+request); - request = request.substring(1, request.length()-1); - String[] keyValuePairs = request.split(","); - Map<String,String> responseBody = new HashMap<>(); - - for(String pair : keyValuePairs) { - String[] entry = pair.split("="); - String val = ""; - if(entry.length == 2) - val = entry[1]; - responseBody.put(entry[0], val); - } - logger.info("After parsing. Saved request_body: "+responseBody); - jsonCallback.setResponseBody(responseBody); - logger.info("Updating Cache with updateCallBackCache: "+notifyon+ " :::: "+jsonCallback); - CachingUtil.updateCallBackCache(notifyon, jsonCallback); - } - CachingUtil.updateCallbackNotifyList(notifyList); - } @POST - @Path("/onboardCallback") + @Path("/callbackOps") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) - public Response addCallback(JsonNotification jsonNotification) { - Map<String, Object> resultMap = new HashMap<>(); - ResponseBuilder response = - Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); - String username = jsonNotification.getUsername(); - String password = jsonNotification.getPassword(); - String endpoint = jsonNotification.getEndpoint(); - String notify_field = jsonNotification.getNotify_field(); - Map<String, String> responseBody = jsonNotification.getResponse_body(); - String triggerName = jsonNotification.getTriggerName(); - if(triggerName == null || triggerName.length() == 0) - triggerName = "MusicTrigger"; - - /*JsonCallback callBackCache = CachingUtil.getCallBackCache(notify_field); - if(callBackCache != null) { - resultMap.put("Exception", "The notification property has already been onboarded."); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - }*/ - - String[] allFields = notify_field.split(":"); - String inserts = null; - String updates = null; - String deletes = null; - String tableName = null; - if(allFields.length >= 2) { - inserts = updates = notify_field; - } else if(allFields.length == 1) { - inserts = deletes = notify_field;; - } - tableName = allFields[0]; - String cql = "CREATE TRIGGER IF NOT EXISTS musictrigger ON "+tableName+" Using '"+triggerName+"'"; - PreparedQueryObject pQuery = new PreparedQueryObject(); - - String uuid = CachingUtil.generateUUID(); - try { - pQuery.appendQueryString( - "INSERT INTO admin.notification_master (id, endpoint_userid, endpoint_password, notify_to_endpoint, " - + "notifyon, notify_insert_on, notify_delete_on, notify_update_on, request, current_notifier) VALUES (?,?,?,?,?,?,?,?,?,?)"); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), username)); - Charset charset = Charset.forName("ISO-8859-1"); - ByteBuffer decodedPwd = charset.encode(password); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.blob(), decodedPwd.array())); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), endpoint)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), notify_field)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), inserts)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), deletes)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), updates)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), responseBody)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), MusicCore.getMyHostId())); - MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.EVENTUAL); - JsonCallback jsonCallback = new JsonCallback(); - jsonCallback.setUuid(uuid); - jsonCallback.setApplicationNotificationEndpoint(endpoint); - jsonCallback.setApplicationPassword(password); - jsonCallback.setApplicationUsername(username); - jsonCallback.setNotifyOn(notify_field); - jsonCallback.setNotifyWhenChangeIn(updates); - jsonCallback.setNotifyWhenDeletesIn(deletes); - jsonCallback.setNotifyWhenInsertsIn(inserts); - jsonCallback.setResponseBody(responseBody); - CachingUtil.updateCallBackCache(notify_field, jsonCallback); - logger.info("Cache updated "); - pQuery = new PreparedQueryObject(); - pQuery.appendQueryString(cql); - ResultType nonKeyRelatedPut = MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.EVENTUAL); - logger.info(EELFLoggerDelegate.applicationLogger, "Created trigger"); - //callBackCache.put(jsonCallback.getApplicationName(), jsonMap); - } catch (InvalidQueryException e) { - logger.error(EELFLoggerDelegate.errorLogger,"Exception callback_api table not configured."+e.getMessage()); - resultMap.put("Exception", "Please make sure admin.notification_master table is configured."); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } catch(Exception e) { - e.printStackTrace(); - resultMap.put("Exception", "Exception Occured."); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Callback api successfully registered").toMap()).build(); + public String callbackOps(JSONObject inputJsonObj) throws Exception { + + System.out.println("Input JSON: "+inputJsonObj.getData()); + return "Success"; } - - /*public String encodePwd(String password) { - return Base64.getEncoder().encodeToString(password.getBytes()); - } - - public String decodePwd(String password) { - byte[] bytes = Base64.getDecoder().decode(password); - return new String(bytes); - }*/ } diff --git a/src/main/java/org/onap/music/rest/RestMusicBmAPI.java b/src/main/java/org/onap/music/rest/RestMusicBmAPI.java deleted file mode 100644 index 55eb47f2..00000000 --- a/src/main/java/org/onap/music/rest/RestMusicBmAPI.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * ============LICENSE_START========================================== org.onap.music - * =================================================================== Copyright (c) 2017 AT&T - * Intellectual Property =================================================================== - * 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.rest; - -import java.util.List; -import java.util.Map; -import java.util.UUID; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.UriInfo; -import org.onap.music.datastore.jsonobjects.JsonInsert; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.main.MusicCore; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.ResultType; -import org.onap.music.main.ReturnType; -import org.onap.music.datastore.PreparedQueryObject; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.TableMetadata; -import io.swagger.annotations.Api; -//import io.swagger.annotations.ApiOperation; -//import io.swagger.annotations.ApiParam; - -/* - * These are functions created purely for benchmarking purposes. Commented out Swagger - This should - * be undocumented API - * - */ -@Path("/v{version: [0-9]+}/benchmarks/") -@Api(value = "Benchmark API", hidden = true) -public class RestMusicBmAPI { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicBmAPI.class); - - // pure zk calls... - - /** - * - * @param nodeName - * @throws Exception - */ - @POST - @Path("/purezk/{name}") - @Consumes(MediaType.APPLICATION_JSON) - public void pureZkCreate(@PathParam("name") String nodeName) throws Exception { - MusicCore.pureZkCreate("/" + nodeName); - } - - - /** - * - * @param insObj - * @param nodeName - * @throws Exception - */ - @PUT - @Path("/purezk/{name}") - @Consumes(MediaType.APPLICATION_JSON) - public void pureZkUpdate(JsonInsert insObj, @PathParam("name") String nodeName) - throws Exception { - logger.info(EELFLoggerDelegate.applicationLogger,"--------------Zk normal update-------------------------"); - long start = System.currentTimeMillis(); - MusicCore.pureZkWrite(nodeName, insObj.serialize()); - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Total time taken for Zk normal update:" + (end - start) + " ms"); - } - - /** - * - * @param nodeName - * @return - * @throws Exception - */ - @GET - @Path("/purezk/{name}") - @Consumes(MediaType.TEXT_PLAIN) - public byte[] pureZkGet(@PathParam("name") String nodeName) throws Exception { - return MusicCore.pureZkRead(nodeName); - } - - /** - * - * @param insObj - * @param lockName - * @param nodeName - * @throws Exception - */ - @PUT - @Path("/purezk/atomic/{lockname}/{name}") - @Consumes(MediaType.APPLICATION_JSON) - public void pureZkAtomicPut(JsonInsert updateObj, @PathParam("lockname") String lockname, - @PathParam("name") String nodeName) throws Exception { - long startTime = System.currentTimeMillis(); - String operationId = UUID.randomUUID().toString();// just for debugging purposes. - String consistency = updateObj.getConsistencyInfo().get("type"); - - logger.info(EELFLoggerDelegate.applicationLogger,"--------------Zookeeper " + consistency + " update-" + operationId - + "-------------------------"); - - byte[] data = updateObj.serialize(); - long jsonParseCompletionTime = System.currentTimeMillis(); - - String lockId = MusicCore.createLockReference(lockname); - - long lockCreationTime = System.currentTimeMillis(); - - long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); - ReturnType lockAcqResult = MusicCore.acquireLockWithLease(lockname, lockId, leasePeriod); - long lockAcqTime = System.currentTimeMillis(); - long zkPutTime = 0, lockReleaseTime = 0; - - if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId); - MusicCore.pureZkWrite(lockname, data); - zkPutTime = System.currentTimeMillis(); - boolean voluntaryRelease = true; - if (consistency.equals("atomic")) - MusicCore.releaseLock(lockId, voluntaryRelease); - else if (consistency.equals("atomic_delete_lock")) - MusicCore.deleteLock(lockname); - lockReleaseTime = System.currentTimeMillis(); - } else { - MusicCore.destroyLockRef(lockId); - } - - long actualUpdateCompletionTime = System.currentTimeMillis(); - - - long endTime = System.currentTimeMillis(); - - String lockingInfo = "|lock creation time:" + (lockCreationTime - jsonParseCompletionTime) - + "|lock accquire time:" + (lockAcqTime - lockCreationTime) - + "|zk put time:" + (zkPutTime - lockAcqTime); - - if (consistency.equals("atomic")) - lockingInfo = lockingInfo + "|lock release time:" + (lockReleaseTime - zkPutTime) + "|"; - else if (consistency.equals("atomic_delete_lock")) - lockingInfo = lockingInfo + "|lock delete time:" + (lockReleaseTime - zkPutTime) + "|"; - - String timingString = "Time taken in ms for Zookeeper " + consistency + " update-" - + operationId + ":" + "|total operation time:" + (endTime - startTime) - + "|json parsing time:" + (jsonParseCompletionTime - startTime) - + "|update time:" + (actualUpdateCompletionTime - jsonParseCompletionTime) - + lockingInfo; - - logger.info(EELFLoggerDelegate.applicationLogger,timingString); - } - - /** - * - * @param insObj - * @param lockName - * @param nodeName - * @throws Exception - */ - @GET - @Path("/purezk/atomic/{lockname}/{name}") - @Consumes(MediaType.APPLICATION_JSON) - public void pureZkAtomicGet(JsonInsert insObj, @PathParam("lockname") String lockName, - @PathParam("name") String nodeName) throws Exception { - logger.info("--------------Zk atomic read-------------------------"); - long start = System.currentTimeMillis(); - String lockId = MusicCore.createLockReference(lockName); - long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); - ReturnType lockAcqResult = MusicCore.acquireLockWithLease(lockName, lockId, leasePeriod); - if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - logger.info("acquired lock with id " + lockId); - MusicCore.pureZkRead(nodeName); - boolean voluntaryRelease = true; - MusicCore.releaseLock(lockId, voluntaryRelease); - } else { - MusicCore.destroyLockRef(lockId); - } - - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Total time taken for Zk atomic read:" + (end - start) + " ms"); - } - - /** - * - * doing an update directly to cassa but through the rest api - * - * @param insObj - * @param keyspace - * @param tablename - * @param info - * @return - * @throws Exception - */ - @PUT - @Path("/cassa/keyspaces/{keyspace}/tables/{tablename}/rows") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public boolean updateTableCassa(JsonInsert insObj, @PathParam("keyspace") String keyspace, - @PathParam("tablename") String tablename, @Context UriInfo info) - throws Exception { - long startTime = System.currentTimeMillis(); - String operationId = UUID.randomUUID().toString();// just for debugging purposes. - String consistency = insObj.getConsistencyInfo().get("type"); - logger.info(EELFLoggerDelegate.applicationLogger,"--------------Cassandra " + consistency + " update-" + operationId - + "-------------------------"); - PreparedQueryObject queryObject = new PreparedQueryObject(); - Map<String, Object> valuesMap = insObj.getValues(); - TableMetadata tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); - String vectorTs = "'" + Thread.currentThread().getId() + System.currentTimeMillis() + "'"; - String fieldValueString = "vector_ts= ? ,"; - queryObject.addValue(vectorTs); - - int counter = 0; - for (Map.Entry<String, Object> entry : valuesMap.entrySet()) { - Object valueObj = entry.getValue(); - DataType colType = tableInfo.getColumn(entry.getKey()).getType(); - Object valueString = MusicUtil.convertToActualDataType(colType, valueObj); - fieldValueString = fieldValueString + entry.getKey() + "= ?"; - queryObject.addValue(valueString); - if (counter != valuesMap.size() - 1) - fieldValueString = fieldValueString + ","; - counter = counter + 1; - } - - // get the row specifier - String rowSpec = ""; - counter = 0; - queryObject.appendQueryString("UPDATE " + keyspace + "." + tablename + " "); - MultivaluedMap<String, String> rowParams = info.getQueryParameters(); - String primaryKey = ""; - for (MultivaluedMap.Entry<String, List<String>> entry : rowParams.entrySet()) { - String keyName = entry.getKey(); - List<String> valueList = entry.getValue(); - String indValue = valueList.get(0); - DataType colType = tableInfo.getColumn(entry.getKey()).getType(); - Object formattedValue = MusicUtil.convertToActualDataType(colType, indValue); - primaryKey = primaryKey + indValue; - rowSpec = rowSpec + keyName + "= ? "; - queryObject.addValue(formattedValue); - if (counter != rowParams.size() - 1) - rowSpec = rowSpec + " AND "; - counter = counter + 1; - } - - - String ttl = insObj.getTtl(); - String timestamp = insObj.getTimestamp(); - - if ((ttl != null) && (timestamp != null)) { - - logger.info(EELFLoggerDelegate.applicationLogger,"both there"); - queryObject.appendQueryString(" USING TTL ? AND TIMESTAMP ?"); - queryObject.addValue(Integer.parseInt(ttl)); - queryObject.addValue(Long.parseLong(timestamp)); - } - - if ((ttl != null) && (timestamp == null)) { - logger.info(EELFLoggerDelegate.applicationLogger,"ONLY TTL there"); - queryObject.appendQueryString(" USING TTL ?"); - queryObject.addValue(Integer.parseInt(ttl)); - } - - if ((ttl == null) && (timestamp != null)) { - logger.info(EELFLoggerDelegate.applicationLogger,"ONLY timestamp there"); - queryObject.appendQueryString(" USING TIMESTAMP ?"); - queryObject.addValue(Long.parseLong(timestamp)); - } - queryObject.appendQueryString(" SET " + fieldValueString + " WHERE " + rowSpec + ";"); - - long jsonParseCompletionTime = System.currentTimeMillis(); - - boolean operationResult = true; - MusicCore.getDSHandle().executePut(queryObject, insObj.getConsistencyInfo().get("type")); - - long actualUpdateCompletionTime = System.currentTimeMillis(); - - long endTime = System.currentTimeMillis(); - - String timingString = "Time taken in ms for Cassandra " + consistency + " update-" - + operationId + ":" + "|total operation time:" + (endTime - startTime) - + "|json parsing time:" + (jsonParseCompletionTime - startTime) - + "|update time:" + (actualUpdateCompletionTime - jsonParseCompletionTime) - + "|"; - logger.info(EELFLoggerDelegate.applicationLogger,timingString); - - return operationResult; - } -} diff --git a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java index 2d1a8836..99c60b30 100755 --- a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java @@ -56,6 +56,7 @@ import org.onap.music.datastore.jsonobjects.JsonTable; import org.onap.music.datastore.jsonobjects.JsonUpdate; import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicQueryException; import org.onap.music.eelf.logging.format.AppMessages; import org.onap.music.eelf.logging.format.ErrorSeverity; import org.onap.music.eelf.logging.format.ErrorTypes; @@ -159,7 +160,7 @@ public class RestMusicDataAPI { if (!authMap.isEmpty()) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); response.status(Status.UNAUTHORIZED); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build(); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } if(kspObject == null || kspObject.getReplicationInfo() == null) { authMap.put(ResultType.EXCEPTION.getResult(), ResultType.BODYMISSING.getResult()); @@ -169,7 +170,7 @@ public class RestMusicDataAPI { try { - authMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + authMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, "createKeySpace"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); @@ -183,7 +184,7 @@ public class RestMusicDataAPI { } else { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); response.status(Status.UNAUTHORIZED); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build(); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } } @@ -285,7 +286,7 @@ public class RestMusicDataAPI { Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); String userId = userCredentials.get(MusicUtil.USERID); String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password,keyspaceName, aid, "dropKeySpace"); + Map<String, Object> authMap = MusicCore.authenticate(ns, userId, password,keyspaceName, aid, "dropKeySpace"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { @@ -362,13 +363,13 @@ public class RestMusicDataAPI { Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); String userId = userCredentials.get(MusicUtil.USERID); String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, + Map<String, Object> authMap = MusicCore.authenticate(ns, userId, password, keyspace, aid, "createTable"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build(); + return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } String consistency = MusicUtil.EVENTUAL; // for now this needs only eventual consistency @@ -548,7 +549,7 @@ public class RestMusicDataAPI { ResultType result = ResultType.FAILURE; try { //logger.info("cjc query="+queryObject.getQuery()); - result = MusicCore.nonKeyRelatedPut(queryObject, consistency); + result = MusicCore.createTable(keyspace, tablename, queryObject, consistency); } catch (MusicServiceException ex) { logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.MUSICSERVICEERROR); response.status(Status.BAD_REQUEST); @@ -588,20 +589,20 @@ public class RestMusicDataAPI { Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); String userId = userCredentials.get(MusicUtil.USERID); String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,aid, "createIndex"); + Map<String, Object> authMap = MusicCore.authenticate(ns, userId, password, keyspace,aid, "createIndex"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); response.status(Status.UNAUTHORIZED); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build(); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } MultivaluedMap<String, String> rowParams = info.getQueryParameters(); String indexName = ""; if (rowParams.getFirst("index_name") != null) indexName = rowParams.getFirst("index_name"); PreparedQueryObject query = new PreparedQueryObject(); - query.appendQueryString("Create index if not exists " + indexName + " on " + keyspace + "." + query.appendQueryString("Create index " + indexName + " if not exists on " + keyspace + "." + tablename + " (" + fieldName + ");"); ResultType result = ResultType.FAILURE; @@ -613,9 +614,9 @@ public class RestMusicDataAPI { return response.entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); } if ( result.equals(ResultType.SUCCESS) ) { - return response.status(Status.OK).entity(new JsonResponse(result).setMessage("Index Created on " + keyspace+"."+tablename+"."+fieldName).toMap()).build(); + return response.entity(new JsonResponse(result).setMessage("Index Created on " + keyspace+"."+tablename+"."+fieldName).toMap()).build(); } else { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Unknown Error in create index.").toMap()).build(); + return response.entity(new JsonResponse(result).setError("Unknown Error in create index.").toMap()).build(); } } @@ -652,7 +653,7 @@ public class RestMusicDataAPI { Map<String, Object> authMap = null; try { - authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, + authMap = MusicCore.authenticate(ns, userId, password, keyspace, aid, "insertIntoTable"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); @@ -662,7 +663,7 @@ public class RestMusicDataAPI { authMap.remove("aid"); if (!authMap.isEmpty()) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build(); + return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } Map<String, Object> valuesMap = insObj.getValues(); @@ -808,10 +809,6 @@ public class RestMusicDataAPI { result = MusicCore.atomicPut(keyspace, tablename, primaryKey, queryObject, null); } - else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) { - result = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, primaryKey, queryObject, null); - - } } catch (Exception ex) { logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); @@ -862,7 +859,7 @@ public class RestMusicDataAPI { String password = userCredentials.get(MusicUtil.PASSWORD); Map<String, Object> authMap; try { - authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, + authMap = MusicCore.authenticate(ns, userId, password, keyspace, aid, "updateTable"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); @@ -872,7 +869,7 @@ public class RestMusicDataAPI { authMap.remove("aid"); if (!authMap.isEmpty()) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build(); + return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } long startTime = System.currentTimeMillis(); String operationId = UUID.randomUUID().toString();// just for infoging @@ -991,20 +988,11 @@ public class RestMusicDataAPI { } operationResult = MusicCore.criticalPut(keyspace, tablename, rowId.primarKeyValue, queryObject, lockId, conditionInfo); - } else if (consistency.equalsIgnoreCase("atomic_delete_lock")) { - // this function is mainly for the benchmarks - try { - operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, - rowId.primarKeyValue, queryObject, conditionInfo); - } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); - } } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { try { operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue, queryObject, conditionInfo); - } catch (MusicLockingException e) { + } catch (MusicLockingException | MusicQueryException | MusicServiceException e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); } @@ -1075,7 +1063,7 @@ public class RestMusicDataAPI { String password = userCredentials.get(MusicUtil.PASSWORD); Map<String, Object> authMap = null; try { - authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, + authMap = MusicCore.authenticate(ns, userId, password, keyspace, aid, "deleteFromTable"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); @@ -1085,7 +1073,7 @@ public class RestMusicDataAPI { authMap.remove("aid"); if (!authMap.isEmpty()) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build(); + return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } if(delObj == null) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.WARN, ErrorTypes.DATAERROR); @@ -1162,11 +1150,7 @@ public class RestMusicDataAPI { operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue, queryObject, conditionInfo); } - else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) { - operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, rowId.primarKeyValue, - queryObject, conditionInfo); - } - } catch (MusicLockingException e) { + } catch (MusicLockingException | MusicQueryException | MusicServiceException e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) .setError("Unable to perform Delete operation. Exception from music").toMap()).build(); @@ -1215,12 +1199,12 @@ public class RestMusicDataAPI { String userId = userCredentials.get(MusicUtil.USERID); String password = userCredentials.get(MusicUtil.PASSWORD); Map<String, Object> authMap = - MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "dropTable"); + MusicCore.authenticate(ns, userId, password, keyspace, aid, "dropTable"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build(); + return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } String consistency = "eventual";// for now this needs only eventual // consistency @@ -1270,12 +1254,12 @@ public class RestMusicDataAPI { Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); String userId = userCredentials.get(MusicUtil.USERID); String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,aid, "selectCritical"); + Map<String, Object> authMap = MusicCore.authenticate(ns, userId, password, keyspace,aid, "selectCritical"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { logger.error(EELFLoggerDelegate.errorLogger,"Error while authentication... ", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build(); + return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } String lockId = selObj.getConsistencyInfo().get("lockId"); @@ -1307,10 +1291,6 @@ public class RestMusicDataAPI { } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { results = MusicCore.atomicGet(keyspace, tablename, rowId.primarKeyValue, queryObject); } - - else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) { - results = MusicCore.atomicGetWithDeleteLock(keyspace, tablename, rowId.primarKeyValue, queryObject); - } if(results!=null && results.getAvailableWithoutFetching() >0) { return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).toMap()).build(); } @@ -1353,12 +1333,12 @@ public class RestMusicDataAPI { String userId = userCredentials.get(MusicUtil.USERID); String password = userCredentials.get(MusicUtil.PASSWORD); Map<String, Object> authMap = - MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "select"); + MusicCore.authenticate(ns, userId, password, keyspace, aid, "select"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build(); + return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } PreparedQueryObject queryObject = new PreparedQueryObject(); @@ -1380,7 +1360,7 @@ public class RestMusicDataAPI { if(results.getAvailableWithoutFetching() >0) { return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).toMap()).build(); } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).setError("No data found").toMap()).build(); + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setError("No data found").toMap()).build(); } catch (MusicServiceException ex) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); diff --git a/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java b/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java index 895f0abf..c7e8fda1 100644 --- a/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java @@ -88,28 +88,8 @@ public class RestMusicHealthCheckAPI { resultMap.put("INACTIVE", "One or more nodes in the Cluster is/are down or not responding."); return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); } - - - } - @GET - @Path("/pingZookeeper") - @ApiOperation(value = "Get Health Status", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - public Response ZKStatus(@Context HttpServletResponse response) { - logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Zookeeper"); - Map<String, Object> resultMap = new HashMap<>(); - MusicHealthCheck ZKHealthCheck = new MusicHealthCheck(); - String status = ZKHealthCheck.getZookeeperStatus(); - if(status.equals("ACTIVE")) { - resultMap.put("ACTIVE", "Zookeeper is Active and Running"); - return Response.status(Status.OK).entity(resultMap).build(); - }else { - resultMap.put("INACTIVE", "Zookeeper is not responding"); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - } diff --git a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java index 70583baa..835dda14 100644 --- a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java @@ -40,7 +40,7 @@ import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.eelf.logging.format.AppMessages; import org.onap.music.eelf.logging.format.ErrorSeverity; import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.lockingservice.MusicLockState; +import org.onap.music.datastore.MusicLockState; import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; @@ -96,7 +96,7 @@ public class RestMusicLocksAPI { String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + resultMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, "createLockReference"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); @@ -148,7 +148,7 @@ public class RestMusicLocksAPI { String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + resultMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, "accquireLock"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); @@ -198,7 +198,7 @@ public class RestMusicLocksAPI { String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + resultMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, "accquireLockWithLease"); if (resultMap.containsKey("aid")) @@ -245,7 +245,7 @@ public class RestMusicLocksAPI { String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + resultMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, "currentLockHolder"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); @@ -291,7 +291,7 @@ public class RestMusicLocksAPI { } String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + resultMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, "currentLockState"); if (resultMap.containsKey("aid")) @@ -301,7 +301,7 @@ public class RestMusicLocksAPI { return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } - MusicLockState mls = MusicCore.getMusicLockState(lockName); + org.onap.music.datastore.MusicLockState mls = MusicCore.getMusicLockState(lockName); Map<String,Object> returnMap = null; JsonResponse jsonResponse = new JsonResponse(ResultType.FAILURE).setLock(lockName); if(mls == null) { @@ -348,7 +348,7 @@ public class RestMusicLocksAPI { String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + resultMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, "unLock"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); @@ -356,8 +356,9 @@ public class RestMusicLocksAPI { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } - boolean voluntaryRelease = true; - MusicLockState mls = MusicCore.releaseLock(lockId,voluntaryRelease); + String fullyQualifiedKey = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$')); + MusicLockState mls = MusicCore.voluntaryReleaseLock(fullyQualifiedKey, lockId); + if(mls.getErrorMessage() != null) { resultMap.put(ResultType.EXCEPTION.getResult(), mls.getErrorMessage()); logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); @@ -405,7 +406,7 @@ public class RestMusicLocksAPI { String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + resultMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, "deleteLock"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); diff --git a/src/main/java/org/onap/music/rest/RestMusicQAPI.java b/src/main/java/org/onap/music/rest/RestMusicQAPI.java index 1f6ec24f..8af334c7 100755 --- a/src/main/java/org/onap/music/rest/RestMusicQAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicQAPI.java @@ -34,6 +34,7 @@ import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; +// cjcimport javax.servlet.http.HttpServletResponse; import org.onap.music.datastore.jsonobjects.JsonDelete; import org.onap.music.datastore.jsonobjects.JsonInsert; import org.onap.music.datastore.jsonobjects.JsonTable; @@ -50,19 +51,22 @@ import org.onap.music.exceptions.MusicServiceException; import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; +// cjc import org.onap.music.main.ReturnType; import org.onap.music.response.jsonobjects.JsonResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; - +// import io.swagger.models.Response; // @Path("/v{version: [0-9]+}/priorityq/") @Path("{version}/priorityq/") @Api(value = "Q Api") public class RestMusicQAPI { private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicQAPI.class); + // private static String xLatestVersion = "X-latestVersion"; /* + * private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicDataAPI.class); * private static final String XMINORVERSION = "X-minorVersion"; private static final String * XPATCHVERSION = "X-patchVersion"; private static final String NS = "ns"; private static final * String USERID = "userId"; private static final String PASSWORD = "password"; @@ -104,12 +108,12 @@ public class RestMusicQAPI { @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) throws Exception { - + //logger.info(logger, "cjc before start in q 1** major version=" + version); ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); Map<String, String> fields = tableObj.getFields(); - if (fields == null) { + if (fields == null) { // || (!fields.containsKey("order")) ){ logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST) @@ -186,13 +190,9 @@ public class RestMusicQAPI { clusteringKey=clusteringKey.replaceAll("[\\(]+",""); clusteringKey=clusteringKey.replaceAll("[\\)]+",""); clusteringKey.trim(); - if (clusteringKey.indexOf(",") == 0) { - clusteringKey=clusteringKey.substring(1); - } + if (clusteringKey.indexOf(",") == 0) clusteringKey=clusteringKey.substring(1); clusteringKey.trim(); - if (",".equals(clusteringKey) ) { - clusteringKey=""; // print error if needed ( ... ),) - } + if (clusteringKey.equals(",") ) clusteringKey=""; // print error if needed ( ... ),) } } @@ -252,11 +252,15 @@ public class RestMusicQAPI { @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) throws Exception { + // ,@Context HttpServletResponse response) throws Exception { + // Map<String, Object> valuesMap = insObj.getValues(); // check valuesMap.isEmpty and proceed + // if(valuesMap.isEmpty() ) { // response.addHeader(xLatestVersion, MusicUtil.getVersion()); ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); if (insObj.getValues().isEmpty()) { + // response.status(404); logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) @@ -292,11 +296,13 @@ public class RestMusicQAPI { JsonUpdate updateObj, @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, - @Context UriInfo info) { + @Context UriInfo info) throws Exception { //logger.info(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, + // ErrorTypes.DATAERROR); ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); if (updateObj.getValues().isEmpty()) { + // response.status(404); logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST) @@ -341,10 +347,11 @@ public class RestMusicQAPI { JsonDelete delObj, @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, - @Context UriInfo info) { + @Context UriInfo info) throws Exception { // added checking as per RestMusicDataAPI ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); if (delObj == null) { + // response.status(404); logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) @@ -396,7 +403,6 @@ public class RestMusicQAPI { queryObject = new RestMusicDataAPI().selectSpecificQuery(version, minorVersion, patchVersion, aid, ns, userId, password, keyspace, tablename, info, limit); } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger, "MusicServiceException occured in peek"+ ex); logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR, ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST) @@ -410,7 +416,6 @@ public class RestMusicQAPI { return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS) .setDataResult(MusicCore.marshallResults(results)).toMap()).build(); } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger, "MusicServiceException occured in peek"+ ex); logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR); return response.status(Status.BAD_REQUEST) @@ -447,9 +452,11 @@ public class RestMusicQAPI { @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, @Context UriInfo info) throws Exception { + //int limit = -1; /* * PreparedQueryObject query = new RestMusicDataAPI().selectSpecificQuery(version, minorVersion, * patchVersion, aid, ns, userId, password, keyspace, tablename, info, limit); ResultSet results + * = MusicCore.get(query); return MusicCore.marshallResults(results); */ /* Map<String ,String> auth = new HashMap<>(); String userId =auth.get(MusicUtil.USERID); @@ -485,6 +492,8 @@ public class RestMusicQAPI { @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) throws Exception { + // @Context HttpServletResponse response) throws Exception { + // tabObj never in use & thus no need to verify return new RestMusicDataAPI().dropTable(version, minorVersion, patchVersion, aid, ns, authorization, keyspace, tablename); diff --git a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java b/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java index b9754f61..a5f2ac49 100644 --- a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java @@ -35,6 +35,9 @@ import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; |