summaryrefslogtreecommitdiffstats
path: root/BRMSGateway/src/main/java/org/onap/policy/brms/api/nexus/NexusRestWrapper.java
blob: 9ee7598fd937186cde0388f8feff5c7e9ac2306a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
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();
    }
}