diff options
24 files changed, 2128 insertions, 677 deletions
diff --git a/BRMSGateway/pom.xml b/BRMSGateway/pom.xml index 82442e10d..29e9289bf 100644 --- a/BRMSGateway/pom.xml +++ b/BRMSGateway/pom.xml @@ -60,25 +60,6 @@ <artifactId>integrity-monitor</artifactId> <version>${project.version}</version> </dependency> - <!-- CLM security fix - force use of commons-collections 3.2.2. Remove - this if a new version of nexus-rest-client-java is upgraded to not use velocity - (and then subsequently commons-collections v3.1 --> - <dependency> - <groupId>commons-collections</groupId> - <artifactId>commons-collections</artifactId> - <version>3.2.2</version> - </dependency> - <dependency> - <groupId>org.sonatype.nexus</groupId> - <artifactId>nexus-rest-client-java</artifactId> - <version>2.3.1-01</version> - <exclusions> - <exclusion> - <groupId>commons-collections</groupId> - <artifactId>commons-collections</artifactId> - </exclusion> - </exclusions> - </dependency> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java index 5a7b25ec3..5e8046e22 100644 --- a/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java @@ -58,6 +58,7 @@ import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; +import javax.ws.rs.ProcessingException; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringEscapeUtils; @@ -76,6 +77,10 @@ import org.codehaus.plexus.util.WriterFactory; import org.eclipse.persistence.config.PersistenceUnitProperties; import org.onap.policy.api.PEDependency; import org.onap.policy.api.PolicyException; +import org.onap.policy.brms.api.nexus.NexusRestSearchParameters; +import org.onap.policy.brms.api.nexus.NexusRestWrapper; +import org.onap.policy.brms.api.nexus.NexusRestWrapperException; +import org.onap.policy.brms.api.nexus.pojo.NexusArtifact; import org.onap.policy.brms.entity.BrmsGroupInfo; import org.onap.policy.brms.entity.BrmsPolicyInfo; import org.onap.policy.brms.entity.DependencyInfo; @@ -89,11 +94,6 @@ import org.onap.policy.utils.BackUpMonitor; import org.onap.policy.utils.BusPublisher; import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; -import org.sonatype.nexus.client.NexusClient; -import org.sonatype.nexus.client.NexusClientException; -import org.sonatype.nexus.client.NexusConnectionException; -import org.sonatype.nexus.client.rest.NexusRestClient; -import org.sonatype.nexus.rest.model.NexusArtifact; /** * BRMSPush: Application responsible to push policies to the BRMS PDP Policy Repository (PR). @@ -102,7 +102,6 @@ import org.sonatype.nexus.rest.model.NexusArtifact; * @version 1.0 */ -@SuppressWarnings("deprecation") public class BrmsPush { private static final String GROUP_NAMES = "groupNames"; private static final String DROOLS_APPS_TEMPLATE_GROUP = @@ -587,7 +586,7 @@ public class BrmsPush { URL website; final String fileName = "rule.jar"; try { - website = new URL(artifact.getResourceURI()); + website = new URL(artifact.getUrlPath() + ".jar"); try (ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(fileName)) { fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); @@ -685,34 +684,30 @@ public class BrmsPush { } private List<NexusArtifact> getArtifactFromNexus(final String selectedName, final String version) { - final NexusClient client = new NexusRestClient(); + NexusRestWrapper restWrapper = null; int index = 0; boolean flag = false; while (index < repUrlList.size()) { try { final String repUrl = repUrlList.get(0); - client.connect(repUrl.substring(0, repUrl.indexOf(repUrl.split(":[0-9]+\\/nexus")[1])), repUserName, - repPassword); - final NexusArtifact template = new NexusArtifact(); - template.setGroupId(getGroupId(selectedName)); - template.setArtifactId(getArtifactId(selectedName)); - if (version != null) { - template.setVersion(version); - } - final List<NexusArtifact> resultList = client.searchByGAV(template); + restWrapper = + new NexusRestWrapper(repUrl.substring(0, repUrl.indexOf(repUrl.split(":[0-9]+\\/nexus")[1])), + repUserName, repPassword); + final NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + searchParameters.useFilterSearch( + getGroupId(selectedName), getArtifactId(selectedName), version, null, null); + + final List<NexusArtifact> resultList = restWrapper.findArtifact(searchParameters).getArtifactList(); if (resultList != null) { flag = true; return resultList; } - } catch (NexusClientException | NexusConnectionException | NullPointerException e) { + } catch (NexusRestWrapperException | ProcessingException e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. " + e.getMessage(), e); - } finally { - try { - client.disconnect(); - } catch (NexusClientException | NexusConnectionException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "failed to disconnect Connection from Nexus." - + e.getMessage(), e); + } finally { + if (null != restWrapper) { + restWrapper.close(); } if (!flag) { Collections.rotate(repUrlList, -1); @@ -937,7 +932,7 @@ public class BrmsPush { pomWriter.write(writer, model); } catch (final Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating POM for " + getArtifactId(name) - + e.getMessage(), e); + + e.getMessage(), e); } finally { IOUtil.close(writer); } diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/NexusRestSearchParameters.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/NexusRestSearchParameters.java new file mode 100644 index 000000000..1288b5982 --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/NexusRestSearchParameters.java @@ -0,0 +1,401 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Ericsson 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.policy.brms.api.nexus; + +import java.net.URI; + +import javax.ws.rs.core.UriBuilder; + +/** + * The Class NexusRestSearchParameters is used to specify the parameters of a search on Nexus. + * The parameters are used to return the search part of the URL for the Maven search. + */ +public class NexusRestSearchParameters { + // The REST end point for Nexus Lucene searches + private static final String NEXUS_LUCENE_SEARCH_PATH = "service/local/lucene/search"; + + // REST search query parameter names + private static final String KEYWORD_QUERY_PARAM = "q"; + private static final String GROUP_ID_QUERY_PARAM = "g"; + private static final String ARTIFACT_ID_QUERY_PARAM = "a"; + private static final String VERSION_QUERY_PARAM = "v"; + private static final String PACKAGING_TYPE_QUERY_PARAM = "p"; + private static final String CLASSIFIER_QUERY_PARAM = "c"; + private static final String CLASS_NAME_QUERY_PARAM = "cn"; + private static final String CHECKSUM_QUERY_PARAM = "sha1"; + private static final String FROM_QUERY_PARAM = "from"; + private static final String COUNT_QUERY_PARAM = "count"; + private static final String REPOSITORY_ID_QUERY_PARAM = "repositoryId"; + + /** The type of searches that can be performed. */ + public enum SearchType { + KEYWORD, /** Search using a keyword. */ + FILTER, /** Search using a group ID, artifact ID, version, packaging type, and/or classifier filter. */ + CLASS_NAME, /** Search for a class name. */ + CHECKSUM /** Search for artifacts matching a certain checksum. */ + } + + // The type of search to perform + private SearchType searchType = null; + + // Search filters + private String keyword; + private String groupId; + private String artifactId; + private String version; + private String packagingType; + private String classifier; + private String className; + private String checksum; + + // Repository filter + private String repositoryId; + + // Scope filters + private int from = -1; + private int count = -1; + + /** + * Specify searching using a keyword. + * + * @param keyword The keyword to search for + * @return this object to allow chaining of methods + * @throws NexusRestWrapperException on invalid keywords + */ + public NexusRestSearchParameters useKeywordSearch(final String keyword) throws NexusRestWrapperException { + clearSearchParameters(); + + if (isNullOrBlank(keyword)) { + throw new NexusRestWrapperException("keyword must be specified for Nexus keyword searches"); + } + + searchType = SearchType.KEYWORD; + this.keyword = keyword; + return this; + } + + /** + * Specify searching using a filter. + * + * @param groupId The group ID to filter on + * @param artifactId The artifact ID to filter on + * @param version The version to filter on + * @param packagingType The packaging type to filter on + * @param classifier The classifier to filter on + * @return this object to allow chaining of methods + * @throws NexusRestWrapperException on invalid filters + */ + public NexusRestSearchParameters useFilterSearch(final String groupId, final String artifactId, + final String version, final String packagingType, final String classifier) + throws NexusRestWrapperException { + clearSearchParameters(); + + if (isNullOrBlank(groupId) && isNullOrBlank(artifactId) && isNullOrBlank(version) + && isNullOrBlank(packagingType) && isNullOrBlank(classifier)) { + throw new NexusRestWrapperException( + "at least one filter parameter must be specified for Nexus filter searches"); + } + + searchType = SearchType.FILTER; + this.groupId = groupId; + this.artifactId = artifactId; + this.version = version; + this.packagingType = packagingType; + this.classifier = classifier; + return this; + } + + /** + * Specify searching using a class name. + * + * @param className The class name to search for + * @return this object to allow chaining of methods + * @throws NexusRestWrapperException on invalid className + */ + public NexusRestSearchParameters useClassNameSearch(final String className) throws NexusRestWrapperException { + clearSearchParameters(); + + if (isNullOrBlank(className)) { + throw new NexusRestWrapperException("className must be specified for Nexus class name searches"); + } + + searchType = SearchType.CLASS_NAME; + this.className = className; + return this; + } + + /** + * Specify searching using a checksum. + * + * @param checksum The checksum to search for + * @return this object to allow chaining of methods + * @throws NexusRestWrapperException on invalid checksum + */ + public NexusRestSearchParameters useChecksumSearch(final String checksum) throws NexusRestWrapperException { + clearSearchParameters(); + + if (isNullOrBlank(checksum)) { + throw new NexusRestWrapperException("checksum must be specified for Nexus checksum searches"); + } + + searchType = SearchType.CHECKSUM; + this.checksum = checksum; + return this; + } + + /** + * Search on a specific repository. + * + * @param repositoryId The repository to search + * @return this object to allow chaining of methods + * @throws NexusRestWrapperException on invalid repositoryId + */ + public NexusRestSearchParameters setRepositoryId(String repositoryId) throws NexusRestWrapperException { + if (isNullOrBlank(repositoryId)) { + throw new NexusRestWrapperException("a repositoryId must be specified"); + } + + this.repositoryId = repositoryId; + return this; + } + + /** + * Return the search results from this result number. + * + * @param from The number of the first result to return + * @return this object to allow chaining of methods + * @throws NexusRestWrapperException on invalid from value + */ + public NexusRestSearchParameters setFrom(int from) throws NexusRestWrapperException { + if (from < 0) { + throw new NexusRestWrapperException("from cannot be less than 0 when from is specified"); + } + + this.from = from; + return this; + } + + /** + * Return the specified number of search results. + * + * @param count The number of results to return + * @return this object to allow chaining of methods + * @throws NexusRestWrapperException on invalid count value + */ + public NexusRestSearchParameters setCount(int count) throws NexusRestWrapperException { + if (count < 1) { + throw new NexusRestWrapperException("count cannot be less than 1 when count is specified"); + } + + this.count = count; + return this; + } + + /** + * Compose the URI for the search to the Nexus server. + * + * @param nexusServerUrl the URL of the server on which to search + * @return the search URI + * @throws NexusRestWrapperException on search URL composition exceptions + */ + public URI getSearchUri(final String nexusServerUrl) throws NexusRestWrapperException { + if (isNullOrBlank(nexusServerUrl)) { + throw new NexusRestWrapperException("nexusServerUrl must be specified for the search URI"); + } + + if (searchType == null) { + throw new NexusRestWrapperException("search parameters have not been set"); + } + + // Use a URI builder to build up the search URI + UriBuilder uriBuilder = UriBuilder + .fromPath(nexusServerUrl) + .path(NEXUS_LUCENE_SEARCH_PATH); + + switch (searchType) { + case KEYWORD: + getKeywordSearchUri(uriBuilder); + break; + + case FILTER: + getFitlerSearchUri(uriBuilder); + break; + + case CLASS_NAME: + getClassNameSearchUri(uriBuilder); + break; + + case CHECKSUM: + getChecksumSearchUri(uriBuilder); + break; + + default: + throw new NexusRestWrapperException("search parameters have not been specified for the Nexus search"); + } + + // Add the repository ID query parameter is required + if (null != repositoryId) { + uriBuilder.queryParam(REPOSITORY_ID_QUERY_PARAM, repositoryId); + } + + // Add the from and count values if required + if (from >= 0) { + uriBuilder.queryParam(FROM_QUERY_PARAM, from); + } + if (count >= 0) { + uriBuilder.queryParam(COUNT_QUERY_PARAM, count); + } + + return uriBuilder.build(); + } + + /** + * Compose the query parameters for a keyword search. + * @param uriBuilder The builder to add query parameters to + */ + private void getKeywordSearchUri(UriBuilder uriBuilder) { + uriBuilder.queryParam(KEYWORD_QUERY_PARAM, keyword); + } + + /** + * Compose the query parameters for a filter search. + * @param uriBuilder The builder to add query parameters to + */ + private void getFitlerSearchUri(UriBuilder uriBuilder) { + if (!isNullOrBlank(groupId)) { + uriBuilder.queryParam(GROUP_ID_QUERY_PARAM, groupId); + } + if (!isNullOrBlank(artifactId)) { + uriBuilder.queryParam(ARTIFACT_ID_QUERY_PARAM, artifactId); + } + if (!isNullOrBlank(version)) { + uriBuilder.queryParam(VERSION_QUERY_PARAM, version); + } + if (!isNullOrBlank(packagingType)) { + uriBuilder.queryParam(PACKAGING_TYPE_QUERY_PARAM, packagingType); + } + if (!isNullOrBlank(classifier)) { + uriBuilder.queryParam(CLASSIFIER_QUERY_PARAM, classifier); + } + } + + /** + * Compose the query parameters for a class name search. + * @param uriBuilder The builder to add query parameters to + */ + private void getClassNameSearchUri(UriBuilder uriBuilder) { + uriBuilder.queryParam(CLASS_NAME_QUERY_PARAM, className); + } + + /** + * Compose the query parameters for a checksum search. + * @param uriBuilder The builder to add query parameters to + */ + private void getChecksumSearchUri(UriBuilder uriBuilder) { + uriBuilder.queryParam(CHECKSUM_QUERY_PARAM, checksum); + } + + public SearchType getSearchType() { + return searchType; + } + + public String getKeyword() { + return keyword; + } + + public String getGroupId() { + return groupId; + } + + public String getArtifactId() { + return artifactId; + } + + public String getVersion() { + return version; + } + + public String getPackagingType() { + return packagingType; + } + + public String getClassifier() { + return classifier; + } + + public String getClassName() { + return className; + } + + public String getChecksum() { + return checksum; + } + + public String getRepositoryId() { + return repositoryId; + } + + public int getFrom() { + return from; + } + + public int getCount() { + return count; + } + + /** + * Check if a string is null or all white space. + */ + private boolean isNullOrBlank(final String parameter) { + return null == parameter || parameter.trim().isEmpty(); + } + + /** + * Clear all search parameters. + * + */ + private void clearSearchParameters() { + searchType = null; + + keyword = null; + groupId = null; + artifactId = null; + version = null; + packagingType = null; + classifier = null; + className = null; + checksum = null; + + repositoryId = null; + + // Scope filters + from = -1; + count = -1; + } + + @Override + public String toString() { + return "NexusRestSearchParameters [searchType=" + searchType + ", keyword=" + keyword + ", groupId=" + groupId + + ", artifactId=" + artifactId + ", version=" + version + ", packagingType=" + packagingType + + ", classifier=" + classifier + ", className=" + className + ", checksum=" + checksum + + ", repositoryId=" + repositoryId + ", from=" + from + ", count=" + count + "]"; + } +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/NexusRestWrapper.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/NexusRestWrapper.java new file mode 100644 index 000000000..9ee7598fd --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/NexusRestWrapper.java @@ -0,0 +1,226 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Ericsson 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.policy.brms.api.nexus; + +import com.google.gson.Gson; + +import java.net.URI; +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Invocation.Builder; +import javax.ws.rs.core.Response; + +import org.onap.policy.brms.api.nexus.pojo.NexusArtifact; +import org.onap.policy.brms.api.nexus.pojo.NexusRepository; +import org.onap.policy.brms.api.nexus.pojo.NexusSearchResult; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +/** + * The Class NexusRestWrapper provides a Java API to a Nexus repository, wrapping the Nexus REST interface. + */ +public class NexusRestWrapper { + private static final Logger LOGGER = FlexLogger.getLogger(NexusRestWrapper.class.getName()); + + // A web client for issuing REST requests to the Nexus server + private final Client client; + + // The URL of the Nexus server + private final String nexusServerUrl; + + // Credentials for Nexus server logins + private String nexusUser; + private String nexusPassword; + + /** + * Instantiates a new Nexus REST agent with credentials. + * + * @param nexusServerUrl the URL of the Nexus server as a string + * @param nexusUser the Nexus userid + * @param nexusPassword the Nexus password + * @throws NexusRestWrapperException on parameter exceptions + */ + public NexusRestWrapper(final String nexusServerUrl, final String nexusUser, final String nexusPassword) + throws NexusRestWrapperException { + LOGGER.trace("new NexusRestWrapper: nexusServerUrl=" + nexusServerUrl); + + if (isNullOrBlank(nexusServerUrl)) { + throw new NexusRestWrapperException("nexusServerUrl must be specified for the Nexus server"); + } + + if ((isNullOrBlank(nexusUser) && !isNullOrBlank(nexusPassword)) + || (!isNullOrBlank(nexusUser) && isNullOrBlank(nexusPassword))) { + throw new NexusRestWrapperException( + "if either nexusUser or nexusPassword are specified, both must be specified"); + } + + this.nexusServerUrl = nexusServerUrl; + this.nexusUser = nexusUser; + this.nexusPassword = nexusPassword; + + // Create a client for RST calls towards the Nexus server + client = ClientBuilder.newClient(); + + LOGGER.trace("NexusRestWrapper created: nexusServerUrl=" + nexusServerUrl); + } + + /** + * Close the REST client. + */ + public void close() { + LOGGER.trace("NexusRestWrapper closing: url=" + nexusServerUrl); + + // Close the web client + client.close(); + + LOGGER.trace("NexusRestWrapper closed: url=" + nexusServerUrl); + } + + /** + * Find an artifact in the Nexus server. + * + * @param searchParameters + * the search parameters to use for the search + * @return the list of artifacts found that match the requested artifact + * @throws NexusRestWrapperException + * Exceptions accessing the Nexus server + */ + public NexusSearchResult findArtifact(final NexusRestSearchParameters searchParameters) + throws NexusRestWrapperException { + LOGGER.trace("new search with search parameters: " + searchParameters); + + if (null == searchParameters) { + throw new NexusRestWrapperException("searchParameters may not be null"); + } + + // Issue the REST request to perform the search + URI searchUri = searchParameters.getSearchUri(nexusServerUrl); + + LOGGER.debug("search URI is: " + searchUri.toString()); + + // Compose the REST request + Builder requestBuilder = client.target(searchUri).request("application/json"); + getAuthorizationHeader(requestBuilder); + + // Issue the REST request + Response response = null; + try { + response = requestBuilder.get(); + } catch (Exception e) { + String message = "search to URI " + searchUri.toString() + " failed with message: " + e.getMessage(); + LOGGER.warn(message, e); + throw new NexusRestWrapperException(message, e); + } + + LOGGER.debug("search response is: " + response.toString()); + + // Check the HTTP response code for the search + if (Response.Status.OK.getStatusCode() != response.getStatus()) { + String message = "search to URI " + searchUri.toString() + " failed, response was: " + response.toString(); + LOGGER.warn(message); + throw new NexusRestWrapperException(message); + } + + try { + // Get the JSON string with the the search result + String responseString = response.readEntity(String.class); + + // Parse the returned JSON into result POJOs + NexusSearchResult searchResult = new Gson().fromJson(responseString, NexusSearchResult.class); + + // We now need to expand the release and snapshot URL paths for each artifact + expandArtifactUrlPaths(searchResult); + + return searchResult; + } catch (Exception e) { + String message = "processing of result from query to Nexus failed with message: " + e.getMessage(); + LOGGER.warn(message, e); + throw new NexusRestWrapperException(message, e); + } + } + + /** + * Get the authorisation header for the user name and password. + * @param requestBuilder the request builder to add authorisation to + * @return the authorisation header + */ + private Builder getAuthorizationHeader(Builder requestBuilder) { + if (null != nexusUser && null != nexusPassword) { + String userPassString = nexusUser + ":" + nexusPassword; + requestBuilder.header("Authorization", "Basic " + + java.util.Base64.getEncoder().encodeToString(userPassString.getBytes())); + } + + return requestBuilder; + } + + /** + * Use the Repository URLs in the search result to create a release and snapshot URL path for each artifact. + * @param searchResult the results of a Nexus server search + */ + private void expandArtifactUrlPaths(NexusSearchResult searchResult) { + // Create a map of repositories for doing lookups + Map<String, NexusRepository> repositoryMap = new HashMap<>(); + + for (NexusRepository repository : searchResult.getRepoDetailsList()) { + repositoryMap.put(repository.getRepositoryId(), repository); + } + + for (NexusArtifact artifact : searchResult.getArtifactList()) { + artifact.setUrlPath(composeArtifactUrlPath(repositoryMap, artifact)); + } + } + + /** + * Compose an artifact URL path using the repository and artifact details for the artifact. + * @param repositoryMap the available repositories + * @param artifact the artifact + * @return the URL path + */ + private String composeArtifactUrlPath(Map<String, NexusRepository> repositoryMap, NexusArtifact artifact) { + // We always have one hit + NexusRepository repository = repositoryMap.get(artifact.getArtifactHits().get(0).getRepositoryId()); + + return new StringBuilder() + .append(repository.getRepositoryUrl()) + .append("/content/") + .append(artifact.getGroupId().replace('.', '/')) + .append('/') + .append(artifact.getArtifactId()) + .append('/') + .append(artifact.getVersion()) + .append('/') + .append(artifact.getArtifactId()) + .append('-') + .append(artifact.getVersion()) + .toString(); + } + + /** + * Check if a string is null or all white space. + */ + private boolean isNullOrBlank(final String parameter) { + return null == parameter || parameter.trim().isEmpty(); + } +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/NexusRestWrapperException.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/NexusRestWrapperException.java new file mode 100644 index 000000000..40f02aef2 --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/NexusRestWrapperException.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Ericsson 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.policy.brms.api.nexus; + +public class NexusRestWrapperException extends Exception { + private static final long serialVersionUID = -3321271612434193960L; + + /** + * Constructor, message only. + * @param message the exception message + */ + public NexusRestWrapperException(String message) { + super(message); + } + + /** + * Constructor, message and nested exception. + * @param message the exception message + * @param throwable the nested exception + */ + public NexusRestWrapperException(final String message, final Throwable throwable) { + super(message, throwable); + } +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifact.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifact.java new file mode 100644 index 000000000..5c770b9ef --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifact.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Ericsson 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.policy.brms.api.nexus.pojo; + +import java.util.List; + +/** + * The Class NexusArtifact is a POJO that holds information on an Artifact in a Maven repository. It is populated from + * the JSON response to a query on the repository. See: + * {@linktourl https://repository.sonatype.org/nexus-indexer-lucene-plugin/default/docs/path__lucene_search.html} + */ +public class NexusArtifact { + private String groupId; + private String artifactId; + private String version; + private String highlightedFragment; + private String latestRelease; + private String latestReleaseRepositoryId; + private String latestSnapshot; + private String latestSnapshotRepositoryId; + private List<NexusArtifactHit> artifactHits; + + // Path to the repository, added by wrapper after search is completed + private String urlPath; + + public String getGroupId() { + return groupId; + } + + public String getArtifactId() { + return artifactId; + } + + public String getVersion() { + return version; + } + + public String getHighlightedFragment() { + return highlightedFragment; + } + + public String getLatestRelease() { + return latestRelease; + } + + public String getLatestReleaseRepositoryId() { + return latestReleaseRepositoryId; + } + + public String getLatestSnapshot() { + return latestSnapshot; + } + + public String getLatestSnapshotRepositoryId() { + return latestSnapshotRepositoryId; + } + + public List<NexusArtifactHit> getArtifactHits() { + return artifactHits; + } + + public String getUrlPath() { + return urlPath; + } + + public void setUrlPath(final String urlPath) { + this.urlPath = urlPath; + } + + @Override + public String toString() { + return "NexusArtifact [groupId=" + groupId + ", artifactId=" + artifactId + ", version=" + version + + ", highlightedFragment=" + highlightedFragment + ", latestRelease=" + latestRelease + + ", latestReleaseRepositoryId=" + latestReleaseRepositoryId + ", latestSnapshot=" + latestSnapshot + + ", latestSnapshotRepositoryId=" + latestSnapshotRepositoryId + ", artifactHits=" + artifactHits + + ", urlPath=" + urlPath + "]"; + } +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactHit.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactHit.java new file mode 100644 index 000000000..0d173e036 --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactHit.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Ericsson 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.policy.brms.api.nexus.pojo; + +import java.util.List; + +/** + * The Class NexusArtifactHit is a POJO that holds information on the occurrences of an Artifact in a Maven repository. + * It is populated from the JSON response to a query on the repository. See: + * {@linktourl https://repository.sonatype.org/nexus-indexer-lucene-plugin/default/docs/path__lucene_search.html} + */ +public class NexusArtifactHit { + private List<NexusArtifactLink> artifactLinks; + private String repositoryId; + + public List<NexusArtifactLink> getArtifactLinks() { + return artifactLinks; + } + + public String getRepositoryId() { + return repositoryId; + } + + @Override + public String toString() { + return "NexusArtifactHit [artifactLinks=" + artifactLinks + ", repositoryId=" + repositoryId + "]"; + } +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactLink.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactLink.java new file mode 100644 index 000000000..ac6da6a72 --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactLink.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Ericsson 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.policy.brms.api.nexus.pojo; + +/** + * The Class NexusArtifactHit is a POJO that holds a link to an occurrence of an Artifact in a Maven repository. + * It is populated from the JSON response to a query on the repository. See: + * {@linktourl https://repository.sonatype.org/nexus-indexer-lucene-plugin/default/docs/path__lucene_search.html} + */ +public class NexusArtifactLink { + private String classifier; + private String extension; + + public String getClassifier() { + return classifier; + } + + public String getExtension() { + return extension; + } + + @Override + public String toString() { + return "NexusArtifactLink [classifier=" + classifier + ", extension=" + extension + "]"; + } +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusRepository.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusRepository.java new file mode 100644 index 000000000..e2bc48e15 --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusRepository.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Ericsson 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.policy.brms.api.nexus.pojo; + +import com.google.gson.annotations.SerializedName; + +/** + * The Class NexusRepository is a POJO that holds information on a repository in Maven. + * It is populated directly from the JSON returned from a search in Maven. + */ +public class NexusRepository { + private String repositoryContentClass; + private String repositoryId; + private String repositoryKind; + private String repositoryName; + private String repositoryPolicy; + @SerializedName("repositoryURL") + private String repositoryUrl; + + public String getRepositoryContentClass() { + return repositoryContentClass; + } + + public String getRepositoryId() { + return repositoryId; + } + + public String getRepositoryKind() { + return repositoryKind; + } + + public String getRepositoryName() { + return repositoryName; + } + + public String getRepositoryPolicy() { + return repositoryPolicy; + } + + public String getRepositoryUrl() { + return repositoryUrl; + } + + @Override + public String toString() { + return "NexusRepository [repositoryContentClass=" + repositoryContentClass + ", repositoryId=" + repositoryId + + ", repositoryKind=" + repositoryKind + ", repositoryName=" + repositoryName + ", repositoryPolicy=" + + repositoryPolicy + ", repositoryUrl=" + repositoryUrl + "]"; + } +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusSearchResult.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusSearchResult.java new file mode 100644 index 000000000..d71d2c7d8 --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/pojo/NexusSearchResult.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Ericsson 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.policy.brms.api.nexus.pojo; + +import java.util.List; + +/** + * The Class NexusSearchResult holds the result of a search in Nexus. It is populated directly from the JSON returned by + * the Nexus search. + */ +public class NexusSearchResult { + private int totalCount; + private int from; + private int count; + private boolean tooManyResults; + private boolean collapsed; + private List<NexusRepository> repoDetails; + private List<NexusArtifact> data; + + public int getTotalCount() { + return totalCount; + } + + public int getFrom() { + return from; + } + + public int getCount() { + return count; + } + + public boolean isTooManyResults() { + return tooManyResults; + } + + public boolean isCollapsed() { + return collapsed; + } + + public List<NexusRepository> getRepoDetailsList() { + return repoDetails; + } + + public List<NexusArtifact> getArtifactList() { + return data; + } + + @Override + public String toString() { + return "NexusSearchResult [totalCount=" + totalCount + ", from=" + from + ", count=" + count + + ", tooManyResults=" + tooManyResults + ", collapsed=" + collapsed + ", repoDetailsList=" + + repoDetails + ", artifactList=" + data + "]"; + } +} diff --git a/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/NexusRestWrapperTest.java b/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/NexusRestWrapperTest.java new file mode 100644 index 000000000..60adecd41 --- /dev/null +++ b/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/NexusRestWrapperTest.java @@ -0,0 +1,402 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Ericsson 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.policy.brms.api.nexus; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.List; + +import org.junit.Test; +import org.onap.policy.brms.api.nexus.NexusRestSearchParameters; +import org.onap.policy.brms.api.nexus.NexusRestWrapper; +import org.onap.policy.brms.api.nexus.NexusRestWrapperException; +import org.onap.policy.brms.api.nexus.pojo.NexusArtifact; + +public class NexusRestWrapperTest { + @Test + public void testRestWrapperConstructionErrors() throws NexusRestWrapperException { + try { + new NexusRestWrapper(null, null, null); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("nexusServerUrl must be specified for the Nexus server", e.getMessage()); + } + + try { + new NexusRestWrapper("", null, null); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("nexusServerUrl must be specified for the Nexus server", e.getMessage()); + } + + try { + new NexusRestWrapper(" ", null, null); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("nexusServerUrl must be specified for the Nexus server", e.getMessage()); + } + + try { + new NexusRestWrapper("\n\t", null, null); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("nexusServerUrl must be specified for the Nexus server", e.getMessage()); + } + + try { + new NexusRestWrapper("server", "user", null); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("if either nexusUser or nexusPassword are specified, both must be specified", e.getMessage()); + } + + try { + new NexusRestWrapper("server", null, "pass"); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("if either nexusUser or nexusPassword are specified, both must be specified", e.getMessage()); + } + + NexusRestWrapper wrapper = new NexusRestWrapper("http://localhost:99999", "user", "pass"); + assertNotNull(wrapper); + + try { + wrapper.findArtifact(null); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("searchParameters may not be null", e.getMessage()); + } + + try { + wrapper.findArtifact(new NexusRestSearchParameters()); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("search parameters have not been set", e.getMessage()); + } + + try { + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + + searchParameters.useFilterSearch("org.onap.policy.engine", null, null, null, null); + wrapper.findArtifact(searchParameters); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("search to URI http://localhost:99999/service/local/lucene/search?g=org.onap.policy.engine " + + "failed with message: ", e.getMessage().substring(0, 111)); + } + + wrapper.close(); + wrapper = new NexusRestWrapper("http://localhost:57344", "user", "pass"); + + try { + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + + searchParameters.useFilterSearch("org.onap.policy.engine", null, null, null, null); + wrapper.findArtifact(searchParameters); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("search to URI http://localhost:57344/service/local/lucene/search?g=org.onap.policy.engine " + + "failed with message: ", e.getMessage().substring(0, 111)); + } + + wrapper.close(); + wrapper = new NexusRestWrapper("https://nexus.onap.org", "user", "pass"); + + try { + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + searchParameters.useFilterSearch("org.onap.policy.engine", null, "", null, null); + wrapper.findArtifact(searchParameters); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("search to URI https://nexus.onap.org/service/local/lucene/search?g=org.onap.policy.engine " + + "failed, response was: InboundJaxrsResponse{context=ClientResponse{method=GET, " + + "uri=https://nexus.onap.org/service/local/lucene/search?g=org.onap.policy.engine, status=401, reason=Unauthorized}}", + e.getMessage()); + } + + try { + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + searchParameters.useFilterSearch(null, null, null, null, null); + wrapper.findArtifact(searchParameters); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("at least one filter parameter must be specified for Nexus filter searches", e.getMessage()); + } + + try { + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + searchParameters.useKeywordSearch(null); + wrapper.findArtifact(searchParameters); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("keyword must be specified for Nexus keyword searches", e.getMessage()); + } + + try { + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + searchParameters.useClassNameSearch(null); + wrapper.findArtifact(searchParameters); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("className must be specified for Nexus class name searches", e.getMessage()); + } + + try { + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + searchParameters.useChecksumSearch(null); + wrapper.findArtifact(searchParameters); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("checksum must be specified for Nexus checksum searches", e.getMessage()); + } + + try { + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + searchParameters.useKeywordSearch("BRMSGateway").setRepositoryId(null); + wrapper.findArtifact(searchParameters); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("a repositoryId must be specified", e.getMessage()); + } + + try { + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + searchParameters.useKeywordSearch("BRMSGateway").setFrom(-1); + wrapper.findArtifact(searchParameters); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("from cannot be less than 0 when from is specified", e.getMessage()); + } + + try { + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + searchParameters.useKeywordSearch("BRMSGateway").setCount(0); + wrapper.findArtifact(searchParameters); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("count cannot be less than 1 when count is specified", e.getMessage()); + } + + try { + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + searchParameters.useKeywordSearch("BRMSGateway"); + searchParameters.getSearchUri(null); + fail("test shold throw an exception here"); + } catch (NexusRestWrapperException e) { + assertEquals("nexusServerUrl must be specified for the search URI", e.getMessage()); + } + + wrapper.close(); + } + + @Test + public void testGetters() throws NexusRestWrapperException { + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + + searchParameters.useKeywordSearch("BRMSGateway"); + assertEquals(NexusRestSearchParameters.SearchType.KEYWORD, searchParameters.getSearchType()); + assertEquals(null, searchParameters.getArtifactId()); + assertEquals(null, searchParameters.getChecksum()); + assertEquals(null, searchParameters.getClassName()); + assertEquals(null, searchParameters.getClassifier()); + assertEquals(-1, searchParameters.getCount()); + assertEquals(-1, searchParameters.getFrom()); + assertEquals(null, searchParameters.getGroupId()); + assertEquals("BRMSGateway", searchParameters.getKeyword()); + assertEquals(null, searchParameters.getPackagingType()); + assertEquals(null, searchParameters.getRepositoryId()); + assertEquals(null, searchParameters.getVersion()); + + searchParameters.useFilterSearch("org.onap.policy.engine", "BRMSGateway", + "1.2.3", "jar", "jar-with-dependencies") + .setFrom(100).setCount(10).setRepositoryId("repository"); + assertEquals(NexusRestSearchParameters.SearchType.FILTER, searchParameters.getSearchType()); + assertEquals("BRMSGateway", searchParameters.getArtifactId()); + assertEquals(null, searchParameters.getChecksum()); + assertEquals(null, searchParameters.getClassName()); + assertEquals("jar-with-dependencies", searchParameters.getClassifier()); + assertEquals(10, searchParameters.getCount()); + assertEquals(100, searchParameters.getFrom()); + assertEquals("org.onap.policy.engine", searchParameters.getGroupId()); + assertEquals(null, searchParameters.getKeyword()); + assertEquals("jar", searchParameters.getPackagingType()); + assertEquals("repository", searchParameters.getRepositoryId()); + assertEquals("1.2.3", searchParameters.getVersion()); + + searchParameters.useClassNameSearch("BRMSGateway"); + assertEquals(NexusRestSearchParameters.SearchType.CLASS_NAME, searchParameters.getSearchType()); + assertEquals(null, searchParameters.getArtifactId()); + assertEquals(null, searchParameters.getChecksum()); + assertEquals("BRMSGateway", searchParameters.getClassName()); + assertEquals(null, searchParameters.getClassifier()); + assertEquals(-1, searchParameters.getCount()); + assertEquals(-1, searchParameters.getFrom()); + assertEquals(null, searchParameters.getGroupId()); + assertEquals(null, searchParameters.getKeyword()); + assertEquals(null, searchParameters.getPackagingType()); + assertEquals(null, searchParameters.getRepositoryId()); + assertEquals(null, searchParameters.getVersion()); + + searchParameters.useChecksumSearch("987654321"); + assertEquals(NexusRestSearchParameters.SearchType.CHECKSUM, searchParameters.getSearchType()); + assertEquals(null, searchParameters.getArtifactId()); + assertEquals("987654321", searchParameters.getChecksum()); + assertEquals(null, searchParameters.getClassName()); + assertEquals(null, searchParameters.getClassifier()); + assertEquals(-1, searchParameters.getCount()); + assertEquals(-1, searchParameters.getFrom()); + assertEquals(null, searchParameters.getGroupId()); + assertEquals(null, searchParameters.getKeyword()); + assertEquals(null, searchParameters.getPackagingType()); + assertEquals(null, searchParameters.getRepositoryId()); + assertEquals(null, searchParameters.getVersion()); + } + + @Test + public void testFilterSearch() throws NexusRestWrapperException { + NexusRestWrapper wrapper = new NexusRestWrapper("https://nexus.onap.org", null, null); + + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + + searchParameters.useFilterSearch("org.onap.policy.dorothy", null, null, null, null).setCount(1); + List<NexusArtifact> foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(0, foundArtifactList.size()); + + searchParameters.useFilterSearch("org.onap.policy.engine", null, null, null, null).setCount(1); + foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(1, foundArtifactList.size()); + + searchParameters.useFilterSearch("org.onap.policy.engine", null, null, null, null).setFrom(2).setCount(2); + foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(2, foundArtifactList.size()); + + searchParameters.useFilterSearch("org.onap.policy.engine", null, null, null, null).setFrom(2).setCount(2); + foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(2, foundArtifactList.size()); + + searchParameters.useFilterSearch(null, "BRMSGateway", null, null, null); + foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertTrue(foundArtifactList.size() > 2); + + searchParameters.useFilterSearch(null, null, "1.2.3", null, null).setCount(1); + foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(1, foundArtifactList.size()); + + searchParameters.useFilterSearch("org.onap.policy.engine", null, "1.1.2", null, null).setCount(1); + foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(1, foundArtifactList.size()); + + searchParameters.useFilterSearch("org.onap.policy.engine", "BRMSGateway", "1.1.2", null, null).setCount(1); + foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(1, foundArtifactList.size()); + + searchParameters.useFilterSearch(null, "BRMSGateway", "1.1.2", null, null).setCount(1); + foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(1, foundArtifactList.size()); + + searchParameters.useFilterSearch(null, "BRMSGateway", "1.1.2", "jar", null).setCount(1); + foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(1, foundArtifactList.size()); + + searchParameters.useFilterSearch(null, "BRMSGateway", "1.1.2", "jar", "jar-with-dependencies").setCount(1); + foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(1, foundArtifactList.size()); + + searchParameters.useFilterSearch(null, "BRMSGateway", "1.1.2", "jar", "jar-with-dependencies") + .setCount(1).setRepositoryId("releases"); + foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(1, foundArtifactList.size()); + + wrapper.close(); + } + + @Test + public void testKeywordSearch() throws NexusRestWrapperException { + NexusRestWrapper wrapper = new NexusRestWrapper("https://nexus.onap.org", null, null); + + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + + searchParameters.useKeywordSearch("TheWizardOfOz").setCount(1); + List<NexusArtifact> foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(0, foundArtifactList.size()); + + searchParameters.useKeywordSearch("BRMSGateway").setCount(1); + foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(1, foundArtifactList.size()); + + wrapper.close(); + } + + @Test + public void testClassNameSearch() throws NexusRestWrapperException { + NexusRestWrapper wrapper = new NexusRestWrapper("https://nexus.onap.org", null, null); + + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + + searchParameters.useClassNameSearch("TheWizardOfOz").setCount(1); + List<NexusArtifact> foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(0, foundArtifactList.size()); + + searchParameters.useClassNameSearch("BRMSGateway").setCount(1); + foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(1, foundArtifactList.size()); + + wrapper.close(); + } + + @Test + public void testChecksumSearch() throws NexusRestWrapperException { + NexusRestWrapper wrapper = new NexusRestWrapper("https://nexus.onap.org", null, null); + + NexusRestSearchParameters searchParameters = new NexusRestSearchParameters(); + + searchParameters.useChecksumSearch("99999999999999").setCount(1); + List<NexusArtifact> foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(0, foundArtifactList.size()); + + searchParameters.useChecksumSearch("914acda2ce67de9b45d599109d6ad8357d01b217").setCount(1); + foundArtifactList = wrapper.findArtifact(searchParameters).getArtifactList(); + assertNotNull(foundArtifactList); + assertEquals(1, foundArtifactList.size()); + + wrapper.close(); + } +} diff --git a/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactHitTest.java b/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactHitTest.java new file mode 100644 index 000000000..f04884660 --- /dev/null +++ b/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactHitTest.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Ericsson 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.policy.brms.api.nexus.pojo; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +public class NexusArtifactHitTest { + + @Test + public void testNexusArtifactHit() { + NexusArtifactHit artifactHit = new NexusArtifactHit(); + + assertNull(artifactHit.getArtifactLinks()); + assertNull(artifactHit.getRepositoryId()); + + assertNotNull(artifactHit.toString()); + } +} diff --git a/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactLinkTest.java b/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactLinkTest.java new file mode 100644 index 000000000..b0ae02e9c --- /dev/null +++ b/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactLinkTest.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Ericsson 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.policy.brms.api.nexus.pojo; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +public class NexusArtifactLinkTest { + + @Test + public void testNexusArtifactLink() { + NexusArtifactLink artifactLink = new NexusArtifactLink(); + + assertNull(artifactLink.getClassifier()); + assertNull(artifactLink.getExtension()); + + assertNotNull(artifactLink.toString()); + } +} diff --git a/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactTest.java b/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactTest.java new file mode 100644 index 000000000..e8ddaabe9 --- /dev/null +++ b/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusArtifactTest.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Ericsson 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.policy.brms.api.nexus.pojo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +public class NexusArtifactTest { + + @Test + public void testNexusArtifact() { + NexusArtifact artifact = new NexusArtifact(); + + assertNull(artifact.getGroupId()); + assertNull(artifact.getArtifactId()); + assertNull(artifact.getVersion()); + assertNull(artifact.getHighlightedFragment()); + assertNull(artifact.getLatestRelease()); + assertNull(artifact.getLatestReleaseRepositoryId()); + assertNull(artifact.getLatestSnapshot()); + assertNull(artifact.getLatestSnapshotRepositoryId()); + assertNull(artifact.getArtifactHits()); + + artifact.setUrlPath("urlPath"); + assertEquals("urlPath", artifact.getUrlPath()); + + assertNotNull(artifact.toString()); + } +} diff --git a/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusRepositoryTest.java b/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusRepositoryTest.java new file mode 100644 index 000000000..41f710386 --- /dev/null +++ b/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusRepositoryTest.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Ericsson 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.policy.brms.api.nexus.pojo; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +public class NexusRepositoryTest { + + @Test + public void testNexusRepository() { + NexusRepository repository = new NexusRepository(); + + assertNull(repository.getRepositoryId()); + assertNull(repository.getRepositoryKind()); + assertNull(repository.getRepositoryContentClass()); + assertNull(repository.getRepositoryName()); + assertNull(repository.getRepositoryPolicy()); + assertNull(repository.getRepositoryUrl()); + + assertNotNull(repository.toString()); + } +} diff --git a/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusSearchResultTest.java b/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusSearchResultTest.java new file mode 100644 index 000000000..ba83a3a27 --- /dev/null +++ b/BRMSGateway/src/test/java/org/onap/policy/brms/api/nexus/pojo/NexusSearchResultTest.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Ericsson 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.policy.brms.api.nexus.pojo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +public class NexusSearchResultTest { + + @Test + public void testNexusSearchResult() { + NexusSearchResult result = new NexusSearchResult(); + + assertNull(result.getArtifactList()); + assertEquals(0, result.getCount()); + assertEquals(0, result.getFrom()); + assertNull(result.getRepoDetailsList()); + assertEquals(0, result.getTotalCount()); + assertEquals(false, result.isCollapsed()); + assertEquals(false, result.isTooManyResults()); + + assertNotNull(result.toString()); + } +} diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientEnd.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientEnd.java index 3f97e19f7..9f9dc37e4 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientEnd.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientEnd.java @@ -20,16 +20,8 @@ package org.onap.policy.std; -import java.io.IOException; import java.net.URI; - import javax.websocket.ClientEndpoint; -import javax.websocket.OnClose; -import javax.websocket.OnError; -import javax.websocket.OnMessage; -import javax.websocket.OnOpen; -import javax.websocket.Session; - import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import org.onap.policy.api.NotificationHandler; @@ -38,231 +30,211 @@ import org.onap.policy.api.NotificationType; import org.onap.policy.api.PDPNotification; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.XACMLErrorConstants; @ClientEndpoint public class AutoClientEnd extends WebSocketClient { - private static StdPDPNotification notification = null; - private static StdPDPNotification oldNotification = null; - private static AutoClientEnd client = null; - private static NotificationScheme scheme = null; - private static NotificationHandler handler = null; - private static String url = null; - private static Session session = null; - private static boolean status = false; - private static boolean stop = false; - private static boolean message = false; - private static boolean error = false; - private static Logger logger = FlexLogger.getLogger(AutoClientEnd.class.getName()); - - private AutoClientEnd(URI serverUri) { - super(serverUri); - } - - @Override - public void onClose(int arg0, String arg1, boolean arg2) { - // Not implemented - } - - @Override - public void onError(Exception arg0) { - // Not implemented - } - - @Override - public void onMessage(String arg0) { - // Not implemented - } - - @Override - public void onOpen(ServerHandshake arg0) { - // Not implemented - } - - public static void setAuto(NotificationScheme scheme, - NotificationHandler handler) { - AutoClientEnd.scheme = scheme; - AutoClientEnd.handler = handler; - } - - public static void setScheme(NotificationScheme scheme) { - AutoClientEnd.scheme = scheme; - } - - public static boolean getStatus(){ - return AutoClientEnd.status; - } - - public static String getURL() { - return AutoClientEnd.url; - } - - public static void start(String url) { - AutoClientEnd.url = url; - - if (scheme == null || handler == null || - ! (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) || - scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS) ) || - AutoClientEnd.client != null) { - return; - } - - if (url.contains("https")) { - url = url.replaceAll("https", "wss"); - } - else { - url = url.replaceAll("http", "ws"); - } - - - // Stop and Start needs to be done. - try { - logger.info("Starting Auto Notification with the PDP server : " + url); - client = new AutoClientEnd(new URI(url + "notifications")); - status = true; - if(error){ - // The URL's will be in Sync according to design Spec. - ManualClientEnd.start(AutoClientEnd.url); - StdPDPNotification notification = NotificationStore.getDeltaNotification((StdPDPNotification)ManualClientEnd.result(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)); - if(notification.getNotificationType()!=null&&oldNotification!=notification){ - oldNotification= notification; - AutoClientEnd.notification = notification; - callHandler(); - } - error = false; - } - // - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - client = null; - status = false; - changeURL(); - } - } - - private static void changeURL(){ - // Change the PDP if it is not Up. - StdPolicyEngine.rotatePDPList(); - start(StdPolicyEngine.getPDPURL()); - } - - public static void stop() { - if (client == null) { - return; - } - client.close(); - if(session!=null){ - try { - stop = true; - logger.info("\n Closing Auto Notification WebSocket Connection.. "); - session.close(); - session = null; - } catch (IOException e) { - logger.error("Error closing websocket connection", e); - } - } - client = null; - status = false; - stop = false; - } - - private static void callHandler() { - if (handler == null || scheme == null) { - return; - } - if (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)) { - boolean removed = false; - boolean updated = false; - if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) { - removed = true; - } - if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) { - updated = true; - } - if (removed && updated) { - notification.setNotificationType(NotificationType.BOTH); - } else if (removed) { - notification.setNotificationType(NotificationType.REMOVE); - } else if (updated) { - notification.setNotificationType(NotificationType.UPDATE); - } - try{ - handler.notificationReceived(notification); - }catch (Exception e){ - logger.error("Error in Clients Handler Object : ", e); - } - } else if (scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS)) { - PDPNotification newNotification = MatchStore.checkMatch(notification); - if (newNotification.getNotificationType() != null) { - try{ - handler.notificationReceived(newNotification); - }catch (Exception e){ - logger.error("Error in Clients Handler Object : ", e); - } - } - } - } - - // WebSockets Code.. - @OnOpen - public static void onOpen(Session session){ - logger.debug("Auto Notification Session Started... " + session.getId()); - if(AutoClientEnd.session == null){ - AutoClientEnd.session = session; - } - } - - @OnError - public static void onError(Session session, Throwable e) { - // trying to Restart by self. - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Session Error.. "+ session.getId() + "\n Error is : " + e ); - stop(); - if (url != null) { - client = null; - status = false; - error= true; - start(url); - } - } - - @OnClose - public static void onClose(Session session) { - logger.info("Session ended with "+ session.getId()); - if(!stop && !message){ - // This Block of code is executed if there is any Network Failure or if the Notification is Down. - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Disconnected from Notification Server"); - client = null; - status = false; - AutoClientEnd.session=null; - // Try to connect Back to available PDP. - error = true; - start(url); - } - AutoClientEnd.message=false; - } - - @OnMessage - public static void onMessage(String message, Session session) throws IOException { - AutoClientEnd.message = true; - logger.debug("Auto Notification Recieved Message " + message + " Session info is : " + session.getId()); - try { - notification = NotificationUnMarshal.notificationJSON(message); - } catch (Exception e) { - logger.error("PE500 " + e); - } - if(AutoClientEnd.session == session){ - try{ - NotificationStore.recordNotification(notification); - }catch(Exception e){ - logger.error(e); - } - if(oldNotification!=notification){ - oldNotification= notification; - callHandler(); - } - }else{ - session.close(); - } - AutoClientEnd.message = false; - } + private static StdPDPNotification notification = null; + private static StdPDPNotification oldNotification = null; + private static AutoClientEnd client = null; + private static NotificationScheme scheme = null; + private static NotificationHandler handler = null; + private static String url = null; + private static boolean status = false; + private static boolean stop = false; + private static boolean message = false; + private static boolean error = false; + private static Logger logger = FlexLogger.getLogger(AutoClientEnd.class.getName()); + + private AutoClientEnd(URI serverUri) { + super(serverUri); + } + + @Override + public void onMessage(String msg) { + logger.info("Received Auto Notification from : " + getURI() + ", Notification: " + msg); + AutoClientEnd.message = true; + try { + AutoClientEnd.notification = NotificationUnMarshal.notificationJSON(msg); + } catch (Exception e) { + logger.error("PE500 " + e); + } + try { + NotificationStore.recordNotification(notification); + } catch (Exception e) { + logger.error(e); + } + if (AutoClientEnd.oldNotification != AutoClientEnd.notification) { + AutoClientEnd.oldNotification = AutoClientEnd.notification; + callHandler(); + } + + AutoClientEnd.message = false; + } + + @Override + public void onClose(int code, String reason, boolean remote) { + logger.info("AutoClientEnd disconnected from: " + getURI() + "; Code: " + code + ", reason : " + reason); + if (!AutoClientEnd.stop && !AutoClientEnd.message) { + // This Block of code is executed if there is any Network Failure or + // if the Notification is Down. + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Disconnected from Notification Server"); + AutoClientEnd.client = null; + AutoClientEnd.status = false; + // Try to connect Back to available PDP. + AutoClientEnd.error = true; + start(url); + } + AutoClientEnd.message = false; + } + + @Override + public void onError(Exception ex) { + logger.error("XACMLErrorConstants.ERROR_PROCESS_FLOW + Error connecting to: " + getURI() + + ", Exception occured ...\n" + ex); + // trying to Restart by self. + stop(); + if (AutoClientEnd.url != null) { + AutoClientEnd.client = null; + AutoClientEnd.status = false; + AutoClientEnd.error = true; + AutoClientEnd.start(AutoClientEnd.url); + } + } + + @Override + public void onOpen(ServerHandshake arg0) { + logger.info("Auto Notification Session Started... " + getURI()); + } + + /** + * Sets the auto. + * + * @param scheme the scheme + * @param handler the handler + */ + public static void setAuto(NotificationScheme scheme, NotificationHandler handler) { + logger.info("Auto Notification setAuto, scheme: " + scheme); + AutoClientEnd.scheme = scheme; + AutoClientEnd.handler = handler; + } + + public static void setScheme(NotificationScheme scheme) { + AutoClientEnd.scheme = scheme; + } + + public static boolean getStatus() { + return AutoClientEnd.status; + } + + public static String getUrl() { + return AutoClientEnd.url; + } + + /** + * Start. + * + * @param url the url + */ + public static void start(String url) { + AutoClientEnd.url = url; + + if (scheme == null || handler == null || !(scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) + || scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS)) || AutoClientEnd.client != null) { + return; + } + + if (url.contains("https")) { + url = url.replaceAll("https", "wss"); + } else { + url = url.replaceAll("http", "ws"); + } + + // Stop and Start needs to be done. + try { + logger.info("Starting Auto Notification with the PDP server : " + url); + client = new AutoClientEnd(new URI(url + "notifications")); + client.connect(); + status = true; + if (error) { + // will not trigger. leave it in to later add checks + // The URL's will be in Sync according to design Spec. + ManualClientEnd.start(AutoClientEnd.url); + StdPDPNotification notification = NotificationStore.getDeltaNotification( + (StdPDPNotification) ManualClientEnd.result(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)); + if (notification.getNotificationType() != null && oldNotification != notification) { + oldNotification = notification; + AutoClientEnd.notification = notification; + callHandler(); + } + error = false; + } + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + client = null; + status = false; + changeUrl(); + } + } + + private static void changeUrl() { + // Change the PDP if it is not Up. + StdPolicyEngine.rotatePDPList(); + start(StdPolicyEngine.getPDPURL()); + } + + /** + * Stop the websocket connection. + */ + public static void stop() { + if (client == null) { + return; + } + logger.info("\n Closing Auto Notification WebSocket Connection.. "); + stop = true; + try { + client.closeBlocking(); + } catch (InterruptedException e) { + logger.info("\n Error Closing Auto Notification WebSocket Connection.. InterruptedException"); + } + logger.info("\n Closed the Auto Notification WebSocket Connection.. "); + client = null; + status = false; + stop = false; + } + + private static void callHandler() { + if (handler == null || scheme == null) { + return; + } + if (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)) { + boolean removed = false; + boolean updated = false; + if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) { + removed = true; + notification.setNotificationType(NotificationType.REMOVE); + } + if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) { + updated = true; + notification.setNotificationType(NotificationType.UPDATE); + } + if (removed && updated) { + notification.setNotificationType(NotificationType.BOTH); + } + try { + handler.notificationReceived(notification); + } catch (Exception e) { + logger.error("Error in Clients Handler Object : ", e); + } + } else if (scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS)) { + PDPNotification newNotification = MatchStore.checkMatch(notification); + if (newNotification.getNotificationType() != null) { + try { + handler.notificationReceived(newNotification); + } catch (Exception e) { + logger.error("Error in Clients Handler Object : ", e); + } + } + } + } } diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEnd.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEnd.java index 991bdca9c..2fe6dc006 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEnd.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEnd.java @@ -20,144 +20,118 @@ package org.onap.policy.std; -import java.io.IOException; import java.net.URI; import java.util.concurrent.CountDownLatch; - import javax.websocket.ClientEndpoint; -import javax.websocket.OnClose; -import javax.websocket.OnError; -import javax.websocket.OnMessage; -import javax.websocket.OnOpen; -import javax.websocket.Session; - import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import org.onap.policy.api.NotificationScheme; import org.onap.policy.api.NotificationType; import org.onap.policy.api.PDPNotification; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.std.StdPDPNotification; - import org.onap.policy.xacml.api.XACMLErrorConstants; -import org.onap.policy.common.logging.flexlogger.*; - @ClientEndpoint public class ManualClientEnd extends WebSocketClient { - private static CountDownLatch latch; - private static StdPDPNotification notification = null; - private static String resultJson = null; - private static Logger logger = FlexLogger.getLogger(ManualClientEnd.class.getName()); - private static ManualClientEnd client; - - public ManualClientEnd(URI serverUri) { - super(serverUri); - } + private static CountDownLatch latch; + private static StdPDPNotification notification = null; + private static String resultJson = null; + private static Logger logger = FlexLogger.getLogger(ManualClientEnd.class.getName()); + private static ManualClientEnd client; + + public ManualClientEnd(URI serverUri) { + super(serverUri); + } + + @Override + public void onClose(int code, String reason, boolean remote) { + logger.info("ManualClientEnd disconnected from: " + getURI() + "; Code: " + code + ", reason : " + reason); + latch.countDown(); + } - @Override - public void onClose(int arg0, String arg1, boolean arg2) { - // Not implemented - } + @Override + public void onError(Exception ex) { + logger.error("XACMLErrorConstants.ERROR_PROCESS_FLOW + ManualClientEnd - Error connecting to: " + getURI() + + ", Exception occured ...\n" + ex); + latch.countDown(); + } - @Override - public void onError(Exception arg0) { - // Not implemented - } + @Override + public void onMessage(String message) { + logger.info("Manual Notification Recieved Message from : " + getURI() + ", Notification: " + message); + ManualClientEnd.resultJson = message; + try { + ManualClientEnd.notification = NotificationUnMarshal.notificationJSON(message); + latch.countDown(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + latch.countDown(); + } + } - @Override - public void onMessage(String arg0) { - // Not implemented - } + @Override + public void onOpen(ServerHandshake arg0) { + logger.info("Manual Notification Session Started... " + getURI()); + send("Manual"); + } - @Override - public void onOpen(ServerHandshake arg0) { - // Not implemented - } + /** + * Start. + * + * @param url the url + */ + public static void start(String url) { + latch = new CountDownLatch(1); - public static void start(String url) { - latch = new CountDownLatch(1); + if (url.contains("https")) { + url = url.replaceAll("https", "wss"); + } else { + url = url.replaceAll("http", "ws"); + } - if (url.contains("https")) { - url = url.replaceAll("https", "wss"); - } - else { - url = url.replaceAll("http", "ws"); - } - - try { - client = new ManualClientEnd(new URI(url+"notifications")); - latch.await(); - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - } - } + try { + client = new ManualClientEnd(new URI(url + "notifications")); + client.connect(); + latch.await(); + client.close(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + } - public static PDPNotification result(NotificationScheme scheme) { - if (resultJson == null || notification == null) { - logger.debug("No Result" ); - return null; - } else { - if(scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) { - boolean removed = false; - boolean updated = false; - if(notification.getRemovedPolicies()!=null && !notification.getRemovedPolicies().isEmpty()){ - removed = true; - } - if(notification.getLoadedPolicies()!=null && !notification.getLoadedPolicies().isEmpty()){ - updated = true; - } - if(removed && updated) { - notification.setNotificationType(NotificationType.BOTH); - }else if(removed){ - notification.setNotificationType(NotificationType.REMOVE); - }else if(updated){ - notification.setNotificationType(NotificationType.UPDATE); - } - return notification; - }else if(scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) { - return MatchStore.checkMatch(notification); - }else { - return null; - } - } - } - - // WebSockets Code.. - @OnOpen - public void onOpen(Session session) throws IOException { - logger.info("Session Started with : " + session.getId()); - session.getBasicRemote().sendText("Manual"); - } - - @OnError - public void onError(Session session, Throwable e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in: "+ session.getId()); - latch.countDown(); - } - - @OnClose - public void onClose(Session session) { - logger.info("Session ended with "+ session.getId()); - latch.countDown(); - client.close(); - } - - @OnMessage - public static void onMessage(String message, Session session){ - logger.debug(" Manual Notification Recieved Message : " + message +" Session info is : "+ session.getId()); - resultJson = message; - try { - notification = NotificationUnMarshal.notificationJSON(message); - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - latch.countDown(); - } - try { - session.close(); - } catch (IOException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - latch.countDown(); - } // For Manual Client.. - latch.countDown(); - } + /** + * Result. + * + * @param scheme the scheme + * @return the PDP notification + */ + public static PDPNotification result(NotificationScheme scheme) { + if (resultJson == null || notification == null) { + logger.info("ManualClientENd - No Result available"); + return null; + } else { + if (scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) { + boolean removed = false; + boolean updated = false; + if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) { + removed = true; + notification.setNotificationType(NotificationType.REMOVE); + } + if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) { + updated = true; + notification.setNotificationType(NotificationType.UPDATE); + } + if (removed && updated) { + notification.setNotificationType(NotificationType.BOTH); + } + return notification; + } else if (scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) { + return MatchStore.checkMatch(notification); + } else { + return null; + } + } + } } diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java index 2349c2e2f..f09b5779c 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java @@ -1103,7 +1103,7 @@ public class StdPolicyEngine { this.dmaapThread = true; } else { if (pdps.get(0) != null) { - if (AutoClientEnd.getURL() == null) { + if (AutoClientEnd.getUrl() == null) { AutoClientEnd.start(pdps.get(0)); } else { AutoClientEnd.stop(); diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientEndTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientEndTest.java index 664dcc808..4f1ce6f59 100644 --- a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientEndTest.java +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientEndTest.java @@ -21,196 +21,111 @@ package org.onap.policy.std.test; import static org.junit.Assert.assertNotNull; - -import org.junit.After; -import org.junit.Before; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.concurrent.CountDownLatch; +import org.java_websocket.WebSocket; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.server.WebSocketServer; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.api.NotificationHandler; import org.onap.policy.api.NotificationScheme; +import org.onap.policy.api.PDPNotification; import org.onap.policy.std.AutoClientEnd; -import org.onap.policy.std.StdPolicyEngine; +import org.onap.policy.std.StdPDPNotification; +import org.springframework.util.SocketUtils; /** * The class <code>AutoClientEndTest</code> contains tests for the class <code>{@link AutoClientEnd}</code>. * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ */ public class AutoClientEndTest { + private static WebSocketServer ws; + + private static int port = 18080; + private static CountDownLatch countServerDownLatch = null; + private StdPDPNotification notification = null; + + /** + * Start server. + * + * @throws Exception the exception + */ + @BeforeClass + public static void startServer() throws Exception { + port = SocketUtils.findAvailableTcpPort(); + ws = new WebSocketServer(new InetSocketAddress(port), 16) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + conn.send("{\"removedPolicies\": [],\"loadedPolicies\": " + + "[{\"policyName\": \"Test.Config_BRMS_Param_BrmsParamTestPa.1.xml\"," + + "\"versionNo\": \"1\",\"matches\": {\"ECOMPName\": \"DROOLS\"," + + "\"ONAPName\": \"DROOLS\",\"ConfigName\": \"BRMS_PARAM_RULE\"," + + "\"guard\": \"false\",\"TTLDate\": \"NA\",\"RiskLevel\": \"5\"," + + "\"RiskType\": \"default\"},\"updateType\": \"NEW\"}],\"notificationType\": \"UPDATE\"}"); + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + + } + + @Override + public void onMessage(WebSocket conn, String message) {} + + @Override + public void onError(WebSocket conn, Exception ex) { + + ex.printStackTrace(); + fail("There should be no exception!"); + } + + @Override + public void onStart() {} + + + }; + + ws.setConnectionLostTimeout(30); + ws.start(); + } + + @Test + public void testAutoClient() throws Exception { + + NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; + NotificationHandler handler = new NotificationHandler() { + + @Override + public void notificationReceived(PDPNotification notifi) { + notification = (StdPDPNotification) notifi; + countServerDownLatch.countDown(); + + } + }; + + AutoClientEnd.setAuto(scheme, handler); + countServerDownLatch = new CountDownLatch(1); + + AutoClientEnd.start("http://localhost:" + port + "/"); + countServerDownLatch.await(); + + + assertNotNull(notification); + assertTrue(AutoClientEnd.getStatus()); + } + + @AfterClass + public static void successTests() throws InterruptedException, IOException { + AutoClientEnd.stop(); + ws.stop(); + } + + - /** - * Run the boolean getStatus() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetStatus_1() - throws Exception { - - boolean result = AutoClientEnd.getStatus(); - - assertNotNull(result); - } - - /** - * Run the String getURL() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetURL_1() - throws Exception { - - String result = AutoClientEnd.getURL(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientEnd - assertNotNull(result); - } - - - /** - * Run the void setAuto(NotificationScheme,NotificationHandler) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetAuto() - throws Exception { - NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; - NotificationHandler handler = null; - - AutoClientEnd.setAuto(scheme, handler); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.ExceptionInInitializerError - // at org.apache.log4j.Logger.getLogger(Logger.java:104) - // at org.onap.policy.std.AutoClientEnd.<clinit>(AutoClientEnd.java:39) - } - - /** - * Run the void setScheme(NotificationScheme) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetScheme() - throws Exception { - - NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; - AutoClientEnd.setScheme(scheme); - - } - - /** - * Run the void start(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testStart() - throws Exception { - String url = "http://test.com"; - - AutoClientEnd.start(url); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientEnd - } - - - /** - * Run the void start(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testStart_2() - throws Exception { - String url = null; - - AutoClientEnd.start(url); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientEnd - } - - /** - * Run the void stop() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testStop_1() - throws Exception { - - AutoClientEnd.stop(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientEnd - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add set up code here - StdPolicyEngine policyEngine = new StdPolicyEngine("Test/config_pass.properties", (String) null); - - NotificationHandler handler = policyEngine.getNotificationHandler(); - AutoClientEnd.setAuto(NotificationScheme.AUTO_ALL_NOTIFICATIONS, handler); - AutoClientEnd.start("http://testurl.com"); - - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(AutoClientEndTest.class); - } } diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndTest.java index b87fa74bd..4a09164b5 100644 --- a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndTest.java +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndTest.java @@ -21,17 +21,21 @@ package org.onap.policy.std.test; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.net.URI; -import java.net.URL; - -import org.junit.After; -import org.junit.Before; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.concurrent.CountDownLatch; +import org.java_websocket.WebSocket; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.server.WebSocketServer; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.api.NotificationScheme; -import org.onap.policy.api.PDPNotification; import org.onap.policy.std.ManualClientEnd; +import org.springframework.util.SocketUtils; /** * The class <code>ManualClientEndTest</code> contains tests for the class <code>{@link ManualClientEnd}</code>. @@ -40,91 +44,72 @@ import org.onap.policy.std.ManualClientEnd; * @version $Revision: 1.0 $ */ public class ManualClientEndTest { - /** - * Run the ManualClientEnd() constructor test. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testManualClientEnd_1() - throws Exception { - ManualClientEnd mce = new ManualClientEnd(new URI("http://www.onap.org")); - assertNotNull(mce); - mce.close(); - // add additional test code here - } - - - /** - * Run the PDPNotification result(NotificationScheme) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testResult_1() - throws Exception { - NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; - - PDPNotification result = ManualClientEnd.result(scheme); - - assertNull(result); - } - - - /** - * Run the void start(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStart_1() - throws Exception { - String url = "This is not a URL"; - - ManualClientEnd.start(url); - - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(ManualClientEndTest.class); - } + private static WebSocketServer ws; + + private static int port = 18080; + private static CountDownLatch countServerDownLatch = null; + private static String recvMsg = null; + + /** + * Start server. + * + * @throws Exception the exception + */ + @BeforeClass + public static void startServer() throws Exception { + port = SocketUtils.findAvailableTcpPort(); + ws = new WebSocketServer(new InetSocketAddress(port), 16) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + countServerDownLatch.countDown(); + } + + @Override + public void onMessage(WebSocket conn, String message) { + recvMsg = message; + conn.send("{\"removedPolicies\": [],\"loadedPolicies\":" + + "[{\"policyName\": \"Test.Config_BRMS_Param_BrmsParamTestPa.1.xml\"," + + "\"versionNo\": \"1\",\"matches\": {\"ECOMPName\": \"DROOLS\"," + + "\"ONAPName\": \"DROOLS\",\"ConfigName\": \"BRMS_PARAM_RULE\"," + + "\"guard\": \"false\",\"TTLDate\": \"NA\",\"RiskLevel\": \"5\"," + + "\"RiskType\": \"default\"},\"updateType\": \"NEW\"}],\"notificationType\": \"UPDATE\"}"); + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + ex.printStackTrace(); + fail("There should be no exception!"); + } + + @Override + public void onStart() {} + + + }; + + ws.setConnectionLostTimeout(30); + ws.start(); + } + + @Test + public void testAutoClient() throws Exception { + countServerDownLatch = new CountDownLatch(1); + + ManualClientEnd.start("http://localhost:" + port + "/"); + countServerDownLatch.await(); + + assertNotNull(ManualClientEnd.result(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)); + assertTrue("Manual".equalsIgnoreCase(recvMsg)); + } + + @AfterClass + public static void successTests() throws InterruptedException, IOException { + ws.stop(); + } } diff --git a/packages/base/src/files/etc/ssl/policy-keystore b/packages/base/src/files/etc/ssl/policy-keystore Binary files differnew file mode 100644 index 000000000..c3890965b --- /dev/null +++ b/packages/base/src/files/etc/ssl/policy-keystore diff --git a/packages/docker/src/main/docker/do-start.sh b/packages/docker/src/main/docker/do-start.sh index 47b835ac9..0179fad70 100644 --- a/packages/docker/src/main/docker/do-start.sh +++ b/packages/docker/src/main/docker/do-start.sh @@ -64,9 +64,10 @@ else . /opt/app/policy/etc/profile.d/env.sh - # install policy keystore - mkdir -p $POLICY_HOME/etc/ssl - cp config/policy-keystore $POLICY_HOME/etc/ssl + if [[ -f config/policy-keystore ]]; then + # install policy keystore + cp config/policy-keystore $POLICY_HOME/etc/ssl + fi if [[ -f config/$container-tweaks.sh ]] ; then # file may not be executable; running it as an diff --git a/packages/docker/src/main/docker/docker-install.sh b/packages/docker/src/main/docker/docker-install.sh index a4dd0ceb1..62289c591 100644 --- a/packages/docker/src/main/docker/docker-install.sh +++ b/packages/docker/src/main/docker/docker-install.sh @@ -356,7 +356,6 @@ function install_base() { exit 1 fi - /bin/mkdir -p ${POLICY_HOME}/etc/ssl > /dev/null 2>&1 /bin/mkdir -p ${POLICY_HOME}/etc/init.d > /dev/null 2>&1 /bin/mkdir -p ${POLICY_HOME}/tmp > /dev/null 2>&1 /bin/mkdir -p ${POLICY_HOME}/var > /dev/null 2>&1 @@ -394,6 +393,21 @@ function configure_base() { fi } +function configure_keystore() { + if [[ $DEBUG == y ]]; then + echo "-- ${FUNCNAME[0]} --" + set -x + fi + + local DEFAULT_KEYSTORE_PASSWORD="Pol1cy_0nap" + + if [[ -n ${KEYSTORE_PASSWD} ]]; then + keytool -storepasswd -storepass ${DEFAULT_KEYSTORE_PASSWORD} -keystore ${POLICY_HOME}/etc/ssl/policy-keystore -new ${KEYSTORE_PASSWD} + keytool -list -keystore ${POLICY_HOME}/etc/ssl/policy-keystore -storepass ${KEYSTORE_PASSWD} + fi +} + + function install_tomcat_component() { if [[ $DEBUG == y ]]; then echo "-- ${FUNCNAME[0]} $@ --" @@ -731,6 +745,7 @@ if [[ ${OPERATION} == configure ]]; then base) configure_base component_preconfigure + configure_keystore ;; pdp) configure_component "${COMPONENT_TYPE}.conf" "${POLICY_HOME}/servers/${COMPONENT_TYPE}/" |