--- /dev/null
+---
+# Dependabot configured for weekly Maven updates
+
+version: 2
+updates:
+ # Enable version updates for Maven
+ - package-ecosystem: "maven"
+ directory: "/"
+ # Check the registry for updates weekly
+ schedule:
+ interval: "weekly"
--- /dev/null
+---
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2024 The Linux Foundation <abelur@linux.com>
+
+name: call-github2gerrit-reusable-workflow
+
+# yamllint disable-line rule:truthy
+on:
+ workflow_dispatch:
+ pull_request_target:
+ types: [opened, reopened, edited, synchronize]
+ branches:
+ - master
+ - main
+
+concurrency:
+ # yamllint disable-line rule:line-length
+ group: ${{ github.workflow }}-${{ github.run_id }}
+ cancel-in-progress: true
+
+jobs:
+ call-in-g2g-workflow:
+ permissions:
+ contents: read
+ pull-requests: write
+ uses: lfit/github2gerrit/.github/workflows/github2gerrit.yaml@main
+ with:
+ GERRIT_KNOWN_HOSTS: ${{ vars.GERRIT_KNOWN_HOSTS }}
+ GERRIT_SSH_USER_G2G: ${{ vars.GERRIT_SSH_USER_G2G }}
+ GERRIT_SSH_USER_G2G_EMAIL: ${{ vars.GERRIT_SSH_USER_G2G_EMAIL }}
+ ORGANIZATION: ${{ vars.ORGANIZATION }}
+ secrets:
+ GERRIT_SSH_PRIVKEY_G2G: ${{ secrets.GERRIT_SSH_PRIVKEY_G2G }}
target/
**/logs/
**/debug-logs/
-bundleconfig-local/etc/auth/aai-client-cert.p12
-bundleconfig-local/etc/auth/tomcat_keystore
bundleconfig-local/etc/logback.xml
/.pydevproject
/bin/
*.log
aai-core/logs/
.classpath
-**/.classpath
\ No newline at end of file
+**/.classpath
+**/bin
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.onap.aai.aai-common</groupId>
- <artifactId>aai-parent</artifactId>
- <version>1.13.6-SNAPSHOT</version>
- <relativePath>../aai-parent/pom.xml</relativePath>
- </parent>
- <artifactId>aai-aaf-auth</artifactId>
- <name>aai-aaf-auth</name>
- <packaging>jar</packaging>
- <dependencies>
- <dependency>
- <groupId>org.onap.aai.aai-common</groupId>
- <artifactId>aai-els-onap-logging</artifactId>
- </dependency>
- <dependency>
- <groupId>org.onap.aaf.authz</groupId>
- <artifactId>aaf-cadi-core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.onap.aaf.authz</groupId>
- <artifactId>aaf-cadi-aaf</artifactId>
- </dependency>
- <dependency>
- <groupId>org.easymock</groupId>
- <artifactId>easymock</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- <exclusions>
- <exclusion>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-tomcat</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- </dependency>
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <!-- TODO: Migrate tests to junit 5 and remove this dependency -->
- <dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-core</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- </dependencies>
-</project>
+++ /dev/null
-/**
- * ============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.aaf.auth;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.UnsupportedEncodingException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Base64;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.UUID;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-import org.eclipse.jetty.util.security.Password;
-import org.onap.aai.aaf.auth.exceptions.AAIUnrecognizedFunctionException;
-import org.onap.aai.logging.ErrorLogHelper;
-import org.onap.aai.util.AAIConfig;
-import org.onap.aai.util.AAIConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * The Class AAIAuthCore.
- */
-public final class AAIAuthCore {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(AAIAuthCore.class);
-
- private static final String ERROR_CODE_AAI_4001 = "AAI_4001";
-
- private String globalAuthFileName = AAIConstants.AAI_AUTH_CONFIG_FILENAME;
-
- private final Pattern authPolicyPattern;
- private final Set<String> validFunctions = new HashSet<>();
- private Map<String, AAIUser> users;
- private boolean timerSet = false;
- private Timer timer = null;
-
- private String basePath;
-
- /**
- * Instantiates a new AAI auth core.
- */
- public AAIAuthCore(String basePath) {
- this(basePath, AAIConstants.AAI_AUTH_CONFIG_FILENAME);
- }
-
- public AAIAuthCore(String basePath, String filename) {
- this.basePath = basePath;
- this.globalAuthFileName = filename;
- authPolicyPattern = Pattern.compile("^" + this.basePath + "/v\\d+/([\\w\\-]*)");
- init();
- }
-
- public AAIAuthCore(String basePath, String filename, String pattern) {
- this.basePath = basePath;
- this.globalAuthFileName = filename;
- authPolicyPattern = Pattern.compile(pattern);
- init();
- }
-
- /**
- * Inits the.
- */
- private synchronized void init() {
-
- LOGGER.debug("Initializing Auth Policy Config");
-
- reloadUsers();
-
- /*
- * this timer code is setting up a recurring task that checks if the
- * auth config file has been updated and reloads the users if so to get
- * the most up to date info (that update check logic is within
- * FileWatcher)
- *
- * the timing this method uses is coarser than the frequency of requests
- * AI&I gets so we're looking at better ways of doing this (TODO)
- */
- TimerTask task = new FileWatcher(new File(globalAuthFileName)) {
- @Override
- protected void onChange(File file) {
- reloadUsers();
- }
- };
-
- if (!timerSet) {
- timerSet = true;
- timer = new Timer();
-
- // repeat the check every second
- timer.schedule(task, new Date(), 10000);
- }
- LOGGER.debug("Static Initializiation complete");
- }
-
- /**
- * Cleanup.
- */
- // just ends the auth config file update checking timer
- public void cleanup() {
- timer.cancel();
- }
-
- /**
- * Reload users.
- */
- /*
- * this essentially takes the data file, which is organized role-first with
- * users under each role and converts it to data organized user-first with
- * each user containing their role with its associated allowed functions
- * this data stored in the class field users
- */
- private synchronized void reloadUsers() {
-
- Map<String, AAIUser> tempUsers = new HashMap<>();
-
- try {
- LOGGER.debug("Reading from " + globalAuthFileName);
- String authFile = new String(Files.readAllBytes(Paths.get(globalAuthFileName)));
-
- JsonObject authObject = JsonParser.parseString(authFile).getAsJsonObject();
- if (authObject.has("roles")) {
- JsonArray roles = authObject.getAsJsonArray("roles");
- for (JsonElement role : roles) {
- if (role.isJsonObject()) {
- JsonObject roleObject = role.getAsJsonObject();
- String roleName = roleObject.get("name").getAsString();
- Map<String, Boolean> usrs = this.getUsernamesFromRole(roleObject);
- List<String> aaiFunctions = this.getAAIFunctions(roleObject);
-
- usrs.forEach((key, value) -> {
- final AAIUser au = tempUsers.getOrDefault(key, new AAIUser(key, value));
- au.addRole(roleName);
- aaiFunctions.forEach(f -> {
- List<String> httpMethods = this.getRoleHttpMethods(f, roleObject);
- httpMethods.forEach(hm -> au.setUserAccess(f, hm));
- this.validFunctions.add(f);
- });
-
- tempUsers.put(key, au);
-
- });
- }
- }
- if (!tempUsers.isEmpty()) {
- users = tempUsers;
- }
- }
- } catch (FileNotFoundException e) {
- ErrorLogHelper.logError(ERROR_CODE_AAI_4001, globalAuthFileName + ". Exception: " + e);
- } catch (JsonProcessingException e) {
- ErrorLogHelper.logError(ERROR_CODE_AAI_4001, globalAuthFileName + ". Not valid JSON: " + e);
- } catch (Exception e) {
- ErrorLogHelper.logError(ERROR_CODE_AAI_4001, globalAuthFileName + ". Exception caught: " + e);
- }
- }
-
- private List<String> getRoleHttpMethods(String aaiFunctionName, JsonObject roleObject) {
- List<String> httpMethods = new ArrayList<>();
-
- JsonArray ja = roleObject.getAsJsonArray("functions");
- for (JsonElement je : ja) {
- if (je.isJsonObject() && je.getAsJsonObject().has("name")
- && je.getAsJsonObject().get("name").getAsString().equals(aaiFunctionName)) {
- JsonArray jaMeth = je.getAsJsonObject().getAsJsonArray("methods");
- for (JsonElement jeMeth : jaMeth) {
- if (jeMeth.isJsonObject() && jeMeth.getAsJsonObject().has("name")) {
- httpMethods.add(jeMeth.getAsJsonObject().get("name").getAsString());
- }
- }
- }
- }
-
- return httpMethods;
- }
-
- private List<String> getAAIFunctions(JsonObject roleObject) {
- List<String> aaiFunctions = new ArrayList<>();
-
- JsonArray ja = roleObject.getAsJsonArray("functions");
- for (JsonElement je : ja) {
- if (je.isJsonObject() && je.getAsJsonObject().has("name")) {
- aaiFunctions.add(je.getAsJsonObject().get("name").getAsString());
- }
- }
-
- return aaiFunctions;
- }
-
- private Map<String, Boolean> getUsernamesFromRole(JsonObject roleObject) throws UnsupportedEncodingException {
- Map<String, Boolean> usernames = new HashMap<>();
-
- JsonArray uja = roleObject.getAsJsonArray("users");
- for (JsonElement je : uja) {
- if (je.isJsonObject()) {
- if (je.getAsJsonObject().has("username")) {
- if (je.getAsJsonObject().has("is-wildcard-id")) {
- usernames.put(je.getAsJsonObject().get("username").getAsString().toLowerCase(),
- je.getAsJsonObject().get("is-wildcard-id").getAsBoolean());
- } else {
- usernames.put(je.getAsJsonObject().get("username").getAsString().toLowerCase(), false);
- }
- } else if (je.getAsJsonObject().has("user")) {
- String auth = je.getAsJsonObject().get("user").getAsString() + ":"
- + Password.deobfuscate(je.getAsJsonObject().get("pass").getAsString());
- String authorizationCode = new String(Base64.getEncoder().encode(auth.getBytes("utf-8")));
- usernames.put(authorizationCode, false);
- }
- }
- }
-
- return usernames;
- }
-
- public String getAuthPolicyFunctName(String uri) {
- String authPolicyFunctionName = "";
- if (uri.startsWith(basePath + "/search")) {
- authPolicyFunctionName = "search";
- } else if (uri.startsWith(basePath + "/recents")) {
- authPolicyFunctionName = "recents";
- } else if (uri.startsWith(basePath + "/cq2gremlin")) {
- authPolicyFunctionName = "cq2gremlin";
- } else if (uri.startsWith(basePath + "/cq2gremlintest")) {
- authPolicyFunctionName = "cq2gremlintest";
- } else if (uri.startsWith(basePath + "/util/echo")) {
- authPolicyFunctionName = "util";
- } else if (uri.startsWith(basePath + "/tools")) {
- authPolicyFunctionName = "tools";
- } else {
- Matcher match = authPolicyPattern.matcher(uri);
- if (match.find()) {
- authPolicyFunctionName = match.group(1);
- }
- }
- return authPolicyFunctionName;
- }
-
- /**
- * for backwards compatibility
- *
- * @param username
- * @param uri
- * @param httpMethod
- * @param haProxyUser
- * @return
- * @throws AAIUnrecognizedFunctionException
- */
- public boolean authorize(String username, String uri, String httpMethod, String haProxyUser)
- throws AAIUnrecognizedFunctionException {
- return authorize(username, uri, httpMethod, haProxyUser, null);
- }
-
- /**
- *
- * @param username
- * @param uri
- * @param httpMethod
- * @param haProxyUser
- * @param issuer issuer of the cert
- * @return
- * @throws AAIUnrecognizedFunctionException
- */
- public boolean authorize(String username, String uri, String httpMethod, String haProxyUser, String issuer)
- throws AAIUnrecognizedFunctionException {
- String aaiMethod = this.getAuthPolicyFunctName(uri);
- if (!this.validFunctions.contains(aaiMethod) && !("info".equalsIgnoreCase(aaiMethod))) {
- throw new AAIUnrecognizedFunctionException(aaiMethod);
- }
- boolean wildcardCheck = isWildcardIssuer(issuer);
- boolean authorized;
- LOGGER.debug(
- "Authorizing the user for the request cert {}, haproxy header {}, aai method {}, httpMethod {}, cert issuer {}",
- username, haProxyUser, aaiMethod, httpMethod, issuer);
- Optional<AAIUser> oau = this.getUser(username, wildcardCheck);
- if (oau.isPresent()) {
- AAIUser au = oau.get();
- if (au.hasRole("HAProxy")) {
- LOGGER.debug("User has HAProxy role");
- if ("GET".equalsIgnoreCase(httpMethod) && "util".equalsIgnoreCase(aaiMethod) && haProxyUser.isEmpty()) {
- LOGGER.debug("Authorized user has HAProxy role with echo request");
- authorized = this.authorize(au, aaiMethod, httpMethod);
- } else {
- authorized = this.authorize(haProxyUser, uri, httpMethod, "", issuer);
- }
- } else {
- LOGGER.debug("User doesn't have HAProxy role so assuming its a regular client");
- authorized = this.authorize(au, aaiMethod, httpMethod);
- }
- } else {
- LOGGER.debug("User not found: " + username + " on function " + aaiMethod + " request type " + httpMethod);
- authorized = false;
- }
-
- return authorized;
- }
-
- private boolean isWildcardIssuer(String issuer) {
- if (issuer != null && !issuer.isEmpty()) {
- List<String> validIssuers = Arrays
- .asList(AAIConfig.get("aaf.valid.issuer.wildcard", UUID.randomUUID().toString()).split("\\|"));
- for (String validIssuer : validIssuers) {
- if (issuer.contains(validIssuer)) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * returns aai user either matching the username or containing the wildcard.
- *
- * @param username
- * @return
- */
- public Optional<AAIUser> getUser(String username, boolean wildcardCheck) {
- if (users.containsKey(username)) {
- return Optional.of(users.get(username));
- } else if (wildcardCheck) {
- List<AAIUser> laus =
- users.entrySet().stream().filter(e -> e.getValue().isWildcard() && username.contains(e.getKey()))
- .map(Map.Entry::getValue).collect(Collectors.toList());
- if (!laus.isEmpty()) {
- return Optional.of(laus.get(0));
- }
- }
- return Optional.empty();
- }
-
- /**
- *
- * @param aaiUser
- * aai user with the username
- * @param aaiMethod
- * aai function the authorization is required on
- * @param httpMethod
- * http action user is attempting
- * @return true, if successful
- */
- private boolean authorize(AAIUser aaiUser, String aaiMethod, String httpMethod) {
- if ("info".equalsIgnoreCase(aaiMethod) || aaiUser.hasAccess(aaiMethod, httpMethod)) {
- LOGGER.debug("AUTH ACCEPTED: " + aaiUser.getUsername() + " on function " + aaiMethod + " request type "
- + httpMethod);
- return true;
- } else {
- LOGGER.debug("AUTH FAILED: " + aaiUser.getUsername() + " on function " + aaiMethod + " request type "
- + httpMethod);
- return false;
- }
- }
-}
+++ /dev/null
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Modifications Copyright © 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.aai.aaf.auth;
-
-import java.util.*;
-
-public class AAIUser {
-
- private String username;
-
- private boolean isWildcard = false;
- private Set<String> roles;
- private Map<String, Set<String>> aaiFunctionToHttpMethod;
-
- public AAIUser(String username) {
- this(username, false);
- }
-
- public AAIUser(String username, boolean isWildcard) {
- this.username = username;
- this.roles = new HashSet<>();
- this.aaiFunctionToHttpMethod = new HashMap<>();
- this.isWildcard = isWildcard;
- }
-
- public boolean isWildcard() {
- return isWildcard;
- }
-
- public String getUsername() {
- return username;
- }
-
- public void addRole(String role) {
- this.roles.add(role);
- }
-
- public boolean hasRole(String role) {
- return this.roles.contains(role);
- }
-
- public void setUserAccess(String aaiMethod, String... httpMethods) {
- for (String httpMethod : httpMethods) {
- this.addUserAccess(aaiMethod, httpMethod);
- }
- }
-
- private void addUserAccess(String aaiMethod, String httpMethod) {
- Set<String> httpMethods = new HashSet<>();
- if (this.aaiFunctionToHttpMethod.containsKey(aaiMethod)) {
- httpMethods = this.aaiFunctionToHttpMethod.get(aaiMethod);
- }
- httpMethods.add(httpMethod);
- this.aaiFunctionToHttpMethod.put(aaiMethod, httpMethods);
- }
-
- public boolean hasAccess(String aaiMethod, String httpMethod) {
- return this.aaiFunctionToHttpMethod.getOrDefault(aaiMethod, Collections.emptySet()).contains(httpMethod);
- }
-
-}
+++ /dev/null
-/**
- * ============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.aaf.auth;
-
-import static org.onap.aai.aaf.auth.ResponseFormatter.errorResponse;
-
-import java.io.IOException;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.Properties;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.onap.aaf.cadi.filter.CadiFilter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * The Class AafRequestFilter provides common auth filter methods
- */
-public class AafRequestFilter {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(AafRequestFilter.class);
-
- public static void authenticationFilter(HttpServletRequest request, HttpServletResponse response,
- FilterChain filterChain, CadiFilter cadiFilter, Properties props, String userChainPattern)
- throws IOException, ServletException {
- if (!request.getRequestURI().matches("^.*/util/echo$")) {
-
- List<String> cadiConfiguredIssuers = CertUtil.getCadiCertIssuers(props);
- String issuer = CertUtil.getCertIssuer(request);
- if (issuer == null || issuer.isEmpty()) {
- errorResponse(request, response);
- return;
- }
- issuer = issuer.replaceAll("\\s+", "").toUpperCase();
-
- if (cadiConfiguredIssuers.contains(issuer)) {
- LOGGER.debug("authenticationFilter CADI issuer " + issuer);
- if (CertUtil.isHaProxy(request)) {
- // get the end user/client mechid and use it in the user chain header value
- String user = CertUtil.getMechId(request);
- LOGGER.debug("authenticationFilter haProxy sent end user/mechid " + user);
- if (user == null || user.isEmpty()) {
- errorResponse(request, response);
- return;
- }
- AafRequestWrapper reqWrapper = new AafRequestWrapper(request);
- String userChainHdr = CertUtil.buildUserChainHeader(user, userChainPattern);
- LOGGER.debug("User chain header value: " + userChainHdr);
- reqWrapper.putHeader(CertUtil.AAF_USER_CHAIN_HDR, userChainHdr);
- cadiFilter.doFilter(reqWrapper, response, filterChain);
- } else {
- cadiFilter.doFilter(request, response, filterChain);
- }
- if (response.getStatus() == 401 || response.getStatus() == 403) {
- LOGGER.debug("authenticationFilter failed CADI authentication");
- errorResponse(request, response);
- return;
- }
- } else {
- filterChain.doFilter(request, response);
- }
- } else {
- filterChain.doFilter(request, response);
- }
- }
-
- public static void authorizationFilter(HttpServletRequest request, HttpServletResponse response,
- FilterChain filterChain, String permission, Properties props) throws IOException, ServletException {
- if (request.getRequestURI().matches("^.*/util/echo$")) {
- filterChain.doFilter(request, response);
- }
- List<String> cadiConfiguredIssuers = CertUtil.getCadiCertIssuers(props);
- String issuer = CertUtil.getCertIssuer(request);
- if (issuer == null || issuer.isEmpty()) {
- errorResponse(request, response);
- return;
- }
- issuer = issuer.replaceAll("\\s+", "").toUpperCase();
- Enumeration<String> hdrs = request.getHeaders(CertUtil.AAF_USER_CHAIN_HDR);
- while (hdrs.hasMoreElements()) {
- String headerValue = (String) hdrs.nextElement();
- LOGGER.debug("authorizationFilter user chain headerValue=" + headerValue);
- }
- if ((cadiConfiguredIssuers.contains(issuer)) && (!request.isUserInRole(permission))) {
- LOGGER.debug(
- "authorizationFilter failed CADI authorization issuer=" + issuer + " permission=" + permission);
- errorResponse(request, response);
- } else {
- filterChain.doFilter(request, response);
- }
- }
-}
+++ /dev/null
-/**
- * ============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.aaf.auth;
-
-import java.util.*;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletRequestWrapper;
-
-/**
- * The AafRequestWrapper sets the user in the principal name
- */
-public class AafRequestWrapper extends HttpServletRequestWrapper {
-
- private final Map<String, String> customHeaders;
-
- public AafRequestWrapper(HttpServletRequest request) {
- super(request);
- this.customHeaders = new HashMap<String, String>();
- }
-
- public void putHeader(String name, String value) {
- this.customHeaders.put(name, value);
- }
-
- @Override
- public String getHeader(String name) {
- String headerValue = customHeaders.get(name);
- if (headerValue != null) {
- return headerValue;
- }
- return (((HttpServletRequest) getRequest()).getHeader(name));
- }
-
- @Override
- public Enumeration<String> getHeaderNames() {
- Set<String> nameSet = new HashSet<String>(customHeaders.keySet());
-
- Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
- while (e.hasMoreElements()) {
- String headerName = e.nextElement();
- nameSet.add(headerName);
- }
- return Collections.enumeration(nameSet);
- }
-
- @Override
- public Enumeration<String> getHeaders(String name) {
- String myHeaderValue = customHeaders.get(name);
- Set<String> headerValueSet = new HashSet<String>();
- if (myHeaderValue != null) {
- headerValueSet.add(myHeaderValue);
- }
- Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaders(name);
- while (e.hasMoreElements()) {
- String headerValue = e.nextElement();
- headerValueSet.add(headerValue);
- }
- return Collections.enumeration(headerValueSet);
- }
-}
+++ /dev/null
-/**
- * ============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.aaf.auth;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
-import java.util.Properties;
-import java.util.stream.Collectors;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * The Class CertUtil provides cert related utility methods.
- */
-public class CertUtil {
- public static final String DEFAULT_CADI_ISSUERS = "CN=ATT AAF CADI Test Issuing "
- + "CA 01, OU=CSO, O=ATT, C=US:CN=ATT AAF CADI Test Issuing CA 02, OU=CSO, O=ATT, C=US";
- public static final String CADI_PROP_FILES = "cadi_prop_files";
- public static final String CADI_ISSUERS_PROP_NAME = "cadi_x509_issuers";
- public static final String CADI_ISSUERS_SEPARATOR = ":";
- public static final String AAI_SSL_CLIENT_OU_HDR = "X-AAI-SSL-Client-OU";
- public static final String AAI_SSL_ISSUER_HDR = "X-AAI-SSL-Issuer";
- public static final String AAI_SSL_CLIENT_CN_HDR = "X-AAI-SSL-Client-CN";
- public static final String AAI_SSL_CLIENT_O_HDR = "X-AAI-SSL-Client-O";
- public static final String AAI_SSL_CLIENT_L_HDR = "X-AAI-SSL-Client-L";
- public static final String AAI_SSL_CLIENT_ST_HDR = "X-AAI-SSL-Client-ST";
- public static final String AAI_SSL_CLIENT_C_HDR = "X-AAI-SSL-Client-C";
- public static final String AAF_USER_CHAIN_HDR = "USER_CHAIN";
- public static final String AAF_ID = "<AAF-ID>";
- private static final Logger LOGGER = LoggerFactory.getLogger(CertUtil.class);
-
- public static String getAaiSslClientOuHeader(HttpServletRequest hsr) {
- return (hsr.getHeader(AAI_SSL_CLIENT_OU_HDR));
- }
-
- public static boolean isHaProxy(HttpServletRequest hsr) {
-
- String haProxyUser = "";
- if (Objects.isNull(hsr.getHeader(AAI_SSL_CLIENT_CN_HDR)) || Objects.isNull(hsr.getHeader(AAI_SSL_CLIENT_OU_HDR))
- || Objects.isNull(hsr.getHeader(AAI_SSL_CLIENT_O_HDR))
- || Objects.isNull(hsr.getHeader(AAI_SSL_CLIENT_L_HDR))
- || Objects.isNull(hsr.getHeader(AAI_SSL_CLIENT_ST_HDR))
- || Objects.isNull(hsr.getHeader(AAI_SSL_CLIENT_C_HDR))) {
- haProxyUser = "";
- } else {
- haProxyUser = String.format("CN=%s, OU=%s, O=\"%s\", L=%s, ST=%s, C=%s",
- Objects.toString(hsr.getHeader(AAI_SSL_CLIENT_CN_HDR), ""),
- Objects.toString(hsr.getHeader(AAI_SSL_CLIENT_OU_HDR), ""),
- Objects.toString(hsr.getHeader(AAI_SSL_CLIENT_O_HDR), ""),
- Objects.toString(hsr.getHeader(AAI_SSL_CLIENT_L_HDR), ""),
- Objects.toString(hsr.getHeader(AAI_SSL_CLIENT_ST_HDR), ""),
- Objects.toString(hsr.getHeader(AAI_SSL_CLIENT_C_HDR), "")).toLowerCase();
- }
- if (!haProxyUser.isEmpty()) {
- LOGGER.debug("isHaProxy haProxyUser=" + haProxyUser);
- return true;
- }
- LOGGER.debug("isHaProxy haProxyUser not found");
- return false;
- }
-
- public static String getMechId(HttpServletRequest hsr) {
- String mechId = null;
- String ou = getAaiSslClientOuHeader(hsr);
- if ((ou != null) && (!ou.isEmpty())) {
- String[] parts = ou.split(CADI_ISSUERS_SEPARATOR);
- if (parts != null && parts.length >= 1) {
- mechId = parts[0];
- }
- }
- LOGGER.debug("getMechId mechId=" + mechId);
- return (mechId);
- }
-
- public static String getCertIssuer(HttpServletRequest hsr) {
- String issuer = hsr.getHeader(AAI_SSL_ISSUER_HDR);
- if (issuer != null && !issuer.isEmpty()) {
- LOGGER.debug("getCertIssuer issuer from header " + AAI_SSL_ISSUER_HDR + " " + issuer);
- // the haproxy header replaces the ', ' with '/' and reverses on the '/' need to undo that.
- List<String> broken = Arrays.asList(issuer.split("/"));
- broken = broken.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
- Collections.reverse(broken);
- issuer = String.join(", ", broken);
- } else {
- if (hsr.getAttribute("javax.servlet.request.cipher_suite") != null) {
- X509Certificate[] certChain =
- (X509Certificate[]) hsr.getAttribute("javax.servlet.request.X509Certificate");
- if (certChain != null && certChain.length > 0) {
- X509Certificate clientCert = certChain[0];
- issuer = clientCert.getIssuerX500Principal().getName();
- LOGGER.debug("getCertIssuer issuer from client cert " + issuer);
- }
- }
- }
- return issuer;
- }
-
- public static List<String> getCadiCertIssuers(Properties cadiProperties) {
-
- List<String> defaultList = new ArrayList<>();
- List<String> resultList = new ArrayList<String>();
-
- String[] cadiIssuers = DEFAULT_CADI_ISSUERS.split(CADI_ISSUERS_SEPARATOR);
- for (String issuer : cadiIssuers) {
- defaultList.add(issuer.replaceAll("\\s+", "").toUpperCase());
- }
- try {
- String certPropFileName = cadiProperties.getProperty(CADI_PROP_FILES);
- String configuredIssuers = DEFAULT_CADI_ISSUERS;
- Properties certProperties = new Properties();
- if (certPropFileName != null) {
- try (FileInputStream fis = new FileInputStream(certPropFileName)) {
- certProperties.load(fis);
- }
- configuredIssuers = certProperties.getProperty(CADI_ISSUERS_PROP_NAME);
- }
- if ((configuredIssuers != null) && (!configuredIssuers.isEmpty())) {
- cadiIssuers = configuredIssuers.split(CADI_ISSUERS_SEPARATOR);
- for (String issuer : cadiIssuers) {
- resultList.add(issuer.replaceAll("\\s+", "").toUpperCase());
- }
- }
- } catch (IOException ioe) {
- return (defaultList);
- }
- if (resultList.isEmpty()) {
- return defaultList;
- }
- LOGGER.debug("getCadiCertIssuers " + resultList.toString());
- return resultList;
- }
-
- public static String buildUserChainHeader(String user, String userChainPattern) {
- // aaf.userchain.pattern=<AAF-ID>:${aaf.userchain.service.reference}:${aaf.userchain.auth.type}:AS
- return (userChainPattern.replaceAll(AAF_ID, user));
- }
-}
+++ /dev/null
-/**
- * ============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.aaf.auth;
-
-import java.io.File;
-import java.util.TimerTask;
-
-public abstract class FileWatcher extends TimerTask {
- private long timeStamp;
- private File file;
-
- /**
- * Instantiates a new file watcher.
- *
- * @param file the file
- */
- public FileWatcher(File file) {
- this.file = file;
- this.timeStamp = file.lastModified();
- }
-
- /**
- * runs a timer task
- *
- * @see TimerTask#run
- */
- public final void run() {
- long timeStamp = file.lastModified();
-
- if ((timeStamp - this.timeStamp) > 500) {
- this.timeStamp = timeStamp;
- onChange(file);
- }
- }
-
- /**
- * On change.
- *
- * @param file the file
- */
- protected abstract void onChange(File file);
-}
+++ /dev/null
-/**
- * ============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.aaf.auth;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.core.MediaType;
-
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.logging.ErrorLogHelper;
-
-public class ResponseFormatter {
-
- private static final String ACCEPT_HEADER = "accept";
- private static final String CONTENT_TYPE_HEADER = "Content-Type";
-
- private ResponseFormatter() {
- throw new IllegalStateException("Utility class");
- }
-
- public static void errorResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
- errorResponse(new AAIException("AAI_3300"), request, response);
- }
-
- public static void errorResponse(AAIException exception, HttpServletRequest request, HttpServletResponse response)
- throws IOException {
-
- if (response.isCommitted()) {
- return;
- }
-
- String accept = request.getHeader(ACCEPT_HEADER);
- switch (accept != null ? accept : MediaType.APPLICATION_XML) {
- case MediaType.APPLICATION_JSON:
- response.setHeader(CONTENT_TYPE_HEADER, MediaType.APPLICATION_JSON);
- break;
- case MediaType.APPLICATION_XML:
- default:
- response.setHeader(CONTENT_TYPE_HEADER, MediaType.APPLICATION_XML);
- }
-
- response.setStatus(exception.getErrorObject().getHTTPResponseCode().getStatusCode());
- response.resetBuffer();
-
- String resp = ErrorLogHelper.getRESTAPIErrorResponse(Collections.singletonList(MediaType.valueOf(accept)),
- exception, new ArrayList<>());
- response.getOutputStream().print(resp);
- response.flushBuffer();
- }
-}
+++ /dev/null
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Modifications Copyright © 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.aai.aaf.auth.exceptions;
-
-import org.onap.aai.exceptions.AAIException;
-
-public class AAIUnrecognizedFunctionException extends AAIException {
-
- private static final String AAI_3012 = "AAI_3012";
- private static final long serialVersionUID = 3297064867724071290L;
-
- public AAIUnrecognizedFunctionException() {
- }
-
- public AAIUnrecognizedFunctionException(String message) {
- super(AAI_3012, message);
- }
-
- public AAIUnrecognizedFunctionException(Throwable cause) {
- super(AAI_3012, cause);
- }
-
- public AAIUnrecognizedFunctionException(String message, Throwable cause) {
- super(AAI_3012, cause, message);
- }
-}
+++ /dev/null
-/**
- * ============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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.aaf.filters;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.stream.Collectors;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.onap.aai.aaf.auth.ResponseFormatter;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.boot.web.servlet.filter.OrderedRequestContextFilter;
-import org.springframework.context.annotation.Profile;
-import org.springframework.context.annotation.PropertySource;
-import org.springframework.stereotype.Component;
-
-/**
- * AAF authorization filter
- */
-
-@Component
-@Profile(AafProfiles.AAF_AUTHENTICATION)
-@PropertySource(value = "file:${CONFIG_HOME}/aaf/permissions.properties", ignoreResourceNotFound = true)
-@PropertySource(value = "file:${server.local.startpath}/aaf/permissions.properties", ignoreResourceNotFound = true)
-public class AafAuthorizationFilter extends OrderedRequestContextFilter {
-
- private static final String ADVANCED = "advanced";
- private static final String BASIC = "basic";
-
- private final String type;
- private final String instance;
-
- private GremlinFilter gremlinFilter;
-
- private List<String> advancedKeywordsList;
-
- @Autowired
- public AafAuthorizationFilter(GremlinFilter gremlinFilter, @Value("${permission.type}") String type,
- @Value("${permission.instance}") String instance,
- @Value("${advanced.keywords.list:}") String advancedKeys) {
- this.gremlinFilter = gremlinFilter;
- this.type = type;
- this.instance = instance;
- if (advancedKeys == null || advancedKeys.isEmpty()) {
- this.advancedKeywordsList = new ArrayList<>();
- } else {
- this.advancedKeywordsList = Arrays.stream(advancedKeys.split(",")).collect(Collectors.toList());
- }
- this.setOrder(FilterPriority.AAF_AUTHORIZATION.getPriority());
- }
-
- @Override
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
- throws IOException, ServletException {
- if (request.getRequestURI().matches("^.*/util/echo$")) {
- filterChain.doFilter(request, response);
- }
- if (request.getRequestURI().endsWith("/query")) {
- gremlinFilter.doBasicAuthFilter(request, response, filterChain);
- } else {
-
- String permission = null;
-
- if (advancedKeywordsList == null || advancedKeywordsList.size() == 0) {
- permission = String.format("%s|%s|%s", type, instance, request.getMethod().toLowerCase());
- } else {
-
- boolean isAdvanced = this.containsAdvancedKeywords(request);
-
- // if the URI contains advanced.keywords it's an advanced query
- String queryType = isAdvanced ? ADVANCED : BASIC;
- permission = String.format("%s|%s|%s", type, instance, queryType);
- }
-
- boolean isAuthorized = request.isUserInRole(permission);
-
- if (!isAuthorized) {
- ResponseFormatter.errorResponse(request, response);
- } else {
- filterChain.doFilter(request, response);
- }
-
- }
- }
-
- private boolean containsAdvancedKeywords(HttpServletRequest request) {
- String uri = request.getRequestURI();
- for (String keyword : advancedKeywordsList) {
- if (uri.contains(keyword)) {
- return true;
- }
- }
- return false;
- }
-}
+++ /dev/null
-/**
- * ============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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.aaf.filters;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.stream.Collectors;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.onap.aai.aaf.auth.AafRequestFilter;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.boot.web.servlet.filter.OrderedRequestContextFilter;
-import org.springframework.context.annotation.Profile;
-import org.springframework.context.annotation.PropertySource;
-import org.springframework.stereotype.Component;
-
-/**
- * AAF with client cert authorization filter
- */
-
-@Component
-@Profile(AafProfiles.AAF_CERT_AUTHENTICATION)
-@PropertySource(value = "file:${CONFIG_HOME}/aaf/permissions.properties", ignoreResourceNotFound = true)
-@PropertySource(value = "file:${server.local.startpath}/aaf/permissions.properties", ignoreResourceNotFound = true)
-public class AafCertAuthorizationFilter extends OrderedRequestContextFilter {
-
- private static final String ADVANCED = "advanced";
- private static final String BASIC = "basic";
-
- String type;
-
- String instance;
-
- private CadiProps cadiProps;
-
- private List<String> advancedKeywordsList;
-
- @Autowired
- public AafCertAuthorizationFilter(@Value("${permission.type}") String type,
- @Value("${permission.instance}") String instance, @Value("${advanced.keywords.list:}") String advancedKeys,
- CadiProps cadiProps) {
- this.type = type;
- this.instance = instance;
- this.cadiProps = cadiProps;
- if (advancedKeys == null || advancedKeys.isEmpty()) {
- this.advancedKeywordsList = new ArrayList<>();
- } else {
- this.advancedKeywordsList = Arrays.stream(advancedKeys.split(",")).collect(Collectors.toList());
- }
- this.setOrder(FilterPriority.AAF_CERT_AUTHORIZATION.getPriority());
- }
-
- @Override
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
- throws IOException, ServletException {
- if (advancedKeywordsList == null || advancedKeywordsList.size() == 0) {
- String permission = String.format("%s|%s|%s", type, instance, request.getMethod().toLowerCase());
- AafRequestFilter.authorizationFilter(request, response, filterChain, permission,
- cadiProps.getCadiProperties());
- } else {
- boolean isAdvanced = this.containsAdvancedKeywords(request);
-
- // if the URI contains advanced.keywords it's an advanced query
- String queryType = isAdvanced ? ADVANCED : BASIC;
- String permission = String.format("%s|%s|%s", type, instance, queryType);
- AafRequestFilter.authorizationFilter(request, response, filterChain, permission,
- cadiProps.getCadiProperties());
- }
- }
-
- private boolean containsAdvancedKeywords(HttpServletRequest request) {
- String uri = request.getRequestURI();
- for (String keyword : advancedKeywordsList) {
- if (uri.contains(keyword)) {
- return true;
- }
- }
- return false;
- }
-}
+++ /dev/null
-/**
- * ============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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.aaf.filters;
-
-import java.io.IOException;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.onap.aaf.cadi.PropAccess;
-import org.onap.aaf.cadi.filter.CadiFilter;
-import org.onap.aai.aaf.auth.AafRequestFilter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.boot.web.servlet.filter.OrderedRequestContextFilter;
-import org.springframework.context.annotation.Profile;
-import org.springframework.context.annotation.PropertySource;
-import org.springframework.stereotype.Component;
-
-/**
- * AAF with client cert authentication filter
- */
-
-@Component
-@Profile(AafProfiles.AAF_CERT_AUTHENTICATION)
-@PropertySource(value = "file:${CONFIG_HOME}/aaf/permissions.properties", ignoreResourceNotFound = true)
-@PropertySource(value = "file:${server.local.startpath}/aaf/permissions.properties", ignoreResourceNotFound = true)
-public class AafCertFilter extends OrderedRequestContextFilter {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(AafCertFilter.class);
-
- String aafUserChainPattern;
-
- private final CadiFilter cadiFilter;
-
- private final CadiProps cadiProps;
-
- @Autowired
- public AafCertFilter(@Value("${aaf.userchain.pattern}") String aafUserChainPattern, CadiProps cadiProps)
- throws IOException, ServletException {
-
- this.aafUserChainPattern = aafUserChainPattern;
- this.cadiProps = cadiProps;
- cadiFilter = new CadiFilter(new PropAccess((level, element) -> {
- switch (level) {
- case DEBUG:
- LOGGER.debug(buildMsg(element));
- break;
- case INFO:
- case AUDIT:
- LOGGER.info(buildMsg(element));
- break;
- case WARN:
- LOGGER.warn(buildMsg(element));
- break;
- case ERROR:
- LOGGER.error(buildMsg(element));
- break;
- case INIT:
- LOGGER.info(buildMsg(element));
- break;
- case TRACE:
- LOGGER.trace(buildMsg(element));
- break;
- case NONE:
- break;
- }
- }, new String[] {"cadi_prop_files=" + cadiProps.getCadiFileName()}));
- this.setOrder(FilterPriority.AAF_CERT_AUTHENTICATION.getPriority());
- }
-
- @Override
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
- throws IOException, ServletException {
- AafRequestFilter.authenticationFilter(request, response, filterChain, cadiFilter, cadiProps.getCadiProperties(),
- aafUserChainPattern);
- }
-
- private String buildMsg(Object[] objects) {
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- for (Object o : objects) {
- if (first) {
- first = false;
- } else {
- sb.append(' ');
- }
- sb.append(o.toString());
- }
- return (sb.toString());
- }
-}
+++ /dev/null
-/**
- * ============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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.aaf.filters;
-
-import java.io.IOException;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.onap.aaf.cadi.PropAccess;
-import org.onap.aaf.cadi.filter.CadiFilter;
-import org.onap.aai.aaf.auth.ResponseFormatter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.web.servlet.filter.OrderedRequestContextFilter;
-import org.springframework.context.annotation.Profile;
-import org.springframework.stereotype.Component;
-
-/**
- * AAF authentication filter
- */
-
-@Component
-@Profile(AafProfiles.AAF_AUTHENTICATION)
-public class AafFilter extends OrderedRequestContextFilter {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(AafCertFilter.class);
-
- private final CadiFilter cadiFilter;
-
- @Autowired
- public AafFilter(CadiProps cadiProps) throws IOException, ServletException {
- cadiFilter = new CadiFilter(new PropAccess((level, element) -> {
- switch (level) {
- case DEBUG:
- LOGGER.debug(buildMsg(element));
- break;
- case INFO:
- case AUDIT:
- LOGGER.info(buildMsg(element));
- break;
- case WARN:
- LOGGER.warn(buildMsg(element));
- break;
- case ERROR:
- LOGGER.error(buildMsg(element));
- break;
- case INIT:
- LOGGER.info(buildMsg(element));
- break;
- case TRACE:
- LOGGER.trace(buildMsg(element));
- break;
- case NONE:
- break;
- }
- }, new String[] {"cadi_prop_files=" + cadiProps.getCadiFileName()}));
- 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() == 401 || response.getStatus() == 403) {
- ResponseFormatter.errorResponse(request, response);
- }
- } else {
- filterChain.doFilter(request, response);
- }
- }
-
- private String buildMsg(Object[] objects) {
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- for (Object o : objects) {
- if (first) {
- first = false;
- } else {
- sb.append(' ');
- }
- sb.append(o.toString());
- }
- return (sb.toString());
- }
-}
+++ /dev/null
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2019 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.aaf.filters;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
-import javax.annotation.PostConstruct;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Profile;
-import org.springframework.stereotype.Component;
-
-// This component will be created if and only if any of the following profiles are active
-@Component
-@Profile({AafProfiles.AAF_CERT_AUTHENTICATION, AafProfiles.AAF_AUTHENTICATION, AafProfiles.TWO_WAY_SSL})
-public class CadiProps {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(CadiProps.class);
-
- private String cadiFileName;
-
- private Properties cadiProperties;
-
- @Autowired
- public CadiProps(@Value("${aaf.cadi.file:./resources/cadi.properties}") String filename) {
- cadiFileName = filename;
- cadiProperties = new Properties();
- }
-
- @PostConstruct
- public void init() throws IOException {
-
- File cadiFile = new File(cadiFileName);
-
- if (!cadiFile.exists()) {
- LOGGER.warn("Unable to find the cadi file in the given path {} so loading cadi.properties from classloader",
- cadiFileName);
- InputStream is = this.getClass().getClassLoader().getResourceAsStream("cadi.properties");
- cadiProperties.load(is);
- } else {
- LOGGER.info("Successfully found the file {} and started loading the properties from it", cadiFileName);
- cadiFileName = cadiFile.getAbsolutePath();
- try (InputStream inputStream = new FileInputStream(cadiFile)) {
- cadiProperties.load(inputStream);
- }
-
- }
- }
-
- public String getCadiFileName() {
- return cadiFileName;
- }
-
- public Properties getCadiProperties() {
- return cadiProperties;
- }
-}
+++ /dev/null
-/**
- * ============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.aaf.filters;
-
-import org.springframework.core.Ordered;
-
-public enum FilterPriority {
-
- AAF_AUTHENTICATION(Ordered.HIGHEST_PRECEDENCE), AAF_AUTHORIZATION(Ordered.HIGHEST_PRECEDENCE + 1), // higher number
- // = lower
- // priority
- AAF_CERT_AUTHENTICATION(Ordered.HIGHEST_PRECEDENCE + 2), AAF_CERT_AUTHORIZATION(
- Ordered.HIGHEST_PRECEDENCE + 3), TWO_WAY_SSL_AUTH(Ordered.HIGHEST_PRECEDENCE + 4);
-
- private final int priority;
-
- FilterPriority(final int p) {
- priority = p;
- }
-
- public int getPriority() {
- return priority;
- }
-}
+++ /dev/null
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2019 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.aaf.filters;
-
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.util.regex.Pattern;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.io.IOUtils;
-import org.onap.aai.aaf.auth.ResponseFormatter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Profile;
-import org.springframework.stereotype.Component;
-
-@Component
-@Profile({AafProfiles.AAF_CERT_AUTHENTICATION, AafProfiles.AAF_AUTHENTICATION})
-public class GremlinFilter {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(GremlinFilter.class);
-
- private static final String ADVANCED = "advanced";
- private static final String BASIC = "basic";
- private static final Pattern ECHO_ENDPOINT = Pattern.compile("^.*/util/echo$");
-
- String type;
-
- String instance;
-
- private CadiProps cadiProps;
-
- @Autowired
- public GremlinFilter(@Value("${permission.type}") String type, @Value("${permission.instance}") String instance,
- CadiProps cadiProps) {
- this.type = type;
- this.instance = instance;
- this.cadiProps = cadiProps;
- }
-
- public void doBasicAuthFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
- throws IOException, ServletException {
- PayloadBufferingRequestWrapper requestBufferWrapper = new PayloadBufferingRequestWrapper(request);
-
- if (ECHO_ENDPOINT.matcher(request.getRequestURI()).matches()) {
- filterChain.doFilter(requestBufferWrapper, response);
- }
-
- String payload = IOUtils.toString(requestBufferWrapper.getInputStream(), StandardCharsets.UTF_8.name());
- boolean containsWordGremlin = payload.contains("\"gremlin\"");
-
- // if the requestBufferWrapper contains the word "gremlin" it's an "advanced" query needing an "advanced" role
- String permissionBasic = String.format("%s|%s|%s", type, instance, BASIC);
- String permissionAdvanced = String.format("%s|%s|%s", type, instance, ADVANCED);
-
- boolean isAuthorized;
-
- if (containsWordGremlin) {
- isAuthorized = requestBufferWrapper.isUserInRole(permissionAdvanced);
- } else {
- isAuthorized = requestBufferWrapper.isUserInRole(permissionAdvanced)
- || requestBufferWrapper.isUserInRole(permissionBasic);
- }
-
- if (!isAuthorized) {
- String name =
- requestBufferWrapper.getUserPrincipal() != null ? requestBufferWrapper.getUserPrincipal().getName()
- : "unknown";
- LOGGER.info("User " + name + " does not have a role for "
- + (containsWordGremlin ? "gremlin" : "non-gremlin") + " query");
- ResponseFormatter.errorResponse(request, response);
- } else {
- filterChain.doFilter(requestBufferWrapper, response);
- }
- }
-}
+++ /dev/null
-/**
- * ============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.aaf.filters;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-
-import javax.servlet.ServletInputStream;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletRequestWrapper;
-
-import org.apache.commons.io.IOUtils;
-import org.onap.aaf.cadi.BufferedServletInputStream;
-
-/**
- * This class buffers the payload of the servlet request. The reason is that we access the payload multiple times,
- * which is not supported by the request per se.
- */
-
-class PayloadBufferingRequestWrapper extends HttpServletRequestWrapper {
-
- private byte[] buffer;
-
- PayloadBufferingRequestWrapper(HttpServletRequest req) throws IOException {
- super(req);
- this.buffer = IOUtils.toByteArray(req.getInputStream());
- }
-
- @Override
- public ServletInputStream getInputStream() {
- ByteArrayInputStream bais = new ByteArrayInputStream(this.buffer);
- return new BufferedServletInputStream(bais);
- }
-}
+++ /dev/null
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2019 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.aaf.filters;
-
-import java.io.IOException;
-import java.security.cert.X509Certificate;
-import java.util.*;
-
-import javax.security.auth.x500.X500Principal;
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.onap.aai.aaf.auth.AAIAuthCore;
-import org.onap.aai.aaf.auth.CertUtil;
-import org.onap.aai.aaf.auth.ResponseFormatter;
-import org.onap.aai.exceptions.AAIException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.web.servlet.filter.OrderedRequestContextFilter;
-import org.springframework.context.annotation.Profile;
-import org.springframework.core.env.Environment;
-import org.springframework.stereotype.Component;
-
-@Component
-@Profile("two-way-ssl")
-public class TwoWaySslAuthorization extends OrderedRequestContextFilter {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(TwoWaySslAuthorization.class);
-
- public static final String HTTP_METHOD_OVERRIDE = "X-HTTP-Method-Override";
-
- public static final String MERGE_PATCH = "MERGE_PATCH";
-
- @Autowired
- private Environment environment;
-
- @Autowired
- private AAIAuthCore aaiAuthCore;
-
- @Autowired
- private CadiProps cadiProps;
-
- public TwoWaySslAuthorization() {
- this.setOrder(FilterPriority.TWO_WAY_SSL_AUTH.getPriority());
- }
-
- @Override
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
- throws IOException, ServletException {
-
- String uri = request.getRequestURI();
- String httpMethod = getHttpMethod(request);
-
- Optional<String> authUser = getUser(request);
-
- if (authUser.isPresent()) {
- Properties cadiProperties = cadiProps.getCadiProperties();
-
- String issuer = CertUtil.getCertIssuer(request);
- if (issuer == null || issuer.isEmpty()) {
- AAIException aaie = new AAIException("AAI_9107");
- ResponseFormatter.errorResponse(aaie, request, response);
- return;
- }
- issuer = issuer.replaceAll("\\s+", "").toUpperCase();
-
- List<String> cadiConfiguredIssuers = CertUtil.getCadiCertIssuers(cadiProperties);
- boolean isAafAuthProfileActive = this.isAafAuthProfileActive();
- if ((!isAafAuthProfileActive) || (!cadiConfiguredIssuers.contains(issuer))) {
- try {
- this.authorize(uri, httpMethod, authUser.get(), this.getHaProxyUser(request), issuer);
- } catch (AAIException e) {
- ResponseFormatter.errorResponse(e, request, response);
- return;
- }
- }
- } else {
- AAIException aaie = new AAIException("AAI_9107");
- ResponseFormatter.errorResponse(aaie, request, response);
- return;
- }
- filterChain.doFilter(request, response);
- }
-
- private String getHttpMethod(HttpServletRequest request) {
- String httpMethod = request.getMethod();
- if ("POST".equalsIgnoreCase(httpMethod) && "PATCH".equals(request.getHeader(HTTP_METHOD_OVERRIDE))) {
- httpMethod = MERGE_PATCH;
- }
- if (httpMethod.equalsIgnoreCase(MERGE_PATCH) || "patch".equalsIgnoreCase(httpMethod)) {
- httpMethod = "PUT";
- }
- return httpMethod;
- }
-
- private Optional<String> getUser(HttpServletRequest hsr) {
- String authUser = null;
- if (hsr.getAttribute("javax.servlet.request.cipher_suite") != null) {
- X509Certificate[] certChain = (X509Certificate[]) hsr.getAttribute("javax.servlet.request.X509Certificate");
-
- /*
- * If the certificate is null or the certificate chain length is zero Then
- * retrieve the authorization in the request header Authorization Check that it
- * is not null and that it starts with Basic and then strip the basic portion to
- * get the base64 credentials Check if this is contained in the AAIBasicAuth
- * Singleton class If it is, retrieve the username associated with that
- * credentials and set to authUser Otherwise, get the principal from certificate
- * and use that authUser
- */
-
- if (certChain == null || certChain.length == 0) {
-
- String authorization = hsr.getHeader("Authorization");
-
- if (authorization != null && authorization.startsWith("Basic ")) {
- authUser = authorization.replace("Basic ", "");
- }
-
- } else {
- X509Certificate clientCert = certChain[0];
- X500Principal subjectDN = clientCert.getSubjectX500Principal();
- authUser = subjectDN.toString().toLowerCase();
- }
- }
-
- return Optional.ofNullable(authUser);
- }
-
- private String getHaProxyUser(HttpServletRequest hsr) {
- String haProxyUser;
- if (Objects.isNull(hsr.getHeader("X-AAI-SSL-Client-CN")) || Objects.isNull(hsr.getHeader("X-AAI-SSL-Client-OU"))
- || Objects.isNull(hsr.getHeader("X-AAI-SSL-Client-O"))
- || Objects.isNull(hsr.getHeader("X-AAI-SSL-Client-L"))
- || Objects.isNull(hsr.getHeader("X-AAI-SSL-Client-ST"))
- || Objects.isNull(hsr.getHeader("X-AAI-SSL-Client-C"))) {
- haProxyUser = "";
- } else {
- haProxyUser = String.format("CN=%s, OU=%s, O=\"%s\", L=%s, ST=%s, C=%s",
- Objects.toString(hsr.getHeader("X-AAI-SSL-Client-CN"), ""),
- Objects.toString(hsr.getHeader("X-AAI-SSL-Client-OU"), ""),
- Objects.toString(hsr.getHeader("X-AAI-SSL-Client-O"), ""),
- Objects.toString(hsr.getHeader("X-AAI-SSL-Client-L"), ""),
- Objects.toString(hsr.getHeader("X-AAI-SSL-Client-ST"), ""),
- Objects.toString(hsr.getHeader("X-AAI-SSL-Client-C"), "")).toLowerCase();
- }
- return haProxyUser;
- }
-
- private void authorize(String uri, String httpMethod, String authUser, String haProxyUser, String issuer)
- throws AAIException {
- if (!aaiAuthCore.authorize(authUser, uri, httpMethod, haProxyUser, issuer)) {
- throw new AAIException("AAI_9101", "Request on " + httpMethod + " " + uri + " status is not OK");
- }
- }
-
- private boolean isAafAuthProfileActive() {
- String[] profiles = environment.getActiveProfiles();
- if (profiles != null) {
- if (Arrays.stream(profiles).anyMatch(env -> (env.equalsIgnoreCase(AafProfiles.AAF_CERT_AUTHENTICATION)))) {
- return true;
- }
- }
- return false;
- }
-}
+++ /dev/null
-/**
- * ============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.aaf.auth;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.aai.aaf.auth.exceptions.AAIUnrecognizedFunctionException;
-
-public class AAIAuthCoreTest extends AAISetup {
-
- private AAIAuthCore authCore;
-
- @Before
- public void setup() {
- authCore = new AAIAuthCore("/aai");
- }
-
- @Test
- public void getAuthPolicyFunctionNameTest() {
-
- String uri = "/aai/v3/search/edge-tag-query";
- assertEquals("Get aai function name from " + uri, "search", authCore.getAuthPolicyFunctName(uri));
-
- uri = "/aai/v10/search/edge-tag-query";
- assertEquals("Get aai function name from " + uri, "search", authCore.getAuthPolicyFunctName(uri));
-
- uri = "/aai/search/model";
- assertEquals("Get aai function name from " + uri, "search", authCore.getAuthPolicyFunctName(uri));
-
- uri = "/aai/v9/cloud-infrastructure/cloud-regions/cloud-region/somecloudregion/some-cloud-owner";
- assertEquals("Get aai function name from " + uri, "cloud-infrastructure", authCore.getAuthPolicyFunctName(uri));
-
- uri = "/aai/v8/network/pnfs/pnf/ff4ca01orc/p-interfaces";
- assertEquals("Get aai function name from " + uri, "network", authCore.getAuthPolicyFunctName(uri));
-
- uri = "/aai/util/echo";
- assertEquals("Get aai function name from " + uri, "util", authCore.getAuthPolicyFunctName(uri));
-
- uri = "/aai/tools";
- assertEquals("Get aai function name from " + uri, "tools", authCore.getAuthPolicyFunctName(uri));
-
- uri = "/aai/v12/bulk/single-transaction";
- assertEquals("Get aai function name from " + uri, "bulk", authCore.getAuthPolicyFunctName(uri));
-
- }
-
- @Test
- public void validUsernameAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("testUser".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", ""));
- }
-
- @Test
- public void validUsernameInvalidHttpMethodAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("testUser".toLowerCase(), "/aai/v0/testFunction/someUri", "POST", ""));
- }
-
- @Test(expected = AAIUnrecognizedFunctionException.class)
- public void validUsernameInvalidFunctionInURIAuthTest() throws AAIUnrecognizedFunctionException {
- authCore.authorize("testUser".toLowerCase(), "/aai/v0/badFunction/someUri", "PUT", "");
- }
-
- @Test
- public void invalidUsernameAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("invlaidTestUser".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", ""));
- }
-
- @Test
- public void validUsernameIsTheExactWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("testWildcardId".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", ""));
- }
-
- @Test
- public void validUsernameContainsTheWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("cn=blah, testWildcardId, O=".toLowerCase(), "/aai/v0/testFunction/someUri",
- "PUT", "", "aafWildCardIssuer"));
- }
-
- @Test
- public void validUsernameContainsTheWildcardIdInvalidIssuerAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("cn=blah, testWildcardId, O=".toLowerCase(), "/aai/v0/testFunction/someUri",
- "PUT", "", "invalidIssuer"));
- }
-
- @Test
- public void invalidUsernameContainsRegularUsernameAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(
- authCore.authorize("cn=blah, testUser, O=".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", ""));
- }
-
- @Test
- public void haProxyUsernameAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/util/echo", "GET", ""));
- }
-
- @Test
- public void haProxyUsernameInvalidFunctionAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", ""));
- }
-
- @Test
- public void validUsernameViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT",
- "testUser".toLowerCase()));
- }
-
- @Test
- public void validUsernameInvalidHttpMethodViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "POST",
- "testUser".toLowerCase()));
- }
-
- @Test(expected = AAIUnrecognizedFunctionException.class)
- public void validUsernameInvalidFunctionInURIViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException {
- authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/badFunction/someUri", "PUT",
- "testUser".toLowerCase());
- }
-
- @Test
- public void invalidUsernameViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT",
- "invlaidTestUser".toLowerCase()));
- }
-
- @Test
- public void validUsernameIsTheExactWildcardIdViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT",
- "testWildcardId".toLowerCase()));
- }
-
- @Test
- public void validUsernameContainsTheWildcardIdViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT",
- "cn=blah, testWildcardId, O=".toLowerCase(), "aafWildCardIssuer"));
- }
-
- @Test
- public void invalidUsernameContainsRegularUsernameViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT",
- "cn=blah, testUser, O=".toLowerCase()));
- }
-
- @Test
- public void haProxyUsernameTwiceAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT",
- "ha-proxy-user".toLowerCase()));
- }
-
- @Test
- public void haProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/util/echo", "GET", "",
- "aafWildCardIssuer"));
- }
-
- @Test
- public void haProxyWildcardIdInvalidFunctionAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(),
- "/aai/v0/testFunction/someUri", "PUT", ""));
- }
-
- @Test
- public void validUsernameViaHaProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri",
- "PUT", "testUser".toLowerCase(), "aafWildCardIssuer"));
- }
-
- @Test
- public void validUsernameInvalidHttpMethodViaHaProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(),
- "/aai/v0/testFunction/someUri", "POST", "testUser".toLowerCase()));
- }
-
- @Test(expected = AAIUnrecognizedFunctionException.class)
- public void validUsernameInvalidFunctionInURIViaHaProxyWildcardIdAuthTest()
- throws AAIUnrecognizedFunctionException {
- authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/badFunction/someUri", "PUT",
- "testUser".toLowerCase());
- }
-
- @Test
- public void invalidUsernameViaHaProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(),
- "/aai/v0/testFunction/someUri", "PUT", "invlaidTestUser".toLowerCase()));
- }
-
- @Test
- public void validUsernameIsTheExactWildcardIdViaHaProxyWildcardIdAuthTest()
- throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri",
- "PUT", "testWildcardId".toLowerCase(), "aafWildCardIssuer"));
- }
-
- @Test
- public void validUsernameContainsTheWildcardIdViaHaProxyWildcardIdAuthTest()
- throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri",
- "PUT", "cn=blah, testWildcardId, O=".toLowerCase(), "aafWildCardIssuer"));
- }
-
- @Test
- public void validUsernameContainsTheWildcardIdViaHaProxyWildcardIdInvalidIssuerAuthTest()
- throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(),
- "/aai/v0/testFunction/someUri", "PUT", "cn=blah, testWildcardId, O=".toLowerCase(), "invalidIssuer"));
- }
-
- @Test
- public void invalidUsernameContainsRegularUsernameViaHaProxyWildcardIdAuthTest()
- throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(),
- "/aai/v0/testFunction/someUri", "PUT", "cn=blah, testUser, O=".toLowerCase()));
- }
-
-}
+++ /dev/null
-/**
- * ============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.aaf.auth;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-
-public class AAIUserTest extends AAISetup {
-
- @Test
- public void testIsAuth() {
- AAIUser usr = new AAIUser("testUser");
- usr.addRole("testRole");
- usr.setUserAccess("auth", "GET");
- usr.setUserAccess("auth", "PUT");
- usr.setUserAccess("authentication", "PUT", "GET", "POST");
-
- assertEquals(true, usr.hasAccess("auth", "GET"));
- assertEquals(true, usr.hasAccess("auth", "PUT"));
- assertEquals(true, usr.hasAccess("authentication", "POST"));
- }
-
- @Test
- public void testIsNotAuth() {
- AAIUser usr = new AAIUser("testUser");
- usr.addRole("testRole");
-
- assertEquals(false, usr.hasAccess("auth", "GET"));
-
- usr.setUserAccess("auth", "GET");
- assertEquals(false, usr.hasAccess("auth", "PUT"));
- }
-
-}
+++ /dev/null
-/*-
- * ============LICENSE_START============================================
- * ONAP Portal
- * =====================================================================
- * Copyright (C) 2020 IBM Intellectual Property. All rights reserved.
- * =====================================================================
- *
- * Unless otherwise specified, all software contained herein is licensed
- * under the Apache License, Version 2.0 (the "License");
- * you may not use this software 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.
- *
- * Unless otherwise specified, all documentation contained herein is licensed
- * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
- * you may not use this documentation except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://creativecommons.org/licenses/by/4.0/
- *
- * Unless required by applicable law or agreed to in writing, documentation
- * 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.aaf.auth;
-
-import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertEquals;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.junit.Test;
-
-public class AafRequestWrapperTest {
-
- @Test
- public void testGetHeader() {
- HttpServletRequest mockRequest = createMock(HttpServletRequest.class);
- expect(mockRequest.getHeader(CertUtil.AAI_SSL_CLIENT_OU_HDR)).andReturn("m55555@org.onap.com:TEST").times(1, 4);
- replay(mockRequest);
- AafRequestWrapper af = new AafRequestWrapper(mockRequest);
- assertEquals(af.getHeader("X-AAI-SSL-Client-OU"), "m55555@org.onap.com:TEST");
- af.putHeader("X-AAI-SSL-Client-C", "test@org.onap.com:test");
- assertEquals(af.getHeader("X-AAI-SSL-Client-C"), "test@org.onap.com:test");
- }
-}
+++ /dev/null
-/**
- * ============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.aaf.auth;
-
-import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.util.List;
-import java.util.Properties;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.junit.Test;
-
-/**
- * The Class CertUtilTest
- */
-public class CertUtilTest extends AAISetup {
-
- @Test
- public void testCadiCertIssuers() throws IOException {
- String propFile = System.getProperty("BUNDLECONFIG_DIR") + "/aaf/cadi.properties";
- Properties cadiProperties = new Properties();
- cadiProperties.load(new FileInputStream(new File(propFile)));
-
- List<String> issuersList = CertUtil.getCadiCertIssuers(cadiProperties);
- assertTrue("issuersList isn't populated", !issuersList.isEmpty());
-
- int x = issuersList.get(0).indexOf(" ");
- assertTrue("issuer contains spaces", x < 0);
- }
-
- @Test
- public void testAaiSslClientOuHeader() {
-
- HttpServletRequest mockRequest = createMock(HttpServletRequest.class);
- expect(mockRequest.getHeader(CertUtil.AAI_SSL_CLIENT_OU_HDR)).andReturn("m55555@org.onap.com:TEST").times(1, 4);
- expect(mockRequest.getHeader(CertUtil.AAI_SSL_CLIENT_CN_HDR)).andReturn("CN").times(1, 2);
- expect(mockRequest.getHeader(CertUtil.AAI_SSL_CLIENT_O_HDR)).andReturn("O").times(1, 2);
- expect(mockRequest.getHeader(CertUtil.AAI_SSL_CLIENT_L_HDR)).andReturn("L").times(1, 2);
- expect(mockRequest.getHeader(CertUtil.AAI_SSL_CLIENT_ST_HDR)).andReturn("ST").times(1, 2);
- expect(mockRequest.getHeader(CertUtil.AAI_SSL_CLIENT_C_HDR)).andReturn("C").times(1, 2);
-
- replay(mockRequest);
- String ou = CertUtil.getAaiSslClientOuHeader(mockRequest);
- assertTrue("OU Header value is not as expected", ou.equals("m55555@org.onap.com:TEST"));
-
- assertTrue("Unexpected isHaProxy() return value", CertUtil.isHaProxy(mockRequest));
-
- String mechId = CertUtil.getMechId(mockRequest);
- assertTrue("mechid value is not as expected", mechId.equals("m55555@org.onap.com"));
-
- }
-
- @Test
- public void testBuildUserChain() {
-
- // aaf.userchain.pattern=<AAF-ID>:${aaf.userchain.service.reference}:${aaf.userchain.auth.type}:AS
- String aafUserChainPattern = "<AAF-ID>:org.onap.haproxy:X509:AS";
- String mechid = "m11111@onap.org";
- String result = CertUtil.buildUserChainHeader(mechid, aafUserChainPattern);
-
- assertTrue("user chain value is not as expected", "m11111@onap.org:org.onap.haproxy:X509:AS".equals(result));
-
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START==========================================
- * ONAP Portal
- * ===================================================================
- * Copyright (C) 2020 IBM Intellectual Property. All rights reserved.
- * ===================================================================
- *
- * Unless otherwise specified, all software contained herein is licensed
- * under the Apache License, Version 2.0 (the "License");
- * you may not use this software 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.
- *
- * Unless otherwise specified, all documentation contained herein is licensed
- * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
- * you may not use this documentation except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://creativecommons.org/licenses/by/4.0/
- *
- * Unless required by applicable law or agreed to in writing, documentation
- * 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.aaf.filters;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import org.junit.Test;
-import org.springframework.beans.factory.annotation.Autowired;
-
-public class CadiPropsTest {
- @Autowired
- CadiProps ca = new CadiProps("src/test/resources/bundleconfig-local/aaf/org.onap.aai.props");
-
- @Test
- public void testGetCadiFileName() {
- assertEquals(ca.getCadiFileName(), "src/test/resources/bundleconfig-local/aaf/org.onap.aai.props");
- assertNotNull(ca.getCadiProperties());
- }
-}
+++ /dev/null
-## Location properties
-##
-## Localized Machine Information
-##
-cadi_loglevel=DEBUG
-cadi_latitude=38.0
-cadi_longitude=-72.0
-
-# Locate URL (which AAF Env) - Use lower case
-aaf_locate_url=https://aafist.test.org:8095
-# AAF URL - Use upper case
-aaf_url=https://AAF_LOCATE_URL/service:2.0
-#
-cadi_prop_files=src/test/resources/bundleconfig-local/aaf/org.onap.aai.props
+++ /dev/null
-cm_url=cm_url
-hostname=hostname
-aaf_env=IST
-cadi_x509_issuers=CN=AAF CADI Test Issuing CA 01, OU=CSO, O=CO, C=US:CN=AAF CADI Test Issuing CA 02, OU=CSO, O=CO, C=US
\ No newline at end of file
+++ /dev/null
-#
-# ============LICENSE_START=======================================================
-# org.onap.aai
-# ================================================================================
-# Copyright © 2017 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=========================================================
-
-aai.config.checktime=1000
-
-# this could come from siteconfig.pl?
-aai.config.nodename=AutomaticallyOverwritten
-
-aai.transaction.logging=true
-aai.transaction.logging.get=true
-aai.transaction.logging.post=true
-
-aai.server.url.base=https://localhost:8443/aai/
-aai.server.url=https://localhost:8443/aai/v10/
-aai.oldserver.url.base=https://localhost:8443/aai/servers/
-aai.oldserver.url=https://localhost:8443/aai/servers/v2/
-aai.global.callback.url=https://localhost:8443/aai/
-
-aai.notification.current.version=v10
-aai.notificationEvent.default.status=UNPROCESSED
-aai.notificationEvent.default.eventType=AAI-EVENT
-aai.notificationEvent.default.domain=devINT1
-aai.notificationEvent.default.sourceName=aai
-aai.notificationEvent.default.sequenceNumber=0
-aai.notificationEvent.default.severity=NORMAL
-aai.notificationEvent.default.version=v10
-# This one lets us enable/disable resource-version checking on updates/deletes
-aai.resourceversion.enableflag=true
-aai.default.api.version=v10
-
-aai.example.passwd.x=OBF:1vn21ugu1saj1v9i1v941sar1ugw1vo0
-aai.example.string=hello
-aai.example.int=7748
-
-aai.realtime.clients=RO,SDNC,SO
-
-aai.jms.enable=false
-
-aai.rest.getall.depthparam=someuuid
-
-aaf.valid.issuer.wildcard=aaf wild card issuer|aafWildCardIssuer|OU=another
-
+++ /dev/null
-# Adding comment trying to trigger a build
-#------------------------------------------------------------------------------- ----------
-#Key=Disposition:Category:Severity:Error Code:HTTP ResponseCode:RESTError Code:Error Message
-#------------------------------------------------------------------------------- ----------
-# testing code, please don't change unless error utility source code changes
-AAI_TESTING=5:2:WARN:0000:400:0001:Error code for testing
-
-# General success
-AAI_0000=0:0:INFO:0000:200:0000:Success
-
-# health check success
-AAI_0001=0:0:INFO:0001:200:0001:Success X-FromAppId=%1 X-TransactionId=%2
-AAI_0002=0:0:INFO:0002:200:0001:Successful health check
-
-# Success with additional info
-AAI_0003=0:3:INFO:0003:202:0003:Success with additional info performing %1 on %2. Added %3 with key %4
-AAI_0004=0:3:INFO:0004:202:0003:Added prerequisite object to db
-
-#--- aairest: 3000-3299
-# svc errors
-AAI_3000=5:2:INFO:3000:400:3000:Invalid input performing %1 on %2
-AAI_3001=5:6:INFO:3001:404:3001:Resource not found for %1 using id %2
-AAI_3002=5:1:WARN:3002:400:3002:Error writing output performing %1 on %2
-AAI_3003=5:1:WARN:3003:400:3003:Failed to make edge to missing target node of type %3 with keys %4 performing %1 on %2
-AAI_3005=5:6:WARN:3005:404:3001:Node cannot be directly accessed for read, must be accessed via ancestor(s)
-AAI_3006=5:6:WARN:3006:404:3001:Node cannot be directly accessed for write, must be accessed via ancestor(s)
-AAI_3007=5:6:INFO:3007:410:3007:This version (%1) of the API is retired, please migrate to %2
-AAI_3008=5:6:ERROR:3008:400:3008:URI is not encoded in UTF-8
-AAI_3009=5:6:ERROR:3009:400:3002:Malformed URL
-# pol errors
-AAI_3100=5:1:WARN:3100:400:3100:Unsupported operation %1
-AAI_3101=5:1:WARN:3101:403:3101:Attempt by client %1 to execute API %2
-AAI_3102=5:1:WARN:3102:400:3102:Error parsing input performing %1 on %2
-AAI_3300=5:1:WARN:3300:403:3300:Unauthorized
-AAI_3301=5:1:WARN:3301:401:3301:Stale credentials
-AAI_3302=5:1:WARN:3302:401:3301:Not authenticated
-AAI_3303=5:1:ERROR:3303:403:3300:Too many objects would be returned by this request, please refine your request and retry
-
-#--- aaigen: 4000-4099
-AAI_4000=5:4:ERROR:4000:500:3002:Internal Error
-AAI_4001=5:4:FATAL:4001:500:3002:Configuration file not found
-AAI_4002=5:4:FATAL:4002:500:3002:Error reading Configuration file
-AAI_4003=5:4:ERROR:4003:500:3002:Error writing to log file
-AAI_4004=5:4:FATAL:4004:500:3002:Error reading/parsing the error properties file
-AAI_4005=5:4:FATAL:4005:500:3002:Missing or invalid configuration parameter
-AAI_4006=5:4:FATAL:4006:500:3002:Unexpected error in service
-AAI_4007=5:4:ERROR:4007:500:3102:Input parsing error
-AAI_4008=5:4:ERROR:4008:500:3002:Output parsing error
-AAI_4009=4:0:ERROR:4009:400:3000:Invalid X-FromAppId in header
-AAI_4010=4:0:ERROR:4010:400:3000:Invalid X-TransactionId in header
-AAI_4011=5:4:ERROR:4011:500:3002:Missing data for REST error response
-AAI_4014=4:0:ERROR:4014:400:3000:Invalid Accept header
-AAI_4015=4:0:ERROR:4015:400:3000:You must provide at least one indexed property
-AAI_4016=4:0:ERROR:4016:400:3000:The depth parameter must be a number or the string "all"
-AAI_4017=5:2:INFO:4017:400:3000:Could not set property
-AAI_4018=5:2:ERROR:4018:400:3000:Unable to convert the string to integer
-#--- aaidbmap: 5102-5199
-AAI_5102=5:4:FATAL:5102:500:3002:Graph database is null after open
-AAI_5105=5:4:ERROR:5105:500:3002:Unexpected error reading/updating database
-AAI_5106=5:4:WARN:5106:404:3001:Node not found
-AAI_5107=5:2:WARN:5107:400:3000:Required information missing
-AAI_5108=5:2:WARN:5108:200:0:Unexpected information in request being ignored
-
-#--- aaidbgen: 6101-6199
-AAI_6101=5:4:ERROR:6101:500:3002:null JanusGraph object passed
-AAI_6102=5:4:WARN:6102:400:3000:Passed-in property is not valid for this nodeType
-AAI_6103=5:4:WARN:6103:400:3000:Required Node-property not found in input data
-AAI_6104=5:4:WARN:6104:400:3000:Required Node-property was passed with no data
-AAI_6105=5:4:WARN:6105:400:3000:Node-Key-Property not defined in DbMaps
-AAI_6106=5:4:WARN:6106:400:3000:Passed-in property is not valid for this edgeType
-AAI_6107=5:4:WARN:6107:400:3000:Required Edge-property not found in input data
-AAI_6108=5:4:WARN:6108:400:3000:Required Edge-property was passed with no data
-AAI_6109=5:4:WARN:6109:400:3000:Bad dependent Node value
-AAI_6110=5:4:ERROR:6110:400:3100:Node cannot be deleted
-AAI_6111=5:4:ERROR:6111:400:3000:JSON processing error
-AAI_6112=5:4:ERROR:6112:400:3000:More than one node found by getUniqueNode()
-AAI_6114=5:4:INFO:6114:404:3001:Node Not Found
-AAI_6115=5:4:ERROR:6115:400:3000:Unrecognized NodeType
-AAI_6116=5:4:ERROR:6116:400:3000:Unrecognized Property
-AAI_6117=5:4:ERROR:6117:400:3000:Uniqueness constraint violated
-AAI_6118=5:4:ERROR:6118:400:3000:Required Field not passed.
-AAI_6120=5:4:ERROR:6120:400:3000:Bad Parameter Passed
-AAI_6121=5:4:ERROR:6121:400:3000:Problem with internal AAI reference data
-AAI_6122=5:4:ERROR:6122:400:3000:Data Set not complete in DB for this request
-AAI_6123=5:4:ERROR:6123:500:3000:Bad Data found by DataGrooming Tool - Investigate
-AAI_6124=5:4:ERROR:6124:500:3000:File read/write error
-AAI_6125=5:4:WARN:6125:500:3000:Problem Pulling Data Set
-AAI_6126=5:4:ERROR:6126:400:3000:Edge cannot be deleted
-AAI_6127=5:4:INFO:6127:404:3001:Edge Not Found
-AAI_6128=5:4:INFO:6128:500:3000:Unexpected error
-AAI_6129=5:4:INFO:6129:404:3003:Error making edge to target node
-AAI_6130=5:4:WARN:6130:412:3000:Precondition Required
-AAI_6131=5:4:WARN:6131:412:3000:Precondition Failed
-AAI_6132=5:4:WARN:6132:400:3000:Bad Model Definition
-AAI_6133=5:4:WARN:6133:400:3000:Bad Named Query Definition
-AAI_6134=5:4:ERROR:6134:500:6134:Could not persist transaction to storage back end. Exhausted retry amount
-AAI_6135=5:4:WARN:6135:412:3000:Resource version specified on create
-AAI_6136=5:4:ERROR:6136:400:3000:Object cannot hold multiple items
-AAI_6137=5:4:ERROR:6137:400:3000:Cannot perform writes on multiple vertices
-AAI_6138=5:4:ERROR:6138:400:3000:Cannot delete multiple vertices
-AAI_6139=5:4:ERROR:6139:404:3000:Attempted to add edge to vertex that does not exist
-AAI_6140=5:4:ERROR:6140:400:3000:Edge multiplicity violated
-AAI_6141=5:4:WARN:6141:400:3000:Please Refine Query
-AAI_6142=5:4:INFO:6142:400:3000:Retrying transaction
-AAI_6143=5:4:INFO:6143:400:3000:Ghost vertex found
-AAI_6144=5:4:WARN:6144:400:3000:Cycle found in graph
-AAI_6145=5:4:ERROR:6145:400:3000:Cannot create a nested/containment edge via relationship
-AAI_6146=5:4:ERROR:6146:400:3000:Ambiguous identity map found, use a URI instead
-
-#--- aaicsvp: 7101-7199
-AAI_7101=5:4:ERROR:7101:500:3002:Unexpected error in CSV file processing
-AAI_7102=5:4:ERROR:7102:500:3002:Error in cleanup temporary directory
-#AAI_7103=4:2:ERROR:7103:500:3002:Unsupported user
-AAI_7104=5:4:ERROR:7104:500:3002:Failed to create directory
-AAI_7105=5:4:ERROR:7105:500:3002:Temporary directory exists
-AAI_7106=5:4:ERROR:7106:500:3002:Cannot delete
-AAI_7107=5:4:ERROR:7107:500:3002:Input file does not exist
-AAI_7108=5:4:ERROR:7108:500:3002:Output file does not exist
-AAI_7109=5:4:ERROR:7109:500:3002:Error closing file
-AAI_7110=5:4:ERROR:7110:500:3002:Error loading/reading properties file
-AAI_7111=5:4:ERROR:7111:500:3002:Error executing shell script
-AAI_7112=5:4:ERROR:7112:500:3002:Error creating output file
-AAI_7113=5:4:ERROR:7113:500:3002:Trailer record error
-AAI_7114=5:4:ERROR:7114:500:3002:Input file error
-AAI_7115=5:4:ERROR:7115:500:3002:Unexpected error
-AAI_7116=5:4:ERROR:7116:500:3002:Request error
-AAI_7117=5:4:ERROR:7117:500:3002:Error in get http client object
-AAI_7118=5:4:ERROR:7118:500:3002:Script Error
-AAI_7119=5:4:ERROR:7119:500:3002:Unknown host
-
-#--- aaisdnc: 7201-7299
-AAI_7202=5:4:ERROR:7202:500:3002:Error getting connection to odl
-AAI_7203=5:4:ERROR:7203:500:3002:Unexpected error calling DataChangeNotification API
-AAI_7204=5:4:ERROR:7204:500:3002:Error returned by DataChangeNotification API
-AAI_7205=5:4:ERROR:7205:500:3002:Unexpected error running notifySDNCOnUpdate
-AAI_7206=5:4:ERROR:7206:500:3002:Invalid data returned from ODL
-
-#--- NotificationEvent, using UEB space
-AAI_7350=5:4:ERROR:7305:500:3002:Notification event creation failed
-
-#--- aairestctlr: 7401-7499
-AAI_7401=5:4:ERROR:7401:500:3002:Error connecting to AAI REST API
-AAI_7402=5:4:ERROR:7402:500:3002:Unexpected error
-AAI_7403=5:4:WARN:7403:400:3001:Request error
-AAI_7404=5:4:INFO:7404:404:3001:Node not found
-AAI_7405=5:4:WARN:7405:200:0:UUID not formatted correctly, generating UUID
-
-#--- aaiauth: 9101-9199
-AAI_9101=5:0:WARN:9101:403:3300:User is not authorized to perform function
-AAI_9102=5:0:WARN:9102:401:3301:Refresh credentials from source
-AAI_9103=5:0:WARN:9103:403:3300:User not found
-AAI_9104=5:0:WARN:9104:401:3302:Authentication error
-AAI_9105=5:0:WARN:9105:403:3300:Authorization error
-AAI_9106=5:0:WARN:9106:403:3300:Invalid AppId
-#AAI_9107=5:0:WARN:9107:403:3300:No Username in Request
-AAI_9107=5:0:WARN:9107:403:3300:SSL is not provided in request, please contact admin
-
-#--- aaiinstar: 9201-9299
-AAI_9201=5:4:ERROR:9201:500:3002:Unable to send notification
-AAI_9202=5:4:ERROR:9202:500:3002:Unable to start a thread
+++ /dev/null
-#
-# ============LICENSE_START=======================================================
-# org.onap.aai
-# ================================================================================
-# Copyright © 2017-18 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=========================================================
-
-query.fast-property=true
-# the following parameters are not reloaded automatically and require a manual bounce
-storage.backend=inmemory
-storage.hostname=localhost
-
-#schema.default=none
-storage.lock.wait-time=300
-storage.hbase.table=aaigraph-dev1.dev
-storage.hbase.ext.zookeeper.znode.parent=/hbase-unsecure
-#caching on
-cache.db-cache = true
-cache.db-cache-clean-wait = 20
-cache.db-cache-time = 180000
-cache.db-cache-size = 0.3
-
-#load graphson file on startup
-load.snapshot.file=false
+++ /dev/null
-#
-# ============LICENSE_START=======================================================
-# org.onap.aai
-# ================================================================================
-# Copyright © 2017-18 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=========================================================
-
-query.fast-property=true
-# the following parameters are not reloaded automatically and require a manual bounce
-storage.backend=inmemory
-storage.hostname=localhost
-
-#schema.default=none
-storage.lock.wait-time=300
-storage.hbase.table=aaigraph-dev1.dev
-storage.hbase.ext.zookeeper.znode.parent=/hbase-unsecure
-# Setting db-cache to false ensure the fastest propagation of changes across servers
-cache.db-cache = false
-
-#load graphson file on startup
-load.snapshot.file=false
+++ /dev/null
-{
- "roles": [
- {
- "name": "testRole",
- "functions": [
- {
- "name": "testFunction",
- "methods": [
- {
- "name": "GET"
- },
- {
- "name": "DELETE"
- },
- {
- "name": "PUT"
- }
- ]
- }
- ],
- "users": [
- {
- "username": "testUser"
- },
- {
- "username": "testWildcardId",
- "is-wildcard-id": true
- }
- ]
- },
- {
- "name": "HAProxy",
- "functions": [
- {
- "name": "util",
- "methods": [
- {
- "name": "GET"
- }
- ]
- }
- ],
- "users": [
- {
- "username": "ha-proxy-user"
- },
- {
- "username": "ha-proxy-wildcard-id",
- "is-wildcard-id": true
- }
- ]
- },
- {
- "name": "testBasicAuth",
- "functions": [
- {
- "name": "testBasicAuthFunction",
- "methods": [
- {
- "name": "GET"
- }
- ]
- }
- ],
- "users": [
- {
- "user": "testBasicAuthUser",
- "pass": "OBF:1ytc1vu91v2p1rxf1mqh1v8s1z0d1msn1san1mqf1z0h1v9u1msl1rvf1v1p1vv11yta"
- }
- ]
- }
- ]
-}
\ No newline at end of file
+++ /dev/null
-{"id": 386506928,"label": "vertex","properties": {"aai-last-mod-ts": [{"id": "ob632u-6e46nk-5j45","value": 1488308500413}],"aai-uri": [{"id": "ob6712-6e46nk-5lhh","value": "/cloud-infrastructure/cloud-regions/cloud-region/cloud-owner-987654321-9922-as988q/cloud-region-id-987654321-9922-as988q/tenants/tenant/tenant-987654321-9999-as988q/vservers/vserver/vserver-987654321-9999-as988q"}],"prov-status": [{"id": "ob651y-6e46nk-1kw5","value": "example-prov-status-val-7367"}],"aai-created-ts": [{"id": "ob62ae-6e46nk-5gqt","value": 1488308500413}],"source-of-truth": [{"id": "ob61w6-6e46nk-5jwl","value": "FitNesse-Test-as988q"}],"vserver-selflink": [{"id": "ob65g6-6e46nk-3xfp","value": "example-vserver-selflink-val-7367"}],"aai-node-type": [{"id": "ob61hy-6e46nk-5f5x","value": "vserver"}],"in-maint": [{"id": "ob65ue-6e46nk-20p1","value": false}],"resource-version": [{"id": "ob62om-6e46nk-23ut","value": "1488308500413"}],"vserver-name": [{"id": "ob649i-6e46nk-3u9x","value": "example-vserver-name-val-7367vserver-987654321-9999-as988q"}],"vserver-id": [{"id": "ob63va-6e46nk-3sp1","value": "vserver-987654321-9999-as988q"}],"last-mod-source-of-truth": [{"id": "ob63h2-6e46nk-5edh","value": "FitNesse-Test-as988q"}],"vserver-name2": [{"id": "ob64nq-6e46nk-3vut","value": "example-vserver-name2-val-7367"}],"is-closed-loop-disabled": [{"id": "ob668m-6e46nk-229x","value": false}]}}
-{"id": 2461872,"label": "vertex","properties": {"aai-last-mod-ts": [{"id": "21hqu-1grlc-5j45","value": 1467901600}],"in-maint": [{"id": "21i52-1grlc-20p1","value": false}],"resource-version": [{"id": "21ija-1grlc-23ut","value": "1467901600"}],"vserver-name": [{"id": "21ixi-1grlc-3u9x","value": "PerfTest_VServerFix0027TenantPez002701611467901587187Name"}],"aai-created-ts": [{"id": "21jbq-1grlc-5gqt","value": 1467901600}],"vserver-id": [{"id": "21jpy-1grlc-3sp1","value": "PerfTest_VServerFix0027TenantPez002701611467901587187"}],"last-mod-source-of-truth": [{"id": "21k46-1grlc-5edh","value": "MSO"}],"vserver-name2": [{"id": "21kie-1grlc-3vut","value": "PerfTest_VServerFix0027TenantPez002701611467901587187-VM Name2 optional"}],"source-of-truth": [{"id": "21kwm-1grlc-5jwl","value": "MSO"}],"vserver-selflink": [{"id": "21lau-1grlc-3xfp","value": "http://testvserverLink.com/.html?vserv=VserverLink"}],"is-closed-loop-disabled": [{"id": "21lp2-1grlc-229x","value": false}],"aai-node-type": [{"id": "21m3a-1grlc-5f5x","value": "vserver"}],"aai-uri": [{"id": "21m3a-1grlc-5a5x","value": "/vservers/vserver/test1"}]}}
\ No newline at end of file
+++ /dev/null
-{
- "results": [
- {
- "vserver": {
-
- }
- },
- {
- "vserver": {
- }
- }
- ]
-}
\ No newline at end of file
+++ /dev/null
-{
- "results": [
- {
- "url" : "/cloud-infrastructure/cloud-regions/cloud-region/cloud-owner-987654321-9922-as988q/cloud-region-id-987654321-9922-as988q/tenants/tenant/tenant-987654321-9999-as988q/vservers/vserver/vserver-987654321-9999-as988q",
- "vserver": {
-
- }
- },
- {
- "url" : "/vservers/vserver/test1",
- "vserver": {
-
- }
- }
- ]
-}
\ No newline at end of file
+++ /dev/null
-{
- "results" : [{
- "id" : "0",
- "node-type" : "generic-vnf",
- "url" : "urimissing",
- "properties" : {
- "vnf-name" : "myVnf"
- },
- "related-to" : [{
- "node-type" : "vserver",
- "id" : "1",
- "url" : "urimissing"
- }]
- } , {
- "id" : "1",
- "node-type" : "vserver",
- "url" : "urimissing",
- "properties" : {
- "vserver-name" : "myVserver"
- },
- "related-to" : [{
- "node-type" : "generic-vnf",
- "id" : "0",
- "url" : "urimissing"
- },{
- "node-type" : "pserver",
- "id" : "2",
- "url" : "/pservers/pserver/key1"
- }]
- },{
- "id" : "2",
- "node-type" : "pserver",
- "url" : "/pservers/pserver/key1",
- "properties" : {
- "hostname" : "myPserver"
- },
- "related-to" : [{
- "node-type" : "vserver",
- "id" : "1",
- "url" : "urimissing"
- }]
- }]
-}
\ No newline at end of file
+++ /dev/null
-{
- "related-to": "generic-vnf",
- "relationship-data" : [{
- "relationship-key" : "generic-vnf.vnf-id",
- "relationship-value":"key1"
- },{
- "relationship-key" : "generic-vnf.vnf-id",
- "relationship-value":"key2"
- }]
-}
\ No newline at end of file
+++ /dev/null
-{
- "related-to": "generic-vnf",
- "related-link": "/aai/v10/network/generic-vnfs/test-objet/key1",
- "relationship-data" : [{
- "relationship-key" : "generic-vnf.vnf-id",
- "relationship-value":"key2"
- }]
-}
\ No newline at end of file
+++ /dev/null
-{
- "related-to": "generic-vnf",
- "related-link": "http://localhost/aai/v10/network/generic-vnfs/generic-vnf/key1",
- "relationship-data" : [{
- "relationship-key" : "test-obect.vnf-id",
- "relationship-value":"key2"
- }]
-}
\ No newline at end of file
+++ /dev/null
-{
- "related-to": "generic-vnf",
- "relationship-data" : []
-}
\ No newline at end of file
+++ /dev/null
-{
- "related-to": "generic-vnf",
- "related-link": "http://localhost/aai/v10/network/generic-vnfs/generic-vnf/key1"
-}
\ No newline at end of file
+++ /dev/null
-{
- "related-to": "generic-vnf",
- "relationship-data" : [{
- "relationship-key" : "generic-vnf.vnf-id",
- "relationship-value":"key1"
- }]
-}
\ No newline at end of file
+++ /dev/null
-{
- "related-to": "l-interface",
- "relationship-data" : [{
- "relationship-key" : "generic-vnf.vnf-id",
- "relationship-value":"key1"
- },{
- "relationship-key" : "subnet.subnet-id",
- "relationship-value":"key5"
- },{
- "relationship-key" : "vlan.vlan-interface",
- "relationship-value":"key3"
- },{
- "relationship-key" : "l-interface.interface-name",
- "relationship-value":"key2"
- },{
- "relationship-key" : "l3-interface-ipv4-address-list.l3-interface-ipv4-address",
- "relationship-value":"key4"
- }]
-}
+++ /dev/null
-{
- "related-to" : "availability-zone",
- "relationship-data" : [ {
- "relationship-key" : "cloud-region.cloud-owner",
- "relationship-value" : "key1"
- }, {
- "relationship-key" : "cloud-region.cloud-region-id",
- "relationship-value" : "key2"
- }, {
- "relationship-key" : "availability-zone.availability-zone-name",
- "relationship-value" : "key3"
- } ]
-}
\ No newline at end of file
+++ /dev/null
-{
- "related-to": "l-interface",
- "relationship-data" : [{
- "relationship-key" : "generic-vnf.vnf-id",
- "relationship-value":"key1"
- },{
- "relationship-key" : "vlan.vlan-interface",
- "relationship-value":"key3"
- },{
- "relationship-key" : "l-interface.interface-name",
- "relationship-value":"key2"
- },{
- "relationship-key" : "zone.zone-id",
- "relationship-value":"key5"
- },{
- "relationship-key" : "l3-interface-ipv4-address-list.l3-interface-ipv4-address",
- "relationship-value":"key4"
- }]
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" output="target/classes" path="src/main/java">
- <attributes>
- <attribute name="optional" value="true"/>
- <attribute name="maven.pomderived" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="src" output="target/test-classes" path="src/test/java">
- <attributes>
- <attribute name="optional" value="true"/>
- <attribute name="maven.pomderived" value="true"/>
- <attribute name="test" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
- <attributes>
- <attribute name="maven.pomderived" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
- <attributes>
- <attribute name="maven.pomderived" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="src" path="target/generated-sources/annotations">
- <attributes>
- <attribute name="optional" value="true"/>
- <attribute name="maven.pomderived" value="true"/>
- <attribute name="ignore_optional_problems" value="true"/>
- <attribute name="m2e-apt" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
- <attributes>
- <attribute name="maven.pomderived" value="true"/>
- <attribute name="optional" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
- <attributes>
- <attribute name="maven.pomderived" value="true"/>
- <attribute name="test" value="true"/>
- <attribute name="optional" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="src" output="target/test-classes" path="target/generated-test-sources/test-annotations">
- <attributes>
- <attribute name="optional" value="true"/>
- <attribute name="maven.pomderived" value="true"/>
- <attribute name="ignore_optional_problems" value="true"/>
- <attribute name="m2e-apt" value="true"/>
- <attribute name="test" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="output" path="target/classes"/>
-</classpath>
<parent>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-parent</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
<relativePath>../aai-parent/pom.xml</relativePath>
</parent>
<artifactId>aai-annotations</artifactId>
</properties>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
package org.onap.aai.annotations;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
+
public class AnnotationsTest {
public AnnotationsTest() {
}
+ @Test
@Metadata(
isKey = false,
description = "",
maximumDepth = "",
crossEntityReference = "")
public void testAnnotation() {
+ assertTrue(true);
}
}
<parent>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-parent</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
<relativePath>../aai-parent/pom.xml</relativePath>
</parent>
<artifactId>aai-auth</artifactId>
<dependencies>
<dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
+ <groupId>org.apache.httpcomponents.client5</groupId>
+ <artifactId>httpclient5</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
package org.onap.aaiauth.auth;
-import org.apache.http.cookie.Cookie;
+import org.apache.hc.client5.http.cookie.Cookie;
public class Auth {
<parent>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-common-docker</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
</parent>
<artifactId>aai-common-images</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>aai-aai-common-images</name>
<description>Contains dockerfiles for aai-common images (alpine and ubuntu based).</description>
<parent>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-common-docker</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
</parent>
<artifactId>aai-haproxy-image</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>aai-aai-haproxy-image</name>
<description>Contains dockerfiles for aai-haproxy image.</description>
-FROM haproxy:2.4.13-alpine
+FROM haproxy:2.4.27-alpine
# For building the image in a proxy environment if necessary
ARG HTTP_PROXY
RUN mkdir -p /etc/ssl/certs/ && mkdir -p /etc/ssl/private
COPY --chown=haproxy aai.pem /etc/ssl/private/aai.pem
-COPY --chown=haproxy docker-entrypoint.sh /docker-entrypoint.sh
-COPY --chown=haproxy resolvers.conf /usr/local/etc/haproxy/resolvers.conf
COPY --chown=haproxy haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg
# Changing group and group permission to allow haproxy user to execute sed comamnd ot change files
RUN chgrp haproxy /usr/local/etc/haproxy; \
- chgrp haproxy /docker-entrypoint.sh /usr/local/etc/haproxy/haproxy.cfg /usr/local/etc/haproxy/resolvers.conf
+ chgrp haproxy /usr/local/etc/haproxy/haproxy.cfg
-RUN chmod +x /docker-entrypoint.sh; \
- chmod g+wx /usr/local/etc/haproxy; \
- chmod g+w /docker-entrypoint.sh /usr/local/etc/haproxy/haproxy.cfg /usr/local/etc/haproxy/resolvers.conf
+RUN chmod g+wx /usr/local/etc/haproxy; \
+ chmod g+w /usr/local/etc/haproxy/haproxy.cfg
# Reverting to haproxy use to not run the pod with root permissions
USER haproxy
-ENTRYPOINT [ "/docker-entrypoint.sh" ]
-CMD [ "haproxy", "-f", "/usr/local/etc/haproxy/haproxy.cfg", "-f", "/usr/local/etc/haproxy/resolvers.conf" ]
+ENTRYPOINT [ "haproxy" ]
+CMD [ "-W", "-db", "-f", "/usr/local/etc/haproxy/haproxy.cfg", "-f", "/usr/local/etc/haproxy/resolvers.conf" ]
EXPOSE 8443
+++ /dev/null
-#!/bin/sh
-set -e
-
-# first arg is `-f` or `--some-option`
-if [ "${1#-}" != "$1" ]; then
- set -- haproxy "$@"
-fi
-
-NAMESERVER_IP=$(cat /etc/resolv.conf | grep 'nameserver' | head -1 | awk '{ print $2; }');
-
-sed -i 's/${ONAP_NAMESERVER_CLUSTER_IP}/'${NAMESERVER_IP}'/g' /usr/local/etc/haproxy/resolvers.conf || {
- echo "Unable to overwrite the nameserver in the haproxy configuration file";
- exit 1;
-}
-
-if [ "$1" = 'haproxy' ]; then
- shift # "haproxy"
- # if the user wants "haproxy", let's add a couple useful flags
- # -W -- "master-worker mode" (similar to the old "haproxy-systemd-wrapper"; allows for reload via "SIGUSR2")
- # -db -- disables background mode
- set -- haproxy -W -db "$@"
-fi
-
-exec "$@"
+++ /dev/null
-resolvers kubernetes
- nameserver dns1 ${ONAP_NAMESERVER_CLUSTER_IP}:53
- hold valid 1s
<parent>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-parent</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
<relativePath>../aai-parent/pom.xml</relativePath>
</parent>
.settings
target/
**/logs/
-bundleconfig-local/etc/auth/aai-client-cert.p12
-bundleconfig-local/etc/auth/tomcat_keystore
bundleconfig-local/etc/oxm
src/main/aai_schema
bundleconfig-local/etc/logback.xml
<parent>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-parent</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
<relativePath>../aai-parent/pom.xml</relativePath>
</parent>
<artifactId>aai-core</artifactId>
<name>aai-core</name>
<packaging>jar</packaging>
<properties>
- <springframework.version>4.3.24.RELEASE</springframework.version>
-
- <jacoco.line.coverage.limit>0.50</jacoco.line.coverage.limit>
- <groovy.version>2.5.15</groovy.version>
+ <jacoco.line.coverage.limit>0.0</jacoco.line.coverage.limit>
<mockito.core.version>3.4.0</mockito.core.version>
<!-- Start of Default ONAP Schema Properties -->
<aai.wiki.link>https://wiki.onap.org/</aai.wiki.link>
<profile>
<id>onap</id>
<properties>
- <springframework.version>4.3.24.RELEASE</springframework.version>
<aai.release>onap</aai.release>
<schema.configuration.location>N/A</schema.configuration.location>
<schema.nodes.location>aai-schema/src/main/resources/${aai.release}/oxm</schema.nodes.location>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.8</version>
+ <version>3.8.1</version>
</plugin>
<plugin>
<!-- explicitly define maven-deploy-plugin after other to force exec
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-schema-ingest</artifactId>
</dependency>
- <dependency>
- <groupId>org.onap.aai.aai-common</groupId>
- <artifactId>aai-aaf-auth</artifactId>
- </dependency>
<dependency>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-annotations</artifactId>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
- <version>1.5.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
</exclusion>
</exclusions>
</dependency>
- <dependency>
- <groupId>com.att.eelf</groupId>
- <artifactId>eelf-core</artifactId>
- <version>2.0.0-oss</version>
- </dependency>
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-core-asl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-asl</artifactId>
- </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-junit</artifactId>
+ <version>2.0.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.glassfish</groupId>
+ <artifactId>jakarta.json</artifactId>
+ <version>2.0.1</version>
+ </dependency>
<dependency>
<groupId>org.janusgraph</groupId>
<artifactId>janusgraph-core</artifactId>
</exclusions>
</dependency>
<dependency>
- <groupId>com.fasterxml.jackson.jaxrs</groupId>
- <artifactId>jackson-jaxrs-json-provider</artifactId>
+ <groupId>org.janusgraph</groupId>
+ <artifactId>janusgraph-inmemory</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.janusgraph</groupId>
+ <artifactId>janusgraph-cql</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.jakarta.rs</groupId>
+ <artifactId>jackson-jakarta-rs-json-provider</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
- <version>2.7.14</version>
</dependency>
<dependency>
- <groupId>org.springframework.kafka</groupId>
- <artifactId>spring-kafka-test</artifactId>
- <scope>test</scope>
- </dependency>
+ <groupId>org.springframework.kafka</groupId>
+ <artifactId>spring-kafka-test</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</dependency>
<dependency>
- <groupId>javax.xml.bind</groupId>
- <artifactId>jaxb-api</artifactId>
+ <groupId>jakarta.xml.bind</groupId>
+ <artifactId>jakarta.xml.bind-api</artifactId>
</dependency>
<dependency>
- <groupId>com.sun.xml.bind</groupId>
- <artifactId>jaxb-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>com.sun.xml.bind</groupId>
- <artifactId>jaxb-core</artifactId>
+ <groupId>org.glassfish.jaxb</groupId>
+ <artifactId>jaxb-runtime</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
- <artifactId>jackson-module-jaxb-annotations</artifactId>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-core</artifactId>
+ <artifactId>jackson-module-jakarta-xmlbind-annotations</artifactId>
</dependency>
<dependency>
- <groupId>com.sun.jersey</groupId>
+ <groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
</dependency>
<dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-json</artifactId>
+ <groupId>org.glassfish.jersey.media</groupId>
+ <artifactId>jersey-media-json-jackson</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tinkerpop</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
- <dependency>
- <groupId>com.beust</groupId>
- <artifactId>jcommander</artifactId>
- </dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
</dependency>
- <dependency>
- <groupId>org.apache.activemq</groupId>
- <artifactId>activemq-broker</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.activemq</groupId>
- <artifactId>activemq-openwire-legacy</artifactId>
- </dependency>
- <dependency>
- <groupId>com.opencsv</groupId>
- <artifactId>opencsv</artifactId>
- </dependency>
- <dependency>
- <groupId>org.freemarker</groupId>
- <artifactId>freemarker</artifactId>
- </dependency>
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>json-patch</artifactId>
</dependency>
- <dependency>
- <groupId>org.codehaus.groovy</groupId>
- <artifactId>groovy</artifactId>
- <version>${groovy.version}</version>
- <classifier>indy</classifier>
- </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-test</artifactId>
+ <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.tinkerpop</groupId>
- <artifactId>gremlin-groovy</artifactId>
<exclusions>
<exclusion>
- <groupId>org.codehaus.groovy</groupId>
- <artifactId>groovy</artifactId>
+ <groupId>com.vaadin.external.google</groupId>
+ <artifactId>android-json</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jms</artifactId>
+ <groupId>org.apache.httpcomponents.client5</groupId>
+ <artifactId>httpclient5</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.tinkerpop</groupId>
+ <artifactId>gremlin-groovy</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.datatype</groupId>
+ <artifactId>jackson-datatype-jsr310</artifactId>
+ </dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.dataformat</groupId>
+ <artifactId>jackson-dataformat-xml</artifactId>
+ </dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
<dependency>
- <groupId>org.apache.logging.log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>${log4j.version}</version>
- <type>pom</type>
+ <groupId>org.projectlombok</groupId>
+ <artifactId>lombok</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.testcontainers</groupId>
+ <artifactId>testcontainers</artifactId>
+ <version>${testcontainers.version}</version>
+ <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.testcontainers</groupId>
+ <artifactId>junit-jupiter</artifactId>
+ <version>${testcontainers.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.testcontainers</groupId>
+ <artifactId>cassandra</artifactId>
+ <version>${testcontainers.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.testcontainers</groupId>
+ <artifactId>toxiproxy</artifactId>
+ <version>${testcontainers.version}</version>
+ <scope>test</scope>
</dependency>
</dependencies>
/**
* The constructor.
*/
- @SuppressWarnings("unchecked")
public AaiCallable() {
mdcCopy = MDC.getCopyOfContextMap();
}
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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;
+
+import java.io.FileNotFoundException;
+
+import org.apache.commons.configuration2.ex.ConfigurationException;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.JanusGraphFactory;
+import org.janusgraph.core.schema.JanusGraphManagement;
+import org.onap.aai.dbgen.SchemaGenerator;
+import org.onap.aai.dbgen.SchemaGenerator4Hist;
+import org.onap.aai.dbmap.AAIGraphConfig;
+import org.onap.aai.exceptions.AAIException;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Configuration
+public class GraphConfig {
+
+ private static final String IN_MEMORY = "inmemory";
+
+ @Value("${spring.application.name}")
+ private String serviceName;
+
+ @Value("${aai.graph.properties.path}")
+ private String configPath;
+
+ @Bean
+ public org.apache.commons.configuration2.Configuration getGraphProperties()
+ throws FileNotFoundException, ConfigurationException {
+
+ return new AAIGraphConfig.Builder(configPath)
+ .forService(serviceName)
+ .withGraphType("realtime")
+ .buildConfiguration();
+ }
+
+ @Bean
+ public JanusGraph janusGraph(org.apache.commons.configuration2.Configuration graphConfiguration) throws AAIException {
+ JanusGraph graph = JanusGraphFactory.open(graphConfiguration);
+
+ boolean loadSchema = false;
+ if (loadSchema) {
+ if (IN_MEMORY.equals(graphConfiguration.getProperty("storage.backend"))) {
+ // Load the propertyKeys, indexes and edge-Labels into the DB
+ loadSchema(graph);
+ }
+ }
+
+ if (graph == null) {
+ throw new AAIException("AAI_5102");
+ }
+
+ return graph;
+ }
+
+ @Bean
+ public Graph graph(JanusGraph janusGraph) {
+ return janusGraph;
+ }
+
+ @Bean
+ public GraphTraversalSource graphTraversalSource(Graph graph) {
+ return graph.traversal();
+ }
+
+ private void loadSchema(JanusGraph graph) {
+ // Load the propertyKeys, indexes and edge-Labels into the DB
+ boolean dbNotEmpty = graph.traversal().V().limit(1).hasNext();
+ log.info("-- loading schema into JanusGraph");
+ if ("true".equals(
+ SpringContextAware.getApplicationContext().getEnvironment().getProperty("history.enabled", "false"))) {
+ JanusGraphManagement graphMgt = graph.openManagement();
+ SchemaGenerator4Hist.loadSchemaIntoJanusGraph(graphMgt, IN_MEMORY);
+ } else {
+ SchemaGenerator.loadSchemaIntoJanusGraph(graph, IN_MEMORY, dbNotEmpty);
+ }
+ }
+}
package org.onap.aai.config;
-import java.util.*;
+import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
-import org.onap.aai.introspection.LoaderFactory;
import org.onap.aai.introspection.MoxyLoader;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.SchemaVersions;
@Import({ConfigConfiguration.class, SchemaServiceConfiguration.class, NodesConfiguration.class,
EdgesConfiguration.class})
@Configuration
-
public class IntrospectionConfig {
private Map<SchemaVersion, MoxyLoader> moxyInstanceMap = new ConcurrentHashMap<>();
@Autowired
NodesConfiguration nodesConfiguration;
- @Bean
- public LoaderFactory loaderFactory(SchemaVersions schemaVersions) {
- return new LoaderFactory(moxyLoaderInstance(schemaVersions));
- }
-
@Bean
public Map<SchemaVersion, MoxyLoader> moxyLoaderInstance(SchemaVersions schemaVersions) {
for (SchemaVersion version : schemaVersions.getVersions()) {
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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;
+
+import java.util.Map;
+import java.util.HashMap;
+
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.common.serialization.StringSerializer;
+import org.onap.aai.domain.deltaEvent.DeltaEvent;
+import org.onap.aai.domain.notificationEvent.NotificationEvent;
+import org.onap.aai.kafka.DeltaProducer;
+import org.onap.aai.kafka.DeltaProducerService;
+import org.onap.aai.kafka.NotificationProducer;
+import org.onap.aai.kafka.NotificationProducerService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.kafka.core.DefaultKafkaProducerFactory;
+import org.springframework.kafka.core.KafkaTemplate;
+import org.springframework.kafka.core.ProducerFactory;
+import org.springframework.kafka.support.serializer.JsonSerializer;
+
+@Configuration
+public class KafkaConfig {
+
+ private static final Logger logger = LoggerFactory.getLogger(KafkaConfig.class);
+
+ @Value("${spring.kafka.producer.bootstrap-servers}")
+ private String bootstrapServers;
+
+ @Value("${spring.kafka.producer.properties.security.protocol}")
+ private String securityProtocol;
+
+ @Value("${spring.kafka.producer.properties.sasl.mechanism}")
+ private String saslMechanism;
+
+ @Value("${spring.kafka.producer.properties.sasl.jaas.config:#{null}}")
+ private String saslJaasConfig;
+
+ @Value("${spring.kafka.producer.retries:3}")
+ private String retries;
+
+ @Value("${spring.kafka.producer.maxInFlightConnections:10}")
+ private String maxInFlightConnections;
+
+ private Map<String, Object> buildKafkaProperties() throws Exception {
+ Map<String, Object> props = new HashMap<>();
+ if (bootstrapServers == null) {
+ logger.error("Environment Variable " + bootstrapServers + " is missing");
+ throw new Exception("Environment Variable " + bootstrapServers + " is missing");
+ } else {
+ props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
+ }
+ props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
+ props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
+ props.put(JsonSerializer.ADD_TYPE_INFO_HEADERS, false);
+ props.put(ProducerConfig.RETRIES_CONFIG, retries);
+ props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, maxInFlightConnections);
+
+ if (saslJaasConfig == null) {
+ logger.info("Not using any authentication for kafka interaction");
+ } else {
+ logger.info("Using authentication provided by kafka interaction");
+ // Strimzi Kafka security properties
+ props.put("security.protocol", securityProtocol);
+ props.put("sasl.mechanism", saslMechanism);
+ props.put("sasl.jaas.config", saslJaasConfig);
+ }
+ return props;
+ }
+
+ @Bean
+ public KafkaTemplate<String, NotificationEvent> kafkaNotificationEventTemplate(ProducerFactory<String, NotificationEvent> producerFactory) throws Exception {
+ return new KafkaTemplate<>(producerFactory);
+ }
+
+ @Bean
+ public NotificationProducer notificationProducer(KafkaTemplate<String,NotificationEvent> kafkaTemplate) {
+ return new NotificationProducerService(kafkaTemplate);
+ }
+
+ @Bean
+ public ProducerFactory<String, NotificationEvent> notificationEventProducerFactory() throws Exception {
+ Map<String, Object> props = buildKafkaProperties();
+ return new DefaultKafkaProducerFactory<>(props);
+ }
+
+ @Bean
+ public ProducerFactory<String, DeltaEvent> deltaEventProducerFactory() throws Exception {
+ Map<String, Object> props = buildKafkaProperties();
+ return new DefaultKafkaProducerFactory<>(props);
+ }
+
+ @Bean
+ public KafkaTemplate<String, DeltaEvent> kafkaDeltaEventTemplate(ProducerFactory<String, DeltaEvent> producerFactory) throws Exception {
+ return new KafkaTemplate<>(producerFactory);
+ }
+
+ @Bean
+ public DeltaProducer deltaProducer(KafkaTemplate<String,DeltaEvent> kafkaTemplate) {
+ return new DeltaProducerService(kafkaTemplate);
+ }
+}
import org.springframework.context.annotation.Scope;
import org.springframework.web.context.annotation.RequestScope;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationModule;
+
@Configuration
public class RestBeanConfig {
+
+ @Bean
+ public ObjectMapper objectMapper() {
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.registerModule(new JakartaXmlBindAnnotationModule());
+ return objectMapper;
+ }
+
@Bean(name = "traversalUriHttpEntry")
@Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public HttpEntry traversalUriHttpEntry() {
import org.onap.aai.edges.EdgeIngestor;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.serialization.db.EdgeSerializer;
-import org.onap.aai.setup.AAIConfigTranslator;
import org.onap.aai.setup.ConfigTranslator;
-import org.onap.aai.setup.SchemaConfigVersions;
-import org.onap.aai.setup.SchemaLocationsBean;
import org.onap.aai.validation.CheckEverythingStrategy;
import org.onap.aai.validation.SchemaErrorStrategy;
import org.onap.aai.validation.nodes.DefaultDuplicateNodeDefinitionValidationModule;
import org.onap.aai.validation.nodes.NodeValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
-import org.springframework.context.annotation.*;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.PropertySource;
@Import({NodesConfiguration.class, EdgesConfiguration.class})
@Configuration
this.version = version;
}
- /**
- * @deprecated As of release 3.2.2, replaced by {@link #onMapper(Consumer)}.
- */
- @Deprecated
- @Override
- public Io.Builder<GraphSONPartialIO> registry(final IoRegistry registry) {
- this.registry = registry;
- return this;
- }
-
@Override
public Io.Builder<? extends Io> onMapper(final Consumer<Mapper.Builder> onMapper) {
this.onMapper = onMapper;
throw new IllegalArgumentException("The graph argument was not specified");
return new GraphSONPartialIO(this);
}
+
+ @Override
+ public <V> boolean requiresVersion(V version) {
+ throw new UnsupportedOperationException("Unimplemented method 'requiresVersion'");
+ }
}
}
if (supportsTx && counter.incrementAndGet() % batchSize == 0)
graphToWriteTo.tx().commit();
} catch (Exception ex) {
- LOGGER.info(String.format("Error in reading vertex from graphson%s", vertex.toString()));
+ LOGGER.info("Error in reading vertex from graphson%s".formatted(vertex.toString()));
}
});
: cachedOutV.addEdge(e.label(), cachedInV);
e.properties().forEachRemaining(p -> newEdge.property(p.key(), p.value()));
} else {
- LOGGER.debug(String.format("Ghost edges from %s to %s", cachedOutV, cachedInV));
+ LOGGER.debug("Ghost edges from %s to %s".formatted(cachedOutV, cachedInV));
}
if (supportsTx && counter.incrementAndGet() % batchSize == 0)
graphToWriteTo.tx().commit();
} catch (Exception ex) {
- LOGGER.info(String.format("Error in writing vertex into graph%s", e.toString()));
+ LOGGER.info("Error in writing vertex into graph%s".formatted(e.toString()));
}
}));
final JsonNode root = mapper.readTree(inputStream);
final JsonNode vertices = root.get(GraphSONTokens.VERTICES);
if (!vertices.getNodeType().equals(JsonNodeType.ARRAY))
- throw new IOException(String.format("The '%s' key must be an array", GraphSONTokens.VERTICES));
+ throw new IOException("The '%s' key must be an array".formatted(GraphSONTokens.VERTICES));
return IteratorUtils.stream(vertices.elements()).map(Object::toString);
} else {
final BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
-import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import org.janusgraph.core.schema.ConsistencyModifier;
import org.janusgraph.core.schema.JanusGraphIndex;
import org.janusgraph.core.schema.JanusGraphManagement;
-import org.janusgraph.core.schema.JanusGraphManagement.IndexJobFuture;
import org.janusgraph.core.schema.RelationTypeIndex;
import org.janusgraph.core.schema.SchemaAction;
import org.janusgraph.core.schema.SchemaStatus;
+import org.janusgraph.diskstorage.keycolumnvalue.scan.ScanJobFuture;
import org.janusgraph.graphdb.database.StandardJanusGraph;
import org.janusgraph.graphdb.database.management.ManagementSystem;
import org.janusgraph.graphdb.database.management.RelationIndexStatusReport;
final Map<String, Introspector> objs = LoaderUtil.getLatestVersion().getAllObjects();
final Map<String, PropertyKey> seenProps = new HashMap<>();
-
+
for (Introspector obj : objs.values()) {
createSchemaForObject(graphMgmt, seenProps, obj);
}
private static void awaitRelationIndexStatus(JanusGraph graph, Collection<String> labels, SchemaStatus newStatus) {
LOGGER.info("Awaiting index status [{}]", newStatus);;
CompletableFuture<RelationIndexStatusReport>[] awaits = labels.stream()
- .map(label ->
+ .map(label ->
CompletableFuture.supplyAsync(() -> {
try {
return ManagementSystem
private static void updateRelationIndexes(JanusGraph graph, Collection<String> labels, SchemaAction updateAction) {
JanusGraphManagement graphMgmt = graph.openManagement();
- CompletableFuture<IndexJobFuture>[] awaits = labels.stream()
- .map(label ->
+ CompletableFuture<ScanJobFuture>[] awaits = labels.stream()
+ .map(label ->
CompletableFuture.supplyAsync(() -> {
EdgeLabel relation = graphMgmt.getEdgeLabel(label);
RelationTypeIndex index = graphMgmt.getRelationIndex(relation, label);
LOGGER.debug("Closing open transaction [{}] before schema generation", transaction.toString());
transaction.rollback();
});
-
+
final JanusGraphManagement graphMgtForClosing = graph.openManagement();
Set<String> instances = graphMgtForClosing.getOpenInstances();
import java.io.FileNotFoundException;
import java.util.Properties;
-import org.apache.commons.configuration.PropertiesConfiguration;
+import org.apache.commons.configuration2.Configuration;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.io.IoCore;
}
this.loadGraph(rtConfig, serviceName);
} catch (Exception e) {
+ logger.error("Failed to instantiate graph", e);
throw new RuntimeException("Failed to instantiate graphs", e);
}
}
// Graph being opened by JanusGraphFactory is being placed in hashmap to be used later
// These graphs shouldn't be closed until the application shutdown
try {
- PropertiesConfiguration propertiesConfiguration = new AAIGraphConfig.Builder(configPath)
+ Configuration propertiesConfiguration = new AAIGraphConfig.Builder(configPath)
.forService(serviceName).withGraphType("realtime").buildConfiguration();
graph = JanusGraphFactory.open(propertiesConfiguration);
transaction.tx().commit();
logger.info("Snapshot loaded to inmemory graph.");
} catch (Exception e) {
- logger.info(String.format("ERROR: Could not load datasnapshot to in memory graph. %n%s",
+ logger.info("ERROR: Could not load datasnapshot to in memory graph. %n%s".formatted(
ExceptionUtils.getStackTrace(e)));
throw new RuntimeException(e);
}
import java.lang.management.ManagementFactory;
import java.util.Objects;
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.commons.configuration.PropertiesConfiguration;
+import org.apache.commons.configuration2.PropertiesConfiguration;
+import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
+import org.apache.commons.configuration2.builder.fluent.Parameters;
+import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.janusgraph.diskstorage.configuration.ConfigElement;
throws ConfigurationException, FileNotFoundException {
File file = new File(shortcutOrFile);
if (file.exists()) {
- PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
- propertiesConfiguration.setAutoSave(false);
- propertiesConfiguration.load(shortcutOrFile);
- return propertiesConfiguration;
+ FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
+ new FileBasedConfigurationBuilder<PropertiesConfiguration>(PropertiesConfiguration.class)
+ .configure(new Parameters()
+ .properties()
+ .setFile(file));
+ return builder.getConfiguration();
} else {
throw new FileNotFoundException(shortcutOrFile);
}
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraphTransaction;
-import org.janusgraph.core.schema.JanusGraphManagement;
import org.onap.aai.dbgen.GraphSONPartialIO;
import org.onap.aai.dbgen.SchemaGenerator;
import org.onap.aai.logging.LogFormatTools;
}
} catch (Exception e) {
- LOGGER.error(String.format("ERROR: Could not load datasnapshot to in memory graph. %n%s",
+ LOGGER.error("ERROR: Could not load datasnapshot to in memory graph. %n%s".formatted(
LogFormatTools.getStackTop(e)));
throw new IllegalStateException("Could not load datasnapshot to in memory graph");
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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.domain.deltaEvent;
+
+import java.util.Collection;
+
+import org.onap.aai.domain.notificationEvent.NotificationEvent.EventHeader;
+import org.onap.aai.util.delta.ObjectDelta;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import lombok.Data;
+
+@Data
+public class DeltaEvent {
+ @JsonProperty("cambria.partition")
+ protected String cambriaPartition;
+ @JsonProperty("event-header")
+ protected EventHeader eventHeader;
+ Collection<ObjectDelta> entities;
+}
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.01.06 at 05:38:00 PM EST
-//
-
package org.onap.aai.domain.notificationEvent;
-import javax.xml.bind.annotation.*;
+import jakarta.xml.bind.annotation.*;
-import org.w3c.dom.Element;
+import com.fasterxml.jackson.annotation.JsonProperty;
-/**
- * <p>
- * Java class for anonymous complex type.
- *
- * <p>
- * The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType>
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="cambria.partition" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="event-header" minOccurs="0">
- * <complexType>
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="timestamp" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="source-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="domain" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="sequence-number" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="severity" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="event-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="version" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="action" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="top-entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="entity-link" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="status" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </element>
- * <any processContents='lax' namespace='##other' minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
+import lombok.Data;
+
+@Data
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"cambriaPartition", "eventHeader", "entity"})
@XmlRootElement(name = "NotificationEvent")
public class NotificationEvent {
@XmlElement(name = "cambria.partition")
+ @JsonProperty("cambria.partition")
protected String cambriaPartition;
@XmlElement(name = "event-header")
+ @JsonProperty("event-header")
protected EventHeader eventHeader;
@XmlAnyElement(lax = true)
protected Object entity;
- /**
- * Gets the value of the eventHeader property.
- *
- * @return
- * possible object is
- * {@link EventHeader }
- *
- */
- public EventHeader getEventHeader() {
- return eventHeader;
- }
-
- /**
- * Sets the value of the eventHeader property.
- *
- * @param value
- * allowed object is
- * {@link EventHeader }
- *
- */
- public void setEventHeader(EventHeader value) {
- this.eventHeader = value;
- }
-
- /**
- * Gets the value of the any property.
- *
- * @return
- * possible object is
- * {@link Object }
- * {@link Element }
- *
- */
- public Object getEntity() {
- return entity;
- }
-
- /**
- * Sets the value of the any property.
- *
- * @param value
- * allowed object is
- * {@link Object }
- * {@link Element }
- *
- */
- public void setEntity(Object value) {
- this.entity = value;
- }
-
- /**
- * Gets the value of the cambriaPartition property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getCambriaPartition() {
- return cambriaPartition;
- }
-
- /**
- * Sets the value of the cambriaPartition property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setCambriaPartition(String value) {
- this.cambriaPartition = value;
- }
-
- /**
- * <p>
- * Java class for anonymous complex type.
- *
- * <p>
- * The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType>
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="timestamp" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="source-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="domain" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="sequence-number" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="severity" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="event-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="version" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="action" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="top-entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="entity-link" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="status" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
+ @Data
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(
name = "",
propOrder = {"id", "timestamp", "sourceName", "domain", "sequenceNumber", "severity", "eventType",
- "version", "action", "entityType", "topEntityType", "entityLink", "status"})
+ "version", "action", "entityType", "topEntityType", "entityLink","entityUuid"})
public static class EventHeader {
@XmlElement(required = true)
@XmlElement(required = true)
protected String timestamp;
@XmlElement(name = "source-name", required = true)
+ @JsonProperty("source-name")
protected String sourceName;
@XmlElement(required = true)
protected String domain;
@XmlElement(name = "sequence-number", required = true)
+ @JsonProperty("sequence-number")
protected String sequenceNumber;
@XmlElement(required = true)
protected String severity;
@XmlElement(name = "event-type", required = true)
+ @JsonProperty("event-type")
protected String eventType;
@XmlElement(required = true)
protected String version;
@XmlElement(required = true)
protected String action;
@XmlElement(name = "entity-type", required = true)
+ @JsonProperty("entity-type")
protected String entityType;
@XmlElement(name = "top-entity-type", required = true)
+ @JsonProperty("top-entity-type")
protected String topEntityType;
@XmlElement(name = "entity-link", required = true)
+ @JsonProperty("entity-link")
protected String entityLink;
- @XmlElement(required = true)
- protected String status;
-
- /**
- * Gets the value of the id property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getId() {
- return id;
- }
-
- /**
- * Sets the value of the id property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setId(String value) {
- this.id = value;
- }
-
- /**
- * Gets the value of the timestamp property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getTimestamp() {
- return timestamp;
- }
-
- /**
- * Sets the value of the timestamp property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setTimestamp(String value) {
- this.timestamp = value;
- }
-
- /**
- * Gets the value of the sourceName property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getSourceName() {
- return sourceName;
- }
-
- /**
- * Sets the value of the sourceName property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setSourceName(String value) {
- this.sourceName = value;
- }
-
- /**
- * Gets the value of the domain property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDomain() {
- return domain;
- }
-
- /**
- * Sets the value of the domain property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDomain(String value) {
- this.domain = value;
- }
-
- /**
- * Gets the value of the sequenceNumber property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getSequenceNumber() {
- return sequenceNumber;
- }
-
- /**
- * Sets the value of the sequenceNumber property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setSequenceNumber(String value) {
- this.sequenceNumber = value;
- }
-
- /**
- * Gets the value of the severity property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getSeverity() {
- return severity;
- }
-
- /**
- * Sets the value of the severity property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setSeverity(String value) {
- this.severity = value;
- }
-
- /**
- * Gets the value of the eventType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getEventType() {
- return eventType;
- }
-
- /**
- * Sets the value of the eventType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setEventType(String value) {
- this.eventType = value;
- }
-
- /**
- * Gets the value of the version property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getVersion() {
- return version;
- }
-
- /**
- * Sets the value of the version property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setVersion(String value) {
- this.version = value;
- }
-
- /**
- * Gets the value of the action property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getAction() {
- return action;
- }
-
- /**
- * Sets the value of the action property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setAction(String value) {
- this.action = value;
- }
-
- /**
- * Gets the value of the entityType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getEntityType() {
- return entityType;
- }
-
- /**
- * Sets the value of the entityType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setEntityType(String value) {
- this.entityType = value;
- }
-
- /**
- * Gets the value of the topEntityType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getTopEntityType() {
- return topEntityType;
- }
-
- /**
- * Sets the value of the topEntityType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setTopEntityType(String value) {
- this.topEntityType = value;
- }
-
- /**
- * Gets the value of the entityLink property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getEntityLink() {
- return entityLink;
- }
-
- /**
- * Sets the value of the entityLink property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setEntityLink(String value) {
- this.entityLink = value;
- }
-
- /**
- * Gets the value of the status property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getStatus() {
- return status;
- }
-
- /**
- * Sets the value of the status property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setStatus(String value) {
- this.status = value;
- }
-
+ @JsonProperty("entity-uuid")
+ protected String entityUuid;
}
}
package org.onap.aai.domain.notificationEvent;
-import javax.xml.bind.annotation.XmlRegistry;
+import jakarta.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
package org.onap.aai.domain.responseMessage;
-import javax.xml.bind.annotation.*;
+import jakarta.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(
import java.util.ArrayList;
import java.util.List;
-import javax.xml.bind.annotation.*;
+import jakarta.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"aaiResponseMessageDatum", "any"})
package org.onap.aai.domain.responseMessage;
-import javax.xml.bind.annotation.*;
+import jakarta.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"aaiResponseMessageDatumKey", "aaiResponseMessageDatumValue",
import java.util.ArrayList;
import java.util.List;
-import javax.xml.bind.annotation.*;
+import jakarta.xml.bind.annotation.*;
/**
* <p>
// Generated on: 2015.06.15 at 03:03:58 PM EDT
//
-@javax.xml.bind.annotation.XmlSchema(
+@jakarta.xml.bind.annotation.XmlSchema(
namespace = "http://org.onap.aai.inventory",
- elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
+ elementFormDefault = jakarta.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.onap.aai.domain.responseMessage;
import java.util.ArrayList;
import java.util.List;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlType;
+import jakarta.xml.bind.annotation.XmlAccessType;
+import jakarta.xml.bind.annotation.XmlAccessorType;
+import jakarta.xml.bind.annotation.XmlRootElement;
+import jakarta.xml.bind.annotation.XmlType;
/**
* <p>
package org.onap.aai.domain.translog;
-import javax.xml.bind.annotation.*;
+import jakarta.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlCDATA;
import java.util.ArrayList;
import java.util.HashMap;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.UriInfo;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.UriInfo;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
// -----------------------------------------------------------------------
// postExtErrorCallback | java.lang.reflect.Method (RW)
// -----------------------------------------------------------------------
- // servletRequest | javax.servlet.http.HttpServletRequest (RO)
+ // servletRequest | jakarta.servlet.http.HttpServletRequest (RO)
// -----------------------------------------------------------------------
- // headers | javax.ws.rs.core.HttpHeaders (RO)
+ // headers | jakarta.ws.rs.core.HttpHeaders (RO)
// -----------------------------------------------------------------------
// objFromRequestType | String (ex. ?org.onap.aai.domain.yang.Vce?) (RO)
// -----------------------------------------------------------------------
package org.onap.aai.introspection;
+import com.fasterxml.jackson.annotation.JsonRawValue;
+import com.fasterxml.jackson.annotation.JsonValue;
import com.google.common.base.CaseFormat;
import java.io.UnsupportedEncodingException;
return marshal(properties);
}
+ @JsonValue
+ @JsonRawValue
+ public String toString() {
+ return marshal(false);
+ }
+
public String makeSingular(String word) {
String result = word;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
+import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
import org.onap.aai.schema.enums.ObjectMetadata;
import org.onap.aai.schema.enums.PropertyMetadata;
import org.onap.aai.setup.SchemaVersion;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
public class JSONStrategy extends Introspector {
- private JSONObject json = null;
+ private JsonNode json = null;
private String namedType = "";
+ private static final ObjectMapper mapper = new ObjectMapper();
protected JSONStrategy(Object o) {
super(o);
- json = (JSONObject) o;
+ json = mapper.valueToTree(o);
// Assumes you provide a wrapper
- Set<String> keySet = json.keySet();
- if (keySet.size() == 1) {
- namedType = keySet.iterator().next();
- json = (JSONObject) json.get(namedType);
+ Iterator<Map.Entry<String, JsonNode>> fields = json.fields();
+ if (fields.hasNext()) {
+ Map.Entry<String, JsonNode> entry = fields.next();
+ if (!fields.hasNext()) {
+ namedType = entry.getKey();
+ json = entry.getValue();
+ } else {
+ throw new IllegalArgumentException("This object has no named type.");
+ }
} else {
throw new IllegalArgumentException("This object has no named type.");
}
protected JSONStrategy(Object o, String namedType) {
super(o);
- json = (JSONObject) o;
+ json = (JsonNode) o;
this.namedType = namedType;
}
@Override
public void setValue(String name, Object obj) {
- json.put(name, obj);
-
+ ((ObjectNode) json).set(name, (JsonNode) obj);
}
@Override
@Override
public Set<String> getProperties() {
- Set<String> result = json.keySet();
- return result;
+ Iterator<String> fieldNames = json.fieldNames();
+ Set<String> properties = new HashSet<>();
+
+ // Iterate through the iterator and add each element to the set
+ while (fieldNames.hasNext()) {
+ properties.add(fieldNames.next());
+ }
+ return properties;
}
@Override
public Class<?> getGenericTypeClass(String name) {
Class<?> resultClass = null;
Object resultObject = this.getValue(name);
- if (resultObject instanceof JSONArray) {
+ if (resultObject instanceof ArrayNode) {
resultClass = ((List<?>) resultObject).get(0).getClass();
}
import java.util.Map;
import org.onap.aai.setup.SchemaVersion;
-import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+/**
+ * Factory method that grants access to the globally loaded schema versions.
+ * There is one {@link MoxyLoader} instance for each api version ({@link SchemaVersion}) that the AAI supports.
+ */
+@Component
public class LoaderFactory {
- @Autowired
- public Map<SchemaVersion, MoxyLoader> moxyLoaderInstance;
+ private final Map<SchemaVersion, MoxyLoader> moxyLoaderInstance;
public LoaderFactory(Map<SchemaVersion, MoxyLoader> moxyLoaderInstance) {
this.moxyLoaderInstance = moxyLoaderInstance;
}
/**
- * Creates a new Loader object.
- *
- * @param type
- * the type
- * @param version
- * the version
- * @param llBuilder
- * the ll builder
- * @return the loader
+ * Contrary to the naming, this method does not create a new loader,
+ * but rather returns an existing loader instance
*/
public Loader createLoaderForVersion(ModelType type, SchemaVersion version) {
}
return null;
-
}
public Loader getLoaderStrategy(ModelType type, SchemaVersion version) {
return getMoxyLoaderInstance().get(version);
}
return null;
-
}
public Map<SchemaVersion, MoxyLoader> getMoxyLoaderInstance() {
return moxyLoaderInstance;
}
-
- public void setMoxyLoaderInstance(Map<SchemaVersion, MoxyLoader> moxyLoaderInstance) {
- this.moxyLoaderInstance = moxyLoaderInstance;
- }
-
}
import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableMap;
-import java.io.*;
+import java.io.StringReader;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.dynamic.DynamicEntity;
/**
* {@inheritDoc}
- *
+ *
* @throws AAIUnknownObjectException
*/
@Override
import java.util.Map.Entry;
import java.util.Set;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Marshaller;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.dynamic.DynamicEntity;
package org.onap.aai.introspection.exceptions;
+import java.io.Serial;
+
import org.onap.aai.exceptions.AAIException;
public class AAIUnknownObjectException extends AAIException {
+ @Serial
private static final long serialVersionUID = -504200228742133774L;
public AAIUnknownObjectException() {
package org.onap.aai.introspection.exceptions;
+import java.io.Serial;
+
import org.onap.aai.exceptions.AAIException;
public class AAIUnmarshallingException extends AAIException {
+ @Serial
private static final long serialVersionUID = -5615651557821878103L;
private static final String AAI_MSG = "AAI_3000";
import java.util.Objects;
import java.util.Optional;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.exceptions.AAIException;
import java.util.Optional;
import java.util.regex.Matcher;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
import java.util.Map.Entry;
import java.util.Optional;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
import java.util.Map.Entry;
import java.util.Optional;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
Multimap<String, EdgeRule> edgeRulesMap = edgeIngestor.getRules(edgeQuery);
if (edgeRulesMap.isEmpty()) {
- String message = String.format("Unable to find edge between %s and %s", obj.getName(),
+ String message = "Unable to find edge between %s and %s".formatted(obj.getName(),
otherVProperty.value().toString());
throw new AAIException("AAI_6127", message);
} else if (edgeRulesMap.size() > 1) {
- String message = String.format("Found multiple edges between %s and %s", obj.getName(),
+ String message = "Found multiple edges between %s and %s".formatted(obj.getName(),
otherVProperty.value().toString());
throw new EdgeMultiplicityException(message);
}
}
private Optional<String> resolveRelativePath(Optional<String> populatedUri) throws UnsupportedEncodingException {
- if (!populatedUri.isPresent()) {
+ if (populatedUri.isEmpty()) {
return Optional.empty();
} else {
return Optional.of(populatedUri.get().replaceFirst("\\./", this.serializer.getURIForVertex(self) + "/"));
package org.onap.aai.introspection.sideeffect.exceptions;
+import java.io.Serial;
+
import org.onap.aai.exceptions.AAIException;
public class AAIMissingRequiredPropertyException extends AAIException {
+ @Serial
private static final long serialVersionUID = -8907079650472014019L;
public AAIMissingRequiredPropertyException() {
package org.onap.aai.introspection.sideeffect.exceptions;
+import java.io.Serial;
+
import org.onap.aai.exceptions.AAIException;
public class AAIMultiplePropertiesException extends AAIException {
+ @Serial
private static final long serialVersionUID = 2098371383166008345L;
public AAIMultiplePropertiesException() {
+++ /dev/null
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Modifications Copyright © 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.aai.kafka;
-
- import java.util.Map;
- import java.util.Objects;
-
- import javax.jms.JMSException;
- import javax.jms.Message;
- import javax.jms.MessageListener;
- import javax.jms.TextMessage;
-
- import org.json.JSONException;
- import org.json.JSONObject;
- import org.onap.aai.aailog.logs.AaiDmaapMetricLog;
- import org.onap.aai.exceptions.AAIException;
- import org.onap.aai.logging.AaiElsErrorCode;
- import org.onap.aai.logging.ErrorLogHelper;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.slf4j.MDC;
- import org.springframework.core.env.Environment;
- import org.springframework.kafka.core.KafkaTemplate;
-
- public class AAIKafkaEventJMSConsumer implements MessageListener {
-
- private static final String EVENT_TOPIC = "event-topic";
-
- private static final Logger LOGGER = LoggerFactory.getLogger(AAIKafkaEventJMSConsumer.class);
-
- private Environment environment;
- private Map<String, String> mdcCopy;
- private KafkaTemplate<String,String> kafkaTemplate;
-
- public AAIKafkaEventJMSConsumer(Environment environment,KafkaTemplate<String,String> kafkaTemplate) {
- super();
- mdcCopy = MDC.getCopyOfContextMap();
- Objects.nonNull(environment);
- this.environment = environment;
- this.kafkaTemplate=kafkaTemplate;
- }
-
- @Override
- public void onMessage(Message message) {
-
- if (kafkaTemplate == null) {
- return;
- }
-
- String jsmMessageTxt = "";
- String aaiEvent = "";
- JSONObject aaiEventHeader;
- JSONObject joPayload;
- String transactionId = "";
- String serviceName = "";
- String eventName = "";
- String aaiElsErrorCode = AaiElsErrorCode.SUCCESS;
- String errorDescription = "";
-
- if (mdcCopy != null) {
- MDC.setContextMap(mdcCopy);
- }
-
- if (message instanceof TextMessage) {
- AaiDmaapMetricLog metricLog = new AaiDmaapMetricLog();
- try {
- jsmMessageTxt = ((TextMessage) message).getText();
- JSONObject jo = new JSONObject(jsmMessageTxt);
- if (jo.has("aaiEventPayload")) {
- joPayload = jo.getJSONObject("aaiEventPayload");
- aaiEvent = joPayload.toString();
- } else {
- return;
- }
- if (jo.getString(EVENT_TOPIC) != null) {
- eventName = jo.getString(EVENT_TOPIC);
- }
- if (joPayload.has("event-header")) {
- try {
- aaiEventHeader = joPayload.getJSONObject("event-header");
- if (aaiEventHeader.has("id")) {
- transactionId = aaiEventHeader.get("id").toString();
- }
- if (aaiEventHeader.has("entity-link")) {
- serviceName = aaiEventHeader.get("entity-link").toString();
- }
- } catch (JSONException jexc) {
- // ignore, this is just used for logging
- }
- }
- metricLog.pre(eventName, aaiEvent, transactionId, serviceName);
-
-
- if ("AAI-EVENT".equals(eventName)) {
- // restTemplate.exchange(baseUrl + endpoint, HttpMethod.POST, httpEntity, String.class);
- kafkaTemplate.send(eventName,aaiEvent);
-
- } else {
- LOGGER.error(String.format("%s|Event Topic invalid.", eventName));
- }
- } catch (JMSException | JSONException e) {
- aaiElsErrorCode = AaiElsErrorCode.DATA_ERROR;
- errorDescription = e.getMessage();
- ErrorLogHelper.logException(new AAIException("AAI_7350"));
- } catch (Exception e) {
- aaiElsErrorCode = AaiElsErrorCode.AVAILABILITY_TIMEOUT_ERROR;
- errorDescription = e.getMessage();
- ErrorLogHelper.logException(new AAIException("AAI_7304", jsmMessageTxt));
- } finally {
- metricLog.post(aaiElsErrorCode, errorDescription);
- }
- }
- }
- }
-
\ No newline at end of file
+++ /dev/null
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Modifications Copyright © 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.aai.kafka;
-
-import org.apache.activemq.ActiveMQConnectionFactory;
-import org.apache.activemq.command.ActiveMQQueue;
-import org.json.JSONObject;
-import org.onap.aai.util.AAIConfig;
-import org.springframework.jms.connection.CachingConnectionFactory;
-import org.springframework.jms.core.JmsTemplate;
-
-public class AAIKafkaEventJMSProducer implements MessageProducer {
-
- private JmsTemplate jmsTemplate;
-
- public AAIKafkaEventJMSProducer() {
- if ("true".equals(AAIConfig.get("aai.jms.enable", "true"))) {
- this.jmsTemplate = new JmsTemplate();
- String activeMqTcpUrl = System.getProperty("activemq.tcp.url", "tcp://localhost:61547");
- this.jmsTemplate
- .setConnectionFactory(new CachingConnectionFactory(new ActiveMQConnectionFactory(activeMqTcpUrl)));
- this.jmsTemplate.setDefaultDestination(new ActiveMQQueue("IN_QUEUE"));
- }
- }
-
- public void sendMessageToDefaultDestination(JSONObject finalJson) {
- if (jmsTemplate != null) {
- jmsTemplate.convertAndSend(finalJson.toString());
- CachingConnectionFactory ccf = (CachingConnectionFactory) this.jmsTemplate.getConnectionFactory();
- if (ccf != null) {
- ccf.destroy();
- }
- }
- }
-
- public void sendMessageToDefaultDestination(String msg) {
- if (jmsTemplate != null) {
- jmsTemplate.convertAndSend(msg);
- CachingConnectionFactory ccf = (CachingConnectionFactory) this.jmsTemplate.getConnectionFactory();
- if (ccf != null) {
- ccf.destroy();
- }
- }
- }
-}
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright © 2024 Deutsche Telekom. 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.
package org.onap.aai.kafka;
-import org.json.JSONObject;
+import org.onap.aai.domain.deltaEvent.DeltaEvent;
+import org.springframework.stereotype.Service;
-public interface MessageProducer {
-
- void sendMessageToDefaultDestination(JSONObject finalJson);
-
- void sendMessageToDefaultDestination(String msg);
+@Service
+public interface DeltaProducer {
+ public void sendNotification(DeltaEvent notificationEvent);
}
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright © 2024 Deutsche Telekom. 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.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.config;
+package org.onap.aai.kafka;
-import org.onap.aai.aaf.auth.AAIAuthCore;
+import org.onap.aai.domain.deltaEvent.DeltaEvent;
import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Profile;
+import org.springframework.kafka.core.KafkaTemplate;
+import org.springframework.stereotype.Service;
-@Profile("two-way-ssl")
-@Configuration
-public class AuthorizationConfiguration {
+import lombok.RequiredArgsConstructor;
- @Value("${schema.uri.base.path}")
- private String basePath;
+@Service
+@RequiredArgsConstructor
+public class DeltaProducerService implements DeltaProducer {
- @Bean
- public AAIAuthCore aaiAuthCore() {
- return new AAIAuthCore(basePath);
+ private final KafkaTemplate<String,DeltaEvent> kafkaTemplate;
+ @Value("${aai.notifications.enabled:true}")
+ boolean notificationsEnabled;
+
+ @Override
+ public void sendNotification(DeltaEvent deltaEvent) {
+ if(notificationsEnabled) {
+ kafkaTemplate.send("DELTA", deltaEvent);
}
+ }
}
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright © 2024 Deutsche Telekom. 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.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.restclient;
+package org.onap.aai.kafka;
-import org.eclipse.jetty.util.security.Password;
+import org.onap.aai.domain.notificationEvent.NotificationEvent;
+import org.onap.aai.rest.notification.UEBNotification;
+import org.springframework.stereotype.Service;
-public class JettyPasswordDecoder implements PasswordDecoder {
-
- @Override
- public String decode(String input) {
- if (input.startsWith("OBF:")) {
- return Password.deobfuscate(input);
- }
- return Password.deobfuscate("OBF:" + input);
- }
+@Service
+public interface NotificationProducer {
+ public void sendNotification(NotificationEvent notificationEvent);
+ public void sendUEBNotification(UEBNotification uebNotification);
}
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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.kafka;
+
+import org.onap.aai.domain.notificationEvent.NotificationEvent;
+import org.onap.aai.rest.notification.UEBNotification;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.kafka.core.KafkaTemplate;
+import org.springframework.stereotype.Service;
+
+import lombok.RequiredArgsConstructor;
+
+@Service
+@RequiredArgsConstructor
+public class NotificationProducerService implements NotificationProducer {
+
+ private final KafkaTemplate<String,NotificationEvent> kafkaTemplate;
+ @Value("${aai.notifications.enabled:true}") boolean notificationsEnabled;
+
+ public void sendNotification(NotificationEvent notificationEvent) {
+ if(notificationsEnabled) {
+ kafkaTemplate.send("AAI-EVENT", notificationEvent);
+ }
+ }
+
+ public void sendUEBNotification(UEBNotification uebNotification) {
+ uebNotification.getEvents().stream()
+ .forEach(this::sendNotification);
+ }
+}
package org.onap.aai.parsers.exceptions;
+import java.io.Serial;
+
import org.onap.aai.exceptions.AAIException;
public class AAIIdentityMapParseException extends AAIException {
+ @Serial
private static final long serialVersionUID = -888876613879411865L;
public AAIIdentityMapParseException(String message) {
package org.onap.aai.parsers.exceptions;
+import java.io.Serial;
+
import org.onap.aai.exceptions.AAIException;
public class AmbiguousMapAAIException extends AAIException {
+ @Serial
private static final long serialVersionUID = -878581771971431246L;
public AmbiguousMapAAIException(String message) {
package org.onap.aai.parsers.exceptions;
+import java.io.Serial;
+
import org.onap.aai.exceptions.AAIException;
public class DoesNotStartWithValidNamespaceException extends AAIException {
+ @Serial
private static final long serialVersionUID = -888876613879411865L;
public DoesNotStartWithValidNamespaceException(String message) {
import java.util.*;
import java.util.Map.Entry;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import java.io.UnsupportedEncodingException;
import java.net.URI;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import java.io.UnsupportedEncodingException;
import java.net.URI;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import java.io.UnsupportedEncodingException;
import java.net.URI;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.UriBuilder;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.UriBuilder;
import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import java.util.List;
import java.util.Optional;
-import javax.ws.rs.core.UriBuilder;
+import jakarta.ws.rs.core.UriBuilder;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.edges.exceptions.AmbiguousRuleChoiceException;
import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.IntrospectorFactory;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.ModelType;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.parsers.exceptions.AAIIdentityMapParseException;
import org.onap.aai.parsers.exceptions.AmbiguousMapAAIException;
try {
if (loader.getVersion().compareTo(schemaVersions.getRelatedLinkVersion()) >= 0) {
result = processRelatedLink(relatedLink);
- if (!result.isPresent()) {
+ if (result.isEmpty()) {
result = processRelationshipData();
}
} else {
result = processRelationshipData();
- if (!result.isPresent()) {
+ if (result.isEmpty()) {
result = processRelatedLink(relatedLink);
}
}
package org.onap.aai.parsers.uri;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import java.net.URISyntaxException;
import java.util.Set;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.UriBuilder;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.UriBuilder;
import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import java.util.ArrayList;
import java.util.List;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import java.util.ArrayList;
import java.util.List;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
+import java.util.Map;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
/**
* Given a URI this class returns an object, or series of nested objects
* with their keys populated based off the values in the URI.
- *
+ *
* It populates the keys in the order they are listed in the model.
*/
public class URIToObject implements Parsable {
+ private final SchemaVersion version;
+ private final Loader loader;
+ private final Map<String, Introspector> relatedObjects;
private Introspector topEntity = null;
-
private String topEntityName = null;
-
private String entityName = null;
-
private Introspector entity = null;
-
private Introspector previous = null;
-
private List<Object> parentList = null;
- private SchemaVersion version = null;
- private Loader loader = null;
- private final HashMap<String, Introspector> relatedObjects;
-
/**
* Instantiates a new URI to object.
*
this.version = loader.getVersion();
}
- public URIToObject(Loader loader, URI uri, HashMap<String, Introspector> relatedObjects)
+ public URIToObject(Loader loader, URI uri, Map<String, Introspector> relatedObjects)
throws AAIException, UnsupportedEncodingException {
URIParser parser = new URIParser(loader, uri);
import java.net.URISyntaxException;
import java.util.List;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.edges.enums.EdgeType;
package org.onap.aai.parsers.uri;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Profile;
-@Profile("pre-validation")
@Configuration
+@ConditionalOnProperty(name = "aai.notification.validation.enabled", havingValue = "true")
public class ValidationConfiguration {
@Bean(name = "validationRestClient")
package org.onap.aai.prevalidation;
-import com.google.gson.Gson;
-import com.google.gson.JsonSyntaxException;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
-import javax.annotation.PostConstruct;
+import jakarta.annotation.PostConstruct;
-import org.apache.http.conn.ConnectTimeoutException;
+import org.apache.hc.client5.http.ConnectTimeoutException;
+import org.onap.aai.domain.notificationEvent.NotificationEvent;
+import org.onap.aai.domain.notificationEvent.NotificationEvent.EventHeader;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.Introspector;
-import org.onap.aai.rest.ueb.NotificationEvent;
+
import org.onap.aai.restclient.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
@Profile("pre-validation")
public class ValidationService {
- /**
- * Error indicating that the service trying to connect is down
- */
static final String CONNECTION_REFUSED_STRING =
"Connection refused to the validation microservice due to service unreachable";
-
- /**
- * Error indicating that the server is unable to reach the port
- * Could be server related connectivity issue
- */
static final String CONNECTION_TIMEOUT_STRING = "Connection timeout to the validation microservice as this could "
+ "indicate the server is unable to reach port, "
+ "please check on server by running: nc -w10 -z -v ${VALIDATION_HOST} ${VALIDATION_PORT}";
-
- /**
- * Error indicating that the request exceeded the allowed time
- *
- * Note: This means that the service could be active its
- * just taking some time to process our request
- */
static final String REQUEST_TIMEOUT_STRING =
"Request to validation service took longer than the currently set timeout";
-
static final String VALIDATION_ENDPOINT = "/v1/validate";
static final String VALIDATION_HEALTH_ENDPOINT = "/v1/info";
- private static final String ENTITY_TYPE = "entity-type";
- private static final String ACTION = "action";
- private static final String SOURCE_NAME = "source-name";
-
- private static final String DELETE = "DELETE";
-
private static final Logger LOGGER = LoggerFactory.getLogger(ValidationService.class);
+ private static final String DELETE = "DELETE";
private final RestClient validationRestClient;
-
private final String appName;
-
private final Set<String> validationNodeTypes;
+ private final ObjectMapper mapper;
+ private final List<Pattern> exclusionList;
- private List<Pattern> exclusionList;
-
- private final Gson gson;
-
- @Autowired
public ValidationService(@Qualifier("validationRestClient") RestClient validationRestClient,
@Value("${spring.application.name}") String appName,
@Value("${validation.service.node-types}") String validationNodes,
- @Value("${validation.service.exclusion-regexes}") String exclusionRegexes) {
+ @Value("${validation.service.exclusion-regexes:#{null}}") String exclusionRegexes,
+ ObjectMapper mapper) {
this.validationRestClient = validationRestClient;
this.appName = appName;
this.exclusionList =
Arrays.stream(exclusionRegexes.split(",")).map(Pattern::compile).collect(Collectors.toList());
}
- this.gson = new Gson();
+ this.mapper = mapper;
LOGGER.info("Successfully initialized the pre validation service");
}
@PostConstruct
public void initialize() throws AAIException {
+ doHealthCheckRequest();
+ }
+ private void doHealthCheckRequest() throws AAIException {
Map<String, String> httpHeaders = new HashMap<>();
-
httpHeaders.put("X-FromAppId", appName);
httpHeaders.put("X-TransactionID", UUID.randomUUID().toString());
httpHeaders.put("Content-Type", "application/json");
ResponseEntity<String> healthCheckResponse = null;
-
try {
-
healthCheckResponse =
- validationRestClient.execute(VALIDATION_HEALTH_ENDPOINT, HttpMethod.GET, httpHeaders, null);
-
+ validationRestClient.execute(VALIDATION_HEALTH_ENDPOINT, HttpMethod.GET, httpHeaders);
} catch (Exception ex) {
AAIException validationException = new AAIException("AAI_4021", ex);
throw validationException;
}
public void validate(List<NotificationEvent> notificationEvents) throws AAIException {
-
- if (notificationEvents == null || notificationEvents.isEmpty()) {
+ if (notificationEvents == null || notificationEvents.isEmpty() || isSourceExcluded(notificationEvents)) {
return;
}
- {
- // Get the first notification and if the source of that notification
- // is in one of the regexes then we skip sending it to validation
- NotificationEvent notification = notificationEvents.get(0);
- Introspector eventHeader = notification.getEventHeader();
- if (eventHeader != null) {
- String source = eventHeader.getValue(SOURCE_NAME);
- for (Pattern pattern : exclusionList) {
- if (pattern.matcher(source).matches()) {
- return;
- }
- }
- }
-
- }
-
for (NotificationEvent event : notificationEvents) {
-
- Introspector eventHeader = event.getEventHeader();
-
+ EventHeader eventHeader = event.getEventHeader();
if (eventHeader == null) {
// Should I skip processing the request and let it continue
// or fail the request and cause client impact
continue;
}
- String entityType = eventHeader.getValue(ENTITY_TYPE);
- String action = eventHeader.getValue(ACTION);
-
- /**
+ /*
* Skipping the delete events for now
* Note: Might revisit this later when validation supports DELETE events
*/
- if (DELETE.equalsIgnoreCase(action)) {
+ if (isDelete(eventHeader)) {
continue;
}
+ String entityType = eventHeader.getEntityType();
if (this.shouldValidate(entityType)) {
- List<String> violations = this.preValidate(event.getNotificationEvent());
+ List<String> violations = preValidate(event);
if (!violations.isEmpty()) {
AAIException aaiException = new AAIException("AAI_4019");
aaiException.getTemplateVars().addAll(violations);
}
}
- List<String> preValidate(String body) throws AAIException {
+ /**
+ * Determine if event is of type delete
+ */
+ private boolean isDelete(EventHeader eventHeader) {
+ String action = eventHeader.getAction();
+ return DELETE.equalsIgnoreCase(action);
+ }
- Map<String, String> httpHeaders = new HashMap<>();
+ /**
+ * Checks the `source` attribute of the first event to determine if validation should be skipped
+ * @param notificationEvents
+ * @return
+ */
+ private boolean isSourceExcluded(List<NotificationEvent> notificationEvents) {
+ // Get the first notification and if the source of that notification
+ // is in one of the regexes then we skip sending it to validation
+ NotificationEvent notification = notificationEvents.get(0);
+ EventHeader eventHeader = notification.getEventHeader();
+ if (eventHeader != null) {
+ String source = eventHeader.getSourceName();
+ return exclusionList.stream().anyMatch(pattern -> pattern.matcher(source).matches());
+ }
+ return false;
+ }
+ public List<String> preValidate(NotificationEvent notificationEvent) throws AAIException {
+ Map<String, String> httpHeaders = new HashMap<>();
httpHeaders.put("X-FromAppId", appName);
httpHeaders.put("X-TransactionID", UUID.randomUUID().toString());
httpHeaders.put("Content-Type", "application/json");
List<String> violations = new ArrayList<>();
ResponseEntity<String> responseEntity;
try {
-
- responseEntity = validationRestClient.execute(VALIDATION_ENDPOINT, HttpMethod.POST, httpHeaders, body);
-
+ String requestBody = mapper.writeValueAsString(notificationEvent);
+ responseEntity = validationRestClient.execute(VALIDATION_ENDPOINT, HttpMethod.POST, httpHeaders, requestBody);
Object responseBody = responseEntity.getBody();
if (isSuccess(responseEntity)) {
LOGGER.debug("Validation Service returned following response status code {} and body {}",
responseEntity.getStatusCodeValue(), responseEntity.getBody());
} else if (responseBody != null) {
- Validation validation = null;
- try {
- validation = gson.fromJson(responseBody.toString(), Validation.class);
- } catch (JsonSyntaxException jsonException) {
- LOGGER.warn("Unable to convert the response body {}", jsonException.getMessage());
- }
+ Validation validation = getValidation(responseBody);
if (validation == null) {
LOGGER.debug("Validation Service following status code {} with body {}",
responseEntity.getStatusCodeValue(), responseEntity.getBody());
} else {
- violations.addAll(extractViolations(validation));
+ violations = extractViolations(validation);
}
} else {
LOGGER.warn("Unable to convert the response body null");
// resources microservice shouldn't be blocked because of validation service
// is taking too long or if the validation service is down
// Any other exception it should block the request from passing?
- if (e.getCause() instanceof SocketTimeoutException) {
+ if (e.getCause() instanceof ConnectTimeoutException) {
+ LOGGER.error(CONNECTION_TIMEOUT_STRING, e.getCause());
+ } else if (e.getCause() instanceof SocketTimeoutException) {
LOGGER.error(REQUEST_TIMEOUT_STRING, e.getCause());
} else if (e.getCause() instanceof ConnectException) {
LOGGER.error(CONNECTION_REFUSED_STRING, e.getCause());
- } else if (e.getCause() instanceof ConnectTimeoutException) {
- LOGGER.error(CONNECTION_TIMEOUT_STRING, e.getCause());
} else {
LOGGER.error("Unknown exception thrown please investigate", e.getCause());
}
return violations;
}
+ private Validation getValidation(Object responseBody) {
+ Validation validation = null;
+ try {
+ validation = mapper.readValue(responseBody.toString(), Validation.class);
+ } catch (JsonProcessingException jsonException) {
+ LOGGER.warn("Unable to convert the response body {}", jsonException.getMessage());
+ }
+ return validation;
+ }
+
boolean isSuccess(ResponseEntity<String> responseEntity) {
return responseEntity != null && responseEntity.getStatusCode().is2xxSuccessful();
}
- List<String> extractViolations(Validation validation) {
-
- List<String> errorMessages = new ArrayList<>();
-
- if (validation == null) {
- return errorMessages;
+ public List<String> extractViolations(Validation validation) {
+ if (validation == null || validation.getViolations() == null) {
+ return Collections.emptyList();
}
-
- List<Violation> violations = validation.getViolations();
-
- if (violations != null && !violations.isEmpty()) {
- for (Violation violation : validation.getViolations()) {
- LOGGER.info(violation.getErrorMessage());
- errorMessages.add(violation.getErrorMessage());
- }
- }
-
- return errorMessages;
+ return validation.getViolations().stream()
+ .map(Violation::getErrorMessage)
+ .peek(LOGGER::info)
+ .collect(Collectors.toList());
}
}
protected HttpComponentsClientHttpRequestFactory getHttpRequestFactory() throws Exception {
HttpComponentsClientHttpRequestFactory requestFactory = super.getHttpRequestFactory();
requestFactory.setConnectionRequestTimeout(timeout);
+ // Manual migration to `SocketConfig.Builder.setSoTimeout(Timeout)` necessary; see: https://docs.spring.io/spring-framework/docs/6.0.0/javadoc-api/org/springframework/http/client/HttpComponentsClientHttpRequestFactory.html#setReadTimeout(int)
requestFactory.setReadTimeout(timeout);
requestFactory.setConnectTimeout(timeout);
return requestFactory;
@Value("${validation.service.base.url}")
private String baseUrl;
- @Value("${validation.service.ssl.trust-store}")
- private String truststorePath;
-
- @Value("${validation.service.ssl.trust-store-password}")
- private String truststorePassword;
-
@Value("${validation.service.timeout-in-milliseconds}")
private Integer timeout;
return baseUrl;
}
- @Override
- protected String getTruststorePath() {
- return truststorePath;
- }
-
- @Override
- protected char[] getTruststorePassword() {
- return truststorePassword.toCharArray();
- }
-
@Override
protected HttpComponentsClientHttpRequestFactory getHttpRequestFactory() throws Exception {
HttpComponentsClientHttpRequestFactory requestFactory = super.getHttpRequestFactory();
requestFactory.setConnectionRequestTimeout(timeout);
+ // Manual migration to `SocketConfig.Builder.setSoTimeout(Timeout)` necessary; see: https://docs.spring.io/spring-framework/docs/6.0.0/javadoc-api/org/springframework/http/client/HttpComponentsClientHttpRequestFactory.html#setReadTimeout(int)
requestFactory.setReadTimeout(timeout);
requestFactory.setConnectTimeout(timeout);
return requestFactory;
@Value("${validation.service.base.url}")
private String baseUrl;
- @Value("${validation.service.ssl.key-store}")
- private String keystorePath;
-
- @Value("${validation.service.ssl.trust-store}")
- private String truststorePath;
-
- @Value("${validation.service.ssl.key-store-password}")
- private String keystorePassword;
-
- @Value("${validation.service.ssl.trust-store-password}")
- private String truststorePassword;
-
@Value("${validation.service.timeout-in-milliseconds}")
private Integer timeout;
return baseUrl;
}
- @Override
- protected String getKeystorePath() {
- return keystorePath;
- }
-
- @Override
- protected String getTruststorePath() {
- return truststorePath;
- }
-
- @Override
- protected char[] getKeystorePassword() {
- return keystorePassword.toCharArray();
- }
-
- @Override
- protected char[] getTruststorePassword() {
- return truststorePassword.toCharArray();
- }
-
protected HttpComponentsClientHttpRequestFactory getHttpRequestFactory() throws Exception {
HttpComponentsClientHttpRequestFactory requestFactory = super.getHttpRequestFactory();
requestFactory.setConnectionRequestTimeout(timeout);
+ // Manual migration to `SocketConfig.Builder.setSoTimeout(Timeout)` necessary; see: https://docs.spring.io/spring-framework/docs/6.0.0/javadoc-api/org/springframework/http/client/HttpComponentsClientHttpRequestFactory.html#setReadTimeout(int)
requestFactory.setReadTimeout(timeout);
requestFactory.setConnectTimeout(timeout);
return requestFactory;
/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * * Modifications Copyright © 2024 DEUTSCHE TELEKOM AG.
- * ================================================================================
- * 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=========================================================
- */
+* ============LICENSE_START=======================================================
+* org.onap.aai
+* ================================================================================
+* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
+* ================================================================================
+* * Modifications Copyright © 2024 DEUTSCHE TELEKOM AG.
+* ================================================================================
+* 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.query.builder;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
+import org.apache.tinkerpop.gremlin.process.traversal.translator.GroovyTranslator;
+import org.apache.tinkerpop.gremlin.process.traversal.Order;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.Path;
-import org.apache.tinkerpop.gremlin.process.traversal.Step;
+import org.apache.tinkerpop.gremlin.process.traversal.Pop;
+import org.apache.tinkerpop.gremlin.process.traversal.Scope;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal.Admin;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
+import org.onap.aai.query.entities.PaginationResult;
import org.onap.aai.schema.enums.ObjectMetadata;
import org.onap.aai.schema.enums.PropertyMetadata;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* The Class GraphTraversalBuilder.
*/
public abstract class GraphTraversalBuilder<E> extends QueryBuilder<E> {
+ private static final Logger LOGGER = LoggerFactory.getLogger(GraphTraversalBuilder.class);
+
+ private final GroovyTranslator groovyTranslator = GroovyTranslator.of("source");
+
protected GraphTraversal<Vertex, E> traversal = null;
protected Admin<Vertex, E> completeTraversal = null;
if (value instanceof String) {// "true"
bValue = Boolean.valueOf(value.toString());
- } else if (value instanceof Boolean) {// true
- bValue = (Boolean) value;
+ } else if (value instanceof Boolean boolean1) {// true
+ bValue = boolean1;
}
this.vertexHas(key, bValue);
@Override
public QueryBuilder<E> store(String name) {
- this.traversal.store(name);
+ this.traversal.aggregate(Scope.local , name);
stepIndex++;
return this;
return this;
}
+ @Override
+ public QueryBuilder<E> select(Pop pop, String name) {
+ this.traversal.select(pop, name);
+
+ stepIndex++;
+
+ return this;
+ }
+
@Override
public QueryBuilder<E> select(String... names) {
if (names.length == 1) {
@Override
public QueryBuilder<E> getContainerQuery() {
-
+
if (this.parentStepIndex == 0) {
return removeQueryStepsBetween(0, containerStepIndex);
} else {
if (start != null) {
this.completeTraversal = traversal.asAdmin();
} else {
+ boolean queryLoggingEnabled = false;
+ if(queryLoggingEnabled) {
+ String query = groovyTranslator.translate(traversal.asAdmin().getBytecode()).getScript();
+ LOGGER.info("Query: {}", query);
+ }
+
admin = source.V().asAdmin();
TraversalHelper.insertTraversal(admin.getEndStep(), traversal.asAdmin(), admin);
return this.completeTraversal.toList();
}
+ @Override
+ public QueryBuilder<E> sort(Sort sort) {
+ Order order = sort.getDirection() == Sort.Direction.ASC ? Order.asc : Order.desc;
+ traversal.order().by(sort.getProperty(), order);
+ stepIndex++;
+ return this;
+ }
+
+ public PaginationResult<E> toPaginationResult(Pageable pageable) {
+ int page = pageable.getPage();
+ int pageSize = pageable.getPageSize();
+ if(pageable.isIncludeTotalCount()) {
+ return paginateWithTotalCount(page, pageSize);
+ } else {
+ return paginateWithoutTotalCount(page, pageSize);
+ }
+ }
+
+ private PaginationResult<E> paginateWithoutTotalCount(int page, int pageSize) {
+ int startIndex = page * pageSize;
+ traversal.range(startIndex, startIndex + pageSize);
+
+ if (this.completeTraversal == null) {
+ executeQuery();
+ }
+ return completeTraversal.hasNext()
+ ? new PaginationResult<E>(completeTraversal.toList())
+ : new PaginationResult<E>(Collections.emptyList());
+ }
+
+ private PaginationResult<E> paginateWithTotalCount(int page, int pageSize) {
+ int startIndex = page * pageSize;
+ traversal.fold().as("results","count")
+ .select("results","count").
+ by(__.range(Scope.local, startIndex, startIndex + pageSize)).
+ by(__.count(Scope.local));
+
+ if (this.completeTraversal == null) {
+ executeQuery();
+ }
+ try {
+ return mapPaginationResult((Map<String,Object>) completeTraversal.next());
+ // .next() will throw an IllegalArguementException if there are no vertices of the given type
+ } catch (NoSuchElementException | IllegalArgumentException e) {
+ return new PaginationResult<>(Collections.emptyList(), 0L);
+ }
+ }
+
+ private PaginationResult<E> mapPaginationResult(Map<String,Object> result) {
+ Object objCount = result.get("count");
+ Object vertices = result.get("results");
+ if(vertices == null) {
+ return new PaginationResult<E>(Collections.emptyList() ,0L);
+ }
+ List<E> results = null;
+ if(vertices instanceof List) {
+ results = (List<E>) vertices;
+ } else if (vertices instanceof Vertex) {
+ results = Collections.singletonList((E) vertices);
+ } else {
+ String msg = "Results must be a list or a vertex, but was %s".formatted(vertices.getClass().getName());
+ LOGGER.error(msg);
+ throw new IllegalArgumentException(msg);
+ }
+ long totalCount = parseCount(objCount);
+ return new PaginationResult<E>(results, totalCount);
+ }
+
+ private long parseCount(Object count) {
+ if(count instanceof String string) {
+ return Long.parseLong(string);
+ } else if(count instanceof Integer integer) {
+ return Long.valueOf(integer);
+ } else if (count instanceof Long long1) {
+ return long1;
+ } else {
+ throw new IllegalArgumentException("Count must be a string, integer, or long");
+ }
+ }
+
protected QueryBuilder<Edge> has(String key, String value) {
traversal.has(key, value);
import java.util.*;
import org.apache.tinkerpop.gremlin.process.traversal.Path;
+import org.apache.tinkerpop.gremlin.process.traversal.Pop;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
+import org.onap.aai.query.entities.PaginationResult;
import org.onap.aai.restcore.search.GremlinGroovyShell;
import org.onap.aai.schema.enums.ObjectMetadata;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
boolean bValue = false;
if (value instanceof String) {
bValue = Boolean.valueOf(value.toString());
- } else if (value instanceof Boolean) {
- bValue = (Boolean) value;
+ } else if (value instanceof Boolean boolean1) {
+ bValue = boolean1;
}
this.vertexHas(key, bValue);
return this;
}
+ @Override
+ public QueryBuilder<E> select(Pop pop, String name) {
+ this.list.add(".select(Pop." + pop.toString() + ",'" + name + "')");
+ stepIndex++;
+
+ return this;
+ }
+
@Override
public QueryBuilder<E> select(String... names) {
String stepString = ".select('";
return (QueryBuilder<Edge>) this;
}
- /*
- * This is required for the subgraphstrategies to work
- */
+ @Override
+ public PaginationResult<E> toPaginationResult(Pageable pageable) {
+ // TODO Auto-generated method stub
+ throw new UnsupportedOperationException("Unimplemented method 'toPaginationResult'");
+ }
+
+ @Override
+ public QueryBuilder<E> sort(Sort sort) {
+ // TODO Auto-generated method stub
+ throw new UnsupportedOperationException("Unimplemented method 'sort'");
+ }
}
import java.util.ArrayList;
import java.util.List;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import java.util.ArrayList;
import java.util.List;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import java.util.ArrayList;
import java.util.List;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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.query.builder;
+
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+
+/**
+ * Object that contains the page and pageSize for pagination.
+ * `includeTotalCount` can optionally be provided to include the total count of objects in the response.
+ * Note that including the total count in the response will trigger a full graph scan (@see <a href="https://jayanta-mondal.medium.com/the-curious-case-of-pagination-for-gremlin-queries-d6fd9518620">The Curious Case of Pagination for Gremlin Queries</a>).
+ */
+@Getter
+@RequiredArgsConstructor
+public class Pageable {
+ private final int page;
+ private final int pageSize;
+ private boolean includeTotalCount = false;
+
+ public Pageable includeTotalCount() {
+ this.includeTotalCount = true;
+ return this;
+ }
+}
import java.util.List;
import java.util.Map;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.process.traversal.Path;
+import org.apache.tinkerpop.gremlin.process.traversal.Pop;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.onap.aai.introspection.Loader;
import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.parsers.query.QueryParserStrategy;
+import org.onap.aai.query.entities.PaginationResult;
import org.springframework.context.ApplicationContext;
/**
* This is necessary in cases such as "if the Optional Property 1 is sent,
* find all Nodes of type A with edges to Nodes of type B with property 1,
* otherwise, simply find all nodes of type A".
- *
+ *
* @param type
* @param outNodeType
* @param inNodeType
* This is necessary in cases such as "if the Optional Property 1 is sent,
* find all Nodes of type A with edges to Nodes of type B with property 1,
* otherwise, simply find all nodes of type A".
- *
+ *
* @param type
* @param outNodeType
* @param inNodeType
public abstract QueryBuilder<E> select(String name);
+ public abstract QueryBuilder<E> select(Pop pop, String name);
+
public abstract QueryBuilder<E> select(String... names);
public abstract QueryBuilder<E> until(QueryBuilder<E> builder);
public abstract List<E> toList();
+ /**
+ * Paginate the resulting list.
+ * This is a final step that returns a PaginationResult.
+ * @param pageable object that contains page and page size
+ * @return returns a page of the results and the total count.
+ */
+ public abstract PaginationResult<E> toPaginationResult(Pageable pageable);
+
+ /**
+ * Sort the resulting list.
+ * @param sort object that contains the property to sort by and the direction
+ * @return returns the QueryBuilder for further query building
+ */
+ public abstract QueryBuilder<E> sort(Sort sort);
+
+
/**
* Used to skip step if there is an optional property missing.
*
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
- * Copyright © 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright © 2024 Deutsche Telekom. 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.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.aaf.filters;
+package org.onap.aai.query.builder;
-public class AafProfiles {
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Getter;
- // AAF Basic Auth
- public static final String AAF_AUTHENTICATION = "aaf-auth";
+@Getter
+@Builder
+@AllArgsConstructor
+public class QueryOptions {
+ @Builder.Default Pageable pageable = null;
+ @Builder.Default Sort sort = null;
- // AAF Auth with Client Certs
- public static final String AAF_CERT_AUTHENTICATION = "aaf-cert-auth";
+ public QueryOptions(Pageable pageable) {
+ this.pageable = pageable;
+ }
- public static final String TWO_WAY_SSL = "two-way-ssl";
-
- private AafProfiles() {
- }
+ public QueryOptions(Sort sort) {
+ this.sort = sort;
+ }
}
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright © 2024 Deutsche Telekom. 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.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.restclient;
+package org.onap.aai.query.builder;
-public interface PasswordDecoder {
+import lombok.Builder;
+import lombok.Data;
- String decode(String input);
+@Data
+@Builder
+public class Sort {
+ private final String property;
+
+ @Builder.Default
+ Direction direction = Direction.ASC;
+
+ public enum Direction {
+ ASC, DESC
+ }
}
import java.util.List;
import java.util.stream.Collectors;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.process.traversal.Step;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
: start;
for (int i = start; i < end - 1; i++) {
Step step = steps.get(start);
- if (step instanceof HasStep) {
- List<HasContainer> hasContainers = ((HasStep) step).getHasContainers();
+ if (step instanceof HasStep hasStep) {
+ List<HasContainer> hasContainers = hasStep.getHasContainers();
int hasContainerSize = hasContainers.size();
boolean isEndWithinHasContainer = isEndWithinHasContainer(end, i, hasContainers);
if (isEndWithinHasContainer) {
int adjustedIndex = start;
for (int i = 0; i < start; i++) {
Step step = steps.get(i);
- if (step instanceof HasStep) {
- if(isEndWithinHasContainer(adjustedIndex, i, ((HasStep) step).getHasContainers())){
+ if (step instanceof HasStep hasStep) {
+ if(isEndWithinHasContainer(adjustedIndex, i, hasStep.getHasContainers())){
adjustedIndex -= 1;
}
- adjustedIndex -= ((HasStep) step).getHasContainers().size();
+ adjustedIndex -= hasStep.getHasContainers().size();
}
}
return adjustedIndex;
for (int i = adjustedIndex; i < steps.size(); i++) {
Step step = steps.get(i);
boolean isFirstStep = i == adjustedIndex;
- if (isFirstStep && step instanceof HasStep) {
+ if (isFirstStep && step instanceof HasStep<?> hasStep) {
int splitPosition = indexAndStepCountTuple.getValue();
- List<HasContainer> newContainers = ((HasStep<?>) step).getHasContainers().stream()
+ List<HasContainer> newContainers = hasStep.getHasContainers().stream()
.skip(splitPosition)
.collect(Collectors.toList());
traversalAdminStart
int stepCount = 0;
for (int j = 0; j <= lastURIStepIndex; j++) {
Step step = steps.get(j);
- if (step instanceof HasStep) {
- stepCount += ((HasStep<?>) step).getHasContainers().size();
+ if (step instanceof HasStep<?> hasStep) {
+ stepCount += hasStep.getHasContainers().size();
} else {
stepCount++;
}
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
- * Copyright © 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright © 2024 Deutsche Telekom. 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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+package org.onap.aai.query.entities;
-package org.onap.aai.aaf.auth;
+import java.util.List;
-import org.junit.BeforeClass;
+import org.springframework.lang.Nullable;
-public class AAISetup {
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
- @BeforeClass
- public static void preSetup() {
- System.setProperty("AJSC_HOME", ".");
- System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
- }
+@Getter
+@AllArgsConstructor
+@RequiredArgsConstructor
+public class PaginationResult <E> {
+ private final List<E> results;
+ @Nullable private Long totalCount = null;
}
import java.net.URI;
import java.util.Optional;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.UriInfo;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.UriInfo;
import org.onap.aai.aailog.logs.DBRequestWrapper;
import org.onap.aai.introspection.Introspector;
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
* ================================================================================
+ * Modifications Copyright © 2024 Deutsche Telekom.
+ * ================================================================================
* 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
import java.util.*;
import java.util.stream.Collectors;
-import javax.ws.rs.core.*;
-import javax.ws.rs.core.Response.Status;
+import jakarta.ws.rs.core.*;
+import jakarta.ws.rs.core.Response.Status;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraphException;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.prevalidation.ValidationService;
-import org.onap.aai.rest.ueb.UEBNotification;
+import org.onap.aai.query.builder.QueryOptions;
+import org.onap.aai.query.entities.PaginationResult;
+import org.onap.aai.rest.notification.NotificationService;
+import org.onap.aai.rest.notification.UEBNotification;
import org.onap.aai.restcore.HttpMethod;
import org.onap.aai.schema.enums.ObjectMetadata;
import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.transforms.XmlFormatTransformer;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.AAIConstants;
-import org.onap.aai.util.delta.DeltaEvents;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
private static final Logger LOGGER = LoggerFactory.getLogger(HttpEntry.class);
private ModelType introspectorFactoryType;
-
private QueryStyle queryStyle;
-
private SchemaVersion version;
-
private Loader loader;
-
private TransactionalGraphEngine dbEngine;
- private boolean processSingle = true;
-
- private int paginationBucket = -1;
- private int paginationIndex = -1;
- private int totalVertices = 0;
- private int totalPaginationBuckets = 0;
-
@Autowired
private NodeIngestor nodeIngestor;
@Autowired
private SchemaVersions schemaVersions;
+ @Autowired
+ private NotificationService notificationService;
+
@Value("${schema.uri.base.path}")
private String basePath;
- @Value("${delta.events.enabled:false}")
- private boolean isDeltaEventsEnabled;
-
private String serverBase;
@Autowired
private XmlFormatTransformer xmlFormatTransformer;
- /**
- * Inject the validation service if the profile pre-valiation is enabled,
- * Otherwise this variable will be set to null and thats why required=false
- * so that it can continue even if pre validation isn't enabled
- */
- @Autowired(required = false)
- private ValidationService validationService;
-
private UEBNotification notification;
private int notificationDepth;
this.dbEngine = new JanusGraphDBEngine(queryStyle, loader);
getDbEngine().startTransaction();
- this.notification = new UEBNotification(loader, loaderFactory, schemaVersions);
+ this.notification = new UEBNotification(loaderFactory, schemaVersions);
if ("true".equals(AAIConfig.get("aai.notification.depth.all.enabled", "true"))) {
this.notificationDepth = AAIProperties.MAXIMUM_DEPTH;
} else {
}
public HttpEntry setHttpEntryProperties(SchemaVersion version, String serverBase) {
- this.version = version;
- this.loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- this.dbEngine = new JanusGraphDBEngine(queryStyle, loader);
-
- getDbEngine().startTransaction();
- this.notification = new UEBNotification(loader, loaderFactory, schemaVersions);
- if ("true".equals(AAIConfig.get("aai.notification.depth.all.enabled", "true"))) {
- this.notificationDepth = AAIProperties.MAXIMUM_DEPTH;
- } else {
- this.notificationDepth = AAIProperties.MINIMUM_DEPTH;
- }
-
+ setHttpEntryProperties(version);
this.serverBase = serverBase;
return this;
}
public HttpEntry setHttpEntryProperties(SchemaVersion version, UEBNotification notification) {
- this.version = version;
- this.loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- this.dbEngine = new JanusGraphDBEngine(queryStyle, loader);
-
+ setHttpEntryProperties(version);
this.notification = notification;
-
- if ("true".equals(AAIConfig.get("aai.notification.depth.all.enabled", "true"))) {
- this.notificationDepth = AAIProperties.MAXIMUM_DEPTH;
- } else {
- this.notificationDepth = AAIProperties.MINIMUM_DEPTH;
- }
- // start transaction on creation
- getDbEngine().startTransaction();
return this;
}
public HttpEntry setHttpEntryProperties(SchemaVersion version, UEBNotification notification,
int notificationDepth) {
- this.version = version;
- this.loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- this.dbEngine = new JanusGraphDBEngine(queryStyle, loader);
-
+ setHttpEntryProperties(version);
this.notification = notification;
this.notificationDepth = notificationDepth;
- // start transaction on creation
- getDbEngine().startTransaction();
return this;
}
- /**
- * Gets the introspector factory type.
- *
- * @return the introspector factory type
- */
public ModelType getIntrospectorFactoryType() {
return introspectorFactoryType;
}
- /**
- * Gets the query style.
- *
- * @return the query style
- */
public QueryStyle getQueryStyle() {
return queryStyle;
}
- /**
- * Gets the version.
- *
- * @return the version
- */
public SchemaVersion getVersion() {
return version;
}
- /**
- * Gets the loader.
- *
- * @return the loader
- */
public Loader getLoader() {
return loader;
}
- /**
- * Gets the db engine.
- *
- * @return the db engine
- */
public TransactionalGraphEngine getDbEngine() {
return dbEngine;
}
- public Pair<Boolean, List<Pair<URI, Response>>> process(List<DBRequest> requests, String sourceOfTruth,
- Set<String> groups) throws AAIException {
- return this.process(requests, sourceOfTruth, groups, true);
- }
-
- public Pair<Boolean, List<Pair<URI, Response>>> process(List<DBRequest> requests, String sourceOfTruth)
- throws AAIException {
+ public Pair<Boolean, List<Pair<URI, Response>>> process(List<DBRequest> requests, String sourceOfTruth) throws AAIException {
return this.process(requests, sourceOfTruth, true);
}
- /**
- * Checks the pagination bucket and pagination index variables to determine whether or not the user
- * requested paginated results
- *
- * @return a boolean true/false of whether the user requested paginated results
- */
- public boolean isPaginated() {
- return this.paginationBucket > -1 && this.paginationIndex > -1;
- }
-
- /**
- * Returns the pagination size
- *
- * @return integer of the size of results to be returned when paginated
- */
- public int getPaginationBucket() {
- return this.paginationBucket;
+ public Pair<Boolean, List<Pair<URI, Response>>> process(List<DBRequest> requests, String sourceOfTruth,boolean enableResourceVersion) throws AAIException {
+ return this.process(requests, sourceOfTruth, Collections.emptySet(), enableResourceVersion, null);
}
- /**
- * Setter for the pagination bucket variable which stores in this object the size of results to return
- *
- * @param pb
- */
- public void setPaginationBucket(int pb) {
- this.paginationBucket = pb;
+ public Pair<Boolean, List<Pair<URI, Response>>> process(List<DBRequest> requests, String sourceOfTruth, Set<String> groups) throws AAIException {
+ return this.process(requests, sourceOfTruth, groups, true, null);
}
- /**
- * Getter to return the pagination index requested by the user when requesting paginated results
- *
- * @return
- */
- public int getPaginationIndex() {
- return this.paginationIndex;
- }
- /**
- * Sets the pagination index that was passed in by the user, to determine which index or results to retrieve when
- * paginated
- *
- * @param pi
- */
- public void setPaginationIndex(int pi) {
- if (pi == 0) {
- pi = 1;
- }
- this.paginationIndex = pi;
- }
-
- /**
- * Sets the total vertices variables and calculates the amount of pages based on size and total vertices
- *
- * @param totalVertices
- * @param paginationBucketSize
- */
- public void setTotalsForPaging(int totalVertices, int paginationBucketSize) {
- this.totalVertices = totalVertices;
- // set total number of buckets equal to full pages
- this.totalPaginationBuckets = totalVertices / paginationBucketSize;
- // conditionally add a page for the remainder
- if (totalVertices % paginationBucketSize > 0) {
- this.totalPaginationBuckets++;
- }
- }
-
- /**
- * @return the total amount of pages
- */
- public int getTotalPaginationBuckets() {
- return this.totalPaginationBuckets;
- }
-
- /**
- *
- * @return the total number of vertices when paginated
- */
- public int getTotalVertices() {
- return this.totalVertices;
- }
-
- /**
- * Process.
- *
- * @param requests the requests
- * @param sourceOfTruth the source of truth
- *
- * @return the pair
- * @throws AAIException the AAI exception
- */
public Pair<Boolean, List<Pair<URI, Response>>> process(List<DBRequest> requests, String sourceOfTruth,
- boolean enableResourceVersion) throws AAIException {
- return this.process(requests, sourceOfTruth, Collections.EMPTY_SET, enableResourceVersion);
- }
-
- private Pair<Boolean, List<Pair<URI, Response>>> process(List<DBRequest> requests, String sourceOfTruth,
- Set<String> groups, boolean enableResourceVersion) throws AAIException {
+ Set<String> groups, boolean enableResourceVersion, QueryOptions queryOptions) throws AAIException {
DBSerializer serializer = null;
-
if (serverBase != null) {
serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, sourceOfTruth, groups,
notificationDepth, serverBase);
notificationDepth);
}
- Response response;
- Introspector obj;
- QueryParser query;
- URI uri;
- String transactionId = null;
- int depth;
- Format format = null;
- List<Pair<URI, Response>> responses = new ArrayList<>();
- MultivaluedMap<String, String> params;
- HttpMethod method;
- String uriTemp;
- boolean success = true;
- QueryEngine queryEngine = dbEngine.getQueryEngine();
Set<Vertex> mainVertexesToNotifyOn = new LinkedHashSet<>();
-
AaiDBMetricLog metricLog = new AaiDBMetricLog(AAIConstants.AAI_RESOURCES_MS);
String outputMediaType = null;
-
if (requests != null && !requests.isEmpty()) {
HttpHeaders headers = requests.get(0).getHeaders();
outputMediaType = getMediaType(headers.getAcceptableMediaTypes());
}
+ String transactionId = requests.get(0).getTransactionId();
+ boolean success = true;
+ QueryEngine queryEngine = dbEngine.getQueryEngine();
+ List<Pair<URI, Response>> responses = new ArrayList<>();
for (DBRequest request : requests) {
- response = null;
+ Response response = null;
Status status = Status.NOT_FOUND;
- method = request.getMethod();
+ HttpMethod method = request.getMethod();
metricLog.pre(request);
try {
try {
-
- obj = request.getIntrospector();
- query = request.getParser();
- transactionId = request.getTransactionId();
- uriTemp = request.getUri().getRawPath().replaceFirst("^v\\d+/", "");
- uri = UriBuilder.fromPath(uriTemp).build();
-
- boolean groupsAvailable = serializer.getGroups() != null && !serializer.getGroups().isEmpty();
- List<Vertex> queryResult = query.getQueryBuilder().toList();
- List<Vertex> vertices;
- if (this.isPaginated()) {
- List<Vertex> vertTemp = groupsAvailable ? queryResult.stream().filter((vx) -> {
- return OwnerCheck.isAuthorized(groups, vx);
- }).collect(Collectors.toList()) : queryResult;
- this.setTotalsForPaging(vertTemp.size(), this.paginationBucket);
- vertices = vertTemp.subList(((this.paginationIndex - 1) * this.paginationBucket),
- Math.min((this.paginationBucket * this.paginationIndex), vertTemp.size()));
+ String uriTemp = request.getUri().getRawPath().replaceFirst("^v\\d+/", "");
+
+ QueryParser query = request.getParser();
+ List<Vertex> queryResult;
+ PaginationResult<Vertex> paginationResult = null;
+ if(queryOptions != null && queryOptions.getPageable() != null) {
+ paginationResult = executePaginatedQuery(query, queryOptions);
+ queryResult = paginationResult.getResults();
} else {
- vertices = groupsAvailable && queryResult.size() > 1 ? queryResult.stream().filter((vx) -> {
- return OwnerCheck.isAuthorized(groups, vx);
- }).collect(Collectors.toList()) : queryResult;
-
+ queryResult = executeQuery(query, queryOptions);
}
- boolean isNewVertex;
- HttpHeaders headers = request.getHeaders();
- outputMediaType = getMediaType(headers.getAcceptableMediaTypes());
- String result = null;
- params = request.getInfo().getQueryParameters(false);
- depth = setDepth(obj, params.getFirst("depth"));
+ boolean groupsAvailable = serializer.getGroups() != null && !serializer.getGroups().isEmpty();
+ List<Vertex> vertices = groupsAvailable
+ ? queryResult.stream()
+ .filter(vertex -> OwnerCheck.isAuthorized(groups, vertex))
+ .collect(Collectors.toList())
+ : queryResult;
+
+ MultivaluedMap<String, String> params = request.getInfo().getQueryParameters(false);
+ Introspector obj = request.getIntrospector();
+ int depth = setDepth(obj, params.getFirst("depth"));
+ Format format = null;
if (params.containsKey("format")) {
format = Format.getFormat(params.getFirst("format"));
}
- String cleanUp = params.getFirst("cleanup");
- String requestContext = "";
- List<String> requestContextList = request.getHeaders().getRequestHeader("aai-request-context");
- if (requestContextList != null) {
- requestContext = requestContextList.get(0);
- }
+ String cleanUp = params.getFirst("cleanup");
if (cleanUp == null) {
cleanUp = "false";
}
- if (vertices.size() > 1 && processSingle
+ if (vertices.size() > 1
&& !(method.equals(HttpMethod.GET) || method.equals(HttpMethod.GET_RELATIONSHIP))) {
if (method.equals(HttpMethod.DELETE)) {
throw new AAIException("AAI_6137");
}
}
+ boolean isNewVertex;
if (method.equals(HttpMethod.PUT)) {
String resourceVersion = obj.getValue(AAIProperties.RESOURCE_VERSION);
if (vertices.isEmpty()) {
HashMap<String, Introspector> relatedObjects = new HashMap<>();
String nodeOnly = params.getFirst("nodes-only");
boolean isNodeOnly = nodeOnly != null;
+
+ String requestContext = "";
+ List<String> requestContextList = request.getHeaders().getRequestHeader("aai-request-context");
+ if (requestContextList != null) {
+ requestContext = requestContextList.get(0);
+ }
+ URI uri = UriBuilder.fromPath(uriTemp).build();
+ HttpHeaders headers = request.getHeaders();
+ outputMediaType = getMediaType(headers.getAcceptableMediaTypes());
+ String result = null;
switch (method) {
case GET:
if (obj != null) {
status = Status.OK;
MarshallerProperties properties;
- if (!request.getMarshallerProperties().isPresent()) {
+ if (request.getMarshallerProperties().isEmpty()) {
properties = new MarshallerProperties.Builder(
org.onap.aai.restcore.MediaType.getEnum(outputMediaType)).build();
} else {
// The format is purposefully %s/%s%s due to the fact
// that every aai-uri will have a slash at the beginning
// If that assumption isn't true, then its best to change this code
- String curUri = String.format("%s/%s%s", basePath, version, entry.getKey());
+ String curUri = "%s/%s%s".formatted(basePath, version, entry.getKey());
Introspector curObj = entry.getValue().getValue0();
HashMap<String, Introspector> curObjRelated = entry.getValue().getValue1();
notification.createNotificationEvent(transactionId, sourceOfTruth,
*/
if (isDelVerticesPresent) {
- this.buildNotificationEvent(sourceOfTruth, status, transactionId, notification,
+ notificationService.buildNotificationEvent(sourceOfTruth, status, transactionId, notification,
deleteObjects, uriMap, deleteRelatedObjects, basePath);
}
break;
) {
String myvertid = v.id().toString();
- if (this.isPaginated()) {
+ if (paginationResult != null && paginationResult.getTotalCount() != null) {
+ long totalPages = getTotalPages(queryOptions, paginationResult);
response = Response.status(status).header("vertex-id", myvertid)
- .header("total-results", this.getTotalVertices())
- .header("total-pages", this.getTotalPaginationBuckets()).entity(result)
+ .header("total-results", paginationResult.getTotalCount())
+ .header("total-pages", totalPages)
+ .entity(result)
.type(outputMediaType).build();
} else {
response = Response.status(status).header("vertex-id", myvertid).entity(result)
}
if (success) {
- generateEvents(sourceOfTruth, serializer, transactionId, queryEngine, mainVertexesToNotifyOn);
+ notificationService.generateEvents(notification, notificationDepth, sourceOfTruth, serializer, transactionId, queryEngine, mainVertexesToNotifyOn, version);
} else {
notification.clearEvents();
}
return Pair.with(success, responses);
}
- /**
- * Generate notification events for the resulting db requests.
- */
- private void generateEvents(String sourceOfTruth, DBSerializer serializer, String transactionId,
- QueryEngine queryEngine, Set<Vertex> mainVertexesToNotifyOn) throws AAIException {
- if (notificationDepth == AAIProperties.MINIMUM_DEPTH) {
- serializer.getUpdatedVertexes().entrySet().stream().filter(Map.Entry::getValue).map(Map.Entry::getKey)
- .forEach(mainVertexesToNotifyOn::add);
- }
- Set<Vertex> edgeVertexes = serializer.touchStandardVertexPropertiesForEdges().stream()
- .filter(v -> !mainVertexesToNotifyOn.contains(v)).collect(Collectors.toSet());
- try {
- createNotificationEvents(mainVertexesToNotifyOn, sourceOfTruth, serializer, transactionId, queryEngine,
- notificationDepth);
- if ("true".equals(AAIConfig.get("aai.notification.both.sides.enabled", "true"))) {
- createNotificationEvents(edgeVertexes, sourceOfTruth, serializer, transactionId, queryEngine,
- AAIProperties.MINIMUM_DEPTH);
- }
- } catch (UnsupportedEncodingException e) {
- LOGGER.warn("Encountered exception generating events", e);
- }
-
- // Since @Autowired required is set to false, we need to do a null check
- // for the existence of the validationService since its only enabled if profile is enabled
- if (validationService != null) {
- validationService.validate(notification.getEvents());
- }
- notification.triggerEvents();
- if (isDeltaEventsEnabled) {
- try {
- DeltaEvents deltaEvents =
- new DeltaEvents(transactionId, sourceOfTruth, version.toString(), serializer.getObjectDeltas());
- deltaEvents.triggerEvents();
- } catch (Exception e) {
- LOGGER.error("Error sending Delta Events", e);
- }
+ private long getTotalPages(QueryOptions queryOptions, PaginationResult<Vertex> paginationResult) {
+ long totalCount = paginationResult.getTotalCount();
+ int pageSize = queryOptions.getPageable().getPageSize();
+ long totalPages = totalCount / pageSize;
+ // conditionally add a page for the remainder
+ if (totalCount % pageSize > 0) {
+ totalPages++;
}
+ return totalPages;
}
- /**
- * Generate notification events for provided set of vertexes at the specified depth
- */
- private void createNotificationEvents(Set<Vertex> vertexesToNotifyOn, String sourceOfTruth, DBSerializer serializer,
- String transactionId, QueryEngine queryEngine, int eventDepth)
- throws AAIException, UnsupportedEncodingException {
- for (Vertex vertex : vertexesToNotifyOn) {
- if (canGenerateEvent(vertex)) {
- boolean isCurVertexNew =
- vertex.value(AAIProperties.CREATED_TS).equals(vertex.value(AAIProperties.LAST_MOD_TS));
- Status curObjStatus = (isCurVertexNew) ? Status.CREATED : Status.OK;
-
- Introspector curObj = serializer.getLatestVersionView(vertex, eventDepth);
- String aaiUri = vertex.<String>property(AAIProperties.AAI_URI).value();
- String uri = String.format("%s/%s%s", basePath, version, aaiUri);
- HashMap<String, Introspector> curRelatedObjs = new HashMap<>();
- if (!curObj.isTopLevel()) {
- curRelatedObjs = serializer.getRelatedObjects(queryEngine, vertex, curObj, this.loader);
- }
- notification.createNotificationEvent(transactionId, sourceOfTruth, curObjStatus, URI.create(uri),
- curObj, curRelatedObjs, basePath);
- }
- }
+ private List<Vertex> executeQuery(QueryParser query, QueryOptions queryOptions) {
+ return (queryOptions != null && queryOptions.getSort() != null)
+ ? query.getQueryBuilder().sort(queryOptions.getSort()).toList()
+ : query.getQueryBuilder().toList();
}
- /**
- * Verifies that vertex has needed properties to generate on
- *
- * @param vertex Vertex to be verified
- * @return <code>true</code> if vertex has necessary properties and exists
- */
- private boolean canGenerateEvent(Vertex vertex) {
- boolean canGenerate = true;
- try {
- if (!vertex.property(AAIProperties.AAI_URI).isPresent()) {
- LOGGER.debug("Encountered an vertex {} with missing aai-uri", vertex.id());
- canGenerate = false;
- } else if (!vertex.property(AAIProperties.CREATED_TS).isPresent()
- || !vertex.property(AAIProperties.LAST_MOD_TS).isPresent()) {
- LOGGER.debug("Encountered an vertex {} with missing timestamp", vertex.id());
- canGenerate = false;
- }
- } catch (IllegalStateException e) {
- if (e.getMessage().contains(" was removed")) {
- LOGGER.warn("Attempted to generate event for non existent vertex", e);
- } else {
- LOGGER.warn("Encountered exception generating events", e);
- }
- canGenerate = false;
- }
- return canGenerate;
+ private PaginationResult<Vertex> executePaginatedQuery(QueryParser query, QueryOptions queryOptions) {
+ return queryOptions.getSort() != null
+ ? query.getQueryBuilder().sort(queryOptions.getSort()).toPaginationResult(queryOptions.getPageable())
+ : query.getQueryBuilder().toPaginationResult(queryOptions.getPageable());
}
- /**
- * Gets the media type.
- *
- * @param mediaTypeList the media type list
- * @return the media type
- */
private String getMediaType(List<MediaType> mediaTypeList) {
String mediaType = MediaType.APPLICATION_JSON; // json is the default
for (MediaType mt : mediaTypeList) {
return mediaType;
}
- /**
- * Gets the object from db.
- *
- * @param serializer the serializer
- * @param query the query
- * @param obj the obj
- * @param uri the uri
- * @param depth the depth
- * @param cleanUp the clean up
- * @return the object from db
- * @throws AAIException the AAI exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws SecurityException the security exception
- * @throws InstantiationException the instantiation exception
- * @throws NoSuchMethodException the no such method exception
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws MalformedURLException the malformed URL exception
- * @throws AAIUnknownObjectException
- * @throws URISyntaxException
- */
private Introspector getObjectFromDb(List<Vertex> results, DBSerializer serializer, QueryParser query,
Introspector obj, URI uri, int depth, boolean nodeOnly, String cleanUp)
throws AAIException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
}
- /**
- * Gets the object from db.
- *
- * @param serializer the serializer
- * @param query the query
- * @param obj the obj
- * @param uri the uri
- * @param depth the depth
- * @param cleanUp the clean up
- * @param isSkipRelatedTo include related to flag
- * @return the object from db
- * @throws AAIException the AAI exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws SecurityException the security exception
- * @throws InstantiationException the instantiation exception
- * @throws NoSuchMethodException the no such method exception
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws MalformedURLException the malformed URL exception
- * @throws AAIUnknownObjectException
- * @throws URISyntaxException
- */
private Introspector getObjectFromDb(List<Vertex> results, DBSerializer serializer, QueryParser query,
Introspector obj, URI uri, int depth, boolean nodeOnly, String cleanUp, boolean isSkipRelatedTo)
throws AAIException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
}
- /**
- * Gets the object from db.
- *
- * @param serializer the serializer
- * @param query the query
- * @param uri the uri
- * @return the object from db
- * @throws AAIException the AAI exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws SecurityException the security exception
- * @throws InstantiationException the instantiation exception
- * @throws NoSuchMethodException the no such method exception
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws MalformedURLException the malformed URL exception
- * @throws AAIUnknownObjectException
- * @throws URISyntaxException
- */
private Introspector getRelationshipObjectFromDb(List<Vertex> results, DBSerializer serializer, QueryParser query,
URI uri, boolean isSkipRelatedTo) throws AAIException, IllegalArgumentException, SecurityException,
UnsupportedEncodingException, AAIUnknownObjectException {
return serializer.dbToRelationshipObject(v, isSkipRelatedTo);
}
- /**
- * Creates the not found message.
- *
- * @param resultType the result type
- * @param uri the uri
- * @return the string
- */
private String createNotFoundMessage(String resultType, URI uri) {
return "No Node of type " + resultType + " found at: " + uri.getPath();
}
- /**
- * Creates the not found message.
- *
- * @param resultType the result type
- * @param uri the uri
- * @return the string
- */
private String createRelationshipNotFoundMessage(String resultType, URI uri) {
return "No relationship found of type " + resultType + " at the given URI: " + uri.getPath()
+ "/relationship-list";
}
- /**
- * Sets the depth.
- *
- * @param depthParam the depth param
- * @return the int
- * @throws AAIException the AAI exception
- */
protected int setDepth(Introspector obj, String depthParam) throws AAIException {
int depth = AAIProperties.MAXIMUM_DEPTH;
return relatedObjectsMap;
}
-
- private void buildNotificationEvent(String sourceOfTruth, Status status, String transactionId,
- UEBNotification notification, Map<Vertex, Introspector> deleteObjects, Map<String, URI> uriMap,
- Map<String, HashMap<String, Introspector>> deleteRelatedObjects, String basePath) {
- for (Map.Entry<Vertex, Introspector> entry : deleteObjects.entrySet()) {
- try {
- if (null != entry.getValue()) {
- String vertexObjectId = entry.getValue().getObjectId();
-
- if (uriMap.containsKey(vertexObjectId) && deleteRelatedObjects.containsKey(vertexObjectId)) {
- notification.createNotificationEvent(transactionId, sourceOfTruth, status,
- uriMap.get(vertexObjectId), entry.getValue(), deleteRelatedObjects.get(vertexObjectId),
- basePath);
- }
- }
- } catch (UnsupportedEncodingException | AAIException e) {
-
- LOGGER.warn("Error in sending notification");
- }
- }
- }
-
- public void setPaginationParameters(String resultIndex, String resultSize) {
- if (resultIndex != null && !"-1".equals(resultIndex) && resultSize != null && !"-1".equals(resultSize)) {
- this.setPaginationIndex(Integer.parseInt(resultIndex));
- this.setPaginationBucket(Integer.parseInt(resultSize));
- }
- }
-
- public List<Object> getPaginatedVertexListForAggregateFormat(List<Object> aggregateVertexList) throws AAIException {
- List<Object> finalList = new Vector<>();
- if (this.isPaginated()) {
- if (aggregateVertexList != null && !aggregateVertexList.isEmpty()) {
- int listSize = aggregateVertexList.size();
- if (listSize == 1) {
- List<Object> vertexList = (List<Object>) aggregateVertexList.get(0);
- this.setTotalsForPaging(vertexList.size(), this.getPaginationBucket());
- int startIndex = (this.getPaginationIndex() - 1) * this.getPaginationBucket();
- int endIndex =
- Math.min((this.getPaginationBucket() * this.getPaginationIndex()), vertexList.size());
- if (startIndex > endIndex) {
- throw new AAIException("AAI_6150",
- " ResultIndex is not appropriate for the result set, Needs to be <= " + endIndex);
- }
- finalList.add(new ArrayList<Object>());
- for (int i = startIndex; i < endIndex; i++) {
- ((ArrayList<Object>) finalList.get(0))
- .add(((ArrayList<Object>) aggregateVertexList.get(0)).get(i));
- }
- return finalList;
- }
- }
- }
- // If the list size is greater than 1 or if pagination is not needed, return the original list.
- return aggregateVertexList;
- }
-
- public List<Object> getPaginatedVertexList(List<Object> vertexList) throws AAIException {
- List<Object> vertices;
- if (this.isPaginated()) {
- this.setTotalsForPaging(vertexList.size(), this.getPaginationBucket());
- int startIndex = (this.getPaginationIndex() - 1) * this.getPaginationBucket();
- int endIndex = Math.min((this.getPaginationBucket() * this.getPaginationIndex()), vertexList.size());
- if (startIndex > endIndex) {
- throw new AAIException("AAI_6150",
- " ResultIndex is not appropriate for the result set, Needs to be <= " + endIndex);
- }
- vertices = vertexList.subList(startIndex, endIndex);
- } else {
- vertices = vertexList;
- }
- return vertices;
- }
}
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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.rest.notification;
+
+import java.util.List;
+
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.exceptions.AAIUnmarshallingException;
+import org.onap.aai.parsers.uri.URIToObject;
+
+import lombok.Value;
+
+@Value
+public class EntityConverter {
+
+ final URIToObject parser;
+
+ public Introspector convert(Introspector obj) throws AAIUnmarshallingException {
+ List<Object> parentList = parser.getParentList();
+ parentList.clear();
+
+ if (!parser.getTopEntity().equals(parser.getEntity())) {
+ Introspector child = obj;
+ if (!parser.getLoader().getVersion().equals(obj.getVersion())) {
+ String json = obj.marshal(false);
+ child = parser.getLoader().unmarshal(parser.getEntity().getName(), json);
+ }
+
+ // wrap the child object in its parents
+ parentList.add(child.getUnderlyingObject());
+ }
+
+ final Introspector eventObject;
+ if (parser.getTopEntity().equals(parser.getEntity())) {
+ // take the top level parent object passed in
+ eventObject = obj;
+ } else {
+ // take the wrapped child objects (ogres are like onions)
+ eventObject = parser.getTopEntity();
+ }
+
+ return eventObject;
+ }
+
+ public String getTopEntityName() {
+ return parser.getTopEntityName();
+ }
+}
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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.rest.notification;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import jakarta.ws.rs.core.Response.Status;
+
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.onap.aai.db.props.AAIProperties;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.LoaderFactory;
+import org.onap.aai.kafka.NotificationProducer;
+import org.onap.aai.prevalidation.ValidationService;
+import org.onap.aai.serialization.db.DBSerializer;
+import org.onap.aai.serialization.engines.query.QueryEngine;
+import org.onap.aai.setup.SchemaVersion;
+import org.onap.aai.util.AAIConfig;
+import org.onap.aai.util.delta.DeltaEvents;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.lang.Nullable;
+import org.springframework.stereotype.Service;
+
+@Service
+public class NotificationService {
+
+ public static final Logger LOGGER = LoggerFactory.getLogger(NotificationService.class);
+
+ private final ValidationService validationService;
+ private final NotificationProducer notificationProducer;
+ private final LoaderFactory loaderFactory;
+ private final boolean isDeltaEventsEnabled;
+ private final String basePath;
+
+ public NotificationService(
+ @Nullable ValidationService validationService,
+ LoaderFactory loaderFactory,
+ @Value("${schema.uri.base.path}") String basePath,
+ @Value("${delta.events.enabled:false}") boolean isDeltaEventsEnabled,
+ NotificationProducer notificationProducer) {
+ this.validationService = validationService;
+ this.loaderFactory = loaderFactory;
+ this.basePath = basePath;
+ this.isDeltaEventsEnabled = isDeltaEventsEnabled;
+ this.notificationProducer = notificationProducer;
+ }
+
+ /**
+ * Generate notification events for the resulting db requests.
+ */
+ public void generateEvents(UEBNotification notification, int notificationDepth, String sourceOfTruth, DBSerializer serializer,
+ String transactionId,
+ QueryEngine queryEngine, Set<Vertex> mainVertexesToNotifyOn, SchemaVersion schemaVersion) throws AAIException {
+ if (notificationDepth == AAIProperties.MINIMUM_DEPTH) {
+ serializer.getUpdatedVertexes().entrySet().stream()
+ .filter(Map.Entry::getValue)
+ .map(Map.Entry::getKey)
+ .forEach(mainVertexesToNotifyOn::add);
+ }
+ Set<Vertex> edgeVertexes = serializer.touchStandardVertexPropertiesForEdges().stream()
+ .filter(v -> !mainVertexesToNotifyOn.contains(v))
+ .collect(Collectors.toSet());
+
+ try {
+ createNotificationEvents(mainVertexesToNotifyOn, notification, sourceOfTruth, serializer, transactionId, queryEngine,
+ notificationDepth, schemaVersion);
+ if ("true".equals(AAIConfig.get("aai.notification.both.sides.enabled", "true"))) {
+ createNotificationEvents(edgeVertexes, notification, sourceOfTruth, serializer, transactionId, queryEngine,
+ AAIProperties.MINIMUM_DEPTH, schemaVersion);
+ }
+ } catch (UnsupportedEncodingException e) {
+ LOGGER.warn("Encountered exception generating events", e);
+ }
+
+ // validation is configurable via aai.notification.validation.enabled
+ if (validationService != null) {
+ validationService.validate(notification.getEvents());
+ }
+
+ notificationProducer.sendUEBNotification(notification);
+ if (isDeltaEventsEnabled) {
+ try {
+ DeltaEvents deltaEvents = new DeltaEvents(transactionId, sourceOfTruth, schemaVersion.toString(),
+ serializer.getObjectDeltas());
+ deltaEvents.triggerEvents();
+ } catch (Exception e) {
+ LOGGER.error("Error sending Delta Events", e);
+ }
+ }
+ }
+
+ /**
+ * Generate notification events for provided set of vertexes at the specified
+ * depth
+ */
+ private void createNotificationEvents(Set<Vertex> vertexesToNotifyOn, UEBNotification notification, String sourceOfTruth, DBSerializer serializer,
+ String transactionId, QueryEngine queryEngine, int eventDepth, SchemaVersion schemaVersion)
+ throws AAIException, UnsupportedEncodingException {
+ for (Vertex vertex : vertexesToNotifyOn) {
+ if (canGenerateEvent(vertex)) {
+ boolean isVertexNew = vertex.value(AAIProperties.CREATED_TS).equals(vertex.value(AAIProperties.LAST_MOD_TS));
+ Status curObjStatus = isVertexNew ? Status.CREATED : Status.OK;
+
+ Introspector curObj = serializer.getLatestVersionView(vertex, eventDepth);
+ String aaiUri = vertex.<String>property(AAIProperties.AAI_URI).value();
+ String uri = "%s/%s%s".formatted(basePath, schemaVersion, aaiUri);
+ HashMap<String, Introspector> curRelatedObjs = new HashMap<>();
+ if (!curObj.isTopLevel()) {
+ curRelatedObjs = serializer.getRelatedObjects(queryEngine, vertex, curObj, loaderFactory.getMoxyLoaderInstance().get(schemaVersion));
+ }
+ notification.createNotificationEvent(transactionId, sourceOfTruth, curObjStatus, URI.create(uri),
+ curObj, curRelatedObjs, basePath);
+ }
+ }
+ }
+
+ /**
+ * Verifies that vertex has needed properties to generate on
+ *
+ * @param vertex Vertex to be verified
+ * @return <code>true</code> if vertex has necessary properties and exists
+ */
+ private boolean canGenerateEvent(Vertex vertex) {
+ boolean canGenerate = true;
+ try {
+ if (!vertex.property(AAIProperties.AAI_URI).isPresent()) {
+ LOGGER.debug("Encountered an vertex {} with missing aai-uri", vertex.id());
+ canGenerate = false;
+ } else if (!vertex.property(AAIProperties.CREATED_TS).isPresent()
+ || !vertex.property(AAIProperties.LAST_MOD_TS).isPresent()) {
+ LOGGER.debug("Encountered an vertex {} with missing timestamp", vertex.id());
+ canGenerate = false;
+ }
+ } catch (IllegalStateException e) {
+ if (e.getMessage().contains(" was removed")) {
+ LOGGER.warn("Attempted to generate event for non existent vertex", e);
+ } else {
+ LOGGER.warn("Encountered exception generating events", e);
+ }
+ canGenerate = false;
+ }
+ return canGenerate;
+ }
+
+ public void buildNotificationEvent(String sourceOfTruth, Status status, String transactionId,
+ UEBNotification notification, Map<Vertex, Introspector> deleteObjects, Map<String, URI> uriMap,
+ Map<String, HashMap<String, Introspector>> deleteRelatedObjects, String basePath) {
+ for (Map.Entry<Vertex, Introspector> entry : deleteObjects.entrySet()) {
+ try {
+ if (null != entry.getValue()) {
+ String vertexObjectId = entry.getValue().getObjectId();
+
+ if (uriMap.containsKey(vertexObjectId) && deleteRelatedObjects.containsKey(vertexObjectId)) {
+ notification.createNotificationEvent(transactionId, sourceOfTruth, status,
+ uriMap.get(vertexObjectId), entry.getValue(), deleteRelatedObjects.get(vertexObjectId),
+ basePath);
+ }
+ }
+ } catch (UnsupportedEncodingException | AAIException e) {
+
+ LOGGER.warn("Error in sending notification");
+ }
+ }
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Modifications Copyright © 2024 Deutsche Telekom.
+ * ================================================================================
+ * 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.rest.notification;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import jakarta.ws.rs.core.Response.Status;
+
+import org.onap.aai.domain.notificationEvent.NotificationEvent;
+import org.onap.aai.domain.notificationEvent.NotificationEvent.EventHeader;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.LoaderFactory;
+import org.onap.aai.introspection.ModelType;
+import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
+import org.onap.aai.introspection.exceptions.AAIUnmarshallingException;
+import org.onap.aai.logging.LogFormatTools;
+import org.onap.aai.parsers.uri.URIToObject;
+import org.onap.aai.setup.SchemaVersion;
+import org.onap.aai.setup.SchemaVersions;
+import org.onap.aai.util.AAIConfig;
+import org.onap.aai.util.AAIConstants;
+import org.onap.aai.util.FormatDate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class UEBNotification {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(UEBNotification.class);
+ private static final FormatDate FORMAT_DATE = new FormatDate("YYYYMMdd-HH:mm:ss:SSS");
+ private static final String EVENT_TYPE = "AAI-EVENT";
+
+ private final String domain = AAIConfig.get("aai.notificationEvent.default.domain", "UNK");
+ private final String sequenceNumber = AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK");
+ private final String severity = AAIConfig.get("aai.notificationEvent.default.severity", "UNK");
+ private final Map<String, NotificationEvent> events;
+ private final Loader currentVersionLoader;
+ private final SchemaVersion notificationVersion;
+
+ public UEBNotification(LoaderFactory loaderFactory, SchemaVersions schemaVersions) {
+ events = new LinkedHashMap<>();
+ notificationVersion = schemaVersions.getDefaultVersion();
+ currentVersionLoader = loaderFactory.createLoaderForVersion(ModelType.MOXY, notificationVersion);
+ }
+
+ public void createNotificationEvent(String transactionId, String sourceOfTruth, Status status, URI uri,
+ Introspector obj, HashMap<String, Introspector> relatedObjects, String basePath)
+ throws AAIException, UnsupportedEncodingException {
+
+ String action = getAction(status);
+
+ try {
+ EntityConverter entityConverter = new EntityConverter(new URIToObject(currentVersionLoader, uri, relatedObjects));
+ EventHeader eventHeader = new EventHeader();
+
+ basePath = formatBasePath(basePath);
+ String entityLink = formatEntityLink(uri, basePath);
+ eventHeader.setEntityLink(entityLink);
+ eventHeader.setAction(action);
+ eventHeader.setEntityType(obj.getDbName());
+ eventHeader.setTopEntityType(entityConverter.getTopEntityName());
+ eventHeader.setSourceName(sourceOfTruth);
+ eventHeader.setVersion(notificationVersion.toString());
+ eventHeader.setId(transactionId);
+
+ // default values
+ eventHeader.setTimestamp(FORMAT_DATE.getDateTime());
+ eventHeader.setEventType(EVENT_TYPE);
+ eventHeader.setDomain(domain);
+ eventHeader.setSequenceNumber(sequenceNumber);
+ eventHeader.setSeverity(severity);
+
+ Introspector entity = entityConverter.convert(obj);
+
+ final NotificationEvent event = new NotificationEvent();
+ event.setEventHeader(eventHeader);
+ event.setCambriaPartition(AAIConstants.UEB_PUB_PARTITION_AAI);
+ event.setEntity(entity);
+ events.put(uri.toString(), event);
+ } catch (AAIUnknownObjectException e) {
+ throw new RuntimeException("Fatal error - notification-event-header object not found!");
+ } catch (AAIUnmarshallingException e) {
+ LOGGER.error(
+ "Unmarshalling error occurred while generating UEBNotification " + LogFormatTools.getStackTop(e));
+ }
+ }
+
+ private String formatEntityLink(URI uri, String basePath) {
+ String uriStr = getUri(uri.toString(), basePath);
+ String entityLink;
+ if (uriStr.startsWith("/")) {
+ entityLink = basePath + notificationVersion + uriStr;
+ } else {
+ entityLink = basePath + notificationVersion + "/" + uriStr;
+ }
+ return entityLink;
+ }
+
+ private String formatBasePath(String basePath) {
+ if ((basePath != null) && (!basePath.isEmpty())) {
+ if (!(basePath.startsWith("/"))) {
+ basePath = "/" + basePath;
+ }
+ if (!(basePath.endsWith("/"))) {
+ basePath = basePath + "/";
+ }
+ } else {
+ // default
+ basePath = "/aai/";
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Please check the schema.uri.base.path as it didn't seem to be set");
+ }
+ }
+ return basePath;
+ }
+
+ private String getAction(Status status) {
+ String action = "UPDATE";
+
+ if (status.equals(Status.CREATED)) {
+ action = "CREATE";
+ } else if (status.equals(Status.OK)) {
+ action = "UPDATE";
+ } else if (status.equals(Status.NO_CONTENT)) {
+ action = "DELETE";
+ }
+ return action;
+ }
+
+ public List<NotificationEvent> getEvents() {
+ return new ArrayList<>(this.events.values());
+ }
+
+ private String getUri(String uri, String basePath) {
+ if (uri == null || uri.isEmpty()) {
+ return "";
+ } else if (uri.charAt(0) != '/') {
+ uri = '/' + uri;
+ }
+
+ if ((basePath != null) && (!basePath.isEmpty())) {
+ if (!(basePath.startsWith("/"))) {
+ basePath = "/" + basePath;
+ }
+ if (!(basePath.endsWith("/"))) {
+ basePath = basePath + "/";
+ }
+ }
+
+ LOGGER.trace("Notification header uri base path:'{}', uri:'{}'", basePath, uri);
+
+ return uri.replaceAll("^" + basePath + "v\\d+", "");
+ }
+
+ public void clearEvents() {
+ events.clear();
+ }
+}
+++ /dev/null
-/**
- * ============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.rest.ueb;
-
-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.util.StoreNotificationEvent;
-
-/**
- * The Class NotificationEvent.
- */
-public class NotificationEvent {
-
- private final Loader loader;
-
- private final Introspector eventHeader;
-
- private final Introspector obj;
- private final String transactionId;
- private final String sourceOfTruth;
-
- /**
- * Instantiates a new notification event.
- *
- * @param eventHeader the event header
- * @param obj the obj
- */
- public NotificationEvent(Loader loader, Introspector eventHeader, Introspector obj, String transactionId,
- String sourceOfTruth) {
- this.loader = loader;
- this.eventHeader = eventHeader;
- this.obj = obj;
- this.transactionId = transactionId;
- this.sourceOfTruth = sourceOfTruth;
- }
-
- /**
- * Trigger.
- *
- * @throws AAIException the AAI exception
- */
- public void trigger() throws AAIException {
-
- StoreNotificationEvent sne = new StoreNotificationEvent(transactionId, sourceOfTruth);
-
- sne.storeEventAndSendToJms(loader, eventHeader, obj);
-
- }
-
- public String getNotificationEvent() throws AAIException {
- return new StoreNotificationEvent(transactionId, sourceOfTruth).storeEventOnly(loader, eventHeader, obj);
- }
-
- /**
- * Gets the notification version.
- *
- * @return the notification version
- */
- public SchemaVersion getNotificationVersion() {
- return loader.getVersion();
- }
-
- /**
- * Gets the event header.
- *
- * @return the event header
- */
- public Introspector getEventHeader() {
- return eventHeader;
- }
-
- /**
- * Gets the obj.
- *
- * @return the obj
- */
- public Introspector getObj() {
- return obj;
- }
-
-}
+++ /dev/null
-/**
- * ============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.rest.ueb;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.ws.rs.core.Response.Status;
-
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.Introspector;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
-import org.onap.aai.introspection.exceptions.AAIUnmarshallingException;
-import org.onap.aai.logging.LogFormatTools;
-import org.onap.aai.parsers.uri.URIToObject;
-import org.onap.aai.setup.SchemaVersion;
-import org.onap.aai.setup.SchemaVersions;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * The Class UEBNotification.
- */
-public class UEBNotification {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(UEBNotification.class);
-
- private Loader currentVersionLoader = null;
- protected Map<String, NotificationEvent> events = null;
- private SchemaVersion notificationVersion = null;
-
- /**
- * Instantiates a new UEB notification.
- *
- * @param loader the loader
- */
- public UEBNotification(Loader loader, LoaderFactory loaderFactory, SchemaVersions schemaVersions) {
- events = new LinkedHashMap<>();
- SchemaVersion defaultVersion = schemaVersions.getDefaultVersion();
- currentVersionLoader = loaderFactory.createLoaderForVersion(loader.getModelType(), defaultVersion);
- notificationVersion = defaultVersion;
- }
-
- /**
- * Instantiates a new UEB notification.
- *
- * @param modelType - Model type
- * @param loaderFactory - the loader factory
- * @param schemaVersions the schema versions bean
- */
- public UEBNotification(ModelType modelType, LoaderFactory loaderFactory, SchemaVersions schemaVersions) {
- events = new LinkedHashMap<>();
- SchemaVersion defaultVersion = schemaVersions.getDefaultVersion();
- currentVersionLoader = loaderFactory.createLoaderForVersion(modelType, defaultVersion);
- notificationVersion = defaultVersion;
- }
-
- /**
- * Creates the notification event.
- *
- * @param transactionId the X-TransactionId
- * @param sourceOfTruth
- * @param status the status
- * @param uri the uri
- * @param obj the obj
- * @param basePath base URI path
- * @throws AAIException the AAI exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws UnsupportedEncodingException the unsupported encoding exception
- */
- public void createNotificationEvent(String transactionId, String sourceOfTruth, Status status, URI uri,
- Introspector obj, HashMap<String, Introspector> relatedObjects, String basePath)
- throws AAIException, UnsupportedEncodingException {
-
- String action = "UPDATE";
-
- if (status.equals(Status.CREATED)) {
- action = "CREATE";
- } else if (status.equals(Status.OK)) {
- action = "UPDATE";
- } else if (status.equals(Status.NO_CONTENT)) {
- action = "DELETE";
- }
-
- try {
- Introspector eventHeader = currentVersionLoader.introspectorFromName("notification-event-header");
- URIToObject parser = new URIToObject(currentVersionLoader, uri, relatedObjects);
-
- if ((basePath != null) && (!basePath.isEmpty())) {
- if (!(basePath.startsWith("/"))) {
- basePath = "/" + basePath;
- }
- if (!(basePath.endsWith("/"))) {
- basePath = basePath + "/";
- }
- } else {
- // default
- basePath = "/aai/";
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Please check the schema.uri.base.path as it didn't seem to be set");
- }
- }
-
- String uriStr = getUri(uri.toString(), basePath);
- String entityLink;
- if (uriStr.startsWith("/")) {
- entityLink = basePath + notificationVersion + uriStr;
- } else {
- entityLink = basePath + notificationVersion + "/" + uriStr;
- }
-
- eventHeader.setValue("entity-link", entityLink);
- eventHeader.setValue("action", action);
- eventHeader.setValue("entity-type", obj.getDbName());
- eventHeader.setValue("top-entity-type", parser.getTopEntityName());
- eventHeader.setValue("source-name", sourceOfTruth);
- eventHeader.setValue("version", notificationVersion.toString());
- eventHeader.setValue("id", transactionId);
-
- List<Object> parentList = parser.getParentList();
- parentList.clear();
-
- if (!parser.getTopEntity().equals(parser.getEntity())) {
- Introspector child = obj;
- if (!parser.getLoader().getVersion().equals(obj.getVersion())) {
- String json = obj.marshal(false);
- child = parser.getLoader().unmarshal(parser.getEntity().getName(), json);
- }
-
- // wrap the child object in its parents
- parentList.add(child.getUnderlyingObject());
- }
-
- final Introspector eventObject;
-
- // convert to most resent version
- if (!parser.getLoader().getVersion().equals(currentVersionLoader.getVersion())) {
- String json = "";
- if (parser.getTopEntity().equals(parser.getEntity())) {
- // convert the parent object passed in
- json = obj.marshal(false);
- eventObject = currentVersionLoader.unmarshal(obj.getName(), json);
- } else {
- // convert the object created in the parser
- json = parser.getTopEntity().marshal(false);
- eventObject = currentVersionLoader.unmarshal(parser.getTopEntity().getName(), json);
- }
- } else {
- if (parser.getTopEntity().equals(parser.getEntity())) {
- // take the top level parent object passed in
- eventObject = obj;
- } else {
- // take the wrapped child objects (ogres are like onions)
- eventObject = parser.getTopEntity();
- }
- }
- final NotificationEvent event =
- new NotificationEvent(currentVersionLoader, eventHeader, eventObject, transactionId, sourceOfTruth);
- events.put(uri.toString(), event);
- } catch (AAIUnknownObjectException e) {
- throw new RuntimeException("Fatal error - notification-event-header object not found!");
- } catch (AAIUnmarshallingException e) {
- LOGGER.error(
- "Unmarshalling error occurred while generating UEBNotification " + LogFormatTools.getStackTop(e));
- }
- }
-
- /**
- * Trigger events.
- *
- * @throws AAIException the AAI exception
- */
- public void triggerEvents() throws AAIException {
- for (NotificationEvent event : events.values()) {
- event.trigger();
- }
- clearEvents();
- }
-
- public List<NotificationEvent> getEvents() {
- return new ArrayList<>(this.events.values());
- }
-
- public Map<String, NotificationEvent> getEventsMap() {
- return this.events;
- }
-
- private String getUri(String uri, String basePath) {
- if (uri == null || uri.isEmpty()) {
- return "";
- } else if (uri.charAt(0) != '/') {
- uri = '/' + uri;
- }
-
- if ((basePath != null) && (!basePath.isEmpty())) {
- if (!(basePath.startsWith("/"))) {
- basePath = "/" + basePath;
- }
- if (!(basePath.endsWith("/"))) {
- basePath = basePath + "/";
- }
- }
-
- LOGGER.trace("Notification header uri base path:'{}', uri:'{}'", basePath, uri);
-
- return uri.replaceAll("^" + basePath + "v\\d+", "");
- }
-
- public void clearEvents() {
- events.clear();
- }
-}
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
-import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
-import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
+import com.fasterxml.jackson.jakarta.rs.json.JacksonXmlBindJsonProvider;
+import com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationModule;
-import javax.ws.rs.ext.Provider;
+import jakarta.ws.rs.ext.Provider;
/**
* The Class CustomJacksonJaxBJsonProvider.
*/
@Provider
-public class CustomJacksonJaxBJsonProvider extends JacksonJaxbJsonProvider {
+public class CustomJacksonJaxBJsonProvider extends JacksonXmlBindJsonProvider {
private static ObjectMapper commonMapper = null;
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
- mapper.registerModule(new JaxbAnnotationModule());
+ mapper.registerModule(new JakartaXmlBindAnnotationModule());
commonMapper = mapper;
}
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.UriInfo;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.exceptions.AAIException;
response = handler.get(timeoutLimit, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
AAIException ex = new AAIException("AAI_7406",
- String.format("Timeout limit of %s seconds reached.", timeoutLimit / 1000));
+ "Timeout limit of %s seconds reached.".formatted(timeoutLimit / 1000));
response = consumerExceptionResponseGenerator(headers, info, method, ex);
handler.cancel(true);
} catch (InterruptedException e) {
"org.apache.tinkerpop.gremlin.process.traversal.Order");
imports.addImports("org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__",
"org.apache.tinkerpop.gremlin.structure.T", "org.apache.tinkerpop.gremlin.process.traversal.P",
- "org.onap.aai.edges.enums.EdgeType", "java.util.Map.Entry");
+ "org.onap.aai.edges.enums.EdgeType", "java.util.Map.Entry","org.apache.tinkerpop.gremlin.process.traversal.Pop");
imports.addStarImports("java.util");
CompilerConfiguration config = new CompilerConfiguration();
config.addCompilationCustomizers(custom, imports);
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import javax.ws.rs.core.UriBuilder;
+import jakarta.ws.rs.core.UriBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.tinkerpop.gremlin.process.traversal.Path;
List<Vertex> results = parser.getQueryBuilder().toList();
if (results.isEmpty()) {
final AAIException ex =
- new AAIException(AAI_6129, String.format("Node of type %s. Could not find object at: %s",
+ new AAIException(AAI_6129, "Node of type %s. Could not find object at: %s".formatted(
parser.getResultType(), parser.getUri()));
ex.getTemplateVars().add(parser.getResultType());
ex.getTemplateVars().add(parser.getUri().toString());
// rule
}
throw new AAIException("AAI_6120",
- String.format("No EdgeRule found for passed nodeTypes: %s, %s.", aNodeType, bNodeType));
+ "No EdgeRule found for passed nodeTypes: %s, %s.".formatted(aNodeType, bNodeType));
} else {
try {
final List<EdgeRule> rules = new ArrayList<>(edgeIngestor.getRules(ruleQuery).values());
if (!edgeRules.hasRule(baseQ.build())) {
throw new AAIException("AAI_6120",
- String.format("No EdgeRule found for passed nodeTypes: %s, %s%s.", aNodeType, cousinType,
+ "No EdgeRule found for passed nodeTypes: %s, %s%s.".formatted(aNodeType, cousinType,
label != null ? (" with label " + label) : ""));
} else if (edgeRules.hasRule(baseQ.edgeType(EdgeType.TREE).build())
&& !edgeRules.hasRule(baseQ.edgeType(EdgeType.COUSIN).build())) {
package org.onap.aai.serialization.db;
+import java.io.Serial;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EdgePropertyMap<K, V> extends HashMap<K, V> {
+ @Serial
private static final long serialVersionUID = -8298355506617458683L;
private static final Pattern variablePattern = Pattern.compile("(!)?\\$\\{(\\w+)\\}");
package org.onap.aai.serialization.db;
-import java.util.EnumMap;
-import java.util.Map;
-import java.util.Map.Entry;
import java.util.Optional;
import java.util.UUID;
if (message.isPresent() && !isBestEffort) {
throw new EdgeMultiplicityException(message.get());
}
- if (!message.isPresent()) {
+ if (message.isEmpty()) {
if (rule.getDirection().equals(Direction.OUT)) {
e = aVertex.addEdge(rule.getLabel(), bVertex);
} else if (rule.getDirection().equals(Direction.IN)) {
if (message.isPresent() && !isBestEffort) {
throw new EdgeMultiplicityException(message.get());
}
- if (!message.isPresent()) {
+ if (message.isEmpty()) {
if (rule.getDirection().equals(Direction.OUT)) {
e = aVertex.addEdge(rule.getLabel(), bVertex);
} else if (rule.getDirection().equals(Direction.IN)) {
package org.onap.aai.serialization.db.exceptions;
+import java.io.Serial;
+
import org.onap.aai.exceptions.AAIException;
public class EdgeMultiplicityException extends AAIException {
+ @Serial
private static final long serialVersionUID = -5575661036426538012L;
public EdgeMultiplicityException(String message) {
package org.onap.aai.serialization.db.exceptions;
+import java.io.Serial;
+
import org.onap.aai.exceptions.AAIException;
public class MultipleEdgeRuleFoundException extends AAIException {
+ @Serial
private static final long serialVersionUID = -906843868234976763L;
public MultipleEdgeRuleFoundException(String message) {
package org.onap.aai.serialization.db.exceptions;
+import java.io.Serial;
+
import org.onap.aai.exceptions.AAIException;
public class NoEdgeRuleFoundException extends AAIException {
+ @Serial
private static final long serialVersionUID = -906843868234976763L;
public NoEdgeRuleFoundException(String message) {
try {
StopWatch.conditionalStart();
final GraphTraversal<Vertex, Vertex> pipe =
- this.g.V().has(AAIProperties.AAI_URI, P.within(uris)).order().by(AAIProperties.AAI_URI, Order.decr);
+ this.g.V().has(AAIProperties.AAI_URI, P.within(uris)).order().by(AAIProperties.AAI_URI, Order.desc);
return pipe.toList();
} finally {
dbTimeMsecs += StopWatch.stopIfStarted();
}
return Optional.<JsonObject>empty();
- }).filter(Optional::isPresent).map(Optional::get).forEach(json -> {
+ }).flatMap(Optional::stream).forEach(json -> {
if (isParallel) {
synchronized (body) {
body.add(json);
JsonArray inner = new JsonArray();
for (Vertex o : (ArrayList<Vertex>) l) {
if (o instanceof Vertex) {
- Optional<JsonObject> obj = this.getJsonFromVertex((Vertex) o, properties);
+ Optional<JsonObject> obj = this.getJsonFromVertex(o, properties);
if (obj.isPresent()) {
inner.add(obj.get());
} else {
final JsonObject countResult = new JsonObject();
- list.stream().map(this::getCount).filter(Optional::isPresent).map(Optional::get)
+ list.stream().map(this::getCount).flatMap(Optional::stream)
.collect(Collectors.toConcurrentMap(Pair::getValue0, Pair::getValue1, Long::sum))
.forEach(countResult::addProperty);
Pair<String, Long> pair = null;
- if (o instanceof Vertex) {
- Vertex v = (Vertex) o;
+ if (o instanceof Vertex v) {
pair = Pair.with(v.property(AAIProperties.NODE_TYPE).value().toString(), 1L);
} else if (o instanceof Tree) {
pair = Pair.with("trees", 1L);
} else if (o instanceof Path) {
pair = Pair.with("paths", 1L);
- } else if (o instanceof Long) {
- pair = Pair.with("count", (Long) o);
+ } else if (o instanceof Long long1) {
+ pair = Pair.with("count", long1);
}
if (pair == null) {
package org.onap.aai.serialization.queryformats;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Loader;
import java.util.Optional;
import java.util.stream.Stream;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.onap.aai.logging.LogFormatTools;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatQueryResultFormatNotSupported;
}
return Optional.<JsonObject>empty();
- }).filter(Optional::isPresent).map(Optional::get).forEach(json -> {
+ }).flatMap(Optional::stream).forEach(json -> {
if (isParallel) {
synchronized (body) {
body.add(json);
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper;
+import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONVersion;
import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter;
import org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatQueryResultFormatNotSupported;
private static final Logger logger = LoggerFactory.getLogger(GraphSON.class);
+ // TODO: Use v2 or v3 here
+ // v2 is the default starting from Janusgraph 0.3.0
+ // Further reference: https://tinkerpop.apache.org/docs/3.3.0/dev/io/#graphson
+ private static final GraphSONVersion version = GraphSONVersion.V1_0;
+
private final GraphSONMapper mapper =
- GraphSONMapper.build().addRegistry(JanusGraphIoRegistry.getInstance()).create();
+ GraphSONMapper.build().version(version).addRegistry(JanusGraphIoRegistry.instance()).create();
private final GraphSONWriter writer = GraphSONWriter.build().mapper(mapper).create();
@Override
}
protected JsonObject mapPropertyValues(JsonObject json, String propertyKey, Object propertyValue) {
- if (propertyValue instanceof String) {
- json.addProperty(propertyKey, (String) propertyValue);
- } else if (propertyValue instanceof Boolean) {
- json.addProperty(propertyKey, (Boolean) propertyValue);
- } else if (propertyValue instanceof Number) {
- json.addProperty(propertyKey, (Number) propertyValue);
+ if (propertyValue instanceof String string) {
+ json.addProperty(propertyKey, string);
+ } else if (propertyValue instanceof Boolean boolean1) {
+ json.addProperty(propertyKey, boolean1);
+ } else if (propertyValue instanceof Number number) {
+ json.addProperty(propertyKey, number);
} else {
if (!(propertyValue instanceof List)) {
return json;
import java.util.Map;
import java.util.Optional;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
}
return Optional.<JsonObject>empty();
- }).filter(Optional::isPresent).map(Optional::get).forEach(json -> {
+ }).flatMap(Optional::stream).forEach(json -> {
if (isParallel) {
synchronized (body) {
body.add(json);
@Override
public Optional<JsonObject> formatObject(Object input)
throws AAIFormatVertexException, AAIFormatQueryResultFormatNotSupported {
- if (input instanceof Vertex) {
+ if (input instanceof Vertex vertex) {
logger.debug("Formatting vertex object");
- return this.getJsonFromVertex((Vertex) input);
- } else if (input instanceof Tree) {
+ return this.getJsonFromVertex(vertex);
+ } else if (input instanceof Tree<?> tree) {
logger.debug("Formatting tree object");
if (isTree) {
- return this.getRelatedNodesFromTree((Tree<?>) input, null);
+ return this.getRelatedNodesFromTree(tree, null);
} else {
- return this.getJsonFromTree((Tree<?>) input);
+ return this.getJsonFromTree(tree);
}
- } else if (input instanceof Path) {
+ } else if (input instanceof Path path) {
logger.debug("Formatting path object");
- return this.getJsonFromPath((Path) input);
+ return this.getJsonFromPath(path);
} else {
throw new AAIFormatQueryResultFormatNotSupported();
}
@Override
public Optional<JsonObject> formatObject(Object input, Map<String, List<String>> properties)
throws AAIFormatVertexException, AAIFormatQueryResultFormatNotSupported {
- if (input instanceof Vertex) {
+ if (input instanceof Vertex vertex) {
logger.debug("Formatting vertex object with properties map filter");
- return this.getJsonFromVertex((Vertex) input, properties);
- } else if (input instanceof Tree) {
+ return this.getJsonFromVertex(vertex, properties);
+ } else if (input instanceof Tree<?> tree) {
logger.debug("Formatting tree object with properties map filter");
if (isTree) {
- return this.getRelatedNodesFromTree((Tree<?>) input, properties);
+ return this.getRelatedNodesFromTree(tree, properties);
} else {
- return this.getJsonFromTree((Tree<?>) input);
+ return this.getJsonFromTree(tree);
}
- } else if (input instanceof Path) {
+ } else if (input instanceof Path path) {
logger.debug("Formatting path object");
- return this.getJsonFromPath((Path) input);
+ return this.getJsonFromPath(path);
} else {
throw new AAIFormatQueryResultFormatNotSupported();
}
JsonArray ja = new JsonArray();
for (Object o : path) {
- if (o instanceof Vertex) {
- Optional<JsonObject> obj = this.getJsonFromVertex((Vertex) o);
+ if (o instanceof Vertex vertex) {
+ Optional<JsonObject> obj = this.getJsonFromVertex(vertex);
obj.ifPresent(ja::add);
}
}
import java.util.Map;
import java.util.Optional;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
import java.util.Optional;
import java.util.Set;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.Vertex;
package org.onap.aai.serialization.queryformats;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+import lombok.extern.slf4j.Slf4j;
+
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.onap.aai.serialization.queryformats.params.NodesOnly;
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
+@Slf4j
public class TreeFormat extends MultiFormatMapper {
- private static final EELFLogger TREE_FORMAT_LOGGER = EELFManager.getInstance().getLogger(TreeFormat.class);
+
protected final DBSerializer serializer;
protected final Loader loader;
protected final UrlBuilder urlBuilder;
for (Object o : queryResults) {
try {
return this.formatObjectToJsonArray(o, properties).orElseGet(() -> {
- TREE_FORMAT_LOGGER.warn("Empty Optional returned by 'formatObjectToJsonArray'");
+ log.warn("Empty Optional returned by 'formatObjectToJsonArray'");
return body;
});
} catch (AAIFormatVertexException e) {
- TREE_FORMAT_LOGGER
+ log
.warn("Failed to format vertex, returning a partial list " + LogFormatTools.getStackTop(e));
} catch (AAIFormatQueryResultFormatNotSupported e) {
- TREE_FORMAT_LOGGER.warn("Failed to format result type of the query " + LogFormatTools.getStackTop(e));
+ log.warn("Failed to format result type of the query " + LogFormatTools.getStackTop(e));
}
}
return body;
}
}
// Gremlin Query
- else if (o instanceof Vertex) {
- Optional<JsonObject> obj = this.getJsonFromVertex((Vertex) o);
+ else if (o instanceof Vertex vertex) {
+ Optional<JsonObject> obj = this.getJsonFromVertex(vertex);
if (obj.isPresent()) {
jsonObject = obj.get();
for (Map.Entry<String, JsonElement> mapEntry : jsonObject.entrySet()) {
for (Map.Entry<Object, Tree<Object>> entry : tree.entrySet()) {
Object o = entry.getKey();
- if (o instanceof Vertex) {
- processVertex(relatedNodes, entry, (Vertex) o);
+ if (o instanceof Vertex vertex) {
+ processVertex(relatedNodes, entry, vertex);
}
}
return Optional.of(relatedNodes);
package org.onap.aai.serialization.queryformats.exceptions;
+import java.io.Serial;
+
public class AAIFormatQueryResultFormatNotSupported extends Exception {
+ @Serial
private static final long serialVersionUID = -5814240842844624097L;
public AAIFormatQueryResultFormatNotSupported() {
package org.onap.aai.serialization.queryformats.exceptions;
+import java.io.Serial;
+
public class AAIFormatVertexException extends Exception {
+ @Serial
private static final long serialVersionUID = -5814240841844624097L;
public AAIFormatVertexException() {
package org.onap.aai.serialization.queryformats.exceptions;
+import java.io.Serial;
+
import org.onap.aai.exceptions.AAIException;
public class QueryParamInjectionException extends AAIException {
+ @Serial
private static final long serialVersionUID = -5575661036426538012L;
public QueryParamInjectionException(String message) {
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.onap.aai.serialization.queryformats.exceptions.QueryParamInjectionException;
import org.onap.aai.serialization.queryformats.params.*;
package org.onap.aai.serialization.tinkerpop;
+import java.io.Serial;
import java.util.Iterator;
import org.apache.tinkerpop.gremlin.structure.Direction;
* These objects are not mutable and can only be used to read information out.
*
*/
-public class TreeBackedEdge extends DetachedEdge implements Edge {
+public class TreeBackedEdge extends DetachedEdge {
+ @Serial
private static final long serialVersionUID = 5419650145562077538L;
private TreeBackedVertex inVertex;
private TreeBackedVertex outVertex;
package org.onap.aai.serialization.tinkerpop;
+import java.io.Serial;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
*
*/
-public class TreeBackedVertex extends DetachedVertex implements Vertex {
+public class TreeBackedVertex extends DetachedVertex {
+ @Serial
private static final long serialVersionUID = -976854460992756953L;
private final transient Tree<Element> tree;
private final transient Vertex self;
package org.onap.aai.service;
-import javax.annotation.PostConstruct;
+import jakarta.annotation.PostConstruct;
import org.onap.aai.validation.nodes.NodeValidator;
import org.slf4j.Logger;
import java.util.List;
import java.util.Map;
-import javax.annotation.Generated;
+import jakarta.annotation.Generated;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.util.List;
import java.util.Map;
-import javax.annotation.Generated;
+import jakarta.annotation.Generated;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
--- /dev/null
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2022 Bell Canada
+ * Modification Copyright (C) 2024 Deutsche Telekom SA
+ * ================================================================================
+ * 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.util;
+
+import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.JanusGraphTransaction;
+import org.springframework.stereotype.Component;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Component
+@RequiredArgsConstructor
+public class GraphChecker {
+
+ private final JanusGraph graph;
+
+ /**
+ * Checks whether a connection to the graph database can be made.
+ *
+ * @return
+ * <li>true, if database is available</li>
+ * <li>false, if database is NOT available</li>
+ */
+ public boolean isAaiGraphDbAvailable() {
+ JanusGraphTransaction transaction = null;
+ try {
+ // disable caching and other features that are not needed for this check
+ transaction = graph
+ .buildTransaction()
+ .readOnly()
+ .consistencyChecks(false)
+ .vertexCacheSize(0)
+ .skipDBCacheRead()
+ .start();
+ transaction.traversal().V().limit(1).hasNext(); // if this is not throwing an exception, the database is available
+ return true;
+ } catch (Throwable e) {
+ log.error("Database is not available: ", e);
+ return false;
+ } finally {
+ if (transaction != null && !transaction.isClosed()) {
+ // check if transaction is open then closed instead of flag
+ try {
+ transaction.rollback();
+ } catch (Exception e) {
+ log.error("Exception occurred while closing transaction", e);
+ }
+ }
+ }
+ }
+}
+++ /dev/null
-/**
- * ============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.util;
-
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.config.ClientConfig;
-import com.sun.jersey.api.client.config.DefaultClientConfig;
-import com.sun.jersey.api.json.JSONConfiguration;
-import com.sun.jersey.client.urlconnection.HTTPSProperties;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSession;
-
-import org.onap.aai.aailog.filter.RestControllerClientLoggingInterceptor;
-import org.onap.aai.exceptions.AAIException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class HttpsAuthClient {
-
- private static final Logger logger = LoggerFactory.getLogger(HttpsAuthClient.class);
-
- /**
- * The main method.
- *
- * @param args the arguments
- */
- public static void main(String[] args) {
- try {
- String url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + "business/customers";
- System.out.println("Making Jersey https call...");
- Client client = HttpsAuthClient.getClient();
-
- ClientResponse res = client.resource(url).accept("application/json").header("X-TransactionId", "PROV001")
- .header("X-FromAppId", "AAI").type("application/json").get(ClientResponse.class);
-
- // System.out.println("Jersey result: ");
- // System.out.println(res.getEntity(String.class).toString());
-
- } catch (KeyManagementException e) {
- logger.debug("HttpsAuthClient KeyManagement error : {}", e.getMessage());
- } catch (Exception e) {
- logger.debug("HttpsAuthClient error : {}", e.getMessage());
- }
- }
-
- /**
- * Gets the client.
- *
- * @param truststorePath the truststore path
- * @param truststorePassword the truststore password
- * @param keystorePath the keystore path
- * @param keystorePassword the keystore password
- * @return the client
- * @throws KeyManagementException the key management exception
- */
- public static Client getClient(String truststorePath, String truststorePassword, String keystorePath,
- String keystorePassword) throws KeyManagementException, UnrecoverableKeyException, CertificateException,
- NoSuchAlgorithmException, KeyStoreException, IOException {
-
- ClientConfig config = new DefaultClientConfig();
- config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
- config.getClasses().add(org.onap.aai.restcore.CustomJacksonJaxBJsonProvider.class);
- SSLContext ctx = null;
- try {
- System.setProperty("javax.net.ssl.trustStore", truststorePath);
- System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
- HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
- public boolean verify(String string, SSLSession ssls) {
- return true;
- }
- });
-
- ctx = SSLContext.getInstance("TLSv1.2");
- KeyManagerFactory kmf = null;
-
- try (FileInputStream fin = new FileInputStream(keystorePath)) {
- kmf = KeyManagerFactory.getInstance("SunX509");
- KeyStore ks = KeyStore.getInstance("PKCS12");
- char[] pwd = keystorePassword.toCharArray();
- ks.load(fin, pwd);
- kmf.init(ks, pwd);
- } catch (Exception e) {
- System.out.println("Error setting up kmf: exiting " + e.getMessage());
- throw e;
- }
-
- ctx.init(kmf.getKeyManagers(), null, null);
- config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
- new HTTPSProperties(new HostnameVerifier() {
- @Override
- public boolean verify(String s, SSLSession sslSession) {
- return true;
- }
- }, ctx));
- } catch (Exception e) {
- System.out.println("Error setting up config: exiting " + e.getMessage());
- throw e;
- }
-
- Client client = Client.create(config);
- client.addFilter(new RestControllerClientLoggingInterceptor());
- // uncomment this line to get more logging for the request/response
- // client.addFilter(new LoggingFilter(System.out));
-
- return client;
- }
-
- /**
- * Gets the client.
- *
- * @return the client
- * @throws KeyManagementException the key management exception
- */
- public static Client getClient() throws KeyManagementException, AAIException, UnrecoverableKeyException,
- CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
- String truststorePath = null;
- String truststorePassword = null;
- String keystorePath = null;
- String keystorePassword = null;
- truststorePath = AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_FILENAME);
- truststorePassword = AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_PASSWD);
- keystorePath = AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_KEYSTORE_FILENAME);
- keystorePassword = AAIConfig.get(AAIConstants.AAI_KEYSTORE_PASSWD);
- return getClient(truststorePath, truststorePassword, keystorePath, keystorePassword);
- }
-
-}
+++ /dev/null
-/**
- * ============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.util;
-
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.config.ClientConfig;
-import com.sun.jersey.api.client.config.DefaultClientConfig;
-import com.sun.jersey.api.json.JSONConfiguration;
-import com.sun.jersey.client.urlconnection.HTTPSProperties;
-
-import java.io.FileInputStream;
-import java.security.KeyStore;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.TrustManagerFactory;
-
-public class HttpsAuthExternalClient {
-
- /**
- * Gets the client.
- *
- * @param keystoreFileName the keystore file name
- * @param keystorePassword the keystore password
- * @return the client
- * @throws Exception the exception
- */
- public static Client getClient(String keystoreFileName, String keystorePassword) throws Exception {
-
- ClientConfig config = new DefaultClientConfig();
- config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
- config.getClasses().add(org.onap.aai.restcore.CustomJacksonJaxBJsonProvider.class);
- Client client = null;
- SSLContext ctx = null;
- String truststore_path = AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_FILENAME);
- try (FileInputStream tin = new FileInputStream(truststore_path)) {
- String truststore_password = AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_PASSWD);
- String keystore_path = AAIConstants.AAI_HOME_ETC_AUTH + keystoreFileName;
- String keystore_password = keystorePassword;
- // System.setProperty("javax.net.ssl.trustStore", truststore_path);
- // System.setProperty("javax.net.ssl.trustStorePassword", truststore_password);
- HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
- public boolean verify(String string, SSLSession ssls) {
- return true;
- }
- });
-
- ctx = SSLContext.getInstance("TLS");
- KeyManagerFactory kmf = null;
-
- /****
- * kmf = KeyManagerFactory.getInstance("SunX509");
- * FileInputStream fin = new FileInputStream(keystore_path);
- * KeyStore ks = KeyStore.getInstance("PKCS12");
- * char[] pwd = keystore_password.toCharArray();
- * ks.load(fin, pwd);
- * kmf.init(ks, pwd);
- ***/
-
- String alg = TrustManagerFactory.getDefaultAlgorithm();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(alg);
-
- KeyStore ts = KeyStore.getInstance("PKCS12");
- char[] tpwd = truststore_password.toCharArray();
- ts.load(tin, tpwd);
- tmf.init(ts);
-
- // ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
- // Updating key manager to null, to disable two way SSL
- ctx.init(null, tmf.getTrustManagers(), null);
-
- config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
- new HTTPSProperties(new HostnameVerifier() {
- @Override
- public boolean verify(String s, SSLSession sslSession) {
- return true;
- }
- }, ctx));
-
- client = Client.create(config);
- // uncomment this line to get more logging for the request/response
- // client.addFilter(new LoggingFilter(System.out));
- } catch (Exception e) {
- throw e;
- }
- return client;
- }
-
-}
import java.util.HashMap;
import java.util.Map;
-import javax.annotation.Generated;
+import jakarta.annotation.Generated;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
-import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
+import com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationModule;
import com.google.common.base.CaseFormat;
import com.google.common.collect.Multimap;
import java.util.List;
import java.util.Random;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Marshaller;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.eclipse.persistence.dynamic.DynamicEntity;
*/
public <T> String getJsonFromObject(T clazz, boolean wrapRoot, boolean indent)
throws JsonGenerationException, JsonMappingException, IOException {
- ObjectMapper mapper = JsonMapper.builder().serializationInclusion(JsonInclude.Include.NON_NULL)
+ ObjectMapper mapper = JsonMapper.builder()
+ .addModule(new JakartaXmlBindAnnotationModule())
+ .addModule(new JavaTimeModule())
+ .serializationInclusion(JsonInclude.Include.NON_NULL)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(SerializationFeature.INDENT_OUTPUT, indent)
.configure(SerializationFeature.WRAP_ROOT_VALUE, wrapRoot)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
- .configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapRoot).addModule(new JaxbAnnotationModule())
+ .configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapRoot)
.build();
return mapper.writeValueAsString(clazz);
+++ /dev/null
-/**
- * ============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.util;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.type.TypeFactory;
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientHandlerException;
-import com.sun.jersey.api.client.ClientResponse;
-
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.security.KeyManagementException;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
-
-import org.onap.aai.exceptions.AAIException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class RestController implements RestControllerInterface {
-
- private static final String TARGET_NAME = "AAI";
- private static final Logger LOGGER = LoggerFactory.getLogger(RestController.class);
-
- private static Client client = null;
-
- private String restSrvrBaseURL;
-
- private String overrideLocalHost = null;
-
- // To do - Come up with helper function that will automatically
- // generate the REST API path based on path parameter(s) and query parameter(s)!
- public static final String REST_APIPATH_COMPLEXES = "cloud-infrastructure/complexes";
- public static final String REST_APIPATH_COMPLEX = "cloud-infrastructure/complexes/complex/";
- public static final String REST_APIPATH_PSERVERS = "cloud-infrastructure/pservers";
- public static final String REST_APIPATH_PSERVER = "cloud-infrastructure/pservers/pserver/";
- public static final String REST_APIPATH_PHYSICALLINKS = "network/physical-links/";
- public static final String REST_APIPATH_PHYSICALLINK = "network/physical-links/physical-link/";
- public static final String REST_APIPATH_PINTERFACES = "network/p-interfaces/";
- public static final String REST_APIPATH_PINTERFACE = "network/p-interfaces/p-interface/";
- public static final String REST_APIPATH_VPLSPES = "network/vpls-pes/";
- public static final String REST_APIPATH_VPLSPE = "network/vpls-pes/vpls-pe/";
- public static final String REST_APIPATH_UPDATE = "actions/update/";
- public static final String REST_APIPATH_SEARCH = "search/nodes-query?search-node-type=";
-
- public static final String REST_APIPATH_CLOUDREGION = "cloud-infrastructure/cloud-regions/cloud-region/";
- public static final String REST_APIPATH_TENANT = "cloud-infrastructure/tenants/tenant/";
- public static final String REST_APIPATH_VIRTUAL_DATA_CENTER =
- "cloud-infrastructure/virtual-data-centers/virtual-data-center/";
- public static final String REST_APIPATH_VIRTUAL_DATA_CENTERS = "cloud-infrastructure/virtual-data-centers/";
- public static final String REST_APIPATH_GENERIC_VNF = "network/generic-vnfs/generic-vnf/";
- public static final String REST_APIPATH_GENERIC_VNFS = "network/generic-vnfs";
- public static final String REST_APIPATH_L3_NETWORK = "network/l3-networks/l3-network/";
- public static final String REST_APIPATH_L3_NETWORKS = "network/l3-networks";
- public static final String REST_APIPATH_INSTANCE_GROUP = "network/instance-groups/instance-group";
- public static final String REST_APIPATH_INSTANCE_GROUPS = "network/instance-groups";
- public static final String REST_APIPATH_VFMODULE = "nodes/vf-modules/vf-module/";
-
- public static final String REST_APIPATH_VCE = "network/vces/vce/";
-
- public static final String REST_APIPATH_SERVICE = "service-design-and-creation/services/service/";
- public static final String REST_APIPATH_LOGICALLINKS = "network/logical-links/";
- public static final String REST_APIPATH_LOGICALLINK = "network/logical-links/logical-link/";
-
- public RestController(String truststorePath, String truststorePassword, String keystorePath,
- String keystorePassword) throws AAIException {
- this.initRestClient(truststorePath, truststorePassword, keystorePath, keystorePassword);
- }
-
- /**
- * Inits the rest client.
- *
- * @throws AAIException the AAI exception
- */
- public void initRestClient(String truststorePath, String truststorePassword, String keystorePath,
- String keystorePassword) throws AAIException {
- if (client == null) {
- try {
- client = getHttpsAuthClient(truststorePath, truststorePassword, keystorePath, keystorePassword);
- } catch (KeyManagementException e) {
- throw new AAIException("AAI_7117", "KeyManagementException in REST call to DB: " + e.toString());
- } catch (Exception e) {
- throw new AAIException("AAI_7117", " Exception in REST call to DB: " + e.toString());
- }
- }
- }
-
- public Client getHttpsAuthClient(String truststorePath, String truststorePassword, String keystorePath,
- String keystorePassword) throws KeyManagementException, UnrecoverableKeyException, CertificateException,
- NoSuchAlgorithmException, KeyStoreException, IOException {
- return HttpsAuthClient.getClient(truststorePath, truststorePassword, keystorePath, keystorePassword);
- }
-
- public Client getHttpsAuthClient() throws KeyManagementException, UnrecoverableKeyException, CertificateException,
- NoSuchAlgorithmException, KeyStoreException, IOException, AAIException {
- return HttpsAuthClient.getClient();
- }
-
- /**
- * Sets the rest srvr base URL.
- *
- * @param baseURL the base URL
- * @throws AAIException the AAI exception
- */
- public void SetRestSrvrBaseURL(String baseURL) throws AAIException {
- if (baseURL == null)
- throw new AAIException("AAI_7117", "REST Server base URL cannot be null.");
- restSrvrBaseURL = baseURL;
- }
-
- /**
- * Gets the rest srvr base URL.
- *
- * @return the rest srvr base URL
- */
- public String getRestSrvrBaseURL() {
- return restSrvrBaseURL;
- }
-
- public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver)
- throws AAIException {
- Get(t, sourceID, transId, path, restObject, oldserver, AAIConstants.AAI_RESOURCES_PORT);
- }
-
- /**
- * To do - optimization and automation. Also make it as generic as possible.
- *
- * @param <T> the generic type
- * @param t the t
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @param restObject the rest object
- * @param oldserver the oldserver
- * @throws AAIException the AAI exception
- */
- @SuppressWarnings("unchecked")
- public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver,
- int port) throws AAIException {
- String methodName = "Get";
- String url = "";
- transId += ":" + UUID.randomUUID().toString();
-
- LOGGER.debug(methodName + " start");
-
- restObject.set(t);
-
- if (oldserver) {
- url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
- } else {
- if (overrideLocalHost == null) {
- overrideLocalHost =
- AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
- }
- if (AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost)) {
- url = String.format(AAIConstants.AAI_LOCAL_REST, port,
- AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- } else {
- url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost,
- AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- }
- }
- LOGGER.debug(url + " for the get REST API");
- ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
- .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json")
- .get(ClientResponse.class);
-
- // System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString());
- // System.out.println("cres.tostring()="+cres.toString());
-
- if (cres.getStatus() == 200) {
- // System.out.println(methodName + ": url=" + url);
- t = (T) cres.getEntity(t.getClass());
- restObject.set(t);
- LOGGER.debug(methodName + "REST api GET was successfull!");
- } else {
- // System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus());
- throw new AAIException("AAI_7116", methodName + " with status=" + cres.getStatus() + ", url=" + url);
- }
- }
-
- /**
- * To do - optimization and automation. Also make it as generic as possible.
- *
- * @param <T> the generic type
- * @param t the t
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @param restObject the rest object
- * @param oldserver the oldserver
- * @throws AAIException the AAI exception
- */
- @SuppressWarnings("unchecked")
- public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, String apiVersion)
- throws AAIException {
- String methodName = "Get";
- String url = "";
- transId += ":" + UUID.randomUUID().toString();
-
- LOGGER.debug(methodName + " start");
-
- restObject.set(t);
-
- url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + apiVersion + "/" + path;
-
- LOGGER.debug(url + " for the get REST API");
- ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
- .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json")
- .get(ClientResponse.class);
-
- // System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString());
- // System.out.println("cres.tostring()="+cres.toString());
-
- if (cres.getStatus() == 200) {
- // System.out.println(methodName + ": url=" + url);
- t = (T) cres.getEntity(t.getClass());
- restObject.set(t);
- LOGGER.debug(methodName + "REST api GET was successfull!");
- } else {
- // System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus());
- throw new AAIException("AAI_7116", methodName + " with status=" + cres.getStatus() + ", url=" + url);
- }
- }
-
- /**
- * Map json to object list.
- *
- * @param <T> the generic type
- * @param typeDef the type def
- * @param json the json
- * @param clazz the clazz
- * @return the list
- * @throws Exception the exception
- */
- private <T> List<T> mapJsonToObjectList(T typeDef, String json, Class<?> clazz) throws Exception {
- List<T> list;
- ObjectMapper mapper = new ObjectMapper();
- System.out.println(json);
- TypeFactory t = TypeFactory.defaultInstance();
- list = mapper.readValue(json, t.constructCollectionType(ArrayList.class, clazz));
-
- return list;
- }
-
- /**
- * Put.
- *
- * @param <T> the generic type
- * @param t the t
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @throws AAIException the AAI exception
- */
- public <T> void Put(T t, String sourceID, String transId, String path) throws AAIException {
- Put(t, sourceID, transId, path, false, AAIConstants.AAI_RESOURCES_PORT);
- }
-
- /**
- * Put.
- *
- * @param <T> the generic type
- * @param t the t
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @throws AAIException the AAI exception
- */
- public <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver) throws AAIException {
- Put(t, sourceID, transId, path, oldserver, AAIConstants.AAI_RESOURCES_PORT);
- }
-
- /**
- * Put.
- *
- * @param <T> the generic type
- * @param t the t
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @param oldserver the oldserver
- * @throws AAIException the AAI exception
- */
- public <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver, int port)
- throws AAIException {
- String methodName = "Put";
- String url = "";
- transId += ":" + UUID.randomUUID().toString();
-
- LOGGER.debug(methodName + " start");
-
- if (oldserver) {
- url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
- } else {
- if (overrideLocalHost == null) {
- overrideLocalHost =
- AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
- }
- if (AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost)) {
- url = String.format(AAIConstants.AAI_LOCAL_REST, port,
- AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- } else {
- url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost,
- AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- }
- }
-
- ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
- .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json").entity(t)
- .put(ClientResponse.class);
-
- // System.out.println("cres.tostring()="+cres.toString());
-
- int statuscode = cres.getStatus();
- if (statuscode >= 200 && statuscode <= 299) {
- LOGGER.debug(methodName + ": url=" + url + ", request=" + path);
- } else {
- throw new AAIException("AAI_7116", methodName + " with status=" + statuscode + ", url=" + url + ", msg="
- + cres.getEntity(String.class));
- }
- }
-
- /**
- * Put.
- *
- * @param <T> the generic type
- * @param t the t
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @param apiVersion version number
- * @throws AAIException the AAI exception
- */
- public <T> void Put(T t, String sourceID, String transId, String path, String apiVersion) throws AAIException {
- String methodName = "Put";
- String url = "";
- transId += ":" + UUID.randomUUID().toString();
-
- LOGGER.debug(methodName + " start");
-
- url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + apiVersion + "/" + path;
-
- ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
- .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json").entity(t)
- .put(ClientResponse.class);
-
- // System.out.println("cres.tostring()="+cres.toString());
-
- int statuscode = cres.getStatus();
- if (statuscode >= 200 && statuscode <= 299) {
- LOGGER.debug(methodName + ": url=" + url + ", request=" + path);
- } else {
- throw new AAIException("AAI_7116", methodName + " with status=" + statuscode + ", url=" + url + ", msg="
- + cres.getEntity(String.class));
- }
- }
-
- public void Delete(String sourceID, String transId, String path) throws AAIException {
- Delete(sourceID, transId, path, AAIConstants.AAI_RESOURCES_PORT);
- }
-
- /**
- * Delete.
- *
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @throws AAIException the AAI exception
- */
- public void Delete(String sourceID, String transId, String path, int port) throws AAIException {
- String methodName = "Delete";
- String url = "";
- transId += ":" + UUID.randomUUID().toString();
-
- LOGGER.debug(methodName + " start");
-
- String request = "{}";
- if (overrideLocalHost == null) {
- overrideLocalHost = AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
- }
- if (AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost)) {
- url = String.format(AAIConstants.AAI_LOCAL_REST, port,
- AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- } else {
- url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost,
- AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- }
- ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
- .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json").entity(request)
- .delete(ClientResponse.class);
-
- if (cres.getStatus() == 404) { // resource not found
- LOGGER.info("Resource does not exist...: " + cres.getStatus() + ":" + cres.getEntity(String.class));
- } else if (cres.getStatus() == 200 || cres.getStatus() == 204) {
- LOGGER.info("Resource " + url + " deleted");
- } else {
- LOGGER.error("Deleting Resource failed: " + cres.getStatus() + ":" + cres.getEntity(String.class));
- throw new AAIException("AAI_7116", "Error during DELETE");
- }
- }
-
- public <T> String Post(T t, String sourceID, String transId, String path) throws Exception {
- return Post(t, sourceID, transId, path, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
- }
-
- /**
- * Post.
- *
- * @param <T> the generic type
- * @param t the t
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @param apiVersion the apiVersion
- * @return the string
- * @throws Exception the exception
- */
- public <T> String Post(T t, String sourceID, String transId, String path, String apiVersion) throws Exception {
- String methodName = "Post";
- String url = "";
- transId += ":" + UUID.randomUUID().toString();
-
- LOGGER.debug(methodName + " start");
-
- try {
-
- url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + apiVersion + "/" + path;
-
- ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
- .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json").entity(t)
- .post(ClientResponse.class);
-
- int statuscode = cres.getStatus();
- if (statuscode >= 200 && statuscode <= 299) {
- LOGGER.debug(methodName + "REST api POST was successful!");
- return cres.getEntity(String.class);
- } else {
- throw new AAIException("AAI_7116", methodName + " with status=" + statuscode + ", url=" + url + ", msg="
- + cres.getEntity(String.class));
- }
-
- } catch (AAIException e) {
- throw new AAIException("AAI_7116", methodName + " with url=" + url + ", Exception: " + e.toString());
- } catch (Exception e) {
- throw new AAIException("AAI_7116", methodName + " with url=" + url + ", Exception: " + e.toString());
-
- } finally {
- }
- }
-
- /**
- * Gets the single instance of RestController.
- *
- * @param <T> the generic type
- * @param clazz the clazz
- * @return single instance of RestController
- * @throws IllegalAccessException the illegal access exception
- * @throws InstantiationException the instantiation exception
- * @throws SecurityException
- * @throws NoSuchMethodException
- * @throws InvocationTargetException
- * @throws IllegalArgumentException
- */
- public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException,
- IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
- return clazz.getDeclaredConstructor().newInstance();
- }
-
- /**
- * Does resource exist.
- *
- * @param <T> the generic type
- * @param resourcePath the resource path
- * @param resourceClassName the resource class name
- * @param fromAppId the from app id
- * @param transId the trans id
- * @return the t
- */
- /*
- * DoesResourceExist
- *
- * To check whether a resource exist or get a copy of the existing version of the resource
- *
- * Resourcepath: should contain the qualified resource path (including encoded unique key identifier value),
- * resourceClassName: is the canonical name of the resource class name,
- * fromAppId:
- * transId:
- *
- * Will return null (if the resource doesn’t exist) (or)
- * Will return the specified resource from the Graph.
- *
- * Example:
- * LogicalLink llink = new LogicalLink();
- * String resourceClassName = llink.getClass().getCanonicalName();
- * llink = RestController.DoesResourceExist("network/logical-links/logical-link/" + <encoded-link-name>,
- * resourceClassName, fromAppId, transId);
- */
- public <T> T DoesResourceExist(String resourcePath, String resourceClassName, String fromAppId, String transId) {
-
- try {
-
- RestObject<T> restObj = new RestObject<T>();
- @SuppressWarnings("unchecked")
- T resourceObj = (T) getInstance(Class.forName(resourceClassName));
- restObj.set(resourceObj);
- Get(resourceObj, fromAppId, transId, resourcePath, restObj, false, AAIConstants.AAI_RESOURCES_PORT);
-
- resourceObj = restObj.get();
- if (resourceObj != null)
- return resourceObj;
-
- } catch (AAIException e) {
-
- } catch (ClientHandlerException che) {
-
- } catch (Exception e) {
-
- }
-
- return null;
- }
-
- /**
- * Patch.
- *
- * @param <T> the generic type
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @throws AAIException the AAI exception
- */
- public <T> void Patch(T t, String sourceID, String transId, String path) throws AAIException {
- String methodName = "Patch";
- String url = "";
- transId += ":" + UUID.randomUUID().toString();
-
- int numRetries = 5;
- ClientResponse cres = null;
- int statusCode = -1;
-
- try {
- if (overrideLocalHost == null) {
- overrideLocalHost =
- AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
- }
- if (AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost)) {
- url = String.format(AAIConstants.AAI_LOCAL_REST, AAIConstants.AAI_RESOURCES_PORT,
- AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- } else {
- url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost,
- AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- }
-
- do {
-
- cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
- .header("X-FromAppId", sourceID).header("X-HTTP-Method-Override", "PATCH")
- .type("application/merge-patch+json").entity(t).post(ClientResponse.class);
-
- statusCode = cres.getStatus();
-
- if (statusCode >= 200 && statusCode <= 299) {
- LOGGER.debug(methodName + "REST api PATCH was successful!");
- return;
- } else {
- LOGGER.debug(methodName + "Unable to make the patch request to url " + url + " so retrying");
- }
-
- numRetries--;
-
- } while (numRetries >= 0);
-
- LOGGER.debug(methodName + "Unable to make the patch request to url " + url + " even after trying = "
- + numRetries + " times.");
- throw new AAIException("AAI_7116", methodName + " with status=" + statusCode + ", url=" + url + ", msg="
- + cres.getEntity(String.class));
-
- } catch (AAIException e) {
- throw new AAIException("AAI_7116", methodName + " with url=" + url + ", Exception: " + e.toString());
- } catch (Exception e) {
- throw new AAIException("AAI_7116", methodName + " with url=" + url + ", Exception: " + e.toString());
-
- } finally {
- }
-
- }
-}
+++ /dev/null
-/**
- * ============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.util;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.onap.aai.exceptions.AAIException;
-
-public interface RestControllerInterface {
-
- public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver)
- throws AAIException;
-
- public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, String apiVersion)
- throws AAIException;
-
- public <T> void Patch(T t, String sourceID, String transId, String path) throws AAIException;
-
- public <T> void Put(T t, String sourceID, String transId, String path) throws AAIException;
-
- public <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver) throws AAIException;
-
- public void Delete(String sourceID, String transId, String path) throws AAIException;
-
- public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException,
- IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException;
-
- public <T> T DoesResourceExist(String resourcePath, String resourceClassName, String fromAppId, String transId);
-}
+++ /dev/null
-/**
- * ============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.util;
-
-import java.io.StringWriter;
-import java.util.Iterator;
-import java.util.UUID;
-
-import javax.xml.bind.Marshaller;
-
-import org.eclipse.persistence.dynamic.DynamicEntity;
-import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.onap.aai.domain.notificationEvent.NotificationEvent;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.Introspector;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
-import org.onap.aai.kafka.AAIKafkaEventJMSProducer;
-import org.onap.aai.kafka.MessageProducer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.ApplicationContext;
-import org.springframework.core.env.Environment;
-
-public class StoreNotificationEvent {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(StoreNotificationEvent.class);
-
- private MessageProducer messageProducer;
- private String fromAppId = "";
- private String transId = "";
- private final String transactionId;
- private final String sourceOfTruth;
-
- private ApplicationContext context;
- private Environment env;
-
- /**
- * Instantiates a new store notification event.
- */
- public StoreNotificationEvent(String transactionId, String sourceOfTruth) {
- this.messageProducer = new AAIKafkaEventJMSProducer();
- this.transactionId = transactionId;
- this.sourceOfTruth = sourceOfTruth;
- }
-
- public StoreNotificationEvent(AAIKafkaEventJMSProducer producer, String transactionId, String sourceOfTruth) {
- this.messageProducer = producer;
- this.transactionId = transactionId;
- this.sourceOfTruth = sourceOfTruth;
- }
-
- /**
- * Store event.
- *
- * @param eh
- * the eh
- * @param obj
- * the obj
- * @throws AAIException
- * the AAI exception
- */
- public String storeEventAndSendToJms(NotificationEvent.EventHeader eh, Object obj) throws AAIException {
-
- if (obj == null) {
- throw new AAIException("AAI_7350");
- }
-
- org.onap.aai.domain.notificationEvent.ObjectFactory factory =
- new org.onap.aai.domain.notificationEvent.ObjectFactory();
-
- org.onap.aai.domain.notificationEvent.NotificationEvent ne = factory.createNotificationEvent();
-
- if (eh.getId() == null) {
- eh.setId(genDate2() + "-" + UUID.randomUUID().toString());
- }
- if (eh.getTimestamp() == null) {
- eh.setTimestamp(genDate());
- }
-
- // there's no default, but i think we want to put this in hbase?
-
- if (eh.getEntityLink() == null) {
- eh.setEntityLink("UNK");
- }
-
- if (eh.getAction() == null) {
- eh.setAction("UNK");
- }
-
- if (eh.getEventType() == null) {
- eh.setEventType(AAIConfig.get("aai.notificationEvent.default.eventType", "UNK"));
- }
-
- if (eh.getDomain() == null) {
- eh.setDomain(AAIConfig.get("aai.notificationEvent.default.domain", "UNK"));
- }
-
- if (eh.getSourceName() == null) {
- eh.setSourceName(AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK"));
- }
-
- if (eh.getSequenceNumber() == null) {
- eh.setSequenceNumber(AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK"));
- }
-
- if (eh.getSeverity() == null) {
- eh.setSeverity(AAIConfig.get("aai.notificationEvent.default.severity", "UNK"));
- }
-
- if (eh.getVersion() == null) {
- eh.setVersion(AAIConfig.get("aai.notificationEvent.default.version", "UNK"));
- }
-
- ne.setCambriaPartition(AAIConstants.UEB_PUB_PARTITION_AAI);
- ne.setEventHeader(eh);
- ne.setEntity(obj);
-
- try {
- PojoUtils pu = new PojoUtils();
- String entityJson = pu.getJsonFromObject(ne);
- sendToKafkaJmsQueue(entityJson);
- return entityJson;
- } catch (Exception e) {
- throw new AAIException("AAI_7350", e);
- }
- }
-
- /**
- * Store dynamic event.
- *
- * @param notificationJaxbContext
- * the notification jaxb context
- * @param notificationVersion
- * the notification version
- * @param eventHeader
- * the event header
- * @param obj
- * the obj
- * @throws AAIException
- * the AAI exception
- */
- public void storeDynamicEvent(DynamicJAXBContext notificationJaxbContext, String notificationVersion,
- DynamicEntity eventHeader, DynamicEntity obj) throws AAIException {
-
- if (obj == null) {
- throw new AAIException("AAI_7350");
- }
-
- DynamicEntity notificationEvent = notificationJaxbContext
- .getDynamicType("inventory.aai.onap.org." + notificationVersion + ".NotificationEvent")
- .newDynamicEntity();
-
- if (eventHeader.get("id") == null) {
- eventHeader.set("id", genDate2() + "-" + UUID.randomUUID().toString());
- }
-
- if (eventHeader.get("timestamp") == null) {
- eventHeader.set("timestamp", genDate());
- }
-
- if (eventHeader.get("entityLink") == null) {
- eventHeader.set("entityLink", "UNK");
- }
-
- if (eventHeader.get("action") == null) {
- eventHeader.set("action", "UNK");
- }
-
- if (eventHeader.get("eventType") == null) {
- eventHeader.set("eventType", AAIConfig.get("aai.notificationEvent.default.eventType", "UNK"));
- }
-
- if (eventHeader.get("domain") == null) {
- eventHeader.set("domain", AAIConfig.get("aai.notificationEvent.default.domain", "UNK"));
- }
-
- if (eventHeader.get("sourceName") == null) {
- eventHeader.set("sourceName", AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK"));
- }
-
- if (eventHeader.get("sequenceNumber") == null) {
- eventHeader.set("sequenceNumber", AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK"));
- }
-
- if (eventHeader.get("severity") == null) {
- eventHeader.set("severity", AAIConfig.get("aai.notificationEvent.default.severity", "UNK"));
- }
-
- if (eventHeader.get("version") == null) {
- eventHeader.set("version", AAIConfig.get("aai.notificationEvent.default.version", "UNK"));
- }
-
- if (notificationEvent.get("cambriaPartition") == null) {
- notificationEvent.set("cambriaPartition", AAIConstants.UEB_PUB_PARTITION_AAI);
- }
-
- notificationEvent.set("eventHeader", eventHeader);
- notificationEvent.set("entity", obj);
-
- try {
- StringWriter result = new StringWriter();
-
- Marshaller marshaller = notificationJaxbContext.createMarshaller();
- marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.MEDIA_TYPE, "application/json");
- marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_INCLUDE_ROOT, false);
- marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, false);
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
- marshaller.marshal(notificationEvent, result);
- this.sendToKafkaJmsQueue(result.toString());
-
- } catch (Exception e) {
- throw new AAIException("AAI_7350", e);
- }
- }
-
- public String storeEventOnly(Loader loader, Introspector eventHeader, Introspector obj) throws AAIException {
- if (obj == null) {
- throw new AAIException("AAI_7350");
- }
-
- try {
- final Introspector notificationEvent = loader.introspectorFromName("notification-event");
-
- if (eventHeader.getValue("id") == null) {
- eventHeader.setValue("id", genDate2() + "-" + UUID.randomUUID().toString());
- }
-
- if (eventHeader.getValue("timestamp") == null) {
- eventHeader.setValue("timestamp", genDate());
- }
-
- if (eventHeader.getValue("entity-link") == null) {
- eventHeader.setValue("entity-link", "UNK");
- }
-
- if (eventHeader.getValue("action") == null) {
- eventHeader.setValue("action", "UNK");
- }
-
- if (eventHeader.getValue("event-type") == null) {
- eventHeader.setValue("event-type", AAIConfig.get("aai.notificationEvent.default.eventType", "UNK"));
- }
-
- if (eventHeader.getValue("domain") == null) {
- eventHeader.setValue("domain", AAIConfig.get("aai.notificationEvent.default.domain", "UNK"));
- }
-
- if (eventHeader.getValue("source-name") == null) {
- eventHeader.setValue("source-name", AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK"));
- }
-
- if (eventHeader.getValue("sequence-number") == null) {
- eventHeader.setValue("sequence-number",
- AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK"));
- }
-
- if (eventHeader.getValue("severity") == null) {
- eventHeader.setValue("severity", AAIConfig.get("aai.notificationEvent.default.severity", "UNK"));
- }
-
- if (eventHeader.getValue("version") == null) {
- eventHeader.setValue("version", AAIConfig.get("aai.notificationEvent.default.version", "UNK"));
- }
-
- if (notificationEvent.getValue("cambria-partition") == null) {
- notificationEvent.setValue("cambria-partition",
- AAIConfig.get("aai.notificationEvent.default.partition", AAIConstants.UEB_PUB_PARTITION_AAI));
- }
-
- notificationEvent.setValue("event-header", eventHeader.getUnderlyingObject());
- notificationEvent.setValue("entity", obj.getUnderlyingObject());
-
- String entityJson = notificationEvent.marshal(false);
- JSONObject entityJsonObject = new JSONObject(entityJson);
-
- JSONObject entityJsonObjectUpdated = new JSONObject();
-
- JSONObject entityHeader = entityJsonObject.getJSONObject("event-header");
- String cambriaPartition = entityJsonObject.getString("cambria.partition");
-
- entityJsonObject.remove("event-header");
- entityJsonObject.remove("cambria.partition");
-
- entityJsonObjectUpdated.put("event-header", entityHeader);
- entityJsonObjectUpdated.put("cambria.partition", cambriaPartition);
-
- Iterator<String> iter = entityJsonObject.keys();
- JSONObject entity = new JSONObject();
- if (iter.hasNext()) {
- entity = entityJsonObject.getJSONObject(iter.next());
- }
-
- entityJsonObjectUpdated.put("entity", entity);
-
- return entityJsonObjectUpdated.toString();
- } catch (JSONException e) {
- throw new AAIException("AAI_7350", e);
- } catch (AAIUnknownObjectException e) {
- throw new AAIException("AAI_7350", e);
- }
- }
-
- public String storeEventAndSendToJms(Loader loader, Introspector eventHeader, Introspector obj)
- throws AAIException {
- if (obj == null) {
- throw new AAIException("AAI_7350");
- }
-
- try {
- final Introspector notificationEvent = loader.introspectorFromName("notification-event");
-
- if (eventHeader.getValue("id") == null) {
- eventHeader.setValue("id", genDate2() + "-" + UUID.randomUUID().toString());
- }
-
- if (eventHeader.getValue("timestamp") == null) {
- eventHeader.setValue("timestamp", genDate());
- }
-
- if (eventHeader.getValue("entity-link") == null) {
- eventHeader.setValue("entity-link", "UNK");
- }
-
- if (eventHeader.getValue("action") == null) {
- eventHeader.setValue("action", "UNK");
- }
-
- if (eventHeader.getValue("event-type") == null) {
- eventHeader.setValue("event-type", AAIConfig.get("aai.notificationEvent.default.eventType", "UNK"));
- }
-
- if (eventHeader.getValue("domain") == null) {
- eventHeader.setValue("domain", AAIConfig.get("aai.notificationEvent.default.domain", "UNK"));
- }
-
- if (eventHeader.getValue("source-name") == null) {
- eventHeader.setValue("source-name", AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK"));
- }
-
- if (eventHeader.getValue("sequence-number") == null) {
- eventHeader.setValue("sequence-number",
- AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK"));
- }
-
- if (eventHeader.getValue("severity") == null) {
- eventHeader.setValue("severity", AAIConfig.get("aai.notificationEvent.default.severity", "UNK"));
- }
-
- if (eventHeader.getValue("version") == null) {
- eventHeader.setValue("version", AAIConfig.get("aai.notificationEvent.default.version", "UNK"));
- }
-
- if (notificationEvent.getValue("cambria-partition") == null) {
- notificationEvent.setValue("cambria-partition",
- AAIConfig.get("aai.notificationEvent.default.partition", AAIConstants.UEB_PUB_PARTITION_AAI));
- }
-
- notificationEvent.setValue("event-header", eventHeader.getUnderlyingObject());
- notificationEvent.setValue("entity", obj.getUnderlyingObject());
-
- String entityJson = notificationEvent.marshal(false);
- sendToKafkaJmsQueue(entityJson);
- return entityJson;
- } catch (JSONException e) {
- throw new AAIException("AAI_7350", e);
- } catch (AAIUnknownObjectException e) {
- throw new AAIException("AAI_7350", e);
- }
- }
-
- private void sendToKafkaJmsQueue(String entityString) throws JSONException {
-
- JSONObject entityJsonObject = new JSONObject(entityString);
-
- JSONObject entityJsonObjectUpdated = new JSONObject();
- JSONObject finalJson = new JSONObject();
-
- JSONObject entityHeader = entityJsonObject.getJSONObject("event-header");
- String cambriaPartition = entityJsonObject.getString("cambria.partition");
-
- entityJsonObject.remove("event-header");
- entityJsonObject.remove("cambria.partition");
-
- entityJsonObjectUpdated.put("event-header", entityHeader);
- entityJsonObjectUpdated.put("cambria.partition", cambriaPartition);
-
- String transId = entityHeader.getString("id");
- String fromAppId = entityHeader.getString("source-name");
-
- Iterator<String> iter = entityJsonObject.keys();
- JSONObject entity = new JSONObject();
- if (iter.hasNext()) {
- entity = entityJsonObject.getJSONObject(iter.next());
- }
-
- entityJsonObjectUpdated.put("entity", entity);
-
- finalJson.put("event-topic", "AAI-EVENT");
- finalJson.put("transId", transId);
- finalJson.put("fromAppId", fromAppId);
- finalJson.put("fullId", "");
- finalJson.put("aaiEventPayload", entityJsonObjectUpdated);
-
- messageProducer.sendMessageToDefaultDestination(finalJson);
- }
-
- /**
- * Gen date.
- *
- * @return the string
- */
- public static String genDate() {
- FormatDate fd = new FormatDate("YYYYMMdd-HH:mm:ss:SSS");
- return fd.getDateTime();
- }
-
- /**
- * Gen date 2.
- *
- * @return the string
- */
- public static String genDate2() {
- FormatDate fd = new FormatDate("YYYYMMddHHmmss");
- return fd.getDateTime();
- }
-
-}
package org.onap.aai.util.delta;
-import com.google.gson.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Map;
import org.onap.aai.db.props.AAIProperties;
-import org.onap.aai.kafka.AAIKafkaEventJMSProducer;
-import org.onap.aai.kafka.MessageProducer;
+import org.onap.aai.domain.deltaEvent.DeltaEvent;
+import org.onap.aai.domain.notificationEvent.NotificationEvent.EventHeader;
+import org.onap.aai.kafka.DeltaProducer;
import org.onap.aai.util.AAIConfig;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
public class DeltaEvents {
+ private final String transId;
+ private final String sourceName;
+ private final String schemaVersion;
+ private final Map<String, ObjectDelta> objectDeltas;
- private static final Logger LOGGER = LoggerFactory.getLogger(DeltaEvents.class);
-
- private static final Gson gson =
- new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();
-
- private String transId;
- private String sourceName;
- private String eventVersion = "v1";
- private String schemaVersion;
- private Map<String, ObjectDelta> objectDeltas;
-
- private MessageProducer messageProducer;
+ @Autowired private DeltaProducer deltaProducer;
public DeltaEvents(String transId, String sourceName, String schemaVersion, Map<String, ObjectDelta> objectDeltas) {
- this(transId, sourceName, schemaVersion, objectDeltas, new AAIKafkaEventJMSProducer());
- }
-
- public DeltaEvents(String transId, String sourceName, String schemaVersion, Map<String, ObjectDelta> objectDeltas,
- MessageProducer messageProducer) {
this.transId = transId;
this.sourceName = sourceName;
this.schemaVersion = schemaVersion;
this.objectDeltas = objectDeltas;
- this.messageProducer = messageProducer;
}
public boolean triggerEvents() {
return false;
}
- JsonObject finalJson = new JsonObject();
- finalJson.addProperty("event-topic", "DELTA");
- finalJson.addProperty("transId", transId);
- finalJson.addProperty("fromAppId", sourceName);
- finalJson.addProperty("fullId", "");
- finalJson.add("aaiEventPayload", buildEvent());
-
- this.messageProducer.sendMessageToDefaultDestination(finalJson.toString());
+ deltaProducer.sendNotification(buildEvent());
return true;
}
- private JsonObject buildEvent() {
- JsonObject event = new JsonObject();
- event.addProperty("cambria.partition", this.getPartition());
- event.add("event-header", getHeader());
- event.add("entities", gson.toJsonTree(objectDeltas.values()));
- return event;
+ private DeltaEvent buildEvent() {
+ DeltaEvent deltaEvent = new DeltaEvent();
+ deltaEvent.setCambriaPartition(getPartition());
+ deltaEvent.setEventHeader(getHeader());
+ deltaEvent.setEntities(objectDeltas.values());
+ return deltaEvent;
}
private String getPartition() {
return "DELTA";
}
- private JsonObject getHeader() {
+ private EventHeader getHeader() {
ObjectDelta first = objectDeltas.values().iterator().next();
- JsonObject header = new JsonObject();
- header.addProperty("id", this.transId);
- header.addProperty("timestamp", this.getTimeStamp(first.getTimestamp()));
- header.addProperty("source-name", this.sourceName);
- header.addProperty("domain", this.getDomain());
- header.addProperty("event-type", this.getEventType());
- header.addProperty("event-version", this.eventVersion);
- header.addProperty("schema-version", this.schemaVersion);
- header.addProperty("action", first.getAction().toString());
- header.addProperty("entity-type", this.getEntityType(first));
- header.addProperty("entity-link", first.getUri());
- header.addProperty("entity-uuid", this.getUUID(first));
-
+ EventHeader header = new EventHeader();
+ header.setId(this.transId);
+ header.setTimestamp(this.getTimeStamp(first.getTimestamp()));
+ header.setSourceName(this.sourceName);
+ header.setDomain(this.getDomain());
+ header.setEventType(this.getEventType());
+ header.setVersion(this.schemaVersion);
+ header.setAction(first.getAction().toString());
+ header.setEntityType(this.getEntityType(first));
+ header.setEntityLink(first.getUri());
+ header.setEntityUuid(this.getUUID(first));
return header;
}
/**
* Given Long timestamp convert to format YYYYMMdd-HH:mm:ss:SSS
- *
+ *
* @param timestamp milliseconds since epoc
* @return long timestamp in format YYYYMMdd-HH:mm:ss:SSS
*/
package org.onap.aai.util.delta;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import lombok.Data;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.commons.lang3.builder.ToStringBuilder;
+@Data
public class ObjectDelta {
- @SerializedName("uri")
private String uri;
-
- @SerializedName("action")
private DeltaAction action;
-
- @SerializedName("source-of-truth")
+ @JsonProperty("source-of-truth")
private String sourceOfTruth;
-
- @SerializedName("timestamp")
private long timestamp;
-
- @SerializedName("property-deltas")
+ @JsonProperty("property-deltas")
private Map<String, PropertyDelta> propertyDeltas = new HashMap<>();
-
- @SerializedName("relationship-deltas")
+ @JsonProperty("relationship-deltas")
private List<RelationshipDelta> relationshipDeltas = new ArrayList<>();
public ObjectDelta(String uri, DeltaAction action, String sourceOfTruth, long timestamp) {
relationshipDeltas.add(relationshipDelta);
}
- public String getUri() {
- return uri;
- }
-
- public void setUri(String uri) {
- this.uri = uri;
- }
-
- public DeltaAction getAction() {
- return action;
- }
-
- public void setAction(DeltaAction action) {
- this.action = action;
- }
-
- public String getSourceOfTruth() {
- return sourceOfTruth;
- }
-
- public void setSourceOfTruth(String sourceOfTruth) {
- this.sourceOfTruth = sourceOfTruth;
- }
-
- public long getTimestamp() {
- return timestamp;
- }
-
- public void setTimestamp(long timestamp) {
- this.timestamp = timestamp;
- }
-
- public void setPropertyDeltas(Map<String, PropertyDelta> propertyDeltas) {
- this.propertyDeltas = propertyDeltas;
- }
-
- public void setRelationshipDeltas(List<RelationshipDelta> relationshipDeltas) {
- this.relationshipDeltas = relationshipDeltas;
- }
-
- public Map<String, PropertyDelta> getPropertyDeltas() {
- return propertyDeltas;
- }
-
- public List<RelationshipDelta> getRelationshipDeltas() {
- return relationshipDeltas;
- }
-
@Override
public String toString() {
return new ToStringBuilder(this).append("uri", uri).append("action", action)
package org.onap.aai.util.delta;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
+@Data
public class PropertyDelta {
- @SerializedName("action")
protected DeltaAction action;
-
- @SerializedName("value")
protected Object value;
-
- @SerializedName("old-value")
+ @JsonProperty("old-value")
private Object oldValue;
public PropertyDelta(DeltaAction action, Object value) {
this.oldValue = oldValue;
}
- public DeltaAction getAction() {
- return action;
- }
-
- public void setAction(DeltaAction action) {
- this.action = action;
- }
-
- public Object getValue() {
- return value;
- }
-
- public void setValue(Object value) {
- this.value = value;
- }
-
- public Object getOldValue() {
- return oldValue;
- }
-
- public void setOldValue(Object oldValue) {
- this.oldValue = oldValue;
- }
-
@Override
public String toString() {
return new ToStringBuilder(this).append("action", action).append("value", value).append("oldValue", oldValue)
+++ /dev/null
-/**
- * ============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.web;
-
- import java.util.HashMap;
- import java.util.Map;
-
- import javax.annotation.PostConstruct;
-
- import org.apache.activemq.ActiveMQConnectionFactory;
- import org.apache.activemq.broker.BrokerService;
- import org.apache.activemq.command.ActiveMQQueue;
- import org.apache.kafka.clients.producer.ProducerConfig;
-import org.onap.aai.kafka.AAIKafkaEventJMSConsumer;
-import org.onap.aai.kafka.AAIKafkaEventJMSProducer;
-import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.context.annotation.Profile;
- import org.springframework.jms.connection.CachingConnectionFactory;
- import org.springframework.jms.core.JmsTemplate;
- import org.springframework.jms.listener.DefaultMessageListenerContainer;
- import org.springframework.kafka.core.DefaultKafkaProducerFactory;
- import org.springframework.kafka.core.KafkaTemplate;
- import org.springframework.kafka.core.ProducerFactory;
-
- @Profile("kafka")
- @Configuration
- public class KafkaConfig {
-
- @Autowired
- private ApplicationContext ctx;
-
-
- @Value("${jms.bind.address}")
- private String bindAddress;
-
- @Value("${spring.kafka.producer.bootstrap-servers}")
- private String bootstrapServers;
-
- @Value("${spring.kafka.producer.properties.security.protocol}")
- private String securityProtocol;
-
- @Value("${spring.kafka.producer.properties.sasl.mechanism}")
- private String saslMechanism;
-
- @Value("${spring.kafka.producer.properties.sasl.jaas.config}")
- private String saslJaasConfig;
-
- @Value("${spring.kafka.producer.retries}")
- private Integer retries;
-
- private static final Logger logger = LoggerFactory.getLogger(KafkaConfig.class);
-
- @PostConstruct
- public void init() {
- System.setProperty("activemq.tcp.url", bindAddress);
- }
-
- @Bean(destroyMethod = "stop")
- public BrokerService brokerService() throws Exception {
-
- BrokerService broker = new BrokerService();
- broker.addConnector(bindAddress);
- broker.setPersistent(false);
- broker.setUseJmx(false);
- broker.setSchedulerSupport(false);
- broker.start();
-
- return broker;
- }
-
- @Bean(name = "connectionFactory")
- public ActiveMQConnectionFactory activeMQConnectionFactory() {
- return new ActiveMQConnectionFactory(bindAddress);
- }
-
- @Bean
- public CachingConnectionFactory cachingConnectionFactory() {
- return new CachingConnectionFactory(activeMQConnectionFactory());
- }
-
- @Bean(name = "destinationQueue")
- public ActiveMQQueue activeMQQueue() {
- return new ActiveMQQueue("IN_QUEUE");
- }
-
- @Bean
- public JmsTemplate jmsTemplate() {
- JmsTemplate jmsTemplate = new JmsTemplate();
-
- jmsTemplate.setConnectionFactory(activeMQConnectionFactory());
- jmsTemplate.setDefaultDestination(activeMQQueue());
-
- return jmsTemplate;
- }
-
- @Bean
- public AAIKafkaEventJMSProducer jmsProducer() {
- return new AAIKafkaEventJMSProducer();
- }
-
- @Bean(name = "jmsConsumer")
- public AAIKafkaEventJMSConsumer jmsConsumer() throws Exception {
- return new AAIKafkaEventJMSConsumer(ctx.getEnvironment(),kafkaTemplate());
- }
-
- @Bean
- public DefaultMessageListenerContainer defaultMessageListenerContainer() throws Exception {
-
- DefaultMessageListenerContainer messageListenerContainer = new DefaultMessageListenerContainer();
-
- messageListenerContainer.setConnectionFactory(cachingConnectionFactory());
- messageListenerContainer.setDestinationName("IN_QUEUE");
- messageListenerContainer.setMessageListener(jmsConsumer());
-
- return messageListenerContainer;
- }
-
- @Bean
- public ProducerFactory<String, String> producerFactory() throws Exception {
- Map<String, Object> props = new HashMap<>();
- if(bootstrapServers == null){
- logger.error("Environment Variable " + bootstrapServers + " is missing");
- throw new Exception("Environment Variable " + bootstrapServers + " is missing");
- }
- else{
- props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
- }
- if(saslJaasConfig == null){
- logger.info("Not using any authentication for kafka interaction");
- }
- else{
- logger.info("Using authentication provided by kafka interaction");
- // Strimzi Kafka security properties
- props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
- props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
- props.put("security.protocol", securityProtocol);
- props.put("sasl.mechanism", saslMechanism);
- props.put("sasl.jaas.config", saslJaasConfig);
- props.put(ProducerConfig.RETRIES_CONFIG, Integer.toString(retries));
- props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION,"5");
- }
-
- return new DefaultKafkaProducerFactory<>(props);
- }
-
- @Bean
- public KafkaTemplate<String, String> kafkaTemplate() throws Exception {
- return new KafkaTemplate<>(producerFactory());
- }
- }
-
\ No newline at end of file
--- /dev/null
+spring.application.name=aai-core
+aai.graph.properties.path=src/main/resources/janusgraph-realtime.properties
<pattern>${eelfTransLogPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asynctranslog" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>1000</queueSize>
<includeCallerData>true</includeCallerData>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.beans" level="WARN" />
<logger name="org.springframework.web" level="WARN" />
- <logger name="com.blog.spring.jms" level="WARN" />
<logger name="com.jayway.jsonpath" level="WARN" />
<!-- AJSC Services (bootstrap services) -->
<logger name="ajsc.UserDefinedBeansDefService" level="WARN" />
<logger name="ajsc.LoggingConfigurationService" level="WARN" />
- <!-- AJSC related loggers (DME2 Registration, csi logging, restlet, servlet
+ <!-- AJSC related loggers (DME2 Registration, csi logging, restlet, servlet
logging) -->
<logger name="org.codehaus.groovy" level="WARN" />
<logger name="com.att.scamper" level="WARN" />
<logger name="org.apache.coyote" level="WARN" />
<logger name="org.apache.jasper" level="WARN" />
- <!-- Camel Related Loggers (including restlet/servlet/jaxrs/cxf logging.
+ <!-- Camel Related Loggers (including restlet/servlet/jaxrs/cxf logging.
May aid in troubleshooting) -->
<logger name="org.apache.camel" level="WARN" />
<logger name="org.apache.cxf" level="WARN" />
</logger>
<logger name="org.onap.aai.kafka" level="DEBUG" additivity="false">
- <appender-ref ref="kafkaAAIEventConsumer" />
- <appender-ref ref="kafkaAAIEventConsumerDebug" />
- <appender-ref ref="kafkaAAIEventConsumerMetric" />
+ <appender-ref ref="STDOUT" />
</logger>
<logger name="org.apache" level="OFF" />
public AAIJunitRunner(Class<?> klass) throws Throwable {
super(klass);
setProps();
- modifyOxmHome();
+ // modifyOxmHome();
}
public void setProps() {
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
}
- public void modifyOxmHome() {
- try {
- Field aaiConstantsField = AAIConstants.class.getField("AAI_HOME_ETC_OXM");
- setFinalStatic(aaiConstantsField, "../aai-schema/src/main/resources/oxm/");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public void setFinalStatic(Field field, Object newValue) throws Exception {
- field.setAccessible(true);
- Field modifiersField = Field.class.getDeclaredField("modifiers");
- modifiersField.setAccessible(true);
- modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
- field.set(null, newValue);
- }
+ // public void modifyOxmHome() {
+ // try {
+ // Field aaiConstantsField = AAIConstants.class.getField("AAI_HOME_ETC_OXM");
+ // setFinalStatic(aaiConstantsField, "../aai-schema/src/main/resources/oxm/");
+ // } catch (Exception e) {
+ // e.printStackTrace();
+ // }
+ // }
}
package org.onap.aai;
+import java.lang.reflect.Field;
import java.util.Map;
import org.junit.BeforeClass;
import org.onap.aai.introspection.LoaderFactory;
import org.onap.aai.introspection.MoxyLoader;
import org.onap.aai.nodes.NodeIngestor;
+import org.onap.aai.prevalidation.ValidationConfiguration;
+import org.onap.aai.prevalidation.ValidationService;
import org.onap.aai.rest.db.HttpEntry;
+import org.onap.aai.rest.notification.NotificationService;
import org.onap.aai.serialization.db.EdgeSerializer;
import org.onap.aai.serialization.queryformats.QueryFormatTestHelper;
import org.onap.aai.setup.AAIConfigTranslator;
@ContextConfiguration(
classes = {ConfigConfiguration.class, AAIConfigTranslator.class, EdgeIngestor.class, EdgeSerializer.class,
NodeIngestor.class, SpringContextAware.class, IntrospectionConfig.class, RestBeanConfig.class,
- XmlFormatTransformerConfiguration.class})
+ XmlFormatTransformerConfiguration.class, ValidationService.class, ValidationConfiguration.class,
+ KafkaConfig.class, LoaderFactory.class, NotificationService.class})
@TestPropertySource(
properties = {"schema.uri.base.path = /aai", "schema.xsd.maxoccurs = 5000", "schema.translator.list=config",
"schema.nodes.location=src/test/resources/onap/oxm",
- "schema.edges.location=src/test/resources/onap/dbedgerules"})
+ "schema.edges.location=src/test/resources/onap/dbedgerules",
+ "aai.notifications.enabled=false"})
public abstract class AAISetup {
@ClassRule
System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
System.setProperty("aai.service.name", SERVICE_NAME);
- QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"),
- "src/test/resources/bundleconfig-local/etc/oxm/");
+ // Field etcHomeField = AAIConstants.class.getField("AAI_HOME_ETC_OXM");
+ // QueryFormatTestHelper.setFinalStatic(etcHomeField,
+ // "src/test/resources/bundleconfig-local/etc/oxm/");
}
}
System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
System.setProperty("aai.service.name", SERVICE_NAME);
- QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"),
- "src/test/resources/bundleconfig-local/etc/oxm/");
}
}
import org.onap.aai.introspection.MoxyLoader;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.rest.db.HttpEntry;
+import org.onap.aai.rest.notification.NotificationService;
import org.onap.aai.serialization.db.EdgeSerializer;
import org.onap.aai.serialization.queryformats.QueryFormatTestHelper;
import org.onap.aai.setup.SchemaVersion;
@ContextConfiguration(
classes = {ConfigConfiguration.class, TestUtilConfigTranslatorforDataLink.class, EdgeIngestor.class,
EdgeSerializer.class, NodeIngestor.class, SpringContextAware.class, IntrospectionConfig.class,
- RestBeanConfig.class, XmlFormatTransformerConfiguration.class})
+ RestBeanConfig.class, XmlFormatTransformerConfiguration.class, LoaderFactory.class, NotificationService.class, KafkaConfig.class})
@TestPropertySource(
properties = {"schema.uri.base.path = /aai", "schema.xsd.maxoccurs = 5000", "schema.version.api.default = v4",
"schema.version.edge.label.start = v4", "schema.version.depth.start = v3",
"schema.version.app.root.start = v4", "schema.version.related.link.start = v4",
"schema.version.namespace.change.start = v4", "schema.version.list = v1,v2,v3,v4",
- "schema.translator.list = config"})
+ "schema.translator.list = config","aai.notifications.enabled = false"})
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public abstract class DataLinkSetup {
System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
System.setProperty("aai.service.name", SERVICE_NAME);
- QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"),
- "src/test/resources/bundleconfig-local/etc/oxm/");
}
}
package org.onap.aai;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
import java.util.Map;
import java.util.UUID;
-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 org.javatuples.Pair;
import org.mockito.Mockito;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.parsers.uri.URIToObject;
import org.onap.aai.rest.db.DBRequest;
import org.onap.aai.rest.db.HttpEntry;
-import org.onap.aai.rest.ueb.UEBNotification;
+import org.onap.aai.rest.notification.UEBNotification;
import org.onap.aai.restcore.HttpMethod;
import org.onap.aai.restcore.RESTAPI;
import org.onap.aai.serialization.engines.QueryStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.UriBuilder;
+import jakarta.ws.rs.core.UriInfo;
+
public class HttpTestUtil extends RESTAPI {
protected HttpEntry traversalHttpEntry;
doReturn(null).when(queryParameters).remove(any());
when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
-
- try {
- if (notification != null) {
- doNothing().when(notification).triggerEvents();
- }
- } catch (AAIException e) {
- e.printStackTrace();
- }
}
public Response doPut(String uri, String payload) throws UnsupportedEncodingException, AAIException {
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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;
+
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.onap.aai.config.ConfigConfiguration;
+import org.onap.aai.config.IntrospectionConfig;
+import org.onap.aai.config.KafkaConfig;
+import org.onap.aai.config.RestBeanConfig;
+import org.onap.aai.config.SpringContextAware;
+import org.onap.aai.config.XmlFormatTransformerConfiguration;
+import org.onap.aai.edges.EdgeIngestor;
+import org.onap.aai.introspection.LoaderFactory;
+import org.onap.aai.nodes.NodeIngestor;
+import org.onap.aai.prevalidation.ValidationConfiguration;
+import org.onap.aai.prevalidation.ValidationService;
+import org.onap.aai.rest.notification.NotificationService;
+import org.onap.aai.serialization.db.EdgeSerializer;
+import org.onap.aai.setup.AAIConfigTranslator;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(
+ classes = {ConfigConfiguration.class, AAIConfigTranslator.class, EdgeIngestor.class, EdgeSerializer.class,
+ NodeIngestor.class, SpringContextAware.class, IntrospectionConfig.class, RestBeanConfig.class,
+ XmlFormatTransformerConfiguration.class, ValidationService.class, ValidationConfiguration.class,
+ KafkaConfig.class, LoaderFactory.class, NotificationService.class})
+@TestPropertySource(
+ value = "classpath:/application.properties",
+ properties = {
+ "schema.uri.base.path = /aai", "schema.xsd.maxoccurs = 5000",
+ "schema.translator.list=config",
+ "schema.nodes.location=src/test/resources/onap/oxm",
+ "schema.edges.location=src/test/resources/onap/dbedgerules",
+ "aai.notifications.enabled=false","classpath:/application.properties",
+ })
+public class IntegrationTest {
+
+}
--- /dev/null
+package org.onap.aai;
+
+import java.io.FileNotFoundException;
+
+import org.apache.commons.configuration2.Configuration;
+import org.apache.commons.configuration2.PropertiesConfiguration;
+import org.apache.commons.configuration2.ex.ConfigurationException;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.context.annotation.Bean;
+
+@TestConfiguration
+public class JanusgraphCassandraConfiguration {
+
+ @Value("${testcontainers.cassandra.host}")
+ String cassandraHost;
+
+ @Value("${testcontainers.cassandra.port}")
+ int cassandraPort;
+
+ @Bean
+ public org.apache.commons.configuration2.Configuration getGraphProperties()
+ throws FileNotFoundException, ConfigurationException {
+
+ Configuration janusgraphConfiguration = new PropertiesConfiguration();
+ janusgraphConfiguration.addProperty("storage.backend", "cql");
+ janusgraphConfiguration.addProperty("storage.hostname", cassandraHost);
+ janusgraphConfiguration.addProperty("storage.port", cassandraPort);
+ return janusgraphConfiguration;
+ }
+}
import org.junit.experimental.categories.Categories.IncludeCategory;
import org.junit.runner.RunWith;
import org.junit.runners.Suite.SuiteClasses;
+import org.onap.aai.db.DbMethHelperTest;
import org.onap.aai.introspection.sideeffect.DataLinkTest;
import org.onap.aai.parsers.query.GraphTraversalTest;
import org.onap.aai.query.builder.TraversalQueryTest;
DataLinkTest.class,
GraphTraversalTest.class,
TraversalQueryTest.class,
- TraversalURIOptimizedQueryTest.class
+ TraversalURIOptimizedQueryTest.class,
+ DbMethHelperTest.class
})
public class TinkerpopUpgradeTests {
}
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
+import org.junit.experimental.categories.Category;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.onap.aai.AAISetup;
+import org.onap.aai.TinkerpopUpgrade;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
+@Category(TinkerpopUpgrade.class)
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class DbMethHelperTest extends AAISetup {
map.put("pserver.hostname", "testSearchVertexByIdentityMap-pserver-hostname-01");
Optional<Vertex> optionalVertex;
- try {
- optionalVertex = dbMethHelper.searchVertexByIdentityMap(type, map);
- } catch (Exception e) {
- throw new Exception(e);
- }
- Assert.assertEquals("vp[hostname->testSearchVertexById]", optionalVertex.get().property("hostname").toString());
+ optionalVertex = dbMethHelper.searchVertexByIdentityMap(type, map);
+
+ String hostname = (String) optionalVertex.get().property("hostname").value();
+ Assert.assertEquals("testSearchVertexByIdentityMap-pserver-hostname-01", hostname);
}
@Test(expected = AmbiguousMapAAIException.class)
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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.introspection;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.aai.AAISetup;
+import org.onap.aai.domain.notificationEvent.NotificationEvent;
+import org.onap.aai.domain.notificationEvent.NotificationEvent.EventHeader;
+import org.onap.aai.introspection.exceptions.AAIUnmarshallingException;
+import org.onap.aai.setup.SchemaVersion;
+import org.skyscreamer.jsonassert.JSONAssert;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationModule;
+
+public class IntrospectorSerializationTest extends AAISetup {
+
+ ObjectMapper mapper;
+ Loader loader;
+
+ @Before
+ public void setup() {
+ loader = loaderFactory.getMoxyLoaderInstance().get(new SchemaVersion("v14"));
+ }
+
+ @Test
+ public void serializePlain() throws IOException, AAIUnmarshallingException {
+ mapper = new ObjectMapper();
+
+ String pserver = new String(Files.readAllBytes(Path.of("src/test/resources/payloads/templates/pserver.json")));
+ Introspector introspector = loader.unmarshal("pserver", pserver);
+ String result = mapper.writeValueAsString(introspector);
+ JSONAssert.assertEquals(pserver, result, false);
+ }
+
+ @Test
+ public void serializeNotificationEvent() throws IOException, AAIUnmarshallingException {
+ mapper = new ObjectMapper();
+ mapper.registerModule(new JakartaXmlBindAnnotationModule());
+
+ String pserver = new String(Files.readAllBytes(Path.of("src/test/resources/payloads/templates/pserver.json"))).replace("${hostname}", "pserver1");
+ Introspector introspector = loader.unmarshal("pserver", pserver);
+
+ NotificationEvent notificationEvent = new NotificationEvent();
+ notificationEvent.setCambriaPartition("AAI");
+ notificationEvent.setEntity(introspector);
+ EventHeader eventHeader = new EventHeader();
+ eventHeader.setSeverity("NORMAL");
+ eventHeader.setEntityType("pserver");
+ eventHeader.setTopEntityType("pserver");
+ eventHeader.setEntityLink("/aai/v14/cloud-infrastructure/pservers/pserver/pserver1");
+ eventHeader.setEventType("AAI-EVENT");
+ eventHeader.setDomain("devINT1");
+ eventHeader.setAction("CREATE");
+ eventHeader.setSequenceNumber("0");
+ eventHeader.setId("someTransaction");
+ eventHeader.setSourceName("test");
+ eventHeader.setVersion("v14");
+ notificationEvent.setEventHeader(eventHeader);
+ String result = mapper.writeValueAsString(notificationEvent);
+ String expectedEvent = new String(Files.readAllBytes(Path.of("src/test/resources/payloads/expected/pserver-event.json")));
+ JSONAssert.assertEquals(expectedEvent, result, false);
+ }
+}
import java.util.HashSet;
import java.util.Set;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.onap.aai.AAISetup;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
@Ignore("Not a used/flushed out feature")
+// This has been converted from org.json to Jackson,
+// but not in a way that tests are working
public class JSONStrategyTest extends AAISetup {
private JSONStrategy jsonStrategy;
private JSONStrategy jsonStrategyContainer;
@Before
public void setup() {
try {
- JSONObject pserver = new JSONObject();
+
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode pserver = mapper.createObjectNode();
+
pserver.put("hostname", "value1");
pserver.put("numberofCpus", 4);
jsonStrategy = new JSONStrategy(pserver, "pserver-type");
// The values of this object are arrays containing JSONObjects
- JSONArray pservers = new JSONArray();
+ ArrayNode pservers = mapper.createArrayNode();
pservers.add(pserver);
- JSONObject container = new JSONObject();
- container.put("pservers", pservers);
+
+ ObjectNode container = mapper.createObjectNode();
+ container.set("pservers", pservers);
jsonStrategyContainer = new JSONStrategy(container, "pservers-type");
// The values of this object are JSONObjects
- JSONObject complex = new JSONObject();
- complex.put("pserver", pserver);
+ ObjectNode complex = mapper.createObjectNode();
+ complex.set("pserver", pserver);
jsonStrategyComplex = new JSONStrategy(complex, "pservers-type");
} catch (Exception e) {
System.out.println("error during setup: " + e.getMessage());
@Test
public void getJavaClassNameTest() {
- Assert.assertEquals("org.json.simple.JSONObject", jsonStrategy.getJavaClassName());
- Assert.assertEquals("org.json.simple.JSONObject", jsonStrategyContainer.getJavaClassName());
+ Assert.assertEquals("com.fasterxml.jackson.databind.node.ObjectNode", jsonStrategy.getJavaClassName());
+ Assert.assertEquals("com.fasterxml.jackson.databind.node.ObjectNode", jsonStrategyContainer.getJavaClassName());
}
@Test
import java.util.List;
import java.util.UUID;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
}
- /**
+ /**
* This is more directly testing the modification mechanism (see verifyModificationOfVertex test)
*/
@Test
URI uri = new URI("/network/vpn-bindings/vpn-binding/modifyKey/route-targets/route-target/modifyTargetKey2/modifyRoleKey2");
MultivaluedMap<String, String> map = URITools.getQueryMap(uri);
GraphTraversal<Vertex, Vertex> traversal = __.<Vertex>start();
-
+
QueryParser uriQuery = dbEngine.getQueryBuilder(this.queryStyle, loader, source, traversal).createQueryFromURI(uri, map);
List<Vertex> results = uriQuery.getQueryBuilder().toList();
}
}
-
\ No newline at end of file
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.ModelType;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.springframework.test.annotation.DirtiesContext;
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.ModelType;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.springframework.test.annotation.DirtiesContext;
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.ModelType;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.springframework.test.annotation.DirtiesContext;
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.ModelType;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.springframework.test.annotation.DirtiesContext;
import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.LoaderFactory;
+import org.onap.aai.introspection.ModelType;
import org.onap.aai.introspection.tools.IntrospectorValidator;
import org.onap.aai.introspection.tools.Issue;
import org.onap.aai.introspection.tools.IssueType;
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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.kafka;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.onap.aai.AAISetup;
+import org.onap.aai.PayloadUtil;
+import org.onap.aai.domain.notificationEvent.NotificationEvent;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.parsers.query.QueryParser;
+import org.onap.aai.rest.db.DBRequest;
+import org.onap.aai.restcore.HttpMethod;
+import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+import org.onap.aai.setup.SchemaVersion;
+import org.skyscreamer.jsonassert.JSONAssert;
+import org.skyscreamer.jsonassert.JSONCompareMode;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Import;
+import org.springframework.kafka.core.ConsumerFactory;
+import org.springframework.kafka.core.KafkaTemplate;
+import org.springframework.kafka.test.context.EmbeddedKafka;
+import org.springframework.kafka.test.utils.KafkaTestUtils;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.TestPropertySource;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.UriInfo;
+import lombok.SneakyThrows;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@ActiveProfiles("kafka")
+@Import(KafkaTestConfiguration.class)
+@EmbeddedKafka(partitions = 1, topics = { "AAI-EVENT" })
+@TestPropertySource(
+ properties = {
+ "aai.events.enabled=true",
+ "spring.kafka.producer.retries=0",
+ "spring.kafka.producer.properties.sasl.jaas.config=#{null}",
+ "spring.kafka.producer.bootstrap-servers=${spring.embedded.kafka.brokers}",
+ "aai.notifications.enabled=true"
+ })
+public class AAIKafkaEventIntegrationTest extends AAISetup {
+
+ @Mock
+ private KafkaTemplate<String, String> kafkaTemplate;
+
+ @Autowired
+ ObjectMapper mapper;
+
+ @Autowired
+ NotificationProducer messageProducer;
+
+ @Autowired
+ private ConsumerFactory<String, String> consumerFactory;
+
+ @Mock UriInfo uriInfoMock;
+ @Mock MultivaluedMap<String, String> queryParamsMock;
+ @Mock HttpHeaders headersMock;
+
+ @Before
+ public void setup() {
+ when(headersMock.getAcceptableMediaTypes()).thenReturn(Collections.singletonList(MediaType.APPLICATION_JSON_TYPE));
+ when(uriInfoMock.getQueryParameters(anyBoolean())).thenReturn(queryParamsMock);
+ when(queryParamsMock.getFirst("depth")).thenReturn("0");
+ when(headersMock.getRequestHeader("aai-request-context")).thenReturn(null);
+ }
+
+ @Test
+ @Ignore
+ public void onMessage_shouldSendMessageToKafkaTopic_whenAAIEventReceived()
+ throws Exception {
+ Consumer<String, String> consumer = consumerFactory.createConsumer();
+
+ consumer.subscribe(Collections.singletonList("AAI-EVENT"));
+
+ String payload = PayloadUtil.getResourcePayload("aai-event.json");
+ NotificationEvent event = mapper.readValue(payload, NotificationEvent.class);
+ String expectedResponse = PayloadUtil.getExpectedPayload("aai-event.json");
+ messageProducer.sendNotification(event);
+
+ ConsumerRecords<String, String> consumerRecords = KafkaTestUtils.getRecords(consumer, Duration.ofSeconds(10));
+ assertFalse(consumerRecords.isEmpty());
+ consumerRecords.forEach(consumerRecord -> {
+ JSONAssert.assertEquals(expectedResponse, consumerRecord.value(), JSONCompareMode.NON_EXTENSIBLE);
+ });
+ }
+
+ @Test
+ public void thatEventsAreBeingCreated() throws AAIException, IOException {
+ Consumer<String, String> consumer = consumerFactory.createConsumer();
+ consumer.subscribe(Collections.singletonList("AAI-EVENT"));
+
+ traversalUriHttpEntry.setHttpEntryProperties(new SchemaVersion("v14"));
+ String pserverUri = "/aai/v14/cloud-infrastructure/pservers/pserver/pserver1";
+ String entity = new String(Files.readAllBytes(Path.of("src/test/resources/payloads/templates/pserver.json"))).replace("${hostname}", "pserver1");
+ DBRequest dbRequest = createDBRequest(pserverUri, entity);
+ List<DBRequest> dbRequests = new ArrayList<>();
+ dbRequests.add(dbRequest);
+
+ traversalUriHttpEntry.process(dbRequests, "test");
+
+ ConsumerRecords<String, String> consumerRecords = KafkaTestUtils.getRecords(consumer, Duration.ofSeconds(10));
+ assertFalse(consumerRecords.isEmpty());
+ String expectedResponse = PayloadUtil.getExpectedPayload("pserver-event.json");
+
+ consumerRecords.forEach(consumerRecord -> {
+ JSONAssert.assertEquals(expectedResponse, consumerRecord.value(), JSONCompareMode.LENIENT);
+ });
+ }
+
+ @SneakyThrows
+ private DBRequest createDBRequest(String uri, String entity) {
+ TransactionalGraphEngine dbEngine = traversalUriHttpEntry.getDbEngine();
+ Loader loader = traversalUriHttpEntry.getLoader();
+ URI uriObject = new URI(uri);
+ QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
+ String objName = uriQuery.getResultType();
+ Introspector obj = loader.unmarshal(objName, entity,
+ org.onap.aai.restcore.MediaType.getEnum("application/json"));
+ return new DBRequest.Builder(HttpMethod.PUT, uriObject, uriQuery, obj, headersMock, uriInfoMock, "someTransaction")
+ .rawRequestContent(entity)
+ .build();
+ }
+
+}
+++ /dev/null
-package org.onap.aai.kafka;
-
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import javax.jms.TextMessage;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
-import org.onap.aai.PayloadUtil;
-import org.springframework.core.env.Environment;
-import org.springframework.kafka.core.KafkaTemplate;
-import org.springframework.kafka.test.context.EmbeddedKafka;
-import org.springframework.test.util.ReflectionTestUtils;
-
-@RunWith(MockitoJUnitRunner.class)
-@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9092", "port=9092" })
-public class AAIKafkaEventJMSConsumerTest {
-
- @Mock
- private Environment environment;
-
- @Mock
- private KafkaTemplate<String,String> kafkaTemplate;
-
- private AAIKafkaEventJMSConsumer aaiKafkaEventJMSConsumer;
-
- @Before
- public void setUp(){
- aaiKafkaEventJMSConsumer = new AAIKafkaEventJMSConsumer(environment,kafkaTemplate);
- }
-
- @Test
- public void onMessage_shouldSendMessageToKafkaTopic_whenAAIEventReceived()
- throws Exception
- {
- TextMessage mockTextMessage = mock(TextMessage.class);
- String payload = PayloadUtil.getResourcePayload("aai-event.json");
-
- when(mockTextMessage.getText()).thenReturn(payload);
- aaiKafkaEventJMSConsumer.onMessage(mockTextMessage);
- verify(kafkaTemplate, times(1)).send(eq("AAI-EVENT"), anyString());
- }
-
- @Test
- public void onMessage_shouldNotSendMessageToKafkaTopic_whenInvalidEventReceived() throws Exception{
- TextMessage mockTextMessage = mock(TextMessage.class);
- String payload = PayloadUtil.getResourcePayload("aai-invalid-event.json");
- when(mockTextMessage.getText()).thenReturn(payload);
- aaiKafkaEventJMSConsumer.onMessage(mockTextMessage);
- }
-
-
- @Test
- public void onMessage_shouldHandleJSONException() throws Exception {
- // Arrange
- AAIKafkaEventJMSConsumer consumer = new AAIKafkaEventJMSConsumer(null, kafkaTemplate);
- TextMessage mockTextMessage = mock(TextMessage.class);
- ReflectionTestUtils.setField(consumer, "kafkaTemplate", null); // Simulate null kafkaTemplate
-
- // Act
- consumer.onMessage(mockTextMessage);
-
- // Assert
- // Verify that exception is logged
- }
-
- @Test
- public void onMessage_shouldHandleGenericException() throws Exception {
- // Arrange
- AAIKafkaEventJMSConsumer consumer = new AAIKafkaEventJMSConsumer(null, kafkaTemplate);
- TextMessage mockTextMessage = mock(TextMessage.class);
- when(mockTextMessage.getText()).thenReturn("{\"event-topic\":\"AAI-EVENT\",\"aaiEventPayload\":{}}"); // Valid JSON but missing required fields
-
- // Act
- consumer.onMessage(mockTextMessage);
-
- // Assert
- // Verify that exception is logged
- }
-
-}
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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.kafka;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.kafka.clients.admin.AdminClientConfig;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.common.serialization.StringDeserializer;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.context.annotation.Bean;
+import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
+import org.springframework.kafka.core.ConsumerFactory;
+import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
+import org.springframework.kafka.core.KafkaAdmin;
+
+@TestConfiguration
+public class KafkaTestConfiguration {
+
+ @Value("${spring.embedded.kafka.brokers}") private String bootstrapAddress;
+
+ private String groupId = "test-consumer";
+
+ @Bean
+ public KafkaAdmin kafkaAdmin() {
+ Map<String, Object> configs = new HashMap<>();
+ configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
+ return new KafkaAdmin(configs);
+ }
+
+ @Bean
+ public ConsumerFactory<String, String> consumerFactory() {
+ Map<String, Object> props = new HashMap<>();
+ props.put(
+ ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
+ bootstrapAddress);
+ props.put(
+ ConsumerConfig.GROUP_ID_CONFIG,
+ groupId);
+ props.put(
+ ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
+ StringDeserializer.class);
+ props.put(
+ ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
+ StringDeserializer.class);
+ props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
+ return new DefaultKafkaConsumerFactory<>(props);
+ }
+
+ @Bean
+ public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory(ConsumerFactory<String, String> consumerFactory) {
+
+ ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
+ factory.setConsumerFactory(consumerFactory);
+ return factory;
+ }
+}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import javax.ws.rs.core.Response.Status;
+import jakarta.ws.rs.core.Response.Status;
import org.junit.Test;
import java.util.Collection;
import java.util.List;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.UriBuilder;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.UriBuilder;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
/**
* Configure.
- *
+ *
* @throws Exception
* @throws SecurityException
* @throws NoSuchFieldException
thrown.expect(AAIException.class);
thrown.expectMessage(containsString(RestTokens.COUSIN.toString()));
- QueryParser query = dbEngineDepthVersion.getQueryBuilder().createQueryFromURI(uri);
-
+ dbEngineDepthVersion.getQueryBuilder().createQueryFromURI(uri);
}
@Test
thrown.expect(AAIException.class);
thrown.expectMessage(containsString("chain plurals"));
- QueryParser query = dbEngineDepthVersion.getQueryBuilder().createQueryFromURI(uri);
-
+ dbEngineDepthVersion.getQueryBuilder().createQueryFromURI(uri);
}
}
import java.io.UnsupportedEncodingException;
import java.net.URI;
-import javax.ws.rs.core.UriBuilder;
-import javax.xml.bind.JAXBException;
-
import org.junit.Ignore;
import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.setup.SchemaVersion;
+import jakarta.ws.rs.core.UriBuilder;
+import jakarta.xml.bind.JAXBException;
+
@Ignore
public class LegacyQueryTest extends AAISetup {
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.junit.rules.ExpectedException;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.IntrospectorFactory;
+import org.onap.aai.introspection.ModelType;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
import org.onap.aai.serialization.engines.QueryStyle;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.IntrospectorFactory;
+import org.onap.aai.introspection.ModelType;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.IntrospectorFactory;
+import org.onap.aai.introspection.ModelType;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
import org.onap.aai.serialization.engines.QueryStyle;
import java.io.UnsupportedEncodingException;
import java.net.URI;
-import javax.ws.rs.core.UriBuilder;
+import jakarta.ws.rs.core.UriBuilder;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
import java.io.UnsupportedEncodingException;
import java.net.URI;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-
-import javax.annotation.PostConstruct;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.UriBuilder;
-import javax.xml.bind.JAXBException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
-import org.mockito.InOrder;
import org.onap.aai.AAISetup;
import org.onap.aai.edges.enums.EdgeType;
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.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.setup.SchemaVersion;
+import jakarta.annotation.PostConstruct;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.UriBuilder;
+import jakarta.xml.bind.JAXBException;
+
public class URIParserTest extends AAISetup {
import java.io.UnsupportedEncodingException;
import java.net.URI;
-import javax.annotation.PostConstruct;
-import javax.ws.rs.core.UriBuilder;
-import javax.xml.bind.JAXBException;
-
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.ModelType;
import org.onap.aai.parsers.exceptions.DoesNotStartWithValidNamespaceException;
+import jakarta.annotation.PostConstruct;
+import jakarta.ws.rs.core.UriBuilder;
+import jakarta.xml.bind.JAXBException;
+
public class URIToDBKeyTest extends AAISetup {
private Loader loader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
-import javax.annotation.PostConstruct;
-import javax.ws.rs.core.UriBuilder;
-import javax.xml.bind.JAXBException;
-
import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.setup.SchemaVersion;
import org.springframework.test.annotation.DirtiesContext;
+import jakarta.annotation.PostConstruct;
+import jakarta.ws.rs.core.UriBuilder;
+import jakarta.xml.bind.JAXBException;
+
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class URIToExtensionInformationTest extends AAISetup {
import java.net.URI;
import java.util.HashMap;
-import javax.annotation.PostConstruct;
-import javax.ws.rs.core.UriBuilder;
-import javax.xml.bind.JAXBException;
-
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.ModelType;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.setup.SchemaVersion;
import org.springframework.test.annotation.DirtiesContext;
+import jakarta.annotation.PostConstruct;
+import jakarta.ws.rs.core.UriBuilder;
+import jakarta.xml.bind.JAXBException;
+
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class URIToObjectTest extends AAISetup {
import java.net.URI;
import java.net.URISyntaxException;
-import javax.annotation.PostConstruct;
-import javax.ws.rs.core.UriBuilder;
-import javax.xml.bind.JAXBException;
-
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.*;
+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.springframework.test.annotation.DirtiesContext;
+import jakarta.annotation.PostConstruct;
+import jakarta.ws.rs.core.UriBuilder;
+import jakarta.xml.bind.JAXBException;
+
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class URIToRelationshipObjectTest extends AAISetup {
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
+import static org.mockito.ArgumentCaptor.forClass;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationModule;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.List;
-import org.apache.http.conn.ConnectTimeoutException;
+import org.apache.hc.client5.http.ConnectTimeoutException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.onap.aai.PayloadUtil;
+import org.onap.aai.domain.notificationEvent.NotificationEvent;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.restclient.RestClient;
+import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
public OutputCaptureRule capture = new OutputCaptureRule();
private Gson gson;
+ private ObjectMapper mapper;
@Before
public void setUp() throws Exception {
+ mapper = new ObjectMapper();
+ mapper.registerModule(new JakartaXmlBindAnnotationModule());
gson = new Gson();
restClient = Mockito.mock(RestClient.class);
- validationService = Mockito.spy(new ValidationService(restClient, "JUNIT", "generic-vnf", null));
+ validationService = Mockito.spy(new ValidationService(restClient, "JUNIT", "generic-vnf", null, mapper));
}
@Test
throws IOException, AAIException {
String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
+ NotificationEvent notificationEvent = mapper.readValue(pserverRequest, NotificationEvent.class);
Mockito.when(restClient.execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(),
- eq(pserverRequest))).thenThrow(new RuntimeException(new ConnectException("Connection refused")));
+ anyString())).thenThrow(new RuntimeException(new ConnectException("Connection refused")));
- validationService.preValidate(pserverRequest);
+ validationService.preValidate(notificationEvent);
assertThat(capture.toString(),
containsString("Connection refused to the validation microservice due to service unreachable"));
+ ArgumentCaptor<String> bodyCaptor = forClass(String.class);
+ verify(restClient).execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(), bodyCaptor.capture());
+
+ JSONAssert.assertEquals(pserverRequest, bodyCaptor.getValue(), false);
}
@Test
throws IOException, AAIException {
String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
+ NotificationEvent notificationEvent = mapper.readValue(pserverRequest, NotificationEvent.class);
Mockito.when(restClient.execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(),
- eq(pserverRequest)))
+ anyString()))
.thenThrow(new RuntimeException(new ConnectTimeoutException("Connection timed out")));
- validationService.preValidate(pserverRequest);
+ validationService.preValidate(notificationEvent);
assertThat(capture.toString(), containsString(
"Connection timeout to the validation microservice as this could indicate the server is unable to reach port"));
+ ArgumentCaptor<String> bodyCaptor = forClass(String.class);
+ verify(restClient).execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(), bodyCaptor.capture());
+
+ JSONAssert.assertEquals(pserverRequest, bodyCaptor.getValue(), false);
}
@Test
throws IOException, AAIException {
String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
+ NotificationEvent notificationEvent = mapper.readValue(pserverRequest, NotificationEvent.class);
String validationResponse =
PayloadUtil.getResourcePayload("prevalidation/success-response-with-empty-violations.json");
ResponseEntity responseEntity = Mockito.mock(ResponseEntity.class, Mockito.RETURNS_DEEP_STUBS);
Mockito.when(restClient.execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(),
- eq(pserverRequest))).thenReturn(responseEntity);
+ anyString())).thenReturn(responseEntity);
Mockito.when(responseEntity.getStatusCodeValue()).thenReturn(200);
Mockito.when(responseEntity.getBody()).thenReturn(validationResponse);
Mockito.doReturn(true).when(validationService).isSuccess(responseEntity);
- List<String> errorMessages = validationService.preValidate(pserverRequest);
+ List<String> errorMessages = validationService.preValidate(notificationEvent);
assertNotNull("Expected the error messages to be not null", errorMessages);
assertThat(errorMessages.size(), is(0));
+
+ ArgumentCaptor<String> bodyCaptor = forClass(String.class);
+ verify(restClient).execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(), bodyCaptor.capture());
+
+ JSONAssert.assertEquals(pserverRequest, bodyCaptor.getValue(), false);
}
@Test
throws IOException, AAIException {
String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
+ NotificationEvent notificationEvent = mapper.readValue(pserverRequest, NotificationEvent.class);
Mockito.when(restClient.execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(),
- eq(pserverRequest)))
+ anyString()))
.thenThrow(new RuntimeException(
new SocketTimeoutException("Request timed out due to taking longer than client expected")));
- validationService.preValidate(pserverRequest);
+ validationService.preValidate(notificationEvent);
assertThat(capture.toString(),
containsString("Request to validation service took longer than the currently set timeout"));
+ ArgumentCaptor<String> bodyCaptor = forClass(String.class);
+ verify(restClient).execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(), bodyCaptor.capture());
+
+ JSONAssert.assertEquals(pserverRequest, bodyCaptor.getValue(), false);
}
@Test
import org.junit.runner.RunWith;
import org.onap.aai.config.ConfigConfiguration;
import org.onap.aai.config.IntrospectionConfig;
+import org.onap.aai.config.KafkaConfig;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.config.XmlFormatTransformerConfiguration;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.introspection.LoaderFactory;
import org.onap.aai.introspection.ModelType;
import org.onap.aai.nodes.NodeIngestor;
+import org.onap.aai.rest.notification.NotificationService;
import org.onap.aai.serialization.db.EdgeSerializer;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
import org.onap.aai.serialization.queryformats.QueryFormatTestHelper;
@ContextConfiguration(
classes = {ConfigConfiguration.class, QueryTestsConfigTranslator.class, NodeIngestor.class, EdgeIngestor.class,
EdgeSerializer.class, SpringContextAware.class, IntrospectionConfig.class,
- XmlFormatTransformerConfiguration.class})
+ XmlFormatTransformerConfiguration.class, LoaderFactory.class, NotificationService.class, KafkaConfig.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
@TestPropertySource(
properties = {"schema.translator.list = config", "schema.nodes.location=src/test/resources/onap/oxm",
- "schema.edges.location=src/test/resources/onap/dbedgerules"})
+ "schema.edges.location=src/test/resources/onap/dbedgerules",
+ "aai.notifications.enabled=false"})
public abstract class QueryBuilderTestAbstraction {
protected Loader loader;
public static void setup() throws Exception {
System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
- QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"),
- "src/test/resources/bundleconfig-local/etc/oxm/");
graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
}
import java.lang.reflect.Method;
import java.net.URI;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Before;
import static org.junit.Assert.assertEquals;
-import com.jayway.jsonpath.JsonPath;
-
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
-import javax.ws.rs.core.Response;
-
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
+import com.jayway.jsonpath.JsonPath;
+
+import jakarta.ws.rs.core.Response;
+
/**
* <b>CloudRegionTest</b> is testing if you put a cloud region with all
* children nodes associated to it then you should be able to
import java.io.IOException;
import java.util.UUID;
-import javax.ws.rs.core.Response;
-
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.engines.QueryStyle;
+import jakarta.ws.rs.core.Response;
+
public class EdgeNotValidAnymoreTest extends AAISetup {
private HttpTestUtil testUtil;
import static org.junit.Assert.assertEquals;
-import com.jayway.jsonpath.JsonPath;
-
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Collection;
-import javax.ws.rs.core.Response;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.test.annotation.DirtiesContext;
+import com.jayway.jsonpath.JsonPath;
+
+import jakarta.ws.rs.core.Response;
+
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class EntitlementTest extends AAISetup {
import java.util.HashMap;
import java.util.Map;
-import javax.ws.rs.core.Response;
-
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.test.annotation.DirtiesContext;
+import jakarta.ws.rs.core.Response;
+
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class GenericVnfLInterfaceTest extends AAISetup {
import static org.junit.Assert.assertEquals;
-import com.jayway.jsonpath.JsonPath;
-
-import java.util.*;
-
-import javax.ws.rs.core.Response;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
import org.junit.Before;
import org.junit.Ignore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.jayway.jsonpath.JsonPath;
+
+import jakarta.ws.rs.core.Response;
+
@Ignore
@RunWith(AAIJunitRunner.class)
public class HPACapabilityTest {
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
-import javax.ws.rs.core.Response;
-
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.janusgraph.core.JanusGraphTransaction;
import org.json.JSONObject;
import org.onap.aai.PayloadUtil;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.dbmap.AAIGraph;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.rest.ueb.NotificationEvent;
-import org.onap.aai.rest.ueb.UEBNotification;
+import org.onap.aai.domain.notificationEvent.NotificationEvent;
+import org.onap.aai.domain.notificationEvent.NotificationEvent.EventHeader;
+import org.onap.aai.rest.notification.UEBNotification;
import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.annotation.DirtiesContext;
+import jakarta.ws.rs.core.Response;
+
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class ImpliedDeleteIntegrationTest extends AAISetup {
String uri = "/aai/v12/cloud-infrastructure/pservers/pserver/test-pserver-implied-delete";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH);
String resource = PayloadUtil.getResourcePayload("pserver-implied-delete.json");
JSONAssert.assertEquals(resource, response.getEntity().toString(), false);
jsonObject.getJSONObject("p-interfaces").remove("p-interface");
- notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH);
response = httpTestUtil.doPut(uri, jsonObject.toString());
List<NotificationEvent> notificationEvents = notification.getEvents();
assertThat(notificationEvents.size(), is(5));
- List<String> notificationEventHeaders = notification.getEvents().stream()
- .map(event -> event.getEventHeader().marshal(false)).collect(Collectors.toList());
+ List<EventHeader> notificationEventHeaders = notification.getEvents().stream()
+ .map(NotificationEvent::getEventHeader)
+ .collect(Collectors.toList());
- Long deletedEventsCount = notificationEventHeaders.stream().filter(e -> e.contains("\"DELETE\"")).count();
+ Long deletedEventsCount = notificationEventHeaders.stream().filter(e -> "DELETE".equals(e.getAction())).count();
assertThat(deletedEventsCount, is(4L));
import static org.junit.Assert.assertEquals;
-import com.jayway.jsonpath.JsonPath;
-
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Collection;
-import javax.ws.rs.core.Response;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.test.annotation.DirtiesContext;
+import com.jayway.jsonpath.JsonPath;
+
+import jakarta.ws.rs.core.Response;
+
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class ModelElementTest extends AAISetup {
import static org.hamcrest.junit.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.List;
import java.util.Map;
-import javax.ws.rs.core.Response;
+import jakarta.ws.rs.core.Response;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.PayloadUtil;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.dbmap.AAIGraph;
+import org.onap.aai.domain.notificationEvent.NotificationEvent;
+import org.onap.aai.domain.notificationEvent.NotificationEvent.EventHeader;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.rest.ueb.NotificationEvent;
-import org.onap.aai.rest.ueb.UEBNotification;
+import org.onap.aai.rest.notification.UEBNotification;
import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class NotificationDmaapEventTest extends AAISetup {
+// ObjectMapper mapper = new ObjectMapper();
+ @Autowired private ObjectMapper mapper;
+
@Parameterized.Parameter
public QueryStyle queryStyle;
@Parameterized.Parameters(name = "QueryStyle.{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}});
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}});
}
@Test
throws IOException, AAIException {
String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH);
String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
// Verify all the events are create since its a new PUT
notification.getEvents().forEach((event) -> {
-
- String header = event.getEventHeader().marshal(false);
-
- assertThat(event.getEventHeader().marshal(false), containsString("\"CREATE\""));
-
- assertThat(header, containsString("\"top-entity-type\":\"pserver\""));
-
+ assertEquals("CREATE", event.getEventHeader().getAction());
+ assertEquals("pserver", event.getEventHeader().getTopEntityType());
});
response = httpTestUtil.doGet(uri);
throws IOException, AAIException {
String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
List<NotificationEvent> events = notification.getEvents();
assertThat(events.size(), is(2));
- String notificationEventHeader = events.get(1).getEventHeader().marshal(false);
- String notificationEventBody = events.get(1).getObj().marshal(false);
+ EventHeader notificationEventHeader = events.get(1).getEventHeader();
+ String notificationEventBody = events.get(1).getEntity().toString();
- assertThat(notificationEventHeader, containsString("\"action\":\"CREATE\""));
- assertThat(notificationEventHeader, containsString("\"entity-type\":\"p-interface\""));
- assertThat(notificationEventHeader, containsString("\"top-entity-type\":\"pserver\""));
+ assertEquals("CREATE", notificationEventHeader.getAction());
+ assertEquals("p-interface", notificationEventHeader.getEntityType());
+ assertEquals("pserver", notificationEventHeader.getTopEntityType());
String expectedNotificationHeader = PayloadUtil.getResourcePayload(
"notification-dmaap-events/depth-zero/expected-notification-header-create-child-on-existing-obj.json");
String expectedNotificationBody = PayloadUtil.getResourcePayload(
"notification-dmaap-events/depth-zero/expected-notification-body-create-child-on-existing-obj.json");
- JSONAssert.assertEquals(expectedNotificationHeader, notificationEventHeader, false);
+ String eventHeaderJson = mapper.writeValueAsString(events.get(1).getEventHeader());
+ JSONAssert.assertEquals(expectedNotificationHeader, eventHeaderJson, false);
JSONAssert.assertEquals(expectedNotificationBody, notificationEventBody, false);
}
throws IOException, AAIException {
String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
List<NotificationEvent> events = notification.getEvents();
assertThat(events.size(), is(1));
- String notificationEventHeader = events.get(0).getEventHeader().marshal(false);
- String notificationEventBody = events.get(0).getObj().marshal(false);
-
- assertThat(notificationEventHeader, containsString("\"action\":\"UPDATE\""));
- assertThat(notificationEventHeader, containsString("\"entity-type\":\"pserver\""));
- assertThat(notificationEventHeader, containsString("\"top-entity-type\":\"pserver\""));
+ EventHeader notificationEventHeader = events.get(0).getEventHeader();
+ String notificationEventBody = events.get(0).getEntity().toString();
+ assertEquals("UPDATE", notificationEventHeader.getAction());
+ assertEquals("pserver", notificationEventHeader.getEntityType());
+ assertEquals("pserver", notificationEventHeader.getTopEntityType());
String expectedNotificationHeader = PayloadUtil.getResourcePayload(
"notification-dmaap-events/depth-all/expected-notification-header-create-child-on-existing-obj.json");
String expectedNotificationBody = PayloadUtil.getResourcePayload(
"notification-dmaap-events/depth-all/expected-notification-body-create-child-on-existing-obj.json");
- JSONAssert.assertEquals(expectedNotificationHeader, notificationEventHeader, false);
+ String eventHeaderJson = mapper.writeValueAsString(events.get(0).getEventHeader());
+ JSONAssert.assertEquals(expectedNotificationHeader, eventHeaderJson, false);
JSONAssert.assertEquals(expectedNotificationBody, notificationEventBody, false);
response = httpTestUtil.doGet(uri, "0");
String cloudRegionUri =
"/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/random-cloud-region-owner/random-cloud-region-id";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH);
Map<String, String> uriPayload = new LinkedHashMap<>();
assertThat("Expecting the number of dmaap events to be 2", numberOfEventsActual, is(expectedEvents));
notification.getEvents().forEach((event) -> {
- String notificationEventHeader = event.getEventHeader().marshal(false);
- assertThat(notificationEventHeader, containsString("\"CREATE\""));
+ assertEquals("CREATE", event.getEventHeader().getAction());
});
}
String cloudRegionUri =
"/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/random-cloud-region-owner/random-cloud-region-id";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH);
Map<String, String> uriPayload = new LinkedHashMap<>();
assertThat("Expecting the number of dmaap events to be 2", numberOfEventsActual, is(expectedEvents));
notification.getEvents().forEach((event) -> {
- String notificationEventHeader = event.getEventHeader().marshal(false);
- assertThat(notificationEventHeader, containsString("\"CREATE\""));
+ assertEquals("CREATE", event.getEventHeader().getAction());
});
}
public void testDeleteOnExistingPserverAndCheckIfNotificationDepthIsZeroThatAllEventsHaveDeleteAndThatDepthIsZeroOnEachNotificationEvent()
throws IOException, AAIException {
String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
assertThat(notificationEvents.size(), is(17));
notificationEvents.forEach((event) -> {
-
- String header = event.getEventHeader().marshal(false);
-
- assertThat(event.getEventHeader().marshal(false), containsString("\"DELETE\""));
-
- assertThat(header, containsString("\"top-entity-type\":\"pserver\""));
+ EventHeader header = event.getEventHeader();
+ assertEquals("DELETE", header.getAction());
+ assertEquals("pserver", header.getTopEntityType());
});
}
@Test
public void testDeleteOnExistingResourceVersionMismatchNoEventGenerated() throws IOException, AAIException {
String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
throws IOException, AAIException {
String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH);
String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
NotificationEvent notificationEvent = notification.getEvents().get(0);
// Verify all the events are create since its a new PUT
- String header = notificationEvent.getEventHeader().marshal(false);
-
- assertThat(header, containsString("\"CREATE\""));
-
- assertThat(header, containsString("\"entity-type\":\"pserver\""));
-
- assertThat(header, containsString("\"top-entity-type\":\"pserver\""));
-
- assertThat(header, containsString("\"entity-link\":\"" + uri + "\""));
+ EventHeader eventHeader = notificationEvent.getEventHeader();
+ assertEquals("CREATE", eventHeader.getAction());
+ assertEquals("pserver", eventHeader.getEntityType());
+ assertEquals("pserver", eventHeader.getTopEntityType());
+ assertEquals(uri, eventHeader.getEntityLink());
response = httpTestUtil.doGet(uri);
assertEquals("Expecting the pserver to be found", 200, response.getStatus());
- JSONAssert.assertEquals(response.getEntity().toString(), notificationEvent.getObj().marshal(false), false);
+ JSONAssert.assertEquals(response.getEntity().toString(), notificationEvent.getEntity().toString(), false);
}
@Test
throws IOException, AAIException {
String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
assertThat(response.getEntity().toString(), containsString("new-equip-patch-type"));
assertThat(notification.getEvents().size(), is(1));
- String updateNotificationEvent = notification.getEvents().get(0).getObj().marshal(true);
+ String updateNotificationEvent = notification.getEvents().get(0).getEntity().toString();
// Check that everything in notification event is also response body
// Not comparing the other way as notification only includes parents main properties
throws IOException, AAIException {
String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
assertThat(response.getEntity().toString(), containsString("new-equip-patch-type"));
assertThat(notification.getEvents().size(), is(1));
- String updateNotificationEvent = notification.getEvents().get(0).getObj().marshal(true);
+ String updateNotificationEvent = notification.getEvents().get(0).getEntity().toString();
// Check that everything in notification event is also response body
// Not comparing the other way as notification only includes parents main properties
throws IOException, AAIException {
String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
assertThat(response.getEntity().toString(), containsString("new-equipment-identifier"));
assertThat(notification.getEvents().size(), is(1));
- String updateNotificationEvent = notification.getEvents().get(0).getObj().marshal(true);
+ String updateNotificationEvent = notification.getEvents().get(0).getEntity().toString();
// Check that everything in notification event is also response body
// Not comparing the other way as notification only includes parents main properties
throws IOException, AAIException {
String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
response = httpTestUtil.doGet(uri);
assertThat(notification.getEvents().size(), is(1));
- String updateNotificationEvent = notification.getEvents().get(0).getObj().marshal(true);
+ String updateNotificationEvent = notification.getEvents().get(0).getEntity().toString();
System.out.println("Update notification " + updateNotificationEvent);
// Check that everything in notification event is also response body
String pserverUri = "/aai/v14/cloud-infrastructure/pservers/pserver/" + hostname;
String genericVnfUri = "/aai/v14/network/generic-vnfs/generic-vnf/generic-vnf-notification";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
String expectedNotificationBody = PayloadUtil.getResourcePayload(
"notification-dmaap-events/depth-zero/expected-notification-body-create-edge-between-pserver-and-generic-vnf.json");
- JSONAssert.assertEquals(expectedNotificationHeader, notificationEvents.get(0).getEventHeader().marshal(false),
+ JSONAssert.assertEquals(expectedNotificationHeader, mapper.writeValueAsString(notificationEvents.get(0).getEventHeader()),
false);
- JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getObj().marshal(false), false);
+ JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getEntity().toString(), false);
response = httpTestUtil.doGet(genericVnfUri);
String pserverUri = "/aai/v14/cloud-infrastructure/pservers/pserver/" + hostname;
String genericVnfUri = "/aai/v14/network/generic-vnfs/generic-vnf/generic-vnf-notification";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
String expectedNotificationBody = PayloadUtil.getResourcePayload(
"notification-dmaap-events/depth-all/expected-notification-body-create-edge-between-pserver-and-generic-vnf.json");
- System.out.println("Notification Body: " + notificationEvents.get(0).getObj().marshal(false));
- JSONAssert.assertEquals(expectedNotificationHeader, notificationEvents.get(0).getEventHeader().marshal(false),
+ System.out.println("Notification Body: " + notificationEvents.get(0).getEntity().toString());
+ JSONAssert.assertEquals(expectedNotificationHeader, mapper.writeValueAsString(notificationEvents.get(0).getEventHeader()),
false);
- JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getObj().marshal(false), false);
+ JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getEntity().toString(), false);
response = httpTestUtil.doGet(genericVnfUri);
String relationship = PayloadUtil.getResourcePayload("pserver-to-gvnf-relationship-notification.json");
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
String expectedNotificationBody = PayloadUtil.getResourcePayload(
"notification-dmaap-events/depth-zero/expected-notification-body-delete-edge-between-pserver-and-generic-vnf.json");
- JSONAssert.assertEquals(expectedNotificationHeader, notificationEvents.get(0).getEventHeader().marshal(false),
+ JSONAssert.assertEquals(expectedNotificationHeader, mapper.writeValueAsString(notificationEvents.get(0).getEventHeader()),
false);
- JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getObj().marshal(false), false);
+ JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getEntity().toString(), false);
}
String relationship = PayloadUtil.getResourcePayload("pserver-to-gvnf-relationship-notification.json");
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
String expectedNotificationBody = PayloadUtil.getResourcePayload(
"notification-dmaap-events/depth-all/expected-notification-body-delete-edge-between-pserver-and-generic-vnf.json");
- JSONAssert.assertEquals(expectedNotificationHeader, notificationEvents.get(0).getEventHeader().marshal(false),
+ JSONAssert.assertEquals(expectedNotificationHeader, mapper.writeValueAsString(notificationEvents.get(0).getEventHeader()),
false);
- JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getObj().marshal(false), false);
+ JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getEntity().toString(), false);
}
public void testDeleteOnExistingResourceVersionMismatchNoEventGeneratedFullDepth()
throws IOException, AAIException {
String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598";
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json");
@Test
public void testCreateVnfWithChildrenCreateCustomerWithChildrenAndCousinBetweenVlanAndServiceInstanceThenDeleteCustomerVerifyingVlanRV()
throws IOException, AAIException {
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String json = PayloadUtil.getResourcePayload(
@Test
public void testBulkCreateOfComplexAndPserverWithRelationshipThenBulkDeleteBoth() throws IOException, AAIException {
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH);
JsonObject payloads = JsonParser
Map<String, Pair<String, String>> deletes = new LinkedHashMap<>();
deletes.put(pserverUri, new Pair<>(pserverRv, null));
deletes.put(complexUri, new Pair<>(complexRV, null));
- notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH);
httpTestUtil.doDelete(deletes);
@Test
public void testCreateVnfWithChildrenCreateCustomerWithChildrenAndCousinBetweenVlanAndServiceInstanceThenImplicitDeleteVlanVerifyingServiceInstanceRV()
throws IOException, AAIException {
- UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions));
+ UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle);
String json = PayloadUtil.getResourcePayload(
import java.util.*;
-import javax.ws.rs.core.Response;
+import jakarta.ws.rs.core.Response;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.junit.Before;
import java.util.*;
-import javax.ws.rs.core.Response;
+import jakarta.ws.rs.core.Response;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Edge;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
-import javax.ws.rs.core.Response;
-
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import jakarta.ws.rs.core.Response;
+
public class PserverDuplicateTest extends AAISetup {
private static final Logger LOGGER = LoggerFactory.getLogger(PserverDuplicateTest.class);
import java.util.HashMap;
import java.util.Map;
-import javax.ws.rs.core.Response;
+import jakarta.ws.rs.core.Response;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.janusgraph.core.JanusGraphTransaction;
package org.onap.aai.rest;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
-import com.jayway.jsonpath.JsonPath;
-
-import java.util.*;
-
-import javax.ws.rs.core.Response;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
import org.junit.Before;
import org.junit.ClassRule;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
+import com.jayway.jsonpath.JsonPath;
+
+import jakarta.ws.rs.core.Response;
+
@RunWith(value = Parameterized.class)
public class TenantTest extends AAISetup {
import java.util.Arrays;
import java.util.Collection;
-import javax.ws.rs.core.Response;
+import jakarta.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
-import javax.ws.rs.core.Response;
-
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.janusgraph.core.JanusGraphTransaction;
-import org.junit.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.onap.aai.AAISetup;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
+import jakarta.ws.rs.core.Response;
+
@RunWith(value = Parameterized.class)
public class VnfcRelationshipIssueTest extends AAISetup {
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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.rest.db;
+
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.not;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.UUID;
+
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.UriBuilder;
+import jakarta.ws.rs.core.UriInfo;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.javatuples.Pair;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.aai.AAISetup;
+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.parsers.query.QueryParser;
+import org.onap.aai.query.builder.QueryOptions;
+import org.onap.aai.rest.notification.UEBNotification;
+import org.onap.aai.restcore.HttpMethod;
+import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+import org.springframework.test.annotation.DirtiesContext;
+
+@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
+public class HttpEntryNotificationIntegrationTest extends AAISetup {
+
+ private static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
+ private Loader loader;
+ private TransactionalGraphEngine dbEngine;
+ private GraphTraversalSource traversal;
+ private HttpHeaders httpHeaders;
+ private UriInfo uriInfo;
+ private MultivaluedMap<String, String> headersMultiMap;
+ private MultivaluedMap<String, String> queryParameters;
+ private List<String> aaiRequestContextList;
+ private List<MediaType> outputMediaTypes;
+
+ @Before
+ public void setup() {
+
+ httpHeaders = Mockito.mock(HttpHeaders.class);
+ uriInfo = Mockito.mock(UriInfo.class);
+
+ headersMultiMap = new MultivaluedHashMap<>();
+ queryParameters = Mockito.spy(new MultivaluedHashMap<>());
+
+ headersMultiMap.add("X-FromAppId", "JUNIT");
+ headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
+ headersMultiMap.add("Real-Time", "true");
+ headersMultiMap.add("Accept", "application/json");
+ headersMultiMap.add("aai-request-context", "");
+
+ outputMediaTypes = new ArrayList<>();
+ outputMediaTypes.add(APPLICATION_JSON);
+
+ aaiRequestContextList = new ArrayList<>();
+ aaiRequestContextList.add("");
+
+ traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion());
+ loader = traversalHttpEntry.getLoader();
+ dbEngine = traversalHttpEntry.getDbEngine();
+ traversal = dbEngine.tx().traversal();
+
+ when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
+ when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
+
+ when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
+
+ when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
+ when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters);
+
+ // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be
+ // very unreasonable
+ Mockito.doReturn(null).when(queryParameters).remove(any());
+
+ when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
+ }
+
+ @After
+ public void rollback() {
+ dbEngine.rollback();
+ }
+
+ @Test
+ public void notificationOnRelatedToTest() throws UnsupportedEncodingException, AAIException {
+
+ Loader ld = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
+ UEBNotification uebNotification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions));
+ traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), uebNotification);
+
+ Loader loader = traversalHttpEntry.getLoader();
+ TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
+ // Put pserver
+ String uri = "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver";
+ String content = "{\"hostname\":\"junit-edge-test-pserver\"}";
+ doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
+ // Put complex
+ uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex";
+ content = "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
+ doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
+
+ // PutEdge
+ uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex/relationship-list/relationship";
+ content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + schemaVersions.getDefaultVersion().toString()
+ + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\"}";
+
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri,
+ content);
+
+ assertEquals("Expected the pserver relationship to be deleted", 200, response.getStatus());
+ assertEquals("Two notifications", 2, uebNotification.getEvents().size());
+ assertEquals("Notification generated for PUT edge", "UPDATE",
+ uebNotification.getEvents().get(1).getEventHeader().getAction());
+ assertThat("Event body for the edge create has the related to",
+ uebNotification.getEvents().get(1).getEntity().toString(),
+ containsString("cloud-infrastructure/pservers/pserver/junit-edge-test-pserver"));
+
+ response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.DELETE_EDGE, uri, content);
+ assertEquals("Expected the pserver relationship to be deleted", 204, response.getStatus());
+ assertEquals("Two notifications", 2, uebNotification.getEvents().size());
+ assertEquals("Notification generated for DELETE edge", "UPDATE",
+ uebNotification.getEvents().get(0).getEventHeader().getAction());
+ assertThat("Event body for the edge delete does not have the related to",
+ uebNotification.getEvents().get(0).getEntity().toString(),
+ not(containsString("cloud-infrastructure/pservers/pserver/junit-edge-test-pserver")));
+ dbEngine.rollback();
+
+ }
+
+ private Response doRequest(HttpEntry httpEntry, Loader loader, TransactionalGraphEngine dbEngine, HttpMethod method,
+ String uri, String requestBody) throws UnsupportedEncodingException, AAIException {
+ return doRequest(httpEntry, loader, dbEngine, method, uri, requestBody, null);
+ }
+
+ private Response doRequest(HttpEntry httpEntry, Loader loader, TransactionalGraphEngine dbEngine, HttpMethod method,
+ String uri, String requestBody, QueryOptions queryOptions) throws UnsupportedEncodingException, AAIException {
+ URI uriObject = UriBuilder.fromPath(uri).build();
+ QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
+ String objType;
+ if (!uriQuery.getContainerType().equals("")) {
+ objType = uriQuery.getContainerType();
+ } else {
+ objType = uriQuery.getResultType();
+ }
+ if (uri.endsWith("relationship")) {
+ objType = "relationship";
+ }
+ Introspector obj;
+ if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.GET_RELATIONSHIP)) {
+ obj = loader.introspectorFromName(objType);
+ } else {
+ obj = loader.unmarshal(objType, requestBody, org.onap.aai.restcore.MediaType.getEnum("application/json"));
+ }
+
+ DBRequest.Builder builder = new DBRequest.Builder(method, uriObject, uriQuery, obj, httpHeaders, uriInfo,
+ "JUNIT-TRANSACTION");
+ DBRequest dbRequest = requestBody != null
+ ? builder.rawRequestContent(requestBody).build()
+ : builder.build();
+
+ List<DBRequest> dbRequestList = Collections.singletonList(dbRequest);
+
+ Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = httpEntry.process(dbRequestList, "JUNIT",
+ Collections.emptySet(), true, queryOptions);
+ return responsesTuple.getValue1().get(0).getValue1();
+ }
+}
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.rest.db;
-
-import static org.onap.aai.edges.enums.AAIDirection.NONE;
-import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.not;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.when;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.UUID;
-
-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 org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.javatuples.Pair;
-import org.json.JSONArray;
-import org.json.JSONObject;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.MethodSorters;
-import org.junit.runners.Parameterized;
-import org.mockito.Mockito;
-import org.onap.aai.AAISetup;
-import org.onap.aai.db.props.AAIProperties;
-import org.onap.aai.edges.enums.EdgeField;
-import org.onap.aai.edges.enums.EdgeProperty;
-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.parsers.query.QueryParser;
-import org.onap.aai.rest.db.responses.ErrorResponse;
-import org.onap.aai.rest.db.responses.Relationship;
-import org.onap.aai.rest.db.responses.RelationshipWrapper;
-import org.onap.aai.rest.db.responses.ServiceException;
-import org.onap.aai.rest.ueb.UEBNotification;
+ package org.onap.aai.rest.db;
+
+ import static org.onap.aai.edges.enums.AAIDirection.NONE;
+ import static org.hamcrest.Matchers.containsString;
+ import static org.junit.Assert.assertEquals;
+ import static org.junit.Assert.assertNull;
+ import static org.junit.Assert.assertThat;
+ import static org.junit.Assert.assertTrue;
+ import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+ import static org.mockito.Mockito.verify;
+ import static org.mockito.Mockito.when;
+
+ import java.util.Collections;
+ import com.fasterxml.jackson.core.JsonProcessingException;
+ import com.fasterxml.jackson.databind.JsonMappingException;
+ import com.fasterxml.jackson.databind.ObjectMapper;
+
+ import java.io.UnsupportedEncodingException;
+ import java.net.URI;
+ import java.util.ArrayList;
+ import java.util.Arrays;
+ import java.util.Collection;
+ import java.util.HashSet;
+ import java.util.List;
+ import java.util.Set;
+ import java.util.UUID;
+
+ import jakarta.ws.rs.core.HttpHeaders;
+ import jakarta.ws.rs.core.MediaType;
+ import jakarta.ws.rs.core.MultivaluedHashMap;
+ import jakarta.ws.rs.core.MultivaluedMap;
+ import jakarta.ws.rs.core.Response;
+ import jakarta.ws.rs.core.UriBuilder;
+ import jakarta.ws.rs.core.UriInfo;
+
+ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
+ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+ import org.apache.tinkerpop.gremlin.structure.Edge;
+ import org.apache.tinkerpop.gremlin.structure.Vertex;
+ import org.javatuples.Pair;
+ import org.json.JSONArray;
+ import org.json.JSONObject;
+ import org.junit.After;
+ import org.junit.Before;
+ import org.junit.FixMethodOrder;
+ import org.junit.Test;
+ import org.junit.runner.RunWith;
+ import org.junit.runners.MethodSorters;
+ import org.junit.runners.Parameterized;
+ import org.mockito.Mockito;
+ import org.onap.aai.AAISetup;
+ import org.onap.aai.db.props.AAIProperties;
+ import org.onap.aai.edges.enums.EdgeField;
+ import org.onap.aai.edges.enums.EdgeProperty;
+ import org.onap.aai.exceptions.AAIException;
+ import org.onap.aai.introspection.Introspector;
+ import org.onap.aai.introspection.Loader;
+ import org.onap.aai.parsers.query.QueryParser;
+ import org.onap.aai.prevalidation.ValidationService;
+ import org.onap.aai.query.builder.Pageable;
+ import org.onap.aai.query.builder.QueryOptions;
+ import org.onap.aai.query.builder.Sort;
+ import org.onap.aai.query.builder.Sort.Direction;
+ import org.onap.aai.rest.db.responses.ErrorResponse;
+ import org.onap.aai.rest.db.responses.Relationship;
+ import org.onap.aai.rest.db.responses.RelationshipWrapper;
+ import org.onap.aai.rest.db.responses.ServiceException;
+import org.onap.aai.rest.notification.NotificationService;
import org.onap.aai.restcore.HttpMethod;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import org.onap.aai.util.AAIConfig;
-import org.skyscreamer.jsonassert.JSONAssert;
-import org.skyscreamer.jsonassert.JSONCompareMode;
+ import org.onap.aai.serialization.engines.QueryStyle;
+ import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+ import org.onap.aai.util.AAIConfig;
+ import org.skyscreamer.jsonassert.JSONAssert;
+ import org.skyscreamer.jsonassert.JSONCompareMode;
+ import org.springframework.boot.test.mock.mockito.MockBean;
+ import org.springframework.http.HttpStatus;
-@RunWith(value = Parameterized.class)
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class HttpEntryTest extends AAISetup {
+ @RunWith(value = Parameterized.class)
+ @FixMethodOrder(MethodSorters.NAME_ASCENDING)
+ public class HttpEntryTest extends AAISetup {
- protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
+ @MockBean ValidationService validationService;
+ @MockBean NotificationService notificationService;
- private static final Set<Integer> VALID_HTTP_STATUS_CODES = new HashSet<>();
+ protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
- static {
- VALID_HTTP_STATUS_CODES.add(200);
- VALID_HTTP_STATUS_CODES.add(201);
- VALID_HTTP_STATUS_CODES.add(204);
- }
+ private static final Set<Integer> VALID_HTTP_STATUS_CODES = new HashSet<>();
- @Parameterized.Parameter(value = 0)
- public QueryStyle queryStyle;
+ static {
+ VALID_HTTP_STATUS_CODES.add(200);
+ VALID_HTTP_STATUS_CODES.add(201);
+ VALID_HTTP_STATUS_CODES.add(204);
+ }
- /*
- * TODO Change the HttpEntry instances accoringly
- */
- @Parameterized.Parameters(name = "QueryStyle.{0}")
- public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][] { { QueryStyle.TRAVERSAL }, { QueryStyle.TRAVERSAL_URI } });
- }
-
- private Loader loader;
- private TransactionalGraphEngine dbEngine;
- private GraphTraversalSource traversal;
-
- private HttpHeaders httpHeaders;
-
- private UriInfo uriInfo;
-
- private MultivaluedMap<String, String> headersMultiMap;
- private MultivaluedMap<String, String> queryParameters;
-
- private List<String> aaiRequestContextList;
-
- private List<MediaType> outputMediaTypes;
-
- ObjectMapper mapper = new ObjectMapper();
-
- @Before
- public void setup() {
-
- httpHeaders = Mockito.mock(HttpHeaders.class);
- uriInfo = Mockito.mock(UriInfo.class);
-
- headersMultiMap = new MultivaluedHashMap<>();
- queryParameters = Mockito.spy(new MultivaluedHashMap<>());
-
- headersMultiMap.add("X-FromAppId", "JUNIT");
- headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
- headersMultiMap.add("Real-Time", "true");
- headersMultiMap.add("Accept", "application/json");
- headersMultiMap.add("aai-request-context", "");
-
- outputMediaTypes = new ArrayList<>();
- outputMediaTypes.add(APPLICATION_JSON);
-
- aaiRequestContextList = new ArrayList<>();
- aaiRequestContextList.add("");
-
- traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion());
- loader = traversalHttpEntry.getLoader();
- dbEngine = traversalHttpEntry.getDbEngine();
- traversal = dbEngine.tx().traversal();
-
- when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
- when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
-
- when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
-
- when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
- when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters);
-
- // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be
- // very unreasonable
- Mockito.doReturn(null).when(queryParameters).remove(any());
-
- when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
- }
-
- @After
- public void rollback() {
- dbEngine.rollback();
- }
-
- @Test
- public void thatObjectsCanBeRetrieved() throws UnsupportedEncodingException, AAIException {
- String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
- traversal.addV()
- .property("aai-node-type", "pserver")
- .property("hostname", "theHostname")
- .property("equip-type", "theEquipType")
- .property(AAIProperties.AAI_URI, uri)
- .next();
- String requestBody = new JSONObject()
- .put("hostname", "theHostname")
- .put("equip-type", "theEquipType")
- .toString();
-
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, requestBody);
- assertEquals("Expected the pserver to be returned", 200, response.getStatus());
- }
-
- @Test
- public void thatObjectsCanNotBeFound() throws UnsupportedEncodingException, AAIException {
- String uri = "/cloud-infrastructure/pservers/pserver/junit-test2";
- String requestBody = "";
-
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, requestBody);
- assertEquals("The pserver is not found", 404, response.getStatus());
- }
-
- @Test
- public void thatObjectCanBeCreatedViaPUT() throws UnsupportedEncodingException, AAIException {
- String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
- String requestBody = new JSONObject().put("hostname", "theHostname").toString();
-
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody);
- assertEquals("Expecting the pserver to be created", 201, response.getStatus());
- }
-
- @Test
- public void thatObjectCreationFailsWhenResourceVersionIsProvided()
- throws UnsupportedEncodingException, AAIException, JsonMappingException, JsonProcessingException {
- String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
- String requestBody = new JSONObject()
- .put("hostname", "theHostname")
- .put("resource-version", "123")
- .toString();
-
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody);
- ErrorResponse errorResponseEntity = mapper.readValue(response.getEntity().toString(), ErrorResponse.class);
- assertEquals("Expecting the pserver to be created", 412, response.getStatus());
- assertEquals(
- "Resource version specified on create:resource-version passed for create of /cloud-infrastructure/pservers/pserver/theHostname",
- errorResponseEntity.getRequestError().getServiceException().getVariables().get(2));
- }
-
- @Test
- public void thatObjectCanBeUpdatedViaPUT() throws UnsupportedEncodingException, AAIException {
- String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
- traversal.addV()
- .property("aai-node-type", "pserver")
- .property("hostname", "theHostname")
- .property("number-of-cpus", "10")
- .property(AAIProperties.AAI_URI, uri)
- .property(AAIProperties.RESOURCE_VERSION, "123")
- .next();
- String requestBody = new JSONObject()
- .put("hostname", "updatedHostname")
- .put("resource-version", "123")
- .toString();
-
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody);
- assertEquals("Expecting the pserver to be updated", 200, response.getStatus());
- assertTrue("That old properties are removed",
- traversal.V().has("hostname", "updatedHostname").hasNot("number-of-cpus").hasNext());
- }
-
- @Test
- public void thatUpdateFailsWhenResourceVersionsMismatch()
- throws UnsupportedEncodingException, AAIException, JsonMappingException, JsonProcessingException {
- String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
- traversal.addV()
- .property("aai-node-type", "pserver")
- .property("hostname", "theHostname")
- .property(AAIProperties.AAI_URI, uri)
- .property(AAIProperties.RESOURCE_VERSION, "123")
- .next();
- String requestBody = new JSONObject()
- .put("hostname", "updatedHostname")
- .put("resource-version", "456")
- .toString();
-
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody);
- ErrorResponse errorResponseEntity = mapper.readValue(response.getEntity().toString(), ErrorResponse.class);
- assertEquals("Expecting the update to fail", 412, response.getStatus());
- assertEquals(
- "Precondition Failed:resource-version MISMATCH for update of /cloud-infrastructure/pservers/pserver/updatedHostname",
- errorResponseEntity.getRequestError().getServiceException().getVariables().get(2));
- }
-
- @Test
- public void thatUpdateFailsWhenResourceVersionIsNotProvided()
- throws UnsupportedEncodingException, AAIException, JsonMappingException, JsonProcessingException {
- String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
- traversal.addV()
- .property("aai-node-type", "pserver")
- .property("hostname", "theHostname")
- .property("in-maint", "false")
- .property(AAIProperties.AAI_URI, uri)
- .next();
-
- String requestBody = new JSONObject()
- .put("hostname", "theHostname")
- .put("is-maint", "true")
- .toString();
-
- doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody);
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody);
- ErrorResponse errorResponseEntity = mapper.readValue(response.getEntity().toString(), ErrorResponse.class);
- assertEquals("Request should fail when no resource-version is provided", 412, response.getStatus());
- assertEquals(
- "Precondition Required:resource-version not passed for update of /cloud-infrastructure/pservers/pserver/theHostname",
- errorResponseEntity.getRequestError().getServiceException().getVariables().get(2));
- }
-
- @Test
- public void thatCreateViaPUTAddsRelationshipsToExistingObjects() throws UnsupportedEncodingException, AAIException {
- traversal.addV()
- .property("aai-node-type", "pserver")
- .property("hostname", "hostname")
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/hostname")
- .next();
- String uri = "/cloud-infrastructure/pservers/pserver/hostname/p-interfaces/p-interface/p1";
- String requestBody = new JSONObject().put("interface-name", "p1").toString();
-
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody);
- assertEquals("response is successful", 201, response.getStatus());
- assertTrue("p-interface was created",
- traversal.V().has("aai-node-type", "p-interface").has("interface-name", "p1").hasNext());
- assertTrue("p-interface has outgoing edge to p-server",
- traversal.V().has("aai-node-type", "p-interface").has("aai-uri", uri).has("interface-name", "p1")
- .out("tosca.relationships.network.BindsTo").has("aai-node-type", "pserver")
- .has("hostname", "hostname").hasNext());
- }
-
- @Test
- public void thatObjectsCanBePatched() throws UnsupportedEncodingException, AAIException {
- String uri = "/cloud-infrastructure/pservers/pserver/the-hostname";
- traversal.addV()
- .property("aai-node-type", "pserver")
- .property("hostname", "the-hostname")
- .property("equip-type", "the-equip-type")
- .property(AAIProperties.AAI_URI, uri)
- .next();
- String requestBody = new JSONObject()
- .put("hostname", "new-hostname")
- .toString();
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.MERGE_PATCH, uri, requestBody);
- assertEquals("Expected the pserver to be updated", 200, response.getStatus());
- assertTrue("object should be updated while keeping old properties",
- traversal.V().has("aai-node-type", "pserver").has("hostname", "new-hostname")
- .has("equip-type", "the-equip-type").hasNext());
- }
-
- @Test
- public void thatObjectsCanBeDeleted() throws UnsupportedEncodingException, AAIException {
- String uri = "/cloud-infrastructure/pservers/pserver/the-hostname";
- String resourceVersion = "123";
- traversal.addV()
- .property("aai-node-type", "pserver")
- .property("hostname", "the-hostname")
- .property(AAIProperties.AAI_URI, uri)
- .property(AAIProperties.RESOURCE_VERSION, resourceVersion)
- .next();
- assertEquals("Expecting a No Content response", 204,
- doDelete(resourceVersion, uri, "pserver").getStatus());
- assertTrue("Expecting the pserver to be deleted",
- !traversal.V().has("aai-node-type", "pserver").has("hostname", "the-hostname").hasNext());
- }
-
- @Test
- public void thatRelationshipCanBeCreated() throws UnsupportedEncodingException, AAIException {
- String uri = "/cloud-infrastructure/pservers/pserver/edge-test-pserver";
- traversal.addV()
- .property("aai-node-type", "pserver")
- .property("hostname", "edge-test-pserver")
- .property(AAIProperties.AAI_URI, uri)
- .property(AAIProperties.RESOURCE_VERSION, "123")
- .next();
- uri = "/cloud-infrastructure/complexes/complex/edge-test-complex";
- traversal.addV()
- .property("aai-node-type", "complex")
- .property("physical-location-id", "edge-test-complex")
- .property("physical-location-type", "AAIDefault")
- .property("street1", "AAIDefault")
- .property("city", "AAIDefault")
- .property("postal-code", "07748")
- .property("country", "USA")
- .property("region", "US")
- .property(AAIProperties.AAI_URI, uri)
- .property(AAIProperties.RESOURCE_VERSION, "234")
- .next();
-
- uri = "/cloud-infrastructure/complexes/complex/edge-test-complex/relationship-list/relationship";
- String requestBody = new JSONObject()
- .put("related-to", "pserver")
- .put("related-link",
- String.format("/aai/%s/cloud-infrastructure/pservers/pserver/edge-test-pserver",
- schemaVersions.getDefaultVersion().toString()))
- .put("relationship-label", "org.onap.relationships.inventory.LocatedIn")
- .toString();
-
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, requestBody);
- assertEquals("Expected the pserver relationship to be created", 200, response.getStatus());
- GraphTraversal<Vertex, Vertex> vertexQuery = traversal.V()
- .has("aai-node-type", "complex")
- .has("physical-location-id", "edge-test-complex")
- .in("org.onap.relationships.inventory.LocatedIn")
- .has("aai-node-type", "pserver")
- .has("hostname", "edge-test-pserver");
- GraphTraversal<Edge, Edge> edgeQuery = traversal.E()
- .has(EdgeField.PRIVATE.toString(), "false")
- .has(EdgeProperty.CONTAINS.toString(), NONE.toString())
- .has(EdgeProperty.DELETE_OTHER_V.toString(), NONE.toString())
- .has(EdgeProperty.PREVENT_DELETE.toString(), "IN");
- assertTrue("p-server has incoming edge from complex", vertexQuery.hasNext());
- assertTrue("Created Edge has expected properties", edgeQuery.hasNext());
- }
-
- @Test
- public void thatRelationshipCanNotBeCreatedEdgeMultiplicity()
- throws UnsupportedEncodingException, AAIException, JsonMappingException, JsonProcessingException {
- String uri = "/cloud-infrastructure/pservers/pserver/httpEntryTest-pserver-01";
- traversal
- .addV() // pserver
- .property("aai-node-type", "pserver")
- .property("hostname", "httpEntryTest-pserver-01")
- .property(AAIProperties.AAI_URI, uri)
- .property(AAIProperties.RESOURCE_VERSION, "123")
- .as("v1")
- .addV() // complex
- .property("aai-node-type", "complex")
- .property("physical-location-id", "httpEntryTest-complex-01")
- .property("physical-location-type", "AAIDefault")
- .property("street1", "AAIDefault")
- .property("city", "AAIDefault")
- .property("postal-code", "07748")
- .property("country", "USA")
- .property("region", "US")
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/complexes/complex/httpEntryTest-complex-01")
- .property(AAIProperties.RESOURCE_VERSION, "234")
- .as("v2")
- // edge between pserver and complex
- .addE("org.onap.relationships.inventory.LocatedIn").from("v1").to("v2")
- .next();
-
- // Put Relationship
- uri = "/cloud-infrastructure/pservers/pserver/httpEntryTest-pserver-01/relationship-list/relationship";
- String requestBody = new JSONObject()
- .put("related-to", "complex")
- .put("related-link",
- String.format("/aai/%s/cloud-infrastructure/complexes/complex/httpEntryTest-complex-01",
- schemaVersions.getDefaultVersion().toString()))
- .put("relationship-label", "org.onap.relationships.inventory.LocatedIn")
- .toString();
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, requestBody);
- ServiceException serviceException = mapper.readValue(response.getEntity().toString(), ErrorResponse.class)
- .getRequestError().getServiceException();
-
- assertEquals("Expected the response code to be Bad Request", 400, response.getStatus());
- assertEquals("ERR.5.4.6140", serviceException.getVariables().get(3));
- assertEquals(
- "Edge multiplicity violated:multiplicity rule violated: only one edge can exist with label: org.onap.relationships.inventory.LocatedIn between pserver and complex",
- serviceException.getVariables().get(2));
- }
-
- @Test
- public void putEdgeWrongLabelTest()
- throws UnsupportedEncodingException, AAIException, JsonMappingException, JsonProcessingException {
- String uri = "/cloud-infrastructure/pservers/pserver/edge-test-pserver";
- traversal.addV()
- .property("aai-node-type", "pserver")
- .property("hostname", "edge-test-pserver")
- .property(AAIProperties.AAI_URI, uri)
- .property(AAIProperties.RESOURCE_VERSION, "123")
- .next();
- uri = "/cloud-infrastructure/complexes/complex/edge-test-complex";
- traversal.addV()
- .property("aai-node-type", "complex")
- .property("physical-location-id", "edge-test-complex")
- .property("physical-location-type", "AAIDefault")
- .property("street1", "AAIDefault")
- .property("city", "AAIDefault")
- .property("postal-code", "07748")
- .property("country", "USA")
- .property("region", "US")
- .property(AAIProperties.AAI_URI, uri)
- .property(AAIProperties.RESOURCE_VERSION, "234")
- .next();
-
- uri = "/cloud-infrastructure/complexes/complex/edge-test-complex/relationship-list/relationship";
- String requestBody = new JSONObject()
- .put("related-to", "pserver")
- .put("related-link",
- String.format("/aai/%s/cloud-infrastructure/pservers/pserver/edge-test-pserver",
- schemaVersions.getDefaultVersion().toString()))
- .put("relationship-label", "does.not.exist")
- .toString();
-
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, requestBody);
- ServiceException serviceException = mapper.readValue(response.getEntity().toString(), ErrorResponse.class)
- .getRequestError().getServiceException();
-
- assertEquals("Expected the pserver to be created", 400, response.getStatus());
- assertEquals("ERR.5.4.6107", serviceException.getVariables().get(3));
- assertEquals(
- "Required Edge-property not found in input data:org.onap.aai.edges.exceptions.EdgeRuleNotFoundException: No rule found for EdgeRuleQuery with filter params node type: complex, node type: pserver, label: does.not.exist, type: COUSIN, isPrivate: false.",
- serviceException.getVariables().get(2));
- }
-
- @Test
- public void thatObjectsCanBeRetrievedInPathedResponseFormat() throws UnsupportedEncodingException, AAIException {
- traversal
- .addV() // pserver
- .property("aai-node-type", "pserver")
- .property("hostname", "pserver-1")
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/pserver-1")
- .property(AAIProperties.RESOURCE_VERSION, "123")
- .addV() // pserver
- .property("aai-node-type", "pserver")
- .property("hostname", "pserver-2")
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/pserver-2")
- .property(AAIProperties.RESOURCE_VERSION, "234")
- .next();
-
- queryParameters.add("format", "pathed");
- String requestBody = "";
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET,
- "/cloud-infrastructure/pservers", requestBody);
- queryParameters.remove("format");
-
- String responseEntity = response.getEntity().toString();
- assertEquals("Expected get to succeed", 200, response.getStatus());
- assertThat(responseEntity, containsString("/cloud-infrastructure/pservers/pserver/pserver-1"));
- assertThat(responseEntity, containsString("/cloud-infrastructure/pservers/pserver/pserver-2"));
- }
-
- @Test
- public void thatRelatedObjectsCanBeRetrieved() throws UnsupportedEncodingException, AAIException {
- String uri = "/cloud-infrastructure/pservers/pserver/related-to-pserver";
- traversal
- .addV() // pserver
- .property("aai-node-type", "pserver")
- .property("hostname", "related-to-pserver")
- .property(AAIProperties.AAI_URI, uri)
- .property(AAIProperties.RESOURCE_VERSION, "123")
- .as("v1")
- .addV() // complex
- .property("aai-node-type", "complex")
- .property("physical-location-id", "related-to-complex")
- .property("physical-location-type", "AAIDefault")
- .property("street1", "AAIDefault")
- .property("city", "AAIDefault")
- .property("postal-code", "07748")
- .property("country", "USA")
- .property("region", "US")
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/complexes/complex/related-to-complex")
- .property(AAIProperties.RESOURCE_VERSION, "234")
- .as("v2")
- // edge between pserver and complex
- .addE("org.onap.relationships.inventory.LocatedIn").from("v1").to("v2")
- .next();
-
- uri = "/cloud-infrastructure/complexes/complex/related-to-complex/related-to/pservers";
- String responseBody = "";
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, responseBody);
-
- assertEquals("Expected the response to be successful", 200, response.getStatus());
- assertThat("Related pserver is returned", response.getEntity().toString(),
- containsString("\"hostname\":\"related-to-pserver\""));
-
- }
-
- @Test
- public void getAbstractTest() throws UnsupportedEncodingException, AAIException {
- String uri = "/cloud-infrastructure/pservers/pserver/abstract-pserver";
- traversal
- .addV() // pserver
- .property("aai-node-type", "pserver")
- .property("hostname", "abstract-pserver")
- .property(AAIProperties.AAI_URI, uri)
- .property(AAIProperties.RESOURCE_VERSION, "123")
- .as("v1")
- .addV() // generic-vnf
- .property("aai-node-type", "generic-vnf")
- .property("vnf-id", "abstract-generic-vnf")
- .property("vnf-name", "the-vnf-name")
- .property(AAIProperties.AAI_URI, "/network/generic-vnfs/generic-vnf/abstract-generic-vnf")
- .property(AAIProperties.RESOURCE_VERSION, "234")
- .as("v2")
- // edge between pserver and generic-vnf
- .addE("tosca.relationships.HostedOn").from("v2").to("v1")
- .next();
-
- String requestBody = "";
- uri = "/network/generic-vnfs/generic-vnf/abstract-generic-vnf/related-to/pservers";
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, requestBody);
- assertThat("Related to pserver is returned.", response.getEntity().toString(),
- containsString("\"hostname\":\"abstract-pserver\""));
- }
-
- @Test
- public void getRelationshipListTest()
- throws UnsupportedEncodingException, AAIException, JsonMappingException, JsonProcessingException {
- String uri = "/cloud-infrastructure/pservers/pserver/related-to-pserver";
- traversal
- .addV() // pserver
- .property("aai-node-type", "pserver")
- .property("hostname", "related-to-pserver")
- .property(AAIProperties.AAI_URI, uri)
- .property(AAIProperties.RESOURCE_VERSION, "123")
- .as("v1")
- .addV() // complex
- .property("aai-node-type", "complex")
- .property("physical-location-id", "related-to-complex")
- .property("physical-location-type", "AAIDefault")
- .property("street1", "AAIDefault")
- .property("city", "AAIDefault")
- .property("postal-code", "07748")
- .property("country", "USA")
- .property("region", "US")
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/complexes/complex/related-to-complex")
- .property(AAIProperties.RESOURCE_VERSION, "234")
- .as("v2")
- // edge between pserver and complex
- .addE("org.onap.relationships.inventory.LocatedIn").from("v1").to("v2")
- // these properties are required when finding related edges
- .property(EdgeProperty.CONTAINS.toString(), NONE.toString())
- .property(EdgeField.PRIVATE.toString(), "false")
- .next();
-
- // Get Relationship
- uri = "/cloud-infrastructure/pservers/pserver/related-to-pserver";
- String requestBody = "";
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET_RELATIONSHIP, uri,
- requestBody);
- Relationship[] relationships = mapper.readValue(response.getEntity().toString(), RelationshipWrapper.class)
- .getRelationships();
-
- assertEquals("complex", relationships[0].getRelatedTo());
- assertEquals("org.onap.relationships.inventory.LocatedIn", relationships[0].getRelationshipLabel());
- assertEquals("/aai/v14/cloud-infrastructure/complexes/complex/related-to-complex",
- relationships[0].getRelatedLink());
- assertEquals("complex.physical-location-id", relationships[0].getRelationshipData()[0].getRelationshipKey());
- assertEquals("related-to-complex", relationships[0].getRelationshipData()[0].getRelationshipValue());
- }
-
- @Test
- public void getRelationshipListTestWithFormatSimple() throws UnsupportedEncodingException, AAIException {
- String uri = "/cloud-infrastructure/pservers/pserver/related-to-pserver";
- traversal
- .addV() // pserver
- .property("aai-node-type", "pserver")
- .property("hostname", "related-to-pserver")
- .property(AAIProperties.AAI_URI, uri)
- .property(AAIProperties.RESOURCE_VERSION, "123")
- .as("v1")
- .addV() // complex
- .property("aai-node-type", "complex")
- .property("physical-location-id", "related-to-complex")
- .property("physical-location-type", "AAIDefault")
- .property("street1", "AAIDefault")
- .property("city", "AAIDefault")
- .property("postal-code", "07748")
- .property("country", "USA")
- .property("region", "US")
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/complexes/complex/related-to-complex")
- .property(AAIProperties.RESOURCE_VERSION, "234")
- .as("v2")
- // edge between pserver and complex
- .addE("org.onap.relationships.inventory.LocatedIn").from("v1").to("v2")
- // these properties are required when finding related edges
- .property(EdgeProperty.CONTAINS.toString(), NONE.toString())
- .property(EdgeField.PRIVATE.toString(), "false")
- .next();
-
- // Get Relationship
- uri = "/cloud-infrastructure/pservers/pserver/related-to-pserver";
- queryParameters.add("format", "resource");
- String requestBody = "";
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET_RELATIONSHIP, uri,
- requestBody);
-
- JSONObject actualResponseBody = new JSONObject(response.getEntity().toString());
-
- // Define the expected response
- JSONObject relationshipData = new JSONObject().put("relationship-key", "complex.physical-location-id")
- .put("relationship-value", "related-to-complex");
- JSONObject relationship = new JSONObject()
- .put("related-to", "complex")
- .put("relationship-label", "org.onap.relationships.inventory.LocatedIn")
- .put("related-link",
- String.format("/aai/%s/cloud-infrastructure/complexes/complex/related-to-complex",
- schemaVersions.getDefaultVersion()))
- .put("relationship-data", new JSONArray().put(relationshipData));
- JSONObject pserver = new JSONObject()
- .put("hostname", "related-to-pserver")
- .put("resource-version", "123")
- .put("relationship-list", new JSONObject().put("relationship", new JSONArray().put(relationship)));
- JSONObject expectedResponseBody = new JSONObject()
- .put("results", new JSONArray().put(new JSONObject().put("pserver", pserver)));
-
- JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, JSONCompareMode.NON_EXTENSIBLE);
- queryParameters.remove("format");
- }
-
- @Test
- public void notificationOnRelatedToTest() throws UnsupportedEncodingException, AAIException {
-
- Loader ld = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
- UEBNotification uebNotification = Mockito.spy(new UEBNotification(ld, loaderFactory, schemaVersions));
- traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), uebNotification);
-
- Loader loader = traversalHttpEntry.getLoader();
- TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
- // Put pserver
- String uri = "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver";
- String content = "{\"hostname\":\"junit-edge-test-pserver\"}";
- doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
- // Put complex
- uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex";
- content = "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
- doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
-
- // PutEdge
- uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex/relationship-list/relationship";
- content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + schemaVersions.getDefaultVersion().toString()
- + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\"}";
-
- doNothing().when(uebNotification).triggerEvents();
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, content);
-
- assertEquals("Expected the pserver relationship to be deleted", 200, response.getStatus());
- assertEquals("Two notifications", 2, uebNotification.getEvents().size());
- assertEquals("Notification generated for PUT edge", "UPDATE",
- uebNotification.getEvents().get(0).getEventHeader().getValue("action").toString());
- assertThat("Event body for the edge create has the related to",
- uebNotification.getEvents().get(0).getObj().marshal(false),
- containsString("cloud-infrastructure/pservers/pserver/junit-edge-test-pserver"));
-
- response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.DELETE_EDGE, uri, content);
- assertEquals("Expected the pserver relationship to be deleted", 204, response.getStatus());
- assertEquals("Two notifications", 2, uebNotification.getEvents().size());
- assertEquals("Notification generated for DELETE edge", "UPDATE",
- uebNotification.getEvents().get(0).getEventHeader().getValue("action").toString());
- assertThat("Event body for the edge delete does not have the related to",
- uebNotification.getEvents().get(0).getObj().marshal(false),
- not(containsString("cloud-infrastructure/pservers/pserver/junit-edge-test-pserver")));
- dbEngine.rollback();
-
- }
-
- private Response doRequest(HttpEntry httpEntry, Loader loader, TransactionalGraphEngine dbEngine, HttpMethod method,
- String uri, String requestBody) throws UnsupportedEncodingException, AAIException {
- URI uriObject = UriBuilder.fromPath(uri).build();
- QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
- String objType = uriQuery.getResultType();
- if (uri.endsWith("relationship")) {
- objType = "relationship";
- }
- Introspector obj;
- if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.GET_RELATIONSHIP)) {
- obj = loader.introspectorFromName(objType);
- } else {
- obj = loader.unmarshal(objType, requestBody, org.onap.aai.restcore.MediaType.getEnum("application/json"));
- }
-
- DBRequest dbRequest = new DBRequest.Builder(method, uriObject, uriQuery, obj, httpHeaders, uriInfo,
- "JUNIT-TRANSACTION")
- .rawRequestContent(requestBody).build();
-
- List<DBRequest> dbRequestList = new ArrayList<>();
- dbRequestList.add(dbRequest);
-
- Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = httpEntry.process(dbRequestList, "JUNIT");
- return responsesTuple.getValue1().get(0).getValue1();
- }
-
- private Response doDelete(String resourceVersion, String uri, String nodeType)
- throws UnsupportedEncodingException, AAIException {
- queryParameters.add("resource-version", resourceVersion);
-
- URI uriObject = UriBuilder.fromPath(uri).build();
-
- QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
-
- String content = "";
-
- Introspector obj = loader.introspectorFromName(nodeType);
-
- DBRequest dbRequest = new DBRequest.Builder(HttpMethod.DELETE, uriObject, uriQuery, obj, httpHeaders, uriInfo,
- "JUNIT-TRANSACTION").rawRequestContent(content).build();
-
- Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = traversalHttpEntry.process(Arrays.asList(dbRequest),
- "JUNIT");
- return responsesTuple.getValue1().get(0).getValue1();
- }
-
- @Test
- public void testSetGetPaginationMethods() {
- traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion());
- traversalHttpEntry.setPaginationBucket(10);
- traversalHttpEntry.setPaginationIndex(1);
- traversalHttpEntry.setTotalsForPaging(101, traversalHttpEntry.getPaginationBucket());
- assertEquals("Expected the pagination bucket size to be 10", 10, traversalHttpEntry.getPaginationBucket());
- assertEquals("Expected the total number of pagination buckets to be 11", 11,
- traversalHttpEntry.getTotalPaginationBuckets());
- assertEquals("Expected the pagination index to be 1", 1, traversalHttpEntry.getPaginationIndex());
- assertEquals("Expected the total amount of vertices to be 101", 101, traversalHttpEntry.getTotalVertices());
- }
-
- @Test
- public void setDepthTest() throws AAIException {
- System.setProperty("AJSC_HOME", ".");
- System.setProperty("BUNDLECONFIG_DIR", "src/main/test/resources");
-
- String depthParam = AAIConfig.get("aai.rest.getall.depthparam");
- traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion());
- int depth = traversalHttpEntry.setDepth(null, depthParam);
- assertEquals(AAIProperties.MAXIMUM_DEPTH.intValue(), depth);
- }
-}
+ @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle;
+
+ /*
+ * TODO Change the HttpEntry instances accoringly
+ */
+ @Parameterized.Parameters(name = "QueryStyle.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][] { { QueryStyle.TRAVERSAL }, { QueryStyle.TRAVERSAL_URI } });
+ }
+
+ private Loader loader;
+ private TransactionalGraphEngine dbEngine;
+ private GraphTraversalSource traversal;
+
+ private HttpHeaders httpHeaders;
+
+ private UriInfo uriInfo;
+
+ private MultivaluedMap<String, String> headersMultiMap;
+ private MultivaluedMap<String, String> queryParameters;
+
+ private List<String> aaiRequestContextList;
+
+ private List<MediaType> outputMediaTypes;
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ @Before
+ public void setup() {
+
+ httpHeaders = Mockito.mock(HttpHeaders.class);
+ uriInfo = Mockito.mock(UriInfo.class);
+
+ headersMultiMap = new MultivaluedHashMap<>();
+ queryParameters = Mockito.spy(new MultivaluedHashMap<>());
+
+ headersMultiMap.add("X-FromAppId", "JUNIT");
+ headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
+ headersMultiMap.add("Real-Time", "true");
+ headersMultiMap.add("Accept", "application/json");
+ headersMultiMap.add("aai-request-context", "");
+
+ outputMediaTypes = new ArrayList<>();
+ outputMediaTypes.add(APPLICATION_JSON);
+
+ aaiRequestContextList = new ArrayList<>();
+ aaiRequestContextList.add("");
+
+ traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion());
+ loader = traversalHttpEntry.getLoader();
+ dbEngine = traversalHttpEntry.getDbEngine();
+ traversal = dbEngine.tx().traversal();
+
+ when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
+ when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
+
+ when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
+
+ when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
+ when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters);
+
+ // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be
+ // very unreasonable
+ Mockito.doReturn(null).when(queryParameters).remove(any());
+
+ when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
+ }
+
+ @After
+ public void rollback() {
+ dbEngine.rollback();
+ }
+
+ @Test
+ public void thatObjectCanBeRetrieved() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "theHostname")
+ .property("equip-type", "theEquipType")
+ .property(AAIProperties.AAI_URI, uri)
+ .next();
+
+ JSONObject expectedResponseBody = new JSONObject()
+ .put("hostname", "theHostname")
+ .put("equip-type", "theEquipType");
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri);
+ JSONObject actualResponseBody = new JSONObject(response.getEntity().toString());
+
+ JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, JSONCompareMode.NON_EXTENSIBLE);
+ assertEquals("Expected the pserver to be returned", 200, response.getStatus());
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void thatObjectsCanBeRetrieved() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "theHostname")
+ .property("equip-type", "theEquipType")
+ .property(AAIProperties.AAI_URI, uri)
+ .next();
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "theHostname2")
+ .property("equip-type", "theEquipType2")
+ .property(AAIProperties.AAI_URI, uri + "2")
+ .next();
+
+ JSONObject expectedResponseBody = new JSONObject();
+ JSONObject pserver1 = new JSONObject()
+ .put("hostname", "theHostname")
+ .put("equip-type", "theEquipType");
+ JSONObject pserver2 = new JSONObject()
+ .put("hostname", "theHostname2")
+ .put("equip-type", "theEquipType2");
+ expectedResponseBody.put("pserver", new JSONArray()
+ .put(pserver1)
+ .put(pserver2));
+
+ uri = "/cloud-infrastructure/pservers";
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri);
+ JSONObject actualResponseBody = new JSONObject(response.getEntity().toString());
+
+ JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, JSONCompareMode.NON_EXTENSIBLE);
+ assertEquals("Expected the pservers to be returned", 200, response.getStatus());
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void thatPaginatedObjectsCanBeRetrieved() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "theHostname")
+ .property("equip-type", "theEquipType")
+ .property(AAIProperties.AAI_URI, uri)
+ .next();
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "theHostname2")
+ .property("equip-type", "theEquipType2")
+ .property(AAIProperties.AAI_URI, uri + "2")
+ .next();
+
+ JSONObject expectedResponseBody = new JSONObject();
+ JSONObject pserver1 = new JSONObject()
+ .put("hostname", "theHostname")
+ .put("equip-type", "theEquipType");
+ expectedResponseBody.put("pserver", new JSONArray()
+ .put(pserver1));
+
+ uri = "/cloud-infrastructure/pservers";
+ QueryOptions queryOptions = QueryOptions.builder().pageable(new Pageable(1, 1)).build();
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, queryOptions);
+ JSONObject actualResponseBody = new JSONObject(response.getEntity().toString());
+
+ assertNull(response.getHeaderString("total-results"));
+ assertEquals(1, actualResponseBody.getJSONArray("pserver").length());
+ assertEquals("Expected the pservers to be returned", 200, response.getStatus());
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+
+ queryOptions = QueryOptions.builder().pageable(new Pageable(0,5).includeTotalCount()).build();
+ response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, queryOptions);
+ actualResponseBody = new JSONObject(response.getEntity().toString());
+ assertEquals(2, actualResponseBody.getJSONArray("pserver").length());
+ }
+
+ @Test
+ public void thatPaginationWithNoResultsCanBeRetrieved() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
+
+ uri = "/cloud-infrastructure/pservers";
+ QueryOptions queryOptions = QueryOptions.builder().pageable(new Pageable(0, 1)).build();
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, queryOptions);
+
+ assertTrue(response.getEntity().toString().contains("Node Not Found:No Node of type pserver found at: /cloud-infrastructure/pservers"));
+ assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatus());
+
+ queryOptions = QueryOptions.builder().pageable(new Pageable(0,1).includeTotalCount()).build();
+ response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, queryOptions);
+
+ assertTrue( response.getEntity().toString().contains("Node Not Found:No Node of type pserver found at: /cloud-infrastructure/pservers"));
+ assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatus());
+ verify(notificationService, never()).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+
+ }
+
+ @Test
+ public void thatPagationResultWithTotalCountCanBeRetrieved() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "theHostname")
+ .property("equip-type", "theEquipType")
+ .property(AAIProperties.AAI_URI, uri)
+ .next();
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "theHostname2")
+ .property("equip-type", "theEquipType2")
+ .property(AAIProperties.AAI_URI, uri + "2")
+ .next();
+
+ JSONObject expectedResponseBody = new JSONObject();
+ JSONObject pserver1 = new JSONObject()
+ .put("hostname", "theHostname")
+ .put("equip-type", "theEquipType");
+ expectedResponseBody.put("pserver", new JSONArray()
+ .put(pserver1));
+
+ uri = "/cloud-infrastructure/pservers";
+ QueryOptions queryOptions = QueryOptions.builder().pageable(new Pageable(1, 1).includeTotalCount()).build();
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, queryOptions);
+ JSONObject actualResponseBody = new JSONObject(response.getEntity().toString());
+ String totalCount = response.getHeaderString("total-results");
+ String totalPages = response.getHeaderString("total-pages");
+
+ assertEquals(2, Integer.parseInt(totalCount));
+ assertEquals(2, Integer.parseInt(totalPages));
+ assertEquals(1, actualResponseBody.getJSONArray("pserver").length());
+ assertEquals("Expected the pservers to be returned", 200, response.getStatus());
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+
+ queryOptions = QueryOptions.builder().pageable(new Pageable(0, 2)).build();
+ response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, queryOptions);
+ actualResponseBody = new JSONObject(response.getEntity().toString());
+ assertEquals(2, actualResponseBody.getJSONArray("pserver").length());
+ }
+
+ @Test
+ public void thatSortedObjectsCanBeRetrieved() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "theHostname")
+ .property("equip-type", "theEquipType")
+ .property(AAIProperties.AAI_URI, uri)
+ .next();
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "theHostname2")
+ .property("equip-type", "theEquipType2")
+ .property(AAIProperties.AAI_URI, uri + "2")
+ .next();
+
+ JSONObject expectedResponseBody = new JSONObject();
+ JSONObject pserver1 = new JSONObject()
+ .put("hostname", "theHostname")
+ .put("equip-type", "theEquipType");
+ JSONObject pserver2 = new JSONObject()
+ .put("hostname", "theHostname2")
+ .put("equip-type", "theEquipType2");
+ expectedResponseBody.put("pserver", new JSONArray()
+ .put(pserver1).put(pserver2));
+
+ // ascending
+ uri = "/cloud-infrastructure/pservers";
+ QueryOptions queryOptions = QueryOptions.builder().sort(Sort.builder().property("equip-type").direction(Direction.ASC).build()).build();
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, queryOptions);
+ JSONObject actualResponseBody = new JSONObject(response.getEntity().toString());
+ assertEquals("theEquipType", actualResponseBody.getJSONArray("pserver").getJSONObject(0).getString("equip-type"));
+ assertEquals("theEquipType2", actualResponseBody.getJSONArray("pserver").getJSONObject(1).getString("equip-type"));
+
+ // descending
+ queryOptions = QueryOptions.builder().sort(Sort.builder().property("equip-type").direction(Direction.DESC).build()).build();
+ response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, queryOptions);
+ actualResponseBody = new JSONObject(response.getEntity().toString());
+ assertEquals("theEquipType2", actualResponseBody.getJSONArray("pserver").getJSONObject(0).getString("equip-type"));
+ assertEquals("theEquipType", actualResponseBody.getJSONArray("pserver").getJSONObject(1).getString("equip-type"));
+ }
+
+ @Test
+ public void thatObjectsCanNotBeFound() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/junit-test2";
+
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri);
+ assertEquals("The pserver is not found", 404, response.getStatus());
+ verify(notificationService, never()).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void thatObjectCanBeCreatedViaPUT() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
+ String requestBody = new JSONObject().put("hostname", "theHostname").toString();
+
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody);
+ assertEquals("Expecting the pserver to be created", 201, response.getStatus());
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void thatObjectCreationFailsWhenResourceVersionIsProvided()
+ throws UnsupportedEncodingException, AAIException, JsonMappingException, JsonProcessingException {
+ String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
+ String requestBody = new JSONObject()
+ .put("hostname", "theHostname")
+ .put("resource-version", "123")
+ .toString();
+
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody);
+ ErrorResponse errorResponseEntity = mapper.readValue(response.getEntity().toString(), ErrorResponse.class);
+ assertEquals("Expecting the pserver to be created", 412, response.getStatus());
+ assertEquals(
+ "Resource version specified on create:resource-version passed for create of /cloud-infrastructure/pservers/pserver/theHostname",
+ errorResponseEntity.getRequestError().getServiceException().getVariables().get(2));
+ verify(notificationService, never()).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void thatObjectCanBeUpdatedViaPUT() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "theHostname")
+ .property("number-of-cpus", "10")
+ .property(AAIProperties.AAI_URI, uri)
+ .property(AAIProperties.RESOURCE_VERSION, "123")
+ .next();
+ String requestBody = new JSONObject()
+ .put("hostname", "updatedHostname")
+ .put("resource-version", "123")
+ .toString();
+
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody);
+ assertEquals("Expecting the pserver to be updated", 200, response.getStatus());
+ assertTrue("That old properties are removed",
+ traversal.V().has("hostname", "updatedHostname").hasNot("number-of-cpus").hasNext());
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void thatUpdateFailsWhenResourceVersionsMismatch()
+ throws UnsupportedEncodingException, AAIException, JsonMappingException, JsonProcessingException {
+ String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "theHostname")
+ .property(AAIProperties.AAI_URI, uri)
+ .property(AAIProperties.RESOURCE_VERSION, "123")
+ .next();
+ String requestBody = new JSONObject()
+ .put("hostname", "updatedHostname")
+ .put("resource-version", "456")
+ .toString();
+
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody);
+ ErrorResponse errorResponseEntity = mapper.readValue(response.getEntity().toString(), ErrorResponse.class);
+ assertEquals("Expecting the update to fail", 412, response.getStatus());
+ assertEquals(
+ "Precondition Failed:resource-version MISMATCH for update of /cloud-infrastructure/pservers/pserver/updatedHostname",
+ errorResponseEntity.getRequestError().getServiceException().getVariables().get(2));
+ verify(notificationService, never()).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void thatUpdateFailsWhenResourceVersionIsNotProvided()
+ throws UnsupportedEncodingException, AAIException, JsonMappingException, JsonProcessingException {
+ String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "theHostname")
+ .property("in-maint", "false")
+ .property(AAIProperties.AAI_URI, uri)
+ .next();
+
+ String requestBody = new JSONObject()
+ .put("hostname", "theHostname")
+ .put("is-maint", "true")
+ .toString();
+
+ doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody);
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody);
+ ErrorResponse errorResponseEntity = mapper.readValue(response.getEntity().toString(), ErrorResponse.class);
+ assertEquals("Request should fail when no resource-version is provided", 412, response.getStatus());
+ assertEquals(
+ "Precondition Required:resource-version not passed for update of /cloud-infrastructure/pservers/pserver/theHostname",
+ errorResponseEntity.getRequestError().getServiceException().getVariables().get(2));
+ }
+
+ @Test
+ public void thatCreateViaPUTAddsRelationshipsToExistingObjects() throws UnsupportedEncodingException, AAIException {
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "hostname")
+ .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/hostname")
+ .next();
+ String uri = "/cloud-infrastructure/pservers/pserver/hostname/p-interfaces/p-interface/p1";
+ String requestBody = new JSONObject().put("interface-name", "p1").toString();
+
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody);
+ assertEquals("response is successful", 201, response.getStatus());
+ assertTrue("p-interface was created",
+ traversal.V().has("aai-node-type", "p-interface").has("interface-name", "p1").hasNext());
+ assertTrue("p-interface has outgoing edge to p-server",
+ traversal.V().has("aai-node-type", "p-interface").has("aai-uri", uri).has("interface-name", "p1")
+ .out("tosca.relationships.network.BindsTo").has("aai-node-type", "pserver")
+ .has("hostname", "hostname").hasNext());
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void thatObjectsCanBePatched() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/the-hostname";
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "the-hostname")
+ .property("equip-type", "the-equip-type")
+ .property(AAIProperties.AAI_URI, uri)
+ .next();
+ String requestBody = new JSONObject()
+ .put("hostname", "new-hostname")
+ .toString();
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.MERGE_PATCH, uri, requestBody);
+ assertEquals("Expected the pserver to be updated", 200, response.getStatus());
+ assertTrue("object should be updated while keeping old properties",
+ traversal.V().has("aai-node-type", "pserver").has("hostname", "new-hostname")
+ .has("equip-type", "the-equip-type").hasNext());
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void thatObjectsCanBeDeleted() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/the-hostname";
+ String resourceVersion = "123";
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "the-hostname")
+ .property(AAIProperties.AAI_URI, uri)
+ .property(AAIProperties.RESOURCE_VERSION, resourceVersion)
+ .next();
+ assertEquals("Expecting a No Content response", 204,
+ doDelete(resourceVersion, uri, "pserver").getStatus());
+ assertTrue("Expecting the pserver to be deleted",
+ !traversal.V().has("aai-node-type", "pserver").has("hostname", "the-hostname").hasNext());
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void thatRelationshipCanBeCreated() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/edge-test-pserver";
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "edge-test-pserver")
+ .property(AAIProperties.AAI_URI, uri)
+ .property(AAIProperties.RESOURCE_VERSION, "123")
+ .next();
+ uri = "/cloud-infrastructure/complexes/complex/edge-test-complex";
+ traversal.addV()
+ .property("aai-node-type", "complex")
+ .property("physical-location-id", "edge-test-complex")
+ .property("physical-location-type", "AAIDefault")
+ .property("street1", "AAIDefault")
+ .property("city", "AAIDefault")
+ .property("postal-code", "07748")
+ .property("country", "USA")
+ .property("region", "US")
+ .property(AAIProperties.AAI_URI, uri)
+ .property(AAIProperties.RESOURCE_VERSION, "234")
+ .next();
+
+ uri = "/cloud-infrastructure/complexes/complex/edge-test-complex/relationship-list/relationship";
+ String requestBody = new JSONObject()
+ .put("related-to", "pserver")
+ .put("related-link",
+ String.format("/aai/%s/cloud-infrastructure/pservers/pserver/edge-test-pserver",
+ schemaVersions.getDefaultVersion().toString()))
+ .put("relationship-label", "org.onap.relationships.inventory.LocatedIn")
+ .toString();
+
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, requestBody);
+ assertEquals("Expected the pserver relationship to be created", 200, response.getStatus());
+ GraphTraversal<Vertex, Vertex> vertexQuery = traversal.V()
+ .has("aai-node-type", "complex")
+ .has("physical-location-id", "edge-test-complex")
+ .in("org.onap.relationships.inventory.LocatedIn")
+ .has("aai-node-type", "pserver")
+ .has("hostname", "edge-test-pserver");
+ GraphTraversal<Edge, Edge> edgeQuery = traversal.E()
+ .has(EdgeField.PRIVATE.toString(), "false")
+ .has(EdgeProperty.CONTAINS.toString(), NONE.toString())
+ .has(EdgeProperty.DELETE_OTHER_V.toString(), NONE.toString())
+ .has(EdgeProperty.PREVENT_DELETE.toString(), "IN");
+ assertTrue("p-server has incoming edge from complex", vertexQuery.hasNext());
+ assertTrue("Created Edge has expected properties", edgeQuery.hasNext());
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void thatRelationshipCanNotBeCreatedEdgeMultiplicity()
+ throws UnsupportedEncodingException, AAIException, JsonMappingException, JsonProcessingException {
+ String uri = "/cloud-infrastructure/pservers/pserver/httpEntryTest-pserver-01";
+ traversal
+ .addV() // pserver
+ .property("aai-node-type", "pserver")
+ .property("hostname", "httpEntryTest-pserver-01")
+ .property(AAIProperties.AAI_URI, uri)
+ .property(AAIProperties.RESOURCE_VERSION, "123")
+ .as("v1")
+ .addV() // complex
+ .property("aai-node-type", "complex")
+ .property("physical-location-id", "httpEntryTest-complex-01")
+ .property("physical-location-type", "AAIDefault")
+ .property("street1", "AAIDefault")
+ .property("city", "AAIDefault")
+ .property("postal-code", "07748")
+ .property("country", "USA")
+ .property("region", "US")
+ .property(AAIProperties.AAI_URI, "/cloud-infrastructure/complexes/complex/httpEntryTest-complex-01")
+ .property(AAIProperties.RESOURCE_VERSION, "234")
+ .as("v2")
+ // edge between pserver and complex
+ .addE("org.onap.relationships.inventory.LocatedIn").from("v1").to("v2")
+ .next();
+
+ // Put Relationship
+ uri = "/cloud-infrastructure/pservers/pserver/httpEntryTest-pserver-01/relationship-list/relationship";
+ String requestBody = new JSONObject()
+ .put("related-to", "complex")
+ .put("related-link",
+ String.format("/aai/%s/cloud-infrastructure/complexes/complex/httpEntryTest-complex-01",
+ schemaVersions.getDefaultVersion().toString()))
+ .put("relationship-label", "org.onap.relationships.inventory.LocatedIn")
+ .toString();
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, requestBody);
+ ServiceException serviceException = mapper.readValue(response.getEntity().toString(), ErrorResponse.class)
+ .getRequestError().getServiceException();
+
+ assertEquals("Expected the response code to be Bad Request", 400, response.getStatus());
+ assertEquals("ERR.5.4.6140", serviceException.getVariables().get(3));
+ assertEquals(
+ "Edge multiplicity violated:multiplicity rule violated: only one edge can exist with label: org.onap.relationships.inventory.LocatedIn between pserver and complex",
+ serviceException.getVariables().get(2));
+ }
+
+ @Test
+ public void putEdgeWrongLabelTest()
+ throws UnsupportedEncodingException, AAIException, JsonMappingException, JsonProcessingException {
+ String uri = "/cloud-infrastructure/pservers/pserver/edge-test-pserver";
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "edge-test-pserver")
+ .property(AAIProperties.AAI_URI, uri)
+ .property(AAIProperties.RESOURCE_VERSION, "123")
+ .next();
+ uri = "/cloud-infrastructure/complexes/complex/edge-test-complex";
+ traversal.addV()
+ .property("aai-node-type", "complex")
+ .property("physical-location-id", "edge-test-complex")
+ .property("physical-location-type", "AAIDefault")
+ .property("street1", "AAIDefault")
+ .property("city", "AAIDefault")
+ .property("postal-code", "07748")
+ .property("country", "USA")
+ .property("region", "US")
+ .property(AAIProperties.AAI_URI, uri)
+ .property(AAIProperties.RESOURCE_VERSION, "234")
+ .next();
+
+ uri = "/cloud-infrastructure/complexes/complex/edge-test-complex/relationship-list/relationship";
+ String requestBody = new JSONObject()
+ .put("related-to", "pserver")
+ .put("related-link",
+ String.format("/aai/%s/cloud-infrastructure/pservers/pserver/edge-test-pserver",
+ schemaVersions.getDefaultVersion().toString()))
+ .put("relationship-label", "does.not.exist")
+ .toString();
+
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, requestBody);
+ ServiceException serviceException = mapper.readValue(response.getEntity().toString(), ErrorResponse.class)
+ .getRequestError().getServiceException();
+
+ assertEquals("Expected the pserver to be created", 400, response.getStatus());
+ assertEquals("ERR.5.4.6107", serviceException.getVariables().get(3));
+ assertEquals(
+ "Required Edge-property not found in input data:org.onap.aai.edges.exceptions.EdgeRuleNotFoundException: No rule found for EdgeRuleQuery with filter params node type: complex, node type: pserver, label: does.not.exist, type: COUSIN, isPrivate: false.",
+ serviceException.getVariables().get(2));
+ }
+
+ @Test
+ public void thatObjectsCanBeRetrievedInPathedResponseFormat() throws UnsupportedEncodingException, AAIException {
+ traversal
+ .addV() // pserver
+ .property("aai-node-type", "pserver")
+ .property("hostname", "pserver-1")
+ .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/pserver-1")
+ .property(AAIProperties.RESOURCE_VERSION, "123")
+ .addV() // pserver
+ .property("aai-node-type", "pserver")
+ .property("hostname", "pserver-2")
+ .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/pserver-2")
+ .property(AAIProperties.RESOURCE_VERSION, "234")
+ .next();
+
+ queryParameters.add("format", "pathed");
+ String requestBody = "";
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET,
+ "/cloud-infrastructure/pservers");
+ queryParameters.remove("format");
+
+ String responseEntity = response.getEntity().toString();
+ assertEquals("Expected get to succeed", 200, response.getStatus());
+ assertThat(responseEntity, containsString("/cloud-infrastructure/pservers/pserver/pserver-1"));
+ assertThat(responseEntity, containsString("/cloud-infrastructure/pservers/pserver/pserver-2"));
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void thatRelatedObjectsCanBeRetrieved() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/related-to-pserver";
+ traversal
+ .addV() // pserver
+ .property("aai-node-type", "pserver")
+ .property("hostname", "related-to-pserver")
+ .property(AAIProperties.AAI_URI, uri)
+ .property(AAIProperties.RESOURCE_VERSION, "123")
+ .as("v1")
+ .addV() // complex
+ .property("aai-node-type", "complex")
+ .property("physical-location-id", "related-to-complex")
+ .property("physical-location-type", "AAIDefault")
+ .property("street1", "AAIDefault")
+ .property("city", "AAIDefault")
+ .property("postal-code", "07748")
+ .property("country", "USA")
+ .property("region", "US")
+ .property(AAIProperties.AAI_URI, "/cloud-infrastructure/complexes/complex/related-to-complex")
+ .property(AAIProperties.RESOURCE_VERSION, "234")
+ .as("v2")
+ // edge between pserver and complex
+ .addE("org.onap.relationships.inventory.LocatedIn").from("v1").to("v2")
+ .next();
+
+ uri = "/cloud-infrastructure/complexes/complex/related-to-complex/related-to/pservers";
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri);
+
+ assertEquals("Expected the response to be successful", 200, response.getStatus());
+ assertThat("Related pserver is returned", response.getEntity().toString(),
+ containsString("\"hostname\":\"related-to-pserver\""));
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+
+ }
+
+ @Test
+ public void getAbstractTest() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/abstract-pserver";
+ traversal
+ .addV() // pserver
+ .property("aai-node-type", "pserver")
+ .property("hostname", "abstract-pserver")
+ .property(AAIProperties.AAI_URI, uri)
+ .property(AAIProperties.RESOURCE_VERSION, "123")
+ .as("v1")
+ .addV() // generic-vnf
+ .property("aai-node-type", "generic-vnf")
+ .property("vnf-id", "abstract-generic-vnf")
+ .property("vnf-name", "the-vnf-name")
+ .property(AAIProperties.AAI_URI, "/network/generic-vnfs/generic-vnf/abstract-generic-vnf")
+ .property(AAIProperties.RESOURCE_VERSION, "234")
+ .as("v2")
+ // edge between pserver and generic-vnf
+ .addE("tosca.relationships.HostedOn").from("v2").to("v1")
+ .next();
+
+ uri = "/network/generic-vnfs/generic-vnf/abstract-generic-vnf/related-to/pservers";
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri);
+ assertThat("Related to pserver is returned.", response.getEntity().toString(),
+ containsString("\"hostname\":\"abstract-pserver\""));
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void getRelationshipListTest()
+ throws UnsupportedEncodingException, AAIException, JsonMappingException, JsonProcessingException {
+ String uri = "/cloud-infrastructure/pservers/pserver/related-to-pserver";
+ traversal
+ .addV() // pserver
+ .property("aai-node-type", "pserver")
+ .property("hostname", "related-to-pserver")
+ .property(AAIProperties.AAI_URI, uri)
+ .property(AAIProperties.RESOURCE_VERSION, "123")
+ .as("v1")
+ .addV() // complex
+ .property("aai-node-type", "complex")
+ .property("physical-location-id", "related-to-complex")
+ .property("physical-location-type", "AAIDefault")
+ .property("street1", "AAIDefault")
+ .property("city", "AAIDefault")
+ .property("postal-code", "07748")
+ .property("country", "USA")
+ .property("region", "US")
+ .property(AAIProperties.AAI_URI, "/cloud-infrastructure/complexes/complex/related-to-complex")
+ .property(AAIProperties.RESOURCE_VERSION, "234")
+ .as("v2")
+ // edge between pserver and complex
+ .addE("org.onap.relationships.inventory.LocatedIn").from("v1").to("v2")
+ // these properties are required when finding related edges
+ .property(EdgeProperty.CONTAINS.toString(), NONE.toString())
+ .property(EdgeField.PRIVATE.toString(), "false")
+ .next();
+
+ // Get Relationship
+ uri = "/cloud-infrastructure/pservers/pserver/related-to-pserver";
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET_RELATIONSHIP, uri);
+ Relationship[] relationships = mapper.readValue(response.getEntity().toString(), RelationshipWrapper.class)
+ .getRelationships();
+
+ assertEquals("complex", relationships[0].getRelatedTo());
+ assertEquals("org.onap.relationships.inventory.LocatedIn", relationships[0].getRelationshipLabel());
+ assertEquals("/aai/v14/cloud-infrastructure/complexes/complex/related-to-complex",
+ relationships[0].getRelatedLink());
+ assertEquals("complex.physical-location-id", relationships[0].getRelationshipData()[0].getRelationshipKey());
+ assertEquals("related-to-complex", relationships[0].getRelationshipData()[0].getRelationshipValue());
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void getRelationshipListTestWithFormatSimple() throws UnsupportedEncodingException, AAIException {
+ String uri = "/cloud-infrastructure/pservers/pserver/related-to-pserver";
+ traversal
+ .addV() // pserver
+ .property("aai-node-type", "pserver")
+ .property("hostname", "related-to-pserver")
+ .property(AAIProperties.AAI_URI, uri)
+ .property(AAIProperties.RESOURCE_VERSION, "123")
+ .as("v1")
+ .addV() // complex
+ .property("aai-node-type", "complex")
+ .property("physical-location-id", "related-to-complex")
+ .property("physical-location-type", "AAIDefault")
+ .property("street1", "AAIDefault")
+ .property("city", "AAIDefault")
+ .property("postal-code", "07748")
+ .property("country", "USA")
+ .property("region", "US")
+ .property(AAIProperties.AAI_URI, "/cloud-infrastructure/complexes/complex/related-to-complex")
+ .property(AAIProperties.RESOURCE_VERSION, "234")
+ .as("v2")
+ // edge between pserver and complex
+ .addE("org.onap.relationships.inventory.LocatedIn").from("v1").to("v2")
+ // these properties are required when finding related edges
+ .property(EdgeProperty.CONTAINS.toString(), NONE.toString())
+ .property(EdgeField.PRIVATE.toString(), "false")
+ .next();
+
+ // Get Relationship
+ uri = "/cloud-infrastructure/pservers/pserver/related-to-pserver";
+ queryParameters.add("format", "resource");
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET_RELATIONSHIP, uri);
+
+ JSONObject actualResponseBody = new JSONObject(response.getEntity().toString());
+
+ // Define the expected response
+ JSONObject relationshipData = new JSONObject().put("relationship-key", "complex.physical-location-id")
+ .put("relationship-value", "related-to-complex");
+ JSONObject relationship = new JSONObject()
+ .put("related-to", "complex")
+ .put("relationship-label", "org.onap.relationships.inventory.LocatedIn")
+ .put("related-link",
+ String.format("/aai/%s/cloud-infrastructure/complexes/complex/related-to-complex",
+ schemaVersions.getDefaultVersion()))
+ .put("relationship-data", new JSONArray().put(relationshipData));
+ JSONObject pserver = new JSONObject()
+ .put("hostname", "related-to-pserver")
+ .put("resource-version", "123")
+ .put("relationship-list", new JSONObject().put("relationship", new JSONArray().put(relationship)));
+ JSONObject expectedResponseBody = new JSONObject()
+ .put("results", new JSONArray().put(new JSONObject().put("pserver", pserver)));
+
+ JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, JSONCompareMode.NON_EXTENSIBLE);
+ queryParameters.remove("format");
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+
+ private Response doRequest(HttpEntry httpEntry, Loader loader, TransactionalGraphEngine dbEngine, HttpMethod method,
+ String uri) throws UnsupportedEncodingException, AAIException {
+ return doRequest(httpEntry, loader, dbEngine, method, uri, null, null);
+ }
+
+ private Response doRequest(HttpEntry httpEntry, Loader loader, TransactionalGraphEngine dbEngine, HttpMethod method,
+ String uri, String requestBody) throws UnsupportedEncodingException, AAIException {
+ return doRequest(httpEntry, loader, dbEngine, method, uri, requestBody, null);
+ }
+ private Response doRequest(HttpEntry httpEntry, Loader loader, TransactionalGraphEngine dbEngine, HttpMethod method,
+ String uri, QueryOptions queryOptions) throws UnsupportedEncodingException, AAIException {
+ return doRequest(httpEntry, loader, dbEngine, method, uri, null, queryOptions);
+ }
+
+ private Response doRequest(HttpEntry httpEntry, Loader loader, TransactionalGraphEngine dbEngine, HttpMethod method,
+ String uri, String requestBody, QueryOptions queryOptions) throws UnsupportedEncodingException, AAIException {
+ URI uriObject = UriBuilder.fromPath(uri).build();
+ QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
+ String objType;
+ if (!uriQuery.getContainerType().equals("")) {
+ objType = uriQuery.getContainerType();
+ } else {
+ objType = uriQuery.getResultType();
+ }
+ if (uri.endsWith("relationship")) {
+ objType = "relationship";
+ }
+ Introspector obj;
+ if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.GET_RELATIONSHIP)) {
+ obj = loader.introspectorFromName(objType);
+ } else {
+ obj = loader.unmarshal(objType, requestBody, org.onap.aai.restcore.MediaType.getEnum("application/json"));
+ }
+
+ DBRequest.Builder builder = new DBRequest.Builder(method, uriObject, uriQuery, obj, httpHeaders, uriInfo,
+ "JUNIT-TRANSACTION");
+ DBRequest dbRequest = requestBody != null
+ ? builder.rawRequestContent(requestBody).build()
+ : builder.build();
+
+ List<DBRequest> dbRequestList = Collections.singletonList(dbRequest);
+
+ Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = httpEntry.process(dbRequestList, "JUNIT", Collections.emptySet(), true, queryOptions);
+ return responsesTuple.getValue1().get(0).getValue1();
+ }
+
+ private Response doDelete(String resourceVersion, String uri, String nodeType)
+ throws UnsupportedEncodingException, AAIException {
+ queryParameters.add("resource-version", resourceVersion);
+
+ URI uriObject = UriBuilder.fromPath(uri).build();
+
+ QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
+
+ String content = "";
+
+ Introspector obj = loader.introspectorFromName(nodeType);
+
+ DBRequest dbRequest = new DBRequest.Builder(HttpMethod.DELETE, uriObject, uriQuery, obj, httpHeaders, uriInfo,
+ "JUNIT-TRANSACTION").rawRequestContent(content).build();
+
+ Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = traversalHttpEntry.process(Arrays.asList(dbRequest),
+ "JUNIT");
+ return responsesTuple.getValue1().get(0).getValue1();
+ }
+
+ @Test
+ public void setDepthTest() throws AAIException {
+ System.setProperty("AJSC_HOME", ".");
+ System.setProperty("BUNDLECONFIG_DIR", "src/main/test/resources");
+
+ String depthParam = AAIConfig.get("aai.rest.getall.depthparam");
+ traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion());
+ int depth = traversalHttpEntry.setDepth(null, depthParam);
+ assertEquals(AAIProperties.MAXIMUM_DEPTH.intValue(), depth);
+ }
+
+ @Test
+ public void thatEventsAreValidated() throws AAIException, UnsupportedEncodingException {
+ String uri = "/cloud-infrastructure/pservers/pserver/theHostname";
+ traversal.addV()
+ .property("aai-node-type", "pserver")
+ .property("hostname", "theHostname")
+ .property("equip-type", "theEquipType")
+ .property(AAIProperties.AAI_URI, uri)
+ .next();
+
+ JSONObject expectedResponseBody = new JSONObject()
+ .put("hostname", "theHostname")
+ .put("equip-type", "theEquipType");
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri);
+ JSONObject actualResponseBody = new JSONObject(response.getEntity().toString());
+
+ JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, JSONCompareMode.NON_EXTENSIBLE);
+ assertEquals("Expected the pserver to be returned", 200, response.getStatus());
+ verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any());
+ }
+ }
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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.rest.db;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.UriBuilder;
+import jakarta.ws.rs.core.UriInfo;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.janusgraph.core.JanusGraphException;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.onap.aai.AAISetup;
+import org.onap.aai.config.SpringContextAware;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.parsers.query.QueryParser;
+import org.onap.aai.restcore.HttpMethod;
+import org.onap.aai.restcore.MediaType;
+import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+
+import lombok.SneakyThrows;
+
+public class HttpEntryTransactionTest extends AAISetup {
+
+ @Mock UriInfo uriInfoMock;
+ @Mock MultivaluedMap<String, String> queryParamsMock;
+ @Mock HttpHeaders headersMock;
+
+ @Before
+ public void setup() {
+ when(uriInfoMock.getQueryParameters(anyBoolean())).thenReturn(queryParamsMock);
+ when(queryParamsMock.getFirst("depth")).thenReturn("0");
+ when(headersMock.getRequestHeader("aai-request-context")).thenReturn(null);
+ }
+
+ @Test
+ public void thatDBRequestsAreWritten() throws AAIException, UnsupportedEncodingException {
+ HttpEntry httpEntry = SpringContextAware.getBean("requestScopedTraversalUriHttpEntry", HttpEntry.class);
+ httpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion());
+ TransactionalGraphEngine dbEngine = httpEntry.getDbEngine();
+ Loader loader = httpEntry.getLoader();
+
+ List<String> hostnames = Arrays.asList("test1", "test2", "test3");
+ List<DBRequest> dbRequests = createDbRequests(dbEngine, loader, hostnames);
+
+ httpEntry.process(dbRequests, SERVICE_NAME);
+
+ GraphTraversalSource source = dbEngine.startTransaction().traversal();
+ Long pserverCount = source.V().has("aai-node-type","pserver").count().next();
+ assertEquals(3, pserverCount.intValue());
+ }
+
+ @Test
+ // same test, only that JanusgraphException is thrown
+ public void thatDBRequestsAreRolledBack() throws AAIException, UnsupportedEncodingException {
+ HttpEntry httpEntry = SpringContextAware.getBean("requestScopedTraversalUriHttpEntry", HttpEntry.class);
+ httpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion());
+ TransactionalGraphEngine dbEngine = httpEntry.getDbEngine();
+ Loader loader = httpEntry.getLoader();
+
+ List<String> hostnames = Arrays.asList("test1", "test2", "test3");
+ List<DBRequest> dbRequests = createDbRequests(dbEngine, loader, hostnames);
+
+ DBRequest request2Spy = spy(dbRequests.get(1));
+ QueryParser uriQuerySpy = spy(dbRequests.get(1).getParser());
+ when(request2Spy.getParser()).thenReturn(uriQuerySpy);
+ dbRequests.set(1, request2Spy);
+ when(uriQuerySpy.getQueryBuilder()).thenThrow(new JanusGraphException(""));
+
+ httpEntry.process(dbRequests, SERVICE_NAME);
+
+ GraphTraversalSource source = dbEngine.startTransaction().traversal();
+ Long pserverCount = source.V().has("aai-node-type","pserver").count().next();
+ assertEquals(0, pserverCount.intValue());
+ }
+
+ @SneakyThrows
+ private List<DBRequest> createDbRequests(TransactionalGraphEngine dbEngine, Loader loader, List<String> hostnames) {
+ List<DBRequest> dbRequests = new ArrayList<>();
+
+ for(String hostname: hostnames) {
+ URI uriObject = UriBuilder.fromPath("/cloud-infrastructure/pservers/pserver/" + hostname).build();
+ QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
+ String content = "{\"hostname\":\"" + hostname + "\"}";
+ Introspector obj = loader.unmarshal(uriQuery.getResultType(), content,MediaType.APPLICATION_JSON_TYPE);
+ DBRequest request = new DBRequest.Builder(HttpMethod.PUT, uriObject, uriQuery, obj, headersMock, uriInfoMock, "someTransaction")
+ .rawRequestContent(content).build();
+ dbRequests.add(request);
+ }
+
+ return dbRequests;
+ }
+}
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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.rest.notification;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.exceptions.AAIUnmarshallingException;
+import org.onap.aai.parsers.uri.URIToObject;
+import org.onap.aai.setup.SchemaVersion;
+
+public class EntityConverterTest {
+
+ @Mock URIToObject parser;
+ @Mock Introspector introspector;
+ @Mock Loader loader;
+ @Mock List<Object> parentList;
+
+ EntityConverter entityConverter;
+
+ @BeforeEach
+ public void setUp() {
+ MockitoAnnotations.openMocks(this);
+ entityConverter = new EntityConverter(parser);
+ }
+
+ @Test
+ public void testConvert_topEntitySameAsEntity() throws AAIUnmarshallingException {
+ when(parser.getParentList()).thenReturn(parentList);
+ when(parser.getTopEntity()).thenReturn(introspector);
+ when(parser.getEntity()).thenReturn(introspector);
+
+ Introspector result = entityConverter.convert(introspector);
+
+ assertEquals(introspector, result);
+ verify(parser.getParentList()).clear();
+ }
+
+ @Test
+ public void testConvert_topEntityDifferentFromEntity_withVersionMismatch() throws AAIUnmarshallingException {
+ Introspector topEntity = mock(Introspector.class);
+ Introspector childEntity = mock(Introspector.class);
+ String json = "{}";
+
+ when(parser.getParentList()).thenReturn(parentList);
+ when(parser.getTopEntity()).thenReturn(topEntity);
+ when(parser.getEntity()).thenReturn(childEntity);
+ when(childEntity.getName()).thenReturn("smth");
+ when(parser.getLoader()).thenReturn(loader);
+ when(introspector.getVersion()).thenReturn(new SchemaVersion("v1"));
+ when(loader.getVersion()).thenReturn(new SchemaVersion("v2"));
+ when(introspector.marshal(false)).thenReturn(json);
+ when(loader.unmarshal(anyString(), eq(json))).thenReturn(childEntity);
+
+ Introspector result = entityConverter.convert(introspector);
+
+ assertEquals(topEntity, result);
+ }
+
+ @Test
+ public void testConvert_topEntityDifferentFromEntity_withoutVersionMismatch() throws AAIUnmarshallingException {
+ Introspector topEntity = mock(Introspector.class);
+ Introspector childEntity = mock(Introspector.class);
+
+ when(parser.getParentList()).thenReturn(parentList);
+ when(parser.getTopEntity()).thenReturn(topEntity);
+ when(parser.getEntity()).thenReturn(childEntity);
+ when(parser.getLoader()).thenReturn(loader);
+ when(introspector.getVersion()).thenReturn(new SchemaVersion("v1"));
+ when(loader.getVersion()).thenReturn(new SchemaVersion("v1"));
+
+ Introspector result = entityConverter.convert(introspector);
+
+ assertEquals(topEntity, result);
+ verify(parentList).add(any());
+ }
+
+ @Test
+ public void testGetTopEntityName() {
+ String topEntityName = "TopEntity";
+ when(parser.getTopEntityName()).thenReturn(topEntityName);
+
+ String result = entityConverter.getTopEntityName();
+
+ assertEquals(topEntityName, result);
+ }
+}
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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.rest.notification;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import jakarta.ws.rs.core.Response.Status;
+
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex;
+import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertexProperty;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aai.AAISetup;
+import org.onap.aai.db.props.AAIProperties;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.LoaderFactory;
+import org.onap.aai.kafka.NotificationProducerService;
+import org.onap.aai.prevalidation.ValidationService;
+import org.onap.aai.serialization.db.DBSerializer;
+import org.onap.aai.serialization.engines.query.QueryEngine;
+import org.onap.aai.setup.SchemaVersion;
+import org.onap.aai.setup.SchemaVersions;
+
+public class NotificationServiceTest extends AAISetup {
+
+ @Mock LoaderFactory loaderFactory;
+ @Mock SchemaVersions schemaVersions;
+ @Mock UEBNotification uebNotification;
+ @Mock ValidationService validationService;
+ @Mock NotificationProducerService notificationProducerService;
+ @Mock DBSerializer dbSerializer;
+ @Mock QueryEngine queryEngine;
+ @Mock Introspector introspector;
+
+ boolean isDeltaEventsEnabled = false;
+ String basePath = "/aai";
+ NotificationService notificationService;
+
+ @Before
+ public void setup() throws UnsupportedEncodingException, AAIException {
+ MockitoAnnotations.openMocks(this);
+
+ when(dbSerializer.touchStandardVertexPropertiesForEdges()).thenReturn(Collections.emptySet());
+ when(dbSerializer.getLatestVersionView(any(),anyInt())).thenReturn(introspector);
+
+ notificationService = new NotificationService(validationService, loaderFactory, basePath, isDeltaEventsEnabled, notificationProducerService);
+ when(schemaVersions.getDefaultVersion()).thenReturn(new SchemaVersion("v29"));
+ doNothing().when(uebNotification).createNotificationEvent(any(),any(),any(),any(),any(),any(),any());
+ doNothing().when(notificationProducerService).sendUEBNotification(any());
+ }
+
+ @Test
+ public void thatNotificationsCanBeCreatedWithoutEdges() throws AAIException, UnsupportedEncodingException {
+
+ Map<String, Object> properties = new HashMap<>();
+ properties.put(AAIProperties.NODE_TYPE, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "pserver", new HashMap<>())));
+ properties.put(AAIProperties.AAI_URI, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "/pservers/pserver/hostname", new HashMap<>())));
+ properties.put(AAIProperties.CREATED_TS, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "12", new HashMap<>())));
+ properties.put(AAIProperties.LAST_MOD_TS, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "34", new HashMap<>())));
+
+ Vertex vertex = new DetachedVertex("1","label", properties);
+ Set<Vertex> mainVertexesToNotifyOn = new HashSet<>();
+ mainVertexesToNotifyOn.add(vertex);
+ SchemaVersion schemaVersion = new SchemaVersion("v29");
+ when(dbSerializer.getUpdatedVertexes()).thenReturn(Collections.emptyMap());
+
+ notificationService.generateEvents(uebNotification, AAIProperties.MINIMUM_DEPTH, "sourceOfTruth", dbSerializer, "transactionId", queryEngine, mainVertexesToNotifyOn, schemaVersion);
+
+ verify(uebNotification, times(1)).createNotificationEvent(eq("transactionId"), eq("sourceOfTruth"), eq(Status.OK), eq(URI.create("/aai/v29/pservers/pserver/hostname")), eq(introspector), any(), eq("/aai"));
+ verify(validationService, times(1)).validate(anyList());
+ verify(notificationProducerService, times(1)).sendUEBNotification(uebNotification);
+ }
+
+ @Test
+ public void thatValidationCanBeDisabled() throws AAIException, UnsupportedEncodingException {
+
+ Map<String, Object> properties = new HashMap<>();
+ properties.put(AAIProperties.NODE_TYPE, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "pserver", new HashMap<>())));
+ properties.put(AAIProperties.AAI_URI, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "/pservers/pserver/hostname", new HashMap<>())));
+ properties.put(AAIProperties.CREATED_TS, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "12", new HashMap<>())));
+ properties.put(AAIProperties.LAST_MOD_TS, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "34", new HashMap<>())));
+
+ Vertex vertex = new DetachedVertex("1","label", properties);
+ Set<Vertex> mainVertexesToNotifyOn = new HashSet<>();
+ mainVertexesToNotifyOn.add(vertex);
+ SchemaVersion schemaVersion = new SchemaVersion("v29");
+ when(dbSerializer.getUpdatedVertexes()).thenReturn(Collections.emptyMap());
+
+ notificationService = new NotificationService(null, loaderFactory, basePath, isDeltaEventsEnabled, notificationProducerService);
+ notificationService.generateEvents(uebNotification, AAIProperties.MINIMUM_DEPTH, "sourceOfTruth", dbSerializer, "transactionId", queryEngine, mainVertexesToNotifyOn, schemaVersion);
+
+ verify(notificationProducerService, times(1)).sendUEBNotification(uebNotification);
+ }
+}
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.rest.ueb;
+package org.onap.aai.rest.notification;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.UUID;
-import javax.ws.rs.core.Response;
+import jakarta.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;
Introspector pserver = loader.introspectorFromName("pserver");
pserver.setValue("hostname", "hn");
URI uri = new URI("/cloud-infrastructure/pservers/pserver/hn");
- UEBNotification uebNotification = new UEBNotification(loader, loaderFactory, schemaVersions);
+ UEBNotification uebNotification = new UEBNotification(loaderFactory, schemaVersions);
uebNotification.createNotificationEvent(UUID.randomUUID().toString(), "JUNIT-SOT", Response.Status.CREATED, uri,
pserver, new HashMap<>(), BASE_PATH);
assertEquals("One event created", 1, uebNotification.getEvents().size());
assertEquals("Uri is correct",
BASE_PATH + "/" + schemaVersions.getDefaultVersion() + "/cloud-infrastructure/pservers/pserver/hn",
- uebNotification.getEvents().get(0).getEventHeader().getValue("entity-link").toString());
+ uebNotification.getEvents().get(0).getEventHeader().getEntityLink());
}
@Test
Introspector pserver = loader.introspectorFromName("pserver");
pserver.setValue("hostname", "hn");
URI uri = new URI(BASE_PATH + "/v12/cloud-infrastructure/pservers/pserver/hn");
- UEBNotification uebNotification = new UEBNotification(loader, loaderFactory, schemaVersions);
+ UEBNotification uebNotification = new UEBNotification(loaderFactory, schemaVersions);
uebNotification.createNotificationEvent(UUID.randomUUID().toString(), "JUNIT-SOT", Response.Status.CREATED, uri,
pserver, new HashMap<>(), BASE_PATH);
assertEquals("One event created", 1, uebNotification.getEvents().size());
assertEquals("Uri is correct",
BASE_PATH + "/" + schemaVersions.getDefaultVersion() + "/cloud-infrastructure/pservers/pserver/hn",
- uebNotification.getEvents().get(0).getEventHeader().getValue("entity-link").toString());
+ uebNotification.getEvents().get(0).getEventHeader().getEntityLink());
}
}
import java.util.List;
import java.util.concurrent.Callable;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.UriInfo;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.onap.aai.config.ConfigConfiguration;
import org.onap.aai.config.IntrospectionConfig;
+import org.onap.aai.config.KafkaConfig;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.config.XmlFormatTransformerConfiguration;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.introspection.ModelType;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.parsers.query.QueryParser;
+import org.onap.aai.rest.notification.NotificationService;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
@ContextConfiguration(
classes = {ConfigConfiguration.class, AAICoreFakeEdgesConfigTranslator.class, NodeIngestor.class,
EdgeIngestor.class, EdgeSerializer.class, SpringContextAware.class, IntrospectionConfig.class,
- XmlFormatTransformerConfiguration.class})
+ XmlFormatTransformerConfiguration.class, LoaderFactory.class, NotificationService.class,
+ KafkaConfig.class})
@TestPropertySource(
properties = {"schema.translator.list = config", "schema.nodes.location=src/test/resources/onap/oxm",
- "schema.edges.location=src/test/resources/onap/dbedgerules"})
+ "schema.edges.location=src/test/resources/onap/dbedgerules","aai.notifications.enabled=false"})
public class DbSerializer_needsFakeRulesTest {
// to use, set thrown.expect to whatever your test needs
graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
- QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"),
- "src/test/resources/bundleconfig-local/etc/oxm/");
}
import com.google.common.collect.Multimap;
-import java.util.*;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.junit.Rule;
/**
* convenience helper method to make it easier to check the contents of the tree against
* a list of expected results
- *
+ *
* @param tree - the tree whose contents you want in collection form
* @return set of the contents of the tree
*/
package org.onap.aai.serialization.engines.query;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
package org.onap.aai.serialization.queryformats;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
import org.junit.Rule;
import org.junit.Test;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-
import java.io.UnsupportedEncodingException;
-import javax.ws.rs.core.MultivaluedHashMap;
-
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+
+import jakarta.ws.rs.core.MultivaluedHashMap;
+
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class MultiFormatTest extends AAISetup {
when(urlBuilder.pathed(pserver)).thenReturn("/aai/v14/cloud-infrastructure/pservers/pserver/hostname-1");
Optional<JsonObject> jsonObjectOptional = pathedURL.getJsonFromVertex(pserver);
- if (!jsonObjectOptional.isPresent()) {
+ if (jsonObjectOptional.isEmpty()) {
fail("Expecting an json object returned from pathed url but returned none");
}
when(urlBuilder.pathed(pserver)).thenReturn("/aai/v14/cloud-infrastructure/pservers/pserver/hostname-1");
Optional<JsonObject> jsonObjectOptional = pathedURL.getJsonFromVertex(pserver);
- if (!jsonObjectOptional.isPresent()) {
+ if (jsonObjectOptional.isEmpty()) {
fail("Expecting an json object returned from pathed url but returned none");
}
return graph;
}
- public static void setFinalStatic(Field field, Object newValue) throws Exception {
- field.setAccessible(true);
- // remove final modifier from field
- Field modifiersField = Field.class.getDeclaredField("modifiers");
- modifiersField.setAccessible(true);
- modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
- field.set(null, newValue);
- }
-
}
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
-import com.google.gson.JsonObject;
-
import java.util.Arrays;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
import org.springframework.test.annotation.DirtiesContext;
+import com.google.gson.JsonObject;
+
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
+
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class ResourceFormatTest extends AAISetup {
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
-import com.google.gson.JsonObject;
-
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
import org.springframework.test.annotation.DirtiesContext;
+import com.google.gson.JsonObject;
+
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
+
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class SimpleFormatTest extends AAISetup {
import static org.junit.Assert.assertEquals;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.queryformats.Resource.Builder;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
+
@RunWith(MockitoJUnitRunner.class)
public class QueryParamInjectorTest {
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2024 Deutsche Telekom. 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.util;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.onap.aai.IntegrationTest;
+import org.onap.aai.JanusgraphCassandraConfiguration;
+import org.onap.aai.config.GraphConfig;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Import;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.springframework.test.context.DynamicPropertySource;
+import org.testcontainers.cassandra.CassandraContainer;
+import org.testcontainers.containers.Network;
+import org.testcontainers.containers.ToxiproxyContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+import eu.rekawek.toxiproxy.Proxy;
+import eu.rekawek.toxiproxy.ToxiproxyClient;
+import eu.rekawek.toxiproxy.model.ToxicDirection;
+
+@Testcontainers
+@Import(JanusgraphCassandraConfiguration.class)
+@ContextConfiguration(classes = {
+ GraphConfig.class, GraphChecker.class
+})
+public class GraphCheckerResiliencyTest extends IntegrationTest {
+
+ private static final Network network = Network.newNetwork();
+
+ @Container
+ private static final CassandraContainer cassandraContainer = new CassandraContainer("cassandra:4.0.5")
+ .withExposedPorts(9042)
+ .withNetwork(network)
+ .withNetworkAliases("cassandra");
+
+
+ @Container
+ private static final ToxiproxyContainer toxiproxy = new ToxiproxyContainer("ghcr.io/shopify/toxiproxy:2.5.0")
+ .withNetwork(network);
+
+ private static Proxy cassandraProxy;
+
+ @Autowired
+ GraphChecker graphChecker;
+
+ @Autowired
+ GraphTraversalSource g;
+
+ @DynamicPropertySource
+ static void setProperties(DynamicPropertyRegistry registry) throws IOException {
+ registry.add("testcontainers.cassandra.host", () -> toxiproxy.getHost());
+ registry.add("testcontainers.cassandra.port", () -> toxiproxy.getMappedPort(8666));
+
+ var toxiproxyClient = new ToxiproxyClient(toxiproxy.getHost(), toxiproxy.getControlPort());
+
+ cassandraProxy = toxiproxyClient.createProxy("cassandra", "0.0.0.0:8666", "cassandra:9042");
+
+ }
+
+ @BeforeEach
+ void resetProxy() throws IOException {
+ for(var toxic: cassandraProxy.toxics().getAll()) {
+ toxic.remove();
+ }
+ }
+
+ @Test
+ public void test() {
+ boolean available = graphChecker.isAaiGraphDbAvailable();
+ assertTrue(available);
+ }
+
+ @Test
+ public void testConnectionFailure() throws IOException {
+ assertTrue(graphChecker.isAaiGraphDbAvailable());
+
+ cassandraProxy.toxics().bandwidth("no-connection-up", ToxicDirection.UPSTREAM, 0);
+ cassandraProxy.toxics().bandwidth("no-connection-down", ToxicDirection.DOWNSTREAM, 0);
+ assertFalse(graphChecker.isAaiGraphDbAvailable());
+
+ // boolean available = graphChecker.isAaiGraphDbAvailable();
+ // // g.addV().property("foo","bar").next();
+ // // boolean exists = g.V().has("foo","bar").hasNext();
+ // assertFalse(available);
+ }
+
+ @AfterAll
+ public static void tearDown() {
+ cassandraContainer.stop();
+ }
+}
--- /dev/null
+package org.onap.aai.util;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
+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.JanusGraphException;
+import org.janusgraph.core.JanusGraphTransaction;
+import org.janusgraph.core.TransactionBuilder;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.onap.aai.AAISetup;
+import org.onap.aai.config.GraphConfig;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestPropertySource;
+
+
+@RunWith(MockitoJUnitRunner.class)
+@ContextConfiguration(classes = {GraphConfig.class, GraphChecker.class})
+@TestPropertySource(value = "classpath:/application.properties")
+public class GraphCheckerTest extends AAISetup {
+
+ @Mock TransactionBuilder transactionBuilder;
+ @Mock JanusGraphTransaction transaction;
+ @Mock GraphTraversalSource traversalSource;
+ @Mock GraphTraversal<Vertex, Vertex> traversal;
+ @MockBean JanusGraph graph;
+ @Autowired GraphChecker graphChecker;
+
+ @Before
+ public void setup() {
+ mockGraphTransaction();
+ mockTraversal();
+ }
+
+ @Test
+ public void thatAvailabilityCanBeTrue() {
+ when(traversal.hasNext()).thenReturn(true);
+ boolean available = graphChecker.isAaiGraphDbAvailable();
+ assertTrue(available);
+ }
+
+ @Test
+ public void thatEmptyDBQueryIsInterpretedAsAvailable() {
+ when(traversal.hasNext()).thenReturn(false);
+ boolean available = graphChecker.isAaiGraphDbAvailable();
+ assertTrue(available);
+ }
+
+ @Test
+ public void thatExceptionWillReturnAvailabilityFalse() {
+ when(traversal.hasNext()).thenThrow(JanusGraphException.class);
+ boolean available = graphChecker.isAaiGraphDbAvailable();
+ assertFalse(available);
+ }
+
+ private void mockTraversal() {
+ when(transaction.traversal()).thenReturn(traversalSource);
+ when(traversalSource.V()).thenReturn(traversal);
+ when(traversal.limit(1)).thenReturn(traversal);
+ }
+
+ private void mockGraphTransaction() {
+ when(graph.buildTransaction()).thenReturn(transactionBuilder);
+ when(transactionBuilder.readOnly()).thenReturn(transactionBuilder);
+ when(transactionBuilder.consistencyChecks(false)).thenReturn(transactionBuilder);
+ when(transactionBuilder.vertexCacheSize(0)).thenReturn(transactionBuilder);
+ when(transactionBuilder.skipDBCacheRead()).thenReturn(transactionBuilder);
+ when(transactionBuilder.start()).thenReturn(transaction);
+ }
+}
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import com.google.common.collect.ImmutableListMultimap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Multimap;
-
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.LinkedHashMap;
import java.util.List;
-import javax.xml.bind.JAXBException;
-
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.JAXBContext;
import org.eclipse.persistence.jaxb.JAXBMarshaller;
import org.mockito.Mockito;
import org.onap.aai.domain.notificationEvent.NotificationEvent;
+import com.google.common.collect.ImmutableListMultimap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Multimap;
+
+import jakarta.xml.bind.JAXBException;
+
public class PojoUtilsTest {
private PojoUtils pojoUtils;
LocalDateTime date = LocalDateTime.of(2017, Month.SEPTEMBER, 18, 10, 55, 0, 300);
String res = pojoUtils.getJsonFromObject(date);
-
+ assertEquals("\"2017-09-18T10:55:00.0000003\"", res);
assertNotNull(res);
- assertTrue(res.contains("\"dayOfMonth\" : 18"));
- assertTrue(res.contains("\"dayOfWeek\" : \"MONDAY\""));
- assertTrue(res.contains("\"dayOfYear\" : 261"));
- assertTrue(res.contains("\"hour\" : 10"));
- assertTrue(res.contains("\"minute\" : 55"));
- assertTrue(res.contains("\"month\" : \"SEPTEMBER\""));
- assertTrue(res.contains("\"monthValue\" : 9"));
- assertTrue(res.contains("\"nano\" : 300"));
- assertTrue(res.contains("\"second\" : 0"));
- assertTrue(res.contains("\"year\" : 2017"));
}
@Test
+++ /dev/null
-/**
- * ============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.util;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import com.fasterxml.jackson.core.JsonGenerationException;
-import com.fasterxml.jackson.databind.JsonMappingException;
-
-import java.io.IOException;
-
-import javax.json.Json;
-import javax.json.JsonObject;
-
-import org.eclipse.persistence.dynamic.DynamicEntity;
-import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.onap.aai.AAISetup;
-import org.onap.aai.domain.notificationEvent.NotificationEvent.EventHeader;
-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.kafka.AAIKafkaEventJMSProducer;
-
-public class StoreNotificationEventTest extends AAISetup {
-
- private static AAIKafkaEventJMSProducer producer;
- private static StoreNotificationEvent sne;
-
- @BeforeClass
- public static void setUp() {
- producer = Mockito.mock(AAIKafkaEventJMSProducer.class);
- // sne = new StoreNotificationEvent(producer, "transiationId", "sourceOfTruth");
- }
-
- @Before
- public void setUpBefore() {
- producer = Mockito.mock(AAIKafkaEventJMSProducer.class);
- sne = new StoreNotificationEvent(producer, "transiationId", "sourceOfTruth");
-
- }
-
- @Test(expected = AAIException.class)
- public void testStoreEventNullObj() throws AAIException {
- sne.storeEventAndSendToJms(new EventHeader(), null);
- }
-
- @Test(expected = AAIException.class)
- public void testStoreEventInvalidObjForPojoUtils() throws AAIException {
- sne.storeEventAndSendToJms(new EventHeader(), new Object());
- }
-
- @Test
- public void testStoreEventEmptyEventHeader()
- throws AAIException, JsonGenerationException, JsonMappingException, IOException {
- JsonObject object = Json.createObjectBuilder().add("hello", "world").build();
- String res = sne.storeEventAndSendToJms(new EventHeader(), object);
-
- assertNotNull(res);
- assertTrue(res.contains("\"cambria.partition\" : \"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\""));
- assertTrue(res.contains("\"event-header\""));
- assertTrue(res.contains("\"id\""));
- assertTrue(res.contains("\"timestamp\""));
- assertTrue(res
- .contains("\"source-name\" : \"" + AAIConfig.get("aai.notificationEvent.default.sourceName") + "\""));
- assertTrue(res.contains("\"domain\" : \"" + AAIConfig.get("aai.notificationEvent.default.domain") + "\""));
- assertTrue(res.contains(
- "\"sequence-number\" : \"" + AAIConfig.get("aai.notificationEvent.default.sequenceNumber") + "\""));
- assertTrue(res.contains("\"severity\" : \"" + AAIConfig.get("aai.notificationEvent.default.severity") + "\""));
- assertTrue(
- res.contains("\"event-type\" : \"" + AAIConfig.get("aai.notificationEvent.default.eventType") + "\""));
- assertTrue(res.contains("\"version\" : \"" + AAIConfig.get("aai.notificationEvent.default.version") + "\""));
- assertTrue(res.contains("\"action\" : \"UNK\""));
- assertTrue(res.contains("\"entity-link\" : \"UNK\""));
- assertTrue(res.contains("\"entity\""));
- assertTrue(res.contains("\"hello\""));
- assertTrue(res.contains("\"chars\" : \"world\""));
- assertTrue(res.contains("\"string\" : \"world\""));
- assertTrue(res.contains("\"valueType\" : \"STRING\""));
- }
-
- @Test
- public void testStoreEvent() throws AAIException, JsonGenerationException, JsonMappingException, IOException {
- JsonObject object = Json.createObjectBuilder().add("hello", "world").build();
- EventHeader eh = new EventHeader();
- eh.setId("123");
- eh.setTimestamp("current-time");
- eh.setEntityLink("entity-link");
- eh.setAction("action!");
- eh.setEventType("surprise");
- eh.setDomain("PROD");
- eh.setSourceName("source");
- eh.setSequenceNumber("23");
- eh.setSeverity("ALERT");
- eh.setVersion("v12");
-
- String res = sne.storeEventAndSendToJms(eh, object);
-
- assertNotNull(res);
- assertTrue(res.contains("\"cambria.partition\" : \"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\""));
- assertTrue(res.contains("\"event-header\""));
- assertTrue(res.contains("\"id\" : \"123\""));
- assertTrue(res.contains("\"timestamp\" : \"current-time\""));
- assertTrue(res.contains("\"source-name\" : \"source\""));
- assertTrue(res.contains("\"domain\" : \"PROD\""));
- assertTrue(res.contains("\"sequence-number\" : \"23\""));
- assertTrue(res.contains("\"severity\" : \"ALERT\""));
- assertTrue(res.contains("\"event-type\" : \"surprise\""));
- assertTrue(res.contains("\"version\" : \"v12\""));
- assertTrue(res.contains("\"action\" : \"action!\""));
- assertTrue(res.contains("\"entity-link\" : \"entity-link\""));
- assertTrue(res.contains("\"entity\""));
- assertTrue(res.contains("\"hello\""));
- assertTrue(res.contains("\"chars\" : \"world\""));
- assertTrue(res.contains("\"string\" : \"world\""));
- assertTrue(res.contains("\"valueType\" : \"STRING\""));
- }
-
- @Test(expected = AAIException.class)
- public void testStoreDynamicEventNullObj() throws AAIException {
- DynamicEntity eventHeader = Mockito.mock(DynamicEntity.class);
- DynamicJAXBContext notificationJaxbContext =
- nodeIngestor.getContextForVersion(schemaVersions.getEdgeLabelVersion());
- sne.storeDynamicEvent(notificationJaxbContext, "v12", eventHeader, null);
- }
-
- @Test(expected = Exception.class)
- public void testStoreDynamicEventAAIException() throws Exception {
-
- DynamicJAXBContext notificationJaxbContext =
- nodeIngestor.getContextForVersion(schemaVersions.getEdgeLabelVersion());
- DynamicEntity obj = Mockito.mock(DynamicEntity.class);
- DynamicEntity eventHeader = Mockito.mock(DynamicEntity.class);
- sne.storeDynamicEvent(notificationJaxbContext, "v12", eventHeader, obj);
- }
-
- @Test(expected = AAIException.class)
- public void testStoreEventIntrospectorNullObj() throws Exception {
- Loader loader = Mockito.mock(Loader.class);
- sne.storeEventAndSendToJms(loader, null, null);
- }
-
- @Ignore("Stopped working since the model driven story")
- @Test
- public void testStoreEvent1Introspector() throws Exception {
- Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getEdgeLabelVersion());
- Introspector eventHeader = loader.introspectorFromName("notification-event-header");
- eventHeader.setValue("id", "123");
- eventHeader.setValue("timestamp", "current-time");
- eventHeader.setValue("entity-link", "entity-link");
- eventHeader.setValue("action", "action!");
- eventHeader.setValue("event-type", "surprise");
- eventHeader.setValue("domain", "PROD");
- eventHeader.setValue("source-name", "source");
- eventHeader.setValue("sequence-number", "23");
- eventHeader.setValue("severity", "ALERT");
- eventHeader.setValue("version", "v12");
- Introspector obj = loader.introspectorFromName("notification-event");
- String res = sne.storeEventAndSendToJms(loader, eventHeader, obj);
-
- assertNotNull(res);
- assertTrue(res.contains("\"cambria.partition\":\"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\""));
- assertTrue(res.contains("\"event-header\""));
- assertTrue(res.contains("\"id\":\"123\""));
- assertTrue(res.contains("\"timestamp\":\"current-time\""));
- assertTrue(res.contains("\"source-name\":\"source\""));
- assertTrue(res.contains("\"domain\":\"PROD\""));
- assertTrue(res.contains("\"sequence-number\":\"23\""));
- assertTrue(res.contains("\"severity\":\"ALERT\""));
- assertTrue(res.contains("\"event-type\":\"surprise\""));
- assertTrue(res.contains("\"version\":\"v12\""));
- assertTrue(res.contains("\"action\":\"action!\""));
- assertTrue(res.contains("\"entity-link\":\"entity-link\""));
- assertTrue(res.contains("\"notification-event\""));
- }
-
- @Ignore("Stopped working since the model driven story")
- @Test
- public void testStoreEventIntrospectorEmptyEventHeader() throws Exception {
- Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getEdgeLabelVersion());
- Introspector eventHeader = loader.introspectorFromName("notification-event-header");
- Introspector obj = loader.introspectorFromName("notification-event");
-
- String res = sne.storeEventAndSendToJms(loader, eventHeader, obj);
-
- assertNotNull(res);
- assertTrue(res.contains("\"cambria.partition\":\"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\""));
- assertTrue(res.contains("\"event-header\""));
- assertTrue(res.contains("\"id\""));
- assertTrue(res.contains("\"timestamp\""));
- assertTrue(
- res.contains("\"source-name\":\"" + AAIConfig.get("aai.notificationEvent.default.sourceName") + "\""));
- assertTrue(res.contains("\"domain\":\"" + AAIConfig.get("aai.notificationEvent.default.domain") + "\""));
- assertTrue(res.contains(
- "\"sequence-number\":\"" + AAIConfig.get("aai.notificationEvent.default.sequenceNumber") + "\""));
- assertTrue(res.contains("\"severity\":\"" + AAIConfig.get("aai.notificationEvent.default.severity") + "\""));
- assertTrue(res.contains("\"event-type\":\"" + AAIConfig.get("aai.notificationEvent.default.eventType") + "\""));
- assertTrue(res.contains("\"version\":\"" + AAIConfig.get("aai.notificationEvent.default.version") + "\""));
- assertTrue(res.contains("\"action\":\"UNK\""));
- assertTrue(res.contains("\"entity-link\":\"UNK\""));
- assertTrue(res.contains("\"notification-event\""));
- }
-}
--- /dev/null
+aai.graph.properties.path=src/test/resources/bundleconfig-local/etc/appprops/janusgraph-realtime.properties
+++ /dev/null
-## Location properties
-##
-## Localized Machine Information
-##
-cadi_loglevel=DEBUG
-cadi_latitude=38.0
-cadi_longitude=-72.0
-
-# Locate URL (which AAF Env) - Use lower case
-aaf_locate_url=https://aafist.test.org:8095
-# AAF URL - Use upper case
-aaf_url=https://AAF_LOCATE_URL/service:2.0
-#
-cadi_prop_files=src/test/resources/bundleconfig-local/aaf/org.onap.aai.props
+++ /dev/null
-cm_url=cm_url
-hostname=hostname
-aaf_env=IST
-cadi_x509_issuers=CN=AAF CADI Test Issuing CA 01, OU=CSO, O=CO, C=US:CN=AAF CADI Test Issuing CA 02, OU=CSO, O=CO, C=US
\ No newline at end of file
aai.realtime.clients=RO,SDNC,SO
-aai.jms.enable=false
-
aai.rest.getall.depthparam=someuuid
aaf.valid.issuer.wildcard=aaf wild card issuer|aafWildCardIssuer|OU=another
+++ /dev/null
-#
-# ============LICENSE_START=======================================================
-# org.onap.aai
-# ================================================================================
-# Copyright © 2017-18 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=========================================================
-
-query.fast-property=true
-query.smart-limit=false
-# the following parameters are not reloaded automatically and require a manual bounce
-storage.backend=inmemory
-storage.hostname=localhost
-
-#schema.default=none
-storage.lock.wait-time=300
-storage.hbase.table=aaigraph-dev1.dev
-storage.hbase.ext.zookeeper.znode.parent=/hbase-unsecure
-#caching on
-cache.db-cache = true
-cache.db-cache-clean-wait = 20
-cache.db-cache-time = 180000
-cache.db-cache-size = 0.3
-
-#load graphson file on startup
-load.snapshot.file=false
<pattern>${eelfTransLogPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asynctranslog" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>1000</queueSize>
<includeCallerData>true</includeCallerData>
<logger name="ajsc.UserDefinedBeansDefService" level="WARN" />
<logger name="ajsc.LoggingConfigurationService" level="WARN" />
- <!-- AJSC related loggers (DME2 Registration, csi logging, restlet, servlet
+ <!-- AJSC related loggers (DME2 Registration, csi logging, restlet, servlet
logging) -->
<logger name="org.codehaus.groovy" level="WARN" />
<logger name="com.att.scamper" level="WARN" />
<logger name="org.apache.coyote" level="WARN" />
<logger name="org.apache.jasper" level="WARN" />
- <!-- Camel Related Loggers (including restlet/servlet/jaxrs/cxf logging.
+ <!-- Camel Related Loggers (including restlet/servlet/jaxrs/cxf logging.
May aid in troubleshooting) -->
<logger name="org.apache.camel" level="WARN" />
<logger name="org.apache.cxf" level="WARN" />
</logger>
<logger name="org.onap.aai.kafka" level="DEBUG" additivity="false">
- <appender-ref ref="kafkaAAIEventConsumer" />
- <appender-ref ref="kafkaAAIEventConsumerDebug" />
- <appender-ref ref="kafkaAAIEventConsumerMetric" />
+ <appender-ref ref="STDOUT" />
</logger>
<logger name="org.apache" level="WARN" />
--- /dev/null
+{
+ "cambria.partition": "AAI",
+ "event-header": {
+ "severity": "NORMAL",
+ "entity-type": "object-group",
+ "top-entity-type": "object-group",
+ "entity-link": "/aai/v28/common/object-groups/object-group/ric_cluster",
+ "event-type": "AAI-EVENT",
+ "domain": "dev",
+ "action": "UPDATE",
+ "sequence-number": "0",
+ "id": "23f12123-c326-48a7-b57e-e48746c295ea",
+ "source-name": "postman-api",
+ "version": "v28",
+ "timestamp": "20231207-12:14:44:757"
+ },
+ "entity": {
+ "relationship-list": {
+ "relationship": [
+ {
+ "related-to": "cell",
+ "relationship-data": [
+ {
+ "relationship-value": "445611193273958916",
+ "relationship-key": "cell.cell-id"
+ }
+ ],
+ "related-link": "/aai/v28/network/cells/cell/445611193273958916",
+ "relationship-label": "org.onap.relationships.inventory.MemberOf",
+ "related-to-property": [
+ {
+ "property-key": "cell.cell-name",
+ "property-value": "MY6885_M-Schwere-Reiter-Str-440460_GU2_84079913"
+ }
+ ]
+ },
+ {
+ "related-to": "cell",
+ "relationship-data": [
+ {
+ "relationship-value": "445611193272330241",
+ "relationship-key": "cell.cell-id"
+ }
+ ],
+ "related-link": "/aai/v28/network/cells/cell/445611193272330241",
+ "relationship-label": "org.onap.relationships.inventory.MemberOf",
+ "related-to-property": [
+ {
+ "property-key": "cell.cell-name",
+ "property-value": "MY6885_M-Schwere-Reiter-Str-440460_GTC2_84003803"
+ }
+ ]
+ }
+ ]
+ },
+ "group-name": "Urban",
+ "resource-version": "1701951284582",
+ "group-type": "cell",
+ "object-group-id": "ric_cluster"
+ }
+}
--- /dev/null
+{
+ "cambria.partition": "AAI",
+ "event-header": {
+ "severity": "NORMAL",
+ "entity-type": "pserver",
+ "top-entity-type": "pserver",
+ "entity-link": "/aai/v14/cloud-infrastructure/pservers/pserver/pserver1",
+ "event-type": "AAI-EVENT",
+ "domain": "devINT1",
+ "action": "CREATE",
+ "sequence-number": "0",
+ "id": "someTransaction",
+ "source-name": "test",
+ "version": "v14",
+ },
+ "entity": {
+ "ptnii-equip-name": "example-ptnii-equip-name-val-36969",
+ "ipaddress-v6-loopback-0": "example-ipaddress-v6-loopback0-val-17856",
+ "equip-vendor": "example-equip-vendor-val-37452",
+ "purpose": "example-purpose-val-90218",
+ "pserver-selflink": "example-pserver-selflink-val-10125",
+ "number-of-cpus": 62220,
+ "ipaddress-v6-aim": "example-ipaddress-v6-aim-val-6210",
+ "pserver-name2": "example-pserver-name2-val-53802",
+ "hostname": "pserver1",
+ "inv-status": "example-inv-status-val-3682",
+ "disk-in-gigabytes": 872,
+ "equip-type": "example-equip-type-val-22986",
+ "fqdn": "example-fqdn-val-33429",
+ "serial-number": "example-serial-number-val-12010",
+ "ipaddress-v6-oam": "example-ipaddress-v6-oam-val-40977",
+ "pserver-id": "example-pserver-id-val-82142",
+ "prov-status": "example-prov-status-val-11642",
+ "ipv4-oam-address": "example-ipv4-oam-address-val-3155",
+ "ipaddress-v4-loopback-0": "example-ipaddress-v4-loopback0-val-77686",
+ "equip-model": "example-equip-model-val-14665",
+ "in-maint": true,
+ "ram-in-megabytes": 35331,
+ "ipaddress-v4-aim": "example-ipaddress-v4-aim-val-33665",
+ "management-option": "example-management-option-val-91111",
+ "internet-topology": "example-internet-topology-val-56425",
+ "host-profile": "example-host-profile-val-36247"
+ }
+}
{
- "event-topic": "AAI-EVENT",
- "aaiEventPayload": {
- "cambria.partition": "AAI",
- "event-header": {
- "severity": "NORMAL",
- "entity-type": "object-group",
- "top-entity-type": "object-group",
- "entity-link": "/aai/v28/common/object-groups/object-group/ric_cluster",
- "event-type": "AAI-EVENT",
- "domain": "dev",
- "action": "UPDATE",
- "sequence-number": "0",
- "id": "23f12123-c326-48a7-b57e-e48746c295ea",
- "source-name": "postman-api",
- "version": "v28",
- "timestamp": "20231207-12:14:44:757"
+ "cambria.partition": "AAI",
+ "event-header": {
+ "severity": "NORMAL",
+ "entity-type": "object-group",
+ "top-entity-type": "object-group",
+ "entity-link": "/aai/v28/common/object-groups/object-group/ric_cluster",
+ "event-type": "AAI-EVENT",
+ "domain": "dev",
+ "action": "UPDATE",
+ "sequence-number": "0",
+ "id": "23f12123-c326-48a7-b57e-e48746c295ea",
+ "source-name": "postman-api",
+ "version": "v28",
+ "timestamp": "20231207-12:14:44:757"
+ },
+ "entity": {
+ "relationship-list": {
+ "relationship": [
+ {
+ "related-to": "cell",
+ "relationship-data": [
+ {
+ "relationship-value": "445611193273958916",
+ "relationship-key": "cell.cell-id"
+ }
+ ],
+ "related-link": "/aai/v28/network/cells/cell/445611193273958916",
+ "relationship-label": "org.onap.relationships.inventory.MemberOf",
+ "related-to-property": [
+ {
+ "property-key": "cell.cell-name",
+ "property-value": "MY6885_M-Schwere-Reiter-Str-440460_GU2_84079913"
+ }
+ ]
+ },
+ {
+ "related-to": "cell",
+ "relationship-data": [
+ {
+ "relationship-value": "445611193272330241",
+ "relationship-key": "cell.cell-id"
+ }
+ ],
+ "related-link": "/aai/v28/network/cells/cell/445611193272330241",
+ "relationship-label": "org.onap.relationships.inventory.MemberOf",
+ "related-to-property": [
+ {
+ "property-key": "cell.cell-name",
+ "property-value": "MY6885_M-Schwere-Reiter-Str-440460_GTC2_84003803"
+ }
+ ]
+ }
+ ]
},
- "entity": {
- "relationship-list": {
- "relationship": [
- {
- "related-to": "cell",
- "relationship-data": [
- {
- "relationship-value": "445611193273958916",
- "relationship-key": "cell.cell-id"
- }
- ],
- "related-link": "/aai/v28/network/cells/cell/445611193273958916",
- "relationship-label": "org.onap.relationships.inventory.MemberOf",
- "related-to-property": [
- {
- "property-key": "cell.cell-name",
- "property-value": "MY6885_M-Schwere-Reiter-Str-440460_GU2_84079913"
- }
- ]
- },
- {
- "related-to": "cell",
- "relationship-data": [
- {
- "relationship-value": "445611193272330241",
- "relationship-key": "cell.cell-id"
- }
- ],
- "related-link": "/aai/v28/network/cells/cell/445611193272330241",
- "relationship-label": "org.onap.relationships.inventory.MemberOf",
- "related-to-property": [
- {
- "property-key": "cell.cell-name",
- "property-value": "MY6885_M-Schwere-Reiter-Str-440460_GTC2_84003803"
- }
- ]
- }
- ]
- },
- "group-name": "Urban",
- "resource-version": "1701951284582",
- "group-type": "cell",
- "object-group-id": "ric_cluster"
- }
+ "group-name": "Urban",
+ "resource-version": "1701951284582",
+ "group-type": "cell",
+ "object-group-id": "ric_cluster"
}
-}
\ No newline at end of file
+}
<parent>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-parent</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
<relativePath>../aai-parent/pom.xml</relativePath>
</parent>
<artifactId>aai-els-onap-logging</artifactId>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
- <dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjrt</artifactId>
- </dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
- <groupId>javax.annotation</groupId>
- <artifactId>javax.annotation-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.onap.logging-analytics</groupId>
- <artifactId>logging-slf4j</artifactId>
- <exclusions>
- <exclusion>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-module-junit4</artifactId>
- </exclusion>
- </exclusions>
+ <groupId>jakarta.servlet</groupId>
+ <artifactId>jakarta.servlet-api</artifactId>
+ <scope>compile</scope>
</dependency>
<dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
+ <groupId>jakarta.annotation</groupId>
+ <artifactId>jakarta.annotation-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>javax.ws.rs</groupId>
- <artifactId>javax.ws.rs-api</artifactId>
+ <groupId>jakarta.ws.rs</groupId>
+ <artifactId>jakarta.ws.rs-api</artifactId>
<scope>provided</scope>
</dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <version>3.12.4</version>
- <scope>test</scope>
- </dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
- <artifactId>jackson-module-jaxb-annotations</artifactId>
+ <artifactId>jackson-module-jakarta-xmlbind-annotations</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
- <groupId>com.sun.jersey</groupId>
+ <groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
- <version>1.18.30</version>
+ <version>1.18.38</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>com.vaadin.external.google</groupId>
+ <artifactId>android-json</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>5.18.0</version>
<scope>test</scope>
</dependency>
- <!-- TODO: Migrate tests to junit 5 and remove this dependency -->
- <dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-core</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
</dependencies>
-
- <!-- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- </plugin>
- </plugins>
- </build> -->
</project>
package org.onap.aai.aailog.filter;
-import javax.annotation.Priority;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.PreMatching;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.UriInfo;
+import jakarta.annotation.Priority;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.PreMatching;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.UriInfo;
import org.onap.aai.aailog.logs.ServiceName;
import org.onap.logging.filter.base.AuditLogContainerFilter;
package org.onap.aai.aailog.filter;
-import com.sun.jersey.api.client.ClientHandler;
-import com.sun.jersey.api.client.ClientHandlerException;
-import com.sun.jersey.api.client.ClientRequest;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.filter.ClientFilter;
-
+import java.io.IOException;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
-import javax.ws.rs.core.MultivaluedMap;
-
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.client.ClientRequestContext;
+import jakarta.ws.rs.client.ClientRequestFilter;
+import org.glassfish.jersey.client.ClientResponse;
import org.onap.aai.aailog.logs.ServiceName;
import org.onap.logging.filter.base.Constants;
import org.onap.logging.filter.base.MDCSetup;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.*;
-public class RestControllerClientLoggingInterceptor extends ClientFilter {
- private static final Logger logger = LoggerFactory.getLogger(RestControllerClientLoggingInterceptor.class);
+public class RestControllerClientRequestLoggingInterceptor implements ClientRequestFilter {
+ private static final Logger logger = LoggerFactory.getLogger(RestControllerClientRequestLoggingInterceptor.class);
private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN");
private final MDCSetup mdcSetup;
private final String partnerName;
- public RestControllerClientLoggingInterceptor() {
+ public RestControllerClientRequestLoggingInterceptor() {
mdcSetup = new MDCSetup();
partnerName = getPartnerName();
}
- @Override
- public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException {
- ClientResponse clientResponse = null;
- pre(clientRequest);
- // Call the next client handler in the filter chain
- ClientHandler nextHandler = getNext();
- if (nextHandler != null) {
- clientResponse = nextHandler.handle(clientRequest);
- }
- if (clientResponse != null) {
- post(clientResponse);
- }
- return clientResponse;
- }
-
- protected String getTargetServiceName(ClientRequest clientRequest) {
- return getServiceName(clientRequest);
+ protected String getTargetServiceName(ClientRequestContext requestContext) {
+ return getServiceName(requestContext);
}
- protected String getServiceName(ClientRequest clientRequest) {
- String path = clientRequest.getURI().getRawPath();
+ protected String getServiceName(ClientRequestContext requestContext) {
+ String path = requestContext.getUri().getRawPath();
return ServiceName.extractServiceName(path);
}
return String.valueOf(clientResponse.getStatus());
}
- protected String getTargetEntity(ClientRequest ClientRequest) {
+ protected String getTargetEntity(ClientRequestContext requestContext) {
return Constants.DefaultValues.UNKNOWN_TARGET_ENTITY;
};
- protected void pre(ClientRequest clientRequest) {
+ @Override
+ public void filter(ClientRequestContext requestContext) throws IOException {
+ pre(requestContext);
+ }
+
+ protected void pre(ClientRequestContext requestContext) {
try {
- setInvocationId(clientRequest);
- setupMDC(clientRequest);
- setupHeaders(clientRequest);
+ setInvocationId(requestContext);
+ setupMDC(requestContext);
+ setupHeaders(requestContext);
logger.info(ONAPLogConstants.Markers.INVOKE, "Invoke");
} catch (Exception e) {
logger.warn("Error in RestControllerClientLoggingInterceptor pre", e.getMessage());
}
}
- public void setInvocationId(ClientRequest clientRequest) {
+ public void setInvocationId(ClientRequestContext requestContext) {
String invocationId = null;
- MultivaluedMap<String, Object> requestHeaders = clientRequest.getHeaders();
+ MultivaluedMap<String, Object> requestHeaders = requestContext.getHeaders();
Object id = requestHeaders.get(ONAPLogConstants.Headers.INVOCATION_ID);
if (id != null) {
invocationId = (String) id;
MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
}
- protected void setupHeaders(ClientRequest clientRequest) {
- String requestId = extractRequestID(clientRequest);
- MultivaluedMap<String, Object> requestHeaders = clientRequest.getHeaders();
+ protected void setupHeaders(ClientRequestContext requestContext) {
+ String requestId = extractRequestID(requestContext);
+ MultivaluedMap<String, Object> requestHeaders = requestContext.getHeaders();
addHeader(requestHeaders, ONAPLogConstants.Headers.REQUEST_ID, requestId);
addHeader(requestHeaders, Constants.HttpHeaders.HEADER_REQUEST_ID, requestId);
Object requestIdObj = requestHeaders.getFirst(Constants.HttpHeaders.TRANSACTION_ID);
}
}
- protected void setupMDC(ClientRequest clientRequest) {
+ protected void setupMDC(ClientRequestContext requestContext) {
MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP,
ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
- MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, getTargetServiceName(clientRequest));
+ MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, getTargetServiceName(requestContext));
MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
mdcSetup.setInvocationIdFromMDC();
if (MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY) == null) {
- String targetEntity = getTargetEntity(clientRequest);
+ String targetEntity = getTargetEntity(requestContext);
if (targetEntity != null) {
MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity);
} else {
}
if (MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME) == null) {
- MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, getServiceName(clientRequest));
+ MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, getServiceName(requestContext));
}
mdcSetup.setServerFQDN();
}
- protected String extractRequestID(ClientRequest clientRequest) {
+ protected String extractRequestID(ClientRequestContext requestContext) {
String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
if (requestId == null || requestId.isEmpty()) {
- MultivaluedMap<String, Object> requestHeaders = clientRequest.getHeaders();
+ MultivaluedMap<String, Object> requestHeaders = requestContext.getHeaders();
Object requestIdObj = requestHeaders.getFirst(Constants.HttpHeaders.TRANSACTION_ID);
if (requestIdObj != null) {
requestId = (String) requestIdObj;
--- /dev/null
+/**
+ * ============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.aailog.filter;
+
+import java.io.IOException;
+import java.util.UUID;
+
+import jakarta.ws.rs.client.ClientRequestContext;
+import jakarta.ws.rs.client.ClientResponseContext;
+import jakarta.ws.rs.client.ClientResponseFilter;
+import jakarta.ws.rs.core.MultivaluedMap;
+
+import org.onap.logging.filter.base.Constants;
+import org.onap.logging.filter.base.MDCSetup;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.slf4j.*;
+
+public class RestControllerClientResponseLoggingInterceptor implements ClientResponseFilter {
+ private static final Logger logger = LoggerFactory.getLogger(RestControllerClientRequestLoggingInterceptor.class);
+ private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN");
+ private final MDCSetup mdcSetup;
+ private final String partnerName;
+
+ public RestControllerClientResponseLoggingInterceptor() {
+ mdcSetup = new MDCSetup();
+ partnerName = getPartnerName();
+ }
+
+ @Override
+ public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
+ post(responseContext);
+ }
+
+ protected void post(ClientResponseContext responseContext) {
+ try {
+ mdcSetup.setLogTimestamp();
+ mdcSetup.setElapsedTimeInvokeTimestamp();
+ mdcSetup.setResponseStatusCode(getHttpStatusCode(responseContext));
+ mdcSetup.setResponseDescription(getHttpStatusCode(responseContext));
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, getResponseCode(responseContext));
+ logger.info(INVOKE_RETURN, "InvokeReturn");
+ mdcSetup.clearClientMDCs();
+ } catch (Exception e) {
+ logger.warn("Error in RestControllerClientLoggingInterceptor post", e.getMessage());
+ }
+ }
+
+ protected int getHttpStatusCode(ClientResponseContext responseContext) {
+ return responseContext.getStatus();
+ }
+
+ protected String getResponseCode(ClientResponseContext responseContext) {
+ return String.valueOf(responseContext.getStatus());
+ }
+
+ public void setInvocationId(ClientRequestContext requestContext) {
+ String invocationId = null;
+ MultivaluedMap<String, Object> requestHeaders = requestContext.getHeaders();
+ Object id = requestHeaders.get(ONAPLogConstants.Headers.INVOCATION_ID);
+ if (id != null) {
+ invocationId = (String) id;
+ }
+ requestHeaders.remove(ONAPLogConstants.Headers.INVOCATION_ID);
+ if (invocationId == null) {
+ invocationId = UUID.randomUUID().toString();
+ }
+ MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
+ }
+
+ protected String getPartnerName() {
+ return mdcSetup.getProperty(Constants.Property.PARTNER_NAME);
+ }
+}
package org.onap.aai.aailog.logs;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Response;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.Response;
import org.onap.logging.filter.base.AbstractMetricLogFilter;
import org.onap.logging.filter.base.ONAPComponents;
import java.util.UUID;
-import javax.ws.rs.core.Response;
+import jakarta.ws.rs.core.Response;
import org.onap.logging.filter.base.MDCSetup;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import java.util.Map;
-import javax.xml.bind.annotation.XmlRootElement;
+import jakarta.xml.bind.annotation.XmlRootElement;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
-import lombok.Value;
import java.util.Map;
@NoArgsConstructor
package org.onap.aai.exceptions;
+import java.io.Serial;
import java.util.Collection;
import java.util.LinkedList;
import org.onap.aai.logging.ErrorLogHelper;
import org.onap.aai.logging.ErrorObject;
-import org.onap.aai.logging.ErrorObjectNotFoundException;
public class AAIException extends Exception {
public static final String DEFAULT_EXCEPTION_CODE = "AAI_4000";
+ @Serial
private static final long serialVersionUID = 1L;
private final String code;
import java.security.cert.X509Certificate;
import javax.security.auth.x500.X500Principal;
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
return "INACTIVE_HEADER_CONV";
}
- String cipherSuite = (String) accessEvent.getRequest().getAttribute("javax.servlet.request.cipher_suite");
+ String cipherSuite = (String) accessEvent.getRequest().getAttribute("jakarta.servlet.request.cipher_suite");
String authUser = null;
if (cipherSuite != null) {
try {
X509Certificate certChain[] = (X509Certificate[]) accessEvent.getRequest()
- .getAttribute("javax.servlet.request.X509Certificate");
+ .getAttribute("jakarta.servlet.request.X509Certificate");
if (certChain == null || certChain.length == 0) {
HttpServletRequest request = accessEvent.getRequest();
import java.util.Properties;
import java.util.Map.Entry;
-import javax.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MediaType;
import org.apache.commons.lang3.StringUtils;
import org.onap.aai.domain.errorResponse.ErrorMessage;
}
private static ErrorObject getRestErrorObject(AAIException aaiException) {
- final int restErrorCode = Integer.parseInt(aaiException.getErrorObject().getRESTErrorCode());
- return ErrorLogHelper.getErrorObject("AAI_" + restErrorCode);
+ return ErrorLogHelper.getErrorObject("AAI_" + aaiException.getErrorObject().getRESTErrorCode());
}
public static Fault createPolicyFault(AAIException aaiException, String text, List<String> variables) {
package org.onap.aai.logging;
-import javax.ws.rs.core.Response.Status;
+import jakarta.ws.rs.core.Response.Status;
/**
*
package org.onap.aai.logging;
+import java.io.Serial;
+
public class ErrorObjectFormatException extends Exception {
+ @Serial
private static final long serialVersionUID = 3732705544448553685L;
public ErrorObjectFormatException() {
package org.onap.aai.logging;
+import java.io.Serial;
+
public class ErrorObjectNotFoundException extends Exception {
+ @Serial
private static final long serialVersionUID = 4115316781400786740L;
public ErrorObjectNotFoundException() {
package org.onap.aai.logging;
+import java.io.Serial;
+
public class LoggingContextNotExistsException extends RuntimeException {
+ @Serial
private static final long serialVersionUID = -4965807709525739623L;
}
package org.onap.aai.logging;
+import java.io.Serial;
+
public class StopWatchNotStartedException extends RuntimeException {
+ @Serial
private static final long serialVersionUID = -4540164295822859408L;
public StopWatchNotStartedException() {
package org.onap.aai.util;
-import java.io.File;
-import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.nio.charset.Charset;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import org.apache.commons.io.IOUtils;
import org.eclipse.jetty.util.security.Password;
import org.onap.aai.exceptions.AAIException;
import org.slf4j.Logger;
private static final Logger LOGGER = LoggerFactory.getLogger(AAIApplicationConfig.class);
private static String GLOBAL_PROP_FILE_NAME = "application.properties";
- private static final String SERVER_CERTS_LOCATION_PROP_NAME = "server.certs.location";
- private static final String PASSPHRASSES_FILENAME = ".passphrases";
- private static final String PASSWORD_FILENAME = ".password";
- private static final String TRUSTSTORE_PASSWORD_PROP_NAME = "cadi_truststore_password";
- public static final String SERVER_SSL_KEYSTORE_PROP_NAME = "server.ssl.key-store";
- public static final String SERVER_SSL_KEYSTORE_PKCS12_PROP_NAME = "server.ssl.key-store.pkcs12";
- public static final String SERVER_SSL_TRUSTSTORE_PROP_NAME = "server.ssl.trust-store";
- public static final String TRUSTSTORE_PASSWORD_NAME = "server.ssl.trust-store-password";
- public static final String KEYSTORE_PASSWORD_NAME = "server.ssl.key-store-password";
+
private static Properties serverProps;
private static boolean propsInitialized = false;
- private static String TRUSTSTORE_PASSWORD = null;
- private static String KEYSTORE_PASSWORD = null;
+
private static final String PROPERTY_REGEX = "\\$\\{([^\\$\\{\\}]+)\\}";
/**
newServerProps.load(is);
propsInitialized = true;
serverProps = newServerProps;
- TRUSTSTORE_PASSWORD = retrieveTruststorePassword();
- KEYSTORE_PASSWORD = retrieveKeystorePassword();
} catch (Exception fnfe) {
final InputStream is =
Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties");
try {
newServerProps.load(is);
serverProps = newServerProps;
- TRUSTSTORE_PASSWORD = retrieveTruststorePassword();
- KEYSTORE_PASSWORD = retrieveKeystorePassword();
} catch (IOException e) {
LOGGER.warn("Encountered IO Exception during loading of props from inputstream", e);
}
return response;
}
- /**
- * Gets the keystore path
- *
- * @return the string
- * @throws AAIException the AAI exception
- */
- public static String getKeystore() throws AAIException {
- return (get(SERVER_SSL_KEYSTORE_PROP_NAME));
- }
-
- /**
- * Gets the PKCS12 keystore path
- *
- * @return the string
- * @throws AAIException the AAI exception
- */
- public static String getKeystorePkcs12() throws AAIException {
- return (get(SERVER_SSL_KEYSTORE_PKCS12_PROP_NAME));
- }
-
- /**
- * Gets the keystore path
- *
- * @return the string
- * @throws AAIException the AAI exception
- */
- public static String getTruststore() throws AAIException {
- return (get(SERVER_SSL_TRUSTSTORE_PROP_NAME));
- }
-
- /**
- * Retrieve the keystore password
- *
- * @return the password
- */
- private static String retrieveKeystorePassword() {
- String certPath = serverProps.getProperty(SERVER_CERTS_LOCATION_PROP_NAME);
- if (certPath == null) {
- return null;
- }
- try {
- certPath = replaceProperties(certPath);
- } catch (AAIException e) {
- return null;
- }
- return (retrieveKeystorePasswordWithCertPath(certPath));
- }
-
- /**
- * Retrieve the keystore password
- *
- * @return the password
- */
- private static String retrieveKeystorePasswordWithCertPath(String certPath) {
-
- File passwordFile = null;
- InputStream passwordStream = null;
- String keystorePassword = null;
-
- // Override the passwords from application.properties if we find AAF certman files
- try {
- passwordFile = new File(certPath + PASSWORD_FILENAME);
- passwordStream = new FileInputStream(passwordFile);
- keystorePassword = IOUtils.toString(passwordStream, Charset.defaultCharset());
- if (keystorePassword != null) {
- keystorePassword = keystorePassword.trim();
- }
-
- } catch (IOException e) {
- LOGGER.warn("Not using AAF Certman password file, e=" + e.getMessage());
- } catch (NullPointerException n) {
- LOGGER.warn("Not using AAF Certman passphrases file, e=" + n.getMessage());
- } finally {
- if (passwordStream != null) {
- try {
- passwordStream.close();
- } catch (Exception e) {
- }
- }
- }
- return keystorePassword;
- }
-
- /**
- * Get the keystore password
- *
- * @return the password
- */
- public static String getKeystorePassword() {
- return (KEYSTORE_PASSWORD);
- }
-
- /**
- * Gets the truststore password
- *
- * @return the password
- */
- private static String retrieveTruststorePasswordWithCertPath(String certPath) {
-
- File passphrasesFile = null;
- InputStream passphrasesStream = null;
- String truststorePassword = null;
- try {
- passphrasesFile = new File(certPath + PASSPHRASSES_FILENAME);
- passphrasesStream = new FileInputStream(passphrasesFile);
-
- Properties passphrasesProps = new Properties();
- passphrasesProps.load(passphrasesStream);
- truststorePassword = passphrasesProps.getProperty(TRUSTSTORE_PASSWORD_PROP_NAME);
- if (truststorePassword != null) {
- truststorePassword = truststorePassword.trim();
- }
-
- } catch (IOException e) {
- LOGGER.warn("Not using AAF Certman passphrases file, e=" + e.getMessage());
- } catch (NullPointerException n) {
- LOGGER.warn("Not using AAF Certman passphrases file, e=" + n.getMessage());
- } finally {
- if (passphrasesStream != null) {
- try {
- passphrasesStream.close();
- } catch (Exception e) {
- }
- }
- }
-
- return truststorePassword;
- }
-
- /**
- * Gets the truststore password
- *
- * @return the password
- */
- private static String retrieveTruststorePassword() {
- String certPath = serverProps.getProperty(SERVER_CERTS_LOCATION_PROP_NAME);
- if (certPath == null) {
- return null;
- }
- try {
- certPath = replaceProperties(certPath);
- } catch (AAIException e) {
- return null;
- }
- return (retrieveTruststorePasswordWithCertPath(certPath));
- }
-
- /**
- * Get the trustore password
- *
- * @return the password
- */
- public static String getTruststorePassword() {
- return (TRUSTSTORE_PASSWORD);
- }
-
/**
* Gets the int value for the key.
*
m.appendTail(sb);
return (sb.toString());
}
-
- public static Properties retrieveKeystoreProps() throws AAIException {
-
- Properties props = new Properties();
- String truststorePath = System.getProperty(SERVER_SSL_TRUSTSTORE_PROP_NAME);
- String truststorePassword = System.getProperty(TRUSTSTORE_PASSWORD_NAME);
- String keystorePath = System.getProperty(SERVER_SSL_KEYSTORE_PKCS12_PROP_NAME);
- String keystorePassword = System.getProperty(KEYSTORE_PASSWORD_NAME);
- String certLocation = System.getProperty(SERVER_CERTS_LOCATION_PROP_NAME);
-
- if (truststorePath == null || truststorePath.isEmpty()) {
- truststorePath = AAIApplicationConfig.getTruststore();
- }
- if (truststorePath != null) {
- props.setProperty(SERVER_SSL_TRUSTSTORE_PROP_NAME, truststorePath);
- }
- if (truststorePassword == null || truststorePassword.isEmpty()) {
- if (certLocation != null && (!certLocation.isEmpty())) {
- truststorePassword = AAIApplicationConfig.retrieveTruststorePasswordWithCertPath(certLocation);
- } else {
- truststorePassword = AAIApplicationConfig.getTruststorePassword();
- }
-
- }
- if (truststorePassword != null) {
- props.setProperty(TRUSTSTORE_PASSWORD_NAME, truststorePassword);
- }
- if (keystorePath == null || keystorePath.isEmpty()) {
- keystorePath = AAIApplicationConfig.getKeystorePkcs12();
- }
- if (keystorePath != null) {
- props.setProperty(SERVER_SSL_KEYSTORE_PKCS12_PROP_NAME, keystorePath);
- }
- if (keystorePassword == null || keystorePassword.isEmpty()) {
- if (certLocation != null && (!certLocation.isEmpty())) {
- keystorePassword = AAIApplicationConfig.retrieveKeystorePasswordWithCertPath(certLocation);
- } else {
- keystorePassword = AAIApplicationConfig.getKeystorePassword();
- }
- }
- if (keystorePassword != null) {
- props.setProperty(KEYSTORE_PASSWORD_NAME, keystorePassword);
- }
- return (props);
- }
}
public static final String AAI_SCHEMA_MOD_LOGBACK_PROPS = "schemaMod-logback.xml";
public static final String AAI_FORCE_DELETE_LOGBACK_PROPS = "forceDelete-logback.xml";
- public static final String AAI_TRUSTSTORE_FILENAME = "aai.truststore.filename";
- public static final String AAI_TRUSTSTORE_PASSWD = "aai.truststore.passwd";
- public static final String AAI_KEYSTORE_FILENAME = "aai.keystore.filename";
- public static final String AAI_KEYSTORE_PASSWD = "aai.keystore.passwd";
-
public static final String AAI_SERVER_URL_BASE = "aai.server.url.base";
public static final String AAI_SERVER_URL = "aai.server.url";
public static final String AAI_OLDSERVER_URL = "aai.oldserver.url";
public class FormatDate {
private final String timeZone;
- private final String pattern;
+ private final DateTimeFormatter formatter ;
public FormatDate(String pattern) {
- this.pattern = pattern;
- this.timeZone = "GMT";
+ this(pattern, "GMT");
}
public FormatDate(String pattern, String timeZone) {
- this.pattern = pattern;
this.timeZone = timeZone;
+ this.formatter = DateTimeFormatter.ofPattern(pattern);
}
public String getDateTime() {
-
- final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return formatter.format(ZonedDateTime.now(ZoneId.of(timeZone)));
}
}
package org.onap.aai.util;
+import org.onap.aai.exceptions.AAIException;
+
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
-import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
-
-import org.onap.aai.exceptions.AAIException;
+import com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationModule;
public class MapperUtil {
public static <T> T readWithDashesAsObjectOf(Class<T> clazz, String value) throws AAIException {
ObjectMapper mapper = new ObjectMapper();
try {
- mapper.registerModule(new JaxbAnnotationModule());
+ mapper.registerModule(new JakartaXmlBindAnnotationModule());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
- mapper.registerModule(new JaxbAnnotationModule());
+ mapper.registerModule(new JakartaXmlBindAnnotationModule());
return mapper.writeValueAsString(obj);
} catch (Exception e) {
throw new AAIException("AAI_4008", e);
* 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.
package org.onap.logging.filter.base;
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.Logger;
additionalPreHandling(request);
setLogTimestamp();
setElapsedTime();
- logger.info(ONAPLogConstants.Markers.ENTRY, "Entering");
} catch (Exception e) {
logger.warn("Error in AbstractInboundFilter pre", e);
}
setResponseDescription(responseCode);
setLogTimestamp();
setElapsedTime();
- logger.info(ONAPLogConstants.Markers.EXIT, "Exiting.");
additionalPostHandling(response);
} catch (Exception e) {
logger.warn("Error in AbstractInboundFilter post", e);
import java.util.Enumeration;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.core.HttpHeaders;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.ws.rs.core.HttpHeaders;
public abstract class AbstractServletFilter {
import java.io.IOException;
-import javax.annotation.Priority;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.container.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.ext.Providers;
+import jakarta.annotation.Priority;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerRequestFilter;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.container.ContainerResponseFilter;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.ext.Providers;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.MDC;
import java.io.IOException;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import jakarta.servlet.Filter;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.FilterConfig;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.MDC;
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain)
throws IOException, ServletException {
try {
- if (request != null && request instanceof HttpServletRequest) {
- pre((HttpServletRequest) request);
+ if (request != null && request instanceof HttpServletRequest servletRequest) {
+ pre(servletRequest);
}
filterChain.doFilter(request, response);
} finally {
- if (request != null && request instanceof HttpServletRequest) {
- post((HttpServletRequest) request, (HttpServletResponse) response);
+ if (request != null && request instanceof HttpServletRequest servletRequest) {
+ post(servletRequest, (HttpServletResponse) response);
}
MDC.clear();
}
* 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.
import java.time.temporal.ChronoUnit;
import java.util.UUID;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Response;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.Response;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.Logger;
}
public void setElapsedTime() {
- DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
- ZonedDateTime entryTimestamp =
- ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP), timeFormatter);
- ZonedDateTime endTimestamp = ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP), timeFormatter);
-
- MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME,
- Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp)));
+ String entryTimestampString = MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP);
+ String elapsedTime = "elapsedTimeIsNotAvailable";
+ if(entryTimestampString != null) {
+ DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
+ ZonedDateTime entryTimestamp =
+ ZonedDateTime.parse(entryTimestampString, timeFormatter);
+ String logTimestamp = MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP);
+ ZonedDateTime endTimestamp = ZonedDateTime.parse(logTimestamp, timeFormatter);
+ elapsedTime = Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp));
+ }
+ MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME, elapsedTime);
}
public void setElapsedTimeInvokeTimestamp() {
package org.onap.logging.filter.base;
-import javax.annotation.Priority;
-import javax.ws.rs.client.ClientRequestContext;
-import javax.ws.rs.client.ClientRequestFilter;
-import javax.ws.rs.client.ClientResponseContext;
-import javax.ws.rs.client.ClientResponseFilter;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.ext.Providers;
+import jakarta.annotation.Priority;
+import jakarta.ws.rs.client.ClientRequestContext;
+import jakarta.ws.rs.client.ClientRequestFilter;
+import jakarta.ws.rs.client.ClientResponseContext;
+import jakarta.ws.rs.client.ClientResponseFilter;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.ext.Providers;
@Priority(0)
public class MetricLogClientFilter
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.client.ClientRequestContext;
-import javax.ws.rs.client.ClientRequestFilter;
-import javax.ws.rs.client.ClientResponseContext;
-import javax.ws.rs.client.ClientResponseFilter;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.ext.WriterInterceptor;
-import javax.ws.rs.ext.WriterInterceptorContext;
+import jakarta.ws.rs.WebApplicationException;
+import jakarta.ws.rs.client.ClientRequestContext;
+import jakarta.ws.rs.client.ClientRequestFilter;
+import jakarta.ws.rs.client.ClientResponseContext;
+import jakarta.ws.rs.client.ClientResponseFilter;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.ext.WriterInterceptor;
+import jakarta.ws.rs.ext.WriterInterceptorContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintWriter;
import java.util.zip.GZIPInputStream;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ReadListener;
-import javax.servlet.ServletException;
-import javax.servlet.ServletInputStream;
-import javax.servlet.ServletOutputStream;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.WriteListener;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletRequestWrapper;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpServletResponseWrapper;
+import jakarta.servlet.Filter;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.FilterConfig;
+import jakarta.servlet.ReadListener;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletInputStream;
+import jakarta.servlet.ServletOutputStream;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.WriteListener;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequestWrapper;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpServletResponseWrapper;
public class PayloadLoggingServletFilter extends AbstractServletFilter implements Filter {
package org.onap.logging.filter.base;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedMap;
public class SimpleJaxrsHeadersMap implements SimpleMap {
MultivaluedMap<String, String> map;
package org.onap.logging.filter.base;
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
public class SimpleServletHeadersMap implements SimpleMap {
private HttpServletRequest request;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.MDC;
package org.onap.aai.aailog.filter;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import java.net.URI;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerResponseContext;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.UriInfo;
-
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.logging.filter.base.Constants;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.MDC;
-@RunWith(MockitoJUnitRunner.class)
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.UriInfo;
+
+@ExtendWith(MockitoExtension.class)
public class AaiAuditLogContainerFilterTest {
@Mock
private ContainerRequestContext containerRequest;
@InjectMocks
private AaiAuditLogContainerFilter aaiAuditFilter;
- @After
+ @AfterEach
public void tearDown() {
MDC.clear();
}
package org.onap.aai.aailog.filter;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.doReturn;
import java.net.InetAddress;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.logging.filter.base.Constants;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.MDC;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class RestClientLoggingInterceptorTest {
@Mock
@InjectMocks
private RestClientLoggingInterceptor restClientLoggingInterceptor;
- @After
+ @AfterEach
public void tearDown() {
MDC.clear();
}
package org.onap.aai.aailog.filter;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import com.sun.jersey.api.client.ClientRequest;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.Mockito.when;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
import org.onap.logging.filter.base.Constants;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.MDC;
-@RunWith(MockitoJUnitRunner.class)
+import jakarta.ws.rs.client.ClientRequestContext;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
+
+@MockitoSettings(strictness = Strictness.WARN)
+@ExtendWith(MockitoExtension.class)
public class RestControllerClientLoggingInterceptorTest {
- private ClientRequest clientRequest;
+ @Spy
+ private ClientRequestContext clientRequest;
@Spy
@InjectMocks
- private RestControllerClientLoggingInterceptor restControllerClientLoggingInterceptor;
+ private RestControllerClientRequestLoggingInterceptor restControllerClientLoggingInterceptor;
- @Before
+ @BeforeEach
public void init() throws URISyntaxException {
- System.setProperty("javax.ws.rs.ext.RuntimeDelegate", "com.sun.ws.rs.ext.RuntimeDelegateImpl");
- clientRequest = ClientRequest.create().build(
- new URI("https://localhost:9999/aai/v1/cloud-infrastructure/complexes/complex/complex-1"), "GET");
+ System.setProperty("jakarta.ws.rs.ext.RuntimeDelegate", "com.sun.ws.rs.ext.RuntimeDelegateImpl");
+ when(clientRequest.getHeaders()).thenReturn(new MultivaluedHashMap<String, Object>());
+ when(clientRequest.getUri())
+ .thenReturn(new URI("https://localhost:9999/aai/v1/cloud-infrastructure/complexes/complex/complex-1"));
+
+ // clientRequest = ClientRequest.create().build(
+ // new
+ // URI("https://localhost:9999/aai/v1/cloud-infrastructure/complexes/complex/complex-1"),
+ // "GET");
}
- @After
+ @AfterEach
public void tearDown() {
MDC.clear();
}
String transId = "37b3ab2a-e57e-4fe8-8d8f-eee3019efce6";
MultivaluedMap<String, Object> requestHeaders = new MultivaluedHashMap<String, Object>();
requestHeaders.add(Constants.HttpHeaders.TRANSACTION_ID, transId);
+ when(clientRequest.getHeaders()).thenReturn(requestHeaders);
+ when(clientRequest.getUri())
+ .thenReturn(new URI("https://localhost:9999/aai/v1/cloud-infrastructure/complexes/complex/complex-1"));
+
clientRequest.getHeaders().putAll(requestHeaders);
restControllerClientLoggingInterceptor.pre(clientRequest);
MultivaluedMap<String, Object> headers = clientRequest.getHeaders();
package org.onap.aai.exceptions;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
-import javax.ws.rs.core.Response;
-
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.aai.logging.AaiElsErrorCode;
import org.onap.aai.logging.ErrorObject;
+import jakarta.ws.rs.core.Response;
+
public class AAIExceptionTest {
private AAIException aaiException;
package org.onap.aai.exceptions;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.util.HashMap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class AAIExceptionWithInfoTest {
package org.onap.aai.logging;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import ch.qos.logback.access.spi.IAccessEvent;
import javax.security.auth.x500.X500Principal;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class CNNameTest {
@Mock
X509Certificate cert;
@InjectMocks
private CNName cnName;
- @Before
+ @BeforeEach
public void setup() {
when(cnName.isStarted()).thenReturn(true);
}
MockHttpServletRequest https = new MockHttpServletRequest();
https.addHeader("Authorization", "Basic dXNlcjpwYXNzd29yZA==");
- https.setAttribute("javax.servlet.request.cipher_suite", "");
- https.setAttribute("javax.servlet.request.X509Certificate", null);
+ https.setAttribute("jakarta.servlet.request.cipher_suite", "");
+ https.setAttribute("jakarta.servlet.request.X509Certificate", null);
when(accessEvent.getRequest()).thenReturn(https);
assertEquals("user", cnName.convert(accessEvent));
MockHttpServletRequest https = new MockHttpServletRequest();
https.addHeader("Authorization", "dXNlcjpwYXNzd29yZA==");
- https.setAttribute("javax.servlet.request.cipher_suite", "");
- https.setAttribute("javax.servlet.request.X509Certificate", null);
+ https.setAttribute("jakarta.servlet.request.cipher_suite", "");
+ https.setAttribute("jakarta.servlet.request.X509Certificate", null);
when(accessEvent.getRequest()).thenReturn(https);
assertEquals("-", cnName.convert(accessEvent));
MockHttpServletRequest https = new MockHttpServletRequest();
https.addHeader("Authorization", "Basic dXNlcjpwYXNzd29yZA==");
- https.setAttribute("javax.servlet.request.cipher_suite", null);
- https.setAttribute("javax.servlet.request.X509Certificate", null);
+ https.setAttribute("jakarta.servlet.request.cipher_suite", null);
+ https.setAttribute("jakarta.servlet.request.X509Certificate", null);
when(accessEvent.getRequest()).thenReturn(https);
assertEquals("-", cnName.convert(accessEvent));
X509Certificate[] certChain = {cert};
MockHttpServletRequest https = new MockHttpServletRequest();
- https.setAttribute("javax.servlet.request.cipher_suite", "");
- https.setAttribute("javax.servlet.request.X509Certificate", certChain);
+ https.setAttribute("jakarta.servlet.request.cipher_suite", "");
+ https.setAttribute("jakarta.servlet.request.X509Certificate", certChain);
when(accessEvent.getRequest()).thenReturn(https);
when(cert.getSubjectX500Principal()).thenReturn(new X500Principal(testSubject));
package org.onap.aai.logging;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class CustomLogPatternLayoutTest {
package org.onap.aai.logging;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import ch.qos.logback.access.spi.IAccessEvent;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class DME2RestFlagTest {
@Mock
@InjectMocks
private DME2RestFlag dme2RestFlag;
- @Before
+ @BeforeEach
public void setup() {
when(dme2RestFlag.isStarted()).thenReturn(true);
}
package org.onap.aai.logging;
import static java.lang.Thread.sleep;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import javax.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MediaType;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.aai.domain.errorResponse.ErrorMessage;
import org.onap.aai.domain.errorResponse.ExceptionType;
import org.onap.aai.domain.errorResponse.Fault;
private static final ObjectMapper objectMapper = new ObjectMapper();
private static final XmlMapper xmlMapper = new XmlMapper();
- @Before
+ @BeforeEach
public void init() {
System.setProperty("AJSC_HOME", ".");
}
- @After
+ @AfterEach
public void cleanup() throws IOException {
MDC.clear();
LogFile.deleteContents(errorLogFileName);
org.onap.aai.domain.errorResponse.Fault restResponse =
objectMapper.readValue(errorResponse, org.onap.aai.domain.errorResponse.Fault.class);
-
+
Map<ExceptionType, ErrorMessage> requestError = restResponse.getRequestError();
assertNotNull(requestError);
ErrorMessage errorMessage = requestError.get(ExceptionType.SERVICE);
@Test
public void thatInvalidMediaTypeWillReturnInvalidAcceptHeaderException() throws ErrorObjectNotFoundException, JsonMappingException, JsonProcessingException {
String errorResponse = ErrorLogHelper.getRESTAPIErrorResponse(Collections.singletonList(MediaType.TEXT_PLAIN_TYPE), new AAIException(), new ArrayList<>());
-
+
Fault restResponse = objectMapper.readValue(errorResponse, Fault.class);
assertNotNull(restResponse);
Info info = ErrorLogHelper.getRestApiInfoResponse(aaiExceptionsMap);
ErrorMessage errorMessage = info.getErrorMessages().get(0);
assertEquals("INF0001", errorMessage.getMessageId());
- assertEquals("Internal Error (msg=%1) (ec=%2)", errorMessage.getText());
+ assertEquals("Success X-FromAppId=%1 X-TransactionId=%2 (msg=%3) (ec=%4)", errorMessage.getText());
assertEquals("Successful health check:OK", errorMessage.getVariables().get(0));
assertEquals("0.0.0002", errorMessage.getVariables().get(1));
}
package org.onap.aai.logging;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class ErrorObjectFormatExceptionTest {
package org.onap.aai.logging;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class ErrorObjectNotFoundExceptionTest {
package org.onap.aai.logging;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import javax.ws.rs.core.Response;
+import org.junit.jupiter.api.Test;
-import org.junit.Test;
+import jakarta.ws.rs.core.Response;
public class ErrorObjectTest {
private ErrorObject errorObject;
package org.onap.aai.logging;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.aai.exceptions.AAIException;
public class LogFormatToolsTest {
package org.onap.aai.logging;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import org.slf4j.MDC;
public class LoggingContextTest {
- @After
+ @AfterEach
public void cleanup() {
MDC.clear();
}
package org.onap.aai.logging;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class StopWatchNotStartedExceptionTest {
package org.onap.aai.logging;
import static java.lang.Thread.sleep;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import org.slf4j.MDC;
public class StopWatchTest {
- @After
+ @AfterEach
public void cleanup() {
MDC.clear();
}
package org.onap.aai.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.aai.exceptions.AAIException;
public class AAIApplicationConfigTest {
- @Before
+ @BeforeEach
public void setup() {
AAIApplicationConfig.init();
}
- @Test
- public void truststoreTest() throws AAIException {
- assertEquals("truststore.jks", AAIApplicationConfig.getTruststore());
- }
-
- @Test
- public void keystoreTest() throws AAIException {
- assertEquals("keystore.jks", AAIApplicationConfig.getKeystore());
- }
-
- @Test
- public void getKeystorePkcs12Test() throws AAIException {
- assertEquals("keystore.pkcs12", AAIApplicationConfig.getKeystorePkcs12());
- }
-
@Test
public void getValueWithDefaultTest() throws AAIException {
assertEquals("default-value", AAIApplicationConfig.get("non-existing-key", "default-value"));
@Test
public void getValueTest() throws AAIException {
- assertEquals("certificates", AAIApplicationConfig.get("server.certs.location"));
+ assertEquals("8446", AAIApplicationConfig.get("server.port"));
}
@Test
public void getIntValueWithDefaultTest() throws AAIException {
assertTrue(9999 == AAIApplicationConfig.getInt("non-existing-key", "9999"));
}
-
- @Test
- public void getValueWithReplacementTest() throws AAIException {
- assertEquals("/opt/app/aai/etc/auth/aai-client-cert.p12",
- AAIApplicationConfig.get("schema.service.ssl.key-store"));
- }
}
package org.onap.aai.util;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.aai.exceptions.AAIException;
public class AAIConfigTest {
- @Before
+ @BeforeEach
public void setup() throws AAIException {
AAIConfig.init();
}
package org.onap.aai.util;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.aai.exceptions.AAIException;
public class FormatDateTest {
package org.onap.aai.util;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import org.json.JSONObject;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
public class MapperUtilTest {
private JSONObject expectedJson;
private JSONObject sampleJson;
- @Before
+ @BeforeEach
public void setup() {
expectedJson = new JSONObject();
sampleJson = new JSONObject();
expectedJson.put("color", "black");
expectedJson.put("shape", "box");
SampleClass sample = new SampleClass("black", "box");
- Assert.assertEquals(expectedJson.toString(), MapperUtil.writeAsJSONString(sample));
+ Assertions.assertEquals(expectedJson.toString(), MapperUtil.writeAsJSONString(sample));
}
@Test
* 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.
package org.onap.logging.filter.base;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerResponseContext;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.UriInfo;
-
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
-@RunWith(MockitoJUnitRunner.class)
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.UriInfo;
+
+@ExtendWith(MockitoExtension.class)
public class AuditLogContainerFilterTest {
protected static final Logger logger = LoggerFactory.getLogger(AbstractMetricLogFilter.class);
@Mock
- private ContainerRequestContext containerRequest;
+ private jakarta.ws.rs.container.ContainerRequestContext containerRequest;
@Mock
private ContainerResponseContext containerResponse;
@InjectMocks
private AuditLogContainerFilter auditLogContainerFilter;
- @After
+ @AfterEach
public void tearDown() {
MDC.clear();
}
* 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.
package org.onap.logging.filter.base;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.MDC;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class AuditLogServletFilterTest {
@Mock
@InjectMocks
private AuditLogServletFilter auditLogServletFilter;
- @After
+ @AfterEach
public void tearDown() {
MDC.clear();
}
* 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.
package org.onap.logging.filter.base;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
public class LoggingContainerFilterTest {
* 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.
package org.onap.logging.filter.base;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
import java.util.HashMap;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.MDC;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class MDCSetupTest extends MDCSetup {
@Mock
private String requestId = "4d31fe02-4918-4975-942f-fe51a44e6a9b";
private String invocationId = "4d31fe02-4918-4975-942f-fe51a44e6a9a";
- @After
+ @AfterEach
public void tearDown() {
MDC.clear();
System.clearProperty("partnerName");
* 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.
package org.onap.logging.filter.base;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.doReturn;
import java.net.URI;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
-import javax.ws.rs.client.ClientRequestContext;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.client.ClientRequestContext;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.MDC;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class MetricLogClientFilterTest {
@Mock
private ClientRequestContext clientRequest;
@InjectMocks
private MetricLogClientFilter metricLogClientFilter;
- @After
+ @AfterEach
public void tearDown() {
MDC.clear();
}
* 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.
package org.onap.logging.filter.base;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.net.URISyntaxException;
-import javax.ws.rs.client.ClientRequestContext;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.client.ClientRequestContext;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class PayloadLoggingClientFilterTest {
@Mock
* 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.
package org.onap.logging.filter.base;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
public class SimpleJaxrsHeadersMapTest {
* 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.
package org.onap.logging.filter.base;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class SimpleServletHeadersMapTest {
@Mock
import static org.hamcrest.core.IsSame.sameInstance;
import static org.hamcrest.core.StringEndsWith.endsWith;
import static org.hamcrest.number.OrderingComparison.lessThan;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-import javax.xml.bind.DatatypeConverter;
-
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.slf4j.event.Level;
import org.springframework.mock.web.MockHttpServletRequest;
+import jakarta.xml.bind.DatatypeConverter;
+
/**
* Tests for {@link ONAPLogAdapter}.
*/
/**
* Ensure that MDCs are cleared after each testcase.
*/
- @After
+ @AfterEach
public void resetMDCs() {
MDC.clear();
}
/**
* Test nullcheck.
*/
- @Test(expected = NullPointerException.class)
+ @Test
public void testCheckNotNull() {
+ assertThrows(NullPointerException.class, () ->
- ONAPLogAdapter.checkNotNull(null);
+ ONAPLogAdapter.checkNotNull(null));
}
/**
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
/**
* Tests for {@link ONAPLogConstants}.
*/
public class ONAPLogConstantsTest {
- @Rule
- public ExpectedException exceptionRule = ExpectedException.none();
-
@Test
public void testConstructors() throws Exception {
assertInaccessibleConstructor(ONAPLogConstants.class);
}
@Test
- public void testConstructorUnsupported() throws Exception {
- exceptionRule.expect(InvocationTargetException.class);
- exceptionRule.expectCause(instanceOf(UnsupportedOperationException.class));
- Constructor<?> c = ONAPLogConstants.class.getDeclaredConstructors()[0];
- c.setAccessible(true);
- c.newInstance();
+ public void testConstructorUnsupported() {
+ Throwable exception = assertThrows(InvocationTargetException.class, () -> {
+ Constructor<?> c = ONAPLogConstants.class.getDeclaredConstructors()[0];
+ c.setAccessible(true);
+ c.newInstance();
+ });
+ assertThat(exception.getCause(), instanceOf(UnsupportedOperationException.class));
}
@Test
}
- void assertInaccessibleConstructor(final Class<?> c) throws Exception {
- exceptionRule.expect(IllegalAccessException.class);
- // Should fail for hidden constructor.
- c.getDeclaredConstructors()[0].newInstance();
-
-
- exceptionRule.expect(InvocationTargetException.class);
- exceptionRule.expectCause(instanceOf(UnsupportedOperationException.class));
- final Constructor<?> constructor = c.getDeclaredConstructors()[0];
- constructor.setAccessible(true);
- constructor.newInstance();
+ void assertInaccessibleConstructor(final Class<?> c) {
+ Throwable exception = assertThrows(InvocationTargetException.class, () -> {
+ final Constructor<?> constructor = c.getDeclaredConstructors()[0];
+ constructor.setAccessible(true);
+ constructor.newInstance();
+ });
+ assertThat(exception.getCause(), instanceOf(UnsupportedOperationException.class));
}
}
# ============LICENSE_START=======================================================
# org.onap.aai
# ================================================================================
-# Copyright © 2017-18 AT&T Intellectual Property. All rights reserved.
+# Copyright � 2017-18 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.
server.port=8446
server.local.startpath=/opt/app/aai
schema.version.list=v10,v11,v12,v13,v14,v15,v16,v17,v18,v19
-server.certs.location=certificates
-server.ssl.key-store=keystore.jks
-server.ssl.key-store.pkcs12=keystore.pkcs12
-server.ssl.trust-store=truststore.jks
-schema.service.ssl.key-store=${server.local.startpath}/etc/auth/aai-client-cert.p12
-schema.service.ssl.trust-store=${server.local.startpath}/etc/auth/aai_keystore.jks
-
<property name="AJSC_HOME" value="${AJSC_HOME:-.}" />
<jmxConfigurator />
<property name="logDirectory" value="${AJSC_HOME}/logs" />
-
+
<property name="p_tim" value="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX", UTC}"/>
<property name="p_lvl" value="%level"/>
<property name="p_log" value="%logger"/>
</pattern>
</encoder>
</appender>
-
+
<appender name="asyncMETRIC" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>1000</queueSize>
<includeCallerData>true</includeCallerData>
<appender-ref ref="AUDIT" />
</appender>
-
+
<appender name="auth"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<logger name="ch.qos.logback.classic" level="WARN" />
<logger name="ch.qos.logback.core" level="WARN" />
-
+
<logger name="com.jayway.jsonpath" level="WARN" />
<logger name="org.apache" level="OFF" />
-
+
<logger name="org.onap.aai" level="DEBUG" additivity="false">
<appender-ref ref="STDOUT" />
</logger>
- <logger name="org.onap.aai.aaf.auth" level="DEBUG" additivity="false">
- <appender-ref ref="asyncAUTH" />
- </logger>
<logger name="org.onap.aai.logging.ErrorLogHelper" level="WARN">
<appender-ref ref="asyncERROR"/>
</logger>
<parent>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-parent</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
<relativePath>../aai-parent/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>aai-failover</artifactId>
<dependencies>
- <!-- Common logging framework -->
- <dependency>
- <groupId>org.onap.aai.logging-service</groupId>
- <artifactId>common-logging</artifactId>
- </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
- <version>${spring.version}</version>
</dependency>
<dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjrt</artifactId>
- <version>1.9.1</version>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
</dependency>
</dependencies>
</project>
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Value;
public boolean shouldRun() throws IOException {
- Path failoverPath = Paths.get(failoverPropertiesPath);
+ Path failoverPath = Path.of(failoverPropertiesPath);
if (Files.exists(failoverPath)) {
Properties properties = new Properties();
<parent>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-common</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
</parent>
<artifactId>aai-parent</artifactId>
<name>aai-parent</name>
</modules>
<properties>
+ <maven.compiler.release>11</maven.compiler.release>
<!-- update this just prior to release or figure out something with version.properties -->
<aai.release.version>${aai.common.version}</aai.release.version>
- <aai.common.logging.version>1.8.0</aai.common.logging.version>
- <aai.rest.client.version>1.6.4</aai.rest.client.version>
- <aai.schema.service.version>1.9.6</aai.schema.service.version>
+ <aai.schema.service.version>1.12.7</aai.schema.service.version>
- <aaf.version>2.1.15</aaf.version>
<antlr.version>4.11.1</antlr.version>
- <activemq.version>5.16.1</activemq.version>
- <codehaus.jackson.version>1.9.13</codehaus.jackson.version>
<commons.beanutils.version>1.9.4</commons.beanutils.version>
<commons.cli.version>1.5.0</commons.cli.version>
- <commons.compress.version>1.21</commons.compress.version>
- <commons.configuration.version>1.10</commons.configuration.version>
- <commons.io.version>2.11.0</commons.io.version>
- <commons.lang3.version>3.9</commons.lang3.version>
+ <commons.compress.version>1.27.1</commons.compress.version>
+ <commons.configuration2.version>2.10.1</commons.configuration2.version>
+ <commons.io.version>2.16.1</commons.io.version>
+ <commons.lang3.version>3.15.0</commons.lang3.version>
<commons.net.version>3.8.0</commons.net.version>
- <commons.text.version>1.10.0</commons.text.version>
+ <commons.text.version>1.13.0</commons.text.version>
<docker.fabric.version>0.40.2</docker.fabric.version>
- <easy.mock.version>5.0.0</easy.mock.version>
- <eclipse.persistence.version>2.7.11</eclipse.persistence.version>
- <eelf.core.version>2.0.0-oss</eelf.core.version>
- <freemarker.version>2.3.31</freemarker.version>
- <google.guava.version>31.1-jre</google.guava.version>
- <gremlin.version>3.2.11</gremlin.version>
- <groovy.version>2.5.15</groovy.version>
+ <eclipse.persistence.version>4.0.6</eclipse.persistence.version>
+ <google.guava.version>33.4.0-jre</google.guava.version>
+ <gremlin.version>3.7.3</gremlin.version>
+ <janusgraph.version>1.1.0</janusgraph.version>
<gson.version>2.9.1</gson.version>
- <hamcrest.junit.version>2.0.0.0</hamcrest.junit.version>
<hamcrest.core.version>2.2</hamcrest.core.version>
- <jackson.bom.version>2.11.4</jackson.bom.version>
- <janusgraph.version>0.2.3</janusgraph.version>
- <javatuples.version>1.2</javatuples.version>
<jaxb.version>2.3.1</jaxb.version>
- <old.jaxb.version>2.3.0.1</old.jaxb.version>
<jaxrs.version>2.1.1</jaxrs.version>
<jcommander.version>1.78</jcommander.version>
- <jersey.version>1.19.4</jersey.version>
<jnr.ffi.version>2.2.12</jnr.ffi.version>
- <jolt.version>0.1.7</jolt.version>
+ <jolt.version>0.1.8</jolt.version>
<jopt.simple.version>5.0.4</jopt.simple.version>
<jsonassert.version>1.5.1</jsonassert.version>
<json.patch.version>1.9</json.patch.version>
Please don't upgrade to 2.3.0 or above for nexus iq or security scans
as it could potentially break our code
-->
- <spring.boot.version>2.4.13</spring.boot.version>
- <spring.version>5.3.13</spring.version>
- <spring.jms.version>5.2.25.RELEASE</spring.jms.version>
- <spring.test.version>${spring.version}</spring.test.version>
+ <spring.boot.version>3.1.12</spring.boot.version>
<json.path.version>2.2.0</json.path.version>
- <json.version>20190722</json.version>
+ <json.version>20240303</json.version>
<junit.version>4.12</junit.version>
- <httpclient.version>4.5.13</httpclient.version>
- <io.swagger.version>1.5.24</io.swagger.version>
- <logback.version>1.2.7</logback.version>
- <slf4j.version>1.7.25</slf4j.version>
- <log4j.version>2.17.1</log4j.version>
+ <logback.version>1.4.14</logback.version>
+ <slf4j.version>2.0.17</slf4j.version>
<mockito.all.version>3.4.0</mockito.all.version>
<mockito.core.version>3.4.0</mockito.core.version>
- <netty.handler.version>4.1.63.Final</netty.handler.version>
- <netty.version>4.1.63.Final</netty.version>
<opencsv.version>3.1</opencsv.version>
<plexus.utils.version>3.1.1</plexus.utils.version>
<reflections.version>0.9.10</reflections.version>
- <snakeyaml.version>1.29</snakeyaml.version>
+ <lombok.version>1.18.38</lombok.version>
+ <testcontainers.version>1.20.4</testcontainers.version>
- <javax.servlet.version>3.1.0</javax.servlet.version>
+ <jakarta.servlet.version>3.1.0</jakarta.servlet.version>
<javax.annotation.version>1.2</javax.annotation.version>
<sonar.jacoco.reportPath />
<!-- we let things pass by default, set custom level for each child project -->
<jacoco.line.coverage.limit>0.00</jacoco.line.coverage.limit>
- <jacoco.version>0.8.5</jacoco.version>
+ <jacoco.version>0.8.13</jacoco.version>
<sonar-jacoco-listeners.version>3.2</sonar-jacoco-listeners.version>
<sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
<sonar.coverage.jacoco.xmlReportPaths>${project.reporting.outputDirectory}/jacoco-ut/jacoco.xml</sonar.coverage.jacoco.xmlReportPaths>
<sonar.scanner.version>3.7.0.1746</sonar.scanner.version>
- <spring.security.rsa.version>1.0.8.RELEASE</spring.security.rsa.version>
<json.simple.version>1.1.1</json.simple.version>
<aspectj.version>1.9.1</aspectj.version>
<logging.analytics.version>1.5.1</logging.analytics.version>
<dependencyManagement>
<dependencies>
- <dependency>
- <groupId>com.fasterxml.jackson</groupId>
- <artifactId>jackson-bom</artifactId>
- <version>${jackson.bom.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<type>pom</type>
<scope>import</scope>
</dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-framework-bom</artifactId>
- <version>${spring.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<type>pom</type>
<scope>import</scope>
</dependency>
- <!-- TODO: check if this can be updated to something > 1.0.8 -->
- <dependency>
- <groupId>org.springframework.security</groupId>
- <artifactId>spring-security-rsa</artifactId>
- <version>${spring.security.rsa.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jms</artifactId>
- <version>5.3.31</version>
- </dependency>
-
-
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<version>${aai.release.version}</version>
</dependency>
- <dependency>
- <groupId>org.onap.aai.aai-common</groupId>
- <artifactId>aai-aaf-auth</artifactId>
- <version>${aai.release.version}</version>
- </dependency>
-
<dependency>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-els-onap-logging</artifactId>
<version>${aai.release.version}</version>
</dependency>
- <dependency>
- <groupId>commons-configuration</groupId>
- <artifactId>commons-configuration</artifactId>
- <version>${commons.configuration.version}</version>
- </dependency>
-
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version>
</dependency>
- <dependency>
- <groupId>com.att.eelf</groupId>
- <artifactId>eelf-core</artifactId>
- <version>${eelf.core.version}</version>
- </dependency>
-
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<dependency>
- <groupId>org.hamcrest</groupId>
- <artifactId>java-hamcrest</artifactId>
- <version>${hamcrest.junit.version}</version>
+ <groupId>org.slf4j</groupId>
+ <artifactId>jcl-over-slf4j</artifactId>
+ <version>${slf4j.version}</version>
</dependency>
<dependency>
- <groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-core</artifactId>
- <version>${hamcrest.core.version}</version>
+ <groupId>org.slf4j</groupId>
+ <artifactId>jul-to-slf4j</artifactId>
+ <version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-junit</artifactId>
- <version>${hamcrest.junit.version}</version>
+ <artifactId>hamcrest-core</artifactId>
+ <version>${hamcrest.core.version}</version>
</dependency>
<dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
- <version>${javax.servlet.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.annotation</groupId>
- <artifactId>javax.annotation-api</artifactId>
- <version>${javax.annotation.version}</version>
+ <groupId>jakarta.annotation</groupId>
+ <artifactId>jakarta.annotation-api</artifactId>
+ <version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.janusgraph</groupId>
<artifactId>janusgraph-core</artifactId>
<version>${janusgraph.version}</version>
+ <exclusions>
+ <exclusion>
+ <!-- vulnerable dependency -->
+ <groupId>com.rabbitmq</groupId>
+ <artifactId>amqp-client</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.janusgraph</groupId>
- <artifactId>janusgraph-cassandra</artifactId>
+ <artifactId>janusgraph-cql</artifactId>
<version>${janusgraph.version}</version>
</dependency>
<dependency>
<groupId>org.janusgraph</groupId>
- <artifactId>janusgraph-cql</artifactId>
+ <artifactId>janusgraph-inmemory</artifactId>
<version>${janusgraph.version}</version>
</dependency>
<version>${gremlin.version}</version>
</dependency>
- <dependency>
- <groupId>org.codehaus.groovy</groupId>
- <artifactId>groovy</artifactId>
- <version>${groovy.version}</version>
- <classifier>indy</classifier>
- </dependency>
-
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
</dependency>
<dependency>
- <groupId>javax.xml.bind</groupId>
- <artifactId>jaxb-api</artifactId>
- <version>${jaxb.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.apache.activemq</groupId>
- <artifactId>activemq-broker</artifactId>
- <version>${activemq.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.apache.activemq</groupId>
- <artifactId>activemq-client</artifactId>
- <version>${activemq.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.apache.activemq</groupId>
- <artifactId>activemq-openwire-legacy</artifactId>
- <version>${activemq.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.onap.aaf.authz</groupId>
- <artifactId>aaf-cadi-core</artifactId>
- <version>${aaf.version}</version>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.onap.aaf.authz</groupId>
- <artifactId>aaf-cadi-aaf</artifactId>
- <version>${aaf.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.easymock</groupId>
- <artifactId>easymock</artifactId>
- <version>${easy.mock.version}</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>com.sun.xml.bind</groupId>
- <artifactId>jaxb-xjc</artifactId>
- <version>${old.jaxb.version}</version>
- </dependency>
-
- <dependency>
- <groupId>com.sun.xml.bind</groupId>
- <artifactId>jaxb-impl</artifactId>
- <version>${old.jaxb.version}</version>
+ <groupId>jakarta.xml.bind</groupId>
+ <artifactId>jakarta.xml.bind-api</artifactId>
+ <version>4.0.2</version>
</dependency>
-
<dependency>
- <groupId>com.sun.xml.bind</groupId>
- <artifactId>jaxb-core</artifactId>
- <version>${old.jaxb.version}</version>
+ <groupId>org.glassfish.jaxb</groupId>
+ <artifactId>jaxb-runtime</artifactId>
+ <version>3.0.1</version>
</dependency>
<dependency>
<version>${json.path.version}</version>
</dependency>
- <dependency>
- <groupId>org.javatuples</groupId>
- <artifactId>javatuples</artifactId>
- <version>${javatuples.version}</version>
- </dependency>
-
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${commons.text.version}</version>
</dependency>
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-core-asl</artifactId>
- <version>${codehaus.jackson.version}</version>
- </dependency>
-
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-core</artifactId>
- <version>${jersey.version}</version>
- </dependency>
-
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-client</artifactId>
- <version>${jersey.version}</version>
- </dependency>
-
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-json</artifactId>
- <version>${jersey.version}</version>
- </dependency>
-
- <dependency>
- <groupId>javax.ws.rs</groupId>
- <artifactId>javax.ws.rs-api</artifactId>
- <version>${jaxrs.version}</version>
- </dependency>
-
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>${opencsv.version}</version>
</dependency>
- <dependency>
- <groupId>org.apache.logging.log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>${log4j.version}</version>
- <type>pom</type>
- </dependency>
-
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
-
- <dependency>
- <groupId>org.onap.aai.logging-service</groupId>
- <artifactId>common-logging</artifactId>
- <version>${aai.common.logging.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.onap.aai.logging-service</groupId>
- <artifactId>logging-api</artifactId>
- <version>${aai.common.logging.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.onap.logging-analytics</groupId>
- <artifactId>logging-slf4j</artifactId>
- <version>${logging.analytics.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.onap.aai</groupId>
- <artifactId>rest-client</artifactId>
- <version>${aai.rest.client.version}</version>
- </dependency>
-
<dependency>
<groupId>net.sf.jopt-simple</groupId>
<artifactId>jopt-simple</artifactId>
</dependency>
<dependency>
- <groupId>io.swagger</groupId>
+ <groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-core</artifactId>
- <version>${io.swagger.version}</version>
+ <version>2.2.29</version>
</dependency>
<dependency>
</dependency>
<dependency>
- <groupId>io.swagger</groupId>
+ <groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-annotations</artifactId>
- <version>${io.swagger.version}</version>
+ <version>2.2.25</version>
</dependency>
<dependency>
<artifactId>swagger-jersey-jaxrs</artifactId>
<version>${io.swagger.version}</version>
</dependency>
-
- <dependency>
- <groupId>io.netty</groupId>
- <artifactId>netty-handler</artifactId>
- <version>${netty.handler.version}</version>
- </dependency>
-
- <dependency>
- <groupId>io.netty</groupId>
- <artifactId>netty-all</artifactId>
- <version>${netty.version}</version>
- </dependency>
-
<dependency>
<groupId>org.onap.aai.schema-service</groupId>
<artifactId>aai-schema</artifactId>
<version>${aai.schema.service.version}</version>
</dependency>
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- <version>${httpclient.version}</version>
- </dependency>
-
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
</dependency>
<dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- <version>${snakeyaml.version}</version>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-compress</artifactId>
+ <version>${commons.compress.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
- <artifactId>commons-compress</artifactId>
- <version>${commons.compress.version}</version>
+ <artifactId>commons-configuration2</artifactId>
+ <version>${commons.configuration2.version}</version>
</dependency>
<dependency>
<version>${commons.net.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.projectlombok</groupId>
+ <artifactId>lombok</artifactId>
+ <version>${lombok.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
</dependencies>
</dependencyManagement>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
- <version>3.0.0-M4</version>
+ <version>3.1.2</version>
<configuration>
<!-- Sets the VM argument line used when unit tests are run. -->
<argLine>${surefireArgLine}</argLine>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
- <version>3.0.0-M4</version>
+ <version>3.1.2</version>
<executions>
<!-- Ensures that both integration-test and verify goals of the Failsafe
Maven plugin are executed. -->
</execution>
</executions>
</plugin>
- <plugin>
- <groupId>org.sonarsource.scanner.maven</groupId>
- <artifactId>sonar-maven-plugin</artifactId>
- <version>${sonar.scanner.version}</version>
- </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
- <version>3.0.0</version>
+ <version>3.3.1</version>
<configuration>
<skip>True</skip>
</configuration>
<parent>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-parent</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
<relativePath>../aai-parent/pom.xml</relativePath>
</parent>
<artifactId>aai-rest</artifactId>
<properties>
<onap.nexus.url>https://nexus.onap.org</onap.nexus.url>
- <spring.boot.starter.web.version>1.5.21.RELEASE</spring.boot.starter.web.version>
- <spring.boot.starter.parent.version>1.5.21.RELEASE</spring.boot.starter.parent.version>
- <spring.security.version>1.0.8.RELEASE</spring.security.version>
</properties>
<dependencies>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
- <dependency>
- <groupId>com.att.eelf</groupId>
- <artifactId>eelf-core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- <exclusions>
- <exclusion>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-tomcat</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.slf4j</groupId>
- <artifactId>log4j-over-slf4j</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-jetty</artifactId>
- </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-jersey</artifactId>
+ <artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
- <groupId>javax.ws.rs</groupId>
- <artifactId>javax.ws.rs-api</artifactId>
+ <groupId>jakarta.ws.rs</groupId>
+ <artifactId>jakarta.ws.rs-api</artifactId>
</dependency>
<dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- </dependency>
- <!--
- Explicitly stating the security spring framework and
- exclude the bouncy castle since that is somehow overwriting
- our p12 file decryption that's built into java security
- This will cause the password is incorrect
- This needs to be added back if org.bouncy castle dependency
- sneaks backs in and causing issues with the two way ssl
- -->
- <dependency>
- <groupId>org.springframework.security</groupId>
- <artifactId>spring-security-rsa</artifactId>
- <exclusions>
- <exclusion>
- <groupId>org.bouncycastle</groupId>
- <artifactId>bcpkix-jdk15on</artifactId>
- </exclusion>
- </exclusions>
+ <groupId>org.apache.httpcomponents.client5</groupId>
+ <artifactId>httpclient5</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-test</artifactId>
- <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>com.vaadin.external.google</groupId>
+ <artifactId>android-json</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.onap.aai.aai-common</groupId>
<scope>compile</scope>
<exclusions>
<exclusion>
- <groupId>javax.ws.rs</groupId>
- <artifactId>javax.ws.rs-api</artifactId>
+ <groupId>jakarta.ws.rs</groupId>
+ <artifactId>jakarta.ws.rs-api</artifactId>
</exclusion>
</exclusions>
</dependency>
+ <dependency>
+ <groupId>org.projectlombok</groupId>
+ <artifactId>lombok</artifactId>
+ <scope>provided</scope>
+ </dependency>
</dependencies>
</project>
import java.util.Collections;
import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
-import org.springframework.context.annotation.Conditional;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
@ConditionalOnExpression("${aai-rest-client.enabled:false}")
public class AAIRestClient extends TwoWaySSLRestClient {
- private static Logger logger = LoggerFactory.getLogger(AAIRestClient.class);
-
@Value("${aai.base.url}")
private String baseUrl;
- @Value("${aai.ssl.key-store}")
- private String keystorePath;
-
- @Value("${aai.ssl.trust-store}")
- private String truststorePath;
-
- @Value("${aai.ssl.key-store-password}")
- private String keystorePassword;
-
- @Value("${aai.ssl.trust-store-password}")
- private String truststorePassword;
-
@Override
public String getBaseUrl() {
return baseUrl;
}
- @Override
- protected String getKeystorePath() {
- return keystorePath;
- }
-
- @Override
- protected String getTruststorePath() {
- return truststorePath;
- }
-
- @Override
- protected char[] getKeystorePassword() {
- return keystorePassword.toCharArray();
- }
-
- @Override
- protected char[] getTruststorePassword() {
- return truststorePassword.toCharArray();
- }
-
@Override
public MultiValueMap<String, String> getHeaders(Map<String, String> headers) {
HttpHeaders httpHeaders = new HttpHeaders();
package org.onap.aai.restclient;
-import javax.annotation.PostConstruct;
-
-import org.apache.http.client.HttpClient;
-import org.apache.http.impl.client.HttpClients;
+import jakarta.annotation.PostConstruct;
+import org.apache.hc.client5.http.classic.HttpClient;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.onap.aai.aailog.filter.RestClientLoggingInterceptor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
public abstract class NoAuthRestClient extends RestClient {
- private static Logger logger = LoggerFactory.getLogger(NoAuthRestClient.class);
-
protected RestTemplate restTemplate;
@PostConstruct
package org.onap.aai.restclient;
-import javax.annotation.PostConstruct;
+import jakarta.annotation.PostConstruct;
+import org.apache.hc.client5.http.classic.HttpClient;
+
import javax.net.ssl.SSLContext;
-import org.apache.http.client.HttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.ssl.SSLContextBuilder;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
+import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
import org.onap.aai.aailog.filter.RestClientLoggingInterceptor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
-import org.springframework.util.ResourceUtils;
import org.springframework.web.client.RestTemplate;
public abstract class OneWaySSLRestClient extends RestClient {
- private static Logger logger = LoggerFactory.getLogger(OneWaySSLRestClient.class);
-
private RestTemplate restTemplate;
@PostConstruct
}
protected HttpClient getClient() throws Exception {
-
- char[] trustStorePassword = getTruststorePassword();
-
- String trustStore = getTruststorePath();
-
- SSLContext sslContext = SSLContextBuilder.create()
- .loadTrustMaterial(ResourceUtils.getFile(trustStore), trustStorePassword).build();
-
- HttpClient client =
- HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier((s, sslSession) -> true).build();
-
- return client;
+ SSLContext sslContext = SSLContext.getDefault();
+ PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
+ .setSSLSocketFactory(
+ SSLConnectionSocketFactoryBuilder.create()
+ .setSslContext(sslContext)
+ .build()
+ )
+ .build();
+ return HttpClients
+ .custom()
+ .setConnectionManager(connectionManager)
+ .build();
}
- protected abstract String getTruststorePath();
-
- protected abstract char[] getTruststorePassword();
-
@Override
public RestTemplate getRestTemplate() {
return restTemplate;
}
-
}
+++ /dev/null
-/**
- * ============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.restclient;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.charset.Charset;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.commons.io.IOUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.ApplicationContextInitializer;
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.core.env.ConfigurableEnvironment;
-import org.springframework.core.env.EnumerablePropertySource;
-import org.springframework.core.env.MapPropertySource;
-import org.springframework.core.env.PropertySource;
-
-public class PropertyPasswordConfiguration implements ApplicationContextInitializer<ConfigurableApplicationContext> {
-
- private static final Pattern decodePasswordPattern = Pattern.compile("password\\((.*?)\\)");
- private PasswordDecoder passwordDecoder = new JettyPasswordDecoder();
- private static final Logger logger = LoggerFactory.getLogger(PropertyPasswordConfiguration.class.getName());
-
- @Override
- public void initialize(ConfigurableApplicationContext applicationContext) {
- ConfigurableEnvironment environment = applicationContext.getEnvironment();
- String certPath = environment.getProperty("server.certs.location");
- File passwordFile = null;
- File passphrasesFile = null;
- InputStream passwordStream = null;
- InputStream passphrasesStream = null;
- Map<String, Object> sslProps = new LinkedHashMap<>();
-
- // Override the passwords from application.properties if we find AAF certman files
- if (certPath != null) {
- try {
- passwordFile = new File(certPath + ".password");
- passwordStream = new FileInputStream(passwordFile);
-
- if (passwordStream != null) {
- String keystorePassword = null;
-
- keystorePassword = IOUtils.toString(passwordStream, Charset.defaultCharset());
- if (keystorePassword != null) {
- keystorePassword = keystorePassword.trim();
- }
- sslProps.put("server.ssl.key-store-password", keystorePassword);
- sslProps.put("schema.service.ssl.key-store-password", keystorePassword);
- sslProps.put("validation.service.ssl.key-store-password", keystorePassword);
- } else {
- logger.info("Not using AAF Certman password file");
- }
- } catch (IOException e) {
- logger.warn("Not using AAF Certman password file, e=" + e.getMessage());
- } finally {
- if (passwordStream != null) {
- try {
- passwordStream.close();
- } catch (Exception e) {
- }
- }
- }
- try {
- passphrasesFile = new File(certPath + ".passphrases");
- passphrasesStream = new FileInputStream(passphrasesFile);
-
- if (passphrasesStream != null) {
- String truststorePassword = null;
- Properties passphrasesProps = new Properties();
- passphrasesProps.load(passphrasesStream);
- truststorePassword = passphrasesProps.getProperty("cadi_truststore_password");
- if (truststorePassword != null) {
- truststorePassword = truststorePassword.trim();
- }
- sslProps.put("server.ssl.trust-store-password", truststorePassword);
- sslProps.put("schema.service.ssl.trust-store-password", truststorePassword);
- sslProps.put("validation.service.ssl.trust-store-password", truststorePassword);
- } else {
- logger.info("Not using AAF Certman passphrases file");
- }
- } catch (IOException e) {
- logger.warn("Not using AAF Certman passphrases file, e=" + e.getMessage());
- } finally {
- if (passphrasesStream != null) {
- try {
- passphrasesStream.close();
- } catch (Exception e) {
- }
- }
- }
- }
- for (PropertySource<?> propertySource : environment.getPropertySources()) {
- Map<String, Object> propertyOverrides = new LinkedHashMap<>();
- decodePasswords(propertySource, propertyOverrides);
- if (!propertyOverrides.isEmpty()) {
- PropertySource<?> decodedProperties =
- new MapPropertySource("decoded " + propertySource.getName(), propertyOverrides);
- environment.getPropertySources().addBefore(propertySource.getName(), decodedProperties);
- }
-
- }
- if (!sslProps.isEmpty()) {
- logger.info("Using AAF Certman files");
- PropertySource<?> additionalProperties = new MapPropertySource("additionalProperties", sslProps);
- environment.getPropertySources().addFirst(additionalProperties);
- }
- }
-
- private void decodePasswords(PropertySource<?> source, Map<String, Object> propertyOverrides) {
- if (source instanceof EnumerablePropertySource) {
- EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource<?>) source;
- for (String key : enumerablePropertySource.getPropertyNames()) {
- Object rawValue = source.getProperty(key);
- if (rawValue instanceof String) {
- String decodedValue = decodePasswordsInString((String) rawValue);
- propertyOverrides.put(key, decodedValue);
- }
- }
- }
- }
-
- private String decodePasswordsInString(String input) {
- if (input == null)
- return null;
- StringBuffer output = new StringBuffer();
- Matcher matcher = decodePasswordPattern.matcher(input);
- while (matcher.find()) {
- String replacement = passwordDecoder.decode(matcher.group(1));
- matcher.appendReplacement(output, replacement);
- }
- matcher.appendTail(output);
- return output.toString();
- }
-
-}
HttpEntity<String> httpEntity;
log.debug("Headers: " + headers.toString());
if (body == null) {
- httpEntity = new HttpEntity(getHeaders(headers));
+ httpEntity = new HttpEntity<String>(getHeaders(headers));
} else {
- httpEntity = new HttpEntity(body, getHeaders(headers));
+ httpEntity = new HttpEntity<String>(body, getHeaders(headers));
}
String url = getBaseUrl() + uri;
return getRestTemplate().exchange(url, method, httpEntity, Resource.class);
package org.onap.aai.restclient;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.security.KeyStore;
+import jakarta.annotation.PostConstruct;
+import org.apache.hc.client5.http.classic.HttpClient;
-import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
-import org.apache.http.client.HttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.ssl.SSLContextBuilder;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
+import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
+import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
+import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.onap.aai.aailog.filter.RestClientLoggingInterceptor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
-import org.springframework.util.ResourceUtils;
import org.springframework.web.client.RestTemplate;
public abstract class TwoWaySSLRestClient extends RestClient {
- private static Logger logger = LoggerFactory.getLogger(TwoWaySSLRestClient.class);
-
private RestTemplate restTemplate;
@PostConstruct
protected HttpClient getClient() throws Exception {
- char[] keyStorePassword = getKeystorePassword();
- char[] trustStorePassword = getTruststorePassword();
-
- String keyStore = getKeystorePath();
- String trustStore = getTruststorePath();
-
- SSLContext sslContext =
- SSLContextBuilder.create().loadKeyMaterial(loadPfx(keyStore, keyStorePassword), keyStorePassword)
- .loadTrustMaterial(ResourceUtils.getFile(trustStore), trustStorePassword).build();
-
- HttpClient client =
- HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier((s, sslSession) -> true).build();
+ SSLContext sslContext = SSLContext.getDefault();
+ PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
+ .setSSLSocketFactory(
+ SSLConnectionSocketFactoryBuilder.create()
+ .setSslContext(sslContext)
+ .build()
+ )
+ .build();
+ HttpClient client = HttpClients
+ .custom()
+ .setConnectionManager(connectionManager)
+ .build();
return client;
}
- private KeyStore loadPfx(String file, char[] password) throws Exception {
- KeyStore keyStore = KeyStore.getInstance("PKCS12");
- File key = ResourceUtils.getFile(file);
- try (InputStream in = new FileInputStream(key)) {
- keyStore.load(in, password);
- }
- return keyStore;
- }
-
- protected abstract String getKeystorePath();
-
- protected abstract String getTruststorePath();
-
- protected abstract char[] getTruststorePassword();
-
- protected abstract char[] getKeystorePassword();
-
@Override
public RestTemplate getRestTemplate() {
return restTemplate;
package org.onap.aai.restclient;
-public class RestClientTest {
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
+public class RestClientTest {
+ @Test
+ public void test() {
+ assertTrue(true);
+ }
}
<parent>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-parent</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
<relativePath>../aai-parent/pom.xml</relativePath>
</parent>
</exclusion>
</exclusions>
</dependency>
- <dependency>
- <groupId>org.onap.aai.logging-service</groupId>
- <artifactId>common-logging</artifactId>
- </dependency>
- <dependency>
- <groupId>com.att.eelf</groupId>
- <artifactId>eelf-core</artifactId>
- <version>1.0.1-oss</version>
- <exclusions>
- <exclusion>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-module-junit4</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.onap.aai.logging-service</groupId>
- <artifactId>logging-api</artifactId>
- </dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
</dependency>
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-core-asl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-asl</artifactId>
- </dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
- <groupId>org.onap.aai</groupId>
- <artifactId>rest-client</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
+ <artifactId>mockito-junit-jupiter</artifactId>
+ <version>5.18.0</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.projectlombok</groupId>
+ <artifactId>lombok</artifactId>
+ <scope>provided</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
package org.onap.aai.schemaif;
+import java.io.Serial;
+
public class SchemaProviderException extends Exception {
+ @Serial
private static final long serialVersionUID = 8162385108397238865L;
public SchemaProviderException() {
package org.onap.aai.schemaif;
-import com.att.eelf.i18n.EELFResourceManager;
-
-import org.onap.aai.cl.eelf.LogMessageEnum;
-
-public enum SchemaProviderMsgs implements LogMessageEnum {
+public enum SchemaProviderMsgs {
SCHEMA_LOAD_ERROR, LOADED_SCHEMA_FILE, LOADED_DB_RULE_FILE;
-
- static {
- EELFResourceManager.loadMessageBundle("logging/SchemaProviderMsgs");
- }
}
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
-import org.onap.aai.cl.api.Logger;
-import org.onap.aai.cl.eelf.LoggerFactory;
import org.onap.aai.schemaif.SchemaProvider;
import org.onap.aai.schemaif.SchemaProviderException;
-import org.onap.aai.schemaif.SchemaProviderMsgs;
import org.onap.aai.schemaif.definitions.EdgeSchema;
import org.onap.aai.schemaif.definitions.VertexSchema;
import org.onap.aai.schemaif.json.definitions.JsonEdgeSchema;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
public class JsonSchemaProvider implements SchemaProvider {
- // Logger logger = LoggerFactory.getInstance().getLogger(JsonSchemaProvider.class.getName());
- Logger logger = LoggerFactory.getInstance().getLogger(SchemaProvider.class);
private JsonSchemaProviderConfig config;
private Map<String, SchemaInstance> schemaCache = new ConcurrentHashMap<>();
public JsonSchemaProvider(JsonSchemaProviderConfig config) {
this.config = config;
- SecureClientHttpRequestFactory fac = new SecureClientHttpRequestFactory(config);
- fac.setBufferRequestBody(false);
- this.restTemplate = new RestTemplate(fac);
+ this.restTemplate = new RestTemplate();
}
@Override
ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class);
if (response.getStatusCodeValue() == HttpStatus.NOT_FOUND.value()) {
- logger.warn(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "version " + version + " not found");
+ log.warn("PVD0500E | Unable to load schema: {}", "version " + version + " not found");
throw new SchemaProviderException("Schema version " + version + " not found");
} else if (response.getStatusCodeValue() != HttpStatus.OK.value()) {
- logger.error(SchemaProviderMsgs.SCHEMA_LOAD_ERROR,
- "failed to load version " + version + ": " + response.getBody());
+ log.error("PVD0500E | Unable to load schema: {}", "version " + version + " not found");
throw new SchemaProviderException("Error getting schema version " + version + ":" + response.getBody());
}
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
- logger.error(SchemaProviderMsgs.SCHEMA_LOAD_ERROR,
- "failed to load version " + version + ": " + response.getBody() + "\n" + writer.toString());
+ log.error("PVD0500E | Unable to load schema: {}", "failed to load version: " + version + ": "+ response.getBody() + "\n" + writer.toString());
throw new SchemaProviderException("Error loading schema version " + version + ":" + ex.getMessage());
}
- logger.info(SchemaProviderMsgs.LOADED_SCHEMA_FILE, version);
+ log.info("PVD0001I|Successfully loaded schema: {}", version);
}
static final int BUFFER = 512;
+++ /dev/null
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * Copyright © 2017-2018 European Software Marketing Ltd.
- * ================================================================================
- * 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.schemaif.json;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.net.HttpURLConnection;
-import java.security.KeyStore;
-import java.security.cert.X509Certificate;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-
-import org.springframework.http.client.SimpleClientHttpRequestFactory;
-
-public class SecureClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
-
- private static final String SSL_PROTOCOL = "TLS";
- private static final String KEYSTORE_ALGORITHM = "SunX509";
- private static final String KEYSTORE_TYPE = "PKCS12";
- private JsonSchemaProviderConfig config;
-
- public SecureClientHttpRequestFactory(JsonSchemaProviderConfig config) {
- super();
- this.config = config;
- }
-
- @Override
- protected void prepareConnection(final HttpURLConnection connection, final String httpMethod) throws IOException {
- if (connection instanceof HttpsURLConnection) {
- ((HttpsURLConnection) connection).setSSLSocketFactory(getSSLContext().getSocketFactory());
- ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {
- @Override
- public boolean verify(String str, SSLSession sslSession) {
- return true;
- }
- });
- } else {
-
- throw new IOException();
- }
- super.prepareConnection(connection, httpMethod);
- }
-
- protected SSLContext getSSLContext() throws IOException {
- try {
- TrustManager[] trustAllCerts = null;
-
- // We aren't validating certificates, so create a trust manager that
- // does
- // not validate certificate chains.
- trustAllCerts = new TrustManager[] {new X509TrustManager() {
- public X509Certificate[] getAcceptedIssuers() {
- return null;
- }
-
- public void checkClientTrusted(X509Certificate[] certs, String authType) {
- }
-
- public void checkServerTrusted(X509Certificate[] certs, String authType) {
- }
- }};
-
- SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL);
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYSTORE_ALGORITHM);
- KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
-
- char[] pwd = null;
- if (config.getSchemaServiceCertPwd() != null) {
- pwd = config.getSchemaServiceCertPwd().toCharArray();
- }
-
- if (config.getSchemaServiceCertFile() != null) {
- try (FileInputStream fin = new FileInputStream(config.getSchemaServiceCertFile())) {
- // Load the keystore and initialize the key manager factory.
- ks.load(fin, pwd);
- kmf.init(ks, pwd);
-
- ctx.init(kmf.getKeyManagers(), trustAllCerts, null);
- }
- } else {
- ctx.init(null, trustAllCerts, null);
- }
-
- return ctx;
- } catch (Exception e) {
- throw new IOException("Problem with getting the SSL Context::" + e.getMessage(), e);
- }
-
- }
-
-}
import com.google.common.collect.Multimap;
+import lombok.extern.slf4j.Slf4j;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.stream.Collectors;
import org.apache.commons.io.IOUtils;
-import org.onap.aai.cl.api.Logger;
-import org.onap.aai.cl.eelf.LoggerFactory;
import org.onap.aai.edges.EdgeIngestor;
import org.onap.aai.edges.EdgeRule;
import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.schemaif.SchemaProviderException;
-import org.onap.aai.schemaif.SchemaProviderMsgs;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.Translator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
+@Slf4j
@Component
public class OxmEdgeRulesLoader {
final static Pattern propsFilePattern = Pattern.compile(propsPrefix + "(.*)" + propsSuffix);
final static Pattern propsVersionPattern = Pattern.compile("(?i)v\\d*");
- private static Logger logger = LoggerFactory.getInstance().getLogger(OxmEdgeRulesLoader.class.getName());
-
private OxmEdgeRulesLoader() {
}
public static synchronized void loadModels() throws SchemaProviderException {
Map<String, File> propFiles = edgePropertyFiles(edgePropsConfiguration);
- if (logger.isDebugEnabled()) {
- logger.debug("Loading DB Edge Rules");
+ if (log.isDebugEnabled()) {
+ log.debug("Loading DB Edge Rules");
}
for (String version : OxmSchemaLoader.getLoadedOXMVersions()) {
public static synchronized void loadModels(String v) throws SchemaProviderException {
Map<String, File> propFiles = edgePropertyFiles(edgePropsConfiguration);
- if (logger.isDebugEnabled()) {
- logger.debug("Loading DB Edge Rules ");
+ if (log.isDebugEnabled()) {
+ log.debug("Loading DB Edge Rules ");
}
try {
if (versionContextMap == null || versionContextMap.isEmpty()) {
loadModels();
} else if (!versionContextMap.containsKey(version)) {
- logger.error(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "Error loading DB Edge Rules for: " + version);
+ log.error("PVD0500E | Unable to load schema: {}", "Error loading DB Edge Rules for: " + version);
throw new SchemaProviderException("Error loading DB Edge Rules for: " + version);
}
// If there are still no models available, then there's not much we can do...
if (versionContextMap.isEmpty()) {
- logger.error(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "No available DB Edge Rules to get latest version for.");
+ log.error("PVD0500E | Unable to load schema: {}", "No available DB Edge Rules to get latest version for.");
throw new SchemaProviderException("No available DB Edge Rules to get latest version for.");
}
if (edges != null) {
RelationshipSchema rs = new RelationshipSchema(edges, edgeProps);
versionContextMap.put(version.toString().toLowerCase(), rs);
- logger.info(SchemaProviderMsgs.LOADED_DB_RULE_FILE, version.toString());
+ log.info("PVD0002I|Successfully loaded DB Edge Rule and Edge Properties for: {}", version);
}
}
import org.eclipse.persistence.dynamic.DynamicType;
import org.eclipse.persistence.internal.oxm.mappings.Descriptor;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
-import org.onap.aai.cl.eelf.LoggerFactory;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.schemaif.SchemaProviderException;
-import org.onap.aai.schemaif.SchemaProviderMsgs;
import org.onap.aai.schemaif.definitions.VertexSchema;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.Translator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
+import lombok.extern.slf4j.Slf4j;
+
/**
* This class contains all of the logic for importing OXM model schemas from the available OXM
* schema files.
*/
+@Slf4j
@Component
public class OxmSchemaLoader {
final static Pattern versionPattern = Pattern.compile("(?i)v(\\d*)");
- private static org.onap.aai.cl.api.Logger logger =
- LoggerFactory.getInstance().getLogger(OxmSchemaLoader.class.getName());
-
private OxmSchemaLoader() {
}
*
*/
public synchronized static void loadModels() throws SchemaProviderException {
- if (logger.isDebugEnabled()) {
- logger.debug("Loading OXM Models");
+ if (log.isDebugEnabled()) {
+ log.debug("Loading OXM Models");
}
for (SchemaVersion oxmVersion : translator.getSchemaVersions().getVersions()) {
versionContextMap.put(oxmVersion, jaxbContext);
loadXmlLookupMap(oxmVersion, jaxbContext);
loadVertexLookupMap(oxmVersion, jaxbContext);
- logger.info(SchemaProviderMsgs.LOADED_SCHEMA_FILE, oxmVersion);
+ log.info("PVD0001I|Successfully loaded schema: {}", oxmVersion);
}
/**
}
// If there are still no models available, then there's not much we can do...
if (versionContextMap.isEmpty()) {
- logger.error(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "No available OXM schemas to get versions for.");
+ log.error("PVD0500E|Unable to load schema: No available OXM schemas to get versions for.");
throw new SchemaProviderException("No available OXM schemas to get latest version for.");
}
List<String> versions = new ArrayList<String>();
package org.onap.aai.schemaif.oxm;
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Multimap;
+import lombok.extern.slf4j.Slf4j;
+
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.stream.Collectors;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.onap.aai.cl.eelf.LoggerFactory;
import org.onap.aai.edges.EdgeRule;
import org.onap.aai.schemaif.SchemaProviderException;
-import org.onap.aai.schemaif.SchemaProviderMsgs;
+@Slf4j
public class RelationshipSchema {
public static final String SCHEMA_SOURCE_NODE_TYPE = "from";
public static final String SCHEMA_RELATIONSHIP_TYPE = "label";
public static final String SCHEMA_RULES_ARRAY = "rules";
- private static org.onap.aai.cl.api.Logger logger =
- LoggerFactory.getInstance().getLogger(RelationshipSchema.class.getName());
-
private Map<String, Map<String, Class<?>>> relations = new HashMap<>();
/**
* Hashmap of valid relationship types along with properties.
try {
return resolveClass(p.getValue());
} catch (SchemaProviderException | ClassNotFoundException e) {
- logger.error(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "Error in RelationshipSchema: " + e);
+ log.error("PVD0500E|Unable to load schema: {}", "Error in RelationshipSchema: " + e);
}
return null;
}));
try {
return resolveClass(p.getValue());
} catch (SchemaProviderException | ClassNotFoundException e) {
- logger.error(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "Error in RelationshipSchema: " + e);
+ log.error("PVD0500E|Unable to load schema: {}", "Error in RelationshipSchema: " + e);
}
return null;
}));
+++ /dev/null
-
-## Error Logs
-SCHEMA_LOAD_ERROR=\
- PVD0500E|\
- Unable to load schema: {0}
-
-## Info Logs
-LOADED_SCHEMA_FILE=\
- PVD0001I|\
- Successfully loaded schema: {0}
-
-LOADED_DB_RULE_FILE=\
- PVD0002I|\
- Successfully loaded DB Edge Rule and Edge Properties for: {0}
-
-
package org.onap.aai.schemaif.json;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
-import java.nio.file.Paths;
+import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.aai.schemaif.SchemaProviderException;
import org.onap.aai.schemaif.definitions.EdgeSchema;
import org.onap.aai.schemaif.definitions.PropertySchema;
JsonSchemaProviderConfig config = new JsonSchemaProviderConfig();
- @Before
+ @BeforeEach
public void init() {
config.setSchemaServiceBaseUrl("https://testurl.com:8443");
config.setSchemaServiceCertFile("/c/certfile");
ByteArrayOutputStream fos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(fos);
zos.putNextEntry(new ZipEntry("schemaServiceResponse.json"));
- byte[] fileData = Files.readAllBytes(Paths.get("src/test/resources/json/schemaServiceResponse.json"));
+ byte[] fileData = Files.readAllBytes(Path.of("src/test/resources/json/schemaServiceResponse.json"));
zos.write(fileData, 0, fileData.length);
zos.closeEntry();
zos.close();
}
}
- @Test(expected = SchemaProviderException.class)
- public void testSchemaValidateBadEdge() throws SchemaProviderException {
- SchemaServiceResponse schema;
-
- try {
- String testSchema = readFile("src/test/resources/json/badEdgeSchema.json");
- schema = SchemaServiceResponse.fromJson(testSchema);
- } catch (Exception ex) {
- fail();
- return;
- }
+ @Test
+ public void testSchemaValidateBadEdge() {
+ assertThrows(SchemaProviderException.class, () -> {
+ SchemaServiceResponse schema;
+
+ try {
+ String testSchema = readFile("src/test/resources/json/badEdgeSchema.json");
+ schema = SchemaServiceResponse.fromJson(testSchema);
+ } catch (Exception ex) {
+ fail();
+ return;
+ }
- schema.getData().validate();
+ schema.getData().validate();
+ });
}
- @Test(expected = SchemaProviderException.class)
- public void testSchemaValidateBadVertex() throws SchemaProviderException {
- SchemaServiceResponse schema;
-
- try {
- String testSchema = readFile("src/test/resources/json/badVertexSchema.json");
- schema = SchemaServiceResponse.fromJson(testSchema);
- } catch (Exception ex) {
- fail();
- return;
- }
+ @Test
+ public void testSchemaValidateBadVertex() {
+ assertThrows(SchemaProviderException.class, () -> {
+ SchemaServiceResponse schema;
+
+ try {
+ String testSchema = readFile("src/test/resources/json/badVertexSchema.json");
+ schema = SchemaServiceResponse.fromJson(testSchema);
+ } catch (Exception ex) {
+ fail();
+ return;
+ }
- System.out.println("Validate");
- schema.getData().validate();
- System.out.println("Validate done");
+ System.out.println("Validate");
+ schema.getData().validate();
+ System.out.println("Validate done");
+ });
}
- @Test(expected = SchemaProviderException.class)
- public void testSchemaValidateBadType() throws SchemaProviderException {
- SchemaServiceResponse schema;
-
- try {
- String testSchema = readFile("src/test/resources/json/badTypeSchema.json");
- schema = SchemaServiceResponse.fromJson(testSchema);
- } catch (Exception ex) {
- fail();
- return;
- }
+ @Test
+ public void testSchemaValidateBadType() {
+ assertThrows(SchemaProviderException.class, () -> {
+ SchemaServiceResponse schema;
+
+ try {
+ String testSchema = readFile("src/test/resources/json/badTypeSchema.json");
+ schema = SchemaServiceResponse.fromJson(testSchema);
+ } catch (Exception ex) {
+ fail();
+ return;
+ }
- schema.getData().validate();
+ schema.getData().validate();
+ });
}
- @Test(expected = SchemaProviderException.class)
- public void testSchemaValidateBadProp() throws SchemaProviderException {
- SchemaServiceResponse schema;
-
- try {
- String testSchema = readFile("src/test/resources/json/badPropSchema.json");
- schema = SchemaServiceResponse.fromJson(testSchema);
- } catch (Exception ex) {
- fail();
- return;
- }
+ @Test
+ public void testSchemaValidateBadProp() {
+ assertThrows(SchemaProviderException.class, () -> {
+ SchemaServiceResponse schema;
+
+ try {
+ String testSchema = readFile("src/test/resources/json/badPropSchema.json");
+ schema = SchemaServiceResponse.fromJson(testSchema);
+ } catch (Exception ex) {
+ fail();
+ return;
+ }
- schema.getData().validate();
+ schema.getData().validate();
+ });
}
static String readFile(String path) throws IOException {
- byte[] encoded = Files.readAllBytes(Paths.get(path));
+ byte[] encoded = Files.readAllBytes(Path.of(path));
return new String(encoded);
}
}
package org.onap.aai.schemaif.oxm;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Set;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.aai.schemaif.SchemaProviderException;
import org.onap.aai.schemaif.definitions.EdgeSchema;
import org.onap.aai.schemaif.definitions.PropertySchema;
import org.onap.aai.schemaif.definitions.VertexSchema;
import org.onap.aai.schemaif.definitions.types.DataType.Type;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class OxmSchemaProviderTest extends OxmSchemaServiceSetup {
@Test
import java.util.List;
import java.util.Set;
-import org.junit.Before;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.aai.edges.EdgeIngestor;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.setup.AAIConfigTranslator;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.Translator;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
public class OxmSchemaServiceSetup {
@Mock
private OxmEdgeRulesLoader edgeLoader;
private OxmSchemaLoader vertexLoader;
- @Before
+ @BeforeEach
public void schemaBeanMockSetup() throws Exception {
schemaVersionList.add(new SchemaVersion("v13"));
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" output="target/classes" path="src/main/java">
- <attributes>
- <attribute name="optional" value="true"/>
- <attribute name="maven.pomderived" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="src" output="target/test-classes" path="src/test/java">
- <attributes>
- <attribute name="optional" value="true"/>
- <attribute name="maven.pomderived" value="true"/>
- <attribute name="test" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
- <attributes>
- <attribute name="maven.pomderived" value="true"/>
- <attribute name="test" value="true"/>
- <attribute name="optional" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
- <attributes>
- <attribute name="maven.pomderived" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
- <attributes>
- <attribute name="maven.pomderived" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="src" path="target/generated-sources/annotations">
- <attributes>
- <attribute name="optional" value="true"/>
- <attribute name="maven.pomderived" value="true"/>
- <attribute name="ignore_optional_problems" value="true"/>
- <attribute name="m2e-apt" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
- <attributes>
- <attribute name="maven.pomderived" value="true"/>
- <attribute name="optional" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="src" output="target/test-classes" path="target/generated-test-sources/test-annotations">
- <attributes>
- <attribute name="optional" value="true"/>
- <attribute name="maven.pomderived" value="true"/>
- <attribute name="ignore_optional_problems" value="true"/>
- <attribute name="m2e-apt" value="true"/>
- <attribute name="test" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="output" path="target/classes"/>
-</classpath>
<parent>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-parent</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
<relativePath>../aai-parent/pom.xml</relativePath>
</parent>
<artifactId>aai-schema-ingest</artifactId>
<name>aai-schema-ingest</name>
<packaging>jar</packaging>
- <properties>
- <httpclient.version>4.5.13</httpclient.version>
- <groovy.version>2.5.15</groovy.version>
- <springframework.version>4.3.24.RELEASE</springframework.version>
- </properties>
<build>
<plugins>
<plugin>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
- <dependency>
- <groupId>org.codehaus.groovy</groupId>
- <artifactId>groovy</artifactId>
- <version>${groovy.version}</version>
- <classifier>indy</classifier>
- </dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<artifactId>json-path</artifactId>
</dependency>
<dependency>
- <groupId>javax.ws.rs</groupId>
- <artifactId>javax.ws.rs-api</artifactId>
+ <groupId>jakarta.ws.rs</groupId>
+ <artifactId>jakarta.ws.rs-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
+ <groupId>org.apache.httpcomponents.client5</groupId>
+ <artifactId>httpclient5</artifactId>
</dependency>
+ <dependency>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
+ </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <!-- TODO: Migrate tests to junit 5 and remove this dependency -->
- <dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-junit</artifactId>
+ <version>2.0.0.0</version>
<scope>test</scope>
<exclusions>
- <exclusion>
- <groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-core</artifactId>
- </exclusion>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
</exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>com.att.eelf</groupId>
- <artifactId>eelf-core</artifactId>
- </dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
import org.onap.aai.setup.SchemaConfigVersions;
import org.onap.aai.setup.SchemaLocationsBean;
import org.onap.aai.setup.SchemaVersions;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class ConfigConfiguration {
@Bean(name = "schemaConfigVersions")
+ @ConditionalOnMissingBean
public SchemaConfigVersions schemaConfigVersions() {
return new SchemaConfigVersions();
}
package org.onap.aai.config;
-import org.onap.aai.restclient.*;
+import org.onap.aai.restclient.RestClient;
+import org.onap.aai.restclient.SchemaServiceNoAuthClient;
+import org.onap.aai.restclient.SchemaServiceOneWayClient;
+import org.onap.aai.restclient.SchemaServiceRestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
package org.onap.aai.config;
-import org.onap.aai.setup.*;
+import org.onap.aai.setup.ConfigTranslator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
-import javax.annotation.PostConstruct;
+import jakarta.annotation.PostConstruct;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.onap.aai.edges.enums.DirectionNotation;
import org.onap.aai.setup.Translator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
private Set<Translator> translators;
- @Autowired
public EdgeIngestor(Set<Translator> translatorSet) {
this.translators = translatorSet;
}
package org.onap.aai.nodes;
-import com.google.common.base.CaseFormat;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import javax.annotation.PostConstruct;
import javax.xml.XMLConstants;
-import javax.xml.bind.JAXBException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.onap.aai.setup.Translator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
+import com.google.common.base.CaseFormat;
+
+import jakarta.annotation.PostConstruct;
+import jakarta.xml.bind.JAXBException;
+
@Component
/*
* NodeIngestor - ingests A&AI OXM files per given config, serves DynamicJAXBContext per version
* @param translatorSet
*/
- @Autowired
public NodeIngestor(Set<Translator> translatorSet) {
this.translators = translatorSet;
this.caseFormatStore = new CaseFormatStore();
} catch (Exception e) {
LOGGER.error("Error while Processing the translator" + e.getMessage());
- throw new ExceptionInInitializerError("NodeIngestor could not ingest schema");
+ throw new ExceptionInInitializerError(e);
}
}
if (versionContextMap.isEmpty() || schemaPerVersion.isEmpty() || typesPerVersion.isEmpty()) {
schemaPerVersion.put(version, createCombinedSchema(inputStreams, version, retrieveLocalSchema));
}
} catch (JAXBException | ParserConfigurationException | SAXException | IOException e) {
+ LOGGER.error("Schema ingestion failed", e);
throw new ExceptionInInitializerError(e);
}
}
import java.util.Map;
import java.util.UUID;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
public class SchemaServiceOneWayClient extends OneWaySSLRestClient {
- private static Logger logger = LoggerFactory.getLogger(SchemaServiceOneWayClient.class);
-
@Value("${schema.service.base.url}")
private String baseUrl;
- @Value("${schema.service.ssl.trust-store}")
- private String truststorePath;
-
- @Value("${schema.service.ssl.trust-store-password}")
- private String truststorePassword;
-
@Override
public String getBaseUrl() {
return baseUrl;
}
- @Override
- protected String getTruststorePath() {
- return truststorePath;
- }
-
- @Override
- protected char[] getTruststorePassword() {
- return truststorePassword.toCharArray();
- }
-
@Override
public MultiValueMap<String, String> getHeaders(Map<String, String> headers) {
HttpHeaders httpHeaders = new HttpHeaders();
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
public class SchemaServiceRestClient extends TwoWaySSLRestClient {
- private static Logger logger = LoggerFactory.getLogger(SchemaServiceRestClient.class);
@Value("${schema.service.base.url}")
private String baseUrl;
- @Value("${schema.service.ssl.key-store}")
- private String keystorePath;
-
- @Value("${schema.service.ssl.trust-store}")
- private String truststorePath;
-
- @Value("${schema.service.ssl.key-store-password}")
- private String keystorePassword;
-
- @Value("${schema.service.ssl.trust-store-password}")
- private String truststorePassword;
-
@Override
public String getBaseUrl() {
return baseUrl;
}
- @Override
- protected String getKeystorePath() {
- return keystorePath;
- }
-
- @Override
- protected String getTruststorePath() {
- return truststorePath;
- }
-
- @Override
- protected char[] getKeystorePassword() {
- return keystorePassword.toCharArray();
- }
-
- @Override
- protected char[] getTruststorePassword() {
- return truststorePassword.toCharArray();
- }
-
@Override
public MultiValueMap<String, String> getHeaders(Map<String, String> headers) {
HttpHeaders httpHeaders = new HttpHeaders();
/*
* (non-Javadoc)
- *
+ *
* @see org.onap.aai.setup.ConfigTranslator#getNodeFiles()
*/
@Override
/*
* (non-Javadoc)
- *
+ *
* @see org.onap.aai.setup.ConfigTranslator#getEdgeFiles()
*/
@Override
private List<String> getVersionFiles(String startDirectory, SchemaVersion schemaVersion,
Supplier<Stream<String>> inclusionPattern, Supplier<Stream<String>> exclusionPattern) {
- final File versionDirectory = new File(startDirectory + "/" + schemaVersion.toString());
- final List<String> container = Arrays.stream(versionDirectory.listFiles())
- .filter(Objects::nonNull)
+ final File versionDirectory = new File(startDirectory + "/" + schemaVersion.toString());
+ File[] versionFiles = versionDirectory.listFiles();
+ if(versionFiles == null) {
+ throw new RuntimeException("No files found in directory: " + versionDirectory.getAbsolutePath());
+ }
+ final List<String> container = Arrays.stream(versionFiles)
+ .filter(Objects::nonNull)
.map(File::getName)
.filter(versionFileName -> inclusionPattern
.get()
import org.onap.aai.edges.JsonIngestor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
/**
* Converts the contents of the schema config file
protected SchemaLocationsBean schemaLocationsBean;
- @Autowired
public ConfigTranslator(SchemaLocationsBean schemaLocationsBean, SchemaConfigVersions schemaConfigVersions) {
super(schemaConfigVersions);
this.schemaLocationsBean = schemaLocationsBean;
import java.util.List;
import java.util.stream.Collectors;
-import javax.annotation.PostConstruct;
+import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
+import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
verifySchemaServiceResponse(schemaResponse.getStatusCode());
LOGGER.debug("SchemaResponse Status code" + schemaResponse.getStatusCode());
-
+
Resource resultBody = schemaResponse.getBody();
return resultBody != null
? Collections.singletonList(resultBody.getInputStream())
}
- private void verifySchemaServiceResponse(HttpStatus statusCode) throws IOException {
- if (statusCode != HttpStatus.OK) {
+ private void verifySchemaServiceResponse(HttpStatusCode statusCode) throws IOException {
+ if (!statusCode.equals(HttpStatusCode.valueOf(HttpStatus.OK.value()))) {
LOGGER.error("Please check the Schema Service. It returned with the status code {}", statusCode);
throw new IOException("SchemaService is not available");
}
import java.util.List;
import java.util.stream.Collectors;
-import javax.annotation.PostConstruct;
+import jakarta.annotation.PostConstruct;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.PropertySource;
import java.util.List;
import java.util.Map;
-import javax.annotation.PostConstruct;
+import jakarta.annotation.PostConstruct;
import org.onap.aai.restclient.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
package org.onap.aai.setup;
-import java.io.*;
+import java.io.IOException;
+import java.io.InputStream;
import java.util.List;
/**
import org.onap.aai.setup.ConfigTranslator;
import org.onap.aai.setup.SchemaVersion;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
private ConfigTranslator config;
- @Autowired
public DefaultVersionValidationModule(ConfigTranslator config) {
this.config = config;
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
package org.onap.aai.validation;
-import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
/**
* all required versions
*/
@Component
+@ConditionalOnProperty(name = "schema.translator.list", havingValue = "config", matchIfMissing = true)
public class VersionValidator {
private SchemaErrorStrategy strat;
private VersionValidationModule verMod;
- @Autowired
public VersionValidator(SchemaErrorStrategy strategy, VersionValidationModule verMod) {
this.strat = strategy;
this.verMod = verMod;
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
import org.onap.aai.setup.ConfigTranslator;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.validation.SchemaErrorStrategy;
-import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
/**
* Runs all validations against the ingested schema
*/
@Component
+@ConditionalOnProperty(name = "schema.translator.list", havingValue = "config", matchIfMissing = true)
public class EdgeRuleValidator {
private Map<SchemaVersion, List<DocumentContext>> versionJsonFilesMap;
private final SchemaErrorStrategy strat;
protected final CousinDefaultingValidationModule defaultsValidator;
protected final NodeTypesValidationModule typeValidator;
- @Autowired
public EdgeRuleValidator(ConfigTranslator config, SchemaErrorStrategy strat,
EdgeFieldsValidationModule fieldValidator, UniqueLabelValidationModule labelValidator,
SingleContainmentValidationModule containsValidator, CousinDefaultingValidationModule defaultsValidator,
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.setup.SchemaVersion;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
public class NodeTypesValidationModule {
private NodeIngestor ni;
- @Autowired
public NodeTypesValidationModule(NodeIngestor ni) {
this.ni = ni;
}
package org.onap.aai.validation.nodes;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Multimap;
-
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.Multimap;
+
/**
* Default duplicate rules for A&AI -
* node types may never have a duplicate definition
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
import org.onap.aai.setup.ConfigTranslator;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.validation.SchemaErrorStrategy;
-import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
@Component
+@ConditionalOnProperty(name = "schema.translator.list", havingValue = "config", matchIfMissing = true)
public class NodeValidator {
private ConfigTranslator translator;
private SchemaErrorStrategy strat;
private DuplicateNodeDefinitionValidationModule dupChecker;
- @Autowired
public NodeValidator(ConfigTranslator translator, SchemaErrorStrategy strategy,
DuplicateNodeDefinitionValidationModule dupChecker) {
this.translator = translator;
package org.onap.aai.edges;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import com.google.common.collect.Multimap;
import java.util.Collection;
import org.apache.tinkerpop.gremlin.structure.Direction;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.config.EdgesConfiguration;
import org.onap.aai.edges.enums.AAIDirection;
import org.onap.aai.edges.enums.MultiplicityRule;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {EdgesConfiguration.class, TestUtilConfigTranslator.class})
@TestPropertySource(
properties = {
@Autowired
EdgeIngestor edgeIngestor;
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
@Test
public void getRulesTest1() throws EdgeRuleNotFoundException {
EdgeRuleQuery q = new EdgeRuleQuery.Builder("foo").build();
}
@Test
- public void getRulesNoneFound() throws EdgeRuleNotFoundException {
- thrown.expect(EdgeRuleNotFoundException.class);
- thrown.expectMessage("No rules found for");
- EdgeRuleQuery q = new EdgeRuleQuery.Builder("l-interface").build();
- edgeIngestor.getRules(q);
+ public void getRulesNoneFound() {
+ Throwable exception = assertThrows(EdgeRuleNotFoundException.class, () -> {
+ EdgeRuleQuery q = new EdgeRuleQuery.Builder("l-interface").build();
+ edgeIngestor.getRules(q);
+ });
+ assertTrue(exception.getMessage().contains("No rules found for"));
}
@Test
// }
@Test
- public void getRuleNoneFoundTest() throws EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- thrown.expect(EdgeRuleNotFoundException.class);
- thrown.expectMessage("No rule found for");
- EdgeRuleQuery q = new EdgeRuleQuery.Builder("l-interface", "nonexistent").build();
- edgeIngestor.getRule(q);
+ public void getRuleNoneFoundTest() {
+ Throwable exception = assertThrows(EdgeRuleNotFoundException.class, () -> {
+ EdgeRuleQuery q = new EdgeRuleQuery.Builder("l-interface", "nonexistent").build();
+ edgeIngestor.getRule(q);
+ });
+ assertTrue(exception.getMessage().contains("No rule found for"));
}
// @Test
// }
@Test
- public void getRuleAmbiguousDefaultTest() throws EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- thrown.expect(AmbiguousRuleChoiceException.class);
- thrown.expectMessage("Multiple defaults found.");
- EdgeRuleQuery q = new EdgeRuleQuery.Builder("seed", "plant").version(new SchemaVersion("v11")).build();
- edgeIngestor.getRule(q);
+ public void getRuleAmbiguousDefaultTest() {
+ Throwable exception = assertThrows(AmbiguousRuleChoiceException.class, () -> {
+ EdgeRuleQuery q = new EdgeRuleQuery.Builder("seed", "plant").version(new SchemaVersion("v11")).build();
+ edgeIngestor.getRule(q);
+ });
+ assertTrue(exception.getMessage().contains("Multiple defaults found."));
}
@Test
- public void getRuleNoDefaultTest() throws EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- thrown.expect(AmbiguousRuleChoiceException.class);
- thrown.expectMessage("No default found.");
- EdgeRuleQuery q = new EdgeRuleQuery.Builder("apple", "orange").version(new SchemaVersion("v11")).build();
- edgeIngestor.getRule(q);
+ public void getRuleNoDefaultTest() {
+ Throwable exception = assertThrows(AmbiguousRuleChoiceException.class, () -> {
+ EdgeRuleQuery q = new EdgeRuleQuery.Builder("apple", "orange").version(new SchemaVersion("v11")).build();
+ edgeIngestor.getRule(q);
+ });
+ assertTrue(exception.getMessage().contains("No default found."));
}
// @Test
// }
@Test
- public void getAllRulesTest() throws EdgeRuleNotFoundException {
- Multimap<String, EdgeRule> res = edgeIngestor.getAllRules(new SchemaVersion("v10"));
- assertTrue(res.size() == 4);
- assertTrue(res.containsKey("bar|foo"));
- assertTrue(res.get("bar|foo").size() == 2);
- assertTrue(res.containsKey("baz|foo"));
- assertTrue(res.containsKey("foo|quux"));
-
- thrown.expect(EdgeRuleNotFoundException.class);
- thrown.expectMessage("No rules found for version v9.");
- edgeIngestor.getAllRules(new SchemaVersion("v9"));
+ public void getAllRulesTest() {
+ Throwable exception = assertThrows(EdgeRuleNotFoundException.class, () -> {
+ Multimap<String, EdgeRule> res = edgeIngestor.getAllRules(new SchemaVersion("v10"));
+ assertTrue(res.size() == 4);
+ assertTrue(res.containsKey("bar|foo"));
+ assertTrue(res.get("bar|foo").size() == 2);
+ assertTrue(res.containsKey("baz|foo"));
+ assertTrue(res.containsKey("foo|quux"));
+ edgeIngestor.getAllRules(new SchemaVersion("v9"));
+ });
+ assertTrue(exception.getMessage().contains("No rules found for version v9."));
}
}
package org.onap.aai.edges;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import com.google.common.collect.Multimap;
import java.util.Collection;
import org.apache.tinkerpop.gremlin.structure.Direction;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.config.EdgesConfiguration;
import org.onap.aai.edges.enums.AAIDirection;
import org.onap.aai.edges.enums.MultiplicityRule;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MockProvider.class, EdgesConfiguration.class})
@TestPropertySource(
properties = {"schema.ingest.file = src/test/resources/forWiringTests/schema-ingest-wiring-test.properties",
@Autowired
EdgeIngestor edgeIngestor;
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
@Test
public void getRulesTest1() throws EdgeRuleNotFoundException {
EdgeRuleQuery q = new EdgeRuleQuery.Builder("foo").build();
}
@Test
- public void getRulesNoneFound() throws EdgeRuleNotFoundException {
- thrown.expect(EdgeRuleNotFoundException.class);
- thrown.expectMessage("No rules found for");
- EdgeRuleQuery q = new EdgeRuleQuery.Builder("bogus-value").build();
- edgeIngestor.getRules(q);
+ public void getRulesNoneFound() {
+ Throwable exception = assertThrows(EdgeRuleNotFoundException.class, () -> {
+ EdgeRuleQuery q = new EdgeRuleQuery.Builder("bogus-value").build();
+ edgeIngestor.getRules(q);
+ });
+ assertTrue(exception.getMessage().contains("No rules found for"));
}
@Test
}
@Test
- public void getRuleNoneFoundTest() throws EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- thrown.expect(EdgeRuleNotFoundException.class);
- thrown.expectMessage("No rule found for");
- EdgeRuleQuery q = new EdgeRuleQuery.Builder("l-interface", "nonexistent").build();
- edgeIngestor.getRule(q);
+ public void getRuleNoneFoundTest() {
+ Throwable exception = assertThrows(EdgeRuleNotFoundException.class, () -> {
+ EdgeRuleQuery q = new EdgeRuleQuery.Builder("l-interface", "nonexistent").build();
+ edgeIngestor.getRule(q);
+ });
+ assertTrue(exception.getMessage().contains("No rule found for"));
}
@Test
- public void getRuleTooManyPairsTest() throws EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- thrown.expect(AmbiguousRuleChoiceException.class);
- thrown.expectMessage("No way to select single rule from these pairs:");
- EdgeRuleQuery q = new EdgeRuleQuery.Builder("foo").build();
- edgeIngestor.getRule(q);
+ public void getRuleTooManyPairsTest() {
+ Throwable exception = assertThrows(AmbiguousRuleChoiceException.class, () -> {
+ EdgeRuleQuery q = new EdgeRuleQuery.Builder("foo").build();
+ edgeIngestor.getRule(q);
+ });
+ assertTrue(exception.getMessage().contains("No way to select single rule from these pairs:"));
}
@Test
- public void getRuleAmbiguousDefaultTest() throws EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- thrown.expect(AmbiguousRuleChoiceException.class);
- thrown.expectMessage("Multiple defaults found.");
- EdgeRuleQuery q = new EdgeRuleQuery.Builder("seed", "plant").version(new SchemaVersion("v11")).build();
- edgeIngestor.getRule(q);
+ public void getRuleAmbiguousDefaultTest() {
+ Throwable exception = assertThrows(AmbiguousRuleChoiceException.class, () -> {
+ EdgeRuleQuery q = new EdgeRuleQuery.Builder("seed", "plant").version(new SchemaVersion("v11")).build();
+ edgeIngestor.getRule(q);
+ });
+ assertTrue(exception.getMessage().contains("Multiple defaults found."));
}
@Test
- public void getRuleNoDefaultTest() throws EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- thrown.expect(AmbiguousRuleChoiceException.class);
- thrown.expectMessage("No default found.");
- EdgeRuleQuery q = new EdgeRuleQuery.Builder("apple", "orange").version(new SchemaVersion("v11")).build();
- edgeIngestor.getRule(q);
+ public void getRuleNoDefaultTest() {
+ Throwable exception = assertThrows(AmbiguousRuleChoiceException.class, () -> {
+ EdgeRuleQuery q = new EdgeRuleQuery.Builder("apple", "orange").version(new SchemaVersion("v11")).build();
+ edgeIngestor.getRule(q);
+ });
+ assertTrue(exception.getMessage().contains("No default found."));
}
@Test
}
@Test
- public void getAllRulesTest() throws EdgeRuleNotFoundException {
- Multimap<String, EdgeRule> res = edgeIngestor.getAllRules(new SchemaVersion("v10"));
- assertTrue(res.size() == 4);
- assertTrue(res.containsKey("bar|foo"));
- assertTrue(res.get("bar|foo").size() == 2);
- assertTrue(res.containsKey("baz|foo"));
- assertTrue(res.containsKey("foo|quux"));
-
- thrown.expect(EdgeRuleNotFoundException.class);
- thrown.expectMessage("No rules found for version v9.");
- edgeIngestor.getAllRules(new SchemaVersion("v9"));
+ public void getAllRulesTest() {
+ Throwable exception = assertThrows(EdgeRuleNotFoundException.class, () -> {
+ Multimap<String, EdgeRule> res = edgeIngestor.getAllRules(new SchemaVersion("v10"));
+ assertTrue(res.size() == 4);
+ assertTrue(res.containsKey("bar|foo"));
+ assertTrue(res.get("bar|foo").size() == 2);
+ assertTrue(res.containsKey("baz|foo"));
+ assertTrue(res.containsKey("foo|quux"));
+ edgeIngestor.getAllRules(new SchemaVersion("v9"));
+ });
+ assertTrue(exception.getMessage().contains("No rules found for version v9."));
}
}
package org.onap.aai.edges;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.Multimap;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.config.EdgesConfiguration;
import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.setup.SchemaVersion;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {EdgesConfiguration.class, ConfigTranslatorForWiringTest.class})
@TestPropertySource(
properties = {
package org.onap.aai.edges;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import java.util.List;
import java.util.Scanner;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.aai.edges.enums.EdgeType;
public class EdgeRuleQueryTest {
private String readStart = "$.rules.[?]";
/* **** DATA SETUP **** */
- @Before
+ @BeforeEach
public void setup() {
InputStream is = getClass().getResourceAsStream("/edgeRules/test.json");
package org.onap.aai.edges;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.apache.tinkerpop.gremlin.structure.Direction;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class EdgeRuleTest {
import static com.jayway.jsonpath.Criteria.where;
import static com.jayway.jsonpath.Filter.filter;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.Filter;
+import org.junit.jupiter.api.Test;
import java.util.*;
-import org.junit.Test;
import org.onap.aai.setup.SchemaVersion;
public class JsonIngestorTest {
package org.onap.aai.edges;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class TypeAlphabetizerTest {
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.*;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
-import java.nio.file.Paths;
+import java.nio.file.Path;
-import javax.xml.bind.SchemaOutputResolver;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.config.NodesConfiguration;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.testutils.TestUtilConfigTranslator;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
import org.w3c.dom.Document;
-@RunWith(SpringRunner.class)
+import jakarta.xml.bind.SchemaOutputResolver;
+
@TestPropertySource(
properties = {
"schema.ingest.file = src/test/resources/forWiringTests/schema-ingest-wiring-test-local-node.properties"})
@SpringBootTest
public class NodeIngestorLocalTest {
-
- // set thrown.expect to whatever a specific test needs
- // this establishes a default of expecting no exceptions to be thrown
- @Rule
- public ExpectedException thrown = ExpectedException.none();
@Autowired
NodeIngestor nodeIngestor;
@Test
public void testGetContextForVersion11() {
- DynamicJAXBContext ctx10 = nodeIngestor.getContextForVersion(new SchemaVersion("v10"));
-
- // should work bc Foo is valid in test_network_v10 schema
- DynamicEntity foo10 = ctx10.newDynamicEntity("Foo");
-
- foo10.set("fooId", "bar");
- assertEquals("bar", foo10.get("fooId"));
-
- // should work bc Bar is valid in test_business_v10 schema
- DynamicEntity bar10 = ctx10.newDynamicEntity("Bar");
- bar10.set("barId", "bar2");
- assertEquals("bar2", bar10.get("barId"));
- XSDOutputResolver outputResolver10 = new XSDOutputResolver();
- ctx10.generateSchema(outputResolver10);
-
- DynamicJAXBContext ctx11 = nodeIngestor.getContextForVersion(new SchemaVersion("v11"));
-
- // should work bc Foo.quantity is valid in test_network_v11 schema
- DynamicEntity foo11 = ctx11.newDynamicEntity("Foo");
- foo11.set("quantity", "12");
- assertEquals("12", foo11.get("quantity"));
-
- DynamicEntity quux11 = ctx11.newDynamicEntity("Quux");
- quux11.set("qManagerName", "some guy");
- assertEquals("some guy", quux11.get("qManagerName"));
- XSDOutputResolver outputResolver11 = new XSDOutputResolver();
- ctx11.generateSchema(outputResolver11);
-
- thrown.expect(IllegalArgumentException.class);
- // should fail bc Quux not in v10 test schema
- ctx10.newDynamicEntity("Quux");
+ assertThrows(IllegalArgumentException.class, () -> {
+ DynamicJAXBContext ctx10 = nodeIngestor.getContextForVersion(new SchemaVersion("v10"));
+
+ // should work bc Foo is valid in test_network_v10 schema
+ DynamicEntity foo10 = ctx10.newDynamicEntity("Foo");
+
+ foo10.set("fooId", "bar");
+ assertEquals("bar", foo10.get("fooId"));
+
+ // should work bc Bar is valid in test_business_v10 schema
+ DynamicEntity bar10 = ctx10.newDynamicEntity("Bar");
+ bar10.set("barId", "bar2");
+ assertEquals("bar2", bar10.get("barId"));
+ XSDOutputResolver outputResolver10 = new XSDOutputResolver();
+ ctx10.generateSchema(outputResolver10);
+
+ DynamicJAXBContext ctx11 = nodeIngestor.getContextForVersion(new SchemaVersion("v11"));
+
+ // should work bc Foo.quantity is valid in test_network_v11 schema
+ DynamicEntity foo11 = ctx11.newDynamicEntity("Foo");
+ foo11.set("quantity", "12");
+ assertEquals("12", foo11.get("quantity"));
+
+ DynamicEntity quux11 = ctx11.newDynamicEntity("Quux");
+ quux11.set("qManagerName", "some guy");
+ assertEquals("some guy", quux11.get("qManagerName"));
+ XSDOutputResolver outputResolver11 = new XSDOutputResolver();
+ ctx11.generateSchema(outputResolver11);
+ // should fail bc Quux not in v10 test schema
+ ctx10.newDynamicEntity("Quux");
+ });
}
@Test
ctx13.generateSchema(outputResolver13);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
printDocument(nodeIngestor.getSchema(new SchemaVersion("v13")), buffer);
- String content = new String(Files.readAllBytes(Paths.get("src/test/resources/forWiringTests/aai_oxm_v13.xml")));
+ String content = new String(Files.readAllBytes(Path.of("src/test/resources/forWiringTests/aai_oxm_v13.xml")));
content = content.replaceAll("\\s+", "");
String expected = buffer.toString().replaceAll("\\s+", "");
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.*;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
-import java.nio.file.Paths;
+import java.nio.file.Path;
-import javax.xml.bind.SchemaOutputResolver;
+import jakarta.xml.bind.SchemaOutputResolver;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.config.NodesConfiguration;
import org.onap.aai.restclient.MockProvider;
import org.onap.aai.setup.SchemaVersion;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.w3c.dom.Document;
-@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(
properties = {"schema.ingest.file = src/test/resources/forWiringTests/schema-ingest-ss-wiring-test.properties",
"spring.main.allow-bean-definition-overriding=true"})
@Autowired
NodeIngestor nodeIngestor;
- // set thrown.expect to whatever a specific test needs
- // this establishes a default of expecting no exceptions to be thrown
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
@Test
public void testGetContextForVersion() {
- DynamicJAXBContext ctx10 = nodeIngestor.getContextForVersion(new SchemaVersion("v10"));
-
- // should work bc Foo is valid in test_network_v10 schema
- DynamicEntity foo10 = ctx10.newDynamicEntity("Foo");
-
- foo10.set("fooId", "bar");
- assertEquals("bar", foo10.get("fooId"));
-
- // should work bc Bar is valid in test_business_v10 schema
- DynamicEntity bar10 = ctx10.newDynamicEntity("Bar");
- bar10.set("barId", "bar2");
- assertEquals("bar2", bar10.get("barId"));
- XSDOutputResolver outputResolver10 = new XSDOutputResolver();
- ctx10.generateSchema(outputResolver10);
-
- DynamicJAXBContext ctx11 = nodeIngestor.getContextForVersion(new SchemaVersion("v11"));
-
- // should work bc Foo.quantity is valid in test_network_v11 schema
- DynamicEntity foo11 = ctx11.newDynamicEntity("Foo");
- foo11.set("quantity", "12");
- assertEquals("12", foo11.get("quantity"));
-
- DynamicEntity quux11 = ctx11.newDynamicEntity("Quux");
- quux11.set("qManagerName", "some guy");
- assertEquals("some guy", quux11.get("qManagerName"));
- XSDOutputResolver outputResolver11 = new XSDOutputResolver();
- ctx11.generateSchema(outputResolver11);
-
- thrown.expect(IllegalArgumentException.class);
- // should fail bc Quux not in v10 test schema
- ctx10.newDynamicEntity("Quux");
+ assertThrows(IllegalArgumentException.class, () -> {
+ DynamicJAXBContext ctx10 = nodeIngestor.getContextForVersion(new SchemaVersion("v10"));
+
+ // should work bc Foo is valid in test_network_v10 schema
+ DynamicEntity foo10 = ctx10.newDynamicEntity("Foo");
+
+ foo10.set("fooId", "bar");
+ assertEquals("bar", foo10.get("fooId"));
+
+ // should work bc Bar is valid in test_business_v10 schema
+ DynamicEntity bar10 = ctx10.newDynamicEntity("Bar");
+ bar10.set("barId", "bar2");
+ assertEquals("bar2", bar10.get("barId"));
+ XSDOutputResolver outputResolver10 = new XSDOutputResolver();
+ ctx10.generateSchema(outputResolver10);
+
+ DynamicJAXBContext ctx11 = nodeIngestor.getContextForVersion(new SchemaVersion("v11"));
+
+ // should work bc Foo.quantity is valid in test_network_v11 schema
+ DynamicEntity foo11 = ctx11.newDynamicEntity("Foo");
+ foo11.set("quantity", "12");
+ assertEquals("12", foo11.get("quantity"));
+
+ DynamicEntity quux11 = ctx11.newDynamicEntity("Quux");
+ quux11.set("qManagerName", "some guy");
+ assertEquals("some guy", quux11.get("qManagerName"));
+ XSDOutputResolver outputResolver11 = new XSDOutputResolver();
+ ctx11.generateSchema(outputResolver11);
+ // should fail bc Quux not in v10 test schema
+ ctx10.newDynamicEntity("Quux");
+ });
}
@Test
ctx13.generateSchema(outputResolver13);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
printDocument(nodeIngestor.getSchema(new SchemaVersion("v13")), buffer);
- String content = new String(Files.readAllBytes(Paths.get("src/test/resources/forWiringTests/aai_oxm_v13.xml")));
+ String content = new String(Files.readAllBytes(Path.of("src/test/resources/forWiringTests/aai_oxm_v13.xml")));
content = content.replaceAll("\\s+", "");
String expected = buffer.toString().replaceAll("\\s+", "");
package org.onap.aai.nodes;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.config.NodesConfiguration;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.testutils.ConfigTranslatorForWiringTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ConfigTranslatorForWiringTest.class, NodesConfiguration.class})
@TestPropertySource(
properties = {
package org.onap.aai.restclient;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
.removeIf(converter -> MappingJackson2XmlHttpMessageConverter.class.isAssignableFrom(converter.getClass()));
}
});
- restTemplate = restTemplateBuilder.build();
+ restTemplate = restTemplateBuilder.detectRequestFactory(false).build();
mockRestServiceServer = MockRestServiceServer.createServer(restTemplate);
JsonObject payload = null;
e.printStackTrace();
}
JsonArray mockUris = payload.getAsJsonArray("mock-uri");
-
+
String url = "https://localhost:8447/aai/v14";
for (int i = 0; i < mockUris.size(); i++) {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filename);
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
- String message = String.format("Unable to find the %s in src/test/resources", filename);
- assertNotNull(message, inputStream);
+ String message = "Unable to find the %s in src/test/resources".formatted(filename);
+ assertNotNull(inputStream, message);
JsonObject payload = JsonParser.parseString(result).getAsJsonObject();
return payload;
import java.util.HashMap;
import java.util.Map;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@Ignore
-@RunWith(SpringJUnit4ClassRunner.class)
+@Disabled
@TestPropertySource(locations = "/schemaService/schema-service-rest.properties")
@ContextConfiguration(
- classes = {RestClientFactoryConfiguration.class, SchemaServiceRestClient.class, RestClientFactory.class,
- PropertyPasswordConfiguration.class})
+ classes = {RestClientFactoryConfiguration.class, SchemaServiceRestClient.class, RestClientFactory.class})
@SpringBootTest
public class SchemaRestClientTest {
package org.onap.aai.setup;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import java.util.Map;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.testutils.ConfigTranslatorForWiringTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = {SchemaLocationsBean.class, SchemaConfigVersions.class, ConfigTranslatorForWiringTest.class})
@TestPropertySource(
package org.onap.aai.setup;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = {SchemaLocationsBean.class})
+@SpringJUnitConfig(classes = {SchemaLocationsBean.class})
public class SchemaLocationsBeanDefaultInjectionTest {
@Autowired
SchemaLocationsBean bean;
package org.onap.aai.setup;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = {SchemaLocationsBean.class})
+@SpringJUnitConfig(classes = {SchemaLocationsBean.class})
@TestPropertySource(properties = {"schema.ingest.file = src/test/resources/forWiringTests/schema-ingest2.properties"})
public class SchemaLocationsBeanEnvVarInjectionTest {
@Autowired
package org.onap.aai.setup;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(locations = {"classpath:forWiringTests/testContext.xml"})
+@SpringJUnitConfig(locations = {"classpath:forWiringTests/testContext.xml"})
public class SchemaLocationsBeanXMLSetterTest {
@Autowired
SchemaLocationsBean bean;
package org.onap.aai.setup;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
-@Ignore("Support of schema ingest via context configuration with prop file is removed as it won't work with spring boot 2")
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(locations = {"classpath:forWiringTests/testUsingPropFileContext.xml"})
+@Disabled("Support of schema ingest via context configuration with prop file is removed as it won't work with spring boot 2")
+@SpringJUnitConfig(locations = {"classpath:forWiringTests/testUsingPropFileContext.xml"})
public class SchemaLocationsBeanXMLSetterWithPropFileTest {
@Autowired
SchemaLocationsBean bean;
package org.onap.aai.setup;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.util.List;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.restclient.MockProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(
properties = {
"schema.ingest.file = src/test/resources/forWiringTests/schema-ingest-ss-wiring-override-test.properties"})
@ContextConfiguration(classes = {MockProvider.class, SchemaVersionsBean.class, SchemaConfigVersions.class})
@SpringBootTest
public class SchemaVersionsBeanOverrideTest {
-
- // set thrown.expect to whatever a specific test needs
- // this establishes a default of expecting no exceptions to be thrown
- @Rule
- public ExpectedException thrown = ExpectedException.none();
@Autowired
SchemaVersionsBean SchemaVersionsBean;
package org.onap.aai.setup;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.util.List;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.restclient.MockProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(
properties = {"schema.ingest.file = src/test/resources/forWiringTests/schema-ingest-ss-wiring-test.properties"})
@ContextConfiguration(classes = {MockProvider.class, SchemaVersionsBean.class})
@SpringBootTest
public class SchemaVersionsBeanTest {
-
- // set thrown.expect to whatever a specific test needs
- // this establishes a default of expecting no exceptions to be thrown
- @Rule
- public ExpectedException thrown = ExpectedException.none();
@Autowired
SchemaVersionsBean SchemaVersionsBean;
package org.onap.aai.validation;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class CheckEverythingStrategyTest {
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
package org.onap.aai.validation;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
public class FailFastStrategyTest {
- @Rule
- public ExpectedException thrown = ExpectedException.none();
@Test
public void test() {
- FailFastStrategy strat = new FailFastStrategy();
+ String testError = "hi i'm a problem";
+ Throwable exception = assertThrows(AAISchemaValidationException.class, () -> {
+ FailFastStrategy strat = new FailFastStrategy();
- // simulate no issues found
- assertTrue(strat.isOK());
- assertTrue("No errors found.".equals(strat.getErrorMsg()));
+ // simulate no issues found
+ assertTrue(strat.isOK());
+ assertTrue("No errors found.".equals(strat.getErrorMsg()));
- // simulate an issue found
- String testError = "hi i'm a problem";
- thrown.expect(AAISchemaValidationException.class);
- thrown.expectMessage(testError);
- strat.notifyOnError(testError);
+ // simulate an issue found
+ strat.notifyOnError(testError);
+ });
+ assertTrue(exception.getMessage().contains(testError));
}
}
package org.onap.aai.validation;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.config.NodesConfiguration;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.testutils.BadNodeConfigForValidationTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = {NodesConfiguration.class, BadNodeConfigForValidationTest.class, CheckEverythingStrategy.class,
DefaultVersionValidationModule.class, VersionValidator.class})
package org.onap.aai.validation;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.config.NodesConfiguration;
import org.onap.aai.testutils.GoodConfigForValidationTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = {NodesConfiguration.class, GoodConfigForValidationTest.class, CheckEverythingStrategy.class,
DefaultVersionValidationModule.class, VersionValidator.class})
package org.onap.aai.validation.edges;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.jayway.jsonpath.DocumentContext;
import java.util.List;
import java.util.Map;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import org.onap.aai.edges.JsonIngestor;
import org.onap.aai.setup.SchemaVersion;
private static List<DocumentContext> ctxs;
private static CousinDefaultingValidationModule validator;
- @BeforeClass
+ @BeforeAll
public static void setUpBeforeClass() {
Map<SchemaVersion, List<String>> testRules = new HashMap<>();
List<String> testFiles = new ArrayList<>();
package org.onap.aai.validation.edges;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashMap;
import java.util.Map;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.edges.enums.EdgeField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {DefaultEdgeFieldsValidationModule.class})
@SpringBootTest
public class DefaultEdgeFieldsValidationModuleTest {
package org.onap.aai.validation.edges;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.config.NodesConfiguration;
import org.onap.aai.testutils.BadEdgeConfigForValidationTest;
import org.onap.aai.validation.CheckEverythingStrategy;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = {NodesConfiguration.class, BadEdgeConfigForValidationTest.class, CheckEverythingStrategy.class,
DefaultEdgeFieldsValidationModule.class, UniqueLabelValidationModule.class,
package org.onap.aai.validation.edges;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.config.NodesConfiguration;
import org.onap.aai.testutils.GoodConfigForValidationTest;
import org.onap.aai.validation.CheckEverythingStrategy;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = {NodesConfiguration.class, GoodConfigForValidationTest.class, CheckEverythingStrategy.class,
DefaultEdgeFieldsValidationModule.class, UniqueLabelValidationModule.class,
package org.onap.aai.validation.edges;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.config.NodesConfiguration;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.testutils.TestUtilConfigTranslator;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = {NodesConfiguration.class, TestUtilConfigTranslator.class, NodeTypesValidationModule.class})
@TestPropertySource(
package org.onap.aai.validation.edges;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.jayway.jsonpath.DocumentContext;
import java.util.*;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import org.onap.aai.edges.JsonIngestor;
import org.onap.aai.setup.SchemaVersion;
private static SingleContainmentValidationModule validator;
public static final SchemaVersion LATEST = new SchemaVersion("v14");
- @BeforeClass
+ @BeforeAll
public static void setUpBeforeClass() {
Map<SchemaVersion, List<String>> testRules = new TreeMap<>();
List<String> testFiles = new ArrayList<>();
package org.onap.aai.validation.edges;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.jayway.jsonpath.DocumentContext;
import java.util.*;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import org.onap.aai.edges.JsonIngestor;
import org.onap.aai.setup.SchemaVersion;
private static UniqueLabelValidationModule validator;
public static final SchemaVersion LATEST = new SchemaVersion("v14");
- @BeforeClass
+ @BeforeAll
public static void setup() {
Map<SchemaVersion, List<String>> testRules = new TreeMap<>();
List<String> testFiles = new ArrayList<>();
package org.onap.aai.validation.nodes;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.config.NodesConfiguration;
import org.onap.aai.testutils.BadNodeConfigForValidationTest;
import org.onap.aai.validation.CheckEverythingStrategy;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = {BadNodeConfigForValidationTest.class, NodesConfiguration.class, CheckEverythingStrategy.class,
DefaultDuplicateNodeDefinitionValidationModule.class, NodeValidator.class})
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
package org.onap.aai.validation.nodes;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import org.onap.aai.config.NodesConfiguration;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.setup.SchemaVersion;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.w3c.dom.Document;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SchemaIncompleteTranslator.class, NodesConfiguration.class})
@TestPropertySource(
properties = {
"schema.ingest.file = src/test/resources/forWiringTests/schema-ingest-wiring-test-local.properties"})
@SpringBootTest
-@Ignore
+@Disabled
public class NodeValidatorSchemaIncompleteTest {
@Autowired
NodeIngestor ni;
- // set thrown.expect to whatever a specific test needs
- // this establishes a default of expecting no exceptions to be thrown
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
// Throws a NullPointerException because a JavaType is referenced, but not defined
@Test
- public void testIncompleteCombinedSchema() throws TransformerException, IOException, IllegalStateException {
- thrown.expect(NullPointerException.class);
+ public void testIncompleteCombinedSchema() {
+ assertThrows(NullPointerException.class, () -> {
- // TODO Change for Exception
- ByteArrayOutputStream buffer = new ByteArrayOutputStream();
- printDocument(ni.getSchema(new SchemaVersion("v12")), buffer);
+ // TODO Change for Exception
+ ByteArrayOutputStream buffer = new ByteArrayOutputStream();
+ printDocument(ni.getSchema(new SchemaVersion("v12")), buffer);
+ });
}
public static void printDocument(Document doc, OutputStream out) throws IOException, TransformerException {
package org.onap.aai.validation.nodes;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.onap.aai.config.NodesConfiguration;
import org.onap.aai.testutils.GoodConfigForValidationTest;
import org.onap.aai.validation.CheckEverythingStrategy;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = {NodesConfiguration.class, GoodConfigForValidationTest.class, CheckEverythingStrategy.class,
DefaultDuplicateNodeDefinitionValidationModule.class, NodeValidator.class})
<parent>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-parent</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
<relativePath>../aai-parent/pom.xml</relativePath>
</parent>
<artifactId>aai-utils</artifactId>
<properties>
<onap.nexus.url>https://nexus.onap.org</onap.nexus.url>
- <logback.version>1.2.3</logback.version>
</properties>
<dependencies>
<dependency>
- <groupId>com.att.eelf</groupId>
- <artifactId>eelf-core</artifactId>
- <version>1.0.1-oss</version>
- <exclusions>
- <exclusion>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-module-junit4</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
+ <groupId>org.apache.httpcomponents.client5</groupId>
+ <artifactId>httpclient5</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
</dependency>
<dependency>
- <groupId>javax.xml.bind</groupId>
- <artifactId>jaxb-api</artifactId>
- </dependency>
- <!-- Common logging framework -->
- <dependency>
- <groupId>org.onap.aai.logging-service</groupId>
- <artifactId>common-logging</artifactId>
+ <groupId>jakarta.xml.bind</groupId>
+ <artifactId>jakarta.xml.bind-api</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.glassfish.jaxb</groupId>
+ <artifactId>jaxb-runtime</artifactId>
+ <scope>runtime</scope>
+ </dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
+ <groupId>org.projectlombok</groupId>
+ <artifactId>lombok</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import javax.xml.bind.JAXBException;
+import jakarta.xml.bind.JAXBException;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;
-import org.onap.aai.cl.api.Logger;
-import org.onap.aai.cl.eelf.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
public class OxmModelLoader {
private static final Pattern AAI_OXM_FILE_PATTERN = Pattern.compile("aai_oxm_(.*).xml");
private static Map<String, DynamicJAXBContext> versionContextMap = new ConcurrentHashMap<>();
- private static final Logger LOGGER = LoggerFactory.getInstance().getLogger(OxmModelLoader.class.getName());
public synchronized static void loadModels() throws Exception {
OxmModelLoader.loadModels("classpath*:/oxm/aai_oxm*.xml", AAI_OXM_FILE_PATTERN);
try {
OxmModelLoader.loadModel(matcher.group(1), resource);
} catch (Exception e) {
- LOGGER.error(OxmModelLoaderMsgs.OXM_LOAD_ERROR,
- "Failed to load " + resource.getFilename() + ": " + e.getMessage());
+ log.error("CRD0503E|Unable to load OXM schema: {}", "Failed to load " + resource.getFilename() + ": " + e.getMessage());
throw new Exception("Failed to load schema");
}
}
Resource[] resources = resolver.getResources(oxmResourcesPattern);
if (resources.length == 0) {
- LOGGER.error(OxmModelLoaderMsgs.OXM_LOAD_ERROR, "No OXM schema files found on classpath");
+ log.error("CRD0503E|Unable to load OXM schema: {}", "No OXM schema files found on classpath");
throw new Exception("Failed to load schema");
}
return resources;
.createContextFromOXM(Thread.currentThread().getContextClassLoader(), properties);
versionContextMap.put(version, jaxbContext);
-
- LOGGER.info(OxmModelLoaderMsgs.LOADED_OXM_FILE, resourceName);
+ log.info("CRD0007I|Successfully loaded schema: {}", resourceName);
}
}
+++ /dev/null
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property.
- * Copyright © 2017-2018 Amdocs
- * 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.aaiutils.oxm;
-
-import com.att.eelf.i18n.EELFResourceManager;
-
-import org.onap.aai.cl.eelf.LogMessageEnum;
-
-public enum OxmModelLoaderMsgs implements LogMessageEnum {
-
- /**
- * Invalid Model File
- * Arguments:
- * {0} = File/Dir
- * {1} = error
- */
-
- INVALID_OXM_FILE, INVALID_OXM_DIR,
-
- /**
- * Unable to load OXM schema: {0}
- *
- * <p>
- * Arguments:
- * {0} = error
- */
- OXM_LOAD_ERROR,
-
- /**
- * Successfully loaded schema: {0}
- *
- * <p>
- * Arguments:
- * {0} = oxm filename
- */
- LOADED_OXM_FILE;
-
- /**
- * Static initializer to ensure the resource bundles for this class are loaded...
- */
- static {
- EELFResourceManager.loadMessageBundle("oxm/OxmModelLoaderMsgs");
- }
-}
+++ /dev/null
-#Resource key=Error Code|Message text|Resolution text |Description text
-#######
-#Newlines can be utilized to add some clarity ensuring continuing line
-#has atleast one leading space
-#ResourceKey=\
-# CA0000E\
-# Sample error msg txt\
-# Sample resolution msg\
-# Sample description txt
-#
-######
-#Error code classification category
-#000 Info/Debug
-#100 Permission errors
-#200 Availability errors/Timeouts
-#300 Data errors
-#400 Schema Interface type/validation errors
-#500 Business process errors
-#900 Unknown errors
-#
-########################################################################
-
-INVALID_OXM_FILE=\
- CRD0002I|\
- Unable to parse schema file: {0} due to error : {1}\
-
-OXM_FILE_CHANGED=\
- CRD0003I|\
- OXM file change detected: {0}\
-
-INVALID_OXM_DIR=\
- CRD0005I|\
- Invalid OXM dir: {0}\
-
-LOADED_OXM_FILE=\
- CRD0007I|\
- Successfully loaded schema: {0}
-OXM_LOAD_ERROR=\
- CRD0503E|\
- Unable to load OXM schema: {0}
* 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.
package org.onap.aaiutils.oxm;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
import java.util.regex.Pattern;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
public class OxmModelLoaderTest {
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
@Test
public void shouldLoadOxmModelsWhichMatchToPattern() throws Exception {
OxmModelLoader.loadModels("classpath*:test_aai_oxm*.xml", Pattern.compile("test_aai_oxm_(.*).xml"));
- Assert.assertTrue(OxmModelLoader.getVersionContextMap().size() == 2);
- Assert.assertFalse(OxmModelLoader.getVersionContextMap().containsKey("v7"));
- Assert.assertTrue(OxmModelLoader.getVersionContextMap().containsKey("v8"));
- Assert.assertTrue(OxmModelLoader.getVersionContextMap().containsKey("v9"));
+ Assertions.assertTrue(OxmModelLoader.getVersionContextMap().size() == 2);
+ Assertions.assertFalse(OxmModelLoader.getVersionContextMap().containsKey("v7"));
+ Assertions.assertTrue(OxmModelLoader.getVersionContextMap().containsKey("v8"));
+ Assertions.assertTrue(OxmModelLoader.getVersionContextMap().containsKey("v9"));
}
@Test
- public void shouldReportAnErrorWhenOxmModelsAreNotAvailable() throws Exception {
- thrown.expect(Exception.class);
- thrown.expectMessage("Failed to load schema");
+ public void shouldReportAnErrorWhenOxmModelsAreNotAvailable() {
+ Throwable exception = assertThrows(Exception.class, () ->
OxmModelLoader.loadModels("classpath*:non_existing_aai_oxm*.xml",
- Pattern.compile("non_existing_aai_oxm_(.*).xml"));
+ Pattern.compile("non_existing_aai_oxm_(.*).xml")));
+ assertTrue(exception.getMessage().contains("Failed to load schema"));
}
}
html_theme_options = {
"style_nav_header_background": "white",
"sticky_navigation": "False" }
-html_logo = "_static/logo_onap_2017.png"
+html_logo = "_static/logo_onap_2024.png"
html_favicon = "_static/favicon.ico"
html_static_path = ["_static"]
html_show_sphinx = False
platform/index.rst
release-notes.rst
+ platform/offeredapis.rst
AAI REST API Documentation/AAIRESTAPI.rst
AAI REST API Documentation/bulkApi.rst
AAI REST API Documentation/customQueries.rst
$ sudo service haproxy restart
-4. Follow the initial setup instructions in `Setting Up Your Development Environment <https://wiki.onap.org/display/DW/Setting+Up+Your+Development+Environment>`__ e.g.
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+4. Follow the initial setup instructions in `Setting Up Your Development Environment <https://lf-onap.atlassian.net/wiki/display/DW/Setting+Up+Your+Development+Environment>`__ e.g.
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
.. code-block:: bash
$ sudo apt-get install git
<tr><td>html doc</td>
<td>yaml doc</td>
</tr>
-<tr><td><p class="first"><a href="#id1"><span class="problematic" id="id2">:download:`link <https://wiki.onap.org/download/attachments/41421924/aai_swagger_v14.html?api=v2>`</span></a></p>
+<tr><td><p class="first"><a href="#id1"><span class="problematic" id="id2">:download:`link <https://lf-onap.atlassian.net/wiki/download/attachments/16506145/aai_swagger_v29.html?api=v2>`</span></a></p>
<div class="last system-message" id="id1">
<p class="system-message-title">System Message: ERROR/3 (<tt class="docutils">offeredapis.rst</tt>, line 20); <em><a href="#id2">backlink</a></em></p>
Unknown interpreted text role "download".</div>
</td>
-<td><p class="first"><a href="#id3"><span class="problematic" id="id4">:download:`link <https://wiki.onap.org/download/attachments/41421924/aai_swagger_v14.yaml?api=v2>`</span></a></p>
+<td><p class="first"><a href="#id3"><span class="problematic" id="id4">:download:`link <https://lf-onap.atlassian.net/wiki/download/attachments/16506145/aai_swagger_v29.yaml?api=v2>`</span></a></p>
<div class="last system-message" id="id3">
<p class="system-message-title">System Message: ERROR/3 (<tt class="docutils">offeredapis.rst</tt>, line 20); <em><a href="#id4">backlink</a></em></p>
Unknown interpreted text role "download".</div>
.. _offeredapis:
========================================
-Offered APIs
+AAI OpenAPI definition
========================================
The list of APIs that AAI offers could be found in the following table:
:widths: 60,60
"html doc", "yaml doc"
- ":download:`link <https://wiki.onap.org/download/attachments/103422039/aai_swagger_v24.html?api=v2>`", ":download:`link <https://wiki.onap.org/download/attachments/103422039/aai_swagger_v24.yaml?api=v2>`"
-
-
+ ":download:`v30 <https://lf-onap.atlassian.net/wiki/download/attachments/110952449/aai_swagger_v30.html?api=v2>`", ":download:`v30 <https://lf-onap.atlassian.net/wiki/download/attachments/110952449/aai_swagger_v30.yaml?api=v2>`"
+ ":download:`v29 <https://lf-onap.atlassian.net/wiki/download/attachments/110952449/aai_swagger_v29.html?api=v2>`", ":download:`v29 <https://lf-onap.atlassian.net/wiki/download/attachments/110952449/aai_swagger_v29.yaml?api=v2>`"
Abstract
========
-This document provides release notes for the Active and Available Inventory Project's Kohn Release
+This document provides release notes for the Active and Available Inventory Project's Oslo Release
Release Data
============
+Version: 15.X.X
+---------------
+
+General
+-------
+
+Features
+^^^^^^^^
+
+- Janusgraph upgrade (`0.6.4` -> `1.0.0`)
+- rework Kafka message publishing to be more efficient and support tracing
+- reduce log noise
+- various security fixes
+
+Version: 14.X.X
+---------------
+
+General
+-------
+
+Features
+^^^^^^^^
+
+- Java upgrade (`8` -> `11`)
+- Janusgraph upgrade (`0.2.3` -> `0.6.4`)
+- Spring-boot upgrade (`2.4.13` -> `2.5.15`)
+- add db-backed pagination which greatly improves performance of this type of requests
+
+Version: 13.0.1
+---------------
+
+General
+-------
+
+Features
+^^^^^^^^
+
+- replace dmaap dependency with kafka
+- make root logging level configurable via chart
+- schema update to `v29`:
+ * New `service-instance` attributes added in AAI schema
+ * New `slice-profile` attributes added in AAI schema
+ * Added New Object: `feasibility-check-job` in the schema
+ * Added new Edge Rule for `feasibility-check-job`, `slice-profile` and `service-subscription`
+
+aai-common (`1.13.6`)
+---------------------
+
+Features
+^^^^^^^^
+
+- update tinkerpop from `3.2.3` to `3.2.11`
+- improve some bean loading for schema generation related objects
+
+resources (`1.13.5`)
+--------------------
+
+Features
+^^^^^^^^
+
+- update aai-common version to `1.13.6`
+- make project runnable locally via `mvn spring-boot:run`
+- migrate to Junit 5
+
+Fixes
+^^^^^
+
+- do not throw exception to communicate ok response in echo/liveness probe
+
+traversal (`1.13.5`)
+--------------------
+
+Features
+^^^^^^^^
+
+- update aai-common version to `1.13.6`
+- use newer java 8 base image
+
+model-loader (`1.14.1`)
+-----------------------
+
+Features
+^^^^^^^^
+
+- update dependencies (in particular spring-boot `2.1` to `2.7`)
+- code refactorings (model controller, less by-reference parameter updates, spring RestTemplate instead of aai rest client)
+- tracing support
+- add spring-boot actuator to enable liveness probes
+
+graphadmin (`1.13.7`)
+---------------------
+
+Features
+^^^^^^^^
+
+- update aai-common to `1.13.6`
+
+babel (`1.13.1`)
+----------------
+
+Features
+^^^^^^^^
+
+- remove AAF dependency, update dependencies
+- support tracing
+
+Fixes
+^^^^^
+
+- service was returning text/plain response with json response body
+
+:Release Date: 2024-06-13
+
Version: 13.0.0
---------------
Quick links:
-- `AAI project page <https://wiki.onap.org/display/DW/Active+and+Available+Inventory+Project>`_
+- `AAI project page <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16230663/Active+and+Available+Inventory+Project>`_
- `Passing Badge information for AAI <https://bestpractices.coreinfrastructure.org/en/projects/1591>`_
For more information on the ONAP Honolulu release, please see:
#. `ONAP Wiki Page`_
.. _`ONAP Home Page`: https://www.onap.org
-.. _`ONAP Wiki Page`: https://wiki.onap.org
+.. _`ONAP Wiki Page`: https://lf-onap.atlassian.net
.. _`ONAP Documentation`: https://docs.onap.org
.. _`ONAP Release Downloads`: https://git.onap.org
Quick links:
-- `AAI project page <https://wiki.onap.org/display/DW/Active+and+Available+Inventory+Project>`_
+- `AAI project page <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16230663/Active+and+Available+Inventory+Project>`_
- `Passing Badge information for AAI <https://bestpractices.coreinfrastructure.org/en/projects/1591>`_
For more information on the ONAP Honolulu release, please see:
#. `ONAP Wiki Page`_
.. _`ONAP Home Page`: https://www.onap.org
-.. _`ONAP Wiki Page`: https://wiki.onap.org
+.. _`ONAP Wiki Page`: https://lf-onap.atlassian.net
.. _`ONAP Documentation`: https://docs.onap.org
.. _`ONAP Release Downloads`: https://git.onap.org
Quick links:
-- `AAI project page <https://wiki.onap.org/display/DW/Active+and+Available+Inventory+Project>`_
+- `AAI project page <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16230663/Active+and+Available+Inventory+Project>`_
- `Passing Badge information for AAI <https://bestpractices.coreinfrastructure.org/en/projects/1591>`_
For more information on the ONAP Honolulu release, please see:
#. `ONAP Wiki Page`_
.. _`ONAP Home Page`: https://www.onap.org
-.. _`ONAP Wiki Page`: https://wiki.onap.org
+.. _`ONAP Wiki Page`: https://lf-onap.atlassian.net
.. _`ONAP Documentation`: https://docs.onap.org
.. _`ONAP Release Downloads`: https://git.onap.org
Known Issues
------------
-* `AAI-3219 <https://jira.onap.org/browse/AAI-3219>`_ - AAI-EVENT notifications failed to be published to DMaap
+* `AAI-3219 <https://lf-onap.atlassian.net/browse/AAI-3219>`_ - AAI-EVENT notifications failed to be published to DMaap
Workarounds
-----------
Quick links:
-- `AAI project page <https://wiki.onap.org/display/DW/Active+and+Available+Inventory+Project>`_
+- `AAI project page <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16230663/Active+and+Available+Inventory+Project>`_
- `Passing Badge information for AAI <https://bestpractices.coreinfrastructure.org/en/projects/1591>`_
For more information on the ONAP Guilin release, please see:
#. `ONAP Wiki Page`_
.. _`ONAP Home Page`: https://www.onap.org
-.. _`ONAP Wiki Page`: https://wiki.onap.org
+.. _`ONAP Wiki Page`: https://lf-onap.atlassian.net
.. _`ONAP Documentation`: https://docs.onap.org
.. _`ONAP Release Downloads`: https://git.onap.org
Known Issues
------------
-* `AAI-2766 <https://jira.onap.org/browse/AAI-2766>`_ - AAI data-router cannot communicate with DMaaP message router service
-* `AAI-2905 <https://jira.onap.org/browse/AAI-2905>`_ - AAI sparky cannot communicate with portal due to certificate issue, might be related to https://jira.onap.org/browse/PORTAL-875
+* `AAI-2766 <https://lf-onap.atlassian.net/browse/AAI-2766>`_ - AAI data-router cannot communicate with DMaaP message router service
+* `AAI-2905 <https://lf-onap.atlassian.net/browse/AAI-2905>`_ - AAI sparky cannot communicate with portal due to certificate issue, might be related to https://lf-onap.atlassian.net/browse/PORTAL-875
The AAI sub-project External System Registry (ESR) is re-using elalto containers. The integration team has helped ESR to meet security requirements for Frankfurt, and the AAI is grateful for the contribution.
Quick links:
-- `AAI project page <https://wiki.onap.org/display/DW/Active+and+Available+Inventory+Project>`_
+- `AAI project page <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16230663/Active+and+Available+Inventory+Project>`_
- `Passing Badge information for AAI <https://bestpractices.coreinfrastructure.org/en/projects/1591>`_
For more information on the ONAP Frankfurt release, please see:
#. `ONAP Wiki Page`_
.. _`ONAP Home Page`: https://www.onap.org
-.. _`ONAP Wiki Page`: https://wiki.onap.org
+.. _`ONAP Wiki Page`: https://lf-onap.atlassian.net
.. _`ONAP Documentation`: https://docs.onap.org
.. _`ONAP Release Downloads`: https://git.onap.org
curl -v -k -u "$CRED" -H "Content-Type: application/UserRoleRequest+json" $URL/authz/userRole -d '{ "user":"demo@people.osaaf.org", "role":"org.onap.aai.aaiui" }'
Frankfurt will include the role and role assignment in the
-default bootstrap data (being tracked under `AAI-2475 <https://jira.onap.org/browse/AAI-2475>`__)
+default bootstrap data (being tracked under `AAI-2475 <https://lf-onap.atlassian.net/browse/AAI-2475>`__)
-- `AAI-2606 <https://jira.onap.org/browse/AAI-2606>`_ Schema-service entity description is not available
+- `AAI-2606 <https://lf-onap.atlassian.net/browse/AAI-2606>`_ Schema-service entity description is not available
-- `AAI-2457 <https://jira.onap.org/browse/AAI-2457>`_ Inconsistent error messages when getting AAI resources
+- `AAI-2457 <https://lf-onap.atlassian.net/browse/AAI-2457>`_ Inconsistent error messages when getting AAI resources
-- `AAI-2457 <https://jira.onap.org/browse/AAI-2457>`_ Inconsistent error messages when getting AAI resources
+- `AAI-2457 <https://lf-onap.atlassian.net/browse/AAI-2457>`_ Inconsistent error messages when getting AAI resources
-- `AAI-2092 <https://jira.onap.org/browse/AAI-2092>`_ aai-resources does excessive amounts of logging
+- `AAI-2092 <https://lf-onap.atlassian.net/browse/AAI-2092>`_ aai-resources does excessive amounts of logging
-- `AAI-2082 <https://jira.onap.org/browse/AAI-2082>`_ aai-resources gives incorrect output when aai-cassandra has shutdown with failure
+- `AAI-2082 <https://lf-onap.atlassian.net/browse/AAI-2082>`_ aai-resources gives incorrect output when aai-cassandra has shutdown with failure
Quick Links:
-- `Active and Available Inventory project page <https://wiki.onap.org/display/DW/Active+and+Available+Inventory+Project>`_
+- `Active and Available Inventory project page <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16230663/Active+and+Available+Inventory+Project>`_
- `R5 Passing Badge information for AAI <https://bestpractices.coreinfrastructure.org/en/projects/1591>`_
-- `R5 Project Vulnerability Review Table for AAI <https://wiki.onap.org/pages/viewpage.action?pageId=64003431>`_
-
Version: 1.4.0
--------------
AAI delivered 55%+ test coverage on all Java-based repos.
-See `AAI-1779 <https://jira.onap.org/browse/AAI-1779>`__ for details
+See `AAI-1779 <https://lf-onap.atlassian.net/browse/AAI-1779>`__ for details
on the schema updates in R4.
Some AAI services can be configured to leverage the ONAP Pluggable
curl -v -k -u "$CRED" -H "Content-Type: application/UserRoleRequest+json" $URL/authz/userRole -d '{ "user":"demo@people.osaaf.org", "role":"org.onap.aai.aaiui" }'
Future releases will include the role and role assignment in the
-default bootstrap data (being tracked under `AAI-2475 <https://jira.onap.org/browse/AAI-2475>`__)
+default bootstrap data (being tracked under `AAI-2475 <https://lf-onap.atlassian.net/browse/AAI-2475>`__)
**Security Notes**
*Fixed Security Issues*
-- `OJSI-114 <https://jira.onap.org/browse/OJSI-114>`_ In default deployment AAI (aai) exposes HTTP port 30232 outside of cluster.
+- `OJSI-114 <https://lf-onap.atlassian.net/browse/OJSI-114>`_ In default deployment AAI (aai) exposes HTTP port 30232 outside of cluster.
*Known Security Issues*
*Known Vulnerabilities in Used Modules*
-AAI code has been formally scanned during build time using NexusIQ and all Critical vulnerabilities have been addressed, items that remain open have been assessed for risk and determined to be false positive. The AAI open Critical security vulnerabilities and their risk assessment have been documented as part of the `R4 project wiki <https://wiki.onap.org/pages/viewpage.action?pageId=64003431>`_.
+AAI code has been formally scanned during build time using NexusIQ and all Critical vulnerabilities have been addressed, items that remain open have been assessed for risk and determined to be false positive. The AAI open Critical security vulnerabilities and their risk assessment have been documented as part of the `R4 project wiki <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16335975/AAI+R4+Release+Planning>`_.
Quick Links:
-- `AAI project page <https://wiki.onap.org/display/DW/Active+and+Available+Inventory+Project>`_
+- `AAI project page <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16230663/Active+and+Available+Inventory+Project>`_
- `Passing Badge information for AAI <https://bestpractices.coreinfrastructure.org/en/projects/1591>`_
-- `R4 Project Vulnerability Review Table for AAI <https://wiki.onap.org/pages/viewpage.action?pageId=64003431>`_
+- `R4 Project Vulnerability Review Table for AAI <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16335975/AAI+R4+Release+Planning>`_
AAI demo certificates were going to expire before Dublin release, so they've been refreshed to last until 2020.
-- `AAI-2282 <https://jira.onap.org/browse/AAI-2282>`_ Update certifcate for Casablanca 3.0.2
+- `AAI-2282 <https://lf-onap.atlassian.net/browse/AAI-2282>`_ Update certifcate for Casablanca 3.0.2
Version: 1.3.1
--------------
bug fixes. Highlights of the issues corrected in the Casablanca
Maintenance Release:
-- `AAI-2047 <https://jira.onap.org/browse/AAI-2047>`_ Make success of createDbSchema job required to proceed in AAI startup
+- `AAI-2047 <https://lf-onap.atlassian.net/browse/AAI-2047>`_ Make success of createDbSchema job required to proceed in AAI startup
-- `AAI-1923 <https://jira.onap.org/browse/AAI-1923>`_ Problem deleting due to EdgeRules in CCVPN usecase Casablanca
+- `AAI-1923 <https://lf-onap.atlassian.net/browse/AAI-1923>`_ Problem deleting due to EdgeRules in CCVPN usecase Casablanca
-- `AAI-1776 <https://jira.onap.org/browse/AAI-1776>`_ Champ fails to start
+- `AAI-1776 <https://lf-onap.atlassian.net/browse/AAI-1776>`_ Champ fails to start
-- `AAI-1958 <https://jira.onap.org/browse/AAI-1958>`_ [graphadmin] createDbSchema.sh job loses detailed logfile
+- `AAI-1958 <https://lf-onap.atlassian.net/browse/AAI-1958>`_ [graphadmin] createDbSchema.sh job loses detailed logfile
-- `AAI-1973 <https://jira.onap.org/browse/AAI-1973>`_ Schema update wiki is out of data of Casablanca
+- `AAI-1973 <https://lf-onap.atlassian.net/browse/AAI-1973>`_ Schema update wiki is out of data of Casablanca
-- `AAI-2058 <https://jira.onap.org/browse/AAI-2058>`_ Upgrade to latest jetty-security
+- `AAI-2058 <https://lf-onap.atlassian.net/browse/AAI-2058>`_ Upgrade to latest jetty-security
-- `AAI-2076 <https://jira.onap.org/browse/AAI-2076>`_ A&AI healthcheck timeout
+- `AAI-2076 <https://lf-onap.atlassian.net/browse/AAI-2076>`_ A&AI healthcheck timeout
-- `AAI-2079 <https://jira.onap.org/browse/AAI-2079>`_ aai-traversal and aai container failure to deploy issues in casablanca 3.0.0-ONAP
+- `AAI-2079 <https://lf-onap.atlassian.net/browse/AAI-2079>`_ aai-traversal and aai container failure to deploy issues in casablanca 3.0.0-ONAP
Dependencies were updated in multiple repos to patch security
vulnerabilities.
**Known Issues**
-- `AAI-2090 <https://jira.onap.org/browse/AAI-2090>`_ aai-data-router pod enters CrashLoopBackOff state
+- `AAI-2090 <https://lf-onap.atlassian.net/browse/AAI-2090>`_ aai-data-router pod enters CrashLoopBackOff state
This issue can still present itself if you use the OOM chart which
references version 1.3.2 (which is the version specified in the
docker-manifest to override. File is oom/kubernetes/aai/charts/aai-data-router/values.yaml
Users should pay special attention to `AAI-2064
-<https://jira.onap.org/browse/AAI-2064>`_ and should consult `this
+<https://lf-onap.atlassian.net/browse/AAI-2064>`_ and should consult `this
page <https://www.rabbitmq.com/ssl.html>`_ for instructions on how to
properly secure it if they are concerned about the issue.
open have been assessed for risk and determined to be false
positive. The AAI open Critical security vulnerabilities and their
risk assessment have been documented as part of the `R3 project wiki
-<https://wiki.onap.org/pages/viewpage.action?pageId=45307817>`_.
+<https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16296535/AAI+R3+Release+Planning>`_.
Quick Links:
-- `AAI main project page <https://wiki.onap.org/display/DW/Active+and+Available+Inventory+Project>`_
-- `CMR Vulnerability Review Table for AAI <https://wiki.onap.org/pages/viewpage.action?pageId=45307817>`_
+- `AAI main project page <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16230663/Active+and+Available+Inventory+Project>`_
+- `CMR Vulnerability Review Table for AAI <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16309541/AAI+R3+Security+Vulnerability+Threat+Analysis>`_
Version: 1.3.0
**Known Issues**
-Please find at this link the list of issues that will be fixed in the `Casablanca Maintenance Release <https://jira.onap.org/issues/?jql=fixVersion%20%3D%20%22Casablanca%20Maintenance%20Release%22%20and%20type%20%3D%20Bug%20and%20project%20%3D%20%22Active%20and%20Available%20Inventory%22>`_
+Please find at this link the list of issues that will be fixed in the `Casablanca Maintenance Release <https://lf-onap.atlassian.net/issues/?jql=fixVersion%20%3D%20%22Casablanca%20Maintenance%20Release%22%20and%20type%20%3D%20Bug%20and%20project%20%3D%20%22Active%20and%20Available%20Inventory%22>`_
**Security Notes**
-AAI code has been formally scanned during build time using NexusIQ and all Critical vulnerabilities have been addressed, items that remain open have been assessed for risk and determined to be false positive. The AAI open Critical security vulnerabilities and their risk assessment have been documented as part of the `R2 project wiki <https://wiki.onap.org/pages/viewpage.action?pageId=45307817>`_.
+AAI code has been formally scanned during build time using NexusIQ and all Critical vulnerabilities have been addressed, items that remain open have been assessed for risk and determined to be false positive. The AAI open Critical security vulnerabilities and their risk assessment have been documented as part of the `R2 project wiki <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16258007/AAI+R2+Release+Planning>`_.
Quick Links:
-- `AAI project page <https://wiki.onap.org/display/DW/Active+and+Available+Inventory+Project>`_
+- `AAI project page <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16230663/Active+and+Available+Inventory+Project>`_
- `Passing Badge information for AAI <https://bestpractices.coreinfrastructure.org/en/projects/1591>`_
-- `R3 Project Vulnerability Review Table for AAI <https://wiki.onap.org/pages/viewpage.action?pageId=45307817>`_
+- `R3 Project Vulnerability Review Table for AAI <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16309541/AAI+R3+Security+Vulnerability+Threat+Analysis>`_
Version: 1.2.0
**Epic**
-- `AAI-16 <https://jira.onap.org/browse/AAI-16>`_ A&AI Platform Deployment
+- `AAI-16 <https://lf-onap.atlassian.net/browse/AAI-16>`_ A&AI Platform Deployment
-- `AAI-17 <https://jira.onap.org/browse/AAI-17>`_ Seed code stabilization
+- `AAI-17 <https://lf-onap.atlassian.net/browse/AAI-17>`_ Seed code stabilization
-- `AAI-21 <https://jira.onap.org/browse/AAI-21>`_ Gizmo
+- `AAI-21 <https://lf-onap.atlassian.net/browse/AAI-21>`_ Gizmo
-- `AAI-24 <https://jira.onap.org/browse/AAI-24>`_ Move to Active Open Source Graph Database
+- `AAI-24 <https://lf-onap.atlassian.net/browse/AAI-24>`_ Move to Active Open Source Graph Database
-- `AAI-38 <https://jira.onap.org/browse/AAI-38>`_ AAI Microservice to generate AAI model XML
+- `AAI-38 <https://lf-onap.atlassian.net/browse/AAI-38>`_ AAI Microservice to generate AAI model XML
-- `AAI-280 <https://jira.onap.org/browse/AAI-280>`_ This epic groups together the various requests for making AAI more configurable
+- `AAI-280 <https://lf-onap.atlassian.net/browse/AAI-280>`_ This epic groups together the various requests for making AAI more configurable
-- `AAI-466 <https://jira.onap.org/browse/AAI-466>`_ Beijing R2 AAI Schema Updates
+- `AAI-466 <https://lf-onap.atlassian.net/browse/AAI-466>`_ Beijing R2 AAI Schema Updates
-- `AAI-680 <https://jira.onap.org/browse/AAI-680>`_ HPA Use Case Support in AAI
+- `AAI-680 <https://lf-onap.atlassian.net/browse/AAI-680>`_ HPA Use Case Support in AAI
-- `AAI-681 <https://jira.onap.org/browse/AAI-681>`_ Change Management Use Case Support in AAI
+- `AAI-681 <https://lf-onap.atlassian.net/browse/AAI-681>`_ Change Management Use Case Support in AAI
-- `AAI-682 <https://jira.onap.org/browse/AAI-682>`_ Scale Out Use Case Support in AAI
+- `AAI-682 <https://lf-onap.atlassian.net/browse/AAI-682>`_ Scale Out Use Case Support in AAI
-- `AAI-769 <https://jira.onap.org/browse/AAI-769>`_ Required updates to the v13 REST API
+- `AAI-769 <https://lf-onap.atlassian.net/browse/AAI-769>`_ Required updates to the v13 REST API
**Bug Fixes**
-- `AAI-129 <https://jira.onap.org/browse/AAI-129>`_ RestClientBuilder SSL protocol should be configurable
+- `AAI-129 <https://lf-onap.atlassian.net/browse/AAI-129>`_ RestClientBuilder SSL protocol should be configurable
-- `AAI-131 <https://jira.onap.org/browse/AAI-131>`_ Model-Loader service of A&AI has it's Log Provider Configuration File sealed inside the WAR
+- `AAI-131 <https://lf-onap.atlassian.net/browse/AAI-131>`_ Model-Loader service of A&AI has it's Log Provider Configuration File sealed inside the WAR
-- `AAI-175 <https://jira.onap.org/browse/AAI-175>`_ aai core service of A&AI has it's Log Provider Configuration File configurable from startup.sh
+- `AAI-175 <https://lf-onap.atlassian.net/browse/AAI-175>`_ aai core service of A&AI has it's Log Provider Configuration File configurable from startup.sh
-- `AAI-295 <https://jira.onap.org/browse/AAI-295>`_ ChampDAO tests failing in gizmo
+- `AAI-295 <https://lf-onap.atlassian.net/browse/AAI-295>`_ ChampDAO tests failing in gizmo
-- `AAI-460 <https://jira.onap.org/browse/AAI-460>`_ vm1-aai-inst1 aai-resources fails to start
+- `AAI-460 <https://lf-onap.atlassian.net/browse/AAI-460>`_ vm1-aai-inst1 aai-resources fails to start
-- `AAI-463 <https://jira.onap.org/browse/AAI-463>`_ Wrong Error message when we use PUT instead of POST to create the relationship
+- `AAI-463 <https://lf-onap.atlassian.net/browse/AAI-463>`_ Wrong Error message when we use PUT instead of POST to create the relationship
-- `AAI-521 <https://jira.onap.org/browse/AAI-521>`_ A&AI resources container sporadically hangs on startup
+- `AAI-521 <https://lf-onap.atlassian.net/browse/AAI-521>`_ A&AI resources container sporadically hangs on startup
-- `AAI-523 <https://jira.onap.org/browse/AAI-523>`_ Sparky UI does not display RelationshipList nodes
+- `AAI-523 <https://lf-onap.atlassian.net/browse/AAI-523>`_ Sparky UI does not display RelationshipList nodes
-- `AAI-558 <https://jira.onap.org/browse/AAI-558>`_ aai-resources java daily jenkins job is failing
+- `AAI-558 <https://lf-onap.atlassian.net/browse/AAI-558>`_ aai-resources java daily jenkins job is failing
-- `AAI-559 <https://jira.onap.org/browse/AAI-559>`_ CSIT jobs should use a set of streams, not a list of branches
+- `AAI-559 <https://lf-onap.atlassian.net/browse/AAI-559>`_ CSIT jobs should use a set of streams, not a list of branches
-- `AAI-561 <https://jira.onap.org/browse/AAI-561>`_ aai-traversal java daily jenkins job is failing
+- `AAI-561 <https://lf-onap.atlassian.net/browse/AAI-561>`_ aai-traversal java daily jenkins job is failing
-- `AAI-568 <https://jira.onap.org/browse/AAI-568>`_ aai/logging-api build fails on license.txt not found when run outside of aai/logging-service dir - for root CI builds
+- `AAI-568 <https://lf-onap.atlassian.net/browse/AAI-568>`_ aai/logging-api build fails on license.txt not found when run outside of aai/logging-service dir - for root CI builds
-- `AAI-601 <https://jira.onap.org/browse/AAI-601>`_ AAI search-data-service build failing on 1.1 JAX-RS instead of required 2.0 library only on clean Ubuntu 16.04/JDK1.8.0_151
+- `AAI-601 <https://lf-onap.atlassian.net/browse/AAI-601>`_ AAI search-data-service build failing on 1.1 JAX-RS instead of required 2.0 library only on clean Ubuntu 16.04/JDK1.8.0_151
-- `AAI-603 <https://jira.onap.org/browse/AAI-603>`_ Sonar only push to master
+- `AAI-603 <https://lf-onap.atlassian.net/browse/AAI-603>`_ Sonar only push to master
-- `AAI-666 <https://jira.onap.org/browse/AAI-666>`_ aai/datarouter startup fails to find logback.xml
+- `AAI-666 <https://lf-onap.atlassian.net/browse/AAI-666>`_ aai/datarouter startup fails to find logback.xml
-- `AAI-679 <https://jira.onap.org/browse/AAI-679>`_ A&AI UI failed to search service-instance based on service-instance-id
+- `AAI-679 <https://lf-onap.atlassian.net/browse/AAI-679>`_ A&AI UI failed to search service-instance based on service-instance-id
-- `AAI-699 <https://jira.onap.org/browse/AAI-699>`_ SDC Tosca does not generate Groups from resource yaml
+- `AAI-699 <https://lf-onap.atlassian.net/browse/AAI-699>`_ SDC Tosca does not generate Groups from resource yaml
-- `AAI-738 <https://jira.onap.org/browse/AAI-738>`_ When register service to MSB, esr-server still will register to MSB automaticly
+- `AAI-738 <https://lf-onap.atlassian.net/browse/AAI-738>`_ When register service to MSB, esr-server still will register to MSB automaticly
-- `AAI-788 <https://jira.onap.org/browse/AAI-788>`_ fix the cookie decryption algorithm
+- `AAI-788 <https://lf-onap.atlassian.net/browse/AAI-788>`_ fix the cookie decryption algorithm
-- `AAI-796 <https://jira.onap.org/browse/AAI-796>`_ AAI is logging %PARSER_ERROR instead of REMOTE_USER
+- `AAI-796 <https://lf-onap.atlassian.net/browse/AAI-796>`_ AAI is logging %PARSER_ERROR instead of REMOTE_USER
-- `AAI-833 <https://jira.onap.org/browse/AAI-833>`_ The url of query vim type from multiCloud is incorrect
+- `AAI-833 <https://lf-onap.atlassian.net/browse/AAI-833>`_ The url of query vim type from multiCloud is incorrect
-- `AAI-838 <https://jira.onap.org/browse/AAI-838>`_ Add back the properties that got removed
+- `AAI-838 <https://lf-onap.atlassian.net/browse/AAI-838>`_ Add back the properties that got removed
-- `AAI-874 <https://jira.onap.org/browse/AAI-874>`_ Fix the test-config traversal aaiconfig to use proper timeout keys
+- `AAI-874 <https://lf-onap.atlassian.net/browse/AAI-874>`_ Fix the test-config traversal aaiconfig to use proper timeout keys
-- `AAI-948 <https://jira.onap.org/browse/AAI-948>`_ aai-rest-client build fails with non-resolvable parent POM
+- `AAI-948 <https://lf-onap.atlassian.net/browse/AAI-948>`_ aai-rest-client build fails with non-resolvable parent POM
-- `AAI-961 <https://jira.onap.org/browse/AAI-961>`_ Fix aai-sparky-be-master-aai-docker-java-daily
+- `AAI-961 <https://lf-onap.atlassian.net/browse/AAI-961>`_ Fix aai-sparky-be-master-aai-docker-java-daily
-- `AAI-985 <https://jira.onap.org/browse/AAI-985>`_ Sparky-be: Change dependency to make use of sparky-fe war file from Beijing version
+- `AAI-985 <https://lf-onap.atlassian.net/browse/AAI-985>`_ Sparky-be: Change dependency to make use of sparky-fe war file from Beijing version
-- `AAI-987 <https://jira.onap.org/browse/AAI-987>`_ Update ML with the latest changes
+- `AAI-987 <https://lf-onap.atlassian.net/browse/AAI-987>`_ Update ML with the latest changes
-- `AAI-993 <https://jira.onap.org/browse/AAI-993>`_ Champ docker image name incorrect
+- `AAI-993 <https://lf-onap.atlassian.net/browse/AAI-993>`_ Champ docker image name incorrect
-- `AAI-994 <https://jira.onap.org/browse/AAI-994>`_ Crud-service (Gizmo) docker tag version is incorrect
+- `AAI-994 <https://lf-onap.atlassian.net/browse/AAI-994>`_ Crud-service (Gizmo) docker tag version is incorrect
-- `AAI-995 <https://jira.onap.org/browse/AAI-995>`_ Gizmo docker image name incorrect
+- `AAI-995 <https://lf-onap.atlassian.net/browse/AAI-995>`_ Gizmo docker image name incorrect
-- `AAI-996 <https://jira.onap.org/browse/AAI-996>`_ Change ML pom file to address build failure problems
+- `AAI-996 <https://lf-onap.atlassian.net/browse/AAI-996>`_ Change ML pom file to address build failure problems
-- `AAI-1005 <https://jira.onap.org/browse/AAI-1005>`_ Fix docker-compose-db.yml in test-config
+- `AAI-1005 <https://lf-onap.atlassian.net/browse/AAI-1005>`_ Fix docker-compose-db.yml in test-config
-- `AAI-1006 <https://jira.onap.org/browse/AAI-1006>`_ Babel start script does not set all required properties
+- `AAI-1006 <https://lf-onap.atlassian.net/browse/AAI-1006>`_ Babel start script does not set all required properties
-- `AAI-1007 <https://jira.onap.org/browse/AAI-1007>`_ Babel: java.lang.NoClassDefFoundError: com/att/aft/dme2/internal/gson/JsonSyntaxException
+- `AAI-1007 <https://lf-onap.atlassian.net/browse/AAI-1007>`_ Babel: java.lang.NoClassDefFoundError: com/att/aft/dme2/internal/gson/JsonSyntaxException
-- `AAI-1016 <https://jira.onap.org/browse/AAI-1016>`_ Model-loader: properties files are incorrectly named and have errors
+- `AAI-1016 <https://lf-onap.atlassian.net/browse/AAI-1016>`_ Model-loader: properties files are incorrectly named and have errors
-- `AAI-1017 <https://jira.onap.org/browse/AAI-1017>`_ Fix Champ build - incorrect definition of Java system path
+- `AAI-1017 <https://lf-onap.atlassian.net/browse/AAI-1017>`_ Fix Champ build - incorrect definition of Java system path
-- `AAI-1018 <https://jira.onap.org/browse/AAI-1018>`_ Model-loader: CONF_INVALID_MSG_BUS_ADDRESS
+- `AAI-1018 <https://lf-onap.atlassian.net/browse/AAI-1018>`_ Model-loader: CONF_INVALID_MSG_BUS_ADDRESS
-- `AAI-1019 <https://jira.onap.org/browse/AAI-1019>`_ aai-resources: does not require username/password after springboot upgrade
+- `AAI-1019 <https://lf-onap.atlassian.net/browse/AAI-1019>`_ aai-resources: does not require username/password after springboot upgrade
-- `AAI-1020 <https://jira.onap.org/browse/AAI-1020>`_ aai-traversal: does not require username/password after springboot upgrade
+- `AAI-1020 <https://lf-onap.atlassian.net/browse/AAI-1020>`_ aai-traversal: does not require username/password after springboot upgrade
-- `AAI-1024 <https://jira.onap.org/browse/AAI-1024>`_ Test-config: model-loader MSG_BUS_ADDRESSES not set
+- `AAI-1024 <https://lf-onap.atlassian.net/browse/AAI-1024>`_ Test-config: model-loader MSG_BUS_ADDRESSES not set
-- `AAI-1025 <https://jira.onap.org/browse/AAI-1025>`_ Test-config: traversal updateQueryData.sh fails to update models and queries
+- `AAI-1025 <https://lf-onap.atlassian.net/browse/AAI-1025>`_ Test-config: traversal updateQueryData.sh fails to update models and queries
-- `AAI-1026 <https://jira.onap.org/browse/AAI-1026>`_ test-config: model-loader is attempting 2-way TLS with AAI
+- `AAI-1026 <https://lf-onap.atlassian.net/browse/AAI-1026>`_ test-config: model-loader is attempting 2-way TLS with AAI
-- `AAI-1027 <https://jira.onap.org/browse/AAI-1027>`_ ModelLoader basic auth failure with aai-resources
+- `AAI-1027 <https://lf-onap.atlassian.net/browse/AAI-1027>`_ ModelLoader basic auth failure with aai-resources
-- `AAI-1029 <https://jira.onap.org/browse/AAI-1029>`_ The DOC about ESR installation should be update
+- `AAI-1029 <https://lf-onap.atlassian.net/browse/AAI-1029>`_ The DOC about ESR installation should be update
-- `AAI-1034 <https://jira.onap.org/browse/AAI-1034>`_ [sparky-be] Portal API Proxy missing from Spring Boot Sparky
+- `AAI-1034 <https://lf-onap.atlassian.net/browse/AAI-1034>`_ [sparky-be] Portal API Proxy missing from Spring Boot Sparky
-- `AAI-1035 <https://jira.onap.org/browse/AAI-1035>`_ Security: Springboot 1.5.10 has new nexusIQ critical exceptions
+- `AAI-1035 <https://lf-onap.atlassian.net/browse/AAI-1035>`_ Security: Springboot 1.5.10 has new nexusIQ critical exceptions
-- `AAI-1038 <https://jira.onap.org/browse/AAI-1038>`_ Babel missing .gitreview file
+- `AAI-1038 <https://lf-onap.atlassian.net/browse/AAI-1038>`_ Babel missing .gitreview file
-- `AAI-1049 <https://jira.onap.org/browse/AAI-1049>`_ [Model Loader] - Remove dependency on PowerMockito
+- `AAI-1049 <https://lf-onap.atlassian.net/browse/AAI-1049>`_ [Model Loader] - Remove dependency on PowerMockito
-- `AAI-1051 <https://jira.onap.org/browse/AAI-1051>`_ API Spec is specifying v12 in v13 file
+- `AAI-1051 <https://lf-onap.atlassian.net/browse/AAI-1051>`_ API Spec is specifying v12 in v13 file
-- `AAI-1052 <https://jira.onap.org/browse/AAI-1052>`_ AAI is using -SNAPSHOT artifacts; remove -SNAPSHOT dependencies
+- `AAI-1052 <https://lf-onap.atlassian.net/browse/AAI-1052>`_ AAI is using -SNAPSHOT artifacts; remove -SNAPSHOT dependencies
-- `AAI-1077 <https://jira.onap.org/browse/AAI-1077>`_ [Babel] master daily build job is not creating an autorelease staging repo
+- `AAI-1077 <https://lf-onap.atlassian.net/browse/AAI-1077>`_ [Babel] master daily build job is not creating an autorelease staging repo
-- `AAI-1082 <https://jira.onap.org/browse/AAI-1082>`_ Champ janus version incompatible with Resources janus version
+- `AAI-1082 <https://lf-onap.atlassian.net/browse/AAI-1082>`_ Champ janus version incompatible with Resources janus version
-- `AAI-1084 <https://jira.onap.org/browse/AAI-1084>`_ POST with PATCH override call is returning 405
+- `AAI-1084 <https://lf-onap.atlassian.net/browse/AAI-1084>`_ POST with PATCH override call is returning 405
-- `AAI-1086 <https://jira.onap.org/browse/AAI-1086>`_ Babel: Compressed files contain proprietary markings
+- `AAI-1086 <https://lf-onap.atlassian.net/browse/AAI-1086>`_ Babel: Compressed files contain proprietary markings
-- `AAI-1088 <https://jira.onap.org/browse/AAI-1088>`_ aai-common: version.properties refers to previous patch release
+- `AAI-1088 <https://lf-onap.atlassian.net/browse/AAI-1088>`_ aai-common: version.properties refers to previous patch release
-- `AAI-1089 <https://jira.onap.org/browse/AAI-1089>`_ haproxy, aai-resources, and aai-traversal using outdated certificate in HEAT config
+- `AAI-1089 <https://lf-onap.atlassian.net/browse/AAI-1089>`_ haproxy, aai-resources, and aai-traversal using outdated certificate in HEAT config
-- `AAI-1090 <https://jira.onap.org/browse/AAI-1090>`_ v13 does not support External System under cloud region
+- `AAI-1090 <https://lf-onap.atlassian.net/browse/AAI-1090>`_ v13 does not support External System under cloud region
-- `AAI-1091 <https://jira.onap.org/browse/AAI-1091>`_ ESR fails to register EMS
+- `AAI-1091 <https://lf-onap.atlassian.net/browse/AAI-1091>`_ ESR fails to register EMS
-- `AAI-1094 <https://jira.onap.org/browse/AAI-1094>`_ Model-loader: failure to negotiate with message router in OOM
+- `AAI-1094 <https://lf-onap.atlassian.net/browse/AAI-1094>`_ Model-loader: failure to negotiate with message router in OOM
-- `AAI-1096 <https://jira.onap.org/browse/AAI-1096>`_ Increase length for field:password in ESR-GUI VIM registration page
+- `AAI-1096 <https://lf-onap.atlassian.net/browse/AAI-1096>`_ Increase length for field:password in ESR-GUI VIM registration page
-- `AAI-1100 <https://jira.onap.org/browse/AAI-1100>`_ OOM Resources and Traversal Config map missing release
+- `AAI-1100 <https://lf-onap.atlassian.net/browse/AAI-1100>`_ OOM Resources and Traversal Config map missing release
-- `AAI-1101 <https://jira.onap.org/browse/AAI-1101>`_ haproxy, aai-resources, and aai-traversal using outdated certificate in OOM config
+- `AAI-1101 <https://lf-onap.atlassian.net/browse/AAI-1101>`_ haproxy, aai-resources, and aai-traversal using outdated certificate in OOM config
-- `AAI-1105 <https://jira.onap.org/browse/AAI-1105>`_ aai-traversal job is failing when trying to start OOM
+- `AAI-1105 <https://lf-onap.atlassian.net/browse/AAI-1105>`_ aai-traversal job is failing when trying to start OOM
-- `AAI-1106 <https://jira.onap.org/browse/AAI-1106>`_ aai-resources: scripts do not work properly with spring-boot
+- `AAI-1106 <https://lf-onap.atlassian.net/browse/AAI-1106>`_ aai-resources: scripts do not work properly with spring-boot
-- `AAI-1107 <https://jira.onap.org/browse/AAI-1107>`_ Security: babel and m-l brings in springboot jersey starter, which includes logback 1.1.11
+- `AAI-1107 <https://lf-onap.atlassian.net/browse/AAI-1107>`_ Security: babel and m-l brings in springboot jersey starter, which includes logback 1.1.11
-- `AAI-1108 <https://jira.onap.org/browse/AAI-1108>`_ [Babel] Remove license violations in latest commit.
+- `AAI-1108 <https://lf-onap.atlassian.net/browse/AAI-1108>`_ [Babel] Remove license violations in latest commit.
-- `AAI-1110 <https://jira.onap.org/browse/AAI-1110>`_ Model Loader logback.xml errors
+- `AAI-1110 <https://lf-onap.atlassian.net/browse/AAI-1110>`_ Model Loader logback.xml errors
-- `AAI-1111 <https://jira.onap.org/browse/AAI-1111>`_ Update test-config project for Babel
+- `AAI-1111 <https://lf-onap.atlassian.net/browse/AAI-1111>`_ Update test-config project for Babel
-- `AAI-1113 <https://jira.onap.org/browse/AAI-1113>`_ ESR VIM registration portal: Physical Location Id does not populate any data
+- `AAI-1113 <https://lf-onap.atlassian.net/browse/AAI-1113>`_ ESR VIM registration portal: Physical Location Id does not populate any data
-- `AAI-1114 <https://jira.onap.org/browse/AAI-1114>`_ Security: [Champ] add Dockerfile and remove additional AJSC files
+- `AAI-1114 <https://lf-onap.atlassian.net/browse/AAI-1114>`_ Security: [Champ] add Dockerfile and remove additional AJSC files
-- `AAI-1116 <https://jira.onap.org/browse/AAI-1116>`_ [Gizmo] addressing Security vulnerabilities (Nexus IQ)
+- `AAI-1116 <https://lf-onap.atlassian.net/browse/AAI-1116>`_ [Gizmo] addressing Security vulnerabilities (Nexus IQ)
-- `AAI-1117 <https://jira.onap.org/browse/AAI-1117>`_ [Champ] addressing Security vulnerabilities (Nexus IQ)
+- `AAI-1117 <https://lf-onap.atlassian.net/browse/AAI-1117>`_ [Champ] addressing Security vulnerabilities (Nexus IQ)
-- `AAI-1118 <https://jira.onap.org/browse/AAI-1118>`_ [Gizmo] upgrade artefacts from aai-common to 1.2.4
+- `AAI-1118 <https://lf-onap.atlassian.net/browse/AAI-1118>`_ [Gizmo] upgrade artefacts from aai-common to 1.2.4
-- `AAI-1119 <https://jira.onap.org/browse/AAI-1119>`_ [Champ] Prevent deployment of Champ service jar
+- `AAI-1119 <https://lf-onap.atlassian.net/browse/AAI-1119>`_ [Champ] Prevent deployment of Champ service jar
-- `AAI-1120 <https://jira.onap.org/browse/AAI-1120>`_ [Gizmo] Fix Jacoco configuration
+- `AAI-1120 <https://lf-onap.atlassian.net/browse/AAI-1120>`_ [Gizmo] Fix Jacoco configuration
-- `AAI-1121 <https://jira.onap.org/browse/AAI-1121>`_ Add the default realtime clients
+- `AAI-1121 <https://lf-onap.atlassian.net/browse/AAI-1121>`_ Add the default realtime clients
-- `AAI-1123 <https://jira.onap.org/browse/AAI-1123>`_ Babel logback.xml errors
+- `AAI-1123 <https://lf-onap.atlassian.net/browse/AAI-1123>`_ Babel logback.xml errors
-- `AAI-1124 <https://jira.onap.org/browse/AAI-1124>`_ [router-core] NexusIQ reporting httpclient 4.5 vulnerability
+- `AAI-1124 <https://lf-onap.atlassian.net/browse/AAI-1124>`_ [router-core] NexusIQ reporting httpclient 4.5 vulnerability
-- `AAI-1125 <https://jira.onap.org/browse/AAI-1125>`_ [data-router] NexusIQ reporting httpclient 4.5 vulnerability
+- `AAI-1125 <https://lf-onap.atlassian.net/browse/AAI-1125>`_ [data-router] NexusIQ reporting httpclient 4.5 vulnerability
-- `AAI-1126 <https://jira.onap.org/browse/AAI-1126>`_ [Babel] Authorisation mechanism is not functioning
+- `AAI-1126 <https://lf-onap.atlassian.net/browse/AAI-1126>`_ [Babel] Authorisation mechanism is not functioning
-- `AAI-1127 <https://jira.onap.org/browse/AAI-1127>`_ [sparky-be] doesn't release artifacts because it is missing the staging plugin
+- `AAI-1127 <https://lf-onap.atlassian.net/browse/AAI-1127>`_ [sparky-be] doesn't release artifacts because it is missing the staging plugin
-- `AAI-1132 <https://jira.onap.org/browse/AAI-1132>`_ AAI's OOM server certificate doesn't include all k8 names
+- `AAI-1132 <https://lf-onap.atlassian.net/browse/AAI-1132>`_ AAI's OOM server certificate doesn't include all k8 names
-- `AAI-1133 <https://jira.onap.org/browse/AAI-1133>`_ AAI's haproxy server config doesn't include all k8 names
+- `AAI-1133 <https://lf-onap.atlassian.net/browse/AAI-1133>`_ AAI's haproxy server config doesn't include all k8 names
-- `AAI-1134 <https://jira.onap.org/browse/AAI-1134>`_ OOF not defined in AAI realm properties files
+- `AAI-1134 <https://lf-onap.atlassian.net/browse/AAI-1134>`_ OOF not defined in AAI realm properties files
-- `AAI-1135 <https://jira.onap.org/browse/AAI-1135>`_ [traversal] closed loop named-query is missing property-collect-list
+- `AAI-1135 <https://lf-onap.atlassian.net/browse/AAI-1135>`_ [traversal] closed loop named-query is missing property-collect-list
-- `AAI-1136 <https://jira.onap.org/browse/AAI-1136>`_ Babel doesnt start in HEAT due to log directory permissions
+- `AAI-1136 <https://lf-onap.atlassian.net/browse/AAI-1136>`_ Babel doesnt start in HEAT due to log directory permissions
-- `AAI-1138 <https://jira.onap.org/browse/AAI-1138>`_ [Champ] Bump to 1.2.1-SNAPSHOT and 1.2.1 in version.properties
+- `AAI-1138 <https://lf-onap.atlassian.net/browse/AAI-1138>`_ [Champ] Bump to 1.2.1-SNAPSHOT and 1.2.1 in version.properties
-- `AAI-1139 <https://jira.onap.org/browse/AAI-1139>`_ [resources and traversal] do not release artifacts properly
+- `AAI-1139 <https://lf-onap.atlassian.net/browse/AAI-1139>`_ [resources and traversal] do not release artifacts properly
-- `AAI-1141 <https://jira.onap.org/browse/AAI-1141>`_ [champ] duplicate dependency in pom.xml
+- `AAI-1141 <https://lf-onap.atlassian.net/browse/AAI-1141>`_ [champ] duplicate dependency in pom.xml
-- `AAI-1142 <https://jira.onap.org/browse/AAI-1142>`_ [champ] doesn't create release artifacts
+- `AAI-1142 <https://lf-onap.atlassian.net/browse/AAI-1142>`_ [champ] doesn't create release artifacts
-- `AAI-1143 <https://jira.onap.org/browse/AAI-1143>`_ [resources] createDbSchema.sh tries to add -SNAPSHOT version to classpath
+- `AAI-1143 <https://lf-onap.atlassian.net/browse/AAI-1143>`_ [resources] createDbSchema.sh tries to add -SNAPSHOT version to classpath
-- `AAI-1144 <https://jira.onap.org/browse/AAI-1144>`_ [oom and test-config] robot-ete is missing from realtime clients list
+- `AAI-1144 <https://lf-onap.atlassian.net/browse/AAI-1144>`_ [oom and test-config] robot-ete is missing from realtime clients list
-- `AAI-1146 <https://jira.onap.org/browse/AAI-1146>`_ [champ] daily build job is failing
+- `AAI-1146 <https://lf-onap.atlassian.net/browse/AAI-1146>`_ [champ] daily build job is failing
-- `AAI-1148 <https://jira.onap.org/browse/AAI-1148>`_ [Model-Loader] Rollback of VNF Images fails
+- `AAI-1148 <https://lf-onap.atlassian.net/browse/AAI-1148>`_ [Model-Loader] Rollback of VNF Images fails
-- `AAI-1151 <https://jira.onap.org/browse/AAI-1151>`_ [Champ & Gizmo] Fix JJB jenkins jobs
+- `AAI-1151 <https://lf-onap.atlassian.net/browse/AAI-1151>`_ [Champ & Gizmo] Fix JJB jenkins jobs
-- `AAI-1153 <https://jira.onap.org/browse/AAI-1153>`_ [Champ] Bump to 1.2.2-SNAPSHOT and 1.2.2 in version.properties
+- `AAI-1153 <https://lf-onap.atlassian.net/browse/AAI-1153>`_ [Champ] Bump to 1.2.2-SNAPSHOT and 1.2.2 in version.properties
**Known Issues**
**Security Notes**
-AAI code has been formally scanned during build time using NexusIQ and all Critical vulnerabilities have been addressed, items that remain open have been assessed for risk and determined to be false positive. The AAI open Critical security vulnerabilities and their risk assessment have been documented as part of the `project <https://wiki.onap.org/pages/viewpage.action?pageId=25441383>`_.
+AAI code has been formally scanned during build time using NexusIQ and all Critical vulnerabilities have been addressed, items that remain open have been assessed for risk and determined to be false positive. The AAI open Critical security vulnerabilities and their risk assessment have been documented as part of the `project <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16258007/AAI+R2+Release+Planning>`_.
Quick Links:
-- `AAI project page <https://wiki.onap.org/display/DW/Active+and+Available+Inventory+Project>`_
+- `AAI project page <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16230663/Active+and+Available+Inventory+Project>`_
- `Passing Badge information for AAI <https://bestpractices.coreinfrastructure.org/en/projects/1591>`_
-- `R2 Project Vulnerability Review Table for AAI <https://wiki.onap.org/pages/viewpage.action?pageId=25441383>`_
+- `R2 Project Vulnerability Review Table for AAI <https://lf-onap.atlassian.net/wiki/spaces/DW/pages/16276191/AAI+R2+Security+Vulnerability+Threat+Analysis>`_
Version: 1.1.1
--------------
**Bug Fixes**
-- `AAI-456 <https://jira.onap.org/browse/AAI-456>`_ AAI named-query for policy not returning extra-properties
+- `AAI-456 <https://lf-onap.atlassian.net/browse/AAI-456>`_ AAI named-query for policy not returning extra-properties
-- `AAI-458 <https://jira.onap.org/browse/AAI-458>`_ [aai] ML, Search, DR, and Sparky Jenkins jobs not creating autorelease repo
+- `AAI-458 <https://lf-onap.atlassian.net/browse/AAI-458>`_ [aai] ML, Search, DR, and Sparky Jenkins jobs not creating autorelease repo
-- `AAI-459 <https://jira.onap.org/browse/AAI-459>`_ aai-common child pom still depends on openecomp artifacts
+- `AAI-459 <https://lf-onap.atlassian.net/browse/AAI-459>`_ aai-common child pom still depends on openecomp artifacts
-- `AAI-461 <https://jira.onap.org/browse/AAI-461>`_ AAI mS configuration files are using old openecomp params in test-config
+- `AAI-461 <https://lf-onap.atlassian.net/browse/AAI-461>`_ AAI mS configuration files are using old openecomp params in test-config
-- `AAI-462 <https://jira.onap.org/browse/AAI-462>`_ Fix the resources junit tests broken in windows environment
+- `AAI-462 <https://lf-onap.atlassian.net/browse/AAI-462>`_ Fix the resources junit tests broken in windows environment
-- `AAI-558 <https://jira.onap.org/browse/AAI-558>`_ aai-resources java daily jenkins job is failing
+- `AAI-558 <https://lf-onap.atlassian.net/browse/AAI-558>`_ aai-resources java daily jenkins job is failing
-- `AAI-561 <https://jira.onap.org/browse/AAI-561>`_ aai-traversal java daily jenkins job is failing
+- `AAI-561 <https://lf-onap.atlassian.net/browse/AAI-561>`_ aai-traversal java daily jenkins job is failing
-- `AAI-566 <https://jira.onap.org/browse/AAI-566>`_ AAI Eclipse build failure - aai-traversal pom as hardcoded 1.8.0_101 jdk.tools version
+- `AAI-566 <https://lf-onap.atlassian.net/browse/AAI-566>`_ AAI Eclipse build failure - aai-traversal pom as hardcoded 1.8.0_101 jdk.tools version
-- `AAI-621 <https://jira.onap.org/browse/AAI-621>`_ Update the snapshot in test-config for v1.1.1-SNAPSHOT
+- `AAI-621 <https://lf-onap.atlassian.net/browse/AAI-621>`_ Update the snapshot in test-config for v1.1.1-SNAPSHOT
Version: 1.1.0
--------------
**Epic**
-- `AAI-17 <https://jira.onap.org/browse/AAI-17>`_ Seed code stabilization
-- `AAI-20 <https://jira.onap.org/browse/AAI-20>`_ Champ Library
-- `AAI-22 <https://jira.onap.org/browse/AAI-22>`_ Amsterdam User Case Schema Updates
-- `AAI-23 <https://jira.onap.org/browse/AAI-23>`_ Model Loader Support for R1
-- `AAI-58 <https://jira.onap.org/browse/AAI-58>`_ Define and build functional test cases for CSIT
-- `AAI-72 <https://jira.onap.org/browse/AAI-72>`_ External System Register
-- `AAI-254 <https://jira.onap.org/browse/AAI-254>`_ Documentation of REST APIs, dev guides, onboarding, etc.
-- `AAI-280 <https://jira.onap.org/browse/AAI-280>`_ Confguration enhancements
+- `AAI-17 <https://lf-onap.atlassian.net/browse/AAI-17>`_ Seed code stabilization
+- `AAI-20 <https://lf-onap.atlassian.net/browse/AAI-20>`_ Champ Library
+- `AAI-22 <https://lf-onap.atlassian.net/browse/AAI-22>`_ Amsterdam User Case Schema Updates
+- `AAI-23 <https://lf-onap.atlassian.net/browse/AAI-23>`_ Model Loader Support for R1
+- `AAI-58 <https://lf-onap.atlassian.net/browse/AAI-58>`_ Define and build functional test cases for CSIT
+- `AAI-72 <https://lf-onap.atlassian.net/browse/AAI-72>`_ External System Register
+- `AAI-254 <https://lf-onap.atlassian.net/browse/AAI-254>`_ Documentation of REST APIs, dev guides, onboarding, etc.
+- `AAI-280 <https://lf-onap.atlassian.net/browse/AAI-280>`_ Confguration enhancements
**Bug Fixes**
-- `AAI-11 <https://jira.onap.org/browse/AAI-11>`_ robot_vm: demo.sh failing - '200' does not match '^(201|412)$' on vanilla openstack
+- `AAI-11 <https://lf-onap.atlassian.net/browse/AAI-11>`_ robot_vm: demo.sh failing - '200' does not match '^(201|412)$' on vanilla openstack
-- `AAI-13 <https://jira.onap.org/browse/AAI-13>`_ VM_init is failing to get sparky
+- `AAI-13 <https://lf-onap.atlassian.net/browse/AAI-13>`_ VM_init is failing to get sparky
-- `AAI-31 <https://jira.onap.org/browse/AAI-31>`_ Compilation failure in aai-traversal
+- `AAI-31 <https://lf-onap.atlassian.net/browse/AAI-31>`_ Compilation failure in aai-traversal
-- `AAI-48 <https://jira.onap.org/browse/AAI-48>`_ AAI Common REST Client returns an error on a 204 (No Content) server response
+- `AAI-48 <https://lf-onap.atlassian.net/browse/AAI-48>`_ AAI Common REST Client returns an error on a 204 (No Content) server response
-- `AAI-49 <https://jira.onap.org/browse/AAI-49>`_ Health check is failing in DFW 1.1 RS. Connection refused
+- `AAI-49 <https://lf-onap.atlassian.net/browse/AAI-49>`_ Health check is failing in DFW 1.1 RS. Connection refused
-- `AAI-62 <https://jira.onap.org/browse/AAI-62>`_ Search Data Service should not implicitly create indexes on document write
+- `AAI-62 <https://lf-onap.atlassian.net/browse/AAI-62>`_ Search Data Service should not implicitly create indexes on document write
-- `AAI-63 <https://jira.onap.org/browse/AAI-63>`_ Data Router must handle Search Service document create failures if index does not exit
+- `AAI-63 <https://lf-onap.atlassian.net/browse/AAI-63>`_ Data Router must handle Search Service document create failures if index does not exit
-- `AAI-73 <https://jira.onap.org/browse/AAI-73>`_ Sparky sync issues
+- `AAI-73 <https://lf-onap.atlassian.net/browse/AAI-73>`_ Sparky sync issues
-- `AAI-76 <https://jira.onap.org/browse/AAI-76>`_ Jenkins stage-site builds failing on resources and traversal
+- `AAI-76 <https://lf-onap.atlassian.net/browse/AAI-76>`_ Jenkins stage-site builds failing on resources and traversal
-- `AAI-94 <https://jira.onap.org/browse/AAI-94>`_ AAI Certificate will expire 30 Nov 2017 - fyi
+- `AAI-94 <https://lf-onap.atlassian.net/browse/AAI-94>`_ AAI Certificate will expire 30 Nov 2017 - fyi
-- `AAI-146 <https://jira.onap.org/browse/AAI-146>`_ Both esr-server and esr-gui Jenkins failed
+- `AAI-146 <https://lf-onap.atlassian.net/browse/AAI-146>`_ Both esr-server and esr-gui Jenkins failed
-- `AAI-192 <https://jira.onap.org/browse/AAI-192>`_ Model Loader depends on httpclient version 4.4.1
+- `AAI-192 <https://lf-onap.atlassian.net/browse/AAI-192>`_ Model Loader depends on httpclient version 4.4.1
-- `AAI-205 <https://jira.onap.org/browse/AAI-205>`_ Having an invalid xml namespace for v11, named-query api returns 500 error, model query return incorrect error message
+- `AAI-205 <https://lf-onap.atlassian.net/browse/AAI-205>`_ Having an invalid xml namespace for v11, named-query api returns 500 error, model query return incorrect error message
-- `AAI-206 <https://jira.onap.org/browse/AAI-206>`_ Model based delete is failing
+- `AAI-206 <https://lf-onap.atlassian.net/browse/AAI-206>`_ Model based delete is failing
-- `AAI-217 <https://jira.onap.org/browse/AAI-217>`_ Remove internal references from A&AI seed code
+- `AAI-217 <https://lf-onap.atlassian.net/browse/AAI-217>`_ Remove internal references from A&AI seed code
-- `AAI-222 <https://jira.onap.org/browse/AAI-222>`_ the version property of esr-server is incorrect
+- `AAI-222 <https://lf-onap.atlassian.net/browse/AAI-222>`_ the version property of esr-server is incorrect
-- `AAI-224 <https://jira.onap.org/browse/AAI-224>`_ aai/esr-gui daily build failed
+- `AAI-224 <https://lf-onap.atlassian.net/browse/AAI-224>`_ aai/esr-gui daily build failed
-- `AAI-225 <https://jira.onap.org/browse/AAI-225>`_ aai/esr-server daily build failed
+- `AAI-225 <https://lf-onap.atlassian.net/browse/AAI-225>`_ aai/esr-server daily build failed
-- `AAI-265 <https://jira.onap.org/browse/AAI-265>`_ EdgePropertyMap throws NullPointer if edge rule does not include property
+- `AAI-265 <https://lf-onap.atlassian.net/browse/AAI-265>`_ EdgePropertyMap throws NullPointer if edge rule does not include property
-- `AAI-266 <https://jira.onap.org/browse/AAI-266>`_ auth-info edge rule does not include contains-other-v
+- `AAI-266 <https://lf-onap.atlassian.net/browse/AAI-266>`_ auth-info edge rule does not include contains-other-v
-- `AAI-273 <https://jira.onap.org/browse/AAI-273>`_ Fix the esr-server setup error issue
+- `AAI-273 <https://lf-onap.atlassian.net/browse/AAI-273>`_ Fix the esr-server setup error issue
-- `AAI-278 <https://jira.onap.org/browse/AAI-278>`_ AAI throws exception about mismatch keys adding esr-system-info to cloud-region
+- `AAI-278 <https://lf-onap.atlassian.net/browse/AAI-278>`_ AAI throws exception about mismatch keys adding esr-system-info to cloud-region
-- `AAI-293 <https://jira.onap.org/browse/AAI-293>`_ Jenkins job failing for aai-sparky-fe-master-release-version-java-daily
+- `AAI-293 <https://lf-onap.atlassian.net/browse/AAI-293>`_ Jenkins job failing for aai-sparky-fe-master-release-version-java-daily
-- `AAI-377 <https://jira.onap.org/browse/AAI-377>`_ esr-gui docker build failed
+- `AAI-377 <https://lf-onap.atlassian.net/browse/AAI-377>`_ esr-gui docker build failed
-- `AAI-393 <https://jira.onap.org/browse/AAI-393>`_ The jjb defiend in a error way that cause CSIT build failed.
+- `AAI-393 <https://lf-onap.atlassian.net/browse/AAI-393>`_ The jjb defiend in a error way that cause CSIT build failed.
-- `AAI-398 <https://jira.onap.org/browse/AAI-398>`_ If a cloud-region didn't contain a external system info, there will be an null pointer error
+- `AAI-398 <https://lf-onap.atlassian.net/browse/AAI-398>`_ If a cloud-region didn't contain a external system info, there will be an null pointer error
-- `AAI-400 <https://jira.onap.org/browse/AAI-400>`_ Register ServiceTest to microservice
+- `AAI-400 <https://lf-onap.atlassian.net/browse/AAI-400>`_ Register ServiceTest to microservice
-- `AAI-401 <https://jira.onap.org/browse/AAI-401>`_ Remove DMaaP router duplication
+- `AAI-401 <https://lf-onap.atlassian.net/browse/AAI-401>`_ Remove DMaaP router duplication
-- `AAI-407 <https://jira.onap.org/browse/AAI-407>`_ There is an error to startup esr-gui docker
+- `AAI-407 <https://lf-onap.atlassian.net/browse/AAI-407>`_ There is an error to startup esr-gui docker
-- `AAI-412 <https://jira.onap.org/browse/AAI-412>`_ Replace the type specification in this constructor call with the diamond operator ("<>")
+- `AAI-412 <https://lf-onap.atlassian.net/browse/AAI-412>`_ Replace the type specification in this constructor call with the diamond operator ("<>")
-- `AAI-417 <https://jira.onap.org/browse/AAI-417>`_ Rackspace 20170928 fails to authenticate nexus3 on 10003 during *_init.sh* (sdnc for example)
+- `AAI-417 <https://lf-onap.atlassian.net/browse/AAI-417>`_ Rackspace 20170928 fails to authenticate nexus3 on 10003 during *_init.sh* (sdnc for example)
-- `AAI-420 <https://jira.onap.org/browse/AAI-420>`_ Can not get the MSB address in esr-server
+- `AAI-420 <https://lf-onap.atlassian.net/browse/AAI-420>`_ Can not get the MSB address in esr-server
-- `AAI-422 <https://jira.onap.org/browse/AAI-422>`_ The esr-server csit failed
+- `AAI-422 <https://lf-onap.atlassian.net/browse/AAI-422>`_ The esr-server csit failed
-- `AAI-424 <https://jira.onap.org/browse/AAI-424>`_ The integration catalog is not in use, should be removed
+- `AAI-424 <https://lf-onap.atlassian.net/browse/AAI-424>`_ The integration catalog is not in use, should be removed
-- `AAI-425 <https://jira.onap.org/browse/AAI-425>`_ Fix the artifact of esr-gui
+- `AAI-425 <https://lf-onap.atlassian.net/browse/AAI-425>`_ Fix the artifact of esr-gui
-- `AAI-426 <https://jira.onap.org/browse/AAI-426>`_ Fix the artifact of esr-server
+- `AAI-426 <https://lf-onap.atlassian.net/browse/AAI-426>`_ Fix the artifact of esr-server
-- `AAI-431 <https://jira.onap.org/browse/AAI-431>`_ esr-gui files did not contained in webapp of tomcat
+- `AAI-431 <https://lf-onap.atlassian.net/browse/AAI-431>`_ esr-gui files did not contained in webapp of tomcat
-- `AAI-433 <https://jira.onap.org/browse/AAI-433>`_ Failed to pre-load vCPE data to AAI. No response from AAI
+- `AAI-433 <https://lf-onap.atlassian.net/browse/AAI-433>`_ Failed to pre-load vCPE data to AAI. No response from AAI
-- `AAI-434 <https://jira.onap.org/browse/AAI-434>`_ Can not visit ESR portal with demo deployment
+- `AAI-434 <https://lf-onap.atlassian.net/browse/AAI-434>`_ Can not visit ESR portal with demo deployment
-- `AAI-435 <https://jira.onap.org/browse/AAI-435>`_ default tenant need be input to A&AI while register VIM
+- `AAI-435 <https://lf-onap.atlassian.net/browse/AAI-435>`_ default tenant need be input to A&AI while register VIM
-- `AAI-436 <https://jira.onap.org/browse/AAI-436>`_ Call the API from MultiCloud failed
+- `AAI-436 <https://lf-onap.atlassian.net/browse/AAI-436>`_ Call the API from MultiCloud failed
-- `AAI-440 <https://jira.onap.org/browse/AAI-440>`_ The version input box should be changed in a more easy to use when register a VIM
+- `AAI-440 <https://lf-onap.atlassian.net/browse/AAI-440>`_ The version input box should be changed in a more easy to use when register a VIM
-- `AAI-441 <https://jira.onap.org/browse/AAI-441>`_ Can not input the vendor and version information to EMS, but there is a default data for the two parameter
+- `AAI-441 <https://lf-onap.atlassian.net/browse/AAI-441>`_ Can not input the vendor and version information to EMS, but there is a default data for the two parameter
-- `AAI-442 <https://jira.onap.org/browse/AAI-442>`_ Can't instantiate a service
+- `AAI-442 <https://lf-onap.atlassian.net/browse/AAI-442>`_ Can't instantiate a service
-- `AAI-444 <https://jira.onap.org/browse/AAI-444>`_ Cannot associate multiple service-instances to PNFs
+- `AAI-444 <https://lf-onap.atlassian.net/browse/AAI-444>`_ Cannot associate multiple service-instances to PNFs
-- `AAI-446 <https://jira.onap.org/browse/AAI-446>`_ vnf to esr-system-info named-query is missing vnfc
+- `AAI-446 <https://lf-onap.atlassian.net/browse/AAI-446>`_ vnf to esr-system-info named-query is missing vnfc
-- `AAI-448 <https://jira.onap.org/browse/AAI-448>`_ Remove snapshot dependencies from aai-common, data-router, and rest-client
+- `AAI-448 <https://lf-onap.atlassian.net/browse/AAI-448>`_ Remove snapshot dependencies from aai-common, data-router, and rest-client
-- `AAI-450 <https://jira.onap.org/browse/AAI-450>`_ Named Query needs to be updated to return VNFC Info
+- `AAI-450 <https://lf-onap.atlassian.net/browse/AAI-450>`_ Named Query needs to be updated to return VNFC Info
-- `AAI-453 <https://jira.onap.org/browse/AAI-453>`_ Fix stage-site jenkins job for aai-common
+- `AAI-453 <https://lf-onap.atlassian.net/browse/AAI-453>`_ Fix stage-site jenkins job for aai-common
-- `AAI-454 <https://jira.onap.org/browse/AAI-454>`_ LoggingContext.requestId required NULL handling in aai/aai-common (20170607) - during demo.sh init_customer
+- `AAI-454 <https://lf-onap.atlassian.net/browse/AAI-454>`_ LoggingContext.requestId required NULL handling in aai/aai-common (20170607) - during demo.sh init_customer
**Known Issues**
-- `AAI-61 <https://jira.onap.org/browse/AAI-61>`_ AAI cleaned up references to OpenECOMP but in order to keep the release stable for R1, the XML namespace still contains openecomp.
+- `AAI-61 <https://lf-onap.atlassian.net/browse/AAI-61>`_ AAI cleaned up references to OpenECOMP but in order to keep the release stable for R1, the XML namespace still contains openecomp.
**Security Issues**
<profiles version="12">
<profile kind="CodeFormatterProfile" name="onap-java-formatter" version="12">
<setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/>
-<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.8"/>
-<setting id="org.eclipse.jdt.core.compiler.compliance" value="1.8"/>
+<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="11"/>
+<setting id="org.eclipse.jdt.core.compiler.compliance" value="11"/>
<setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/>
<setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/>
-<setting id="org.eclipse.jdt.core.compiler.source" value="1.8"/>
+<setting id="org.eclipse.jdt.core.compiler.source" value="11"/>
<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="48"/>
<parent>
<groupId>org.onap.oparent</groupId>
<artifactId>oparent</artifactId>
- <version>2.1.0</version>
+ <version>3.0.2</version>
</parent>
<groupId>org.onap.aai.aai-common</groupId>
<artifactId>aai-common</artifactId>
- <version>1.13.6-SNAPSHOT</version>
+ <version>1.16.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>aai-aai-common</name>
<description>Contains all of the common code for resources and traversal repos</description>
<module>aai-rest</module>
<module>aai-schema-ingest</module>
<module>aai-annotations</module>
- <module>aai-aaf-auth</module>
<module>aai-core</module>
<module>aai-auth</module>
<module>aai-els-onap-logging</module>
<properties>
<aai.common.version>${project.version}</aai.common.version>
<aai.generate.schema>true</aai.generate.schema>
+ <maven.compiler.release>17</maven.compiler.release>
<sitePath>/content/sites/site/org/onap/aai/aai-common/${project.artifactId}/${project.version}</sitePath>
<onap.nexus.url>https://nexus.onap.org</onap.nexus.url>
<onap.nexus.snapshot.path>/content/repositories/snapshots/</onap.nexus.snapshot.path>
<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
- <version>1.18.0</version>
+ <version>1.20.0</version>
<configuration>
<java>
<importOrder>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
- <source>1.8</source>
- <target>1.8</target>
+ <release>17</release>
</configuration>
</plugin>
<plugin>
<!-- Start of ONAP Specific Repositories -->
<repositories>
- <repository>
- <id>Log4j</id>
- <name>Log4J repository</name>
- <url>https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j</url>
- </repository>
<repository>
<id>AJSC</id>
<name>AJSC repository</name>
<url>https://mvnrepository.com/artifact/com.att.ajsc</url>
</repository>
- <repository>
- <id>restlet</id>
- <name>maven reslet</name>
- <url>https://maven.restlet.com/</url>
- </repository>
<repository>
<id>ecomp-releases</id>
<name>ECOMP Release Repository</name>
--- /dev/null
+distribution_type: container
+container_release_tag: 1.13.6
+project: aai-common
+ref: 286bfbfb686254577788c8b49417e3b50ee5c858
+containers:
+ - name: aai-common-alpine
+ version: latest
+ - name: aai-common-ubuntu
+ version: latest
+ - name: aai-haproxy
+ version: latest
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1450/
+project: aai-common
+version: 1.14.0
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1452/
+project: aai-common
+version: 1.14.1
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1453/
+project: aai-common
+version: 1.14.2
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1456/
+project: aai-common
+version: 1.14.3
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1458/
+project: aai-common
+version: 1.14.4
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1461/
+project: aai-common
+version: 1.14.5
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1462/
+project: aai-common
+version: 1.14.6
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1464/
+project: aai-common
+version: 1.14.7
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1465/
+project: aai-common
+version: 1.15.0
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1466/
+project: aai-common
+version: 1.15.1
--- /dev/null
+distribution_type: container
+container_release_tag: 1.15.2
+project: aai-common
+ref: 929e949696463324b21bf2f6c008755d12ec6530
+containers:
+ - name: aai-common-alpine
+ version: latest
+ - name: aai-common-ubuntu
+ version: latest
+ - name: aai-haproxy
+ version: latest
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1469/
+project: aai-common
+version: 1.15.2
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1471/
+project: aai-common
+version: 1.15.3
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1474/
+project: aai-common
+version: 1.15.4
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1475/
+project: aai-common
+version: 1.15.5
--- /dev/null
+distribution_type: maven
+log_dir: aai-aai-common-maven-stage-master/1477/
+project: aai-common
+version: 1.16.0
# because they are used in Jenkins, whose plug-in doesn't support
major_version=1
-minor_version=13
-patch_version=6
+minor_version=16
+patch_version=1
base_version=${major_version}.${minor_version}.${patch_version}