aboutsummaryrefslogtreecommitdiffstats
path: root/src/main
diff options
context:
space:
mode:
Diffstat (limited to 'src/main')
-rw-r--r--src/main/java/LICENSE.txt24
-rwxr-xr-xsrc/main/java/org/onap/music/JerseyConfig.java68
-rwxr-xr-xsrc/main/java/org/onap/music/MusicApplication.java138
-rwxr-xr-xsrc/main/java/org/onap/music/authentication/CachingUtil.java445
-rw-r--r--src/main/java/org/onap/music/authentication/CadiAuthFilter.java110
-rw-r--r--src/main/java/org/onap/music/authentication/MusicAAFAuthentication.java183
-rw-r--r--src/main/java/org/onap/music/authentication/MusicAuthenticator.java62
-rw-r--r--src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java90
-rw-r--r--src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java357
-rw-r--r--src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java198
-rw-r--r--src/main/java/org/onap/music/datastore/Condition.java52
-rwxr-xr-xsrc/main/java/org/onap/music/datastore/MusicDataStore.java592
-rw-r--r--src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java112
-rw-r--r--src/main/java/org/onap/music/datastore/PreparedQueryObject.java128
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/AAFResponse.java46
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java37
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java90
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java140
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java78
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java53
-rwxr-xr-xsrc/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java94
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java61
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java135
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java141
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/NameSpace.java48
-rw-r--r--src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java111
-rw-r--r--src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java384
-rw-r--r--src/main/java/org/onap/music/eelf/logging/format/AppMessages.java188
-rw-r--r--src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java107
-rw-r--r--src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java38
-rw-r--r--src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java46
-rw-r--r--src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java54
-rw-r--r--src/main/java/org/onap/music/exceptions/MusicLockingException.java75
-rw-r--r--src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java82
-rw-r--r--src/main/java/org/onap/music/exceptions/MusicQueryException.java90
-rw-r--r--src/main/java/org/onap/music/exceptions/MusicServiceException.java88
-rw-r--r--src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java254
-rw-r--r--src/main/java/org/onap/music/lockingservice/cassandra/MusicLockState.java138
-rw-r--r--src/main/java/org/onap/music/main/MusicCore.java162
-rw-r--r--src/main/java/org/onap/music/main/MusicDigest.java79
-rwxr-xr-xsrc/main/java/org/onap/music/main/MusicUtil.java846
-rw-r--r--src/main/java/org/onap/music/main/PropertiesLoader.java187
-rw-r--r--src/main/java/org/onap/music/main/ResultType.java42
-rw-r--r--src/main/java/org/onap/music/main/ReturnType.java75
-rw-r--r--src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java279
-rw-r--r--src/main/java/org/onap/music/rest/Application.java79
-rwxr-xr-xsrc/main/java/org/onap/music/rest/RestMusicAdminAPI.java496
-rwxr-xr-xsrc/main/java/org/onap/music/rest/RestMusicDataAPI.java1531
-rw-r--r--src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java112
-rw-r--r--src/main/java/org/onap/music/rest/RestMusicLocksAPI.java457
-rwxr-xr-xsrc/main/java/org/onap/music/rest/RestMusicQAPI.java452
-rw-r--r--src/main/java/org/onap/music/rest/RestMusicTestAPI.java68
-rw-r--r--src/main/java/org/onap/music/rest/RestMusicVersionAPI.java64
-rw-r--r--src/main/java/org/onap/music/service/MusicCoreService.java110
-rw-r--r--src/main/java/org/onap/music/service/impl/MusicCassaCore.java709
-rw-r--r--src/main/resources/LICENSE.txt24
-rw-r--r--src/main/resources/Resources.properties50
-rwxr-xr-xsrc/main/resources/application.properties2
-rw-r--r--src/main/resources/cache.ccf62
-rw-r--r--src/main/resources/logback.xml302
-rw-r--r--src/main/resources/project.properties4
61 files changed, 0 insertions, 11329 deletions
diff --git a/src/main/java/LICENSE.txt b/src/main/java/LICENSE.txt
deleted file mode 100644
index cc6cdea5..00000000
--- a/src/main/java/LICENSE.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-
-The following license applies to all files in this and sub-directories. Licenses
-are included in individual source files where appropriate, and if it differs
-from this text, it supersedes this. Any file that does not have license text
-defaults to being covered by this text; not all files support the addition of
-licenses.
-#
-# -------------------------------------------------------------------------
-# 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.
-#
-# -------------------------------------------------------------------------
-# \ No newline at end of file
diff --git a/src/main/java/org/onap/music/JerseyConfig.java b/src/main/java/org/onap/music/JerseyConfig.java
deleted file mode 100755
index 1b5f034a..00000000
--- a/src/main/java/org/onap/music/JerseyConfig.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2012-2015 the original author or authors.
- *
- * 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.
- */
-
-package org.onap.music;
-
-import io.swagger.jaxrs.config.BeanConfig;
-import io.swagger.jaxrs.listing.ApiListingResource;
-import io.swagger.jaxrs.listing.SwaggerSerializers;
-import org.glassfish.jersey.server.ResourceConfig;
-import org.onap.music.rest.*;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.PostConstruct;
-
-@Component public class JerseyConfig extends ResourceConfig {
-
- @Value("${spring.jersey.application-path:/}") private String apiPath;
-
- public JerseyConfig() {
- this.registerEndpoints();
- }
-
- @PostConstruct public void init() {
- this.configureSwagger();
- }
-
- private void registerEndpoints() {
- register(RestMusicAdminAPI.class);
- register(RestMusicDataAPI.class);
- register(RestMusicLocksAPI.class);
- register(RestMusicQAPI.class);
- register(RestMusicTestAPI.class);
- register(RestMusicVersionAPI.class);
- register(RestMusicHealthCheckAPI.class);
- }
-
- private void configureSwagger() {
- //Available at localhost:port/swagger.json
- this.register(ApiListingResource.class);
- this.register(SwaggerSerializers.class);
-
- BeanConfig config = new BeanConfig();
- config.setConfigId("MUSIC");
- config.setTitle("MUSIC");
- config.setVersion("v2");
- config.setContact("Thomas Nelson");
- config.setSchemes(new String[] {"http", "https"});
- config.setBasePath("/MUSIC/rest");
- config.setResourcePackage("org.onap.music");
- config.setPrettyPrint(true);
- config.setScan(true);
- }
-
-}
diff --git a/src/main/java/org/onap/music/MusicApplication.java b/src/main/java/org/onap/music/MusicApplication.java
deleted file mode 100755
index e6fee58f..00000000
--- a/src/main/java/org/onap/music/MusicApplication.java
+++ /dev/null
@@ -1,138 +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;
-
-
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-
-import org.onap.aaf.cadi.PropAccess;
-import org.onap.music.authentication.CadiAuthFilter;
-import org.onap.music.main.MusicUtil;
-import org.onap.music.main.PropertiesLoader;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
-import org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration;
-import org.springframework.boot.builder.SpringApplicationBuilder;
-import org.springframework.boot.web.servlet.FilterRegistrationBean;
-//import org.springframework.boot.web.support.SpringBootServletInitializer;
-import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.DependsOn;
-import org.springframework.scheduling.annotation.EnableScheduling;
-import org.springframework.web.context.request.RequestContextListener;
-
-
-@SpringBootApplication(scanBasePackages = { "org.onap.music.rest"})
-@EnableAutoConfiguration(exclude={CassandraDataAutoConfiguration.class})
-@ComponentScan(value = {"org.onap.music"})
-@EnableScheduling
-public class MusicApplication extends SpringBootServletInitializer {
-
- @Autowired
- PropertiesLoader propertyLoader;
-
-
- public static void main(String[] args) {
- System.setProperty("AFT_DME2_CLIENT_IGNORE_SSL_CONFIG","false");
- System.setProperty("AFT_DME2_CLIENT_KEYSTORE","/opt/app/music/etc/truststore2018.jks");
- System.setProperty("AFT_DME2_CLIENT_KEYSTORE_PASSWORD","changeit");
- System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS","TLSv1.1,TLSv1.2");
- new MusicApplication().configure(new SpringApplicationBuilder(MusicApplication.class)).run(args);
- }
-
- @Override
- protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
-
- return application.sources(MusicApplication.class);
- }
-
-
- @Bean("loadProperties")
- public void loadProperties() {
- propertyLoader.loadProperties();
- }
-
- @Autowired
- private ApplicationContext appContext;
-
- @Bean
- @DependsOn("loadProperties")
- public PropAccess propAccess() {
- if(MusicUtil.getIsCadi())
- return new PropAccess(new String[] { "cadi_prop_files=/opt/app/music/etc/cadi.properties" });
- else
- return null;
- }
-
- @Bean(name = "cadiFilter")
- @DependsOn("loadProperties")
- public Filter cadiFilter() throws ServletException {
- propertyLoader.loadProperties();
- if(MusicUtil.getIsCadi()) {
- PropAccess propAccess = propAccess();
- CadiAuthFilter cadiFilter = new CadiAuthFilter(propAccess);
- return cadiFilter;
- } else
- return (ServletRequest request, ServletResponse response, FilterChain chain) -> {
- //do nothing for now.
- };
-
- }
-
- @Bean
- @DependsOn("loadProperties")
- public FilterRegistrationBean<Filter> cadiFilterRegistration() throws ServletException {
- FilterRegistrationBean<Filter> frb = new FilterRegistrationBean<>();
- frb.setFilter(cadiFilter());
- // The Following Patterns are used to control what APIs will be secure
- // TODO: Make this a configurable item. Build this from an array?
- if(MusicUtil.getIsCadi()) {
- frb.addUrlPatterns(
- "/v2/keyspaces/*",
- "/v2/locks/*",
- "/v3/locks/*",
- "/v2/priorityq/*",
- "/v2/admin/*"
- );
- } else {
- frb.addUrlPatterns("/v0/test");
- }
- frb.setName("cadiFilter");
- frb.setOrder(0);
- return frb;
- }
-
- @Bean
- @ConditionalOnMissingBean(RequestContextListener.class)
- public RequestContextListener requestContextListener() {
- return new RequestContextListener();
- }
-}
diff --git a/src/main/java/org/onap/music/authentication/CachingUtil.java b/src/main/java/org/onap/music/authentication/CachingUtil.java
deleted file mode 100755
index 5c379c6e..00000000
--- a/src/main/java/org/onap/music/authentication/CachingUtil.java
+++ /dev/null
@@ -1,445 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * ===================================================================
- * Modifications Copyright (c) 2018 IBM
- * Modifications Copyright (c) 2019 Samsung
- * ===================================================================
- * 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.authentication;
-
-import java.util.Calendar;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import javax.ws.rs.core.MediaType;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.jcs.JCS;
-import org.apache.commons.jcs.access.CacheAccess;
-import org.mindrot.jbcrypt.BCrypt;
-import org.onap.music.authentication.MusicAuthenticator.Operation;
-import org.onap.music.datastore.PreparedQueryObject;
-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.exceptions.MusicServiceException;
-import org.onap.music.main.MusicCore;
-import org.onap.music.main.MusicUtil;
-import com.datastax.driver.core.DataType;
-import com.datastax.driver.core.PreparedStatement;
-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;
-
-/**
- * All Caching related logic is handled by this class and a schedule cron runs to update cache.
- *
- * @author Vikram
- *
- */
-public class CachingUtil implements Runnable {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
-
- /** keyspace & ns */
- private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
- /** cache to hold isaaf application */
- private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
- /** hold user creds for namespace */
- private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
- private static Map<String, Number> userAttempts = new HashMap<>();
- private static Map<String, Calendar> lastFailedTime = new HashMap<>();
- private static CacheAccess<String, String> adminUserCache = JCS.getInstance("adminUserCache");
-
- public static CacheAccess<String, String> getAdminUserCache() {
- return adminUserCache;
- }
-
- public static void updateAdminUserCache(String authorization,String userId) {
- adminUserCache.put(authorization,userId);
- }
-
- private static final String USERNAME="username";
- private static final String PASSWORD="password";
-
-
- public void initializeAafCache() throws MusicServiceException {
- logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
-
- String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(query);
- try {
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
- } catch (Exception e1) {
- logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- }
- ResultSet rs = MusicCore.get(pQuery);
- Iterator<Row> it = rs.iterator();
- Map<String, String> map = null;
- while (it.hasNext()) {
- Row row = it.next();
- String nameSpace = row.getString("keyspace_name");
- String userId = row.getString(USERNAME);
- String password = row.getString(PASSWORD);
- String keySpace = row.getString("application_name");
- try {
- userAttempts.put(nameSpace, 0);
- boolean responseObj = triggerAAF(nameSpace, userId, password);
- if (responseObj) {
- map = new HashMap<>();
- map.put(userId, password);
- musicValidateCache.put(nameSpace, map);
- musicCache.put(keySpace, nameSpace);
- logger.debug("Cronjob: Cache Updated with AAF response for namespace "
- + nameSpace);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
- }
- }
-
- }
-
- @Override
- public void run() {
- logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
- try {
- initializeAafCache();
- } catch (MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
- }
- }
-
- public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
- String keySpace) throws Exception {
-
- if (musicValidateCache.get(nameSpace) != null && musicCache.get(keySpace)!=null) {
- if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
- } else if (musicValidateCache.get(nameSpace).get(userId).equals(password)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
- // reset invalid attempts to 0
- userAttempts.put(nameSpace, 0);
- return true;
- } else {
- // call AAF update cache with new password
- if (userAttempts.get(nameSpace) == null)
- userAttempts.put(nameSpace, 0);
- if ((Integer) userAttempts.get(nameSpace) >= 3) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
- logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
- Calendar calendar = Calendar.getInstance();
- long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
- logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
- if( delayTime > 120000) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
- userAttempts.put(nameSpace, 0);
- } else {
- logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
- throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
- }
- }
- logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
- }
- }
-
- boolean responseObj = false;
- try {
- responseObj = triggerAAF(nameSpace, userId, password);
- }catch (Exception ex) {
- logger.info("Exception while trigger aaf");
- logger.info("Exception: " + ex.getMessage());
- throw new Exception("Exception raised while triggering AAF authentication" +ex.getMessage());
- }
- if (responseObj) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Valid user. Cache is updated for "+nameSpace);
- Map<String, String> map = new HashMap<>();
- map.put(userId, password);
- musicValidateCache.put(nameSpace, map);
- musicCache.put(keySpace, nameSpace);
- return true;
- }
- logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
- return false;
- }
-
- private static boolean triggerAAF(String nameSpace, String userId, String password)
- throws Exception {
- logger.info(EELFLoggerDelegate.applicationLogger,"Inside AAF authorization");
- if (MusicUtil.getAafEndpointUrl() == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"AAF endpoint is not set. Please specify in the properties file.",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
- }
- Client client = Client.create();
- // WebResource webResource =
- // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
- WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
- String plainCreds = userId + ":" + password;
- byte[] plainCredsBytes = plainCreds.getBytes();
- byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
- String base64Creds = new String(base64CredsBytes);
-
- ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
- .header("Authorization", "Basic " + base64Creds)
- .header("content-type", "application/json").get(ClientResponse.class);
- logger.info(EELFLoggerDelegate.applicationLogger, "aaf response: "+response.toString());
- if (response.getStatus() != 200) {
- if (userAttempts.get(nameSpace) == null)
- userAttempts.put(nameSpace, 0);
- if ((Integer) userAttempts.get(nameSpace) >= 2) {
- lastFailedTime.put(nameSpace, Calendar.getInstance());
- userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
- throw new Exception(
- "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
- }
- userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
- throw new Exception(
- "Unable to authenticate. Please check the AAF credentials against namespace.");
- // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
- // for specific time.
- }
- /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
- Arrays.asList(MediaType.APPLICATION_JSON));
- // AAFResponse output = response.getEntity(AAFResponse.class);
- response.bufferEntity();
- String x = response.getEntity(String.class);
- AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/
-
- return true;
- }
-
- public static void updateMusicCache(String keyspace, String nameSpace) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
- musicCache.put(keyspace, nameSpace);
- }
-
- public static void updateCadiCache(String user, String keyspace) {
- musicCache.put(user, keyspace);
- }
-
- public static String getKSFromCadiCache(String user) {
- return musicCache.get(user);
- }
-
- public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
- Map<String, String> map = new HashMap<>();
- map.put(userId, password);
- musicValidateCache.put(nameSpace, map);
- }
-
- public static void updateisAAFCache(String namespace, String isAAF) {
- appNameCache.put(namespace, isAAF);
- }
-
- public static String isAAFApplication(String namespace) throws MusicServiceException {
- String isAAF = appNameCache.get(namespace);
- if (isAAF == null) {
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "SELECT is_aaf from admin.keyspace_master where application_name = '"
- + namespace + "' allow filtering");
- Row rs = null;
- try {
- rs = MusicCore.get(pQuery).one();
- } catch(InvalidQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
- throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
- }
- try {
- isAAF = String.valueOf(rs.getBool("is_aaf"));
- if(isAAF != null)
- appNameCache.put(namespace, isAAF);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- }
- }
- return isAAF;
- }
-
- public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
- String uuid = null;
- if (uuid == null) {
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "SELECT uuid from admin.keyspace_master where keyspace_name = '"
- + keyspace + "' allow filtering");
- Row rs = MusicCore.get(pQuery).one();
- try {
- uuid = rs.getUUID("uuid").toString();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,"Exception occurred during uuid retrieval from DB."+e.getMessage());
- }
- }
- return uuid;
- }
-
- public static String getAppName(String keyspace) throws MusicServiceException {
- String appName = null;
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "SELECT application_name from admin.keyspace_master where keyspace_name = '"
- + keyspace + "' allow filtering");
- Row rs = MusicCore.get(pQuery).one();
- try {
- appName = rs.getString("application_name");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- }
- return appName;
- }
-
- @Deprecated
- public static Map<String, Object> validateRequest(String nameSpace, String userId,
- String password, String keyspace, String aid, String operation) {
- Map<String, Object> resultMap = new HashMap<>();
- if (!"createKeySpace".equals(operation)) {
- if (nameSpace == null) {
- resultMap.put("Exception", "Application namespace is mandatory.");
- }
- }
- return resultMap;
- }
-
- public static Map<String, Object> validateRequest(String nameSpace, String userId,
- String password, String keyspace, String aid, Operation operation) {
- Map<String, Object> resultMap = new HashMap<>();
- if (Operation.CREATE_KEYSPACE!=operation) {
- if (nameSpace == null) {
- resultMap.put("Exception", "Application namespace is mandatory.");
- }
- }
- return resultMap;
- }
-
- public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
- Map<String, Object> resultMap = new HashMap<>();
- if (ns == null || userId == null || password == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
- resultMap.put("Exception",
- "One or more required headers appName(ns), userId, password is missing. Please check.");
- return resultMap;
- }
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString(
- "select * from admin.keyspace_master where application_name = ? allow filtering");
- try {
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
- } catch(Exception e) {
- resultMap.put("Exception",
- "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
- return resultMap;
- }
- Row rs = null;
- try {
- rs = MusicCore.get(queryObject).one();
- } catch (MusicServiceException e) {
- String errorMsg = "Unable to process operation. Error is "+e.getMessage();
- logger.error(EELFLoggerDelegate.errorLogger, errorMsg);
- resultMap.put("Exception", errorMsg);
- return resultMap;
- } catch (InvalidQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
- resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
- return resultMap;
- }
- if (rs == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
- resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
- } else {
- if(!(rs.getString(USERNAME).equals(userId)) || !(BCrypt.checkpw(password, rs.getString(PASSWORD)))) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
- resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
- return resultMap;
- }
- }
- return resultMap;
- }
-
- public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
- String keyspace) {
- Map<String, Object> resultMap = new HashMap<>();
- String pwd = null;
- if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null)
- && (musicValidateCache.get(nameSpace).containsKey(userId))) {
- if(!musicCache.get(keyspace).equals(nameSpace)) {
- resultMap.put("Exception", "Namespace and keyspace doesn't match");
- return resultMap;
- }
- if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
- resultMap.put("Exception", "Namespace, userId and password doesn't match");
- return resultMap;
- }
- return resultMap;
- }
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString(
- "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
- try {
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,"Adding value to query object failed: " + e.getMessage());
- }
- Row rs = null;
- try {
- rs = MusicCore.get(queryObject).one();
- } catch (MusicServiceException e) {
- String errMsg = "Unable to process operation. Error is "+e.getMessage();
- logger.error(EELFLoggerDelegate.errorLogger, errMsg);
- resultMap.put("Exception", errMsg);
- return resultMap;
- }
- if(rs == null) {
- resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
- return resultMap;
- }
- else {
- String user = rs.getString(USERNAME);
- pwd = rs.getString(PASSWORD);
- String ns = rs.getString("application_name");
- if(!ns.equals(nameSpace)) {
- resultMap.put("Exception", "Namespace and keyspace doesn't match");
- return resultMap;
- }
- if(!user.equals(userId)) {
- resultMap.put("Exception", "Invalid userId :"+userId);
- return resultMap;
- }
- if(!BCrypt.checkpw(password, pwd)) {
- resultMap.put("Exception", "Invalid password");
- return resultMap;
- }
- }
- CachingUtil.updateMusicCache(keyspace, nameSpace);
- CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);
- return resultMap;
- }
-}
diff --git a/src/main/java/org/onap/music/authentication/CadiAuthFilter.java b/src/main/java/org/onap/music/authentication/CadiAuthFilter.java
deleted file mode 100644
index 56371c7d..00000000
--- a/src/main/java/org/onap/music/authentication/CadiAuthFilter.java
+++ /dev/null
@@ -1,110 +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.authentication;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.http.HttpServletRequest;
-
-import com.att.eelf.configuration.EELFLogger;
-import org.onap.aaf.cadi.CadiWrap;
-import org.onap.aaf.cadi.Permission;
-import org.onap.aaf.cadi.PropAccess;
-import org.onap.aaf.cadi.aaf.AAFPermission;
-import org.onap.aaf.cadi.filter.CadiFilter;
-import org.onap.music.eelf.logging.EELFLoggerDelegate;
-import org.onap.music.main.MusicCore;
-
-public class CadiAuthFilter extends CadiFilter {
-
- private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CadiAuthFilter.class);
-
- public CadiAuthFilter(PropAccess access) throws ServletException {
- super(true, access);
- }
-
- public void init(FilterConfig filterConfig) throws ServletException {
- super.init(filterConfig);
- }
-
-
- private boolean matchPattern(String requestedPath, String includeUrl) {
- includeUrl = includeUrl.substring(1);
- String[] path = requestedPath.split("/");
- if (path.length > 1) {
- String[] roleFunctionArray = includeUrl.split("/");
- boolean match = true;
- for (int i = 0; i < roleFunctionArray.length; i++) {
- if (match) {
- if (!"*".equals(roleFunctionArray[i])) {
- Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
- Matcher m = p.matcher(roleFunctionArray[i]);
- match = m.matches();
- } else if (roleFunctionArray[i].equals("*")) {
- match = true;
- }
-
- }
- }
- if (match)
- return match;
- } else {
- if (requestedPath.matches(includeUrl))
- return true;
- else if ("*".equals(includeUrl))
- return true;
- }
- return false;
- }
-
-
- public static List<AAFPermission> getAAFPermissions(HttpServletRequest request) {
- CadiWrap wrapReq = (CadiWrap) request;
- List<Permission> perms = wrapReq.getPermissions(wrapReq.getUserPrincipal());
- List<AAFPermission> aafPermsList = new ArrayList<>();
- for (Permission perm : perms) {
- AAFPermission aafPerm = (AAFPermission) perm;
- aafPermsList.add(aafPerm);
- logger.info(aafPerm.toString());
- logger.info(aafPerm.getType());
- }
- return aafPermsList;
- }
-
- public static List<AAFPermission> getAAFPermissions(ServletRequest request) {
- CadiWrap wrapReq = (CadiWrap) request;
- List<Permission> perms = wrapReq.getPermissions(wrapReq.getUserPrincipal());
- List<AAFPermission> aafPermsList = new ArrayList<>();
- for (Permission perm : perms) {
- AAFPermission aafPerm = (AAFPermission) perm;
- aafPermsList.add(aafPerm);
- }
- return aafPermsList;
- }
-
-} \ No newline at end of file
diff --git a/src/main/java/org/onap/music/authentication/MusicAAFAuthentication.java b/src/main/java/org/onap/music/authentication/MusicAAFAuthentication.java
deleted file mode 100644
index 2d0d4e59..00000000
--- a/src/main/java/org/onap/music/authentication/MusicAAFAuthentication.java
+++ /dev/null
@@ -1,183 +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.authentication;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.ws.rs.core.MediaType;
-
-import org.apache.commons.jcs.access.CacheAccess;
-import org.onap.music.datastore.PreparedQueryObject;
-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.exceptions.MusicServiceException;
-import org.onap.music.authentication.MusicAuthenticator.Operation;
-import org.onap.music.main.MusicCore;
-import org.onap.music.main.MusicUtil;
-
-import com.datastax.driver.core.DataType;
-import com.datastax.driver.core.Row;
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource;
-
-public class MusicAAFAuthentication implements MusicAuthenticator {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicAAFAuthentication.class);
-
- @Override
- public boolean authenticateAdmin(String authorization) {
- logger.info(EELFLoggerDelegate.applicationLogger, "MusicCore.authenticateAdmin: ");
- String userId = MusicUtil.extractBasicAuthentication(authorization).get(MusicUtil.USERID);
- if(MusicUtil.getIsCadi()) {
- CachingUtil.updateAdminUserCache(authorization, userId);
- return true;
- }
- CacheAccess<String, String> adminCache = CachingUtil.getAdminUserCache();
- if (authorization == null) {
- logger.error(EELFLoggerDelegate.errorLogger, "Authorization cannot be empty...");
- return false;
- }
- if (adminCache.get(authorization) != null && adminCache.get(authorization).equals(userId)) {
- logger.info(EELFLoggerDelegate.applicationLogger, "MusicCore.authenticateAdmin: Validated against admincache.. ");
- return true;
- }
- else {
- Client client = Client.create();
- String aafUrl = MusicUtil.getAafAdminUrl();
- if (aafUrl==null) {
- logger.error(EELFLoggerDelegate.errorLogger, "Admin url is not set, please set in properties");
- return false;
- }
-
- WebResource webResource = client.resource(
- MusicUtil.getAafAdminUrl().concat(userId).concat("/").concat(MusicUtil.getAdminAafRole()));
-
- ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
- .header("Authorization", authorization).get(ClientResponse.class);
- if (response.getStatus() == 200) {
- CachingUtil.updateAdminUserCache(authorization, userId);
- return true;
- }
- }
- return false;
- }
-
- @Override
- public boolean authenticateUser(String namespace, String authorization, String keyspace,
- String aid, Operation operation) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Inside User Authentication.......");
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
-
- Map<String, Object> resultMap = new HashMap<>();
- String uuid = null;
- if(! MusicUtil.getIsCadi()) {
- resultMap = CachingUtil.validateRequest(namespace, userId, password, keyspace, aid,
- operation);
- if (!resultMap.isEmpty())
- return false;
- String isAAFApp = null;
- try {
- isAAFApp= CachingUtil.isAAFApplication(namespace);
- } catch(MusicServiceException e) {
- logger.error(e.getErrorMessage(), e);
- resultMap.put("Exception", e.getMessage());
- return false;
- }
- if(isAAFApp == null) {
- resultMap.put("Exception", "Namespace: "+namespace+" doesn't exist. Please make sure ns(appName)"
- + " is correct and Application is onboarded.");
- return false;
- }
- boolean isAAF = Boolean.parseBoolean(isAAFApp);
- if (userId == null || password == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- logger.error(EELFLoggerDelegate.errorLogger,"UserId/Password or more required headers is missing.");
- resultMap.put("Exception",
- "UserId and Password are mandatory for the operation " + operation);
- return false;
- }
- if(!isAAF && !(operation==Operation.CREATE_KEYSPACE)) {
- resultMap = CachingUtil.authenticateAIDUser(namespace, userId, password, keyspace);
- if (!resultMap.isEmpty())
- return false;
-
- }
- if (isAAF && namespace != null && userId != null && password != null) {
- boolean isValid = true;
- try {
- isValid = CachingUtil.authenticateAAFUser(namespace, userId, password, keyspace);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,"Error while aaf authentication for user:" + userId);
- logger.error(EELFLoggerDelegate.errorLogger,"Error: "+ e.getMessage());
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- logger.error(EELFLoggerDelegate.errorLogger,"Got exception while AAF authentication for namespace " + namespace);
- resultMap.put("Exception", e.getMessage());
- }
- if (!isValid) {
- logger.error(EELFLoggerDelegate.errorLogger,"User not authenticated...", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- resultMap.put("Exception", "User not authenticated...");
- }
- if (!resultMap.isEmpty())
- return false;
-
- }
- } else {
-
- String cachedKS = CachingUtil.getKSFromCadiCache(userId);
- if(cachedKS != null && !cachedKS.equals(keyspace)) {
- resultMap.put("Exception", "User not authenticated to access this keyspace...");
- return false;
- }
- }
-
- if (operation==Operation.CREATE_KEYSPACE) {
- try {
- logger.info(EELFLoggerDelegate.applicationLogger,"AID is not provided. Creating new UUID for keyspace.");
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "select uuid from admin.keyspace_master where application_name=? and username=? and keyspace_name=? allow filtering");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), namespace));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),
- MusicUtil.DEFAULTKEYSPACENAME));
- Row rs = MusicCore.get(pQuery).one();
- uuid = rs.getUUID("uuid").toString();
- resultMap.put("uuid", "existing");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.applicationLogger,"No UUID found in DB. So creating new UUID.");
- uuid = MusicUtil.generateUUID();
- resultMap.put("uuid", "new");
- }
- resultMap.put("aid", uuid);
- CachingUtil.updateCadiCache(userId, keyspace);
- }
- return true;
- }
-
-}
diff --git a/src/main/java/org/onap/music/authentication/MusicAuthenticator.java b/src/main/java/org/onap/music/authentication/MusicAuthenticator.java
deleted file mode 100644
index 78f76ab1..00000000
--- a/src/main/java/org/onap/music/authentication/MusicAuthenticator.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2019 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.authentication;
-
-public interface MusicAuthenticator {
- public enum Operation{
- CREATE_KEYSPACE,
- DROP_KEYSPACE,
- CREATE_TABLE,
- CREATE_INDEX,
- INSERT_INTO_TABLE,
- UPDATE_TABLE,
- DELETE_FROM_TABLE,
- DROP_TABLE,
- SELECT_CRITICAL,
- SELECT,
- CREATE_LOCKREF,
- ACQUIRE_LOCK,
- CURRENT_LOCK,
- DELETE_LOCK
- }
-
- /**
- * Authenticate a user account
- * @param namespace - user's namespace
- * @param authorization - basicAuth representation of username/password
- * @param keyspace - keyspace user is trying to access
- * @param aid - aid that identifies the user
- * @param operation - operation that user is trying to do
- * @return true if user has access
- */
- public boolean authenticateUser(String namespace, String authorization,
- String keyspace, String aid, Operation operation);
-
- /**
- * Authenticate an administrative account
- * @param authorization - basicAuth representation of username/password
- * @return true if user has admin privileges
- */
- public boolean authenticateAdmin(String authorization);
-
-}
diff --git a/src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java b/src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java
deleted file mode 100644
index 4efcabea..00000000
--- a/src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java
+++ /dev/null
@@ -1,90 +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.conductor.conditionals;
-
-import java.io.Serializable;
-import java.util.Map;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-import io.swagger.annotations.ApiModel;
-
-@ApiModel(value = "JsonConditional", description = "Json model for insert or update into table based on some conditions")
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class JsonConditional implements Serializable {
-
- private String primaryKey;
- private String primaryKeyValue;
- private String casscadeColumnName;
- private Map<String,Object> tableValues;
- private Map<String,Object> casscadeColumnData;
- private Map<String,Map<String,String>> conditions;
-
- public Map<String, Object> getTableValues() {
- return tableValues;
- }
- public void setTableValues(Map<String, Object> tableValues) {
- this.tableValues = tableValues;
- }
-
- public String getPrimaryKey() {
- return primaryKey;
- }
- public String getPrimaryKeyValue() {
- return primaryKeyValue;
- }
- public String getCasscadeColumnName() {
- return casscadeColumnName;
- }
-
- public Map<String, Object> getCasscadeColumnData() {
- return casscadeColumnData;
- }
-
-
-
- public void setPrimaryKey(String primaryKey) {
- this.primaryKey = primaryKey;
- }
- public void setPrimaryKeyValue(String primaryKeyValue) {
- this.primaryKeyValue = primaryKeyValue;
- }
- public Map<String, Map<String, String>> getConditions() {
- return conditions;
- }
- public void setConditions(Map<String, Map<String, String>> conditions) {
- this.conditions = conditions;
- }
- public void setCasscadeColumnName(String casscadeColumnName) {
- this.casscadeColumnName = casscadeColumnName;
- }
-
- public void setCasscadeColumnData(Map<String, Object> casscadeColumnData) {
- this.casscadeColumnData = casscadeColumnData;
- }
-
-
-
-
-
-} \ No newline at end of file
diff --git a/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java b/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java
deleted file mode 100644
index 045abd98..00000000
--- a/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java
+++ /dev/null
@@ -1,357 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * Modifications Copyright (C) 2019 IBM.
- * ===================================================================
- * 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.conductor.conditionals;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.codehaus.jettison.json.JSONObject;
-import org.onap.music.datastore.MusicDataStoreHandle;
-import org.onap.music.datastore.PreparedQueryObject;
-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.exceptions.MusicLockingException;
-import org.onap.music.exceptions.MusicQueryException;
-import org.onap.music.exceptions.MusicServiceException;
-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.rest.RestMusicDataAPI;
-
-import com.datastax.driver.core.ColumnDefinitions;
-import com.datastax.driver.core.DataType;
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Row;
-import com.datastax.driver.core.TableMetadata;
-
-public class MusicConditional {
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicDataAPI.class);
-
- public static ReturnType conditionalInsert(String keyspace, String tablename, String casscadeColumnName,
- Map<String, Object> casscadeColumnData, String primaryKey, Map<String, Object> valuesMap,
- Map<String, String> status) throws Exception {
-
- Map<String, PreparedQueryObject> queryBank = new HashMap<>();
- TableMetadata tableInfo = null;
- tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename);
- DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType();
- String primaryId = tableInfo.getPrimaryKey().get(0).getName();
- DataType casscadeColumnType = tableInfo.getColumn(casscadeColumnName).getType();
- String vector = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
-
- PreparedQueryObject select = new PreparedQueryObject();
- select.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " where " + primaryId + " = ?");
- select.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKey));
- queryBank.put(MusicUtil.SELECT, select);
-
- PreparedQueryObject update = new PreparedQueryObject();
- //casscade column values
- Map<String, String> updateColumnvalues = getValues(true, casscadeColumnData, status);
- Object formatedValues = MusicUtil.convertToActualDataType(casscadeColumnType, updateColumnvalues);
- update.appendQueryString("UPDATE " + keyspace + "." + tablename + " SET " + casscadeColumnName + " ="
- + casscadeColumnName + " + ? , vector_ts = ?" + " WHERE " + primaryId + " = ? ");
- update.addValue(formatedValues);
- update.addValue(MusicUtil.convertToActualDataType(DataType.text(), vector));
- update.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKey));
- queryBank.put(MusicUtil.UPDATE, update);
-
-
- //casscade column values
- Map<String, String> insertColumnvalues = getValues(false, casscadeColumnData, status);
- formatedValues = MusicUtil.convertToActualDataType(casscadeColumnType, insertColumnvalues);
- PreparedQueryObject insert = extractQuery(valuesMap, tableInfo, tablename, keyspace, primaryId, primaryKey,casscadeColumnName,formatedValues);
- queryBank.put(MusicUtil.INSERT, insert);
-
-
- String key = keyspace + "." + tablename + "." + primaryKey;
- String lockId = MusicCore.createLockReference(key);
- long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
- ReturnType lockAcqResult = MusicCore.acquireLockWithLease(key, lockId, leasePeriod);
-
- try {
- if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
- ReturnType criticalPutResult = conditionalInsertAtomic(lockId, keyspace, tablename, primaryKey,
- queryBank);
- MusicCore.destroyLockRef(lockId);
- if (criticalPutResult.getMessage().contains("insert"))
- criticalPutResult
- .setMessage("Insert values: ");
- else if (criticalPutResult.getMessage().contains("update"))
- criticalPutResult
- .setMessage("Update values: " + updateColumnvalues);
- return criticalPutResult;
-
- } else {
- MusicCore.destroyLockRef(lockId);
- return lockAcqResult;
- }
- } catch (Exception e) {
- MusicCore.destroyLockRef(lockId);
- return new ReturnType(ResultType.FAILURE, e.getMessage());
- }
-
- }
-
- public static ReturnType conditionalInsertAtomic(String lockId, String keyspace, String tableName,
- String primaryKey, Map<String, PreparedQueryObject> queryBank) {
-
- ResultSet results = null;
-
- try {
- String fullyQualifiedKey = keyspace + "." + tableName + "." + primaryKey;
- ReturnType lockAcqResult = MusicCore.acquireLock(fullyQualifiedKey, lockId);
- if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
- try {
- results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(queryBank.get(MusicUtil.SELECT));
- } catch (Exception e) {
- return new ReturnType(ResultType.FAILURE, e.getMessage());
- }
- if (results.all().isEmpty()) {
- MusicDataStoreHandle.getDSHandle().executePut(queryBank.get(MusicUtil.INSERT), "critical");
- return new ReturnType(ResultType.SUCCESS, "insert");
- } else {
- MusicDataStoreHandle.getDSHandle().executePut(queryBank.get(MusicUtil.UPDATE), "critical");
- return new ReturnType(ResultType.SUCCESS, "update");
- }
- } else {
- return new ReturnType(ResultType.FAILURE,
- "Cannot perform operation since you are the not the lock holder");
- }
-
- } catch (Exception e) {
- StringWriter sw = new StringWriter();
- e.printStackTrace(new PrintWriter(sw));
- String exceptionAsString = sw.toString();
- return new ReturnType(ResultType.FAILURE,
- "Exception thrown while doing the critical put, check sanctity of the row/conditions:\n"
- + exceptionAsString);
- }
-
- }
-
- public static ReturnType update(Map<String,PreparedQueryObject> queryBank, String keyspace, String tableName, String primaryKey,String primaryKeyValue,String planId,String cascadeColumnName,Map<String,String> cascadeColumnValues) throws MusicLockingException, MusicQueryException, MusicServiceException {
-
- String key = keyspace + "." + tableName + "." + primaryKeyValue;
- String lockId = MusicCore.createLockReference(key);
- long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
- ReturnType lockAcqResult = MusicCore.acquireLockWithLease(key, lockId, leasePeriod);
-
- try {
-
- if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
- ReturnType criticalPutResult = updateAtomic(lockId, keyspace, tableName, primaryKey,primaryKeyValue, queryBank,planId,cascadeColumnValues,cascadeColumnName);
- MusicCore.destroyLockRef(lockId);
- return criticalPutResult;
- } else {
- MusicCore.destroyLockRef(lockId);
- return lockAcqResult;
- }
-
- } catch (Exception e) {
- MusicCore.destroyLockRef(lockId);
- return new ReturnType(ResultType.FAILURE, e.getMessage());
-
- }
- }
-
- public static ReturnType updateAtomic(String lockId, String keyspace, String tableName, String primaryKey,String primaryKeyValue,
- Map<String,PreparedQueryObject> queryBank,String planId,Map<String,String> cascadeColumnValues,String casscadeColumnName) {
- try {
- String fullyQualifiedKey = keyspace + "." + tableName + "." + primaryKeyValue;
- ReturnType lockAcqResult = MusicCore.acquireLock(fullyQualifiedKey, lockId);
-
- if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
- Row row = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(queryBank.get(MusicUtil.SELECT)).one();
-
- if(row != null) {
- Map<String, String> updatedValues = cascadeColumnUpdateSpecific(row, cascadeColumnValues, casscadeColumnName, planId);
- JSONObject json = new JSONObject(updatedValues);
- PreparedQueryObject update = new PreparedQueryObject();
- String vector_ts = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
- update.appendQueryString("UPDATE " + keyspace + "." + tableName + " SET " + casscadeColumnName + "['" + planId
- + "'] = ?, vector_ts = ? WHERE " + primaryKey + " = ?");
- update.addValue(MusicUtil.convertToActualDataType(DataType.text(), json.toString()));
- update.addValue(MusicUtil.convertToActualDataType(DataType.text(), vector_ts));
- update.addValue(MusicUtil.convertToActualDataType(DataType.text(), primaryKeyValue));
- try {
- MusicDataStoreHandle.getDSHandle().executePut(update, "critical");
- } catch (Exception ex) {
- return new ReturnType(ResultType.FAILURE, ex.getMessage());
- }
- }else {
- return new ReturnType(ResultType.FAILURE,"Cannot find data related to key: "+primaryKey);
- }
- MusicDataStoreHandle.getDSHandle().executePut(queryBank.get(MusicUtil.UPSERT), "critical");
- return new ReturnType(ResultType.SUCCESS, "update success");
-
- } else {
- return new ReturnType(ResultType.FAILURE,
- "Cannot perform operation since you are the not the lock holder");
- }
-
- } catch (Exception e) {
- StringWriter sw = new StringWriter();
- e.printStackTrace(new PrintWriter(sw));
- String exceptionAsString = sw.toString();
- return new ReturnType(ResultType.FAILURE,
- "Exception thrown while doing the critical put, check sanctity of the row/conditions:\n"
- + exceptionAsString);
- }
-
- }
-
- @SuppressWarnings("unchecked")
- public static Map<String, String> getValues(boolean isExists, Map<String, Object> casscadeColumnData,
- Map<String, String> status) {
-
- Map<String, String> returnMap = new HashMap<>();
- Object key = casscadeColumnData.get("key");
- String setStatus = "";
- Map<String, String> value = (Map<String, String>) casscadeColumnData.get("value");
-
- if (isExists)
- setStatus = status.get("exists");
- else
- setStatus = status.get("nonexists");
-
- value.put("status", setStatus);
- JSONObject valueJson = new JSONObject(value);
- returnMap.put(key.toString(), valueJson.toString());
- return returnMap;
-
- }
-
- public static PreparedQueryObject extractQuery(Map<String, Object> valuesMap, TableMetadata tableInfo, String tableName,
- String keySpaceName,String primaryKeyName,String primaryKey,String casscadeColumn,Object casscadeColumnValues) throws Exception {
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
- StringBuilder fieldsString = new StringBuilder("(vector_ts"+",");
- StringBuilder valueString = new StringBuilder("(" + "?" + ",");
- String vector = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
- String localPrimaryKey;
- queryObject.addValue(vector);
- if(casscadeColumn!=null && casscadeColumnValues!=null) {
- fieldsString.append(casscadeColumn).append(" ,");
- valueString.append("?,");
- queryObject.addValue(casscadeColumnValues);
- }
-
- int counter = 0;
- for (Map.Entry<String, Object> entry : valuesMap.entrySet()) {
-
- fieldsString.append(entry.getKey());
- Object valueObj = entry.getValue();
- if (primaryKeyName.equals(entry.getKey())) {
- localPrimaryKey = entry.getValue() + "";
- localPrimaryKey = localPrimaryKey.replace("'", "''");
- }
- DataType colType = null;
- try {
- colType = tableInfo.getColumn(entry.getKey()).getType();
- } catch(NullPointerException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() +" Invalid column name : "+entry.getKey(), AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
-
- }
-
- Object formattedValue = null;
- try {
- formattedValue = MusicUtil.convertToActualDataType(colType, valueObj);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- }
-
- valueString.append("?");
- queryObject.addValue(formattedValue);
-
-
- if (counter == valuesMap.size() - 1) {
- fieldsString.append(")");
- valueString.append(")");
- } else {
- fieldsString.append(",");
- valueString.append(",");
- }
- counter = counter + 1;
- }
- queryObject.appendQueryString("INSERT INTO " + keySpaceName + "." + tableName + " "
- + fieldsString + " VALUES " + valueString);
- return queryObject;
- }
-
- public static Object getColValue(Row row, String colName, DataType colType) {
- switch (colType.getName()) {
- case VARCHAR:
- return row.getString(colName);
- case UUID:
- return row.getUUID(colName);
- case VARINT:
- return row.getVarint(colName);
- case BIGINT:
- return row.getLong(colName);
- case INT:
- return row.getInt(colName);
- case FLOAT:
- return row.getFloat(colName);
- case DOUBLE:
- return row.getDouble(colName);
- case BOOLEAN:
- return row.getBool(colName);
- case MAP:
- return row.getMap(colName, String.class, String.class);
- default:
- return null;
- }
- }
-
- @SuppressWarnings("unchecked")
- public static Map<String, String> cascadeColumnUpdateSpecific(Row row, Map<String, String> changeOfStatus,
- String cascadeColumnName, String planId) {
-
- ColumnDefinitions colInfo = row.getColumnDefinitions();
- DataType colType = colInfo.getType(cascadeColumnName);
- Object columnValue = getColValue(row, cascadeColumnName, colType);
-
- Map<String, String> finalValues = new HashMap<>();
- Map<String, String> values = (Map<String, String>) columnValue;
- if (values != null && values.keySet().contains(planId)) {
- String valueString = values.get(planId);
- String tempValueString = valueString.replaceAll("\\{", "").replaceAll("\"", "").replaceAll("\\}", "");
- String[] elements = tempValueString.split(",");
- for (String str : elements) {
- String[] keyValue = str.split(":");
- if ((changeOfStatus.keySet().contains(keyValue[0].replaceAll("\\s", ""))))
- keyValue[1] = changeOfStatus.get(keyValue[0].replaceAll("\\s", ""));
- finalValues.put(keyValue[0], keyValue[1]);
- }
- }
- return finalValues;
-
- }
-
-}
diff --git a/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java b/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java
deleted file mode 100644
index 20fd3150..00000000
--- a/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * ===================================================================
- * Modifications Copyright (c) 2018 IBM
- * ===================================================================
- * 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.conductor.conditionals;
-
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.HeaderParam;
-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.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import javax.ws.rs.core.Response.Status;
-
-import org.codehaus.jettison.json.JSONObject;
-import org.onap.music.datastore.MusicDataStoreHandle;
-import org.onap.music.datastore.PreparedQueryObject;
-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.MusicUtil;
-import org.onap.music.main.ResultType;
-import org.onap.music.main.ReturnType;
-import org.onap.music.response.jsonobjects.JsonResponse;
-import org.onap.music.rest.RestMusicAdminAPI;
-import org.onap.music.authentication.MusicAAFAuthentication;
-import org.onap.music.authentication.MusicAuthenticator;
-import org.onap.music.authentication.MusicAuthenticator.Operation;
-import org.onap.music.conductor.*;
-
-import com.datastax.driver.core.DataType;
-import com.datastax.driver.core.TableMetadata;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiParam;
-
-@Path("/v2/conditional")
-@Api(value = "Conditional Api", hidden = true)
-public class RestMusicConditionalAPI {
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicAdminAPI.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 VERSION = "v2";
-
- private MusicAuthenticator authenticator = new MusicAAFAuthentication();
-
- @POST
- @Path("/insert/keyspaces/{keyspace}/tables/{tablename}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response insertConditional(
- @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version", required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam("Authorization") String authorization,
- @ApiParam(value = "Keyspace Name", required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename,
- JsonConditional jsonObj) throws Exception {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
- if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.INSERT_INTO_TABLE)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- String primaryKey = jsonObj.getPrimaryKey();
- String primaryKeyValue = jsonObj.getPrimaryKeyValue();
- String casscadeColumnName = jsonObj.getCasscadeColumnName();
- Map<String, Object> tableValues = jsonObj.getTableValues();
- Map<String, Object> casscadeColumnData = jsonObj.getCasscadeColumnData();
- Map<String, Map<String, String>> conditions = jsonObj.getConditions();
-
- if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null || tableValues.isEmpty()
- || casscadeColumnData.isEmpty() || conditions.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
- ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE)
- .setError(String.valueOf("One or more input values missing")).toMap()).build();
-
- }
-
- Map<String, Object> valuesMap = new LinkedHashMap<>();
- for (Map.Entry<String, Object> entry : tableValues.entrySet()) {
- valuesMap.put(entry.getKey(), entry.getValue());
- }
-
- Map<String, String> status = new HashMap<>();
- status.put("exists", conditions.get("exists").get("status"));
- status.put("nonexists", conditions.get("nonexists").get("status"));
- ReturnType out = null;
-
- out = MusicConditional.conditionalInsert(keyspace, tablename, casscadeColumnName, casscadeColumnData,
- primaryKeyValue, valuesMap, status);
- return response.status(Status.OK).entity(new JsonResponse(out.getResult()).setMessage(out.getMessage()).toMap())
- .build();
-
- }
-
- @SuppressWarnings("unchecked")
- @PUT
- @Path("/update/keyspaces/{keyspace}/tables/{tablename}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response updateConditional(
- @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version", required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam("Authorization") String authorization,
- @ApiParam(value = "Major Version", required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Major Version", required = true) @PathParam("tablename") String tablename,
- JsonConditional upObj) throws Exception {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
- if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.INSERT_INTO_TABLE)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- String primaryKey = upObj.getPrimaryKey();
- String primaryKeyValue = upObj.getPrimaryKeyValue();
- String casscadeColumnName = upObj.getCasscadeColumnName();
- Map<String, Object> casscadeColumnData = upObj.getCasscadeColumnData();
- Map<String, Object> tableValues = upObj.getTableValues();
-
- if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null
- || casscadeColumnData.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
- ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE)
- .setError(String.valueOf("One or more input values missing")).toMap()).build();
-
- }
-
- String planId = casscadeColumnData.get("key").toString();
- Map<String,String> casscadeColumnValueMap = (Map<String, String>) casscadeColumnData.get("value");
- TableMetadata tableInfo = null;
- tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename);
- DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType();
- String primaryId = tableInfo.getPrimaryKey().get(0).getName();
-
- PreparedQueryObject select = new PreparedQueryObject();
- select.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " where " + primaryId + " = ?");
- select.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKeyValue));
-
- PreparedQueryObject upsert = MusicConditional.extractQuery(tableValues, tableInfo, tablename, keyspace, primaryKey, primaryKeyValue, null, null);
- Map<String,PreparedQueryObject> queryBank = new HashMap<>();
- queryBank.put(MusicUtil.SELECT, select);
- queryBank.put(MusicUtil.UPSERT, upsert);
- ReturnType result = MusicConditional.update(queryBank, keyspace, tablename, primaryKey,primaryKeyValue,planId,casscadeColumnName,casscadeColumnValueMap);
- if (result.getResult() == ResultType.SUCCESS) {
- return response.status(Status.OK)
- .entity(new JsonResponse(result.getResult()).setMessage(result.getMessage()).toMap()).build();
-
- }
- return response.status(Status.BAD_REQUEST)
- .entity(new JsonResponse(result.getResult()).setMessage(result.getMessage()).toMap()).build();
-
- }
-
-} \ No newline at end of file
diff --git a/src/main/java/org/onap/music/datastore/Condition.java b/src/main/java/org/onap/music/datastore/Condition.java
deleted file mode 100644
index 2fd4596a..00000000
--- a/src/main/java/org/onap/music/datastore/Condition.java
+++ /dev/null
@@ -1,52 +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.datastore;
-import java.util.Map;
-
-import org.onap.music.main.MusicCore;
-
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Row;
-
-public class Condition {
- Map<String, Object> conditions;
- PreparedQueryObject selectQueryForTheRow;
-
- public Condition(Map<String, Object> conditions, PreparedQueryObject selectQueryForTheRow) {
- this.conditions = conditions;
- this.selectQueryForTheRow = selectQueryForTheRow;
- }
-
- public boolean testCondition() throws Exception {
- // first generate the row
- ResultSet results = MusicCore.quorumGet(selectQueryForTheRow);
- Row row = null;
- if(results != null) {
- row = results.one();
- }
- if(row == null) {
- throw new Exception(" No data found to update");
- }
- return MusicDataStoreHandle.getDSHandle().doesRowSatisfyCondition(row, conditions);
- }
- } \ No newline at end of file
diff --git a/src/main/java/org/onap/music/datastore/MusicDataStore.java b/src/main/java/org/onap/music/datastore/MusicDataStore.java
deleted file mode 100755
index f58bd831..00000000
--- a/src/main/java/org/onap/music/datastore/MusicDataStore.java
+++ /dev/null
@@ -1,592 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * ===================================================================
- * Modifications Copyright (c) 2018-2019 IBM
- * ===================================================================
- * 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.datastore;
-
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.net.SocketException;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.apache.commons.jcs.access.CacheAccess;
-import org.onap.music.authentication.CachingUtil;
-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.exceptions.MusicQueryException;
-import org.onap.music.exceptions.MusicServiceException;
-import org.onap.music.main.MusicUtil;
-
-import com.codahale.metrics.JmxReporter;
-import com.datastax.driver.core.Cluster;
-import com.datastax.driver.core.ColumnDefinitions;
-import com.datastax.driver.core.ColumnDefinitions.Definition;
-import com.datastax.driver.core.ConsistencyLevel;
-import com.datastax.driver.core.DataType;
-import com.datastax.driver.core.HostDistance;
-import com.datastax.driver.core.KeyspaceMetadata;
-import com.datastax.driver.core.Metadata;
-import com.datastax.driver.core.PoolingOptions;
-import com.datastax.driver.core.PreparedStatement;
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Row;
-import com.datastax.driver.core.Session;
-import com.datastax.driver.core.SimpleStatement;
-import com.datastax.driver.core.TableMetadata;
-import com.datastax.driver.core.exceptions.AlreadyExistsException;
-import com.datastax.driver.core.exceptions.InvalidQueryException;
-import com.datastax.driver.core.exceptions.NoHostAvailableException;
-import com.sun.jersey.core.util.Base64;
-
-/**
- * @author nelson24
- *
- */
-public class MusicDataStore {
-
- public static final String CONSISTENCY_LEVEL_ONE = "ONE";
- public static final String CONSISTENCY_LEVEL_QUORUM = "QUORUM";
- private Session session;
- private Cluster cluster;
-
-
- /**
- * @param session
- */
- public void setSession(Session session) {
- this.session = session;
- }
-
- /**
- * @param session
- */
- public Session getSession() {
- return session;
- }
-
- /**
- * @param cluster
- */
- public void setCluster(Cluster cluster) {
- this.cluster = cluster;
- }
-
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStore.class);
-
- /**
- *
- */
- public MusicDataStore() {
- connectToCassaCluster();
- }
-
-
- /**
- * @param cluster
- * @param session
- */
- public MusicDataStore(Cluster cluster, Session session) {
- this.session = session;
- this.cluster = cluster;
- }
-
- /**
- *
- * @param remoteIp
- * @throws MusicServiceException
- */
- public MusicDataStore(String remoteIp) {
- try {
- connectToCassaCluster(remoteIp);
- } catch (MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- }
- }
-
- /**
- *
- * @return
- */
- private ArrayList<String> getAllPossibleLocalIps() {
- ArrayList<String> allPossibleIps = new ArrayList<>();
- try {
- Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
- while (en.hasMoreElements()) {
- NetworkInterface ni = en.nextElement();
- Enumeration<InetAddress> ee = ni.getInetAddresses();
- while (ee.hasMoreElements()) {
- InetAddress ia = ee.nextElement();
- allPossibleIps.add(ia.getHostAddress());
- }
- }
- } catch (SocketException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.CONNCECTIVITYERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
- }catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
- }
- return allPossibleIps;
- }
-
- /**
- * This method iterates through all available IP addresses and connects to multiple cassandra
- * clusters.
- */
- private void connectToCassaCluster() {
- Iterator<String> it = getAllPossibleLocalIps().iterator();
- String address = "localhost";
- String[] addresses = null;
- address = MusicUtil.getMyCassaHost();
- addresses = address.split(",");
-
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Connecting to cassa cluster: Iterating through possible ips:"
- + getAllPossibleLocalIps());
- PoolingOptions poolingOptions = new PoolingOptions();
- poolingOptions
- .setConnectionsPerHost(HostDistance.LOCAL, 4, 10)
- .setConnectionsPerHost(HostDistance.REMOTE, 2, 4);
- while (it.hasNext()) {
- try {
- if(MusicUtil.getCassName() != null && MusicUtil.getCassPwd() != null) {
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Building with credentials "+MusicUtil.getCassName()+" & "+MusicUtil.getCassPwd());
- cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
- .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd())
- //.withLoadBalancingPolicy(new RoundRobinPolicy())
- .withoutJMXReporting()
- .withPoolingOptions(poolingOptions)
- .addContactPoints(addresses).build();
- }
- else
- cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
- //.withLoadBalancingPolicy(new RoundRobinPolicy())
- .addContactPoints(addresses).build();
-
- Metadata metadata = cluster.getMetadata();
- logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster "
- + metadata.getClusterName() + " at " + address);
- session = cluster.connect();
-
- break;
- } catch (NoHostAvailableException e) {
- address = it.next();
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.HOSTUNAVAILABLE, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
- }
- }
- }
-
- /**
- *
- */
- public void close() {
- session.close();
- }
-
- /**
- * This method connects to cassandra cluster on specific address.
- *
- * @param address
- */
- private void connectToCassaCluster(String address) throws MusicServiceException {
- String[] addresses = null;
- addresses = address.split(",");
- PoolingOptions poolingOptions = new PoolingOptions();
- poolingOptions
- .setConnectionsPerHost(HostDistance.LOCAL, 4, 10)
- .setConnectionsPerHost(HostDistance.REMOTE, 2, 4);
- if(MusicUtil.getCassName() != null && MusicUtil.getCassPwd() != null) {
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Building with credentials "+MusicUtil.getCassName()+" & "+MusicUtil.getCassPwd());
- cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
- .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd())
- //.withLoadBalancingPolicy(new RoundRobinPolicy())
- .withoutJMXReporting()
- .withPoolingOptions(poolingOptions)
- .addContactPoints(addresses).build();
- }
- else {
- cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
- //.withLoadBalancingPolicy(new RoundRobinPolicy())
- .withoutJMXReporting()
- .withPoolingOptions(poolingOptions)
- .addContactPoints(addresses).build();
- }
-
- // JmxReporter reporter =
- // JmxReporter.forRegistry(cluster.getMetrics().getRegistry())
- // .inDomain(cluster.getClusterName() + "-metrics")
- // .build();
-
- // reporter.start();
-
- Metadata metadata = cluster.getMetadata();
- logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster "
- + metadata.getClusterName() + " at " + address);
- try {
- session = cluster.connect();
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.CASSANDRACONNECTIVITY, ErrorSeverity.ERROR, ErrorTypes.SERVICEUNAVAILABLE);
- throw new MusicServiceException(
- "Error while connecting to Cassandra cluster.. " + ex.getMessage());
- }
- }
-
- /**
- *
- * @param keyspace
- * @param tableName
- * @param columnName
- * @return DataType
- */
- public DataType returnColumnDataType(String keyspace, String tableName, String columnName) {
- KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(keyspace);
- TableMetadata table = ks.getTable(tableName);
- return table.getColumn(columnName).getType();
-
- }
-
- /**
- *
- * @param keyspace
- * @param tableName
- * @return TableMetadata
- */
- public TableMetadata returnColumnMetadata(String keyspace, String tableName) {
- KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(keyspace);
- return ks.getTable(tableName);
- }
-
-
- /**
- * Utility function to return the Java specific object type.
- *
- * @param row
- * @param colName
- * @param colType
- * @return
- */
- public Object getColValue(Row row, String colName, DataType colType) {
-
- switch (colType.getName()) {
- case VARCHAR:
- return row.getString(colName);
- case UUID:
- return row.getUUID(colName);
- case VARINT:
- return row.getVarint(colName);
- case BIGINT:
- return row.getLong(colName);
- case INT:
- return row.getInt(colName);
- case FLOAT:
- return row.getFloat(colName);
- case DOUBLE:
- return row.getDouble(colName);
- case BOOLEAN:
- return row.getBool(colName);
- case MAP:
- return row.getMap(colName, String.class, String.class);
- case LIST:
- return row.getList(colName, String.class);
- default:
- return null;
- }
- }
-
- public byte[] getBlobValue(Row row, String colName, DataType colType) {
- ByteBuffer bb = row.getBytes(colName);
- return bb.array();
- }
-
- public boolean doesRowSatisfyCondition(Row row, Map<String, Object> condition) throws Exception {
- ColumnDefinitions colInfo = row.getColumnDefinitions();
-
- for (Map.Entry<String, Object> entry : condition.entrySet()) {
- String colName = entry.getKey();
- DataType colType = colInfo.getType(colName);
- Object columnValue = getColValue(row, colName, colType);
- Object conditionValue = MusicUtil.convertToActualDataType(colType, entry.getValue());
- if (columnValue.equals(conditionValue) == false)
- return false;
- }
- return true;
- }
-
- /**
- * Utility function to store ResultSet values in to a MAP for output.
- *
- * @param results
- * @return MAP
- */
- public Map<String, HashMap<String, Object>> marshalData(ResultSet results) {
- Map<String, HashMap<String, Object>> resultMap =
- new HashMap<>();
- int counter = 0;
- for (Row row : results) {
- ColumnDefinitions colInfo = row.getColumnDefinitions();
- HashMap<String, Object> resultOutput = new HashMap<>();
- for (Definition definition : colInfo) {
- if (!(("vector_ts").equals(definition.getName()))) {
- if(definition.getType().toString().toLowerCase().contains("blob")) {
- resultOutput.put(definition.getName(),
- getBlobValue(row, definition.getName(), definition.getType()));
- }
- else
- resultOutput.put(definition.getName(),
- getColValue(row, definition.getName(), definition.getType()));
- }
- }
- resultMap.put("row " + counter, resultOutput);
- counter++;
- }
- return resultMap;
- }
-
-
- // Prepared Statements 1802 additions
-
- public boolean executePut(PreparedQueryObject queryObject, String consistency)
- throws MusicServiceException, MusicQueryException {
- return executePut(queryObject, consistency, 0);
- }
- /**
- * This Method performs DDL and DML operations on Cassandra using specified consistency level
- *
- * @param queryObject Object containing cassandra prepared query and values.
- * @param consistency Specify consistency level for data synchronization across cassandra
- * replicas
- * @return Boolean Indicates operation success or failure
- * @throws MusicServiceException
- * @throws MusicQueryException
- */
- public boolean executePut(PreparedQueryObject queryObject, String consistency,long timeSlot)
- throws MusicServiceException, MusicQueryException {
-
- boolean result = false;
- long timeOfWrite = System.currentTimeMillis();
- if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) {
- logger.error(EELFLoggerDelegate.errorLogger, queryObject.getQuery(),AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicQueryException("Ill formed queryObject for the request = " + "["
- + queryObject.getQuery() + "]");
- }
- logger.info(EELFLoggerDelegate.applicationLogger,
- "In preprared Execute Put: the actual insert query:"
- + queryObject.getQuery() + "; the values"
- + queryObject.getValues());
-/*<<<<<<< HEAD
- PreparedStatement preparedInsert = null;
- try {
-
- preparedInsert = session.prepare(queryObject.getQuery());
-
- } catch(InvalidQueryException iqe) {
- logger.error("Exception", iqe);
- logger.error(EELFLoggerDelegate.errorLogger, iqe.getMessage(),AppMessages.QUERYERROR, ErrorSeverity.CRITICAL, ErrorTypes.QUERYERROR);
- throw new MusicQueryException(iqe.getMessage());
- }catch(Exception e) {
- logger.error("Exception", e);
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.QUERYERROR, ErrorSeverity.CRITICAL, ErrorTypes.QUERYERROR);
- throw new MusicQueryException(e.getMessage());
- }
-
-=======*/
- SimpleStatement preparedInsert = null;
-
- try {
- preparedInsert = new SimpleStatement(queryObject.getQuery(), queryObject.getValues().toArray());
- if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
- logger.info(EELFLoggerDelegate.applicationLogger, "Executing critical put query");
- preparedInsert.setConsistencyLevel(ConsistencyLevel.QUORUM);
- } else if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) {
- logger.info(EELFLoggerDelegate.applicationLogger, "Executing simple put query");
- if(queryObject.getConsistency() == null)
- preparedInsert.setConsistencyLevel(ConsistencyLevel.ONE);
- else
- preparedInsert.setConsistencyLevel(MusicUtil.getConsistencyLevel(queryObject.getConsistency()));
- } else if (consistency.equalsIgnoreCase(MusicUtil.ONE)) {
- preparedInsert.setConsistencyLevel(ConsistencyLevel.ONE);
- } else if (consistency.equalsIgnoreCase(MusicUtil.QUORUM)) {
- preparedInsert.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);
- } else if (consistency.equalsIgnoreCase(MusicUtil.ALL)) {
- preparedInsert.setConsistencyLevel(ConsistencyLevel.ALL);
- }
- long timestamp = MusicUtil.v2sTimeStampInMicroseconds(timeSlot, timeOfWrite);
- preparedInsert.setDefaultTimestamp(timestamp);
-
- ResultSet rs = session.execute(preparedInsert);
- result = rs.wasApplied();
-
- }
- catch (AlreadyExistsException ae) {
- logger.error(EELFLoggerDelegate.errorLogger, ae.getMessage(),AppMessages.SESSIONFAILED+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicServiceException(ae.getMessage());
- }
- catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.SESSIONFAILED+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicQueryException("Executing Session Failure for Request = " + "["
- + queryObject.getQuery() + "]" + " Reason = " + e.getMessage());
- }
-
-
- return result;
- }
-
- /* *//**
- * This method performs DDL operations on Cassandra using consistency level ONE.
- *
- * @param queryObject Object containing cassandra prepared query and values.
- * @return ResultSet
- * @throws MusicServiceException
- * @throws MusicQueryException
- *//*
- public ResultSet executeEventualGet(PreparedQueryObject queryObject)
- throws MusicServiceException, MusicQueryException {
- CacheAccess<String, PreparedStatement> queryBank = CachingUtil.getStatementBank();
- PreparedStatement preparedEventualGet = null;
- if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) {
- logger.error(EELFLoggerDelegate.errorLogger, "",AppMessages.QUERYERROR+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicQueryException("Ill formed queryObject for the request = " + "["
- + queryObject.getQuery() + "]");
- }
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Executing Eventual get query:" + queryObject.getQuery());
-
- ResultSet results = null;
- try {
- if(queryBank.get(queryObject.getQuery()) != null )
- preparedEventualGet=queryBank.get(queryObject.getQuery());
- else {
- preparedEventualGet = session.prepare(queryObject.getQuery());
- CachingUtil.updateStatementBank(queryObject.getQuery(), preparedEventualGet);
- }
- if(queryObject.getConsistency() == null) {
- preparedEventualGet.setConsistencyLevel(ConsistencyLevel.ONE);
- }
- else {
- preparedEventualGet.setConsistencyLevel(MusicUtil.getConsistencyLevel(queryObject.getConsistency()));
- }
- results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray()));
-
- } catch (Exception ex) {
- logger.error("Exception", ex);
- logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicServiceException(ex.getMessage());
- }
- return results;
- }
-
- *//**
- *
- * This method performs DDL operation on Cassandra using consistency level QUORUM.
- *
- * @param queryObject Object containing cassandra prepared query and values.
- * @return ResultSet
- * @throws MusicServiceException
- * @throws MusicQueryException
- *//*
- public ResultSet executeCriticalGet(PreparedQueryObject queryObject)
- throws MusicServiceException, MusicQueryException {
- if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) {
- logger.error(EELFLoggerDelegate.errorLogger, "",AppMessages.QUERYERROR+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicQueryException("Error processing Prepared Query Object for the request = " + "["
- + queryObject.getQuery() + "]");
- }
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Executing Critical get query:" + queryObject.getQuery());
- PreparedStatement preparedEventualGet = session.prepare(queryObject.getQuery());
- preparedEventualGet.setConsistencyLevel(ConsistencyLevel.QUORUM);
- ResultSet results = null;
- try {
- results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray()));
- } catch (Exception ex) {
- logger.error("Exception", ex);
- logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicServiceException(ex.getMessage());
- }
- return results;
-
- }
- */
- public ResultSet executeGet(PreparedQueryObject queryObject,String consistencyLevel) throws MusicQueryException, MusicServiceException {
- if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) {
- logger.error(EELFLoggerDelegate.errorLogger, "",AppMessages.QUERYERROR+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicQueryException("Error processing Prepared Query Object for the request = " + "["
- + queryObject.getQuery() + "]");
- }
- ResultSet results = null;
- try {
- SimpleStatement statement = new SimpleStatement(queryObject.getQuery(), queryObject.getValues().toArray());
-
- if (consistencyLevel.equalsIgnoreCase(CONSISTENCY_LEVEL_ONE)) {
- if(queryObject.getConsistency() == null) {
- statement.setConsistencyLevel(ConsistencyLevel.ONE);
- }
- else {
- statement.setConsistencyLevel(MusicUtil.getConsistencyLevel(queryObject.getConsistency()));
- }
- }
- else if (consistencyLevel.equalsIgnoreCase(CONSISTENCY_LEVEL_QUORUM)) {
- statement.setConsistencyLevel(ConsistencyLevel.QUORUM);
- }
-
- results = session.execute(statement);
-
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicServiceException(ex.getMessage());
- }
-
- return results;
-
- }
-
- /**
- * This method performs DDL operations on Cassandra using consistency level ONE.
- *
- * @param queryObject Object containing cassandra prepared query and values.
- */
- public ResultSet executeOneConsistencyGet(PreparedQueryObject queryObject)
- throws MusicServiceException, MusicQueryException {
- return executeGet(queryObject, CONSISTENCY_LEVEL_ONE);
- }
-
- /**
- *
- * This method performs DDL operation on Cassandra using consistency level QUORUM.
- *
- * @param queryObject Object containing cassandra prepared query and values.
- */
- public ResultSet executeQuorumConsistencyGet(PreparedQueryObject queryObject)
- throws MusicServiceException, MusicQueryException {
- return executeGet(queryObject, CONSISTENCY_LEVEL_QUORUM);
- }
-
-}
diff --git a/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java b/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java
deleted file mode 100644
index dc1c43a8..00000000
--- a/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * Modifications Copyright (C) 2019 IBM.
- * ===================================================================
- * Modifications Copyright (c) 2019 Samsung
- * ===================================================================
- * 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.datastore;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.onap.music.eelf.logging.EELFLoggerDelegate;
-import org.onap.music.exceptions.MusicServiceException;
-import org.onap.music.main.MusicUtil;
-
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.TableMetadata;
-
-public class MusicDataStoreHandle {
-
- private MusicDataStoreHandle(){
- throw new IllegalStateException("Utility class");
- }
-
- public static MusicDataStore mDstoreHandle = null;
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStoreHandle.class);
-
- /**
- *
- * @param remoteIp
- * @return
- */
- public static MusicDataStore getDSHandle(String remoteIp) {
- logger.info(EELFLoggerDelegate.metricsLogger,"Acquiring data store handle");
- long start = System.currentTimeMillis();
- if (mDstoreHandle == null) {
- mDstoreHandle = new MusicDataStore(remoteIp);
- }
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.metricsLogger,"Time taken to acquire data store handle:" + (end - start) + " ms");
- return mDstoreHandle;
- }
-
- /**
- *
- * @return
- * @throws MusicServiceException
- */
- public static MusicDataStore getDSHandle() throws MusicServiceException {
- logger.info(EELFLoggerDelegate.metricsLogger,"Acquiring data store handle");
- long start = System.currentTimeMillis();
- if (mDstoreHandle == null) {
- // Quick Fix - Best to put this into every call to getDSHandle?
- if (!"localhost".equals(MusicUtil.getMyCassaHost())) {
- mDstoreHandle = new MusicDataStore(MusicUtil.getMyCassaHost());
- } else {
- mDstoreHandle = new MusicDataStore();
- }
- }
- if(mDstoreHandle.getSession() == null) {
- String message = "Connection to Cassandra has not been enstablished."
- + " Please check connection properites and reboot.";
- logger.info(EELFLoggerDelegate.applicationLogger, message);
- throw new MusicServiceException(message);
- }
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.metricsLogger,"Time taken to acquire data store handle:" + (end - start) + " ms");
- return mDstoreHandle;
- }
-
-
- /**
- *
- * @param keyspace
- * @param tablename
- * @return
- * @throws MusicServiceException
- */
- public static TableMetadata returnColumnMetadata(String keyspace, String tablename) throws MusicServiceException {
- return getDSHandle().returnColumnMetadata(keyspace, tablename);
- }
-
- /**
- *
- * @param results
- * @return
- * @throws MusicServiceException
- */
- public static Map<String, HashMap<String, Object>> marshallResults(ResultSet results) throws MusicServiceException {
- return getDSHandle().marshalData(results);
- }
-
-}
diff --git a/src/main/java/org/onap/music/datastore/PreparedQueryObject.java b/src/main/java/org/onap/music/datastore/PreparedQueryObject.java
deleted file mode 100644
index 9b109630..00000000
--- a/src/main/java/org/onap/music/datastore/PreparedQueryObject.java
+++ /dev/null
@@ -1,128 +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.datastore;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- *
- * @author srupane
- *
- */
-public class PreparedQueryObject {
-
-
- private List<Object> values;
- private StringBuilder query;
- private String consistency;
- private String keyspaceName;
- private String tableName;
- private String operation;
- private String primaryKeyValue;
-
-
-
- public String getKeyspaceName() {
- return keyspaceName;
- }
-
- public void setKeyspaceName(String keyspaceName) {
- this.keyspaceName = keyspaceName;
- }
-
- public String getTableName() {
- return tableName;
- }
-
- public void setTableName(String tableName) {
- this.tableName = tableName;
- }
-
- public String getOperation() {
- return operation;
- }
-
- public void setOperation(String operation) {
- this.operation = operation;
- }
-
- public String getPrimaryKeyValue() {
- return primaryKeyValue;
- }
-
- public void setPrimaryKeyValue(String primaryKeyValue) {
- this.primaryKeyValue = primaryKeyValue;
- }
-
- public String getConsistency() {
- return consistency;
- }
-
- public void setConsistency(String consistency) {
- this.consistency = consistency;
- }
-
- /**
- *
- */
- public PreparedQueryObject() {
-
- this.values = new ArrayList<>();
- this.query = new StringBuilder();
- }
-
- /**
- * @return
- */
- public List<Object> getValues() {
- return values;
- }
-
- /**
- * @param o
- */
- public void addValue(Object o) {
- this.values.add(o);
- }
-
- /**
- * @param s
- */
- public void appendQueryString(String s) {
- this.query.append(s);
- }
- public void replaceQueryString(String s) {
- this.query.replace(0, query.length(), s);
- }
-
- /**
- * @return
- */
- public String getQuery() {
- return this.query.toString();
- }
-
-
-
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/AAFResponse.java b/src/main/java/org/onap/music/datastore/jsonobjects/AAFResponse.java
deleted file mode 100644
index 3544e068..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/AAFResponse.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * ===================================================================
- * Modifications Copyright (c) 2018 IBM
- * ===================================================================
- * 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.datastore.jsonobjects;
-
-import java.util.List;
-
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
-
-@ApiModel(value = "JsonTable", description = "Reponse class for AAF request")
-public class AAFResponse {
-
- private List<NameSpace> ns = null;
-
- @ApiModelProperty(value = "Namespace value")
- public List<NameSpace> getNs() {
- return ns;
- }
-
- public void setNs(List<NameSpace> ns) {
- this.ns = ns;
- }
-
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java b/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java
deleted file mode 100644
index 2fc4215b..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package org.onap.music.datastore.jsonobjects;
-/*
- * ============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=============================================
- * ====================================================================
- */
-
-
-public class JSONObject {
-
- private String data;
-
- public String getData() {
- return data;
- }
-
- public void setData(String data) {
- this.data = data;
- }
-
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java
deleted file mode 100644
index b98a391d..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * ===================================================================
- * Modifications Copyright (c) 2019 Samsung
- * ===================================================================
- * 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.datastore.jsonobjects;
-
-import java.util.List;
-import java.util.Map;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
-
-@ApiModel(value = "JsonTable", description = "Json model for delete")
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class JsonDelete {
-
- private List<String> columns = null;
- private Map<String, String> consistencyInfo;
- private Map<String, Object> conditions;
- String ttl, timestamp;
-
-
- @ApiModelProperty(value = "Conditions")
- public Map<String, Object> getConditions() {
- return conditions;
- }
-
- public void setConditions(Map<String, Object> conditions) {
- this.conditions = conditions;
- }
-
- @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic")
- public Map<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
-
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
- }
-
- @ApiModelProperty(value = "Column values")
- public List<String> getColumns() {
- return columns;
- }
-
- public void setColumns(List<String> columns) {
- this.columns = columns;
- }
-
-
- @ApiModelProperty(value = "Time to live information")
- public String getTtl() {
- return ttl;
- }
-
- public void setTtl(String ttl) {
- this.ttl = ttl;
- }
-
- @ApiModelProperty(value = "Time stamp")
- public String getTimestamp() {
- return timestamp;
- }
-
- public void setTimestamp(String timestamp) {
- this.timestamp = timestamp;
- }
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java
deleted file mode 100644
index 4533f947..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * Modifications Copyright (C) 2018 IBM.
- * ===================================================================
- * 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.datastore.jsonobjects;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.Map;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
-
-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;
-
-@ApiModel(value = "JsonTable", description = "Json model for table vlaues insert")
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class JsonInsert implements Serializable {
- private String keyspaceName;
- private String tableName;
- private transient Map<String, Object> values;
- private String ttl;
- private String timestamp;
- private transient Map<String, Object> rowSpecification;
- private Map<String, String> consistencyInfo;
- private Map<String, byte[]> objectMap;
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonInsert.class);
-
- @ApiModelProperty(value = "objectMap")
- public Map<String, byte[]> getObjectMap() {
- return objectMap;
- }
-
- public void setObjectMap(Map<String, byte[]> objectMap) {
- this.objectMap = objectMap;
- }
-
- @ApiModelProperty(value = "keyspace")
- public String getKeyspaceName() {
- return keyspaceName;
- }
-
- public void setKeyspaceName(String keyspaceName) {
- this.keyspaceName = keyspaceName;
- }
-
- @ApiModelProperty(value = "Table name")
- public String getTableName() {
- return tableName;
- }
-
- public void setTableName(String tableName) {
- this.tableName = tableName;
- }
-
- @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic")
- public Map<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
-
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
- }
-
- @ApiModelProperty(value = "Time to live information")
- public String getTtl() {
- return ttl;
- }
-
- public void setTtl(String ttl) {
- this.ttl = ttl;
- }
-
- @ApiModelProperty(value = "Time stamp")
- public String getTimestamp() {
- return timestamp;
- }
-
- public void setTimestamp(String timestamp) {
- this.timestamp = timestamp;
- }
-
- @ApiModelProperty(value = "values returned")
- public Map<String, Object> getValues() {
- return values;
- }
-
- public void setValues(Map<String, Object> values) {
- this.values = values;
- }
-
- @ApiModelProperty(value = "Information for selecting specific rows for insert")
- public Map<String, Object> getRow_specification() {
- return rowSpecification;
- }
-
- public void setRow_specification(Map<String, Object> rowSpecification) {
- this.rowSpecification = rowSpecification;
- }
-
- public byte[] serialize() {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ObjectOutput out = null;
- try {
- out = new ObjectOutputStream(bos);
- out.writeObject(this);
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.DATAERROR);
- }
- return bos.toByteArray();
- }
-
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java
deleted file mode 100644
index f2232ffd..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java
+++ /dev/null
@@ -1,78 +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.datastore.jsonobjects;
-
-import java.util.Map;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
-
-@ApiModel(value = "JsonTable", description = "Json model creating new keyspace")
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class JsonKeySpace {
- private String keyspaceName;
- private Map<String, Object> replicationInfo;
- private String durabilityOfWrites;
- private Map<String, String> consistencyInfo;
-
- @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic")
- public Map<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
-
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
- }
-
- @ApiModelProperty(value = "Replication information")
- public Map<String, Object> getReplicationInfo() {
- return replicationInfo;
- }
-
- public void setReplicationInfo(Map<String, Object> replicationInfo) {
- this.replicationInfo = replicationInfo;
- }
-
- @ApiModelProperty(value = "Durability", allowableValues = "true,false")
- public String getDurabilityOfWrites() {
- return durabilityOfWrites;
- }
-
- public void setDurabilityOfWrites(String durabilityOfWrites) {
- this.durabilityOfWrites = durabilityOfWrites;
- }
-
- @ApiModelProperty(value = "Keyspace name")
- public String getKeyspaceName() {
- return keyspaceName;
- }
-
- public void setKeyspaceName(String keyspaceName) {
- this.keyspaceName = keyspaceName;
- }
-
-
-
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java
deleted file mode 100644
index 06a76f57..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java
+++ /dev/null
@@ -1,53 +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.datastore.jsonobjects;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
-
-@ApiModel(value = "JsonTable", description = "model for leased lock")
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class JsonLeasedLock {
- long leasePeriod;
- String notifyUrl;
-
- @ApiModelProperty(value = "Lease period")
- public long getLeasePeriod() {
- return leasePeriod;
- }
-
- public void setLeasePeriod(long leasePeriod) {
- this.leasePeriod = leasePeriod;
- }
-
- @ApiModelProperty(value = "URL to be notified")
- public String getNotifyUrl() {
- return notifyUrl;
- }
-
- public void setNotifyUrl(String notifyUrl) {
- this.notifyUrl = notifyUrl;
- }
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java
deleted file mode 100755
index 82993ebc..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java
+++ /dev/null
@@ -1,94 +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.datastore.jsonobjects;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
-
-@ApiModel(value = "JsonOnboard", description = "Defines the Json for Onboarding an application.")
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class JsonOnboard {
- private String appname;
- private String userId;
- private String password;
- private String isAAF;
- private String aid;
- private String keyspace;
-
- @ApiModelProperty(value = "Application Keyspace")
- public String getKeyspace() {
- return keyspace;
- }
-
- public void setKeyspace_name(String keyspace) {
- this.keyspace = keyspace;
- }
-
- @ApiModelProperty(value = "Application Password")
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
- @ApiModelProperty(value = "Application UUID")
- public String getAid() {
- return aid;
- }
-
- public void setAid(String aid) {
- this.aid = aid;
- }
-
- @ApiModelProperty(value = "Application name")
- public String getAppname() {
- return appname;
- }
-
- public void setAppname(String appname) {
- this.appname = appname;
- }
-
- @ApiModelProperty(value = "User Id")
- public String getUserId() {
- return userId;
- }
-
- public void setUserId(String userId) {
- this.userId = userId;
- }
-
- @ApiModelProperty(value = "Is AAF Application", allowableValues = "true, false")
- public String getIsAAF() {
- return isAAF;
- }
-
- public void setIsAAF(String isAAF) {
- this.isAAF = isAAF;
- }
-
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java
deleted file mode 100644
index faef9b8f..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * Modifications Copyright (C) 2018 IBM.
- * ===================================================================
- * 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.datastore.jsonobjects;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.Map;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class JsonSelect implements Serializable {
- private Map<String, String> consistencyInfo;
-
-
- public Map<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
-
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
- }
-
- public byte[] serialize() {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ObjectOutput out = null;
- try {
- out = new ObjectOutputStream(bos);
- out.writeObject(this);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return bos.toByteArray();
- }
-
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java
deleted file mode 100644
index badcaebe..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java
+++ /dev/null
@@ -1,135 +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.datastore.jsonobjects;
-
-import java.util.Map;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
-
-@ApiModel(value = "JsonTable", description = "Defines the Json for Creating a new Table.")
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class JsonTable {
- private String keyspaceName;
- private String tableName;
-
- private Map<String, String> fields;
- private Map<String, Object> properties;
- private String primaryKey;
- private String partitionKey;
- private String clusteringKey;
- private String filteringKey;
- private String clusteringOrder;
- private Map<String, String> consistencyInfo;
-
- @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic")
- public Map<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
-
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
- }
-
- @ApiModelProperty(value = "Properties")
- public Map<String, Object> getProperties() {
- return properties;
- }
-
- public void setProperties(Map<String, Object> properties) {
- this.properties = properties;
- }
-
- @ApiModelProperty(value = "Fields")
- public Map<String, String> getFields() {
- return fields;
- }
-
- public void setFields(Map<String, String> fields) {
- this.fields = fields;
- }
-
- @ApiModelProperty(value = "KeySpace Name")
- public String getKeyspaceName() {
- return keyspaceName;
- }
-
- public void setKeyspaceName(String keyspaceName) {
- this.keyspaceName = keyspaceName;
- }
-
- @ApiModelProperty(value = "Table Name")
- public String getTableName() {
- return tableName;
- }
-
- public void setTableName(String tableName) {
- this.tableName = tableName;
- }
-
- @ApiModelProperty(value = "Clustering Order", notes = "")
- public String getClusteringOrder() {
- return clusteringOrder;
- }
-
- public void setClusteringOrder(String clusteringOrder) {
- this.clusteringOrder = clusteringOrder;
- }
-
- @ApiModelProperty(value = "Primary Key")
- public String getPrimaryKey() {
- return primaryKey;
- }
-
- public void setPrimaryKey(String primaryKey) {
- this.primaryKey = primaryKey;
- }
-
- public String getClusteringKey() {
- return clusteringKey;
- }
-
- public void setClusteringKey(String clusteringKey) {
- this.clusteringKey = clusteringKey;
- }
-
- public String getFilteringKey() {
- return filteringKey;
- }
-
- public void setFilteringKey(String filteringKey) {
- this.filteringKey = filteringKey;
- }
-
- public String getPartitionKey() {
- return partitionKey;
- }
-
- public void setPartitionKey(String partitionKey) {
- this.partitionKey = partitionKey;
- }
-
-
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java
deleted file mode 100644
index e31c6ccf..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * Modifications Copyright (C) 2018 IBM.
- * ===================================================================
- * 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.datastore.jsonobjects;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.Map;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
-
-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;
-
-@ApiModel(value = "JsonTable", description = "Json model for table update")
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class JsonUpdate implements Serializable {
- private String keyspaceName;
- private String tableName;
- private transient Map<String, Object> values;
- private String ttl;
- private String timestamp;
- private Map<String, String> consistencyInfo;
- private transient Map<String, Object> conditions;
- private transient Map<String, Object> rowSpecification;
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonUpdate.class);
-
- @ApiModelProperty(value = "Conditions")
- public Map<String, Object> getConditions() {
- return conditions;
- }
-
- public void setConditions(Map<String, Object> conditions) {
- this.conditions = conditions;
- }
-
- @ApiModelProperty(value = "Information for selecting sepcific rows")
- public Map<String, Object> getRow_specification() {
- return rowSpecification;
- }
-
- public void setRow_specification(Map<String, Object> rowSpecification) {
- this.rowSpecification = rowSpecification;
- }
-
-
- @ApiModelProperty(value = "Keyspace name")
- public String getKeyspaceName() {
- return keyspaceName;
- }
-
- public void setKeyspaceName(String keyspaceName) {
- this.keyspaceName = keyspaceName;
- }
-
- @ApiModelProperty(value = "Table name")
- public String getTableName() {
- return tableName;
- }
-
- public void setTableName(String tableName) {
- this.tableName = tableName;
- }
-
- @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic")
- public Map<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
-
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
- }
-
- @ApiModelProperty(value = "Time to live value")
- public String getTtl() {
- return ttl;
- }
-
- public void setTtl(String ttl) {
- this.ttl = ttl;
- }
-
- @ApiModelProperty(value = "Time stamp")
- public String getTimestamp() {
- return timestamp;
- }
-
- public void setTimestamp(String timestamp) {
- this.timestamp = timestamp;
- }
-
- @ApiModelProperty(value = "Column values")
- public Map<String, Object> getValues() {
- return values;
- }
-
- public void setValues(Map<String, Object> values) {
- this.values = values;
- }
-
- public byte[] serialize() {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ObjectOutput out = null;
- try {
- out = new ObjectOutputStream(bos);
- out.writeObject(this);
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e,AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.DATAERROR);
- }
- return bos.toByteArray();
- }
-
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/NameSpace.java b/src/main/java/org/onap/music/datastore/jsonobjects/NameSpace.java
deleted file mode 100644
index 3c18c791..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/NameSpace.java
+++ /dev/null
@@ -1,48 +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.datastore.jsonobjects;
-
-import java.util.List;
-
-
-public class NameSpace {
- private String name;
- private List<String> admin;
-
- public List<String> getAdmin() {
- return admin;
- }
-
- public String getName() {
- return name;
- }
-
- public void setAdmin(List<String> admin) {
- this.admin = admin;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
-}
diff --git a/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java b/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java
deleted file mode 100644
index 079fc579..00000000
--- a/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- *
- * Modifications Copyright (C) 2019 IBM.
- * ===================================================================
- * 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.eelf.healthcheck;
-
-import java.util.UUID;
-
-import org.onap.music.datastore.PreparedQueryObject;
-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.exceptions.MusicLockingException;
-import org.onap.music.exceptions.MusicServiceException;
-import org.onap.music.main.MusicUtil;
-import org.onap.music.main.ResultType;
-import org.onap.music.main.MusicCore;
-
-import com.datastax.driver.core.ConsistencyLevel;
-
-/**
- * @author inam
- *
- */
-public class MusicHealthCheck {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
-
- private String cassandrHost;
-
- public String getCassandraStatus(String consistency) {
- logger.info(EELFLoggerDelegate.applicationLogger, "Getting Status for Cassandra");
-
- boolean result = false;
- try {
- result = getAdminKeySpace(consistency);
- } catch(Exception e) {
- if(e.getMessage().toLowerCase().contains("unconfigured table healthcheck")) {
- logger.error("Error", e);
- logger.debug("Creating table....");
- boolean ksresult = createKeyspace();
- if(ksresult)
- try {
- result = getAdminKeySpace(consistency);
- } catch (MusicServiceException e1) {
- logger.error(EELFLoggerDelegate.errorLogger, e1, AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.UNKNOWN);
- }
- } else {
- logger.error("Error", e);
- return "One or more nodes are down or not responding.";
- }
- }
- if (result) {
- return "ACTIVE";
- } else {
- logger.info(EELFLoggerDelegate.applicationLogger, "Cassandra Service is not responding");
- return "INACTIVE";
- }
- }
-
- private Boolean getAdminKeySpace(String consistency) throws MusicServiceException {
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString("insert into admin.healthcheck (id) values (?)");
- pQuery.addValue(UUID.randomUUID());
- ResultType rs = MusicCore.nonKeyRelatedPut(pQuery, consistency);
- logger.info(rs.toString());
- return null != rs;
- }
-
- private boolean createKeyspace() {
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString("CREATE TABLE admin.healthcheck (id uuid PRIMARY KEY)");
- ResultType rs = null ;
- try {
- rs = MusicCore.nonKeyRelatedPut(pQuery, ConsistencyLevel.ONE.toString());
- } catch (MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.UNKNOWN);
- }
- return rs != null && rs.getResult().toLowerCase().contains("success");
- }
-
- public String getCassandrHost() {
- return cassandrHost;
- }
-
- public void setCassandrHost(String cassandrHost) {
- this.cassandrHost = cassandrHost;
- }
-
-}
diff --git a/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java b/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java
deleted file mode 100644
index 64960b1e..00000000
--- a/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java
+++ /dev/null
@@ -1,384 +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.eelf.logging;
-
-import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
-import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
-import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
-import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
-import java.net.InetAddress;
-import java.text.MessageFormat;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import javax.servlet.http.HttpServletRequest;
-import org.slf4j.MDC;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.att.eelf.configuration.SLF4jWrapper;
-
-public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger {
-
- public static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger();
- public static final EELFLogger applicationLogger =
- EELFManager.getInstance().getApplicationLogger();
- public static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
- public static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
- public static final EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger();
-
- private String className;
- private static ConcurrentMap<String, EELFLoggerDelegate> classMap = new ConcurrentHashMap<>();
-
- public EELFLoggerDelegate(final String className) {
- super(className);
- this.className = className;
- }
-
- /**
- * Convenience method that gets a logger for the specified class.
- *
- * @see #getLogger(String)
- *
- * @param clazz
- * @return Instance of EELFLoggerDelegate
- */
- public static EELFLoggerDelegate getLogger(Class<?> clazz) {
- return getLogger(clazz.getName());
- }
-
- /**
- * Gets a logger for the specified class name. If the logger does not already exist in the map,
- * this creates a new logger.
- *
- * @param className If null or empty, uses EELFLoggerDelegate as the class name.
- * @return Instance of EELFLoggerDelegate
- */
- public static EELFLoggerDelegate getLogger(final String className) {
- String classNameNeverNull = className == null || "".equals(className)
- ? EELFLoggerDelegate.class.getName()
- : className;
- EELFLoggerDelegate delegate = classMap.get(classNameNeverNull);
- if (delegate == null) {
- delegate = new EELFLoggerDelegate(className);
- classMap.put(className, delegate);
- }
- return delegate;
- }
-
- /**
- * Logs a message at the lowest level: trace.
- *
- * @param logger
- * @param msg
- */
- public void trace(EELFLogger logger, String msg) {
- if (logger.isTraceEnabled()) {
- logger.trace(msg);
- }
- }
-
- /**
- * Logs a message with parameters at the lowest level: trace.
- *
- * @param logger
- * @param msg
- * @param arguments
- */
- public void trace(EELFLogger logger, String msg, Object... arguments) {
- if (logger.isTraceEnabled()) {
- logger.trace(msg, arguments);
- }
- }
-
- /**
- * Logs a message and throwable at the lowest level: trace.
- *
- * @param logger
- * @param msg
- * @param th
- */
- public void trace(EELFLogger logger, String msg, Throwable th) {
- if (logger.isTraceEnabled()) {
- logger.trace(msg, th);
- }
- }
-
- /**
- * Logs a message at the second-lowest level: debug.
- *
- * @param logger
- * @param msg
- */
- public void debug(EELFLogger logger, String msg) {
- if (logger.isDebugEnabled()) {
- logger.debug(msg);
- }
- }
-
- /**
- * Logs a message with parameters at the second-lowest level: debug.
- *
- * @param logger
- * @param msg
- * @param arguments
- */
- public void debug(EELFLogger logger, String msg, Object... arguments) {
- if (logger.isDebugEnabled()) {
- logger.debug(msg, arguments);
- }
- }
-
- /**
- * Logs a message and throwable at the second-lowest level: debug.
- *
- * @param logger
- * @param msg
- * @param th
- */
- public void debug(EELFLogger logger, String msg, Throwable th) {
- if (logger.isDebugEnabled()) {
- logger.debug(msg, th);
- }
- }
-
- /**
- * Logs a message at info level.
- *
- * @param logger
- * @param msg
- */
- public void info(EELFLogger logger, String msg) {
- logger.info(className + " - "+msg);
- }
-
- /**
- * Logs a message with parameters at info level.
- *
- * @param logger
- * @param msg
- * @param arguments
- */
- public void info(EELFLogger logger, String msg, Object... arguments) {
- logger.info(msg, arguments);
- }
-
- /**
- * Logs a message and throwable at info level.
- *
- * @param logger
- * @param msg
- * @param th
- */
- public void info(EELFLogger logger, String msg, Throwable th) {
- logger.info(msg, th);
- }
-
- /**
- * Logs a message at warn level.
- *
- * @param logger
- * @param msg
- */
- public void warn(EELFLogger logger, String msg) {
- logger.warn(msg);
- }
-
- /**
- * Logs a message with parameters at warn level.
- *
- * @param logger
- * @param msg
- * @param arguments
- */
- public void warn(EELFLogger logger, String msg, Object... arguments) {
- logger.warn(msg, arguments);
- }
-
- /**
- * Logs a message and throwable at warn level.
- *
- * @param logger
- * @param msg
- * @param th
- */
- public void warn(EELFLogger logger, String msg, Throwable th) {
- logger.warn(msg, th);
- }
-
- /**
- * Logs a message at error level.
- *
- * @param logger
- * @param msg
- *
- * @deprecated use {@link #error(EELF, Exception)} instead
- */
- @Deprecated
- public void error(EELFLogger logger, String msg) {
- logger.error(className+ " - " + msg);
- }
-
- /**
- * Logs a message at error level.
- *
- * @param logger
- * @param msg
- */
- public void error(EELFLogger logger, Exception e) {
- logger.error(className+ " - ", e);
- }
-
- /**
- * Logs a message with parameters at error level.
- *
- * @param logger
- * @param msg
- * @param arguments
- *
- * @deprecated use {@link #error(EELF, Exception, Object...)} instead
- */
- @Deprecated
- public void error(EELFLogger logger, String msg, Object... arguments) {
- logger.error(msg, arguments);
- }
-
- /**
- * Logs a message with parameters at error level.
- *
- * @param logger
- * @param msg
- * @param arguments
- */
- public void error(EELFLogger logger, Exception e, Object... arguments) {
- logger.error("Exception", e, arguments);
- }
-
- /**
- * Logs a message and throwable at error level.
- *
- * @param logger
- * @param msg
- * @param th
- */
- public void error(EELFLogger logger, String msg, Throwable th) {
- logger.error(msg, th);
- }
-
- /**
- * Logs a message with the associated alarm severity at error level.
- *
- * @param logger
- * @param msg
- * @param severtiy
- * @deprecated use {@link #error(EELF, Exception)} instead
- */
- @Deprecated
- public void error(EELFLogger logger, String msg, Object /* AlarmSeverityEnum */ severtiy) {
- logger.error(msg);
- }
-
- /**
- * Initializes the logger context.
- */
- public void init() {
- setGlobalLoggingContext();
- final String msg =
- "############################ Logging is started. ############################";
- // These loggers emit the current date-time without being told.
- info(applicationLogger, msg);
- error(errorLogger, msg);
- debug(debugLogger, msg);
- info(auditLogger, msg);
- info(metricsLogger, msg);
- }
-
- /**
- * Builds a message using a template string and the arguments.
- *
- * @param message
- * @param args
- * @return
- */
- private String formatMessage(String message, Object... args) {
- StringBuilder sbFormattedMessage = new StringBuilder();
- if (args != null && args.length > 0 && message != null && message != "") {
- MessageFormat mf = new MessageFormat(message);
- sbFormattedMessage.append(mf.format(args));
- } else {
- sbFormattedMessage.append(message);
- }
-
- return sbFormattedMessage.toString();
- }
-
- /**
- * Loads all the default logging fields into the MDC context.
- */
- private void setGlobalLoggingContext() {
- MDC.put(MDC_SERVICE_INSTANCE_ID, "");
- try {
- MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
- MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
- } catch (Exception e) {
- errorLogger.error("setGlobalLoggingContext failed", e);
- }
- }
-
- public static void mdcPut(String key, String value) {
- MDC.put(key, value);
- }
-
- public static String mdcGet(String key) {
- return MDC.get(key);
- }
-
- public static void mdcRemove(String key) {
- MDC.remove(key);
- }
-
- /**
- * Loads the RequestId/TransactionId into the MDC which it should be receiving with an each
- * incoming REST API request. Also, configures few other request based logging fields into the
- * MDC context.
- *
- * @param req
- * @param appName
- */
- public void setRequestBasedDefaultsIntoGlobalLoggingContext(HttpServletRequest req,
- String appName) {
- // Load the default fields
- setGlobalLoggingContext();
-
- // Load the request based fields
- if (req != null) {
- // Rest Path
- MDC.put(MDC_SERVICE_NAME, req.getServletPath());
-
- // Client IPAddress i.e. IPAddress of the remote host who is making
- // this request.
- String clientIPAddress = req.getHeader("X-FORWARDED-FOR");
- if (clientIPAddress == null) {
- clientIPAddress = req.getRemoteAddr();
- }
- }
- }
-}
diff --git a/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java b/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java
deleted file mode 100644
index 5af3661c..00000000
--- a/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * Copyright (c) 2019 IBM 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.eelf.logging.format;
-
-/**
- * @author inam
- *
- */
-public enum AppMessages {
-
-
-
- /*
- * 100-199 Security/Permission Related - Authentication problems
- * [ERR100E] Missing Information
- * [ERR101E] Authentication error occured
- *
- * 200-299 Availability/Timeout Related/IO - connectivity error - connection timeout
- * [ERR200E] Connectivity
- * [ERR201E] Host not available
- * [ERR202E] Error while connecting to Cassandra cluster
- * [ERR203E] IO Error has occured
- * [ERR204E] Execution Interrupted
- * [ERR205E] Session Expired
- * [ERR206E] Cache not authenticated
- *
- *
- * 300-399 Data Access/Integrity Related
- * [ERR300E] Incorrect data
- *
- * 400-499 - Cassandra Query Related
- * [ERR400E] Error while processing prepared query object
- * [ERR401E] Executing Session Failure for Request
- * [ERR402E] Ill formed queryObject for the request
- * [ERR403E] Error processing Prepared Query Object
- *
- * 500-599 - Locking Related
- * [ERR500E] Invalid lock
- * [ERR501E] Locking Error has occured
- * [ERR502E] Deprecated
- * [ERR503E] Failed to aquire lock store handle
- * [ERR504E] Failed to create Lock Reference
- * [ERR505E] Lock does not exist
- * [ERR506E] Failed to aquire lock
- * [ERR507E] Lock not aquired
- * [ERR508E] Lock state not set
- * [ERR509E] Lock not destroyed
- * [ERR510E] Lock not released
- * [ERR511E] Lock not deleted
- * [ERR512E] Deprecated
- *
- *
- * 600 - 699 - Music Service Errors
- * [ERR600E] Error initializing the cache
- *
- * 700-799 Schema Interface Type/Validation - received Pay-load checksum is
- * invalid - received JSON is not valid
- *
- * 800-899 Business/Flow Processing Related - check out to service is not
- * allowed - Roll-back is done - failed to generate heat file
- *
- *
- * 900-999 Unknown Errors - Unexpected exception
- * [ERR900E] Unexpected error occured
- * [ERR901E] Number format exception
- *
- *
- * 1000-1099 Reserved - do not use
- *
- */
-
-
-
-
- MISSINGINFO("[ERR100E]", "Missing Information ","Details: NA", "Please check application credentials and/or headers"),
- AUTHENTICATIONERROR("[ERR101E]", "Authentication error occured ","Details: NA", "Please verify application credentials"),
- CONNCECTIVITYERROR("[ERR200E]"," Connectivity error","Details: NA ","Please check connectivity to external resources"),
- HOSTUNAVAILABLE("[ERR201E]","Host not available","Details: NA","Please verify the host details"),
- CASSANDRACONNECTIVITY("[ERR202E]","Error while connecting to Cassandra cluster",""," Please check cassandra cluster details"),
- IOERROR("[ERR203E]","IO Error has occured","","Please check IO"),
- EXECUTIONINTERRUPTED("[ERR204E]"," Execution Interrupted","",""),
- SESSIONEXPIRED("[ERR205E]"," Session Expired","","Session has expired."),
- CACHEAUTHENTICATION("[ERR206E]","Cache not authenticated",""," Cache not authenticated"),
-
- INCORRECTDATA("[ERR300E]"," Incorrect data",""," Please verify the request payload and try again"),
- MULTIPLERECORDS("[ERR301E]"," Multiple records found",""," Please verify the request payload and try again"),
- ALREADYEXIST("[ERR302E]"," Record already exist",""," Please verify the request payload and try again"),
- MISSINGDATA("[ERR300E]"," Incorrect data",""," Please verify the request payload and try again"),
-
- QUERYERROR("[ERR400E]","Error while processing prepared query object",""," Please verify the query"),
- SESSIONFAILED("[ERR401E]","Executing Session Failure for Request","","Please verify the session and request"),
-
- INVALIDLOCK("[ERR500E]"," Invalid lock or acquire failed",""," Lock is not valid to aquire"),
- LOCKINGERROR("[ERR501E]"," Locking Error has occured",""," Locking Error has occured"),
- LOCKHANDLE("[ERR503E]","Failed to aquire lock store handle",""," Failed to aquire lock store handle"),
- CREATELOCK("[ERR504E]","Failed to aquire lock store handle ","","Failed to aquire lock store handle "),
- LOCKSTATE("[ERR508E]"," Lock state not set",""," Lock state not set"),
- DESTROYLOCK("[ERR509E]"," Lock not destroyed",""," Lock not destroyed"),
- RELEASELOCK("[ERR510E]"," Lock not released",""," Lock not released"),
- DELTELOCK("[ERR511E]",""," Lock not deleted "," Lock not deleted "),
- CACHEERROR("[ERR600E]"," Error initializing the cache",""," Error initializing the cache"),
-
- UNKNOWNERROR("[ERR900E]"," Unexpected error occured",""," Please check logs for details");
-
-
-
-
- private ErrorTypes eType;
- private ErrorSeverity alarmSeverity;
- private ErrorSeverity errorSeverity;
- private String errorCode;
- private String errorDescription;
- private String details;
- private String resolution;
-
-
- AppMessages(String errorCode, String errorDescription, String details,String resolution) {
-
- this.errorCode = errorCode;
- this.errorDescription = errorDescription;
- this.details = details;
- this.resolution = resolution;
- }
-
-
- public ErrorTypes getEType() {
- return eType;
- }
-
- public ErrorSeverity getAlarmSeverity() {
- return alarmSeverity;
- }
- public ErrorSeverity getErrorSeverity() {
- return errorSeverity;
- }
-
- public void setDetails(String details){ this.details=details; }
-
- public String getDetails() {
- return this.details;
- }
-
- public void setResolution(String resolution){ this.resolution=resolution; }
-
- public String getResolution() {
- return this.resolution;
- }
-
- public void setErrorCode(String errorCode){ this.errorCode=errorCode; }
-
- public String getErrorCode() {
- return this.errorCode;
- }
-
- public void setErrorDescription(String errorDescription){ this.errorDescription=errorDescription; }
-
- public String getErrorDescription() {
- return this.errorDescription;
- }
-
-
-
-
-
-
-
-}
diff --git a/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java b/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java
deleted file mode 100644
index 0afd9eea..00000000
--- a/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java
+++ /dev/null
@@ -1,107 +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.eelf.logging.format;
-
-
-
-/**
- * @author inam
- *
- */
-public enum ErrorCodes {
-
-
- /*
- * 100-199 Security/Permission Related - Authentication problems
- * [ERR100E] Missing Information
- * [ERR101E] Authentication error occured
- *
- * 200-299 Availability/Timeout Related/IO - connectivity error - connection timeout
- * [ERR200E] Connectivity
- * [ERR201E] Host not available
- * [ERR202E] Error while connecting to Cassandra cluster
- * [ERR203E] IO Error has occured
- * [ERR204E] Execution Interrupted
- * [ERR205E] Session Expired
- * [ERR206E] Cache not authenticated
- *
- *
- * 300-399 Data Access/Integrity Related
- *
- * 400-499 - Cassandra Query Related
- * [ERR400E] Error while processing prepared query object
- * [ERR401E] Executing Session Failure for Request
- * [ERR402E] Ill formed queryObject for the request
- * [ERR403E] Error processing Prepared Query Object
- *
- * 500-599 - Zookeepr/Locking Related
- * [ERR500E] Invalid lock
- * [ERR501E] Locking Error has occured
- * [ERR502E] Zookeeper error has occured
- * [ERR503E] Failed to aquire lock store handle
- * [ERR504E] Failed to create Lock Reference
- * [ERR505E] Lock does not exist
- * [ERR506E] Failed to aquire lock
- * [ERR507E] Lock not aquired
- * [ERR508E] Lock state not set
- * [ERR509E] Lock not destroyed
- * [ERR510E] Lock not released
- * [ERR511E] Lock not deleted
- * [ERR512E] Failed to get ZK Lock Handle
- *
- *
- * 600 - 699 - Music Service Errors
- * [ERR600E] Error initializing the cache
- *
- * 700-799 Schema Interface Type/Validation - received Pay-load checksum is
- * invalid - received JSON is not valid
- *
- * 800-899 Business/Flow Processing Related - check out to service is not
- * allowed - Roll-back is done - failed to generate heat file
- *
- *
- * 900-999 Unknown Errors - Unexpected exception
- * [ERR900E] Unexpected error occured
- * [ERR901E] Number format exception
- *
- *
- * 1000-1099 Reserved - do not use
- *
- */
-
- /*SUCCESS("Success"), FAILURE("Failure");
-
- private String result;
-
- ResultType(String result) {
- this.result = result;
- }
-
- public String getResult() {
- return result;
- }
-*/
-
-
-
-}
diff --git a/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java b/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java
deleted file mode 100644
index 4e798239..00000000
--- a/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java
+++ /dev/null
@@ -1,38 +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.eelf.logging.format;
-
-/**
- * @author inam
- *
- */
-public enum ErrorSeverity {
- INFO,
- WARN,
- ERROR,
- FATAL,
- CRITICAL,
- MAJOR,
- MINOR,
- NONE,
-}
diff --git a/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java b/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java
deleted file mode 100644
index 9bdbf20f..00000000
--- a/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java
+++ /dev/null
@@ -1,46 +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.eelf.logging.format;
-
-import com.att.eelf.i18n.EELFResolvableErrorEnum;
-
-/**
- * @author inam
- *
- */
-public enum ErrorTypes implements EELFResolvableErrorEnum {
-
-
- CONNECTIONERROR,
- SESSIONEXPIRED,
- AUTHENTICATIONERROR,
- CACHEERROR,
- SERVICEUNAVAILABLE,
- QUERYERROR,
- DATAERROR,
- GENERALSERVICEERROR,
- MUSICSERVICEERROR,
- LOCKINGERROR,
- UNKNOWN,
-
-}
diff --git a/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java b/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java
deleted file mode 100644
index 83bb1b8a..00000000
--- a/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java
+++ /dev/null
@@ -1,54 +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.exceptions;
-
-import java.io.EOFException;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.ExceptionMapper;
-import javax.ws.rs.ext.Provider;
-
-import org.codehaus.jackson.map.exc.UnrecognizedPropertyException;
-import org.onap.music.main.ResultType;
-import org.onap.music.response.jsonobjects.JsonResponse;
-
-@Provider
-public class MusicExceptionMapper implements ExceptionMapper<Exception> {
- @Override
- public Response toResponse(Exception exception) {
- if(exception instanceof UnrecognizedPropertyException) {
- return Response.status(Response.Status.BAD_REQUEST).
- entity(new JsonResponse(ResultType.FAILURE).setError("Unknown field :"+((UnrecognizedPropertyException) exception).getUnrecognizedPropertyName()).toMap()).
- build();
- }
- else if(exception instanceof EOFException) {
- return Response.status(Response.Status.BAD_REQUEST).
- entity(new JsonResponse(ResultType.FAILURE).setError("Request body cannot be empty").toMap()).
- build();
- }
- else {
- return Response.status(Response.Status.BAD_REQUEST).
- entity(new JsonResponse(ResultType.FAILURE).setError(exception.getMessage()).toMap()).
- build();
- }
- }
-}
diff --git a/src/main/java/org/onap/music/exceptions/MusicLockingException.java b/src/main/java/org/onap/music/exceptions/MusicLockingException.java
deleted file mode 100644
index ab70c54c..00000000
--- a/src/main/java/org/onap/music/exceptions/MusicLockingException.java
+++ /dev/null
@@ -1,75 +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.exceptions;
-
-/**
- * @author inam
- *
- */
-public class MusicLockingException extends Exception {
-
- /**
- *
- */
- public MusicLockingException() {
-
- }
-
- /**
- * @param message
- */
- public MusicLockingException(String message) {
- super(message);
-
- }
-
- /**
- * @param cause
- */
- public MusicLockingException(Throwable cause) {
- super(cause);
-
- }
-
- /**
- * @param message
- * @param cause
- */
- public MusicLockingException(String message, Throwable cause) {
- super(message, cause);
-
- }
-
- /**
- * @param message
- * @param cause
- * @param enableSuppression
- * @param writableStackTrace
- */
- public MusicLockingException(String message, Throwable cause, boolean enableSuppression,
- boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
-
- }
-
-}
diff --git a/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java b/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java
deleted file mode 100644
index f489cd45..00000000
--- a/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * ===================================================================
- * Modifications Copyright (c) 2018 IBM
- * ===================================================================
- * 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.exceptions;
-
-/**
- * @author inam
- *
- */
-public class MusicPolicyVoilationException extends Exception {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- /**
- *
- */
- public MusicPolicyVoilationException() {
-
- }
-
- /**
- * @param message
- */
- public MusicPolicyVoilationException(String message) {
- super(message);
-
- }
-
- /**
- * @param cause
- */
- public MusicPolicyVoilationException(Throwable cause) {
- super(cause);
-
- }
-
- /**
- * @param message
- * @param cause
- */
- public MusicPolicyVoilationException(String message, Throwable cause) {
- super(message, cause);
-
- }
-
- /**
- * @param message
- * @param cause
- * @param enableSuppression
- * @param writableStackTrace
- */
- public MusicPolicyVoilationException(String message, Throwable cause, boolean enableSuppression,
- boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
-
- }
-
-}
diff --git a/src/main/java/org/onap/music/exceptions/MusicQueryException.java b/src/main/java/org/onap/music/exceptions/MusicQueryException.java
deleted file mode 100644
index 803f993f..00000000
--- a/src/main/java/org/onap/music/exceptions/MusicQueryException.java
+++ /dev/null
@@ -1,90 +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.exceptions;
-
-
-
-/**
- * @author inam
- *
- */
-public class MusicQueryException extends Exception {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private int errorCode;
-
-
- /**
- *
- */
- public MusicQueryException() {
- super();
- }
-
- /**
- * @param message
- */
- public MusicQueryException(String message) {
- super(message);
- }
-
-
-
- /**
- * @param message
- */
- public MusicQueryException(String message, int errorCode) {
- super(message);
- this.errorCode = errorCode;
- }
-
- /**
- * @param cause
- */
- public MusicQueryException(Throwable cause) {
- super(cause);
- }
-
- /**
- * @param message
- * @param cause
- */
- public MusicQueryException(String message, Throwable cause) {
- super(message, cause);
- }
-
- /**
- * @param message
- * @param cause
- * @param enableSuppression
- * @param writableStackTrace
- */
- public MusicQueryException(String message, Throwable cause, boolean enableSuppression,
- boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- }
-
-}
diff --git a/src/main/java/org/onap/music/exceptions/MusicServiceException.java b/src/main/java/org/onap/music/exceptions/MusicServiceException.java
deleted file mode 100644
index 76e1f948..00000000
--- a/src/main/java/org/onap/music/exceptions/MusicServiceException.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * ===================================================================
- * Modifications Copyright (C) 2018 IBM.
- * ===================================================================
- * 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.exceptions;
-
-/**
- * @author inam
- *
- */
-public class MusicServiceException extends Exception {
-
-
- private int errorCode;
- private String errorMessage;
-
- public MusicServiceException() {
- super();
- }
-
-
- public MusicServiceException(String message) {
- super(message);
-
- }
-
- public MusicServiceException(String message, int errorCode) {
- super(message);
- this.errorCode=errorCode;
- }
-
- public MusicServiceException(String message, int errorCode, String errorMessage) {
- super(message);
- this.errorCode=errorCode;
- this.errorMessage=errorMessage;
- }
-
- public MusicServiceException(Throwable cause) {
- super(cause);
-
- }
-
-
- public MusicServiceException(String message, Throwable cause) {
- super(message, cause);
-
- }
-
-
- public MusicServiceException(String message, Throwable cause, boolean enableSuppression,
- boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
-
- }
- public void setErrorCode(int errorCode) {
- this.errorCode=errorCode;
- }
-
- public int getErrorCode() {
- return errorCode;
- }
- public void setErrorMessage(String errorMessage) {
- this.errorMessage=errorMessage;
- }
- public String getErrorMessage() {
- return errorMessage;
- }
-}
diff --git a/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java b/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java
deleted file mode 100644
index 4ed63575..00000000
--- a/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * Modifications Copyright (C) 2019 IBM.
- * ===================================================================
- * 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.lockingservice.cassandra;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.onap.music.datastore.MusicDataStore;
-import org.onap.music.datastore.PreparedQueryObject;
-import org.onap.music.eelf.logging.EELFLoggerDelegate;
-import org.onap.music.exceptions.MusicQueryException;
-import org.onap.music.exceptions.MusicServiceException;
-
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Row;
-
-/*
- * This is the lock store that is built on top of Cassandra that is used by MUSIC to maintain lock state.
- */
-
-public class CassaLockStore {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CassaLockStore.class);
- private static String table_prepend_name = "lockQ_";
-
- public class LockObject{
- public String lockRef;
- public String createTime;
- public String acquireTime;
- public LockObject(String lockRef, String createTime, String acquireTime) {
- this.lockRef = lockRef;
- this.acquireTime = acquireTime;
- this.createTime = createTime;
-
- }
- }
- MusicDataStore dsHandle;
- public CassaLockStore() {
- dsHandle = new MusicDataStore();
- }
-
- public CassaLockStore(MusicDataStore dsHandle) {
- this.dsHandle=dsHandle;
- }
-
-
- /**
- *
- * This method creates a shadow locking table for every main table in Cassandra. This table tracks all information regarding locks.
- * @param keyspace of the application.
- * @param table of the application.
- * @return true if the operation was successful.
- * @throws MusicServiceException
- * @throws MusicQueryException
- */
- public boolean createLockQueue(String keyspace, String table) throws MusicServiceException, MusicQueryException {
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Create lock queue/table for " + keyspace+"."+table);
- table = table_prepend_name+table;
- String tabQuery = "CREATE TABLE IF NOT EXISTS "+keyspace+"."+table
- + " ( key text, lockReference bigint, createTime text, acquireTime text, guard bigint static, PRIMARY KEY ((key), lockReference) ) "
- + "WITH CLUSTERING ORDER BY (lockReference ASC);";
- PreparedQueryObject queryObject = new PreparedQueryObject();
-
- queryObject.appendQueryString(tabQuery);
- boolean result;
- result = dsHandle.executePut(queryObject, "eventual");
- return result;
- }
-
- /**
- * This method creates a lock reference for each invocation. The lock references are monotonically increasing timestamps.
- * @param keyspace of the locks.
- * @param table of the locks.
- * @param lockName is the primary key of the lock table
- * @return the UUID lock reference.
- * @throws MusicServiceException
- * @throws MusicQueryException
- */
- public String genLockRefandEnQueue(String keyspace, String table, String lockName) throws MusicServiceException, MusicQueryException {
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Create lock reference for " + keyspace + "." + table + "." + lockName);
- String lockTable ="";
- lockTable = table_prepend_name+table;
-
-
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
- String selectQuery = "SELECT guard FROM " + keyspace + "." + lockTable + " WHERE key=?;";
-
- queryObject.addValue(lockName);
- queryObject.appendQueryString(selectQuery);
- ResultSet gqResult = dsHandle.executeOneConsistencyGet(queryObject);
- List<Row> latestGuardRow = gqResult.all();
-
- long prevGuard = 0;
- long lockRef = 1;
- if (!latestGuardRow.isEmpty()) {
- prevGuard = latestGuardRow.get(0).getLong(0);
- lockRef = prevGuard + 1;
- }
-
- long lockEpochMillis = System.currentTimeMillis();
-
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Created lock reference for " + keyspace + "." + lockTable + "." + lockName + ":" + lockRef);
-
- queryObject = new PreparedQueryObject();
- String insQuery = "BEGIN BATCH" +
- " UPDATE " + keyspace + "." + lockTable +
- " SET guard=? WHERE key=? IF guard = " + (prevGuard == 0 ? "NULL" : "?") +";" +
- " INSERT INTO " + keyspace + "." + lockTable +
- "(key, lockReference, createTime, acquireTime) VALUES (?,?,?,?) IF NOT EXISTS; APPLY BATCH;";
-
- queryObject.addValue(lockRef);
- queryObject.addValue(lockName);
- if (prevGuard != 0)
- queryObject.addValue(prevGuard);
-
- queryObject.addValue(lockName);
- queryObject.addValue(lockRef);
- queryObject.addValue(String.valueOf(lockEpochMillis));
- queryObject.addValue("0");
- queryObject.appendQueryString(insQuery);
- dsHandle.executePut(queryObject, "critical");
- return "$"+keyspace+"."+table+"."+lockName+"$"+ lockRef;
- }
-
- /**
- * Returns a result set containing the list of clients waiting for a particular lock
- * @param keyspace
- * @param table
- * @param key
- * @return list of lockrefs in the queue
- * @throws MusicServiceException
- * @throws MusicQueryException
- */
- public List<String> getLockQueue(String keyspace, String table, String key)
- throws MusicServiceException, MusicQueryException {
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Getting the queue for " + keyspace+"."+table+"."+key);
- table = table_prepend_name+table;
- String selectQuery = "select * from " + keyspace + "." + table + " where key='" + key + "';";
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString(selectQuery);
- ResultSet rs = dsHandle.executeOneConsistencyGet(queryObject);
- ArrayList<String> lockQueue = new ArrayList<>();
- for (Row row: rs) {
- lockQueue.add(Long.toString(row.getLong("lockReference")));
- }
- return lockQueue;
- }
-
-
- /**
- * Returns a result set containing the list of clients waiting for a particular lock
- * @param keyspace
- * @param table
- * @param key
- * @return size of lockrefs queue
- * @throws MusicServiceException
- * @throws MusicQueryException
- */
- public long getLockQueueSize(String keyspace, String table, String key)
- throws MusicServiceException, MusicQueryException {
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Getting the queue size for " + keyspace+"."+table+"."+key);
- table = table_prepend_name+table;
- String selectQuery = "select count(*) from " + keyspace + "." + table + " where key='" + key + "';";
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString(selectQuery);
- ResultSet rs = dsHandle.executeOneConsistencyGet(queryObject);
- return rs.one().getLong("count");
- }
-
-
- /**
- * This method returns the top of lock table/queue for the key.
- * @param keyspace of the application.
- * @param table of the application.
- * @param key is the primary key of the application table
- * @return the UUID lock reference.
- * @throws MusicServiceException
- * @throws MusicQueryException
- */
- public LockObject peekLockQueue(String keyspace, String table, String key) throws MusicServiceException, MusicQueryException{
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Peek in lock table for " + keyspace+"."+table+"."+key);
- table = table_prepend_name+table;
- String selectQuery = "select * from "+keyspace+"."+table+" where key='"+key+"' LIMIT 1;";
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString(selectQuery);
- ResultSet results = dsHandle.executeOneConsistencyGet(queryObject);
- Row row = results.one();
- String lockReference = "" + row.getLong("lockReference");
- String createTime = row.getString("createTime");
- String acquireTime = row.getString("acquireTime");
-
- return new LockObject(lockReference, createTime,acquireTime);
- }
-
-
- /**
- * This method removes the lock ref from the lock table/queue for the key.
- * @param keyspace of the application.
- * @param table of the application.
- * @param key is the primary key of the application table
- * @param lockReference the lock reference that needs to be dequeued.
- * @throws MusicServiceException
- * @throws MusicQueryException
- */
- public void deQueueLockRef(String keyspace, String table, String key, String lockReference) throws MusicServiceException, MusicQueryException{
- table = table_prepend_name+table;
- PreparedQueryObject queryObject = new PreparedQueryObject();
- Long lockReferenceL = Long.parseLong(lockReference.substring(lockReference.lastIndexOf('$')+1));
- String deleteQuery = "delete from "+keyspace+"."+table+" where key='"+key+"' AND lockReference ="+lockReferenceL+" IF EXISTS;";
- queryObject.appendQueryString(deleteQuery);
- dsHandle.executePut(queryObject, "critical");
- }
-
-
- public void updateLockAcquireTime(String keyspace, String table, String key, String lockReference) throws MusicServiceException, MusicQueryException{
- table = table_prepend_name+table;
- PreparedQueryObject queryObject = new PreparedQueryObject();
- Long lockReferenceL = Long.parseLong(lockReference);
- String updateQuery = "update "+keyspace+"."+table+" set acquireTime='"+ System.currentTimeMillis()+"' where key='"+key+"' AND lockReference = "+lockReferenceL+" IF EXISTS;";
- queryObject.appendQueryString(updateQuery);
- dsHandle.executePut(queryObject, "eventual");
-
- }
-
-
-}
diff --git a/src/main/java/org/onap/music/lockingservice/cassandra/MusicLockState.java b/src/main/java/org/onap/music/lockingservice/cassandra/MusicLockState.java
deleted file mode 100644
index 5128e2cd..00000000
--- a/src/main/java/org/onap/music/lockingservice/cassandra/MusicLockState.java
+++ /dev/null
@@ -1,138 +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.lockingservice.cassandra;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-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;
-
-// the state variable that will be stored in the locking service, capturing the transitions of
-public class MusicLockState implements Serializable {
- public enum LockStatus {
- UNLOCKED, BEING_LOCKED, LOCKED
- };// captures the state of the lock
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicLockState.class);
- LockStatus lockStatus;
- boolean needToSyncQuorum = false;
- String lockHolder;
- long leasePeriod = Long.MAX_VALUE, leaseStartTime = -1;
-
- private String errorMessage = null;
-
- public MusicLockState(String errorMessage) {
- this.errorMessage = errorMessage;
- }
-
- public MusicLockState(LockStatus lockStatus, String lockHolder) {
- this.lockStatus = lockStatus;
- this.lockHolder = lockHolder;
- }
-
- public MusicLockState(LockStatus lockStatus, String lockHolder, boolean needToSyncQuorum) {
- this.lockStatus = lockStatus;
- this.lockHolder = lockHolder;
- this.needToSyncQuorum = needToSyncQuorum;
- }
-
-
- public long getLeasePeriod() {
- return leasePeriod;
- }
-
- public boolean isNeedToSyncQuorum() {
- return needToSyncQuorum;
- }
-
-
-
- public void setLeasePeriod(long leasePeriod) {
- this.leasePeriod = leasePeriod;
- }
-
-
- public long getLeaseStartTime() {
- return leaseStartTime;
- }
-
-
- public void setLeaseStartTime(long leaseStartTime) {
- this.leaseStartTime = leaseStartTime;
- }
-
-
-
- public LockStatus getLockStatus() {
- return lockStatus;
- }
-
- public void setLockStatus(LockStatus lockStatus) {
- this.lockStatus = lockStatus;
- }
-
- public String getLockHolder() {
- return lockHolder;
- }
-
- public void setLockHolder(String lockHolder) {
- this.lockHolder = lockHolder;
- }
-
- public String getErrorMessage() {
- return errorMessage;
- }
-
- public byte[] serialize() {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ObjectOutput out = null;
- try {
- out = new ObjectOutputStream(bos);
- out.writeObject(this);
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
- }
- return bos.toByteArray();
- }
-
- public static MusicLockState deSerialize(byte[] data) {
- ByteArrayInputStream bis = new ByteArrayInputStream(data);
- Object o = null;
- ObjectInput in = null;
- try {
- in = new ObjectInputStream(bis);
- o = in.readObject();
- } catch (ClassNotFoundException | IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.UNKNOWN);
- }
- return (MusicLockState) o;
- }
-}
diff --git a/src/main/java/org/onap/music/main/MusicCore.java b/src/main/java/org/onap/music/main/MusicCore.java
deleted file mode 100644
index 221e680b..00000000
--- a/src/main/java/org/onap/music/main/MusicCore.java
+++ /dev/null
@@ -1,162 +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.main;
-
-import java.util.List;
-import java.util.Map;
-
-import org.onap.music.datastore.Condition;
-import org.onap.music.datastore.PreparedQueryObject;
-import org.onap.music.eelf.logging.EELFLoggerDelegate;
-import org.onap.music.exceptions.MusicLockingException;
-import org.onap.music.exceptions.MusicQueryException;
-import org.onap.music.exceptions.MusicServiceException;
-import org.onap.music.lockingservice.cassandra.CassaLockStore;
-import org.onap.music.lockingservice.cassandra.MusicLockState;
-import org.onap.music.service.MusicCoreService;
-import org.onap.music.service.impl.MusicCassaCore;
-
-import com.datastax.driver.core.ResultSet;
-
-public class MusicCore {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCore.class);
- private static boolean unitTestRun=true;
-
- private static MusicCoreService musicCore = MusicUtil.getMusicCoreService();
- public static CassaLockStore mLockHandle;
-
-
- /**
- * Acquire lock
- * @param fullyQualifiedKey DO NOT RELY ON THIS KEY WORKING. INCLUDE THE KEY IN THE LOCKID.
- * @param lockId - the full lock id (key + lockRef)
- * @return
- * @throws MusicLockingException
- * @throws MusicQueryException
- * @throws MusicServiceException
- */
- public static ReturnType acquireLock(String fullyQualifiedKey, String lockId)
- throws MusicLockingException, MusicQueryException, MusicServiceException {
- return musicCore.acquireLock(fullyQualifiedKey, lockId);
- }
-
- public static ReturnType acquireLockWithLease(String key, String lockId, long leasePeriod)
- throws MusicLockingException, MusicQueryException, MusicServiceException {
- return musicCore.acquireLockWithLease(key, lockId, leasePeriod);
- }
-
- public static String createLockReference(String fullyQualifiedKey) {
- return musicCore.createLockReference(fullyQualifiedKey);
- }
-
- public static ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject,
- String consistency) throws MusicServiceException {
- return musicCore.createTable(keyspace, table, tableQueryObject, consistency);
- }
-
- public static ResultSet quorumGet(PreparedQueryObject query) {
- return musicCore.quorumGet(query);
- }
-
- public static String whoseTurnIsIt(String fullyQualifiedKey) {
- return musicCore.whoseTurnIsIt(fullyQualifiedKey);
- }
-
- public static void destroyLockRef(String lockId) {
- musicCore.destroyLockRef(lockId);
- }
-
- public static ReturnType eventualPut(PreparedQueryObject queryObject) {
- return musicCore.eventualPut(queryObject);
- }
-
- public static ReturnType eventualPut_nb(PreparedQueryObject queryObject,String keyspace,
- String tablename,String primaryKey) {
- return musicCore.eventualPut_nb(queryObject, keyspace, tablename, primaryKey);
- }
-
- public static ReturnType criticalPut(String keyspace, String table, String primaryKeyValue,
- PreparedQueryObject queryObject, String lockReference, Condition conditionInfo) {
- return musicCore.criticalPut(keyspace, table, primaryKeyValue, queryObject, lockReference, conditionInfo);
- }
-
- public static ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency)
- throws MusicServiceException {
- return musicCore.nonKeyRelatedPut(queryObject, consistency);
- }
-
- public static ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException{
- return musicCore.get(queryObject);
- }
-
- public static ResultSet criticalGet(String keyspace, String table, String primaryKeyValue,
- PreparedQueryObject queryObject, String lockReference) throws MusicServiceException {
- return musicCore.criticalGet(keyspace, table, primaryKeyValue, queryObject,lockReference);
- }
-
- public static ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException,
- MusicQueryException,MusicServiceException {
- return musicCore.atomicPut(keyspaceName, tableName, primaryKey, queryObject, conditionInfo);
- }
-
- public static ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException {
- return musicCore.atomicGet(keyspaceName, tableName, primaryKey, queryObject);
- }
-
- public static List<String> getLockQueue(String fullyQualifiedKey)
- throws MusicServiceException, MusicQueryException, MusicLockingException {
- return musicCore.getLockQueue(fullyQualifiedKey);
- }
-
- public static long getLockQueueSize(String fullyQualifiedKey)
- throws MusicServiceException, MusicQueryException, MusicLockingException {
- return musicCore.getLockQueueSize(fullyQualifiedKey);
- }
-
- public static void deleteLock(String lockName) throws MusicLockingException {
- musicCore.deleteLock(lockName);
- }
-
- public static ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName,
- String primaryKey, PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException {
- return musicCore.atomicPutWithDeleteLock(keyspaceName, tableName, primaryKey, queryObject, conditionInfo);
- }
-
- public static ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException {
- return musicCore.atomicGetWithDeleteLock(keyspaceName, tableName, primaryKey, queryObject);
- }
-
- public static Map<String, Object> validateLock(String lockName) {
- return musicCore.validateLock(lockName);
- }
-
- public static MusicLockState releaseLock(String lockId, boolean voluntaryRelease) {
- return musicCore.releaseLock(lockId, voluntaryRelease);
- }
-
-
-} \ No newline at end of file
diff --git a/src/main/java/org/onap/music/main/MusicDigest.java b/src/main/java/org/onap/music/main/MusicDigest.java
deleted file mode 100644
index d05969e3..00000000
--- a/src/main/java/org/onap/music/main/MusicDigest.java
+++ /dev/null
@@ -1,79 +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.main;
-
-/**
- *
- *
- */
-public class MusicDigest {
- private String evPutStatus;
- private String vectorTs;
-
- /**
- * @param evPutStatus
- * @param vectorTs
- */
- public MusicDigest(String evPutStatus, String vectorTs) {
- this.evPutStatus = evPutStatus;
- this.vectorTs = vectorTs;
- }
-
- /**
- * @return
- */
- public String getEvPutStatus() {
- return evPutStatus;
- }
-
- /**
- * @param evPutStatus
- */
- public void setEvPutStatus(String evPutStatus) {
- this.evPutStatus = evPutStatus;
- }
-
- /**
- * @return
- */
- public String getVectorTs() {
- return vectorTs;
- }
-
- /**
- * @param vectorTs
- */
- public void setVectorTs(String vectorTs) {
- this.vectorTs = vectorTs;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return vectorTs + "|" + evPutStatus;
- }
-}
-
diff --git a/src/main/java/org/onap/music/main/MusicUtil.java b/src/main/java/org/onap/music/main/MusicUtil.java
deleted file mode 100755
index b737377d..00000000
--- a/src/main/java/org/onap/music/main/MusicUtil.java
+++ /dev/null
@@ -1,846 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * ===================================================================
- * Modifications Copyright (c) 2018 IBM.
- * Modifications Copyright (c) 2019 Samsung.
- * ===================================================================
- * 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.main;
-
-import com.datastax.driver.core.ColumnDefinitions;
-import com.datastax.driver.core.ColumnDefinitions.Definition;
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Row;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.math.BigInteger;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Scanner;
-import java.util.StringTokenizer;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import org.onap.music.datastore.MusicDataStoreHandle;
-import org.onap.music.datastore.PreparedQueryObject;
-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.exceptions.MusicQueryException;
-import org.onap.music.exceptions.MusicServiceException;
-import org.onap.music.service.MusicCoreService;
-import org.onap.music.service.impl.MusicCassaCore;
-
-import com.datastax.driver.core.ConsistencyLevel;
-import com.datastax.driver.core.DataType;
-import com.sun.jersey.core.util.Base64;
-
-/**
- * @author nelson24
- *
- * Properties This will take Properties and load them into MusicUtil.
- * This is a hack for now. Eventually it would bebest to do this in
- * another way.
- *
- */
-public class MusicUtil {
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
-
- public static final String ATOMIC = "atomic";
- public static final String EVENTUAL = "eventual";
- public static final String CRITICAL = "critical";
- public static final String EVENTUAL_NB = "eventual_nb";
- public static final String ALL = "all";
- public static final String QUORUM = "quorum";
- public static final String ONE = "one";
- public static final String ATOMICDELETELOCK = "atomic_delete_lock";
- public static final String DEFAULTKEYSPACENAME = "TBD";
- private static final String XLATESTVERSION = "X-latestVersion";
- private static final String XMINORVERSION = "X-minorVersion";
- private static final String XPATCHVERSION = "X-patchVersion";
- public static final String SELECT = "select";
- public static final String INSERT = "insert";
- public static final String UPDATE = "update";
- public static final String UPSERT = "upsert";
- public static final String USERID = "userId";
- public static final String PASSWORD = "password";
- public static final String CASSANDRA = "cassandra";
-
- public static final String AUTHORIZATION = "Authorization";
-
- private static final String LOCALHOST = "localhost";
- private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties";
-
- private static int myId = 0;
- private static ArrayList<String> allIds = new ArrayList<>();
- private static String publicIp = "";
- private static ArrayList<String> allPublicIps = new ArrayList<>();
- private static String myZkHost = LOCALHOST;
- private static String myCassaHost = LOCALHOST;
- private static String defaultMusicIp = LOCALHOST;
- private static int cassandraPort = 9042;
- private static int notifytimeout = 30000;
- private static int notifyinterval = 5000;
- private static int cacheObjectMaxLife = -1;
- private static String lockUsing = MusicUtil.CASSANDRA;
- private static boolean isCadi = false;
-
- private static boolean debug = true;
- private static String version = "2.3.0";
- private static String musicRestIp = LOCALHOST;
- private static String musicPropertiesFilePath = PROPERTIES_FILE;
- private static long defaultLockLeasePeriod = 6000;
- private static final String[] propKeys = new String[] { "cassandra.host", "music.ip", "debug",
- "version", "music.rest.ip", "music.properties", "lock.lease.period", "id", "all.ids", "public.ip",
- "all.pubic.ips", "cassandra.user", "cassandra.password", "aaf.endpoint.url","admin.username","admin.password","aaf.admin.url",
- "music.namespace","admin.aaf.role","cassandra.port","lock.using"};
- private static final String[] cosistencyLevel = new String[] {
- "ALL","EACH_QUORUM","QUORUM","LOCAL_QUORUM","ONE","TWO","THREE","LOCAL_ONE","ANY","SERIAL","LOCAL_SERIAL"};
- private static final Map<String,ConsistencyLevel> consistencyName = new HashMap<>();
- static {
- consistencyName.put("ONE",ConsistencyLevel.ONE);
- consistencyName.put("TWO",ConsistencyLevel.TWO);
- consistencyName.put("THREE",ConsistencyLevel.THREE);
- consistencyName.put("SERIAL",ConsistencyLevel.SERIAL);
- consistencyName.put("ALL",ConsistencyLevel.ALL);
- consistencyName.put("EACH_QUORUM",ConsistencyLevel.EACH_QUORUM);
- consistencyName.put("QUORUM",ConsistencyLevel.QUORUM);
- consistencyName.put("LOCAL_QUORUM",ConsistencyLevel.LOCAL_QUORUM);
- consistencyName.put("LOCAL_ONE",ConsistencyLevel.LOCAL_ONE);
- consistencyName.put("LOCAL_SERIAL",ConsistencyLevel.LOCAL_SERIAL);
- }
-
- private static String cassName = "cassandra";
- private static String cassPwd;
- private static String aafEndpointUrl = null;
- public static ConcurrentMap<String, Long> zkNodeMap = new ConcurrentHashMap<>();
- private static String adminId = "username";
- private static String adminPass= "password";
- private static String aafAdminUrl= null;
- private static String musicNamespace= "com.att.music.api";
- private static String adminAafRole= "com.att.music.api.admin_api";
-
- public static final long MusicEternityEpochMillis = 1533081600000L; // Wednesday, August 1, 2018 12:00:00 AM
-
- public static final long MaxLockReferenceTimePart = 1000000000000L; // millis after eternity (eq sometime in 2050)
-
- public static final long MaxCriticalSectionDurationMillis = 1L * 24 * 60 * 60 * 1000; // 1 day
-
-
- public static String getLockUsing() {
- return lockUsing;
- }
-
-
- public static void setLockUsing(String lockUsing) {
- MusicUtil.lockUsing = lockUsing;
- }
-
- public static String getAafAdminUrl() {
- return aafAdminUrl;
- }
-
-
- public static void setAafAdminUrl(String aafAdminUrl) {
- MusicUtil.aafAdminUrl = aafAdminUrl;
- }
-
-
- public static String getMusicNamespace() {
- return musicNamespace;
- }
-
-
- public static void setMusicNamespace(String musicNamespace) {
- MusicUtil.musicNamespace = musicNamespace;
- }
-
-
- public static String getAdminAafRole() {
- return adminAafRole;
- }
-
-
- public static void setAdminAafRole(String adminAafRole) {
- MusicUtil.adminAafRole = adminAafRole;
- }
-
-
-
- public static String getAdminId() {
- return adminId;
- }
-
-
- public static void setAdminId(String adminId) {
- MusicUtil.adminId = adminId;
- }
-
-
- public static String getAdminPass() {
- return adminPass;
- }
-
- public static void setAdminPass(String adminPass) {
- MusicUtil.adminPass = adminPass;
- }
-
-
- private MusicUtil() {
- throw new IllegalStateException("Utility Class");
- }
- /**
- *
- * @return cassandra port
- */
- public static int getCassandraPort() {
- return cassandraPort;
- }
-
- /**
- * set cassandra port
- * @param cassandraPort
- */
- public static void setCassandraPort(int cassandraPort) {
- MusicUtil.cassandraPort = cassandraPort;
- }
- /**
- * @return the cassName
- */
- public static String getCassName() {
- return cassName;
- }
-
- /**
- * @return the cassPwd
- */
- public static String getCassPwd() {
- return cassPwd;
- }
-
- /**
- * @return the aafEndpointUrl
- */
- public static String getAafEndpointUrl() {
- return aafEndpointUrl;
- }
-
- /**
- *
- * @param aafEndpointUrl
- */
- public static void setAafEndpointUrl(String aafEndpointUrl) {
- MusicUtil.aafEndpointUrl = aafEndpointUrl;
- }
-
- /**
- *
- * @return
- */
- public static int getMyId() {
- return myId;
- }
-
- /**
- *
- * @param myId
- */
- public static void setMyId(int myId) {
- MusicUtil.myId = myId;
- }
-
- /**
- *
- * @return
- */
- public static List<String> getAllIds() {
- return allIds;
- }
-
- /**
- *
- * @param allIds
- */
- public static void setAllIds(List<String> allIds) {
- MusicUtil.allIds = (ArrayList<String>) allIds;
- }
-
- /**
- *
- * @return
- */
- public static String getPublicIp() {
- return publicIp;
- }
-
- /**
- *
- * @param publicIp
- */
- public static void setPublicIp(String publicIp) {
- MusicUtil.publicIp = publicIp;
- }
-
- /**
- *
- * @return
- */
- public static List<String> getAllPublicIps() {
- return allPublicIps;
- }
-
- /**
- *
- * @param allPublicIps
- */
- public static void setAllPublicIps(List<String> allPublicIps) {
- MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps;
- }
-
- /**
- * Returns An array of property names that should be in the Properties
- * files.
- *
- * @return
- */
- public static String[] getPropkeys() {
- return propKeys;
- }
-
- /**
- * Get MusicRestIp - default = localhost property file value - music.rest.ip
- *
- * @return
- */
- public static String getMusicRestIp() {
- return musicRestIp;
- }
-
- /**
- * Set MusicRestIp
- *
- * @param musicRestIp
- */
- public static void setMusicRestIp(String musicRestIp) {
- MusicUtil.musicRestIp = musicRestIp;
- }
-
- /**
- * Get MusicPropertiesFilePath - Default = /opt/music/music.properties
- * property file value - music.properties
- *
- * @return
- */
- public static String getMusicPropertiesFilePath() {
- return musicPropertiesFilePath;
- }
-
- /**
- * Set MusicPropertiesFilePath
- *
- * @param musicPropertiesFilePath
- */
- public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) {
- MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath;
- }
-
- /**
- * Get DefaultLockLeasePeriod - Default = 6000 property file value -
- * lock.lease.period
- *
- * @return
- */
- public static long getDefaultLockLeasePeriod() {
- return defaultLockLeasePeriod;
- }
-
- /**
- * Set DefaultLockLeasePeriod
- *
- * @param defaultLockLeasePeriod
- */
- public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) {
- MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod;
- }
-
- /**
- * Set Debug
- *
- * @param debug
- */
- public static void setDebug(boolean debug) {
- MusicUtil.debug = debug;
- }
-
- /**
- * Is Debug - Default = true property file value - debug
- *
- * @return
- */
- public static boolean isDebug() {
- return debug;
- }
-
- /**
- * Set Version
- *
- * @param version
- */
- public static void setVersion(String version) {
- MusicUtil.version = version;
- }
-
- /**
- * Return the version property file value - version
- *
- * @return
- */
- public static String getVersion() {
- return version;
- }
-
- /**
- * Get MyCassHost - Cassandra Hostname - Default = localhost property file
- * value - cassandra.host
- *
- * @return
- */
- public static String getMyCassaHost() {
- return myCassaHost;
- }
-
- /**
- * Set MyCassHost - Cassandra Hostname
- *
- * @param myCassaHost
- */
- public static void setMyCassaHost(String myCassaHost) {
- MusicUtil.myCassaHost = myCassaHost;
- }
-
- /**
- * Get DefaultMusicIp - Default = localhost property file value - music.ip
- *
- * @return
- */
- public static String getDefaultMusicIp() {
- return defaultMusicIp;
- }
-
- /**
- * Set DefaultMusicIp
- *
- * @param defaultMusicIp
- */
- public static void setDefaultMusicIp(String defaultMusicIp) {
- MusicUtil.defaultMusicIp = defaultMusicIp;
- }
-
- /**
- *
- * @return
- */
- public static String getTestType() {
- String testType = "";
- try {
- Scanner fileScanner = new Scanner(new File(""));
- testType = fileScanner.next();// ignore the my id line
- @SuppressWarnings("unused")
- String batchSize = fileScanner.next();// ignore the my public ip
- // line
- fileScanner.close();
- } catch (FileNotFoundException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- }
- return testType;
-
- }
-
- /**
- *
- * @param time
- */
- public static void sleep(long time) {
- try {
- Thread.sleep(time);
- } catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- Thread.currentThread().interrupt();
- }
- }
-
- /**
- * Utility function to check if the query object is valid.
- *
- * @param withparams
- * @param queryObject
- * @return
- */
- public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) {
- if (withparams) {
- int noOfValues = queryObject.getValues().size();
- int noOfParams = 0;
- char[] temp = queryObject.getQuery().toCharArray();
- for (int i = 0; i < temp.length; i++) {
- if (temp[i] == '?')
- noOfParams++;
- }
- return (noOfValues == noOfParams);
- } else {
- return !queryObject.getQuery().isEmpty();
- }
-
- }
-
- public static void setCassName(String cassName) {
- MusicUtil.cassName = cassName;
- }
-
- public static void setCassPwd(String cassPwd) {
- MusicUtil.cassPwd = cassPwd;
- }
-
- @SuppressWarnings("unchecked")
- public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception {
-
- String value = "";
- switch (type.getName()) {
- case UUID:
- value = valueObj + "";
- break;
- case TEXT:
- case VARCHAR:
- String valueString = valueObj + "";
- valueString = valueString.replace("'", "''");
- value = "'" + valueString + "'";
- break;
- case MAP: {
- Map<String, Object> otMap = (Map<String, Object>) valueObj;
- value = "{" + jsonMaptoSqlString(otMap, ",") + "}";
- break;
- }
- default:
- value = valueObj + "";
- break;
- }
- return value;
- }
-
- /**
- *
- * @param colType
- * @param valueObj
- * @return
- * @throws MusicTypeConversionException
- * @throws Exception
- */
- @SuppressWarnings("unchecked")
- public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception {
- String valueObjString = valueObj + "";
- switch (colType.getName()) {
- case UUID:
- return UUID.fromString(valueObjString);
- case VARINT:
- return BigInteger.valueOf(Long.parseLong(valueObjString));
- case BIGINT:
- return Long.parseLong(valueObjString);
- case INT:
- return Integer.parseInt(valueObjString);
- case FLOAT:
- return Float.parseFloat(valueObjString);
- case DOUBLE:
- return Double.parseDouble(valueObjString);
- case BOOLEAN:
- return Boolean.parseBoolean(valueObjString);
- case MAP:
- return (Map<String, Object>) valueObj;
- case LIST:
- return (List<Object>)valueObj;
- case BLOB:
-
- default:
- return valueObjString;
- }
- }
-
- public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) {
- ByteBuffer buffer = ByteBuffer.wrap(valueObj);
- return buffer;
- }
-
- /**
- *
- * Utility function to parse json map into sql like string
- *
- * @param jMap
- * @param lineDelimiter
- * @return
- */
-
- public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) throws Exception{
- StringBuilder sqlString = new StringBuilder();
- int counter = 0;
- for (Map.Entry<String, Object> entry : jMap.entrySet()) {
- Object ot = entry.getValue();
- String value = ot + "";
- if (ot instanceof String) {
- value = "'" + value.replace("'", "''") + "'";
- }
- sqlString.append("'" + entry.getKey() + "':" + value);
- if (counter != jMap.size() - 1)
- sqlString.append(lineDelimiter);
- counter = counter + 1;
- }
- return sqlString.toString();
- }
-
- @SuppressWarnings("unused")
- public static String buildVersion(String major, String minor, String patch) {
- if (minor != null) {
- major += "." + minor;
- if (patch != null) {
- major += "." + patch;
- }
- }
- return major;
- }
-
- /**
- * Currently this will build a header with X-latestVersion, X-minorVersion and X-pathcVersion
- * X-latestVerstion will be equal to the latest full version.
- * X-minorVersion - will be equal to the latest minor version.
- * X-pathVersion - will be equal to the latest patch version.
- * Future plans will change this.
- * @param response
- * @param major
- * @param minor
- * @param patch
- * @return
- */
- public static ResponseBuilder buildVersionResponse(String major, String minor, String patch) {
- ResponseBuilder response = Response.noContent();
- String versionIn = buildVersion(major,minor,patch);
- String version = MusicUtil.getVersion();
- String[] verArray = version.split("\\.",3);
- if ( minor != null ) {
- response.header(XMINORVERSION,minor);
- } else {
- response.header(XMINORVERSION,verArray[1]);
- }
- if ( patch != null ) {
- response.header(XPATCHVERSION,patch);
- } else {
- response.header(XPATCHVERSION,verArray[2]);
- }
- response.header(XLATESTVERSION,version);
- logger.info(EELFLoggerDelegate.applicationLogger,"Version In:" + versionIn);
- return response;
- }
-
-
- public static Map<String,String> extractBasicAuthentication(String authorization){
- Map<String,String> authValues = new HashMap<>();
- if(authorization == null) {
- authValues.put("ERROR", "Authorization cannot be null");
- return authValues;
- }
- authorization = authorization.replaceFirst("Basic", "");
- String decoded = Base64.base64Decode(authorization);
- StringTokenizer token = new StringTokenizer(decoded, ":");
- authValues.put(MusicUtil.USERID, token.nextToken());
- authValues.put(MusicUtil.PASSWORD,token.nextToken());
- return authValues;
-
- }
-
- public static boolean isValidConsistency(String consistency) {
- for (String string : cosistencyLevel) {
- if (string.equalsIgnoreCase(consistency))
- return true;
- }
- return false;
-
- }
-
- public static ConsistencyLevel getConsistencyLevel(String consistency) {
- return consistencyName.get(consistency.toUpperCase());
- }
-
- public static void loadProperties() throws Exception {
- Properties prop = new Properties();
- InputStream input = null;
- try {
- // load the properties file
- input = MusicUtil.class.getClassLoader().getResourceAsStream("music.properties");
- prop.load(input);
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
- throw new Exception();
- } finally {
- if (input != null) {
- try {
- input.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- // get the property value and return it
- MusicUtil.setMyCassaHost(prop.getProperty("cassandra.host"));
- MusicUtil.setCassName(prop.getProperty("cassandra.user"));
- MusicUtil.setCassPwd(prop.getProperty("cassandra.password"));
- MusicUtil.setCassandraPort(Integer.parseInt(prop.getProperty("cassandra.port")));
- MusicUtil.setNotifyTimeOut(Integer.parseInt(prop.getProperty("notify.timeout")));
- MusicUtil.setNotifyInterval(Integer.parseInt(prop.getProperty("notify.interval")));
- MusicUtil.setCacheObjectMaxLife(Integer.parseInt(prop.getProperty("cacheobject.maxlife")));
- }
-
- public static void setNotifyInterval(int notifyinterval) {
- MusicUtil.notifyinterval = notifyinterval;
- }
- public static void setNotifyTimeOut(int notifytimeout) {
- MusicUtil.notifytimeout = notifytimeout;
- }
-
- public static int getNotifyInterval() {
- return MusicUtil.notifyinterval;
- }
-
- public static int getNotifyTimeout() {
- return MusicUtil.notifytimeout;
- }
-
- public static int getCacheObjectMaxLife() {
- return MusicUtil.cacheObjectMaxLife;
- }
-
- public static void setCacheObjectMaxLife(int cacheObjectMaxLife) {
- MusicUtil.cacheObjectMaxLife = cacheObjectMaxLife;
- }
-
- /**
- * Given the time of write for an update in a critical section, this method provides a transformed timestamp
- * that ensures that a previous lock holder who is still alive can never corrupt a later critical section.
- * The main idea is to us the lock reference to clearly demarcate the timestamps across critical sections.
- * @param the UUID lock reference associated with the write.
- * @param the long timeOfWrite which is the actual time at which the write took place
- * @throws MusicServiceException
- * @throws MusicQueryException
- */
- public static long v2sTimeStampInMicroseconds(long ordinal, long timeOfWrite) throws MusicServiceException, MusicQueryException {
- // TODO: use acquire time instead of music eternity epoch
- long ts = ordinal * MaxLockReferenceTimePart + (timeOfWrite - MusicEternityEpochMillis);
-
- return ts;
- }
-
- public static MusicCoreService getMusicCoreService() {
- if(getLockUsing().equals(MusicUtil.CASSANDRA))
- return MusicCassaCore.getInstance();
- else
- return MusicCassaCore.getInstance();
- }
-
- /**
- * @param lockName
- * @return
- */
- public static Map<String, Object> validateLock(String lockName) {
- Map<String, Object> resultMap = new HashMap<>();
- String[] locks = lockName.split("\\.");
- if(locks.length < 3) {
- resultMap.put("Error", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey");
- return resultMap;
- }
- String keyspace= locks[0];
- if(keyspace.startsWith("$"))
- keyspace = keyspace.substring(1);
- resultMap.put("keyspace",keyspace);
- return resultMap;
- }
-
-
- public static void setIsCadi(boolean isCadi) {
- MusicUtil.isCadi = isCadi;
- }
-
- public static void writeBackToQuorum(PreparedQueryObject selectQuery, String primaryKeyName,
- PreparedQueryObject updateQuery, String keyspace, String table,
- Object cqlFormattedPrimaryKeyValue)
- throws Exception {
- try {
- ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(selectQuery);
- // write it back to a quorum
- Row row = results.one();
- ColumnDefinitions colInfo = row.getColumnDefinitions();
- int totalColumns = colInfo.size();
- int counter = 1;
- StringBuilder fieldValueString = new StringBuilder("");
- for (Definition definition : colInfo) {
- String colName = definition.getName();
- if (colName.equals(primaryKeyName))
- continue;
- DataType colType = definition.getType();
- Object valueObj = MusicDataStoreHandle.getDSHandle().getColValue(row, colName, colType);
- Object valueString = MusicUtil.convertToActualDataType(colType, valueObj);
- fieldValueString.append(colName + " = ?");
- updateQuery.addValue(valueString);
- if (counter != (totalColumns - 1))
- fieldValueString.append(",");
- counter = counter + 1;
- }
- updateQuery.appendQueryString("UPDATE " + keyspace + "." + table + " SET "
- + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";");
- updateQuery.addValue(cqlFormattedPrimaryKeyValue);
-
- MusicDataStoreHandle.getDSHandle().executePut(updateQuery, "critical");
- } catch (MusicServiceException | MusicQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,
- ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR);
- }
- }
-
- public static boolean getIsCadi() {
- return MusicUtil.isCadi;
- }
-
-
- /**
- * @return a random uuid
- */
- public static String generateUUID() {
- String uuid = UUID.randomUUID().toString();
- logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
- return uuid;
- }
-
-}
-
diff --git a/src/main/java/org/onap/music/main/PropertiesLoader.java b/src/main/java/org/onap/music/main/PropertiesLoader.java
deleted file mode 100644
index db04ff4b..00000000
--- a/src/main/java/org/onap/music/main/PropertiesLoader.java
+++ /dev/null
@@ -1,187 +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.main;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import org.onap.music.eelf.logging.EELFLoggerDelegate;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.PropertySource;
-import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
-import org.springframework.stereotype.Component;
-
-@PropertySource(value = {"file:/opt/app/music/etc/music.properties", "classpath:/project.properties"})
-@Component
-public class PropertiesLoader implements InitializingBean {
-
- @Value("${cassandra.host}")
- public String cassandraHost;
-
- @Value("${music.ip}")
- public String musicIp;
-
- @Value("${debug}")
- public String debug;
-
- @Value("${version}")
- public String version;
-
- @Value("${music.rest.ip}")
- public String musicRestIp;
-
- @Value("${music.properties}")
- public String musicProperties;
-
- @Value("${lock.lease.period}")
- public String lockLeasePeriod;
-
- @Value("${public.ip}")
- public String publicIp;
-
- @Value("${my.id}")
- public String myId;
-
- @Value("${all.ids}")
- public String allIds;
-
- @Value("${all.public.ips}")
- public String allPublicIps;
-
- @Value("${cassandra.user}")
- public String cassandraUser;
-
- @Value("${cassandra.password}")
- public String cassandraPassword;
-
- @Value("${aaf.endpoint.url}")
- public String aafEndpointUrl;
-
- @Value("${admin.username}")
- public String adminUsername;
-
- @Value("${admin.password}")
- public String adminPassword;
-
- @Value("${cassandra.port}")
- public String cassandraPort;
-
- @Value("${aaf.admin.url}")
- public String aafAdminUrl;
-
- @Value("${music.namespace}")
- public String musicNamespace;
-
- @Value("${admin.aaf.role}")
- public String adminAafRole;
-
- @Value("${notify.interval}")
- public String notifyInterval;
-
- @Value("${notify.timeout}")
- public String notifyTimeout;
-
- @Value("${cadi}")
- public String isCadi;
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PropertiesLoader.class);
-
- @Bean
- public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
- //return new PropertySourcesPlaceholderConfigurer();
- PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
- pspc.setIgnoreResourceNotFound(true);
- pspc.setIgnoreUnresolvablePlaceholders(true);
- return pspc;
- }
-
- public void loadProperties () {
- if(aafAdminUrl != null && !aafAdminUrl.equals("${aaf.admin.url}"))
- MusicUtil.setAafAdminUrl(aafAdminUrl);
- if(aafEndpointUrl != null && !aafEndpointUrl.equals("${aaf.endpoint.url}"))
- MusicUtil.setAafEndpointUrl(aafEndpointUrl);
- if(adminAafRole != null && !adminAafRole.equals("${admin.aaf.role}"))
- MusicUtil.setAdminAafRole(adminAafRole);
- //MusicUtil.setAdminId(adminId);
- if(adminPassword != null && !adminPassword.equals("${admin.password}"))
- MusicUtil.setAdminPass(adminPassword);
- if(adminUsername != null && !adminUsername.equals("${admin.username}"))
- MusicUtil.setAdminId(adminUsername);
- if(allIds != null && !allIds.equals("${all.ids}")) {
- String[] ids = allIds.split(":");
- MusicUtil.setAllIds(new ArrayList<String>(Arrays.asList(ids)));
- }
- if(allPublicIps != null && !allPublicIps.equals("${all.public.ips}")) {
- String[] ips = allPublicIps.split(":");
- if (ips.length == 1) {
- // Future use
- } else if (ips.length > 1) {
- MusicUtil.setAllPublicIps(
- new ArrayList<String>(Arrays.asList(ips)));
- }
- }
- if(cassandraPort != null && !cassandraPort.equals("${cassandra.port}"))
- MusicUtil.setCassandraPort(Integer.parseInt(cassandraPort));
- if(cassandraUser != null && !cassandraUser.equals("${cassandra.user}"))
- MusicUtil.setCassName(cassandraUser);
- if(cassandraPassword != null && !cassandraPassword.equals("${cassandra.password}"))
- MusicUtil.setCassPwd(cassandraPassword);
- if(debug != null && !debug.equals("${debug}"))
- MusicUtil.setDebug(Boolean.parseBoolean(debug));
- if(lockLeasePeriod != null && !lockLeasePeriod.equals("${lock.lease.period}"))
- MusicUtil.setDefaultLockLeasePeriod(Long.parseLong(lockLeasePeriod));
- if(musicIp != null && !musicIp.equals("${music.ip}"))
- MusicUtil.setDefaultMusicIp(musicIp);
- if(musicNamespace != null && !musicNamespace.equals("${music.namespace}"))
- MusicUtil.setMusicNamespace(musicNamespace);
- if(musicProperties != null && !musicProperties.equals("${music.properties}"))
- MusicUtil.setMusicPropertiesFilePath(musicProperties);
- if(musicRestIp != null && !musicRestIp.equals("${music.rest.ip}"))
- MusicUtil.setMusicRestIp(musicRestIp);
- if(cassandraHost != null && !cassandraHost.equals("${cassandra.host}"))
- MusicUtil.setMyCassaHost(cassandraHost);
- logger.info("#### Cassandra Host: " + MusicUtil.getMyCassaHost());
- if(myId != null && !myId.equals("${my.id}"))
- MusicUtil.setMyId(Integer.parseInt(myId));
- if(notifyInterval != null && !notifyInterval.equals("${notify.interval}"))
- MusicUtil.setNotifyInterval(Integer.parseInt(notifyInterval));
- if(notifyTimeout != null && !notifyTimeout.equals("${notify.timeout}"))
- MusicUtil.setNotifyTimeOut(Integer.parseInt(notifyTimeout));
- if(allPublicIps != null && !allPublicIps.equals("${public.ip}"))
- MusicUtil.setPublicIp(allPublicIps);
- if(version != null && !version.equals("${version}"))
- MusicUtil.setVersion(version);
- if(isCadi != null && !isCadi.equals("${cadi}"))
- MusicUtil.setIsCadi(Boolean.parseBoolean(isCadi));
- }
-
-
- @Override
- public void afterPropertiesSet() throws Exception {
- // TODO Auto-generated method stub
-
- }
-
-}
diff --git a/src/main/java/org/onap/music/main/ResultType.java b/src/main/java/org/onap/music/main/ResultType.java
deleted file mode 100644
index f5ef2070..00000000
--- a/src/main/java/org/onap/music/main/ResultType.java
+++ /dev/null
@@ -1,42 +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.main;
-
-public enum ResultType {
- SUCCESS("Success"), FAILURE("Failure"),
- SYNTAXERROR("SyntaxError"), EXCEPTION("Exception"),
- BODYMISSING("Incomplete Request body. Please correct your input request and retry.");
-
- private String result;
-
- ResultType(String result) {
- this.result = result;
- }
-
- public String getResult() {
- return result;
- }
-
-}
-
-
diff --git a/src/main/java/org/onap/music/main/ReturnType.java b/src/main/java/org/onap/music/main/ReturnType.java
deleted file mode 100644
index f02dabbf..00000000
--- a/src/main/java/org/onap/music/main/ReturnType.java
+++ /dev/null
@@ -1,75 +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.main;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class ReturnType {
- private ResultType result;
- private String message;
-
- private String timingInfo;
-
- public ReturnType(ResultType result, String message) {
- super();
- this.result = result;
- this.message = message;
- }
-
- public String getTimingInfo() {
- return timingInfo;
- }
-
- public void setTimingInfo(String timingInfo) {
- this.timingInfo = timingInfo;
- }
-
- public ResultType getResult() {
- return result;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- public String toJson() {
- return "{ \"result\":\"" + result.getResult() + "\", \"message\":\"" + message + "\"}";
- }
-
- public String toString() {
- return result + " | " + message;
- }
-
- public Map<String, Object> toMap() {
- Map<String, Object> newMap = new HashMap<>();
- newMap.put("result", result.getResult());
- newMap.put("message", message);
- return newMap;
- }
-
-}
diff --git a/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java b/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java
deleted file mode 100644
index 8e589efe..00000000
--- a/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java
+++ /dev/null
@@ -1,279 +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.response.jsonobjects;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus;
-import org.onap.music.main.ResultType;
-
-
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
-
-@ApiModel(value = "JsonResponse", description = "General Response JSON")
-public class JsonResponse {
-
- /* Status is required */
- private ResultType status;
-
- /* Standard informational fields */
- private String error;
- private String message;
-
- /* versioning */
- private String musicVersion;
-
- /* Data Fields */
- private Map<String, HashMap<String, Object>> dataResult;
-
- /* Locking fields */
- private String lock;
- private LockStatus lockStatus;
- private String lockHolder;
- private String lockLease;
-
-
- /**
- * Create a JSONLock Response
- * Use setters to provide more information as in
- * JsonLockResponse(ResultType.SUCCESS).setMessage("We did it").setLock(mylockname)
- * @param status
- */
- public JsonResponse(ResultType status) {
- this.status = status;
- }
-
- /**
- *
- * @return
- */
- @ApiModelProperty(value = "Overall status of the response.",
- allowableValues = "Success,Failure")
- public ResultType getStatus() {
- return status;
- }
-
- /**
- *
- * @param status
- */
- public JsonResponse setStatus(ResultType status) {
- this.status = status;
- return this;
- }
-
- /**
- *
- * @return the error
- */
- @ApiModelProperty(value = "Error value")
- public String getError() {
- return error;
- }
-
- /**
- *
- * @param error
- */
- public JsonResponse setError(String error) {
- this.error = error;
- return this;
- }
-
- /**
- *
- * @return the message
- */
- @ApiModelProperty(value = "Message value")
- public String getMessage() {
- return message;
- }
-
- /**
- *
- * @param message
- */
- public JsonResponse setMessage(String message) {
- this.message = message;
- return this;
- }
-
-
- /**
- *
- * @return the music version
- */
- public String getMusicVersion() {
- return this.musicVersion;
- }
-
- /**
- *
- * @param version of music
- * @return
- */
- public JsonResponse setMusicVersion(String version) {
- this.musicVersion = version;
- return this;
- }
-
- public Map<String, HashMap<String, Object>> getDataResult() {
- return this.dataResult;
- }
-
- public JsonResponse setDataResult(Map<String, HashMap<String, Object>> map) {
- this.dataResult = map;
- return this;
- }
-
- /**
- *
- * @return
- */
- public String getLock() {
- return lock;
- }
-
- /**
- *
- * @param lock
- */
- public JsonResponse setLock(String lock) {
- this.lock = lock;
- return this;
- }
-
- /**
- *
- * @return the lockStatus
- */
- @ApiModelProperty(value = "Status of the lock")
- public LockStatus getLockStatus() {
- return lockStatus;
- }
-
- /**
- *
- * @param lockStatus
- */
- public JsonResponse setLockStatus(LockStatus lockStatus) {
- this.lockStatus = lockStatus;
- return this;
- }
-
- /**
- *
- *
- * @return the lockHolder
- */
- @ApiModelProperty(value = "Holder of the Lock")
- public String getLockHolder() {
- return lockHolder;
- }
-
- /**
- *
- * @param lockHolder
- */
- public JsonResponse setLockHolder(String lockHolder) {
- this.lockHolder = lockHolder;
- return this;
- }
-
-
-
- /**
- * @return the lockLease
- */
- public String getLockLease() {
- return lockLease;
- }
-
- /**
- * @param lockLease the lockLease to set
- */
- public JsonResponse setLockLease(String lockLease) {
- this.lockLease = lockLease;
- return this;
- }
-
- /**
- * Convert to Map
- *
- * @return
- */
- public Map<String, Object> toMap() {
- Map<String, Object> fullMap = new HashMap<>();
- fullMap.put("status", status);
-/*<<<<<<< HEAD
- if (error!=null) {
- fullMap.put("error", error);
- }
- if (message!=null) {
- fullMap.put("message", message);
- }
-=======*/
- if (error!=null && !"".equals(error)) {fullMap.put("error", error);}
- if (message!=null) {fullMap.put("message", message);}
-
- if (musicVersion!=null) {
- fullMap.put("version", musicVersion);
- }
-
- if (dataResult!=null) {
- fullMap.put("result", dataResult);
- }
-
- if (lock!=null) {
- Map<String, Object> lockMap = new HashMap<>();
- if (lock!=null) {
- lockMap.put("lock", lock);
- }
- if (lockStatus!=null) {
- lockMap.put("lock-status", lockStatus);
- }
- if (lockHolder!=null) {
- lockMap.put("lock-holder", lockHolder);
- }
- if (lockLease!=null) {
- lockMap.put("lock-lease", lockLease);
- }
- fullMap.put("lock", lockMap);
- }
-
- return fullMap;
- }
-
- /**
- * Convert to String
- */
- @Override
- public String toString() {
- return "JsonLockResponse [status=" + status + ", error=" + error + ", message=" + message
- + ", lock=" + lock + ", lockStatus=" + lockStatus + ", lockHolder="
- + lockHolder + "]";
- }
-
-}
diff --git a/src/main/java/org/onap/music/rest/Application.java b/src/main/java/org/onap/music/rest/Application.java
deleted file mode 100644
index 5375155b..00000000
--- a/src/main/java/org/onap/music/rest/Application.java
+++ /dev/null
@@ -1,79 +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;
-
-public class Application {
-
- private String application_name;
- private String username;
- private String password;
- private String keyspace_name;
- private boolean is_aaf;
- private String uuid;
- private boolean is_api;
-
- public String getApplication_name() {
- return application_name;
- }
- public void setApplication_name(String application_name) {
- this.application_name = application_name;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getKeyspace_name() {
- return keyspace_name;
- }
- public void setKeyspace_name(String keyspace_name) {
- this.keyspace_name = keyspace_name;
- }
- public boolean isIs_aaf() {
- return is_aaf;
- }
- public void setIs_aaf(boolean is_aaf) {
- this.is_aaf = is_aaf;
- }
- public String getUuid() {
- return uuid;
- }
- public void setUuid(String uuid) {
- this.uuid = uuid;
- }
- public boolean getIs_api() {
- return is_api;
- }
- public void setIs_api(boolean is_api) {
- this.is_api = is_api;
- }
-
-
-}
diff --git a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java
deleted file mode 100755
index adcb6584..00000000
--- a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java
+++ /dev/null
@@ -1,496 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * ===================================================================
- * Modifications Copyright (C) 2018 IBM.
- * ================================================================================
- * 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.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import javax.ws.rs.core.Response.Status;
-
-import org.mindrot.jbcrypt.BCrypt;
-import org.onap.music.authentication.CachingUtil;
-import org.onap.music.authentication.MusicAAFAuthentication;
-import org.onap.music.authentication.MusicAuthenticator;
-import org.onap.music.datastore.PreparedQueryObject;
-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.exceptions.MusicServiceException;
-import org.onap.music.main.MusicCore;
-import org.onap.music.main.MusicUtil;
-import org.onap.music.main.ResultType;
-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 io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-//import java.util.Base64.Encoder;
-//import java.util.Base64.Decoder;
-
-@Path("/v2/admin")
-// @Path("/v{version: [0-9]+}/admin")
-// @Path("/admin")
-@Api(value = "Admin Api", hidden = true)
-public class RestMusicAdminAPI {
- private static EELFLoggerDelegate logger =
- EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class);
- // Set to true in env like ONAP. Where access to creating and dropping keyspaces exist.
- private static final boolean KEYSPACE_ACTIVE = false;
-
- private MusicAuthenticator authenticator = new MusicAAFAuthentication();
-
- /*
- * API to onboard an application with MUSIC. This is the mandatory first step.
- *
- */
- @POST
- @Path("/onboardAppWithMusic")
- @ApiOperation(value = "Onboard application", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response onboardAppWithMusic(JsonOnboard jsonObj,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception {
- logger.info(EELFLoggerDelegate.errorLogger, "oboarding app");
- ResponseBuilder response =
- Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
- if (!authenticator.authenticateAdmin(authorization)) {
- logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
- ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check admin username,password and try again").toMap())
- .build();
- }
-
- Map<String, Object> resultMap = new HashMap<>();
- String appName = jsonObj.getAppname();
- String userId = jsonObj.getUserId();
- String isAAF = jsonObj.getIsAAF();
- String password = jsonObj.getPassword();
- String keyspace_name = jsonObj.getKeyspace();
-
- if (appName == null || userId == null || isAAF == null || password == null) {
- logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing.", AppMessages.MISSINGINFO,
- ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
- resultMap.put("Exception",
- "Unauthorized: Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing.");
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
-
- PreparedQueryObject pQuery = new PreparedQueryObject();
- /*
- * pQuery.appendQueryString(
- * "select uuid from admin.keyspace_master where application_name = ? allow filtering"
- * ); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),
- * appName)); ResultSet rs = MusicCore.get(pQuery); if (!rs.all().isEmpty()) {
- * logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA
- * ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- * response.status(Status.BAD_REQUEST); return response.entity(new
- * JsonResponse(ResultType.FAILURE).setError("Application " + appName +
- * " has already been onboarded. Please contact admin.").toMap()).build(); }
- */
- //pQuery = new PreparedQueryObject();
- String uuid = MusicUtil.generateUUID();
- pQuery.appendQueryString(
- "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
- + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),keyspace_name));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt())));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
-
- String returnStr = MusicCore.eventualPut(pQuery).toString();
- if (returnStr.contains("Failure")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- response.status(Status.BAD_REQUEST);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError("Oops. Something wrong with onboarding process. "
- + "Please retry later or contact admin.").toMap()).build();
- }
- CachingUtil.updateisAAFCache(appName, isAAF);
- resultMap.put("Success", "Your application " + appName + " has been onboarded with MUSIC.");
- resultMap.put("Generated AID", uuid);
- return response.status(Status.OK).entity(resultMap).build();
- }
-
-
- @POST
- @Path("/search")
- @ApiOperation(value = "Search Onboard application", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response getOnboardedInfoSearch(JsonOnboard jsonObj,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception {
- ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
-
- if (!authenticator.authenticateAdmin(authorization)) {
- logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
- ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check admin username,password and try again").toMap())
- .build();
- }
-
- Map<String, Object> resultMap = new HashMap<>();
- String appName = jsonObj.getAppname();
- String uuid = jsonObj.getAid();
- String isAAF = jsonObj.getIsAAF();
- if (appName == null && uuid == null && isAAF == null) {
- logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF.", AppMessages.MISSINGINFO,
- 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();
- }
-
- PreparedQueryObject pQuery = new PreparedQueryObject();
- String cql = "select uuid, keyspace_name from admin.keyspace_master where ";
- if (appName != null)
- cql = cql + "application_name = ? AND ";
- if (uuid != null)
- cql = cql + "uuid = ? AND ";
- if (isAAF != null)
- cql = cql + "is_aaf = ?";
-
- if (cql.endsWith("AND "))
- cql = cql.trim().substring(0, cql.length() - 4);
- logger.info("Query in callback is: " + cql);
- cql = cql + " allow filtering";
- pQuery.appendQueryString(cql);
- if (appName != null)
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
- if (uuid != null)
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
- if (isAAF != null)
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(),
- Boolean.parseBoolean(isAAF)));
- ResultSet rs = MusicCore.get(pQuery);
- Iterator<Row> it = rs.iterator();
- while (it.hasNext()) {
- Row row = it.next();
- resultMap.put(row.getUUID("uuid").toString(), row.getString("keyspace_name"));
- }
- if (resultMap.isEmpty()) {
- if (uuid != null) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- response.status(Status.BAD_REQUEST);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError("Please make sure Aid is correct and application is onboarded.").toMap()).build();
-
- } else {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- response.status(Status.BAD_REQUEST);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError("Application is not onboarded. Please make sure all the information is correct.").toMap()).build();
- }
- }
- return response.status(Status.OK).entity(resultMap).build();
- }
-
-
- @DELETE
- @Path("/onboardAppWithMusic")
- @ApiOperation(value = "Delete Onboard application", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response deleteOnboardApp(JsonOnboard jsonObj,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception {
- ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
-
- if (!authenticator.authenticateAdmin(authorization)) {
- logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
- ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check admin username,password and try again").toMap())
- .build();
- }
-
- Map<String, Object> resultMap = new HashMap<>();
- String appName = jsonObj.getAppname();
- String aid = jsonObj.getAid();
- PreparedQueryObject pQuery = new PreparedQueryObject();
- String consistency = MusicUtil.EVENTUAL;
- if (appName == null && aid == null) {
- logger.error(EELFLoggerDelegate.errorLogger, "Please make sure either appName(ns) or Aid is present", AppMessages.MISSINGINFO,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- resultMap.put("Exception", "Please make sure either appName(ns) or Aid is present");
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- if (aid != null) {
- if ( KEYSPACE_ACTIVE ) {
- pQuery.appendQueryString(
- "SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
- UUID.fromString(aid)));
- Row row = MusicCore.get(pQuery).one();
- if (row != null) {
- String ks = row.getString("keyspace_name");
- if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString("DROP KEYSPACE IF EXISTS " + ks + ";");
- MusicCore.nonKeyRelatedPut(queryObject, consistency);
- }
- }
- }
- pQuery = new PreparedQueryObject();
- pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ? IF EXISTS");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
- UUID.fromString(aid)));
- ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
- if (result == ResultType.SUCCESS) {
- resultMap.put("Success", "Your application has been deleted successfully");
- } else {
- resultMap.put("Exception",
- "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded");
- logger.error(EELFLoggerDelegate.errorLogger, "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded", AppMessages.INCORRECTDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
-
- }
- return response.status(Status.OK).entity(resultMap).build();
- }
-
- pQuery.appendQueryString(
- "select uuid from admin.keyspace_master where application_name = ? allow filtering");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
- ResultSet rs = MusicCore.get(pQuery);
- List<Row> rows = rs.all();
- String uuid = null;
- if (rows.isEmpty()) {
- resultMap.put("Exception",
- "Application not found. Please make sure Application exists.");
- logger.error(EELFLoggerDelegate.errorLogger, "Application not found. Please make sure Application exists.", AppMessages.INCORRECTDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- } else if (rows.size() == 1) {
- uuid = rows.get(0).getUUID("uuid").toString();
- pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
- UUID.fromString(uuid)));
- Row row = MusicCore.get(pQuery).one();
- String ks = row.getString("keyspace_name");
- if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString("DROP KEYSPACE " + ks + ";");
- MusicCore.nonKeyRelatedPut(queryObject, consistency);
- }
-
- pQuery = new PreparedQueryObject();
- pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
- UUID.fromString(uuid)));
- MusicCore.eventualPut(pQuery);
- resultMap.put("Success", "Your application " + appName + " has been deleted.");
- return response.status(Status.OK).entity(resultMap).build();
- } else {
- resultMap.put("Failure",
- "More than one Aid exists for this application, so please provide Aid.");
- logger.error(EELFLoggerDelegate.errorLogger, "More than one Aid exists for this application, so please provide Aid.", AppMessages.MULTIPLERECORDS,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- }
-
-
- @PUT
- @Path("/onboardAppWithMusic")
- @ApiOperation(value = "Update Onboard application", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response updateOnboardApp(JsonOnboard jsonObj,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception {
- ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
- if (!authenticator.authenticateAdmin(authorization)) {
- logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
- ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check admin username,password and try again").toMap())
- .build();
- }
-
- Map<String, Object> resultMap = new HashMap<>();
- String aid = jsonObj.getAid();
- String appName = jsonObj.getAppname();
- String userId = jsonObj.getUserId();
- String isAAF = jsonObj.getIsAAF();
- String password = jsonObj.getPassword();
- String consistency = "eventual";
- PreparedQueryObject pQuery;
-
- if (aid == null) {
- resultMap.put("Exception", "Please make sure Aid is present");
- logger.error(EELFLoggerDelegate.errorLogger, "Please make sure Aid is present", AppMessages.MISSINGDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
-
- if (appName == null && userId == null && password == null && isAAF == null) {
- resultMap.put("Exception",
- "No parameters found to update. Please update atleast one parameter.");
- logger.error(EELFLoggerDelegate.errorLogger, "No parameters found to update. Please update atleast one parameter.", AppMessages.MISSINGDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
-
- if (appName != null) {
- pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "select uuid from admin.keyspace_master where application_name = ? allow filtering");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
- ResultSet rs = MusicCore.get(pQuery);
- if (!rs.all().isEmpty()) {
- resultMap.put("Exception", "Application " + appName
- + " has already been onboarded. Please contact admin.");
- logger.error(EELFLoggerDelegate.errorLogger, "Application " + appName+"has already been onboarded. Please contact admin.", AppMessages.ALREADYEXIST,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- }
-
- pQuery = new PreparedQueryObject();
- StringBuilder preCql = new StringBuilder("UPDATE admin.keyspace_master SET ");
- if (appName != null)
- preCql.append(" application_name = ?,");
- if (userId != null)
- preCql.append(" username = ?,");
- if (password != null)
- preCql.append(" password = ?,");
- if (isAAF != null)
- preCql.append(" is_aaf = ?,");
- preCql.deleteCharAt(preCql.length() - 1);
- preCql.append(" WHERE uuid = ? IF EXISTS");
- pQuery.appendQueryString(preCql.toString());
- if (appName != null)
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
- if (userId != null)
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
- if (password != null)
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt())));
- if (isAAF != null)
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
-
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid)));
- ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
-
- if (result == ResultType.SUCCESS) {
- resultMap.put("Success", "Your application has been updated successfully");
- } else {
- resultMap.put("Exception",
- "Oops. Something went wrong. Please make sure Aid is correct and application is onboarded");
- logger.error(EELFLoggerDelegate.errorLogger, "Oops. Something went wrong. Please make sure Aid is correct and application is onboarded", AppMessages.INCORRECTDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
-
- return response.status(Status.OK).entity(resultMap).build();
- }
-
-
-
- //Dashboard related calls
- @GET
- @Path("/getall")
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.APPLICATION_JSON)
- public List<Application> getall(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws MusicServiceException{
- List<Application> appList = new ArrayList<>();
- ResponseBuilder response =
- Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
- if (!authenticator.authenticateAdmin(authorization)) {
- logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
- ErrorTypes.AUTHENTICATIONERROR);
- return appList;
- }
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString("SELECT * FROM " + "admin" + "." + "keyspace_master" + ";");
- ResultSet results = MusicCore.get(queryObject);
- for(Row row : results) {
- Application app = new Application();
- app.setApplication_name(row.getString("application_name"));
- app.setIs_aaf(row.getBool("is_aaf"));
- app.setIs_api(row.getBool("is_api"));
- app.setUsername(row.getString("username"));
- app.setKeyspace_name(row.getString("keyspace_name"));
- app.setUuid(row.getUUID("uuid").toString());
- appList.add(app);
- }
- return appList;
-
- //return app;
-
- }
- @DELETE
- @Path("/delete")
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.APPLICATION_JSON)
- public boolean delete(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "uuid", required = true) @HeaderParam("uuid") String uuid) throws Exception {
- ResponseBuilder response =
- Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
- if (!authenticator.authenticateAdmin(authorization)) {
- logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
- ErrorTypes.AUTHENTICATIONERROR);
- return false;
- }
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString("delete from admin.keyspace_master where uuid=?");
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),uuid));
- ResultType result;
- try {
- result = MusicCore.nonKeyRelatedPut(queryObject, "eventual");
- }catch(Exception ex) {
- return false;
- }
- return true;
- }
-}
diff --git a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java
deleted file mode 100755
index dfcf0bdb..00000000
--- a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java
+++ /dev/null
@@ -1,1531 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * ===================================================================
- * Modifications Copyright (c) 2019 Samsung
- * ===================================================================
- * 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.nio.ByteBuffer;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-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.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import javax.ws.rs.core.Response.Status;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.commons.lang3.StringUtils;
-import org.mindrot.jbcrypt.BCrypt;
-import org.onap.music.authentication.CachingUtil;
-import org.onap.music.authentication.MusicAAFAuthentication;
-import org.onap.music.authentication.MusicAuthenticator;
-import org.onap.music.authentication.MusicAuthenticator.Operation;
-import org.onap.music.datastore.PreparedQueryObject;
-import org.onap.music.datastore.jsonobjects.JsonDelete;
-import org.onap.music.datastore.jsonobjects.JsonInsert;
-import org.onap.music.datastore.jsonobjects.JsonKeySpace;
-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;
-import org.onap.music.exceptions.MusicServiceException;
-import org.onap.music.main.MusicCore;
-import org.onap.music.datastore.Condition;
-import org.onap.music.datastore.MusicDataStoreHandle;
-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.TableMetadata;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponses;
-import io.swagger.annotations.ApiResponse;
-
-/* Version 2 Class */
-//@Path("/v{version: [0-9]+}/keyspaces")
-@Path("/v2/keyspaces")
-@Api(value = "Data Api")
-public class RestMusicDataAPI {
- /*
- * Header values for Versioning X-minorVersion *** - Used to request or communicate a MINOR
- * version back from the client to the server, and from the server back to the client - This
- * will be the MINOR version requested by the client, or the MINOR version of the last MAJOR
- * version (if not specified by the client on the request) - Contains a single position value
- * (e.g. if the full version is 1.24.5, X-minorVersion = "24") - Is optional for the client on
- * request; however, this header should be provided if the client needs to take advantage of
- * MINOR incremented version functionality - Is mandatory for the server on response
- *
- *** X-patchVersion *** - Used only to communicate a PATCH version in a response for
- * troubleshooting purposes only, and will not be provided by the client on request - This will
- * be the latest PATCH version of the MINOR requested by the client, or the latest PATCH version
- * of the MAJOR (if not specified by the client on the request) - Contains a single position
- * value (e.g. if the full version is 1.24.5, X-patchVersion = "5") - Is mandatory for the
- * server on response (CURRENTLY NOT USED)
- *
- *** X-latestVersion *** - Used only to communicate an API's latest version - Is mandatory for the
- * server on response, and shall include the entire version of the API (e.g. if the full version
- * is 1.24.5, X-latestVersion = "1.24.5") - Used in the response to inform clients that they are
- * not using the latest version of the API (CURRENTLY NOT USED)
- *
- */
-
- 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 VERSION = "v2";
- private MusicAuthenticator authenticator = new MusicAAFAuthentication();
- // Set to true in env like ONAP. Where access to creating and dropping keyspaces exist.
- private static final boolean KEYSPACE_ACTIVE = false;
-
- private class RowIdentifier {
- public String primarKeyValue;
- public StringBuilder rowIdString;
- @SuppressWarnings("unused")
- public PreparedQueryObject queryObject;// the string with all the row
- // identifiers separated by AND
-
- public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString,
- PreparedQueryObject queryObject) {
- this.primarKeyValue = primaryKeyValue;
- this.rowIdString = rowIdString;
- this.queryObject = queryObject;
- }
- }
-
-
- /**
- * Create Keyspace REST
- *
- * @param kspObject
- * @param keyspaceName
- * @return
- * @throws Exception
- */
- @POST
- @Path("/{name}")
- @ApiOperation(value = "Create Keyspace", response = String.class,hidden = true)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response createKeySpace(
- @ApiParam(value = "Major Version",required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
- JsonKeySpace kspObject,
- @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) {
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) ");
- logger.info(EELFLoggerDelegate.applicationLogger,"In Create Keyspace " + keyspaceName);
- if ( KEYSPACE_ACTIVE ) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Creating Keyspace " + keyspaceName);
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- Map<String, Object> authMap = CachingUtil.verifyOnboarding(ns, userId, password);
- if (!authMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
- response.status(Status.UNAUTHORIZED);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build();
- }
-
- if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.CREATE_KEYSPACE)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- String consistency = MusicUtil.EVENTUAL;// for now this needs only
- // eventual consistency
-
- if(kspObject == null || kspObject.getReplicationInfo() == null) {
- response.status(Status.BAD_REQUEST);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError(ResultType.BODYMISSING.getResult()).toMap()).build();
- }
- PreparedQueryObject queryObject = new PreparedQueryObject();
- if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && kspObject.getConsistencyInfo().get("consistency") != null) {
- if(MusicUtil.isValidConsistency(kspObject.getConsistencyInfo().get("consistency")))
- queryObject.setConsistency(kspObject.getConsistencyInfo().get("consistency"));
- else
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Invalid Consistency type").toMap()).build();
- }
- long start = System.currentTimeMillis();
- Map<String, Object> replicationInfo = kspObject.getReplicationInfo();
- String repString = null;
- try {
- repString = "{" + MusicUtil.jsonMaptoSqlString(replicationInfo, ",") + "}";
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
-
- }
- queryObject.appendQueryString(
- "CREATE KEYSPACE " + keyspaceName + " WITH replication = " + repString);
- if (kspObject.getDurabilityOfWrites() != null) {
- queryObject.appendQueryString(
- " AND durable_writes = " + kspObject.getDurabilityOfWrites());
- }
-
- queryObject.appendQueryString(";");
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Time taken for setting up query in create keyspace:" + (end - start));
-
- ResultType result = ResultType.FAILURE;
- try {
- result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
- logger.info(EELFLoggerDelegate.applicationLogger, "result = " + result);
- } catch ( MusicServiceException 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("err:" + ex.getMessage()).toMap()).build();
- }
-
- try {
- queryObject = new PreparedQueryObject();
- queryObject.appendQueryString("CREATE ROLE IF NOT EXISTS '" + userId
- + "' WITH PASSWORD = '" + password + "' AND LOGIN = true;");
- MusicCore.nonKeyRelatedPut(queryObject, consistency);
- queryObject = new PreparedQueryObject();
- queryObject.appendQueryString("GRANT ALL PERMISSIONS on KEYSPACE " + keyspaceName
- + " to '" + userId + "'");
- queryObject.appendQueryString(";");
- MusicCore.nonKeyRelatedPut(queryObject, consistency);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- }
-
- try {
- boolean isAAF = Boolean.valueOf(CachingUtil.isAAFApplication(ns));
- String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt());
- queryObject = new PreparedQueryObject();
- queryObject.appendQueryString(
- "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
- + "password, username, is_aaf) values (?,?,?,?,?,?,?)");
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), aid));
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName));
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd));
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
- CachingUtil.updateMusicCache(keyspaceName, ns);
- CachingUtil.updateMusicValidateCache(ns, userId, hashedpwd);
- MusicCore.eventualPut(queryObject);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
- }
-
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Created").toMap()).build();
- } else {
- String vError = "Keyspace Creation no longer supported after versions 3.2.x. Contact DBA to create the keyspace.";
- logger.info(EELFLoggerDelegate.applicationLogger,vError);
- logger.error(EELFLoggerDelegate.errorLogger,vError, AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(vError).toMap()).build();
- }
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
-
- }
-
- /**
- *
- * @param kspObject
- * @param keyspaceName
- * @return
- * @throws Exception
- */
- @DELETE
- @Path("/{name}")
- @ApiOperation(value = "Delete Keyspace", response = String.class,hidden=true)
- @Produces(MediaType.APPLICATION_JSON)
- public Response dropKeySpace(
- @ApiParam(value = "Major Version",required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
- @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) throws Exception {
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) ");
- logger.info(EELFLoggerDelegate.applicationLogger,"In Drop Keyspace " + keyspaceName);
- if ( KEYSPACE_ACTIVE ) {
- if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.DROP_KEYSPACE)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- String consistency = MusicUtil.EVENTUAL;// for now this needs only
- // eventual
- // consistency
- String appName = CachingUtil.getAppName(keyspaceName);
- String uuid = CachingUtil.getUuidFromMusicCache(keyspaceName);
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "select count(*) as count from admin.keyspace_master where application_name=? allow filtering;");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
- Row row = MusicCore.get(pQuery).one();
- long count = row.getLong(0);
-
- if (count == 0) {
- logger.error(EELFLoggerDelegate.errorLogger,"Keyspace not found. Please make sure keyspace exists.", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Keyspace not found. Please make sure keyspace exists.").toMap()).build();
- // Admin Functions:
- } else if (count == 1) {
- pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "UPDATE admin.keyspace_master SET keyspace_name=? where uuid = ?;");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),
- MusicUtil.DEFAULTKEYSPACENAME));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
- MusicCore.nonKeyRelatedPut(pQuery, consistency);
- } else {
- pQuery = new PreparedQueryObject();
- pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
- MusicCore.nonKeyRelatedPut(pQuery, consistency);
- }
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString("DROP KEYSPACE " + keyspaceName + ";");
- ResultType result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
- if ( result.equals(ResultType.FAILURE) ) {
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Deleteing Keyspace " + keyspaceName).toMap()).build();
- }
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Deleted").toMap()).build();
- } else {
- String vError = "Keyspace Droping no longer supported after versions 3.2.x. Contact DBA to drop the keyspace.";
- logger.info(EELFLoggerDelegate.applicationLogger,vError);
- logger.error(EELFLoggerDelegate.errorLogger,vError, AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(vError).toMap()).build();
- }
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
- /**
- *
- * @param tableObj
- * @param version
- * @param keyspace
- * @param tablename
- * @param headers
- * @return
- * @throws Exception
- */
- @POST
- @Path("/{keyspace: .*}/tables/{tablename: .*}")
- @ApiOperation(value = "Create Table", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiResponses(value={
- @ApiResponse(code= 400, message = "Will return JSON response with message"),
- @ApiResponse(code= 401, message = "Unautorized User")
- })
- public Response createTable(
- @ApiParam(value = "Major Version",required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- JsonTable tableObj,
- @ApiParam(value = "Keyspace Name",required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name",required = true) @PathParam("tablename") String tablename) throws Exception {
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- if(keyspace == null || keyspace.isEmpty() || tablename == null || tablename.isEmpty()){
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
- .setError("One or more path parameters are not set, please check and try again."
- + "Parameter values: keyspace='" + keyspace + "' tablename='" + tablename + "'")
- .toMap()).build();
- }
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
- if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.CREATE_TABLE)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- String consistency = MusicUtil.EVENTUAL;
- // for now this needs only eventual consistency
-
- String primaryKey = null;
- String partitionKey = tableObj.getPartitionKey();
- String clusterKey = tableObj.getClusteringKey();
- String filteringKey = tableObj.getFilteringKey();
- if(filteringKey != null) {
- clusterKey = clusterKey + "," + filteringKey;
- }
- primaryKey = tableObj.getPrimaryKey(); // get primaryKey if available
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
- // first read the information about the table fields
- Map<String, String> fields = tableObj.getFields();
- StringBuilder fieldsString = new StringBuilder("(vector_ts text,");
- int counter = 0;
- for (Map.Entry<String, String> entry : fields.entrySet()) {
- if (entry.getKey().equals("PRIMARY KEY")) {
- primaryKey = entry.getValue(); // replaces primaryKey
- primaryKey = primaryKey.trim();
- } else {
- if (counter == 0 ) fieldsString.append("" + entry.getKey() + " " + entry.getValue() + "");
- else fieldsString.append("," + entry.getKey() + " " + entry.getValue() + "");
- }
-
- if (counter != (fields.size() - 1) ) {
-
- counter = counter + 1;
- } else {
-
- if((primaryKey != null) && (partitionKey == null)) {
- primaryKey = primaryKey.trim();
- int count1 = StringUtils.countMatches(primaryKey, ')');
- int count2 = StringUtils.countMatches(primaryKey, '(');
- if (count1 != count2) {
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
- .setError("Create Table Error: primary key '(' and ')' do not match, primary key=" + primaryKey)
- .toMap()).build();
- }
-
- if ( primaryKey.indexOf('(') == -1 || ( count2 == 1 && (primaryKey.lastIndexOf(')') +1) == primaryKey.length() ) )
- {
- if (primaryKey.contains(",") ) {
- partitionKey= primaryKey.substring(0,primaryKey.indexOf(','));
- partitionKey=partitionKey.replaceAll("[\\(]+","");
- clusterKey=primaryKey.substring(primaryKey.indexOf(',')+1); // make sure index
- clusterKey=clusterKey.replaceAll("[)]+", "");
- } else {
- partitionKey=primaryKey;
- partitionKey=partitionKey.replaceAll("[\\)]+","");
- partitionKey=partitionKey.replaceAll("[\\(]+","");
- clusterKey="";
- }
- } else { // not null and has ) before the last char
- partitionKey= primaryKey.substring(0,primaryKey.indexOf(')'));
- partitionKey=partitionKey.replaceAll("[\\(]+","");
- partitionKey = partitionKey.trim();
- clusterKey= primaryKey.substring(primaryKey.indexOf(')'));
- clusterKey=clusterKey.replaceAll("[\\(]+","");
- clusterKey=clusterKey.replaceAll("[\\)]+","");
- clusterKey = clusterKey.trim();
- if (clusterKey.indexOf(',') == 0) clusterKey=clusterKey.substring(1);
- clusterKey = clusterKey.trim();
- if (clusterKey.equals(",") ) clusterKey=""; // print error if needed ( ... ),)
- }
-
- if (!(partitionKey.isEmpty() || clusterKey.isEmpty())
- && (partitionKey.equalsIgnoreCase(clusterKey) ||
- clusterKey.contains(partitionKey) || partitionKey.contains(clusterKey)) )
- {
- logger.error("DataAPI createTable partition/cluster key ERROR: partitionKey="+partitionKey+", clusterKey=" + clusterKey + " and primary key=" + primaryKey );
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(
- "Create Table primary key error: clusterKey(" + clusterKey + ") equals/contains/overlaps partitionKey(" +partitionKey+ ") of"
- + " primary key=" + primaryKey)
- .toMap()).build();
-
- }
-
- if (partitionKey.isEmpty() ) primaryKey="";
- else if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey + ")";
- else primaryKey=" (" + partitionKey + ")," + clusterKey;
-
-
- if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )");
-
- } // end of length > 0
- else {
- if (!(partitionKey.isEmpty() || clusterKey.isEmpty())
- && (partitionKey.equalsIgnoreCase(clusterKey) ||
- clusterKey.contains(partitionKey) || partitionKey.contains(clusterKey)) )
- {
- logger.error("DataAPI createTable partition/cluster key ERROR: partitionKey="+partitionKey+", clusterKey=" + clusterKey);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(
- "Create Table primary key error: clusterKey(" + clusterKey + ") equals/contains/overlaps partitionKey(" +partitionKey+ ")")
- .toMap()).build();
- }
-
- if (partitionKey.isEmpty() ) primaryKey="";
- else if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey + ")";
- else primaryKey=" (" + partitionKey + ")," + clusterKey;
-
-
- if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )");
- }
- fieldsString.append(")");
-
- } // end of last field check
-
- } // end of for each
- // information about the name-value style properties
- Map<String, Object> propertiesMap = tableObj.getProperties();
- StringBuilder propertiesString = new StringBuilder();
- if (propertiesMap != null) {
- counter = 0;
- for (Map.Entry<String, Object> entry : propertiesMap.entrySet()) {
- Object ot = entry.getValue();
- String value = ot + "";
- if (ot instanceof String) {
- value = "'" + value + "'";
- } else if (ot instanceof Map) {
- @SuppressWarnings("unchecked")
- Map<String, Object> otMap = (Map<String, Object>) ot;
- value = "{" + MusicUtil.jsonMaptoSqlString(otMap, ",") + "}";
- }
-
- propertiesString.append(entry.getKey() + "=" + value + "");
- if (counter != propertiesMap.size() - 1)
- propertiesString.append(" AND ");
-
- counter = counter + 1;
- }
- }
-
- String clusteringOrder = tableObj.getClusteringOrder();
-
- if (clusteringOrder != null && !(clusteringOrder.isEmpty())) {
- String[] arrayClusterOrder = clusteringOrder.split("[,]+");
-
- for (int i = 0; i < arrayClusterOrder.length; i++) {
- String[] clusterS = arrayClusterOrder[i].trim().split("[ ]+");
- if ( (clusterS.length ==2) && (clusterS[1].equalsIgnoreCase("ASC") || clusterS[1].equalsIgnoreCase("DESC"))) {
- continue;
- } else {
- return response.status(Status.BAD_REQUEST)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("createTable/Clustering Order vlaue ERROR: valid clustering order is ASC or DESC or expecting colname order; please correct clusteringOrder:"+ clusteringOrder+".")
- .toMap()).build();
- }
- // add validation for column names in cluster key
- }
-
- if (!(clusterKey.isEmpty())) {
- clusteringOrder = "CLUSTERING ORDER BY (" +clusteringOrder +")";
- //cjc check if propertiesString.length() >0 instead propertiesMap
- if (propertiesMap != null) {
- propertiesString.append(" AND "+ clusteringOrder);
- } else {
- propertiesString.append(clusteringOrder);
- }
- } else {
- logger.warn("Skipping clustering order=("+clusteringOrder+ ") since clustering key is empty ");
- }
- } //if non empty
-
- queryObject.appendQueryString(
- "CREATE TABLE " + keyspace + "." + tablename + " " + fieldsString);
-
-
- if (propertiesString != null && propertiesString.length()>0 )
- queryObject.appendQueryString(" WITH " + propertiesString);
- queryObject.appendQueryString(";");
- ResultType result = ResultType.FAILURE;
- try {
- 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);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
- }
- if ( result.equals(ResultType.FAILURE) ) {
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Creating Table " + tablename).toMap()).build();
- }
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("TableName " + tablename.trim() + " Created under keyspace " + keyspace.trim()).toMap()).build();
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
- /**
- *
- * @param keyspace
- * @param tablename
- * @param fieldName
- * @param info
- * @throws Exception
- */
- @POST
- @Path("/{keyspace: .*}/tables/{tablename: .*}/index/{field: .*}")
- @ApiOperation(value = "Create Index", response = String.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response createIndex(
- @ApiParam(value = "Major Version",required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "Keyspace Name",required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name",required = true) @PathParam("tablename") String tablename,
- @ApiParam(value = "Field Name",required = true) @PathParam("field") String fieldName,
- @Context UriInfo info) throws Exception {
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty()) || (fieldName == null || fieldName.isEmpty())){
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
- .setError("one or more path parameters are not set, please check and try again")
- .toMap()).build();
- }
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
- if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.CREATE_INDEX)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .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 + "."
- + tablename + " (" + fieldName + ");");
-
- ResultType result = ResultType.FAILURE;
- try {
- result = MusicCore.nonKeyRelatedPut(query, "eventual");
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- response.status(Status.BAD_REQUEST);
- 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();
- } else {
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Unknown Error in create index.").toMap()).build();
- }
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
- /**
- *
- * @param insObj
- * @param keyspace
- * @param tablename
- * @return
- * @throws Exception
- */
- @POST
- @Path("/{keyspace: .*}/tables/{tablename: .*}/rows")
- @ApiOperation(value = "Insert Into Table", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response insertIntoTable(
- @ApiParam(value = "Major Version",required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- JsonInsert insObj,
- @ApiParam(value = "Keyspace Name",
- required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name",
- required = true) @PathParam("tablename") String tablename) {
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
- .setError("one or more path parameters are not set, please check and try again")
- .toMap()).build();
- }
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
- if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.INSERT_INTO_TABLE)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- Map<String, Object> valuesMap = insObj.getValues();
- PreparedQueryObject queryObject = new PreparedQueryObject();
- TableMetadata tableInfo = null;
- try {
- tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename);
- if(tableInfo == null) {
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Table name doesn't exists. Please check the table name.").toMap()).build();
- }
- } catch (MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
- }
- String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName();
- StringBuilder fieldsString = new StringBuilder("(vector_ts,");
- String vectorTs =
- String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
- StringBuilder valueString = new StringBuilder("(" + "?" + ",");
- queryObject.addValue(vectorTs);
- int counter = 0;
- String primaryKey = "";
- Map<String, byte[]> objectMap = insObj.getObjectMap();
- for (Map.Entry<String, Object> entry : valuesMap.entrySet()) {
- fieldsString.append("" + entry.getKey());
- Object valueObj = entry.getValue();
- if (primaryKeyName.equals(entry.getKey())) {
- primaryKey = entry.getValue() + "";
- primaryKey = primaryKey.replace("'", "''");
- }
- DataType colType = null;
- try {
- colType = tableInfo.getColumn(entry.getKey()).getType();
- } catch(NullPointerException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() +" Invalid column name : "+entry.getKey(), AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Invalid column name : "+entry.getKey()).toMap()).build();
- }
-
- Object formattedValue = null;
- try {
- formattedValue = MusicUtil.convertToActualDataType(colType, valueObj);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e);
- }
- valueString.append("?");
-
- queryObject.addValue(formattedValue);
-
- if (counter == valuesMap.size() - 1) {
- fieldsString.append(")");
- valueString.append(")");
- } else {
- fieldsString.append(",");
- valueString.append(",");
- }
- counter = counter + 1;
- }
-
- //blobs..
- if(objectMap != null) {
- for (Map.Entry<String, byte[]> entry : objectMap.entrySet()) {
- if(counter > 0) {
- fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ",");
- valueString.replace(valueString.length()-1, valueString.length(), ",");
- }
- fieldsString.append("" + entry.getKey());
- byte[] valueObj = entry.getValue();
- if (primaryKeyName.equals(entry.getKey())) {
- primaryKey = entry.getValue() + "";
- primaryKey = primaryKey.replace("'", "''");
- }
-
- DataType colType = tableInfo.getColumn(entry.getKey()).getType();
-
- ByteBuffer formattedValue = null;
-
- if(colType.toString().toLowerCase().contains("blob"))
- formattedValue = MusicUtil.convertToActualDataType(colType, valueObj);
-
- valueString.append("?");
-
- queryObject.addValue(formattedValue);
- counter = counter + 1;
- /*if (counter == valuesMap.size() - 1) {
- fieldsString.append(")");
- valueString.append(")");
- } else {*/
- fieldsString.append(",");
- valueString.append(",");
- //}
- } }
-
- if(primaryKey == null || primaryKey.length() <= 0) {
- logger.error(EELFLoggerDelegate.errorLogger, "Some required partition key parts are missing: "+primaryKeyName );
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Some required partition key parts are missing: "+primaryKeyName).toMap()).build();
- }
-
- fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ")");
- valueString.replace(valueString.length()-1, valueString.length(), ")");
-
- queryObject.appendQueryString("INSERT INTO " + keyspace + "." + tablename + " "
- + fieldsString + " VALUES " + valueString);
-
- 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(";");
-
- ReturnType result = null;
- String consistency = insObj.getConsistencyInfo().get("type");
- if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && insObj.getConsistencyInfo().get("consistency") != null) {
- if(MusicUtil.isValidConsistency(insObj.getConsistencyInfo().get("consistency")))
- queryObject.setConsistency(insObj.getConsistencyInfo().get("consistency"));
- else
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Invalid Consistency type").toMap()).build();
- }
- queryObject.setOperation("insert");
- try {
- if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) {
- result = MusicCore.eventualPut(queryObject);
- } else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
- String lockId = insObj.getConsistencyInfo().get("lockId");
- if(lockId == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or"
- + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock "
- + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build();
- }
- result = MusicCore.criticalPut(keyspace, tablename, primaryKey, queryObject, lockId,null);
- } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
-
- result = MusicCore.atomicPut(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();
- }
-
- if (result==null) {
- logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build();
- }else if(result.getResult() == ResultType.FAILURE) {
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result.getResult()).setError(result.getMessage()).toMap()).build();
- }
- return response.status(Status.OK).entity(new JsonResponse(result.getResult()).setMessage("Insert Successful").toMap()).build();
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
- /**
- *
- * @param insObj
- * @param keyspace
- * @param tablename
- * @param info
- * @return
- * @throws MusicServiceException
- * @throws MusicQueryException
- * @throws Exception
- */
- @PUT
- @Path("/{keyspace: .*}/tables/{tablename: .*}/rows")
- @ApiOperation(value = "Update Table", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response updateTable(
- @ApiParam(value = "Major Version",
- required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",
- required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",
- required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam(NS) String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- JsonUpdate updateObj,
- @ApiParam(value = "Keyspace Name",
- required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name",
- required = true) @PathParam("tablename") String tablename,
- @Context UriInfo info) throws MusicQueryException, MusicServiceException {
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
- .setError("one or more path parameters are not set, please check and try again")
- .toMap()).build();
- }
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
- if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.UPDATE_TABLE)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- long startTime = System.currentTimeMillis();
- String operationId = UUID.randomUUID().toString();// just for infoging
- // purposes.
- String consistency = updateObj.getConsistencyInfo().get("type");
-
- logger.info(EELFLoggerDelegate.applicationLogger, "--------------Music " + consistency
- + " update-" + operationId + "-------------------------");
- // obtain the field value pairs of the update
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
- Map<String, Object> valuesMap = updateObj.getValues();
-
- TableMetadata tableInfo;
- try {
- tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename);
- } catch (MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
- }
- if (tableInfo == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"Table information not found. Please check input for table name= "+tablename, AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
- .setError("Table information not found. Please check input for table name= "
- + keyspace + "." + tablename).toMap()).build();
- }
- String vectorTs =
- String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
- StringBuilder fieldValueString = new StringBuilder("vector_ts=?,");
- queryObject.addValue(vectorTs);
- int counter = 0;
- for (Map.Entry<String, Object> entry : valuesMap.entrySet()) {
- Object valueObj = entry.getValue();
- DataType colType = null;
- try {
- colType = tableInfo.getColumn(entry.getKey()).getType();
- } catch(NullPointerException ex) {
- logger.error(EELFLoggerDelegate.errorLogger, ex, "Invalid column name : "+entry.getKey());
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Invalid column name : "+entry.getKey()).toMap()).build();
- }
- Object valueString = null;
- try {
- valueString = MusicUtil.convertToActualDataType(colType, valueObj);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e);
- }
- fieldValueString.append(entry.getKey() + "= ?");
- queryObject.addValue(valueString);
- if (counter != valuesMap.size() - 1)
- fieldValueString.append(",");
- counter = counter + 1;
- }
- String ttl = updateObj.getTtl();
- String timestamp = updateObj.getTimestamp();
-
- queryObject.appendQueryString("UPDATE " + keyspace + "." + tablename + " ");
- if ((ttl != null) && (timestamp != null)) {
-
- logger.info("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("ONLY TTL there");
- queryObject.appendQueryString(" USING TTL ?");
- queryObject.addValue(Integer.parseInt(ttl));
- }
-
- if ((ttl == null) && (timestamp != null)) {
- logger.info("ONLY timestamp there");
- queryObject.appendQueryString(" USING TIMESTAMP ?");
- queryObject.addValue(Long.parseLong(timestamp));
- }
- // get the row specifier
- RowIdentifier rowId = null;
- try {
- rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject);
- if(rowId == null || rowId.primarKeyValue.isEmpty()) {
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
- .setError("Mandatory WHERE clause is missing. Please check the input request.").toMap()).build();
- }
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
- }
-
- queryObject.appendQueryString(
- " SET " + fieldValueString + " WHERE " + rowId.rowIdString + ";");
-
- // get the conditional, if any
- Condition conditionInfo;
- if (updateObj.getConditions() == null)
- conditionInfo = null;
- else {// to avoid parsing repeatedly, just send the select query to
- // obtain row
- PreparedQueryObject selectQuery = new PreparedQueryObject();
- selectQuery.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " WHERE "
- + rowId.rowIdString + ";");
- selectQuery.addValue(rowId.primarKeyValue);
- conditionInfo = new Condition(updateObj.getConditions(), selectQuery);
- }
-
- ReturnType operationResult = null;
- long jsonParseCompletionTime = System.currentTimeMillis();
-
- if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && updateObj.getConsistencyInfo().get("consistency") != null) {
- if(MusicUtil.isValidConsistency(updateObj.getConsistencyInfo().get("consistency")))
- queryObject.setConsistency(updateObj.getConsistencyInfo().get("consistency"));
- else
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Invalid Consistency type").toMap()).build();
- }
- queryObject.setOperation("update");
- if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL))
- operationResult = MusicCore.eventualPut(queryObject);
- else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
- String lockId = updateObj.getConsistencyInfo().get("lockId");
- if(lockId == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or"
- + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock "
- + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build();
- }
- 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, 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) {
- logger.error(EELFLoggerDelegate.errorLogger,e, 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.EVENTUAL_NB)) {
- operationResult = MusicCore.eventualPut_nb(queryObject, keyspace, tablename, rowId.primarKeyValue);
- }
- long actualUpdateCompletionTime = System.currentTimeMillis();
-
- long endTime = System.currentTimeMillis();
- String timingString = "Time taken in ms for Music " + consistency + " update-" + operationId
- + ":" + "|total operation time:" + (endTime - startTime)
- + "|json parsing time:" + (jsonParseCompletionTime - startTime)
- + "|update time:" + (actualUpdateCompletionTime - jsonParseCompletionTime)
- + "|";
-
- if (operationResult != null && operationResult.getTimingInfo() != null) {
- String lockManagementTime = operationResult.getTimingInfo();
- timingString = timingString + lockManagementTime;
- }
- logger.info(EELFLoggerDelegate.applicationLogger, timingString);
-
- if (operationResult==null) {
- logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build();
- }
- if ( operationResult.getResult() == ResultType.SUCCESS ) {
- return response.status(Status.OK).entity(new JsonResponse(operationResult.getResult()).setMessage(operationResult.getMessage()).toMap()).build();
- } else {
- logger.error(EELFLoggerDelegate.errorLogger,operationResult.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(operationResult.getResult()).setError(operationResult.getMessage()).toMap()).build();
- }
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
- /**
- *
- * @param delObj
- * @param keyspace
- * @param tablename
- * @param info
- * @return
- * @throws MusicServiceException
- * @throws MusicQueryException
- * @throws Exception
- */
- @DELETE
- @Path("/{keyspace: .*}/tables/{tablename: .*}/rows")
- @ApiOperation(value = "Delete From table", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response deleteFromTable(
- @ApiParam(value = "Major Version",
- required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",
- required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",
- required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam(NS) String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- JsonDelete delObj,
- @ApiParam(value = "Keyspace Name",
- required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name",
- required = true) @PathParam("tablename") String tablename,
- @Context UriInfo info) throws MusicQueryException, MusicServiceException {
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
- .setError("one or more path parameters are not set, please check and try again")
- .toMap()).build();
- }
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
- if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.DELETE_FROM_TABLE)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- if(delObj == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"Required HTTP Request body is missing.", AppMessages.MISSINGDATA ,ErrorSeverity.WARN, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Required HTTP Request body is missing.").toMap()).build();
- }
- PreparedQueryObject queryObject = new PreparedQueryObject();
- StringBuilder columnString = new StringBuilder();
-
- int counter = 0;
- List<String> columnList = delObj.getColumns();
- if (columnList != null) {
- for (String column : columnList) {
- columnString.append(column);
- if (counter != columnList.size() - 1)
- columnString.append(",");
- counter = counter + 1;
- }
- }
-
- // get the row specifier
- RowIdentifier rowId = null;
- try {
- rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject);
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
- }
- String rowSpec = rowId.rowIdString.toString();
-
- if ((columnList != null) && (!rowSpec.isEmpty())) {
- queryObject.appendQueryString("DELETE " + columnString + " FROM " + keyspace + "."
- + tablename + " WHERE " + rowSpec + ";");
- }
-
- if ((columnList == null) && (!rowSpec.isEmpty())) {
- queryObject.appendQueryString("DELETE FROM " + keyspace + "." + tablename + " WHERE "
- + rowSpec + ";");
- }
-
- if ((columnList != null) && (rowSpec.isEmpty())) {
- queryObject.appendQueryString(
- "DELETE " + columnString + " FROM " + keyspace + "." + rowSpec + ";");
- }
- // get the conditional, if any
- Condition conditionInfo;
- if (delObj.getConditions() == null)
- conditionInfo = null;
- else {// to avoid parsing repeatedly, just send the select query to
- // obtain row
- PreparedQueryObject selectQuery = new PreparedQueryObject();
- selectQuery.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " WHERE "
- + rowId.rowIdString + ";");
- selectQuery.addValue(rowId.primarKeyValue);
- conditionInfo = new Condition(delObj.getConditions(), selectQuery);
- }
-
- String consistency = delObj.getConsistencyInfo().get("type");
-
-
- if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && delObj.getConsistencyInfo().get("consistency")!=null) {
-
- if(MusicUtil.isValidConsistency(delObj.getConsistencyInfo().get("consistency")))
- queryObject.setConsistency(delObj.getConsistencyInfo().get("consistency"));
- else
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Invalid Consistency type").toMap()).build();
- }
-
- ReturnType operationResult = null;
- queryObject.setOperation("delete");
- try {
- if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL))
- operationResult = MusicCore.eventualPut(queryObject);
- else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
- String lockId = delObj.getConsistencyInfo().get("lockId");
- if(lockId == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or"
- + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock "
- + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build();
- }
- operationResult = MusicCore.criticalPut(keyspace, tablename, rowId.primarKeyValue,
- queryObject, lockId, conditionInfo);
- } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
- operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue,
- queryObject, conditionInfo);
- } else if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) {
-
- operationResult = MusicCore.eventualPut_nb(queryObject, keyspace, tablename, rowId.primarKeyValue);
- }
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e, 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();
- }
- if (operationResult==null) {
- logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build();
- }
- if (operationResult.getResult().equals(ResultType.SUCCESS)) {
- return response.status(Status.OK).entity(new JsonResponse(operationResult.getResult()).setMessage(operationResult.getMessage()).toMap()).build();
- } else {
- logger.error(EELFLoggerDelegate.errorLogger,operationResult.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(operationResult.getMessage()).toMap()).build();
- }
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
- /**
- *
- * @param tabObj
- * @param keyspace
- * @param tablename
- * @throws Exception
- */
- @DELETE
- @Path("/{keyspace: .*}/tables/{tablename: .*}")
- @ApiOperation(value = "Drop Table", response = String.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response dropTable(
- @ApiParam(value = "Major Version",
- required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",
- required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",
- required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam(NS) String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "Keyspace Name",
- required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name",
- required = true) @PathParam("tablename") String tablename) throws Exception {
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
- .setError("one or more path parameters are not set, please check and try again")
- .toMap()).build();
- }
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
- if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.DROP_TABLE)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- String consistency = "eventual";// for now this needs only eventual
- // consistency
- PreparedQueryObject query = new PreparedQueryObject();
- query.appendQueryString("DROP TABLE " + keyspace + "." + tablename + ";");
- try {
- return response.status(Status.OK).entity(new JsonResponse(MusicCore.nonKeyRelatedPut(query, consistency)).toMap()).build();
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
- }
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
- /**
- *
- * @param selObj
- * @param keyspace
- * @param tablename
- * @param info
- * @return
- */
- @PUT
- @Path("/{keyspace: .*}/tables/{tablename: .*}/rows/criticalget")
- @ApiOperation(value = "Select Critical", response = Map.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response selectCritical(
- @ApiParam(value = "Major Version",
- required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",
- required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",
- required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam(NS) String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- JsonInsert selObj,
- @ApiParam(value = "Keyspace Name",
- required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name",
- required = true) @PathParam("tablename") String tablename,
- @Context UriInfo info) throws Exception {
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
- .setError("one or more path parameters are not set, please check and try again")
- .toMap()).build();
- }
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
- if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.SELECT_CRITICAL)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- String lockId = selObj.getConsistencyInfo().get("lockId");
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
-
- RowIdentifier rowId = null;
- try {
- rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject);
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
- }
- queryObject.appendQueryString(
- "SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowId.rowIdString + ";");
-
- ResultSet results = null;
-
- String consistency = selObj.getConsistencyInfo().get("type");
-
- if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
- if(lockId == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or"
- + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock "
- + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build();
- }
- results = MusicCore.criticalGet(keyspace, tablename, rowId.primarKeyValue, queryObject,
- lockId);
- } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
- results = MusicCore.atomicGet(keyspace, tablename, rowId.primarKeyValue, queryObject);
- }
- if(results!=null && results.getAvailableWithoutFetching() >0) {
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build();
- }
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setError("No data found").toMap()).build();
-
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
- /**
- *
- * @param keyspace
- * @param tablename
- * @param info
- * @return
- * @throws Exception
- */
- @GET
- @Path("/{keyspace: .*}/tables/{tablename: .*}/rows")
- @ApiOperation(value = "Select All or Select Specific", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response select(
- @ApiParam(value = "Major Version",
- required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",
- required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",
- required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam(NS) String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "Keyspace Name",
- required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name",
- required = true) @PathParam("tablename") String tablename,
- @Context UriInfo info) throws Exception {
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
- .setError("one or more path parameters are not set, please check and try again")
- .toMap()).build();
- }
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
- if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.SELECT)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
-
- if (info.getQueryParameters().isEmpty())// select all
- queryObject.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + ";");
- else {
- int limit = -1; // do not limit the number of results
- try {
- queryObject = selectSpecificQuery(keyspace, tablename, info, limit);
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger, ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
- }
- }
-
- try {
- ResultSet results = MusicCore.get(queryObject);
- if(results.getAvailableWithoutFetching() >0) {
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build();
- }
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).setError("No data found").toMap()).build();
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger, ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
- }
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
- /**
- *
- * @param keyspace
- * @param tablename
- * @param info
- * @param limit
- * @return
- * @throws MusicServiceException
- */
- public PreparedQueryObject selectSpecificQuery(String keyspace,
- String tablename, UriInfo info, int limit)
- throws MusicServiceException {
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
- StringBuilder rowIdString = getRowIdentifier(keyspace, tablename, info.getQueryParameters(),
- queryObject).rowIdString;
-
- queryObject.appendQueryString(
- "SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowIdString);
-
- if (limit != -1) {
- queryObject.appendQueryString(" LIMIT " + limit);
- }
-
- queryObject.appendQueryString(";");
- return queryObject;
-
- }
-
- /**
- *
- * @param keyspace
- * @param tablename
- * @param rowParams
- * @param queryObject
- * @return
- * @throws MusicServiceException
- */
- private RowIdentifier getRowIdentifier(String keyspace, String tablename,
- MultivaluedMap<String, String> rowParams, PreparedQueryObject queryObject)
- throws MusicServiceException {
- StringBuilder rowSpec = new StringBuilder();
- int counter = 0;
- TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename);
- if (tableInfo == null) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Table information not found. Please check input for table name= "
- + keyspace + "." + tablename);
- throw new MusicServiceException(
- "Table information not found. Please check input for table name= "
- + keyspace + "." + tablename);
- }
- StringBuilder primaryKey = new StringBuilder();
- 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 = null;
- Object formattedValue = null;
- try {
- colType = tableInfo.getColumn(entry.getKey()).getType();
- formattedValue = MusicUtil.convertToActualDataType(colType, indValue);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e);
- }
- if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey()))
- primaryKey.append(indValue);
- rowSpec.append(keyName + "= ?");
- queryObject.addValue(formattedValue);
- if (counter != rowParams.size() - 1)
- rowSpec.append(" AND ");
- counter = counter + 1;
- }
- return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject);
- }
-}
diff --git a/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java b/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java
deleted file mode 100644
index cb8965ee..00000000
--- a/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- *
- * Modifications Copyright (C) 2018 IBM.
- * ===================================================================
- * 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.HashMap;
-/**
- * @author inam
- *
- */
-import java.util.Map;
-
-import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.GET;
-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.Response;
-import javax.ws.rs.core.Response.Status;
-
-
-import org.onap.music.eelf.healthcheck.MusicHealthCheck;
-import org.onap.music.eelf.logging.EELFLoggerDelegate;
-import org.onap.music.main.MusicUtil;
-
-import com.datastax.driver.core.ConsistencyLevel;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-
-
-
-
-@Path("/v2/service")
-@Api(value="Healthcheck Api")
-public class RestMusicHealthCheckAPI {
-
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
- private static final String ACTIVE_STATUS = "ACTIVE";
-
- @GET
- @Path("/pingCassandra/{consistency}")
- @ApiOperation(value = "Get Health Status", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response cassandraStatus(@Context HttpServletResponse response, @ApiParam(value = "Consistency level",
- required = true) @PathParam("consistency") String consistency) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Cassandra");
-
- Map<String, Object> resultMap = new HashMap<>();
- if(ConsistencyLevel.valueOf(consistency) == null) {
- resultMap.put("INVALID", "Consistency level is invalid...");
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- MusicHealthCheck cassHealthCheck = new MusicHealthCheck();
- String status = cassHealthCheck.getCassandraStatus(consistency);
- if(status.equals(ACTIVE_STATUS)) {
- resultMap.put(ACTIVE_STATUS, "Cassandra Running and Listening to requests");
- return Response.status(Status.OK).entity(resultMap).build();
- } else {
- 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("/musicHealthCheck")
- @ApiOperation(value = "Get Health Status", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response musicHealthCheck() {
- logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for Health Check status for MUSIC");
- Map<String, Object> resultMap = new HashMap<>();
- MusicHealthCheck healthCheck = new MusicHealthCheck();
-
- String status = healthCheck.getCassandraStatus(ConsistencyLevel.ANY.toString());
- if(status.equals(ACTIVE_STATUS)) {
- resultMap.put("Cassandra", "Active");
- } else {
- resultMap.put("Cassandra", "Inactive");
- }
- resultMap.put("MUSIC", "Active");
- return Response.status(Status.OK).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
deleted file mode 100644
index 943f4ca8..00000000
--- a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java
+++ /dev/null
@@ -1,457 +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.Map;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import javax.ws.rs.core.Response.Status;
-
-import org.onap.music.authentication.MusicAAFAuthentication;
-import org.onap.music.authentication.MusicAuthenticator;
-import org.onap.music.authentication.MusicAuthenticator.Operation;
-import org.onap.music.datastore.jsonobjects.JsonLeasedLock;
-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.cassandra.MusicLockState;
-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 io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-
-
-@Path("/v2/locks/")
-@Api(value="Lock Api")
-public class RestMusicLocksAPI {
-
- private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicLocksAPI.class);
- private static final String XMINORVERSION = "X-minorVersion";
- private static final String XPATCHVERSION = "X-patchVersion";
- private static final String VERSION = "v2";
-
- private MusicAuthenticator authenticator = new MusicAAFAuthentication();
-
- /**
- * Puts the requesting process in the q for this lock. The corresponding
- * node will be created if it did not already exist
- *
- * @param lockName
- * @return
- * @throws Exception
- */
- @POST
- @Path("/create/{lockname}")
- @ApiOperation(value = "Create Lock",
- notes = "Puts the requesting process in the q for this lock." +
- " The corresponding lock will be created if it did not already exist." +
- " Lock Name is the \"key\" of the form keyspaceName.tableName.rowId",
- response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response createLockReference(
- @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName,
- @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam("ns") String ns) throws Exception{
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String, Object> resultMap = MusicCore.validateLock(lockName);
- if (resultMap.containsKey("Error")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- response.status(Status.BAD_REQUEST);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build();
- }
- String keyspaceName = (String) resultMap.get("keyspace");
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) ");
-
- if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.CREATE_LOCKREF)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- ResultType status = ResultType.SUCCESS;
- String lockId = MusicCore.createLockReference(lockName);
-
- if (lockId == null) {
- status = ResultType.FAILURE;
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.LOCKINGERROR ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(status).setError("Lock Id is null").toMap()).build();
- }
- return response.status(Status.OK).entity(new JsonResponse(status).setLock(lockId).toMap()).build();
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
- /**
- *
- * Checks if the node is in the top of the queue and hence acquires the lock
- *
- * @param lockId
- * @return
- * @throws Exception
- */
- @GET
- @Path("/acquire/{lockreference}")
- @ApiOperation(value = "Aquire Lock",
- notes = "Checks if the node is in the top of the queue and hence acquires the lock",
- response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response accquireLock(
- @ApiParam(value="Lock Reference",required=true) @PathParam("lockreference") String lockId,
- @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam("ns") String ns) throws Exception{
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String, Object> resultMap = MusicCore.validateLock(lockId);
- if (resultMap.containsKey("Error")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- response.status(Status.BAD_REQUEST);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build();
- }
-
- String keyspaceName = (String) resultMap.get("keyspace");
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) ");
-
- if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.ACQUIRE_LOCK)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- try {
- String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$'));
- ReturnType lockStatus = MusicCore.acquireLock(lockName,lockId);
- if ( lockStatus.getResult().equals(ResultType.SUCCESS)) {
- response.status(Status.OK);
- } else {
- response.status(Status.BAD_REQUEST);
- }
- return response.entity(new JsonResponse(lockStatus.getResult()).setLock(lockId).setMessage(lockStatus.getMessage()).toMap()).build();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,AppMessages.INVALIDLOCK + lockId, ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Unable to aquire lock").toMap()).build();
- }
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
-
-
-
- @POST
- @Path("/acquire-with-lease/{lockreference}")
- @ApiOperation(value = "Aquire Lock with Lease", response = Map.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response accquireLockWithLease(JsonLeasedLock lockObj,
- @ApiParam(value="Lock Reference",required=true) @PathParam("lockreference") String lockId,
- @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam("ns") String ns) throws Exception{
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String, Object> resultMap = MusicCore.validateLock(lockId);
- if (resultMap.containsKey("Error")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- response.status(Status.BAD_REQUEST);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build();
- }
- String keyspaceName = (String) resultMap.get("keyspace");
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) ");
- resultMap.remove("keyspace");
- if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.ACQUIRE_LOCK)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$'));
- ReturnType lockLeaseStatus = MusicCore.acquireLockWithLease(lockName, lockId, lockObj.getLeasePeriod());
- if ( lockLeaseStatus.getResult().equals(ResultType.SUCCESS)) {
- response.status(Status.OK);
- } else {
- response.status(Status.BAD_REQUEST);
- }
- return response.entity(new JsonResponse(lockLeaseStatus.getResult()).setLock(lockName)
- .setMessage(lockLeaseStatus.getMessage())
- .setLockLease(String.valueOf(lockObj.getLeasePeriod())).toMap()).build();
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
-
- @GET
- @Path("/enquire/{lockname}")
- @ApiOperation(value = "Get Lock Holder",
- notes = "Gets the current Lock Holder",
- response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response currentLockHolder(
- @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName,
- @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam("ns") String ns) throws Exception{
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String, Object> resultMap = MusicCore.validateLock(lockName);
- if (resultMap.containsKey("Error")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- response.status(Status.BAD_REQUEST);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build();
- }
-
- String keyspaceName = (String) resultMap.get("keyspace");
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) ");
- resultMap.remove("keyspace");
- if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.CURRENT_LOCK)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- String who = MusicCore.whoseTurnIsIt(lockName);
- ResultType status = ResultType.SUCCESS;
- String error = "";
- if ( who == null ) {
- status = ResultType.FAILURE;
- error = "There was a problem getting the lock holder";
- logger.error(EELFLoggerDelegate.errorLogger,"There was a problem getting the lock holder", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build();
- }
- return response.status(Status.OK).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build();
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
- @GET
- @Path("/{lockname}")
- @ApiOperation(value = "Lock State",
- notes = "Returns current Lock State and Holder.",
- response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response currentLockState(
- @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName,
- @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam("ns") String ns) throws Exception{
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String, Object> resultMap = MusicCore.validateLock(lockName);
- if (resultMap.containsKey("Error")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- response.status(Status.BAD_REQUEST);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build();
- }
- String keyspaceName = (String) resultMap.get("keyspace");
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) ");
- resultMap.remove("keyspace");
- if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.CURRENT_LOCK)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- String who = MusicCore.whoseTurnIsIt(lockName);
- ResultType status = ResultType.SUCCESS;
- String error = "";
- if ( who == null ) {
- status = ResultType.FAILURE;
- error = "There was a problem getting the lock holder";
- logger.error(EELFLoggerDelegate.errorLogger,"There was a problem getting the lock holder", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build();
- }
- return response.status(Status.OK).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build();
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
-
- //MusicLockState mls = MusicZKCore.getMusicLockState(lockName);
-// Map<String,Object> returnMap = null;
-// JsonResponse jsonResponse = new JsonResponse(ResultType.FAILURE).setLock(lockName);
-// if(mls == null) {
-// jsonResponse.setError("");
-// jsonResponse.setMessage("No lock object created yet..");
-// logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
-// return response.status(Status.BAD_REQUEST).entity(jsonResponse.toMap()).build();
-// } else {
-// jsonResponse.setStatus(ResultType.SUCCESS);
-// jsonResponse.setLockStatus(mls.getLockStatus());
-// jsonResponse.setLockHolder(mls.getLockHolder());
-// return response.status(Status.OK).entity(jsonResponse.toMap()).build();
-// }
-
- }
-
- /**
- *
- * deletes the process from the zk queue
- *
- * @param lockId
- * @throws Exception
- */
- @DELETE
- @Path("/release/{lockreference}")
- @ApiOperation(value = "Release Lock",
- notes = "deletes the process from the zk queue",
- response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response unLock(@PathParam("lockreference") String lockId,
- @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam("ns") String ns) throws Exception{
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String, Object> resultMap = MusicCore.validateLock(lockId);
- if (resultMap.containsKey("Error")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- response.status(Status.BAD_REQUEST);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build();
- }
-
- String keyspaceName = (String) resultMap.get("keyspace");
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) ");
- resultMap.remove("keyspace");
- if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.DELETE_LOCK)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- boolean voluntaryRelease = true;
- MusicLockState mls = MusicCore.releaseLock(lockId,voluntaryRelease);
- if(mls.getErrorMessage() != null) {
- resultMap.put(ResultType.EXCEPTION.getResult(), mls.getErrorMessage());
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- Map<String,Object> returnMap = null;
- if (mls.getLockStatus() == MusicLockState.LockStatus.UNLOCKED) {
- returnMap = new JsonResponse(ResultType.SUCCESS).setLock(lockId)
- .setLockStatus(mls.getLockStatus()).toMap();
- response.status(Status.OK);
- }
- if (mls.getLockStatus() == MusicLockState.LockStatus.LOCKED) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.LOCKINGERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- returnMap = new JsonResponse(ResultType.FAILURE).setLock(lockId)
- .setLockStatus(mls.getLockStatus()).toMap();
- response.status(Status.BAD_REQUEST);
- }
- return response.entity(returnMap).build();
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
- /**
- *
- * @param lockName
- * @throws Exception
- */
- @DELETE
- @Path("/delete/{lockname}")
- @ApiOperation(value = "Delete Lock", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response deleteLock(@PathParam("lockname") String lockName,
- @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
- @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
- @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam("ns") String ns) throws Exception{
- try {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String, Object> resultMap = MusicCore.validateLock(lockName);
- if (resultMap.containsKey("Error")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- response.status(Status.BAD_REQUEST);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build();
- }
-
- String keyspaceName = (String) resultMap.get("keyspace");
- EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) ");
- resultMap.remove("keyspace");
- if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.DELETE_LOCK)) {
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
- .toMap()).build();
- }
-
- try{
- MusicCore.deleteLock(lockName);
- }catch (Exception e) {
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
- }
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).toMap()).build();
- } finally {
- EELFLoggerDelegate.mdcRemove("keyspace");
- }
- }
-
-}
diff --git a/src/main/java/org/onap/music/rest/RestMusicQAPI.java b/src/main/java/org/onap/music/rest/RestMusicQAPI.java
deleted file mode 100755
index 676730e0..00000000
--- a/src/main/java/org/onap/music/rest/RestMusicQAPI.java
+++ /dev/null
@@ -1,452 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * Modifications Copyright (C) 2019 IBM.
- * ===================================================================
- * 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.HashMap;
-import java.util.Map;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-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.UriInfo;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import javax.ws.rs.core.Response.Status;
-import org.onap.music.datastore.jsonobjects.JsonDelete;
-import org.onap.music.datastore.jsonobjects.JsonInsert;
-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.eelf.logging.format.AppMessages;
-import org.onap.music.eelf.logging.format.ErrorSeverity;
-import org.onap.music.eelf.logging.format.ErrorTypes;
-import org.apache.commons.lang3.StringUtils;
-import org.onap.music.datastore.MusicDataStoreHandle;
-import org.onap.music.datastore.PreparedQueryObject;
-import com.datastax.driver.core.ResultSet;
-import org.onap.music.exceptions.MusicQueryException;
-import org.onap.music.exceptions.MusicServiceException;
-import org.onap.music.main.MusicCore;
-import org.onap.music.main.MusicUtil;
-import org.onap.music.main.ResultType;
-import org.onap.music.response.jsonobjects.JsonResponse;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-
-@Path("/v2/priorityq/")
-@Api(value = "Q Api")
-public class RestMusicQAPI {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicQAPI.class);
-
-
- /**
- *
- * @param tableObj
- * @param keyspace
- * @param tablename
- * @throws Exception
- */
-
- @POST
- @Path("/keyspaces/{keyspace}/{qname}") // qname same as tablename
- @ApiOperation(value = "Create Q", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response createQ(
- @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",
- required = false) @HeaderParam("X-minorVersion") String minorVersion,
- @ApiParam(value = "Patch Version",
- required = false) @HeaderParam("X-patchVersion") String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- JsonTable tableObj,
- @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) throws Exception {
- ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion);
-
- Map<String, String> fields = tableObj.getFields();
- if (fields == null) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("CreateQ/Required table fields are empty or not set").toMap())
- .build();
- }
-
- String primaryKey = tableObj.getPrimaryKey();
- String partitionKey = tableObj.getPartitionKey();
- String clusteringKey = tableObj.getClusteringKey();
- String filteringKey = tableObj.getFilteringKey();
- String clusteringOrder = tableObj.getClusteringOrder();
-
- if(primaryKey == null) {
- primaryKey = tableObj.getFields().get("PRIMARY KEY");
- }
-
- if ((primaryKey == null) && (partitionKey == null)) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("CreateQ: Partition key cannot be empty").toMap())
- .build();
- }
-
- if ((primaryKey == null) && (clusteringKey == null)) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("CreateQ: Clustering key cannot be empty").toMap())
- .build();
- }
-
- if (clusteringOrder == null) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("CreateQ: Clustering Order cannot be empty").toMap())
- .build();
- }
-
- if ((primaryKey!=null) && (partitionKey == null)) {
- primaryKey = primaryKey.trim();
- int count1 = StringUtils.countMatches(primaryKey,')');
- int count2 = StringUtils.countMatches(primaryKey,'(');
- if (count1 != count2) {
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
- .setError("CreateQ Error: primary key '(' and ')' do not match, primary key=" + primaryKey)
- .toMap()).build();
- }
-
- if ( primaryKey.indexOf('(') == -1 || ( count2 == 1 && (primaryKey.lastIndexOf(')') +1) == primaryKey.length() ) )
- {
- if (primaryKey.contains(",") ) {
- partitionKey= primaryKey.substring(0,primaryKey.indexOf(','));
- partitionKey=partitionKey.replaceAll("[\\(]+","");
- clusteringKey=primaryKey.substring(primaryKey.indexOf(',')+1); // make sure index
- clusteringKey=clusteringKey.replaceAll("[)]+", "");
- } else {
- partitionKey=primaryKey;
- partitionKey=partitionKey.replaceAll("[\\)]+","");
- partitionKey=partitionKey.replaceAll("[\\(]+","");
- clusteringKey="";
- }
- } else {
- partitionKey= primaryKey.substring(0,primaryKey.indexOf(')'));
- partitionKey=partitionKey.replaceAll("[\\(]+","");
- partitionKey = partitionKey.trim();
- clusteringKey= primaryKey.substring(primaryKey.indexOf(')'));
- clusteringKey=clusteringKey.replaceAll("[\\(]+","");
- clusteringKey=clusteringKey.replaceAll("[\\)]+","");
- clusteringKey = clusteringKey.trim();
- if (clusteringKey.indexOf(',') == 0) clusteringKey=clusteringKey.substring(1);
- clusteringKey = clusteringKey.trim();
- if (clusteringKey.equals(",") ) clusteringKey=""; // print error if needed ( ... ),)
- }
- }
-
- if (partitionKey.trim().isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("CreateQ: Partition key cannot be empty").toMap())
- .build();
- }
-
- if (clusteringKey.trim().isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("CreateQ: Clustering key cannot be empty").toMap())
- .build();
- }
-
- if((filteringKey != null) && (filteringKey.equalsIgnoreCase(partitionKey))) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST)
- .entity(new JsonResponse(ResultType.FAILURE)
- .setError("CreateQ: Filtering key cannot be same as Partition Key").toMap())
- .build();
- }
-
- return new RestMusicDataAPI().createTable(version, minorVersion, patchVersion, aid, ns, authorization, tableObj, keyspace, tablename);
- }
-
- /**
- *
- * @param insObj
- * @param keyspace
- * @param tablename
- * @throws Exception
- */
- @POST
- @Path("/keyspaces/{keyspace}/{qname}/rows")
- @ApiOperation(value = "", response = Void.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- // public Map<String, Object> insertIntoQ(
- public Response insertIntoQ(
- @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",
- required = false) @HeaderParam("X-minorVersion") String minorVersion,
- @ApiParam(value = "Patch Version",
- required = false) @HeaderParam("X-patchVersion") String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- JsonInsert insObj,
- @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename)
- {
- ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion);
- if (insObj.getValues().isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
- .setError("Required HTTP Request body is missing.").toMap()).build();
- }
- return new RestMusicDataAPI().insertIntoTable(version, minorVersion, patchVersion, aid, ns,
- authorization, insObj, keyspace, tablename);
- }
-
- /**
- *
- * @param updateObj
- * @param keyspace
- * @param tablename
- * @param info
- * @return
- * @throws Exception
- */
- @PUT
- @Path("/keyspaces/{keyspace}/{qname}/rows")
- @ApiOperation(value = "updateQ", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response updateQ(
- @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",
- required = false) @HeaderParam("X-minorVersion") String minorVersion,
- @ApiParam(value = "Patch Version",
- required = false) @HeaderParam("X-patchVersion") String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- 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) throws MusicServiceException, MusicQueryException {
-
- ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion);
- if (updateObj.getValues().isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST)
- .entity(new JsonResponse(ResultType.FAILURE).setError(
- "Required HTTP Request body is missing. JsonUpdate updateObj.getValues() is empty. ")
- .toMap())
- .build();
-
-
- }
- return new RestMusicDataAPI().updateTable(version, minorVersion, patchVersion, aid, ns,
- authorization,updateObj, keyspace, tablename, info);
- }
-
- /**
- *
- * @param delObj
- * @param keyspace
- * @param tablename
- * @param info
- *
- * @return
- * @throws Exception
- */
-
- @DELETE
- @Path("/keyspaces/{keyspace}/{qname}/rows")
- @ApiOperation(value = "deleteQ", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response deleteFromQ(
- @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",
- required = false) @HeaderParam("X-minorVersion") String minorVersion,
- @ApiParam(value = "Patch Version",
- required = false) @HeaderParam("X-patchVersion") String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- 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) throws MusicServiceException, MusicQueryException {
- // added checking as per RestMusicDataAPI
- ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion);
- if (delObj == null) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
- .setError("deleteFromQ JsonDelete delObjis empty").toMap()).build();
- }
-
- return new RestMusicDataAPI().deleteFromTable(version, minorVersion, patchVersion, aid, ns,
- authorization, delObj, keyspace, tablename, info);
- }
-
- /**
- *
- * @param keyspace
- * @param tablename
- * @param info
- * @return
- * @throws Exception
- */
- @GET
- @Path("/keyspaces/{keyspace}/{qname}/peek")
- @ApiOperation(value = "", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- //public Map<String, HashMap<String, Object>> peek(
- public Response peek(
- @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",
- required = false) @HeaderParam("X-minorVersion") String minorVersion,
- @ApiParam(value = "Patch Version",
- required = false) @HeaderParam("X-patchVersion") String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename,
- @Context UriInfo info) {
- int limit =1; //peek must return just the top row
- Map<String ,String> auth = new HashMap<>();
- String userId =auth.get(MusicUtil.USERID);
- String password =auth.get(MusicUtil.PASSWORD);
- ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion);
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
- if (info.getQueryParameters() == null ) //|| info.getQueryParameters().isEmpty())
- queryObject.appendQueryString(
- "SELECT * FROM " + keyspace + "." + tablename + " LIMIT " + limit + ";");
- else {
-
- try {
- queryObject = new RestMusicDataAPI().selectSpecificQuery(keyspace, tablename, info, limit);
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR,
- ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST)
- .entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap())
- .build();
- }
- }
-
- try {
- ResultSet results = MusicCore.get(queryObject);
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS)
- .setDataResult(MusicDataStoreHandle.marshallResults(results)).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();
- }
- }
-
- /**
- *
- *
- * @param keyspace
- * @param tablename
- * @param info
- * @return
- * @throws Exception
- */
- @GET
- @Path("/keyspaces/{keyspace}/{qname}/filter")
- @ApiOperation(value = "filter", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- // public Map<String, HashMap<String, Object>> filter(
- public Response filter(
- @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version", required = false) @HeaderParam("X-minorVersion") String minorVersion,
- @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @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 {
- return new RestMusicDataAPI().select(version, minorVersion, patchVersion, aid, ns, authorization, keyspace, tablename, info);// , limit)
-
- }
-
- /**
- *
- * @param tabObj
- * @param keyspace
- * @param tablename
- * @throws Exception
- */
- @DELETE
- @ApiOperation(value = "DropQ", response = String.class)
- @Path("/keyspaces/{keyspace}/{qname}")
- @Produces(MediaType.APPLICATION_JSON)
- public Response dropQ(
- @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
- @ApiParam(value = "Minor Version",
- required = false) @HeaderParam("X-minorVersion") String minorVersion,
- @ApiParam(value = "Patch Version",
- required = false) @HeaderParam("X-patchVersion") String patchVersion,
- @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) throws Exception {
-
- return new RestMusicDataAPI().dropTable(version, minorVersion, patchVersion, aid, ns, authorization, keyspace, tablename);
- }
-}
diff --git a/src/main/java/org/onap/music/rest/RestMusicTestAPI.java b/src/main/java/org/onap/music/rest/RestMusicTestAPI.java
deleted file mode 100644
index 6d973acb..00000000
--- a/src/main/java/org/onap/music/rest/RestMusicTestAPI.java
+++ /dev/null
@@ -1,68 +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.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-
-import org.onap.music.eelf.logging.EELFLoggerDelegate;
-import org.onap.music.main.MusicUtil;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-
-
-@Path("/v{version: [0-9]+}/test")
-@Api(value="Test Api")
-public class RestMusicTestAPI {
-
- @SuppressWarnings("unused")
- private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicTestAPI.class);
-
- /**
- * Returns a test JSON. This will confirm that REST is working.
- * @return
- */
- @GET
- @ApiOperation(value = "Get Test", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Map<String, HashMap<String, String>> simpleTests(
- @Context HttpServletResponse response) {
- response.addHeader("X-latestVersion",MusicUtil.getVersion());
- Map<String, HashMap<String, String>> testMap = new HashMap<>();
- for(int i=0; i < 3; i++){
- HashMap<String, String> innerMap = new HashMap<>();
- innerMap.put("Music Version",MusicUtil.getVersion());
- innerMap.put(i+1+"", i+2+"");
- testMap.put(i+"", innerMap);
- }
- return testMap;
- }
-}
diff --git a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java b/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java
deleted file mode 100644
index 74b8e5dd..00000000
--- a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java
+++ /dev/null
@@ -1,64 +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.Map;
-
-import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-
-import org.onap.music.response.jsonobjects.JsonResponse;
-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;
-
-
-@Path("/v{version: [0-9]+}/version")
-@Api(value="Version Api")
-public class RestMusicVersionAPI {
-
- private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicVersionAPI.class);
-
- /**
- * Get the version of MUSIC
- * @return
- */
- @GET
- @ApiOperation(value = "Get Version", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Map<String,Object> version(@Context HttpServletResponse response) {
- logger.info("Replying to request for MUSIC version with MUSIC:" + MusicUtil.getVersion());
- response.addHeader("X-latestVersion",MusicUtil.getVersion());
- return new JsonResponse(ResultType.SUCCESS).setMusicVersion("MUSIC:" + MusicUtil.getVersion()).toMap();
- }
-} \ No newline at end of file
diff --git a/src/main/java/org/onap/music/service/MusicCoreService.java b/src/main/java/org/onap/music/service/MusicCoreService.java
deleted file mode 100644
index affdc7f2..00000000
--- a/src/main/java/org/onap/music/service/MusicCoreService.java
+++ /dev/null
@@ -1,110 +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.service;
-
-import java.util.List;
-import java.util.Map;
-
-import org.onap.music.datastore.PreparedQueryObject;
-import org.onap.music.exceptions.MusicLockingException;
-import org.onap.music.exceptions.MusicQueryException;
-import org.onap.music.exceptions.MusicServiceException;
-import org.onap.music.lockingservice.cassandra.MusicLockState;
-import org.onap.music.main.ResultType;
-import org.onap.music.main.ReturnType;
-import org.onap.music.datastore.*;
-
-import com.datastax.driver.core.ResultSet;
-
-public interface MusicCoreService {
-
-
- // Core Music Database Methods
-
-
- public ReturnType eventualPut(PreparedQueryObject queryObject);
-
- public ReturnType eventualPut_nb(PreparedQueryObject queryObject,String keyspace,String tablename,String primaryKey);
-
- public ReturnType criticalPut(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject, String lockId, Condition conditionInfo);
-
- public ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency)
- throws MusicServiceException;
-
- public ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException;
-
- public ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException;
-
- public ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException;
-
- public ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException;
-
- public ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject, Condition conditionInfo)
- throws MusicLockingException, MusicQueryException, MusicServiceException;
-
- public ResultSet criticalGet(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject, String lockId) throws MusicServiceException;
-
- // Core Music Locking Service Methods
-
- public String createLockReference(String fullyQualifiedKey); // lock name
-
- public ReturnType acquireLockWithLease(String key, String lockReference, long leasePeriod)
- throws MusicLockingException, MusicQueryException, MusicServiceException; // key,lock id,time
-
- public ReturnType acquireLock(String key, String lockReference)
- throws MusicLockingException, MusicQueryException, MusicServiceException; // key,lock id
-
- public ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject,
- String consistency) throws MusicServiceException;
-
- public ResultSet quorumGet(PreparedQueryObject query);
-
- public String whoseTurnIsIt(String fullyQualifiedKey);// lock name
-
- public void destroyLockRef(String lockId);
-
- //public MusicLockState destroyLockRef(String fullyQualifiedKey, String lockReference); // lock name, lock id
-
- //public MusicLockState voluntaryReleaseLock(String fullyQualifiedKey, String lockReference)
- // throws MusicLockingException;// lock name,lock id
-
- public void deleteLock(String lockName) throws MusicLockingException;
-
- //public MusicLockState forciblyReleaseLock(String fullyQualifiedKey, String lockReference) throws MusicLockingException, MusicServiceException, MusicQueryException;
-
- public List<String> getLockQueue(String fullyQualifiedKey)
- throws MusicServiceException, MusicQueryException, MusicLockingException;
-
- public long getLockQueueSize(String fullyQualifiedKey)
- throws MusicServiceException, MusicQueryException, MusicLockingException;
-
- public Map<String, Object> validateLock(String lockName);
-
- public MusicLockState releaseLock(String lockId, boolean voluntaryRelease);
-}
diff --git a/src/main/java/org/onap/music/service/impl/MusicCassaCore.java b/src/main/java/org/onap/music/service/impl/MusicCassaCore.java
deleted file mode 100644
index cb6e1ce4..00000000
--- a/src/main/java/org/onap/music/service/impl/MusicCassaCore.java
+++ /dev/null
@@ -1,709 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * Modifications Copyright (c) 2018 IBM.
- * ===================================================================
- * Modifications Copyright (c) 2019 Samsung
- * ===================================================================
- * 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.service.impl;
-
-import java.io.StringWriter;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.onap.music.datastore.MusicDataStore;
-import org.onap.music.datastore.MusicDataStoreHandle;
-import org.onap.music.datastore.PreparedQueryObject;
-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.exceptions.MusicLockingException;
-import org.onap.music.exceptions.MusicQueryException;
-import org.onap.music.exceptions.MusicServiceException;
-import org.onap.music.lockingservice.cassandra.CassaLockStore;
-import org.onap.music.lockingservice.cassandra.CassaLockStore.LockObject;
-import org.onap.music.lockingservice.cassandra.MusicLockState;
-import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus;
-import org.onap.music.main.MusicUtil;
-import org.onap.music.main.ResultType;
-import org.onap.music.main.ReturnType;
-import org.onap.music.service.MusicCoreService;
-
-import com.datastax.driver.core.DataType;
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Row;
-import com.datastax.driver.core.TableMetadata;
-
-import org.onap.music.datastore.*;
-
-public class MusicCassaCore implements MusicCoreService {
-
- public static CassaLockStore mLockHandle = null;;
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCassaCore.class);
- private static boolean unitTestRun=true;
- private static MusicCassaCore musicCassaCoreInstance = null;
-
- private MusicCassaCore() {
-
- }
- public static MusicCassaCore getInstance() {
-
- if(musicCassaCoreInstance == null) {
- musicCassaCoreInstance = new MusicCassaCore();
- }
- return musicCassaCoreInstance;
- }
-
- public static CassaLockStore getLockingServiceHandle() throws MusicLockingException {
- logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring lock store handle");
- long start = System.currentTimeMillis();
-
- if (mLockHandle == null) {
- try {
- mLockHandle = new CassaLockStore(MusicDataStoreHandle.getDSHandle());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKHANDLE,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- throw new MusicLockingException("Failed to aquire Locl store handle " + e);
- }
- }
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire lock store handle:" + (end - start) + " ms");
- return mLockHandle;
- }
-
-
-
- public String createLockReference(String fullyQualifiedKey) {
- String[] splitString = fullyQualifiedKey.split("\\.");
- String keyspace = splitString[0];
- String table = splitString[1];
- String lockName = splitString[2];
-
- logger.info(EELFLoggerDelegate.applicationLogger,"Creating lock reference for lock name:" + lockName);
- long start = System.currentTimeMillis();
- String lockReference = null;
- try {
- lockReference = "" + getLockingServiceHandle().genLockRefandEnQueue(keyspace, table, lockName);
- } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
- e.printStackTrace();
- }
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to create lock reference:" + (end - start) + " ms");
- return lockReference;
- }
-
-
- public ReturnType acquireLockWithLease(String fullyQualifiedKey, String lockReference, long leasePeriod) throws MusicLockingException, MusicQueryException, MusicServiceException {
- evictExpiredLockHolder(fullyQualifiedKey,leasePeriod);
- return acquireLock(fullyQualifiedKey, lockReference);
- }
-
- private void evictExpiredLockHolder(String fullyQualifiedKey, long leasePeriod) throws MusicLockingException, MusicQueryException, MusicServiceException {
-
- String[] splitString = fullyQualifiedKey.split("\\.");
- String keyspace = splitString[0];
- String table = splitString[1];
- String primaryKeyValue = splitString[2];
-
- LockObject currentLockHolderObject = getLockingServiceHandle().peekLockQueue(keyspace, table, primaryKeyValue);
-
- /* Release the lock of the previous holder if it has expired. if the update to the acquire time has not reached due to network delays, simply use the create time as the
- * reference*/
-
- long referenceTime = Math.max(Long.parseLong(currentLockHolderObject.acquireTime), Long.parseLong(currentLockHolderObject.createTime));
- if((System.currentTimeMillis() - referenceTime) > leasePeriod) {
- forciblyReleaseLock(fullyQualifiedKey, currentLockHolderObject.lockRef+"");
- logger.info(EELFLoggerDelegate.applicationLogger, currentLockHolderObject.lockRef+" forcibly released");
- }
- }
-
- private static ReturnType isTopOfLockStore(String keyspace, String table, String primaryKeyValue, String lockReference) throws MusicLockingException, MusicQueryException, MusicServiceException {
-
- //return failure to lock holders too early or already evicted from the lock store
- String topOfLockStoreS = getLockingServiceHandle().peekLockQueue(keyspace, table, primaryKeyValue).lockRef;
- long topOfLockStoreL = Long.parseLong(topOfLockStoreS);
- long lockReferenceL = Long.parseLong(lockReference);
-
- if(lockReferenceL > topOfLockStoreL) {
- logger.info(EELFLoggerDelegate.applicationLogger, lockReference+" is not the lock holder yet");
- return new ReturnType(ResultType.FAILURE, lockReference+" is not the lock holder yet");
- }
-
-
- if(lockReferenceL < topOfLockStoreL) {
- logger.info(EELFLoggerDelegate.applicationLogger, lockReference+" is no longer/or was never in the lock store queue");
- return new ReturnType(ResultType.FAILURE, lockReference+" is no longer/or was never in the lock store queue");
- }
-
- return new ReturnType(ResultType.SUCCESS, lockReference+" is top of lock store");
- }
-
- public ReturnType acquireLock(String fullyQualifiedKey, String lockId)
- throws MusicLockingException, MusicQueryException, MusicServiceException {
- String[] splitString = lockId.split("\\.");
- String keyspace = splitString[0].substring(1);//remove '$'
- String table = splitString[1];
- String primaryKeyValue = splitString[2].substring(0, splitString[2].lastIndexOf("$"));
- String localFullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$"));
- String lockRef = lockId.substring(lockId.lastIndexOf("$")+1); //lockRef is "$" to end
-
- ReturnType result = isTopOfLockStore(keyspace, table, primaryKeyValue, lockRef);
-
- if(result.getResult().equals(ResultType.FAILURE))
- return result;//not top of the lock store q
-
- //check to see if the value of the key has to be synced in case there was a forceful release
- String syncTable = keyspace+".unsyncedKeys_"+table;
- String query = "select * from "+syncTable+" where key='"+localFullyQualifiedKey+"';";
- PreparedQueryObject readQueryObject = new PreparedQueryObject();
- readQueryObject.appendQueryString(query);
- ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(readQueryObject);
- if (results.all().size() != 0) {
- logger.info("In acquire lock: Since there was a forcible release, need to sync quorum!");
- try {
- syncQuorum(keyspace, table, primaryKeyValue);
- } catch (Exception e) {
- StringWriter sw = new StringWriter();
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR506E] Failed to aquire lock ",ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- String exceptionAsString = sw.toString();
- return new ReturnType(ResultType.FAILURE, "Exception thrown while syncing key:\n" + exceptionAsString);
- }
- String cleanQuery = "delete from music_internal.unsynced_keys where key='"+localFullyQualifiedKey+"';";
- PreparedQueryObject deleteQueryObject = new PreparedQueryObject();
- deleteQueryObject.appendQueryString(cleanQuery);
- MusicDataStoreHandle.getDSHandle().executePut(deleteQueryObject, "critical");
- }
-
- getLockingServiceHandle().updateLockAcquireTime(keyspace, table, primaryKeyValue, lockRef);
-
- return new ReturnType(ResultType.SUCCESS, lockRef+" is the lock holder for the key");
- }
-
-
-
- /**
- *
- * @param tableQueryObject
- * @param consistency
- * @return Boolean Indicates success or failure
- * @throws MusicServiceException
- *
- *
- */
- public ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject, String consistency) throws MusicServiceException {
- boolean result = false;
-
- try {
- //create shadow locking table
- result = getLockingServiceHandle().createLockQueue(keyspace, table);
- if(result == false)
- return ResultType.FAILURE;
-
- result = false;
-
- //create table to track unsynced_keys
- table = "unsyncedKeys_"+table;
-
- String tabQuery = "CREATE TABLE IF NOT EXISTS "+keyspace+"."+table
- + " ( key text,PRIMARY KEY (key) );";
- PreparedQueryObject queryObject = new PreparedQueryObject();
-
- queryObject.appendQueryString(tabQuery);
- result = false;
- result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, "eventual");
-
-
- //create actual table
- result = MusicDataStoreHandle.getDSHandle().executePut(tableQueryObject, consistency);
- } catch (MusicQueryException | MusicServiceException | MusicLockingException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- throw new MusicServiceException(ex.getMessage());
- }
- return result?ResultType.SUCCESS:ResultType.FAILURE;
- }
-
- private static void syncQuorum(String keyspace, String table, String primaryKeyValue) throws Exception {
- logger.info(EELFLoggerDelegate.applicationLogger,"Performing sync operation---");
- PreparedQueryObject selectQuery = new PreparedQueryObject();
- PreparedQueryObject updateQuery = new PreparedQueryObject();
-
- // get the primary key d
- TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, table);
- String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName();// we only support single
- // primary key
- DataType primaryKeyType = tableInfo.getPrimaryKey().get(0).getType();
- Object cqlFormattedPrimaryKeyValue =
- MusicUtil.convertToActualDataType(primaryKeyType, primaryKeyValue);
-
- // get the row of data from a quorum
- selectQuery.appendQueryString("SELECT * FROM " + keyspace + "." + table + " WHERE "
- + primaryKeyName + "= ?" + ";");
- selectQuery.addValue(cqlFormattedPrimaryKeyValue);
- MusicUtil.writeBackToQuorum(selectQuery, primaryKeyName, updateQuery, keyspace, table,
- cqlFormattedPrimaryKeyValue);
-
- }
-
- /**
- *
- * @param query
- * @return ResultSet
- */
- public ResultSet quorumGet(PreparedQueryObject query) {
- ResultSet results = null;
- try {
- results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(query);
- } catch (MusicServiceException | MusicQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.MAJOR, ErrorTypes.GENERALSERVICEERROR);
-
- }
- return results;
-
- }
-
- /**
- *
- * @param fullyQualifiedKey lockName
- * @return
- */
- public String whoseTurnIsIt(String fullyQualifiedKey) {
- String[] splitString = fullyQualifiedKey.split("\\.");
- String keyspace = splitString[0];
- String table = splitString[1];
- String primaryKeyValue = splitString[2];
- try {
- return "$" + fullyQualifiedKey + "$"
- + getLockingServiceHandle().peekLockQueue(keyspace, table, primaryKeyValue).lockRef;
- } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKINGERROR+fullyQualifiedKey ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
- return null;
- }
-
- /**
- *
- * @param lockReference
- * @return
- */
- public static String getLockNameFromId(String lockReference) {
- StringTokenizer st = new StringTokenizer(lockReference);
- return st.nextToken("$");
- }
-
- @Override
- public void destroyLockRef(String lockId) {
- long start = System.currentTimeMillis();
- String fullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$"));
- String lockRef = lockId.substring(lockId.lastIndexOf('$')+1);
- String[] splitString = fullyQualifiedKey.split("\\.");
- String keyspace = splitString[0];
- String table = splitString[1];
- String primaryKeyValue = splitString[2];
- try {
- getLockingServiceHandle().deQueueLockRef(keyspace, table, primaryKeyValue, lockRef);
- } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK+lockRef ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms");
- }
-
- public MusicLockState destroyLockRef(String fullyQualifiedKey, String lockReference) {
- long start = System.currentTimeMillis();
- String[] splitString = fullyQualifiedKey.split("\\.");
- String keyspace = splitString[0];
- String table = splitString[1];
- String primaryKeyValue = splitString[2];
- try {
- getLockingServiceHandle().deQueueLockRef(keyspace, table, primaryKeyValue, lockReference);
- } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK+lockReference ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms");
- return new MusicLockState(LockStatus.UNLOCKED, "");
- }
-
- @Override
- public MusicLockState releaseLock(String lockId, boolean voluntaryRelease) {
- String fullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$"));
- String lockRef = lockId.substring(lockId.lastIndexOf('$')+1);
- if (voluntaryRelease) {
- return voluntaryReleaseLock(fullyQualifiedKey, lockRef);
- } else {
- return forciblyReleaseLock(fullyQualifiedKey, lockRef);
- }
- }
-
- public MusicLockState voluntaryReleaseLock(String fullyQualifiedKey, String lockReference) {
- return destroyLockRef(fullyQualifiedKey, lockReference);
- }
-
- public MusicLockState forciblyReleaseLock(String fullyQualifiedKey, String lockReference) {
- String[] splitString = fullyQualifiedKey.split("\\.");
- String keyspace = splitString[0];
- String table = splitString[1];
-
- //leave a signal that this key could potentially be unsynchronized
- String syncTable = keyspace+".unsyncedKeys_"+table;
- PreparedQueryObject queryObject = new PreparedQueryObject();
- String values = "(?)";
- queryObject.addValue(fullyQualifiedKey);
- String insQuery = "insert into "+syncTable+" (key) values "+values+";";
- queryObject.appendQueryString(insQuery);
- try {
- MusicDataStoreHandle.getDSHandle().executePut(queryObject, "critical");
- } catch (Exception e) {
- logger.error("Cannot forcibly release lock: " + fullyQualifiedKey + " " + lockReference + ". "
- + e.getMessage());
- }
-
- //now release the lock
- return destroyLockRef(fullyQualifiedKey, lockReference);
- }
-
- /**
- *
- * @param lockName
- * @throws MusicLockingException
- */
- public void deleteLock(String lockName) throws MusicLockingException {
- //deprecated
- }
-
- // Prepared Query Additions.
-
- /**
- *
- * @param queryObject
- * @return ReturnType
- * @throws MusicServiceException
- */
- public ReturnType eventualPut(PreparedQueryObject queryObject) {
- boolean result = false;
- try {
- result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL);
- } catch (MusicServiceException | MusicQueryException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " " + ex);
- return new ReturnType(ResultType.FAILURE, ex.getMessage());
- }
- if (result) {
- return new ReturnType(ResultType.SUCCESS, "Eventual Operation Successfully performed");
- } else {
- return new ReturnType(ResultType.FAILURE, "Eventual Operation failed to perform");
- }
- }
-
- /**
- *
- * @param queryObject
- * @return ReturnType
- * @throws MusicServiceException
- */
- public ReturnType eventualPut_nb(PreparedQueryObject queryObject,String keyspace,String tablename,String primaryKey) {
- boolean result = false;
- long guard = 0;
- PreparedQueryObject getGaurd = new PreparedQueryObject();
- getGaurd.appendQueryString("SELECT guard FROM "+keyspace+".lockq_"+tablename+ " WHERE key = ? ;");
- getGaurd.addValue(primaryKey);
- try {
- ResultSet getGaurdResult = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(getGaurd);
- Row row = getGaurdResult.one();
- if (row != null) {
- guard = row.getLong("guard");
- long timeOfWrite = System.currentTimeMillis();
- long ts = MusicUtil.v2sTimeStampInMicroseconds(guard, timeOfWrite);
- String query = queryObject.getQuery();
- if (!queryObject.getQuery().contains("USING TIMESTAMP")) {
- if (queryObject.getOperation().equalsIgnoreCase("delete"))
- query = query.replaceFirst("WHERE", " USING TIMESTAMP " + ts + " WHERE ");
- else
- query = query.replaceFirst("SET", "USING TIMESTAMP " + ts + " SET");
- }
- queryObject.replaceQueryString(query);
- }
-
- } catch (MusicServiceException | MusicQueryException e) {
- logger.error(EELFLoggerDelegate.applicationLogger,e.getMessage());
- }
- try {
- result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL);
- } catch (MusicServiceException | MusicQueryException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " " + ex);
- return new ReturnType(ResultType.FAILURE, ex.getMessage());
- }
- if (result) {
- return new ReturnType(ResultType.SUCCESS, "Eventual Operation Successfully performed");
- } else {
- return new ReturnType(ResultType.FAILURE, "Eventual Operation failed to perform");
- }
- }
-
- /**
- *
- * @param keyspace
- * @param table
- * @param primaryKeyValue
- * @param queryObject
- * @param lockId
- * @return
- */
- public ReturnType criticalPut(String keyspace, String table, String primaryKeyValue,
- PreparedQueryObject queryObject, String lockId, Condition conditionInfo) {
- long start = System.currentTimeMillis();
- try {
- ReturnType result = isTopOfLockStore(keyspace, table, primaryKeyValue,
- lockId.substring(lockId.lastIndexOf("$")+1));
- if(result.getResult().equals(ResultType.FAILURE))
- return result;//not top of the lock store q
-
- if (conditionInfo != null)
- try {
- if (conditionInfo.testCondition() == false)
- return new ReturnType(ResultType.FAILURE,
- "Lock acquired but the condition is not true");
- } catch (Exception e) {
- return new ReturnType(ResultType.FAILURE,
- "Exception thrown while checking the condition, check its sanctity:\n"
- + e.getMessage());
- }
-
- String query = queryObject.getQuery();
- long timeOfWrite = System.currentTimeMillis();
- long lockOrdinal = Long.parseLong(lockId.substring(lockId.lastIndexOf("$")+1));
- long ts = MusicUtil.v2sTimeStampInMicroseconds(lockOrdinal, timeOfWrite);
- // TODO: use Statement instead of modifying query
- if (!queryObject.getQuery().contains("USING TIMESTAMP")) {
- if (queryObject.getOperation().equalsIgnoreCase("delete"))
- query = query.replaceFirst("WHERE", " USING TIMESTAMP " + ts + " WHERE ");
- else if (queryObject.getOperation().equalsIgnoreCase("insert"))
- query = query.replaceFirst(";", " USING TIMESTAMP " + ts + " ; ");
- else
- query = query.replaceFirst("SET", "USING TIMESTAMP " + ts + " SET");
- }
- queryObject.replaceQueryString(query);
- MusicDataStore dsHandle = MusicDataStoreHandle.getDSHandle();
- dsHandle.executePut(queryObject, MusicUtil.CRITICAL);
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the critical put:" + (end - start) + " ms");
- }catch (MusicQueryException | MusicServiceException | MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- return new ReturnType(ResultType.FAILURE,
- "Exception thrown while doing the critical put\n"
- + e.getMessage());
- }
- return new ReturnType(ResultType.SUCCESS, "Update performed");
- }
-
-
- /**
- *
- * @param queryObject
- * @param consistency
- * @return Boolean Indicates success or failure
- * @throws MusicServiceException
- *
- *
- */
- public ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) throws MusicServiceException {
- // this is mainly for some functions like keyspace creation etc which does not
- // really need the bells and whistles of Music locking.
- boolean result = false;
- try {
- result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, consistency);
- } catch (MusicQueryException | MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.UNKNOWNERROR,
- ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- throw new MusicServiceException(ex.getMessage());
- }
- return result ? ResultType.SUCCESS : ResultType.FAILURE;
- }
-
- /**
- * This method performs DDL operation on cassandra.
- *
- * @param queryObject query object containing prepared query and values
- * @return ResultSet
- * @throws MusicServiceException
- */
- public ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException {
- ResultSet results = null;
- try {
- results = MusicDataStoreHandle.getDSHandle().executeOneConsistencyGet(queryObject);
- } catch (MusicQueryException | MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- throw new MusicServiceException(e.getMessage());
- }
- return results;
- }
-
- /**
- * This method performs DDL operations on cassandra, if the the resource is available. Lock ID
- * is used to check if the resource is free.
- *
- * @param keyspace name of the keyspace
- * @param table name of the table
- * @param primaryKeyValue primary key value
- * @param queryObject query object containing prepared query and values
- * @param lockId lock ID to check if the resource is free to perform the operation.
- * @return ResultSet
- */
- public ResultSet criticalGet(String keyspace, String table, String primaryKeyValue,
- PreparedQueryObject queryObject, String lockId) throws MusicServiceException {
- ResultSet results = null;
-
- try {
- ReturnType result = isTopOfLockStore(keyspace, table, primaryKeyValue,
- lockId.substring(lockId.lastIndexOf("$")+1));
- if(result.getResult().equals(ResultType.FAILURE))
- return null;//not top of the lock store q
- results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(queryObject);
- } catch (MusicQueryException | MusicServiceException | MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- }
- return results;
- }
-
- /**
- * This method performs DML operation on cassandra, when the lock of the dd is acquired.
- *
- * @param keyspaceName name of the keyspace
- * @param tableName name of the table
- * @param primaryKey primary key value
- * @param queryObject query object containing prepared query and values
- * @return ReturnType
- * @throws MusicLockingException
- * @throws MusicServiceException
- * @throws MusicQueryException
- */
- public ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException, MusicQueryException, MusicServiceException {
- long start = System.currentTimeMillis();
- String fullyQualifiedKey = keyspaceName + "." + tableName + "." + primaryKey;
- String lockId = createLockReference(fullyQualifiedKey);
- long lockCreationTime = System.currentTimeMillis();
- ReturnType lockAcqResult = acquireLock(fullyQualifiedKey, lockId);
- long lockAcqTime = System.currentTimeMillis();
-
- if (!lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId);
- voluntaryReleaseLock(fullyQualifiedKey,lockId);
- return lockAcqResult;
- }
-
- logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId);
- String lockRef = lockId.substring(lockId.lastIndexOf("$"));
- ReturnType criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey,
- queryObject, lockRef, conditionInfo);
- long criticalPutTime = System.currentTimeMillis();
- voluntaryReleaseLock(fullyQualifiedKey,lockId);
- long lockDeleteTime = System.currentTimeMillis();
- String timingInfo = "|lock creation time:" + (lockCreationTime - start)
- + "|lock accquire time:" + (lockAcqTime - lockCreationTime)
- + "|critical put time:" + (criticalPutTime - lockAcqTime)
- + "|lock delete time:" + (lockDeleteTime - criticalPutTime) + "|";
- criticalPutResult.setTimingInfo(timingInfo);
- return criticalPutResult;
- }
-
-
-
-
- /**
- * This method performs DDL operation on cassasndra, when the lock for the resource is acquired.
- *
- * @param keyspaceName name of the keyspace
- * @param tableName name of the table
- * @param primaryKey primary key value
- * @param queryObject query object containing prepared query and values
- * @return ResultSet
- * @throws MusicServiceException
- * @throws MusicLockingException
- * @throws MusicQueryException
- */
- public ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException {
- String fullyQualifiedKey = keyspaceName + "." + tableName + "." + primaryKey;
- String lockId = createLockReference(fullyQualifiedKey);
- long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
- ReturnType lockAcqResult = acquireLock(fullyQualifiedKey, lockId);
- if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId);
- String lockRef = lockId.substring(lockId.lastIndexOf("$"));
- ResultSet result =
- criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockRef);
- voluntaryReleaseLock(fullyQualifiedKey,lockId);
- return result;
- } else {
- voluntaryReleaseLock(fullyQualifiedKey,lockId);
- logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId);
- return null;
- }
- }
-
-
-
- /**
- * @param lockName
- * @return
- */
- public Map<String, Object> validateLock(String lockName) {
- return MusicUtil.validateLock(lockName);
- }
-
- @Override
- public ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException {
- //Deprecated
- return null;
- }
- @Override
- public List<String> getLockQueue(String fullyQualifiedKey)
- throws MusicServiceException, MusicQueryException, MusicLockingException {
- String[] splitString = fullyQualifiedKey.split("\\.");
- String keyspace = splitString[0];
- String table = splitString[1];
- String primaryKeyValue = splitString[2];
-
- return getLockingServiceHandle().getLockQueue(keyspace, table, primaryKeyValue);
- }
- @Override
- public long getLockQueueSize(String fullyQualifiedKey)
- throws MusicServiceException, MusicQueryException, MusicLockingException {
- String[] splitString = fullyQualifiedKey.split("\\.");
- String keyspace = splitString[0];
- String table = splitString[1];
- String primaryKeyValue = splitString[2];
-
- return getLockingServiceHandle().getLockQueueSize(keyspace, table, primaryKeyValue);
- }
- @Override
- public ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException {
- //deprecated
- return null;
- }
-
-}
diff --git a/src/main/resources/LICENSE.txt b/src/main/resources/LICENSE.txt
deleted file mode 100644
index cc6cdea5..00000000
--- a/src/main/resources/LICENSE.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-
-The following license applies to all files in this and sub-directories. Licenses
-are included in individual source files where appropriate, and if it differs
-from this text, it supersedes this. Any file that does not have license text
-defaults to being covered by this text; not all files support the addition of
-licenses.
-#
-# -------------------------------------------------------------------------
-# 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.
-#
-# -------------------------------------------------------------------------
-# \ No newline at end of file
diff --git a/src/main/resources/Resources.properties b/src/main/resources/Resources.properties
deleted file mode 100644
index 72269cb8..00000000
--- a/src/main/resources/Resources.properties
+++ /dev/null
@@ -1,50 +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=============================================
-#====================================================================
-#Resource key=Error Code|Message text|Resolution text |Description text
-LOADING_DEFAULT_LOG_CONFIGURATION=\
- EELF0001I|\
- Loading default logging configuration from system resource file "{0}"|\
- No external logging configurations were defined or found, So verify the default logging configuration from system resource file (../logback.xml). |\
- Loading default logging configuration from system resource file
-LOADING_LOG_CONFIGURATION=EELF0002I|\
- Loading logging configuration from file "{0}"|\
- Verify the correct logging configuration file is loaded. |\
- Loading logging configuration for specific file
-LOGGING_ALREADY_INITIALIZED=\
- EELF0003W|\
- Logging has already been initialized, check the container logging definitions to ensure they represent your desired logging configuration.|\
- Verify the container logging definitions to ensure they represent your desired logging configuration. |\
- Logging has already been initialized, check the container logging definitions to ensure they represent your desired logging configuration.
-NO_LOG_CONFIGURATION=\
- EELF0004E|\
- No log configuration could be found or defaulted!|\
- No external and default logging configuration file. |\
- No log configuration could be found or defaulted!
-SEARCHING_LOG_CONFIGURATION=\
- EELF0005I|\
- Searching path "{0}" for log configuration file "{1}"|\
- Verify the correct Path({user.home};etc;../etc) and filename (eelf.logging.file).|\
- Searching path for specific log configuration file.
-UNSUPPORTED_LOGGING_FRAMEWORK=\
- EELF0006E|\
- An unsupported logging framework is bound to SLF4J. |\
- Verify your logging frameworks.|\
- An unsupported logging framework is bound to SLF4J.
-
diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties
deleted file mode 100755
index 02e9c1a9..00000000
--- a/src/main/resources/application.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-server.port=8080
-server.servlet.context-path=/MUSIC/rest \ No newline at end of file
diff --git a/src/main/resources/cache.ccf b/src/main/resources/cache.ccf
deleted file mode 100644
index e152ee8b..00000000
--- a/src/main/resources/cache.ccf
+++ /dev/null
@@ -1,62 +0,0 @@
-# DEFAULT CACHE REGION
-jcs.default=DC
-jcs.default.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes
-jcs.default.cacheattributes.MaxObjects=1000
-jcs.default.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache
-jcs.default.elementattributes=org.apache.commons.jcs.engine.ElementAttributes
-jcs.default.elementattributes.IsEternal=true
-jcs.default.elementattributes.IsSpool=true
-
-# PRE-DEFINED CACHE REGIONS
-jcs.region.musicCache=
-jcs.region.musicCache.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes
-jcs.region.musicCache.cacheattributes.MaxObjects=1000
-jcs.region.musicCache.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache
-jcs.region.musicCache.cacheattributes.UseMemoryShrinker=false
-jcs.region.musicCache.cacheattributes.MaxMemoryIdleTime=3600
-jcs.region.musicCache.cacheattributes.ShrinkerInterval=60
-jcs.region.musicCache.cacheattributes.MaxSpoolPerRun=500
-jcs.region.musicCache.elementattributes=org.apache.commons.jcs.engine.ElementAttributes
-jcs.region.musicCache.elementattributes.IsEternal=false
-
-
-# PRE-DEFINED CACHE REGIONS
-jcs.region.aafCache=
-jcs.region.aafCache.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes
-jcs.region.aafCache.cacheattributes.MaxObjects=1000
-jcs.region.aafCache.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache
-jcs.region.aafCache.cacheattributes.UseMemoryShrinker=false
-jcs.region.aafCache.cacheattributes.MaxMemoryIdleTime=3600
-jcs.region.aafCache.cacheattributes.ShrinkerInterval=60
-jcs.region.aafCache.cacheattributes.MaxSpoolPerRun=500
-jcs.region.aafCache.elementattributes=org.apache.commons.jcs.engine.ElementAttributes
-jcs.region.aafCache.elementattributes.IsEternal=false
-
-# PRE-DEFINED CACHE REGIONS
-jcs.region.appNameCache=
-jcs.region.appNameCache.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes
-jcs.region.appNameCache.cacheattributes.MaxObjects=1000
-jcs.region.appNameCache.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache
-jcs.region.appNameCache.cacheattributes.UseMemoryShrinker=false
-jcs.region.appNameCache.cacheattributes.MaxMemoryIdleTime=3600
-jcs.region.appNameCache.cacheattributes.ShrinkerInterval=60
-jcs.region.appNameCache.cacheattributes.MaxSpoolPerRun=500
-jcs.region.appNameCache.elementattributes=org.apache.commons.jcs.engine.ElementAttributes
-jcs.region.appNameCache.elementattributes.IsEternal=false
-
-jcs.default=DC
-jcs.default.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes
-jcs.default.cacheattributes.MaxObjects=1000
-jcs.default.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache
-jcs.default.elementattributes=org.apache.commons.jcs.engine.ElementAttributes
-jcs.default.elementattributes.IsEternal=true
-jcs.default.elementattributes.IsSpool=true
-
-jcs.region.eternalCache=DC
-jcs.region.eternalCache.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes
-jcs.region.eternalCache.cacheattributes.MaxObjects=1000
-jcs.region.eternalCache.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache
-jcs.region.eternalCache.elementattributes=org.apache.commons.jcs.engine.ElementAttributes
-jcs.region.eternalCache.elementattributes.IsEternal=true
-jcs.region.eternalCache.elementattributes.IsSpool=true
-
diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml
deleted file mode 100644
index 6bc5fd5e..00000000
--- a/src/main/resources/logback.xml
+++ /dev/null
@@ -1,302 +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=============================================
- ====================================================================
--->
-<configuration scan="true" scanPeriod="3 seconds">
- <!--<jmxConfigurator /> -->
- <!-- directory path for all other type logs -->
- <property name="logDir" value="/opt/app/music/logs" />
-
- <!-- directory path for debugging type logs -->
- <property name="debugDir" value="debug-logs" />
-
- <!-- specify the component name -->
- <!-- <property name="componentName" value="EELF"></property> -->
- <property name="componentName" value="MUSIC"></property>
-
- <!-- log file names -->
- <property name="generalLogName" value="music" />
- <property name="securityLogName" value="security" />
- <property name="errorLogName" value="error" />
- <property name="metricsLogName" value="metrics" />
- <property name="auditLogName" value="audit" />
- <property name="debugLogName" value="debug" />
- <property name="defaultPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n" />
- <!-- <property name="applicationLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n" /> -->
- <property name="applicationLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5level %X{keyspace} - %msg%n" />
- <property name="auditLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
- <property name="metricsLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
- <!-- <property name="errorLoggerPattern" value= "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n " /> -->
- <property name="errorLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5level %X{keyspace} - %msg%n" />
- <property name="debugLoggerPattern" value="%date{ISO8601,UTC}|%X{RequestId}| %msg%n" ></property>
- <property name="logDirectory" value="${logDir}/${componentName}" />
- <property name="debugLogDirectory" value="${debugDir}/${componentName}" />
- <!-- Example evaluator filter applied against console appender -->
- <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
- <!-- <encoder>
- <pattern>${defaultPattern}</pattern>
- </encoder> -->
- <layout class="">
- <pattern>
- %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
- </pattern>
- </layout>
- </appender>
-
- <!-- ============================================================================ -->
- <!-- EELF Appenders -->
- <!-- ============================================================================ -->
-<!-- <appender name="EELF"
- class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${logDirectory}/${generalLogName}.log</file>
- <rollingPolicy
- class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${logDirectory}/${generalLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <triggeringPolicy
- class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>100MB</maxFileSize>
- </triggeringPolicy>
- <encoder>
- <pattern>${applicationLoggerPattern}</pattern>
- </encoder>
- </appender> -->
-
- <!-- <appender name="EELF" class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${logDirectory}/${generalLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
- daily rollover
- <fileNamePattern>${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
- <maxFileSize>1GB</maxFileSize>
- <maxHistory>5</maxHistory>
- <totalSizeCap>5GB</totalSizeCap>
- </rollingPolicy>
- <encoder>
- <pattern>${applicationLoggerPattern}</pattern>
- </encoder>
- </appender> -->
-
-
- <appender name="EELF" class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${logDirectory}/${generalLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
- <!-- daily rollover -->
- <fileNamePattern>${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
- <maxFileSize>1GB</maxFileSize>
- <maxHistory>5</maxHistory>
- <totalSizeCap>5GB</totalSizeCap>
- </rollingPolicy>
- <encoder>
- <pattern>${applicationLoggerPattern}</pattern>
- </encoder>
- </appender>
-
- <appender name="asyncEELF" class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>256</queueSize>
- <includeCallerData>true</includeCallerData>
- <appender-ref ref="EELF" />
- </appender>
-
- <!-- EELF Security Appender. This appender is used to record security events
- to the security log file. Security events are separate from other loggers
- in EELF so that security log records can be captured and managed in a secure
- way separate from the other logs. This appender is set to never discard any
- events. -->
- <appender name="EELFSecurity"
- class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${logDirectory}/${securityLogName}.log</file>
- <rollingPolicy
- class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${logDirectory}/${securityLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <triggeringPolicy
- class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <encoder>
- <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n </pattern>
- </encoder>
- </appender>
-
- <appender name="asyncEELFSecurity" class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>256</queueSize>
- <discardingThreshold>0</discardingThreshold>
- <appender-ref ref="EELFSecurity" />
- </appender>
-
-
-
-
- <!-- EELF Audit Appender. This appender is used to record audit engine
- related logging events. The audit logger and appender are specializations
- of the EELF application root logger and appender. This can be used to segregate
- Policy engine events from other components, or it can be eliminated to record
- these events as part of the application root log. -->
-
- <appender name="EELFAudit"
- class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${logDirectory}/${auditLogName}.log</file>
- <rollingPolicy
- class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${logDirectory}/${auditLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <triggeringPolicy
- class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <encoder>
- <pattern>${auditLoggerPattern}</pattern>
- </encoder>
- </appender>
- <appender name="asyncEELFAudit" class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>256</queueSize>
- <appender-ref ref="EELFAudit" />
- </appender>
-
-<appender name="EELFMetrics"
- class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${logDirectory}/${metricsLogName}.log</file>
- <rollingPolicy
- class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${logDirectory}/${metricsLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <triggeringPolicy
- class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <encoder>
- <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} -
- %msg%n"</pattern> -->
- <pattern>${metricsLoggerPattern}</pattern>
- </encoder>
- </appender>
-
-
- <appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>256</queueSize>
- <appender-ref ref="EELFMetrics"/>
- </appender>
-
- <appender name="EELFError"
- class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${logDirectory}/${errorLogName}.log</file>
- <rollingPolicy
- class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${logDirectory}/${errorLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <triggeringPolicy
- class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <encoder>
- <pattern>${errorLoggerPattern}</pattern>
- </encoder>
- </appender>
-
- <appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>256</queueSize>
- <appender-ref ref="EELFError"/>
- </appender>
-
- <appender name="EELFDebug"
- class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${debugLogDirectory}/${debugLogName}.log</file>
- <rollingPolicy
- class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${debugLogDirectory}/${debugLogName}.%i.log.zip
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>9</maxIndex>
- </rollingPolicy>
- <triggeringPolicy
- class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <encoder>
- <pattern>${debugLoggerPattern}</pattern>
- </encoder>
- </appender>
-
- <appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>256</queueSize>
- <appender-ref ref="EELFDebug" />
- <includeCallerData>true</includeCallerData>
- </appender>
-
-
- <!-- ============================================================================ -->
- <!-- EELF loggers -->
- <!-- ============================================================================ -->
- <logger name="com.att.eelf" level="info" additivity="false">
- <appender-ref ref="asyncEELF" />
-
- </logger>
- <logger name="com.att.eelf.security" level="info" additivity="false">
- <appender-ref ref="asyncEELFSecurity" />
-
- </logger>
-
-
- <logger name="com.att.eelf.audit" level="info" additivity="false">
- <appender-ref ref="asyncEELFAudit" />
-
- </logger>
-
- <logger name="com.att.eelf.metrics" level="info" additivity="false">
- <appender-ref ref="asyncEELFMetrics" />
-
- </logger>
-
-
- <logger name="com.att.eelf.error" level="error" additivity="false">
- <appender-ref ref="asyncEELFError" />
-
- </logger>
-
- <logger name="com.att.eelf.debug" level="debug" additivity="false">
- <appender-ref ref="asyncEELFDebug" />
-
- </logger>
-
- <root level="INFO">
- <appender-ref ref="asyncEELF" />
- <!-- <appender-ref ref="STDOUT" /> -->
- </root>
-
- <!-- Conductor Specific additions to squash WARNING and INFO -->
- <logger name="com.datastax.driver.core.Cluster" level="ERROR"/>
- <logger name="org.onap.music.main.MusicCore" level="ERROR"/>
-
-</configuration>
diff --git a/src/main/resources/project.properties b/src/main/resources/project.properties
deleted file mode 100644
index 199afa33..00000000
--- a/src/main/resources/project.properties
+++ /dev/null
@@ -1,4 +0,0 @@
-version=${project.version}
-artifactId=${project.artifactId}
-music.properties=/opt/app/music/etc/music.properties
-