summaryrefslogtreecommitdiffstats
path: root/aai-resources/src/main/java/org/onap
diff options
context:
space:
mode:
authorKajur, Harish (vk250x) <vk250x@att.com>2020-02-29 22:17:05 -0500
committerjimmy <jf2512@att.com>2020-03-03 13:20:06 -0500
commit3a27813b663c34df52b2b1b50df7f0754dcfe134 (patch)
tree1f962778cd649286f70ae7ec8dbc5d868a668a7b /aai-resources/src/main/java/org/onap
parent50315fe106b88e0cd556b8b6fab1dbdd4c9856a4 (diff)
Update resources to use aai-common changes
Issue-ID: AAI-2750 Change-Id: I33ea2b3d7b4b706edc59c3d45c9957d05effd306 Signed-off-by: Kajur, Harish (vk250x) <vk250x@att.com>
Diffstat (limited to 'aai-resources/src/main/java/org/onap')
-rw-r--r--aai-resources/src/main/java/org/onap/aai/IncreaseNodesTool.java25
-rw-r--r--aai-resources/src/main/java/org/onap/aai/Profiles.java2
-rw-r--r--aai-resources/src/main/java/org/onap/aai/ResourcesApp.java110
-rw-r--r--aai-resources/src/main/java/org/onap/aai/TenantIsolation/DataImportTasks.java288
-rw-r--r--aai-resources/src/main/java/org/onap/aai/config/aaf/AafAuthorizationFilter.java68
-rw-r--r--aai-resources/src/main/java/org/onap/aai/config/aaf/AafFilter.java69
-rw-r--r--aai-resources/src/main/java/org/onap/aai/config/aaf/FilterPriority.java35
-rw-r--r--aai-resources/src/main/java/org/onap/aai/config/aaf/ResponseFormatter.java45
-rw-r--r--aai-resources/src/main/java/org/onap/aai/interceptors/AAIHeaderProperties.java4
-rw-r--r--aai-resources/src/main/java/org/onap/aai/interceptors/post/ResetLoggingContext.java100
-rw-r--r--aai-resources/src/main/java/org/onap/aai/interceptors/post/ResponseTransactionLogging.java6
-rw-r--r--aai-resources/src/main/java/org/onap/aai/interceptors/pre/HeaderValidation.java92
-rw-r--r--aai-resources/src/main/java/org/onap/aai/interceptors/pre/RequestTransactionLogging.java20
-rw-r--r--aai-resources/src/main/java/org/onap/aai/interceptors/pre/SetLoggingContext.java70
-rw-r--r--aai-resources/src/main/java/org/onap/aai/interceptors/pre/TwoWaySslAuthorization.java2
-rw-r--r--aai-resources/src/main/java/org/onap/aai/rest/BulkConsumer.java67
-rw-r--r--aai-resources/src/main/java/org/onap/aai/rest/LegacyMoxyConsumer.java159
-rw-r--r--aai-resources/src/main/java/org/onap/aai/rest/URLFromVertexIdConsumer.java38
-rw-r--r--aai-resources/src/main/java/org/onap/aai/rest/VertexIdConsumer.java42
-rw-r--r--aai-resources/src/main/java/org/onap/aai/rest/bulk/BulkSingleTransactionConsumer.java119
-rw-r--r--aai-resources/src/main/java/org/onap/aai/service/AuthorizationService.java8
-rw-r--r--aai-resources/src/main/java/org/onap/aai/web/JerseyConfiguration.java11
22 files changed, 621 insertions, 759 deletions
diff --git a/aai-resources/src/main/java/org/onap/aai/IncreaseNodesTool.java b/aai-resources/src/main/java/org/onap/aai/IncreaseNodesTool.java
index 23814bf..614d16f 100644
--- a/aai-resources/src/main/java/org/onap/aai/IncreaseNodesTool.java
+++ b/aai-resources/src/main/java/org/onap/aai/IncreaseNodesTool.java
@@ -24,17 +24,16 @@ import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
+import org.onap.aai.restclient.PropertyPasswordConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphTransaction;
-import org.onap.aai.config.PropertyPasswordConfiguration;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.dbmap.AAIGraph;
-import org.onap.aai.edges.EdgeIngestor;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
@@ -42,7 +41,6 @@ import org.onap.aai.introspection.LoaderFactory;
import org.onap.aai.introspection.ModelType;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.logging.ErrorLogHelper;
-import org.onap.aai.logging.LoggingContext;
import org.onap.aai.setup.SchemaVersions;
import org.onap.aai.util.AAISystemExitUtil;
import org.onap.aai.util.PositiveNumValidator;
@@ -65,7 +63,7 @@ public class IncreaseNodesTool {
protected TransactionalGraphEngine engine;
Vertex parentVtx;
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(IncreaseNodesTool.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(IncreaseNodesTool.class);
public IncreaseNodesTool(LoaderFactory loaderFactory, SchemaVersions schemaVersions){
this.loaderFactory = loaderFactory;
@@ -84,11 +82,14 @@ public class IncreaseNodesTool {
);
context.refresh();
} catch (Exception e) {
- AAIException aai = ResourcesApp.schemaServiceExceptionTranslator(e);
- LOGGER.error("Problems running the tool "+aai.getMessage());
- LoggingContext.statusCode(LoggingContext.StatusCode.ERROR);
- LoggingContext.responseCode(LoggingContext.DATA_ERROR);
- ErrorLogHelper.logError(aai.getCode(), e.getMessage() + ", resolve and retry");
+ AAIException aai = null;
+ if(e.getCause() instanceof AAIException){
+ aai = (AAIException)e.getCause();
+ } else {
+ aai = ResourcesApp.schemaServiceExceptionTranslator(e);
+ }
+ LOGGER.error("Problems starting the Increase Nodes Tool due to {}", aai.getMessage());
+ ErrorLogHelper.logException(aai);
throw aai;
}
@@ -141,7 +142,7 @@ public class IncreaseNodesTool {
GraphTraversalSource g = transaction.traversal();
for (long i = 1; i <= nodeCount; i++) {
String randomId = UUID.randomUUID().toString();
- Vertex v = g.addV().next();
+ Vertex v = g.addV(nodeType).next();
v.property("aai-node-type", nodeType);
v.property("source-of-truth", "IncreaseNodesTool");
diff --git a/aai-resources/src/main/java/org/onap/aai/Profiles.java b/aai-resources/src/main/java/org/onap/aai/Profiles.java
index ea65b9a..f35a4c9 100644
--- a/aai-resources/src/main/java/org/onap/aai/Profiles.java
+++ b/aai-resources/src/main/java/org/onap/aai/Profiles.java
@@ -25,7 +25,7 @@ public final class Profiles {
public static final String DME2 = "dme2";
public static final String ONE_WAY_SSL = "one-way-ssl";
- public static final String AAF_AUTHENTICATION = "aaf-auth";
+
public static final String TWO_WAY_SSL = "two-way-ssl";
private Profiles(){}
diff --git a/aai-resources/src/main/java/org/onap/aai/ResourcesApp.java b/aai-resources/src/main/java/org/onap/aai/ResourcesApp.java
index f653487..6377af8 100644
--- a/aai-resources/src/main/java/org/onap/aai/ResourcesApp.java
+++ b/aai-resources/src/main/java/org/onap/aai/ResourcesApp.java
@@ -19,23 +19,17 @@
*/
package org.onap.aai;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-
import org.apache.commons.lang3.exception.ExceptionUtils;
-import org.onap.aai.config.PropertyPasswordConfiguration;
+import org.onap.aai.aailog.logs.AaiDebugLog;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.dbmap.AAIGraph;
import org.onap.aai.exceptions.AAIException;
-
import org.onap.aai.logging.ErrorLogHelper;
-import org.onap.aai.logging.LoggingContext;
-import org.onap.aai.logging.LoggingContext.StatusCode;
+import org.onap.aai.nodes.NodeIngestor;
+import org.onap.aai.restclient.PropertyPasswordConfiguration;
import org.onap.aai.util.AAIConfig;
-import org.slf4j.MDC;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -45,36 +39,42 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerA
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
-import org.onap.aai.nodes.NodeIngestor;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
-@SpringBootApplication
+@SpringBootApplication(
+ exclude = {
+ DataSourceAutoConfiguration.class,
+ DataSourceTransactionManagerAutoConfiguration.class,
+ HibernateJpaAutoConfiguration.class
+ }
+)
// Component Scan provides a way to look for spring beans
// It only searches beans in the following packages
// Any method annotated with @Bean annotation or any class
// with @Component, @Configuration, @Service will be picked up
@ComponentScan(basePackages = {
- "org.onap.aai.config",
- "org.onap.aai.web",
- "org.onap.aai.setup",
- "org.onap.aai.tasks",
- "org.onap.aai.service",
- "org.onap.aai.rest"
-})
-@EnableAutoConfiguration(exclude = {
- DataSourceAutoConfiguration.class,
- DataSourceTransactionManagerAutoConfiguration.class,
- HibernateJpaAutoConfiguration.class
+ "org.onap.aai.config",
+ "org.onap.aai.web",
+ "org.onap.aai.setup",
+ "org.onap.aai.tasks",
+ "org.onap.aai.service",
+ "org.onap.aai.rest",
+ "org.onap.aai.aaf",
+ "org.onap.aai.TenantIsolation",
+ "org.onap.aai.aailog",
+ "org.onap.aai.prevalidation"
})
public class ResourcesApp {
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(ResourcesApp.class.getName());
+ private static final Logger logger = LoggerFactory.getLogger(ResourcesApp.class.getName());
private static final String APP_NAME = "aai-resources";
- private static Map<String,String> contextMap;
+ private static AaiDebugLog debugLog = new AaiDebugLog();
+ static {
+ debugLog.setupMDC();
+ }
@Autowired
private Environment env;
@@ -93,17 +93,6 @@ public class ResourcesApp {
private void init() throws AAIException {
System.setProperty("org.onap.aai.serverStarted", "false");
setDefaultProps();
-
- LoggingContext.save();
- LoggingContext.component("init");
- LoggingContext.partnerName("NA");
- LoggingContext.targetEntity(APP_NAME);
- LoggingContext.requestId(UUID.randomUUID().toString());
- LoggingContext.serviceName(APP_NAME);
- LoggingContext.targetServiceName("contextInitialized");
- LoggingContext.statusCode(StatusCode.COMPLETE);
-
- contextMap = MDC.getCopyOfContextMap();
logger.info("AAI Server initialization started...");
// Setting this property to allow for encoded slash (/) in the path parameter
@@ -116,7 +105,6 @@ public class ResourcesApp {
logger.warn("You have seriously misconfigured your application");
}
- LoggingContext.restoreIfPossible();
}
@PreDestroy
@@ -129,15 +117,6 @@ public class ResourcesApp {
setDefaultProps();
- LoggingContext.save();
- LoggingContext.component("init");
- LoggingContext.partnerName("NA");
- LoggingContext.targetEntity(APP_NAME);
- LoggingContext.requestId(UUID.randomUUID().toString());
- LoggingContext.serviceName(APP_NAME);
- LoggingContext.targetServiceName("contextInitialized");
- LoggingContext.statusCode(StatusCode.COMPLETE);
-
Environment env =null;
AAIConfig.init();
try {
@@ -148,21 +127,21 @@ public class ResourcesApp {
env = app.run(args).getEnvironment();
}
catch(Exception ex){
- AAIException aai = schemaServiceExceptionTranslator(ex);
- LoggingContext.statusCode(LoggingContext.StatusCode.ERROR);
- LoggingContext.responseCode(LoggingContext.DATA_ERROR);
- logger.error("Problems starting ResourcesApp "+aai.getMessage());
+ AAIException aai = null;
+ if(ex.getCause() instanceof AAIException){
+ aai = (AAIException)ex.getCause();
+ } else {
+ aai = schemaServiceExceptionTranslator(ex);
+ }
+ logger.error("Problems starting the ResourcesApp due to {}", aai.getMessage());
ErrorLogHelper.logException(aai);
- ErrorLogHelper.logError(aai.getCode(), ex.getMessage() + ", resolve and restart Resources");
- //ErrorLogHelper.logError(aai.getCode(), aai.getMessage() + aai.getCause().toString());
throw aai;
}
- MDC.setContextMap (contextMap);
logger.info(
- "Application '{}' is running on {}!" ,
- env.getProperty("spring.application.name"),
- env.getProperty("server.port")
+ "Application '{}' is running on {}!" ,
+ env.getProperty("spring.application.name"),
+ env.getProperty("server.port")
);
// The main reason this was moved from the constructor is due
@@ -173,12 +152,10 @@ public class ResourcesApp {
AAIGraph.getInstance();
logger.info("Resources MicroService Started");
- logger.error("Resources MicroService Started");
logger.debug("Resources MicroService Started");
System.out.println("Resources Microservice Started");
- LoggingContext.restoreIfPossible();
}
public static void setDefaultProps(){
@@ -206,17 +183,18 @@ public class ResourcesApp {
}
public static AAIException schemaServiceExceptionTranslator(Exception ex) {
AAIException aai = null;
- if(ExceptionUtils.getRootCause(ex).getMessage().contains("NodeIngestor")){
+ String message = ExceptionUtils.getRootCause(ex).getMessage();
+ if(message.contains("NodeIngestor")){
aai = new AAIException("AAI_3026","Error reading OXM from SchemaService - Investigate");
}
- else if(ExceptionUtils.getRootCause(ex).getMessage().contains("EdgeIngestor")){
+ else if(message.contains("EdgeIngestor")){
aai = new AAIException("AAI_3027","Error reading EdgeRules from SchemaService - Investigate");
}
- else if(ExceptionUtils.getRootCause(ex).getMessage().contains("Connection refused")){
+ else if(message.contains("Connection refused")){
aai = new AAIException("AAI_3025","Error connecting to SchemaService - Investigate");
}
else {
- aai = new AAIException("AAI_3025","Error connecting to SchemaService - Please Investigate");
+ aai = new AAIException("AAI_3025","Unable to determine what the error is, please check external.log");
}
return aai;
diff --git a/aai-resources/src/main/java/org/onap/aai/TenantIsolation/DataImportTasks.java b/aai-resources/src/main/java/org/onap/aai/TenantIsolation/DataImportTasks.java
new file mode 100644
index 0000000..917146f
--- /dev/null
+++ b/aai-resources/src/main/java/org/onap/aai/TenantIsolation/DataImportTasks.java
@@ -0,0 +1,288 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.aai.TenantIsolation;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileFilter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.Properties;
+import java.util.TreeMap;
+import java.util.UUID;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.logging.ErrorLogHelper;
+import org.onap.aai.util.AAIConfig;
+import org.onap.aai.util.AAIConstants;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import com.att.eelf.configuration.Configuration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.commons.io.comparator.LastModifiedFileComparator;
+import org.apache.commons.io.filefilter.DirectoryFileFilter;
+import org.apache.commons.io.filefilter.FileFileFilter;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.filefilter.RegexFileFilter;
+
+/**
+ * DataImportTasks
+ *
+ */
+@Component
+@PropertySource("file:${server.local.startpath}/etc/appprops/datatoolscrons.properties")
+public class DataImportTasks {
+
+ private static final Logger LOGGER;
+ private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
+
+ private static final List<String> EXTS = Arrays.asList("tar.gz", "tgz");
+
+ static {
+ Properties props = System.getProperties();
+ props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_LOGBACK_PROPS);
+ props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_BUNDLECONFIG);
+ LOGGER = LoggerFactory.getLogger(DataImportTasks.class);
+ }
+ /**
+ * Scheduled task to invoke importTask
+ */
+ @Scheduled(cron = "${dataimporttask.cron}" )
+ public void import1() {
+ try {
+ importTask();
+ }
+ catch (Exception e) {
+ }
+ }
+ /**
+ * The importTask method.
+ *
+ * @throws AAIException, Exception
+ */
+ public void importTask() throws AAIException, Exception {
+
+
+ if (AAIConfig.get("aai.dataimport.enable").equalsIgnoreCase("false")) {
+ LOGGER.info("Data Import is not enabled");
+ return;
+ }
+ // Check if the process was started via command line
+ if (isDataImportRunning()) {
+ LOGGER.info("There is a dataImport process already running");
+ return;
+ }
+
+ LOGGER.info("Started importTask: " + dateFormat.format(new Date()));
+
+ String inputLocation = AAIConstants.AAI_HOME_BUNDLECONFIG + AAIConfig.get("aai.dataimport.input.location");
+
+ // Check that the input location exist
+ File targetDirFile = new File(inputLocation);
+ if ( targetDirFile.exists() ) {
+ //Delete any existing payload file directories
+ deletePayload(targetDirFile);
+ }
+
+ File payloadFile = findExportedPayload();
+ if (payloadFile == null)
+ return; // already logged error in the findExportedPayload function
+
+ if ( unpackPayloadFile(payloadFile.getAbsolutePath())) {
+ String[] command = new String[2];
+ command[0] = AAIConstants.AAI_HOME + AAIConstants.AAI_FILESEP + "bin" + AAIConstants.AAI_FILESEP + "install" + AAIConstants.AAI_FILESEP + "addManualData.sh";
+ command[1] = "tenant_isolation";
+ runAddManualDataScript(command);
+ }
+
+ //clean up
+ payloadFile.delete();
+
+ }
+ /**
+ * The isDataImportRunning method, checks if the data import task was started separately via command line
+ * @return true if another process is running, false if not
+ */
+ private static boolean isDataImportRunning(){
+
+ Process process = null;
+
+ int count = 0;
+ try {
+ process = new ProcessBuilder().command("bash", "-c", "ps -ef | grep 'addManualData'").start();
+ InputStream is = process.getInputStream();
+ InputStreamReader isr = new InputStreamReader(is);
+ BufferedReader br = new BufferedReader(isr);
+
+ while (br.readLine() != null){
+ count++;
+ }
+
+ int exitVal = process.waitFor();
+ LOGGER.info("Check if dataImport is running returned: " + exitVal);
+ } catch (Exception e) {
+ ErrorLogHelper.logError("AAI_8002", "Exception while running the check to see if dataImport is running "+ e.getMessage());
+ LOGGER.info("Exception while running the check to see if dataImport is running "+ e.getMessage());
+ }
+
+ if(count > 0){
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * The findPayExportedPayload method tries to find the latest exported payload.
+ * Also deletes the old files if any or any other file in this directory
+ */
+ private static File findExportedPayload() throws AAIException {
+ String targetDir = AAIConstants.AAI_HOME_BUNDLECONFIG + AAIConfig.get("aai.dataimport.input.location");
+ File targetDirFile = new File(targetDir);
+ File payloadFile = null;
+
+ File[] allFilesArr = targetDirFile.listFiles((FileFilter) FileFileFilter.FILE);
+ if ( allFilesArr == null || allFilesArr.length == 0 ) {
+ ErrorLogHelper.logError("AAI_8001", "Unable to find payload file at " + targetDir);
+ LOGGER.info ("Unable to find payload at " + targetDir);
+ return null;
+ }
+ if ( allFilesArr.length > 1 ) {
+ Arrays.sort(allFilesArr, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
+ // get the latest payload file
+ boolean foundTheLatestPayload = false;
+ for (File f : allFilesArr) {
+ if (!foundTheLatestPayload && isTargzExtension(f.getAbsolutePath())) {
+ payloadFile = f;
+ foundTheLatestPayload = true;
+ }
+ else // delete all files except the latest payload file!
+ f.delete();
+ }
+ }
+ else {
+ if (isTargzExtension(allFilesArr[0].getAbsolutePath()))
+ payloadFile = allFilesArr[0];
+ }
+
+ return payloadFile;
+ }
+
+ /**
+ * The deletePayload method deletes all the payload files that it finds at targetDirectory
+ * @param targetDirFile the directory that contains payload files
+ * @throws AAIException
+ */
+ private static void deletePayload(File targetDirFile) throws AAIException {
+
+ File[] allFilesArr = targetDirFile.listFiles((FileFilter)DirectoryFileFilter.DIRECTORY);
+ if ( allFilesArr == null || allFilesArr.length == 0 ) {
+ LOGGER.info ("No payload files found at " + targetDirFile.getPath());
+ return;
+ }
+ for ( File f : allFilesArr ) {
+ try {
+ FileUtils.deleteDirectory(f);
+ }
+ catch (IOException e) {
+
+ LOGGER.info ("Unable to delete directory " + f.getAbsolutePath() + " " + e.getMessage());
+ }
+
+ }
+
+ }
+
+ /**
+ * The isDataImportRunning method, checks if the data import task was started separately via command line
+ * @return true if another process is running, false if not
+ */
+ private static boolean unpackPayloadFile(String payLoadFileName){
+
+ Process process = null;
+
+ try {
+ process = new ProcessBuilder().command("bash", "-c", "gzip –d < " + payLoadFileName + " | tar xf -").start();
+ int exitVal = process.waitFor();
+ LOGGER.info("gzip -d returned: " + exitVal);
+ } catch (Exception e) {
+ ErrorLogHelper.logError("AAI_8002", "Exception while running the unzip "+ e.getMessage());
+ LOGGER.info("Exception while running the unzip "+ e.getMessage());
+ return false;
+ }
+ /*
+ if (payLoadFileName.indexOf(".") > 0)
+ payLoadFileName = payLoadFileName.substring(0, payLoadFileName.lastIndexOf("."));
+
+ try {
+ process = new ProcessBuilder().command("bash", "-c", "tar xf " + payLoadFileName).start();
+ int exitVal = process.waitFor();
+ LOGGER.info("tar xf returned: " + exitVal);
+ } catch (Exception e) {
+ ErrorLogHelper.logError("AAI_8002", "Exception while running the tar xf "+ e.getMessage());
+ LOGGER.info("Exception while running the tar xf "+ e.getMessage());
+ return false;
+ }
+ */
+ return true;
+ }
+
+ private static boolean isTargzExtension(String fileName) {
+ boolean found = false;
+ for (String ext : EXTS) {
+ if (fileName.toLowerCase().endsWith("." + ext)) {
+ found = true;
+ }
+ }
+ return found;
+ }
+
+ /**
+ * The runAddManualDataScript method runs a shell script/command with a variable number of arguments
+ * @param script The script/command arguments
+ */
+ private static void runAddManualDataScript(String ...script ) {
+ Process process = null;
+ try {
+ process = new ProcessBuilder().command(script).start();
+ int exitVal = process.waitFor();
+ LOGGER.info("addManualData.sh returned: " + exitVal);
+ } catch (Exception e) {
+ ErrorLogHelper.logError("AAI_8002", "Exception while running addManualData.sh "+ e.getMessage());
+ LOGGER.info("Exception while running addManualData.sh" + e.getMessage());
+ }
+
+ }
+}
diff --git a/aai-resources/src/main/java/org/onap/aai/config/aaf/AafAuthorizationFilter.java b/aai-resources/src/main/java/org/onap/aai/config/aaf/AafAuthorizationFilter.java
deleted file mode 100644
index 653fc51..0000000
--- a/aai-resources/src/main/java/org/onap/aai/config/aaf/AafAuthorizationFilter.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.aai.config.aaf;
-
-import org.onap.aai.Profiles;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.boot.web.filter.OrderedRequestContextFilter;
-import org.springframework.context.annotation.Profile;
-import org.springframework.context.annotation.PropertySource;
-import org.springframework.stereotype.Component;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-
-import static org.onap.aai.config.aaf.ResponseFormatter.errorResponse;
-
-/**
- * AAF authorization filter
- */
-
-@Component
-@Profile(Profiles.AAF_AUTHENTICATION)
-@PropertySource("file:${server.local.startpath}/aaf/permissions.properties")
-public class AafAuthorizationFilter extends OrderedRequestContextFilter {
-
- @Value("${permission.type}")
- String type;
-
- @Value("${permission.instance}")
- String instance;
-
- public AafAuthorizationFilter() {
- this.setOrder(FilterPriority.AAF_AUTHORIZATION.getPriority());
- }
-
- @Override
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
- String permission = String.format("%s|%s|%s", type, instance, request.getMethod().toLowerCase());
- if(request.getRequestURI().matches("^.*/util/echo$")){
- filterChain.doFilter(request, response);
- }
- if(!request.isUserInRole(permission)){
- errorResponse(request, response);
- }else{
- filterChain.doFilter(request,response);
- }
- }
- }
diff --git a/aai-resources/src/main/java/org/onap/aai/config/aaf/AafFilter.java b/aai-resources/src/main/java/org/onap/aai/config/aaf/AafFilter.java
deleted file mode 100644
index f1aa7c1..0000000
--- a/aai-resources/src/main/java/org/onap/aai/config/aaf/AafFilter.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.aai.config.aaf;
-
-import org.onap.aaf.cadi.PropAccess;
-import org.onap.aaf.cadi.filter.CadiFilter;
-import org.onap.aai.Profiles;
-import org.onap.aai.ResourcesApp;
-import org.springframework.boot.web.filter.OrderedRequestContextFilter;
-import org.springframework.context.annotation.Profile;
-import org.springframework.stereotype.Component;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.util.Properties;
-
-import static org.onap.aai.config.aaf.ResponseFormatter.*;
-
-/**
- * AAF authentication filter
- */
-
-@Component
-@Profile(Profiles.AAF_AUTHENTICATION)
-public class AafFilter extends OrderedRequestContextFilter {
-
- private final CadiFilter cadiFilter;
-
- public AafFilter() throws IOException, ServletException {
- Properties cadiProperties = new Properties();
- cadiProperties.load(ResourcesApp.class.getClassLoader().getResourceAsStream("cadi.properties"));
- cadiFilter = new CadiFilter(new PropAccess(cadiProperties));
- this.setOrder(FilterPriority.AAF_AUTHENTICATION.getPriority());
- }
-
- @Override
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
- if(!request.getRequestURI().matches("^.*/util/echo$")){
- cadiFilter.doFilter(request, response, filterChain);
- if(response.getStatus() >=400 && response.getStatus() < 500){
- errorResponse(request, response);
- }
- } else {
- filterChain.doFilter(request, response);
- }
- }
-
-
-}
diff --git a/aai-resources/src/main/java/org/onap/aai/config/aaf/FilterPriority.java b/aai-resources/src/main/java/org/onap/aai/config/aaf/FilterPriority.java
deleted file mode 100644
index 910db69..0000000
--- a/aai-resources/src/main/java/org/onap/aai/config/aaf/FilterPriority.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.aai.config.aaf;
-
-import org.springframework.core.Ordered;
-
-public enum FilterPriority {
- AAF_AUTHENTICATION(Ordered.HIGHEST_PRECEDENCE),
- AAF_AUTHORIZATION(Ordered.HIGHEST_PRECEDENCE + 1); //higher number = lower priority
-
- private final int priority;
-
- FilterPriority(final int p) {
- priority = p;
- }
-
- public int getPriority() { return priority; }
-}
diff --git a/aai-resources/src/main/java/org/onap/aai/config/aaf/ResponseFormatter.java b/aai-resources/src/main/java/org/onap/aai/config/aaf/ResponseFormatter.java
deleted file mode 100644
index 9e09827..0000000
--- a/aai-resources/src/main/java/org/onap/aai/config/aaf/ResponseFormatter.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.aai.config.aaf;
-
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.logging.ErrorLogHelper;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.core.MediaType;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-
-class ResponseFormatter {
-
- private static final String ACCEPT_HEADER = "accept";
-
- static void errorResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
- String accept = request.getHeader(ACCEPT_HEADER) == null ? MediaType.APPLICATION_XML : request.getHeader(ACCEPT_HEADER);
- AAIException aaie = new AAIException("AAI_3300");
- response.setStatus(aaie.getErrorObject().getHTTPResponseCode().getStatusCode());
- response.getWriter().write(ErrorLogHelper.getRESTAPIErrorResponse(Collections.singletonList(MediaType.valueOf(accept)), aaie, new ArrayList<>()));
- response.getWriter().flush();
- response.getWriter().close();
- }
-
-}
diff --git a/aai-resources/src/main/java/org/onap/aai/interceptors/AAIHeaderProperties.java b/aai-resources/src/main/java/org/onap/aai/interceptors/AAIHeaderProperties.java
index 6801aee..8783ed2 100644
--- a/aai-resources/src/main/java/org/onap/aai/interceptors/AAIHeaderProperties.java
+++ b/aai-resources/src/main/java/org/onap/aai/interceptors/AAIHeaderProperties.java
@@ -30,7 +30,9 @@ public final class AAIHeaderProperties {
public static final String TRANSACTION_ID = "X-TransactionId";
public static final String FROM_APP_ID = "X-FromAppId";
-
+
+ public static final String SOURCE_OF_TRUTH = "X-SourceOfTruth";
+
public static final String AAI_TX_ID = "X-AAI-TXID";
public static final String AAI_REQUEST = "X-REQUEST";
diff --git a/aai-resources/src/main/java/org/onap/aai/interceptors/post/ResetLoggingContext.java b/aai-resources/src/main/java/org/onap/aai/interceptors/post/ResetLoggingContext.java
deleted file mode 100644
index 04f0391..0000000
--- a/aai-resources/src/main/java/org/onap/aai/interceptors/post/ResetLoggingContext.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.aai.interceptors.post;
-
-import java.io.IOException;
-
-import javax.annotation.Priority;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerResponseContext;
-import javax.ws.rs.container.ContainerResponseFilter;
-import javax.ws.rs.core.Response.Status;
-import javax.ws.rs.core.Response.StatusType;
-
-import org.onap.aai.interceptors.AAIContainerFilter;
-import org.onap.aai.logging.LoggingContext;
-import org.onap.aai.logging.LoggingContext.StatusCode;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-
-@Priority(AAIResponseFilterPriority.RESET_LOGGING_CONTEXT)
-public class ResetLoggingContext extends AAIContainerFilter implements ContainerResponseFilter {
-
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(ResetLoggingContext.class);
-
- @Autowired
- private HttpServletRequest httpServletRequest;
-
- @Override
- public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
- throws IOException {
-
- this.cleanLoggingContext(responseContext);
-
- }
-
- private void cleanLoggingContext(ContainerResponseContext responseContext) {
- //String url = httpServletRequest.getRequestURL().toString();
- boolean success = true;
- String uri = httpServletRequest.getRequestURI();
- String queryString = httpServletRequest.getQueryString();
-
- if(queryString != null && !queryString.isEmpty()){
- uri = uri + "?" + queryString;
- }
- // For now, we use the the HTTP status code,
- // This may change, once the requirements for response codes are defined
-
- int httpStatusCode = responseContext.getStatus();
- if ( httpStatusCode < 100 || httpStatusCode > 599 ) {
- httpStatusCode = Status.INTERNAL_SERVER_ERROR.getStatusCode();
- }
- LoggingContext.responseCode(Integer.toString(httpStatusCode));
-
- StatusType sType = responseContext.getStatusInfo();
- if ( sType != null ) {
- Status.Family sFamily = sType.getFamily();
- if ( ! ( Status.Family.SUCCESSFUL.equals(sFamily) ||
- ( Status.NOT_FOUND.equals(Status.fromStatusCode(httpStatusCode)) ) ) ) {
- success = false;
- }
- }
- else {
- if ( (httpStatusCode < 200 || httpStatusCode > 299) && ( ! ( Status.NOT_FOUND.equals(Status.fromStatusCode(httpStatusCode) ) ) ) ) {
- success = false;
- }
- }
- if (success) {
- LoggingContext.statusCode(StatusCode.COMPLETE);
- LOGGER.info(uri + " call succeeded");
- }
- else {
- LoggingContext.statusCode(StatusCode.ERROR);
- LOGGER.error(uri + " call failed with responseCode=" + httpStatusCode);
- }
- LoggingContext.clear();
-
-
- }
-
-}
diff --git a/aai-resources/src/main/java/org/onap/aai/interceptors/post/ResponseTransactionLogging.java b/aai-resources/src/main/java/org/onap/aai/interceptors/post/ResponseTransactionLogging.java
index 4a47658..bfc1636 100644
--- a/aai-resources/src/main/java/org/onap/aai/interceptors/post/ResponseTransactionLogging.java
+++ b/aai-resources/src/main/java/org/onap/aai/interceptors/post/ResponseTransactionLogging.java
@@ -19,8 +19,8 @@
*/
package org.onap.aai.interceptors.post;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import com.google.gson.JsonObject;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.interceptors.AAIContainerFilter;
@@ -42,7 +42,7 @@ import java.util.Optional;
@Priority(AAIResponseFilterPriority.RESPONSE_TRANS_LOGGING)
public class ResponseTransactionLogging extends AAIContainerFilter implements ContainerResponseFilter {
- private static final EELFLogger TRANSACTION_LOGGER = EELFManager.getInstance().getLogger(ResponseTransactionLogging.class);
+ private static final Logger TRANSACTION_LOGGER = LoggerFactory.getLogger(ResponseTransactionLogging.class);
@Autowired
private HttpServletResponse httpServletResponse;
diff --git a/aai-resources/src/main/java/org/onap/aai/interceptors/pre/HeaderValidation.java b/aai-resources/src/main/java/org/onap/aai/interceptors/pre/HeaderValidation.java
index dfc4376..8113fa7 100644
--- a/aai-resources/src/main/java/org/onap/aai/interceptors/pre/HeaderValidation.java
+++ b/aai-resources/src/main/java/org/onap/aai/interceptors/pre/HeaderValidation.java
@@ -36,6 +36,10 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.interceptors.AAIContainerFilter;
import org.onap.aai.interceptors.AAIHeaderProperties;
import org.onap.aai.logging.ErrorLogHelper;
+import org.onap.logging.filter.base.Constants;
+import org.onap.logging.filter.base.ONAPComponents;
+import org.onap.logging.filter.base.SimpleMap;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
@PreMatching
@Priority(AAIRequestFilterPriority.HEADER_VALIDATION)
@@ -45,36 +49,28 @@ public class HeaderValidation extends AAIContainerFilter implements ContainerReq
public void filter(ContainerRequestContext requestContext) throws IOException {
Optional<Response> oResp;
-
- String transId = requestContext.getHeaderString(AAIHeaderProperties.TRANSACTION_ID);
- String fromAppId = requestContext.getHeaderString(AAIHeaderProperties.FROM_APP_ID);
-
List<MediaType> acceptHeaderValues = requestContext.getAcceptableMediaTypes();
+ String fromAppId = getPartnerName(requestContext);
oResp = this.validateHeaderValuePresence(fromAppId, "AAI_4009", acceptHeaderValues);
if (oResp.isPresent()) {
requestContext.abortWith(oResp.get());
return;
}
+
+ String transId = getRequestId(requestContext);
oResp = this.validateHeaderValuePresence(transId, "AAI_4010", acceptHeaderValues);
if (oResp.isPresent()) {
requestContext.abortWith(oResp.get());
return;
}
-
- if (!this.isValidUUID(transId)) {
- transId = UUID.randomUUID().toString();
- requestContext.getHeaders().get(AAIHeaderProperties.TRANSACTION_ID).clear();
- requestContext.getHeaders().add(AAIHeaderProperties.TRANSACTION_ID, transId);
- }
-
}
private Optional<Response> validateHeaderValuePresence(String value, String errorCode,
List<MediaType> acceptHeaderValues) {
Response response = null;
AAIException aaie;
- if (value == null) {
+ if (value == null || value.isEmpty()) {
aaie = new AAIException(errorCode);
return Optional.of(Response.status(aaie.getErrorObject().getHTTPResponseCode())
.entity(ErrorLogHelper.getRESTAPIErrorResponse(acceptHeaderValues, aaie, new ArrayList<>()))
@@ -83,5 +79,77 @@ public class HeaderValidation extends AAIContainerFilter implements ContainerReq
return Optional.ofNullable(response);
}
+ public String getRequestId(ContainerRequestContext requestContext) {
+ String requestId = requestContext.getHeaderString(ONAPLogConstants.Headers.REQUEST_ID);
+ if (requestId == null || requestId.isEmpty()) {
+ requestId = requestContext.getHeaderString(Constants.HttpHeaders.HEADER_REQUEST_ID);
+ if (requestId == null || requestId.isEmpty()) {
+ requestId = requestContext.getHeaderString(Constants.HttpHeaders.TRANSACTION_ID);
+ if (requestId == null || requestId.isEmpty()) {
+ requestId = requestContext.getHeaderString(Constants.HttpHeaders.ECOMP_REQUEST_ID);
+ if (requestId == null || requestId.isEmpty()) {
+ return requestId;
+ }
+ }
+ }
+ }
+ if (requestContext.getHeaders().get(ONAPLogConstants.Headers.REQUEST_ID) != null) {
+ requestContext.getHeaders().get(ONAPLogConstants.Headers.REQUEST_ID).clear();
+ }
+ if (requestContext.getHeaders().get(Constants.HttpHeaders.TRANSACTION_ID) != null) {
+ requestContext.getHeaders().get(Constants.HttpHeaders.TRANSACTION_ID).clear();
+ }
+ if (requestContext.getHeaders().get(Constants.HttpHeaders.HEADER_REQUEST_ID) != null) {
+ requestContext.getHeaders().get(Constants.HttpHeaders.HEADER_REQUEST_ID).clear();
+ }
+ if (requestContext.getHeaders().get(Constants.HttpHeaders.ECOMP_REQUEST_ID) != null) {
+ requestContext.getHeaders().get(Constants.HttpHeaders.ECOMP_REQUEST_ID).clear();
+ }
+ requestContext.getHeaders().add(Constants.HttpHeaders.TRANSACTION_ID, requestId);
+ return requestId;
+ }
+
+ public String getPartnerName(ContainerRequestContext requestContext) {
+
+ // CDM header overrides everything else for source of truth
+ String sourceOfTruth = requestContext.getHeaderString(AAIHeaderProperties.SOURCE_OF_TRUTH);
+ String partnerName = requestContext.getHeaderString(ONAPLogConstants.Headers.PARTNER_NAME);
+ if ( sourceOfTruth == null || sourceOfTruth.isEmpty()) {
+
+ if (partnerName != null && !(partnerName.isEmpty())) {
+ String components[] = partnerName.split("\\.");
+ if (components.length > 1) {
+ if (!(ONAPComponents.AAI.toString().equalsIgnoreCase(components[0]))) {
+ sourceOfTruth = components[0];
+ } else {
+ // request is coming internally from AAI, check X-FromAppId
+ partnerName = null;
+ }
+ }
+ }
+ if (sourceOfTruth == null || sourceOfTruth.isEmpty()) {
+ if (partnerName == null || (partnerName.isEmpty())) {
+ partnerName = requestContext.getHeaderString(AAIHeaderProperties.FROM_APP_ID);
+ if (partnerName == null || (partnerName.isEmpty())) {
+ return partnerName;
+ }
+ }
+ }
+ }
+ if (requestContext.getHeaders().get(ONAPLogConstants.Headers.PARTNER_NAME) != null) {
+ requestContext.getHeaders().get(ONAPLogConstants.Headers.PARTNER_NAME).clear();
+ }
+ if (requestContext.getHeaders().get(AAIHeaderProperties.FROM_APP_ID) != null) {
+ requestContext.getHeaders().get(AAIHeaderProperties.FROM_APP_ID).clear();
+ }
+ if ((sourceOfTruth != null) && !(sourceOfTruth.isEmpty())) {
+ requestContext.getHeaders().add(AAIHeaderProperties.FROM_APP_ID, sourceOfTruth);
+ partnerName = sourceOfTruth;
+ }
+ else {
+ requestContext.getHeaders().add(AAIHeaderProperties.FROM_APP_ID, partnerName);
+ }
+ return partnerName;
+ }
}
diff --git a/aai-resources/src/main/java/org/onap/aai/interceptors/pre/RequestTransactionLogging.java b/aai-resources/src/main/java/org/onap/aai/interceptors/pre/RequestTransactionLogging.java
index f9976c2..54f2695 100644
--- a/aai-resources/src/main/java/org/onap/aai/interceptors/pre/RequestTransactionLogging.java
+++ b/aai-resources/src/main/java/org/onap/aai/interceptors/pre/RequestTransactionLogging.java
@@ -33,6 +33,8 @@ import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.UriInfo;
import org.glassfish.jersey.message.internal.ReaderWriter;
import org.glassfish.jersey.server.ContainerException;
@@ -60,6 +62,8 @@ public class RequestTransactionLogging extends AAIContainerFilter implements Con
private static final String CONTENT_TYPE = "Content-Type";
private static final String ACCEPT = "Accept";
private static final String TEXT_PLAIN = "text/plain";
+ private static final String WILDCARD = "*/*";
+ private static final String APPLICATION_JSON = "application/json";
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
@@ -85,8 +89,20 @@ public class RequestTransactionLogging extends AAIContainerFilter implements Con
requestContext.getHeaders().putSingle(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
}
- if(StringUtils.isEmpty(acceptType) || acceptType.contains(TEXT_PLAIN)){
- requestContext.getHeaders().putSingle(ACCEPT, DEFAULT_RESPONSE_TYPE);
+ if(WILDCARD.equals(acceptType) || StringUtils.isEmpty(acceptType) || acceptType.contains(TEXT_PLAIN)){
+ UriInfo uriInfo = requestContext.getUriInfo();
+ if(uriInfo != null){
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if(queryParameters != null && queryParameters.containsKey("format")){
+ // Add application/json as the default header if request contains query parameter format
+ // Since clients are assuming the default response to be application json for when format is specified
+ requestContext.getHeaders().putSingle(ACCEPT, APPLICATION_JSON);
+ } else {
+ requestContext.getHeaders().putSingle(ACCEPT, DEFAULT_RESPONSE_TYPE);
+ }
+ } else {
+ requestContext.getHeaders().putSingle(ACCEPT, DEFAULT_RESPONSE_TYPE);
+ }
}
}
diff --git a/aai-resources/src/main/java/org/onap/aai/interceptors/pre/SetLoggingContext.java b/aai-resources/src/main/java/org/onap/aai/interceptors/pre/SetLoggingContext.java
deleted file mode 100644
index 368d071..0000000
--- a/aai-resources/src/main/java/org/onap/aai/interceptors/pre/SetLoggingContext.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.aai.interceptors.pre;
-
-import java.io.IOException;
-
-import javax.annotation.Priority;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerRequestFilter;
-import javax.ws.rs.container.PreMatching;
-
-import org.onap.aai.interceptors.AAIContainerFilter;
-import org.onap.aai.interceptors.AAIHeaderProperties;
-import org.onap.aai.logging.LoggingContext;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.env.Environment;
-
-@PreMatching
-@Priority(AAIRequestFilterPriority.SET_LOGGING_CONTEXT)
-public class SetLoggingContext extends AAIContainerFilter implements ContainerRequestFilter {
-
- @Autowired
- private Environment environment;
-
- @Autowired
- private HttpServletRequest httpServletRequest;
-
- @Override
- public void filter(ContainerRequestContext requestContext) throws IOException {
-
- String uri = httpServletRequest.getRequestURI();
- String queryString = httpServletRequest.getQueryString();
-
- if(queryString != null && !queryString.isEmpty()){
- uri = uri + "?" + queryString;
- }
-
- String httpMethod = requestContext.getMethod();
- String transId = requestContext.getHeaderString(AAIHeaderProperties.TRANSACTION_ID);
- String fromAppId = requestContext.getHeaderString(AAIHeaderProperties.FROM_APP_ID);
-
- LoggingContext.init();
- LoggingContext.requestId(transId);
- LoggingContext.partnerName(fromAppId);
- LoggingContext.targetEntity(environment.getProperty("spring.application.name"));
- LoggingContext.component(fromAppId);
- LoggingContext.serviceName(httpMethod + " " + uri);
- LoggingContext.targetServiceName(httpMethod + " " + uri);
- LoggingContext.statusCode(LoggingContext.StatusCode.COMPLETE);
- }
-
-}
diff --git a/aai-resources/src/main/java/org/onap/aai/interceptors/pre/TwoWaySslAuthorization.java b/aai-resources/src/main/java/org/onap/aai/interceptors/pre/TwoWaySslAuthorization.java
index d4e8c4f..6c1c9f8 100644
--- a/aai-resources/src/main/java/org/onap/aai/interceptors/pre/TwoWaySslAuthorization.java
+++ b/aai-resources/src/main/java/org/onap/aai/interceptors/pre/TwoWaySslAuthorization.java
@@ -33,7 +33,7 @@ import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-import org.onap.aai.auth.AAIAuthCore;
+import org.onap.aai.aaf.auth.AAIAuthCore;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.interceptors.AAIContainerFilter;
import org.onap.aai.interceptors.AAIHeaderProperties;
diff --git a/aai-resources/src/main/java/org/onap/aai/rest/BulkConsumer.java b/aai-resources/src/main/java/org/onap/aai/rest/BulkConsumer.java
index 8033278..3f595d1 100644
--- a/aai-resources/src/main/java/org/onap/aai/rest/BulkConsumer.java
+++ b/aai-resources/src/main/java/org/onap/aai/rest/BulkConsumer.java
@@ -19,40 +19,15 @@
*/
package org.onap.aai.rest;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.PUT;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-import javax.ws.rs.core.UriBuilder;
-import javax.ws.rs.core.UriInfo;
-
+import com.google.gson.*;
import org.javatuples.Pair;
import org.onap.aai.config.SpringContextAware;
-import org.onap.aai.dbmap.DBConnectionType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.ModelType;
-import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.introspection.exceptions.AAIUnmarshallingException;
import org.onap.aai.logging.ErrorObjectNotFoundException;
-import org.onap.aai.logging.LoggingContext;
import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.rest.bulk.BulkOperation;
import org.onap.aai.rest.bulk.BulkOperationResponse;
@@ -63,18 +38,24 @@ import org.onap.aai.restcore.HttpMethod;
import org.onap.aai.restcore.RESTAPI;
import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.AAIConstants;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonSyntaxException;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.PUT;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.*;
+import javax.ws.rs.core.Response.Status;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
/**
* The Class BulkAddConsumer.
@@ -120,26 +101,11 @@ public abstract class BulkConsumer extends RESTAPI {
String transId = headers.getRequestHeaders().getFirst("X-TransactionId");
String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
- String realTime = headers.getRequestHeaders().getFirst("Real-Time");
String outputMediaType = getMediaType(headers.getAcceptableMediaTypes());
SchemaVersion version = new SchemaVersion(versionParam);
Response response = null;
try {
- DBConnectionType type = null;
- if(AAIConfig.get("aai.use.realtime", "true").equals("true")){
- type = DBConnectionType.REALTIME;
- } else {
- type = this.determineConnectionType(sourceOfTruth, realTime);
- }
-
- String serviceName = req.getMethod() + " " + req.getRequestURI().toString();
- LoggingContext.requestId(transId);
- LoggingContext.partnerName(sourceOfTruth);
- LoggingContext.serviceName(serviceName);
- LoggingContext.targetEntity(TARGET_ENTITY);
- LoggingContext.targetServiceName(serviceName);
-
/* A Response will be generated for each object in each transaction.
* To keep track of what came from where to give organized feedback to the client,
@@ -152,7 +118,7 @@ public abstract class BulkConsumer extends RESTAPI {
for (int i = 0; i < transactions.size(); i++){
HttpEntry resourceHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
- resourceHttpEntry.setHttpEntryProperties(version, type);
+ resourceHttpEntry.setHttpEntryProperties(version);
Loader loader = resourceHttpEntry.getLoader();
TransactionalGraphEngine dbEngine = resourceHttpEntry.getDbEngine();
URI thisUri = null;
@@ -515,8 +481,7 @@ public abstract class BulkConsumer extends RESTAPI {
* @param headers the headers
* @param info the info
* @param templateAction the template action
- * @param logline Generates a Response based on the given exception and adds it to the collection of responses for this request.
- * @throws ErrorObjectNotFoundException
+ * @throws ErrorObjectNotFoundException
*/
private void addExceptionCaseFailureResponse(List<List<BulkOperationResponse>> allResponses, Exception e, int index, URI thisUri, HttpHeaders headers, UriInfo info, HttpMethod templateAction) {
AAIException ex = null;
diff --git a/aai-resources/src/main/java/org/onap/aai/rest/LegacyMoxyConsumer.java b/aai-resources/src/main/java/org/onap/aai/rest/LegacyMoxyConsumer.java
index 0b544f4..e6dcc77 100644
--- a/aai-resources/src/main/java/org/onap/aai/rest/LegacyMoxyConsumer.java
+++ b/aai-resources/src/main/java/org/onap/aai/rest/LegacyMoxyConsumer.java
@@ -19,46 +19,13 @@
*/
package org.onap.aai.rest;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.Encoded;
-import javax.ws.rs.GET;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriBuilder;
-import javax.ws.rs.core.UriInfo;
-
import io.swagger.jaxrs.PATCH;
import org.javatuples.Pair;
-import org.json.JSONArray;
-import org.json.JSONObject;
import org.onap.aai.concurrent.AaiCallable;
import org.onap.aai.config.SpringContextAware;
-import org.onap.aai.dbmap.DBConnectionType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
-import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.rest.db.DBRequest;
import org.onap.aai.rest.db.HttpEntry;
@@ -67,13 +34,19 @@ import org.onap.aai.rest.util.ValidateEncoding;
import org.onap.aai.restcore.HttpMethod;
import org.onap.aai.restcore.RESTAPI;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import org.onap.aai.util.AAIConfig;
+import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.util.AAIConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.google.common.base.Joiner;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.*;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.*;
+import java.util.stream.Collectors;
/**
* The Class LegacyMoxyConsumer.
@@ -82,18 +55,7 @@ import com.google.common.base.Joiner;
@Path("{version: v[1-9][0-9]*|latest}")
public class LegacyMoxyConsumer extends RESTAPI {
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(LegacyMoxyConsumer.class.getName());
-
-// private HttpEntry traversalUriHttpEntry;
-
-// @Autowired
-// public LegacyMoxyConsumer(HttpEntry traversalUriHttpEntry){
-// this.traversalUriHttpEntry = traversalUriHttpEntry;
-// }
-
- public LegacyMoxyConsumer(){
-
- }
+ private static final Logger logger = LoggerFactory.getLogger(LegacyMoxyConsumer.class.getName());
/**
*
@@ -133,24 +95,18 @@ public class LegacyMoxyConsumer extends RESTAPI {
String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
String transId = headers.getRequestHeaders().getFirst("X-TransactionId");
- String realTime = headers.getRequestHeaders().getFirst("Real-Time");
MediaType inputMediaType = headers.getMediaType();
- Response response = null;
- Loader loader = null;
+ Response response;
+ Loader loader;
TransactionalGraphEngine dbEngine = null;
boolean success = true;
try {
validateRequest(info);
SchemaVersion version = new SchemaVersion(versionParam);
- DBConnectionType type = null;
- if(AAIConfig.get("aai.use.realtime", "true").equals("true")){
- type = DBConnectionType.REALTIME;
- } else {
- type = this.determineConnectionType(sourceOfTruth, realTime);
- }
+
HttpEntry traversalUriHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
- traversalUriHttpEntry.setHttpEntryProperties(version, type);
+ traversalUriHttpEntry.setHttpEntryProperties(version);
loader = traversalUriHttpEntry.getLoader();
dbEngine = traversalUriHttpEntry.getDbEngine();
@@ -262,22 +218,16 @@ public class LegacyMoxyConsumer extends RESTAPI {
public Response getLegacy(String content, String versionParam, String uri, String depthParam, String cleanUp, HttpHeaders headers, UriInfo info, HttpServletRequest req, Set<String> removeQueryParams, String resultIndex, String resultSize) {
String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
String transId = headers.getRequestHeaders().getFirst("X-TransactionId");
- String realTime = headers.getRequestHeaders().getFirst("Real-Time");
- Response response = null;
+ Response response;
TransactionalGraphEngine dbEngine = null;
- Loader loader = null;
+ Loader loader;
try {
validateRequest(info);
SchemaVersion version = new SchemaVersion(versionParam);
- DBConnectionType type = null;
- if(AAIConfig.get("aai.use.realtime", "true").equals("true")){
- type = DBConnectionType.REALTIME;
- } else {
- type = this.determineConnectionType(sourceOfTruth, realTime);
- }
+
final HttpEntry traversalUriHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
- traversalUriHttpEntry.setHttpEntryProperties(version, type);
+ traversalUriHttpEntry.setHttpEntryProperties(version);
dbEngine = traversalUriHttpEntry.getDbEngine();
loader = traversalUriHttpEntry.getLoader();
MultivaluedMap<String, String> params = info.getQueryParameters();
@@ -301,7 +251,7 @@ public class LegacyMoxyConsumer extends RESTAPI {
new DBRequest.Builder(HttpMethod.GET, uriObject, uriQuery, obj, headers, info, transId).build();
List<DBRequest> requests = new ArrayList<>();
requests.add(request);
- if (resultIndex != null && resultIndex != "-1" && resultSize != null && resultSize != "-1") {
+ if (resultIndex != null && !"-1".equals(resultIndex) && resultSize != null && !"-1".equals(resultSize)) {
traversalUriHttpEntry.setPaginationIndex(Integer.parseInt(resultIndex));
traversalUriHttpEntry.setPaginationBucket(Integer.parseInt(resultSize));
}
@@ -330,11 +280,11 @@ public class LegacyMoxyConsumer extends RESTAPI {
private MultivaluedMap<String, String> removeNonFilterableParams(MultivaluedMap<String, String> params) {
- String[] toRemove = { "depth", "cleanup", "nodes-only", "format", "resultIndex", "resultSize"};
+ String[] toRemove = { "depth", "cleanup", "nodes-only", "format", "resultIndex", "resultSize", "skip-related-to"};
Set<String> toRemoveSet = Arrays.stream(toRemove).collect(Collectors.toSet());
MultivaluedMap<String, String> cleanedParams = new MultivaluedHashMap<>();
- params.keySet().stream().forEach(k -> {
+ params.keySet().forEach(k -> {
if (!toRemoveSet.contains(k)) {
cleanedParams.addAll(k, params.get(k));
}
@@ -362,11 +312,9 @@ public class LegacyMoxyConsumer extends RESTAPI {
String outputMediaType = getMediaType(headers.getAcceptableMediaTypes());
String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
String transId = headers.getRequestHeaders().getFirst("X-TransactionId");
- String realTime = headers.getRequestHeaders().getFirst("Real-Time");
TransactionalGraphEngine dbEngine = null;
- Response response = Response.status(404)
- .type(outputMediaType).build();
+ Response response;
boolean success = true;
@@ -374,14 +322,9 @@ public class LegacyMoxyConsumer extends RESTAPI {
validateRequest(info);
SchemaVersion version = new SchemaVersion(versionParam);
- DBConnectionType type = null;
- if(AAIConfig.get("aai.use.realtime", "true").equals("true")){
- type = DBConnectionType.REALTIME;
- } else {
- type = this.determineConnectionType(sourceOfTruth, realTime);
- }
+
HttpEntry traversalUriHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
- traversalUriHttpEntry.setHttpEntryProperties(version, type);
+ traversalUriHttpEntry.setHttpEntryProperties(version);
dbEngine = traversalUriHttpEntry.getDbEngine();
Loader loader = traversalUriHttpEntry.getLoader();
@@ -437,30 +380,20 @@ public class LegacyMoxyConsumer extends RESTAPI {
public Response deleteRelationship (String content, @PathParam("version")String versionParam, @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, @Context UriInfo info, @Context HttpServletRequest req) {
MediaType inputMediaType = headers.getMediaType();
-
- String outputMediaType = getMediaType(headers.getAcceptableMediaTypes());
String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
String transId = headers.getRequestHeaders().getFirst("X-TransactionId");
- String realTime = headers.getRequestHeaders().getFirst("Real-Time");
-
- Loader loader = null;
+ Loader loader;
TransactionalGraphEngine dbEngine = null;
- Response response = Response.status(404)
- .type(outputMediaType).build();
+ Response response;
boolean success = true;
try {
this.validateRequest(info);
SchemaVersion version = new SchemaVersion(versionParam);
- DBConnectionType type = null;
- if(AAIConfig.get("aai.use.realtime", "true").equals("true")){
- type = DBConnectionType.REALTIME;
- } else {
- type = this.determineConnectionType(sourceOfTruth, realTime);
- }
+
HttpEntry traversalUriHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
- traversalUriHttpEntry.setHttpEntryProperties(version, type);
+ traversalUriHttpEntry.setHttpEntryProperties(version);
loader = traversalUriHttpEntry.getLoader();
dbEngine = traversalUriHttpEntry.getDbEngine();
@@ -533,7 +466,6 @@ public class LegacyMoxyConsumer extends RESTAPI {
public Response getRelationshipList(String versionParam, String uri, String cleanUp, HttpHeaders headers, UriInfo info, String resultIndex, String resultSize) {
String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
String transId = headers.getRequestHeaders().getFirst("X-TransactionId");
- String realTime = headers.getRequestHeaders().getFirst("Real-Time");
Response response = null;
TransactionalGraphEngine dbEngine = null;
Loader loader = null;
@@ -541,14 +473,9 @@ public class LegacyMoxyConsumer extends RESTAPI {
try {
validateRequest(info);
SchemaVersion version = new SchemaVersion(versionParam);
- DBConnectionType type = null;
- if(AAIConfig.get("aai.use.realtime", "true").equals("true")){
- type = DBConnectionType.REALTIME;
- } else {
- type = this.determineConnectionType(sourceOfTruth, realTime);
- }
+
final HttpEntry traversalUriHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
- traversalUriHttpEntry.setHttpEntryProperties(version, type);
+ traversalUriHttpEntry.setHttpEntryProperties(version);
dbEngine = traversalUriHttpEntry.getDbEngine();
loader = traversalUriHttpEntry.getLoader();
MultivaluedMap<String, String> params = info.getQueryParameters();
@@ -572,7 +499,7 @@ public class LegacyMoxyConsumer extends RESTAPI {
new DBRequest.Builder(HttpMethod.GET_RELATIONSHIP, uriObject, uriQuery, obj, headers, info, transId).build();
List<DBRequest> requests = new ArrayList<>();
requests.add(request);
- if (resultIndex != null && resultIndex != "-1" && resultSize != null && resultSize != "-1") {
+ if (resultIndex != null && !"-1".equals(resultIndex) && resultSize != null && !"-1".equals(resultSize)) {
traversalUriHttpEntry.setPaginationIndex(Integer.parseInt(resultIndex));
traversalUriHttpEntry.setPaginationBucket(Integer.parseInt(resultSize));
}
@@ -627,8 +554,8 @@ public class LegacyMoxyConsumer extends RESTAPI {
parmList.add(key + "=" + value);
}
}
- String queryParams = Joiner.on("&").join(parmList);
- if (map.keySet().size() > 0) {
+ String queryParams = String.join("&", parmList);
+ if (!map.isEmpty()) {
path += params + queryParams;
}
@@ -650,27 +577,21 @@ public class LegacyMoxyConsumer extends RESTAPI {
*/
private Response handleWrites(MediaType mediaType, HttpMethod method, String content, String versionParam, String uri, HttpHeaders headers, UriInfo info) {
- Response response = null;
+ Response response;
TransactionalGraphEngine dbEngine = null;
- Loader loader = null;
- SchemaVersion version = null;
+ Loader loader;
+ SchemaVersion version;
String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
String transId = headers.getRequestHeaders().getFirst("X-TransactionId");
- String realTime = headers.getRequestHeaders().getFirst("Real-Time");
- Boolean success = true;
+ boolean success = true;
try {
validateRequest(info);
version = new SchemaVersion(versionParam);
- DBConnectionType type = null;
- if(AAIConfig.get("aai.use.realtime", "true").equals("true")){
- type = DBConnectionType.REALTIME;
- } else {
- type = this.determineConnectionType(sourceOfTruth, realTime);
- }
+
HttpEntry traversalUriHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
- traversalUriHttpEntry.setHttpEntryProperties(version, type);
+ traversalUriHttpEntry.setHttpEntryProperties(version);
loader = traversalUriHttpEntry.getLoader();
dbEngine = traversalUriHttpEntry.getDbEngine();
URI uriObject = UriBuilder.fromPath(uri).build();
diff --git a/aai-resources/src/main/java/org/onap/aai/rest/URLFromVertexIdConsumer.java b/aai-resources/src/main/java/org/onap/aai/rest/URLFromVertexIdConsumer.java
index b9e5aa8..041952b 100644
--- a/aai-resources/src/main/java/org/onap/aai/rest/URLFromVertexIdConsumer.java
+++ b/aai-resources/src/main/java/org/onap/aai/rest/URLFromVertexIdConsumer.java
@@ -19,43 +19,35 @@
*/
package org.onap.aai.rest;
-import java.net.URI;
-import java.util.Iterator;
-
-import javax.servlet.http.HttpServletRequest;
-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.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-import javax.ws.rs.core.UriInfo;
-
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.config.SpringContextAware;
-import org.onap.aai.dbmap.DBConnectionType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.ModelType;
-import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.rest.db.HttpEntry;
import org.onap.aai.restcore.HttpMethod;
import org.onap.aai.restcore.RESTAPI;
import org.onap.aai.serialization.db.DBSerializer;
-import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.util.AAIConfig;
+import javax.servlet.http.HttpServletRequest;
+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.*;
+import javax.ws.rs.core.Response.Status;
+import java.net.URI;
+import java.util.Iterator;
+
/**
* The Class URLFromVertexIdConsumer.
*/
@Path("{version: v[1-9][0-9]*|latest}/generateurl")
public class URLFromVertexIdConsumer extends RESTAPI {
private ModelType introspectorFactoryType = ModelType.MOXY;
- private QueryStyle queryStyle = QueryStyle.TRAVERSAL_URI;
-
+
private final String ID_ENDPOINT = "/id/{vertexid: \\d+}";
/**
@@ -75,16 +67,14 @@ public class URLFromVertexIdConsumer extends RESTAPI {
public Response generateUrlFromVertexId(String content, @PathParam("version")String versionParam, @PathParam("vertexid")long vertexid, @Context HttpHeaders headers, @Context UriInfo info, @Context HttpServletRequest req) {
String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
- String realTime = headers.getRequestHeaders().getFirst("Real-Time");
SchemaVersion version = new SchemaVersion(versionParam);
StringBuilder result = new StringBuilder();
- Response response = null;
+ Response response;
TransactionalGraphEngine dbEngine = null;
try {
- DBConnectionType type = this.determineConnectionType(sourceOfTruth, realTime);
HttpEntry resourceHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
- resourceHttpEntry.setHttpEntryProperties(version, type);
+ resourceHttpEntry.setHttpEntryProperties(version);
dbEngine = resourceHttpEntry.getDbEngine();
DBSerializer serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, sourceOfTruth);
diff --git a/aai-resources/src/main/java/org/onap/aai/rest/VertexIdConsumer.java b/aai-resources/src/main/java/org/onap/aai/rest/VertexIdConsumer.java
index 3451528..6637d41 100644
--- a/aai-resources/src/main/java/org/onap/aai/rest/VertexIdConsumer.java
+++ b/aai-resources/src/main/java/org/onap/aai/rest/VertexIdConsumer.java
@@ -19,31 +19,10 @@
*/
package org.onap.aai.rest;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-import javax.ws.rs.core.UriBuilder;
-import javax.ws.rs.core.UriInfo;
-
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.javatuples.Pair;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.db.props.AAIProperties;
-import org.onap.aai.dbmap.DBConnectionType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
@@ -54,11 +33,17 @@ import org.onap.aai.rest.db.DBRequest;
import org.onap.aai.rest.db.HttpEntry;
import org.onap.aai.restcore.HttpMethod;
import org.onap.aai.restcore.RESTAPI;
-import org.onap.aai.serialization.db.DBSerializer;
-import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.setup.SchemaVersion;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.*;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
/**
* The Class VertexIdConsumer.
*/
@@ -66,7 +51,6 @@ import org.onap.aai.setup.SchemaVersion;
public class VertexIdConsumer extends RESTAPI {
private ModelType introspectorFactoryType = ModelType.MOXY;
- private QueryStyle queryStyle = QueryStyle.TRAVERSAL_URI;
private final String ID_ENDPOINT = "/id/{vertexid: \\d+}";
@@ -92,22 +76,16 @@ public class VertexIdConsumer extends RESTAPI {
String outputMediaType = getMediaType(headers.getAcceptableMediaTypes());
String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
String transId = headers.getRequestHeaders().getFirst("X-TransactionId");
- String realTime = headers.getRequestHeaders().getFirst("Real-Time");
SchemaVersion version = new SchemaVersion(versionParam);
- Status status = Status.NOT_FOUND;
- String result = "";
Response response = null;
TransactionalGraphEngine dbEngine = null;
try {
- int depth = setDepth(depthParam);
- DBConnectionType type = this.determineConnectionType(sourceOfTruth, realTime);
resourceHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
- resourceHttpEntry.setHttpEntryProperties(version, type);
+ resourceHttpEntry.setHttpEntryProperties(version);
dbEngine = resourceHttpEntry.getDbEngine();
Loader loader = resourceHttpEntry.getLoader();
- DBSerializer serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, sourceOfTruth);
-
+
//get type of the object represented by the given id
Vertex thisVertex = null;
Iterator<Vertex> itr = dbEngine.asAdmin().getTraversalSource().V(vertexid);
diff --git a/aai-resources/src/main/java/org/onap/aai/rest/bulk/BulkSingleTransactionConsumer.java b/aai-resources/src/main/java/org/onap/aai/rest/bulk/BulkSingleTransactionConsumer.java
index b06abaa..b7b4873 100644
--- a/aai-resources/src/main/java/org/onap/aai/rest/bulk/BulkSingleTransactionConsumer.java
+++ b/aai-resources/src/main/java/org/onap/aai/rest/bulk/BulkSingleTransactionConsumer.java
@@ -19,18 +19,16 @@
*/
package org.onap.aai.rest.bulk;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonParser;
import org.javatuples.Pair;
import org.onap.aai.config.SpringContextAware;
-import org.onap.aai.dbmap.DBConnectionType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.logging.ErrorLogHelper;
-import org.onap.aai.logging.LoggingContext;
import org.onap.aai.rest.bulk.pojos.Operation;
import org.onap.aai.rest.bulk.pojos.OperationResponse;
import org.onap.aai.rest.bulk.pojos.Transaction;
@@ -44,6 +42,8 @@ import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.AAIConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
@@ -57,11 +57,21 @@ import java.util.*;
@Path(value = "{version: v[1-9][0-9]*|latest}/bulk/single-transaction")
public class BulkSingleTransactionConsumer extends RESTAPI {
- private static final String TARGET_ENTITY = "aai-resources";
private static final Set<String> validOperations = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("put", "patch", "delete")));
+ private static final JsonParser parser = new JsonParser();
private int allowedOperationCount = 30;
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(BulkSingleTransactionConsumer.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(BulkSingleTransactionConsumer.class);
+
+ private final String uriPrefix;
+
+ public BulkSingleTransactionConsumer() {
+ uriPrefix = SpringContextAware.getApplicationContext().getEnvironment().getProperty("schema.uri.base.path", "");
+ }
+
+ public BulkSingleTransactionConsumer(String uriPrefix) {
+ this.uriPrefix = uriPrefix;
+ }
@POST
@Consumes(value = javax.ws.rs.core.MediaType.APPLICATION_JSON)
@@ -70,11 +80,8 @@ public class BulkSingleTransactionConsumer extends RESTAPI {
String transId = headers.getRequestHeaders().getFirst("X-TransactionId");
String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
- String realTime = headers.getRequestHeaders().getFirst("Real-Time");
SchemaVersion version = new SchemaVersion(versionParam);
- DBConnectionType type;
- initLogging(req, transId, sourceOfTruth);
boolean success = true;
TransactionalGraphEngine dbEngine = null;
@@ -82,11 +89,6 @@ public class BulkSingleTransactionConsumer extends RESTAPI {
Response response;
try {
- if(AAIConfig.get("aai.use.realtime", "true").equals("true")){
- type = DBConnectionType.REALTIME;
- } else {
- type = this.determineConnectionType(sourceOfTruth, realTime);
- }
// unmarshall the payload.
Gson gson = new Gson();
@@ -107,7 +109,7 @@ public class BulkSingleTransactionConsumer extends RESTAPI {
//init http entry
HttpEntry resourceHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
- resourceHttpEntry.setHttpEntryProperties(version, type);
+ resourceHttpEntry.setHttpEntryProperties(version);
Loader loader = resourceHttpEntry.getLoader();
dbEngine = resourceHttpEntry.getDbEngine();
@@ -123,16 +125,19 @@ public class BulkSingleTransactionConsumer extends RESTAPI {
//process db requests
Pair<Boolean, List<Pair<URI, Response>>> results = resourceHttpEntry.process(dbRequests, sourceOfTruth, this.enableResourceVersion());
- //process result of db requests
- transactionResponse = buildTransactionResponse(transaction, results.getValue1());
-
//commit/rollback based on results
success = results.getValue0();
- response = Response
- .status(Response.Status.CREATED)
- .entity(new GsonBuilder().serializeNulls().create().toJson(transactionResponse))
- .build();
+ if (success) { //process result of db requests if all are successful
+ transactionResponse = buildTransactionResponse(transaction, results.getValue1());
+ response = Response
+ .status(Response.Status.CREATED)
+ .entity(new GsonBuilder().serializeNulls().create().toJson(transactionResponse))
+ .build();
+ } else {
+ response = getErrorResponseForFirstFailure(transaction, results.getValue1(), info, javax.ws.rs.HttpMethod.POST, headers);
+
+ }
} catch (AAIException e) {
response = consumerExceptionResponseGenerator(headers, info, javax.ws.rs.HttpMethod.POST, e);
@@ -152,6 +157,44 @@ public class BulkSingleTransactionConsumer extends RESTAPI {
return response;
}
+ private Response getErrorResponseForFirstFailure(Transaction transaction, List<Pair<URI, Response>> results, UriInfo info, String action, HttpHeaders headers) throws AAIException {
+ final String failureInResponse = "Operation %s with action (%s) on uri (%s) failed with status code (%s), error code (%s) and msg (%s)";
+ for (int i = 0; i < transaction.getOperations().size(); i++) {
+ if (!Response.Status.Family.familyOf(results.get(i).getValue1().getStatus()).equals(Response.Status.Family.SUCCESSFUL)) {
+ final JsonArray vars = parser.parse(results.get(i).getValue1().getEntity().toString()).getAsJsonObject()
+ .getAsJsonObject("requestError")
+ .getAsJsonObject("serviceException")
+ .getAsJsonArray("variables");
+ StringBuilder sb = new StringBuilder();
+ for (int j = 2; j < vars.size() - 1; j++) {
+ if (j != 2) {
+ sb.append(": ");
+ }
+ sb.append(vars.get(j).getAsString());
+ }
+ final AAIException e = new AAIException("AAI_3000",
+ String.format(
+ failureInResponse,
+ i,
+ vars.get(0).getAsString(),
+ vars.get(1).getAsString(),
+ results.get(i).getValue1().getStatus(),
+ vars.get(vars.size()-1).getAsString(),
+ sb.toString()
+ ));
+ ArrayList<String> templateVars = new ArrayList<>();
+ templateVars.add(action); //GET, PUT, etc
+ templateVars.add(info.getPath());
+ return Response
+ .status(results.get(i).getValue1().getStatus())
+ .entity(ErrorLogHelper.getRESTAPIErrorResponseWithLogging(headers.getAcceptableMediaTypes(), e, templateVars))
+ .build();
+ }
+ }
+ LOGGER.error("Transaction Process reported failure, none found.");
+ throw new AAIException("AAI_3000", "Transaction Process reported failure, none found.");
+ }
+
/**
* Builds the response
@@ -297,11 +340,9 @@ public class BulkSingleTransactionConsumer extends RESTAPI {
List<BulkOperation> bulkOperations = new ArrayList<>(transaction.getOperations().size());
BulkOperation bulkOperation;
- for (int i = 0; i < transaction.getOperations().size(); i++) {
- final Operation operation = transaction.getOperations().get(i);
+ for (Operation operation : transaction.getOperations()) {
bulkOperation = new BulkOperation();
-
- UriComponents uriComponents = UriComponentsBuilder.fromUriString(operation.getUri()).build();
+ UriComponents uriComponents = UriComponentsBuilder.fromUriString(getUri(operation)).build();
bulkOperation.setUri(UriBuilder.fromPath(uriComponents.getPath()).build());
bulkOperation.addUriInfoQueryParams(uriComponents.getQueryParams());
bulkOperation.setHttpMethod(getHttpMethod(operation.getAction(), bulkOperation.getUri()));
@@ -312,6 +353,17 @@ public class BulkSingleTransactionConsumer extends RESTAPI {
return bulkOperations;
}
+ private String getUri(Operation operation) {
+ String uri = operation.getUri();
+ if (uri == null || uri.isEmpty()) {
+ return uri;
+ } else if (uri.charAt(0) != '/') {
+ uri = '/' + uri;
+ }
+ return uri.replaceAll("^" + uriPrefix + "/v\\d+", "");
+ }
+
+
/**
* Map action to httpmethod
* @param action action to be mapped
@@ -386,21 +438,6 @@ public class BulkSingleTransactionConsumer extends RESTAPI {
}
- /**
- * Initialize logging context
- * @param req requestContext
- * @param transId transaction id
- * @param sourceOfTruth application source
- */
- private void initLogging(@Context HttpServletRequest req, String transId, String sourceOfTruth) {
- String serviceName = req.getMethod() + " " + req.getRequestURI().toString();
- LoggingContext.requestId(transId);
- LoggingContext.partnerName(sourceOfTruth);
- LoggingContext.serviceName(serviceName);
- LoggingContext.targetEntity(TARGET_ENTITY);
- LoggingContext.targetServiceName(serviceName);
- }
-
protected boolean enableResourceVersion() {
return true;
}
diff --git a/aai-resources/src/main/java/org/onap/aai/service/AuthorizationService.java b/aai-resources/src/main/java/org/onap/aai/service/AuthorizationService.java
index d2597d0..9b5a614 100644
--- a/aai-resources/src/main/java/org/onap/aai/service/AuthorizationService.java
+++ b/aai-resources/src/main/java/org/onap/aai/service/AuthorizationService.java
@@ -19,8 +19,8 @@
*/
package org.onap.aai.service;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.eclipse.jetty.util.security.Password;
import org.onap.aai.Profiles;
import org.onap.aai.util.AAIConstants;
@@ -41,7 +41,7 @@ import java.util.stream.Stream;
@Service
public class AuthorizationService {
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(AuthorizationService.class);
+ private static final Logger logger = LoggerFactory.getLogger(AuthorizationService.class);
private final Map<String, String> authorizedUsers = new HashMap<>();
@@ -72,7 +72,7 @@ public class AuthorizationService {
String[] usernamePasswordArray = usernamePassword.split(":");
if(usernamePasswordArray == null || usernamePasswordArray.length != 3){
- throw new RuntimeException("Not a valid entry for the realm.properties entry: " + usernamePassword);
+ throw new RuntimeException("This username / pwd is not a valid entry in realm.properties");
}
String username = usernamePasswordArray[0];
diff --git a/aai-resources/src/main/java/org/onap/aai/web/JerseyConfiguration.java b/aai-resources/src/main/java/org/onap/aai/web/JerseyConfiguration.java
index 9592639..c5f3e08 100644
--- a/aai-resources/src/main/java/org/onap/aai/web/JerseyConfiguration.java
+++ b/aai-resources/src/main/java/org/onap/aai/web/JerseyConfiguration.java
@@ -28,6 +28,8 @@ import java.util.Comparator;
import java.util.Set;
import java.util.logging.Logger;
import javax.annotation.Priority;
+import javax.ws.rs.client.ClientRequestFilter;
+import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseFilter;
import jersey.repackaged.com.google.common.collect.Sets;
@@ -41,6 +43,7 @@ import org.onap.aai.rest.URLFromVertexIdConsumer;
import org.onap.aai.rest.VertexIdConsumer;
import org.onap.aai.rest.bulk.BulkSingleTransactionConsumer;
import org.onap.aai.rest.util.EchoResponse;
+import org.onap.logging.filter.base.AuditLogContainerFilter;
import org.reflections.Reflections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
@@ -55,9 +58,11 @@ public class JerseyConfiguration {
private static final String LOGGING_ENABLED_PROPERTY = "aai.request.logging.enabled";
private static final String INTERCEPTOR_PACKAGE = "org.onap.aai.interceptors";
+ private static final String LOGGING_INTERCEPTOR_PACKAGE = "org.onap.aai.aailog.filter";
private static final boolean ENABLE_RESPONSE_LOGGING = false;
private final Reflections reflections = new Reflections(INTERCEPTOR_PACKAGE);
+ private final Reflections loggingReflections = new Reflections(LOGGING_INTERCEPTOR_PACKAGE);
private final Environment environment;
@Autowired
@@ -80,7 +85,7 @@ public class JerseyConfiguration {
URLFromVertexIdConsumer.class
);
resourceConfig.registerClasses(classes);
- registerFiltersForClasses(resourceConfig, ContainerRequestFilter.class, ContainerResponseFilter.class);
+ registerFiltersForClasses(resourceConfig, ContainerRequestFilter.class, ContainerResponseFilter.class, AuditLogContainerFilter.class);
if (isLoggingEnabled()) {
logRequests(resourceConfig);
@@ -96,8 +101,8 @@ public class JerseyConfiguration {
}
private <T> void registerFiltersFor(Class<T> clazz, ResourceConfig resourceConfig) {
- Set<Class<? extends T>> filters = reflections.getSubTypesOf(clazz);
-
+ Set<Class<? extends T>> filters = loggingReflections.getSubTypesOf(clazz);
+ filters.addAll(reflections.getSubTypesOf(clazz));
throwIfPriorityAnnotationAbsent(filters);
filters.stream()