b74d87c482ec69a7ba9db273e32820fe3f9b1c0b
[portal/sdk.git] /
1 /*-
2  * ================================================================================
3  * eCOMP Portal SDK
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20 package org.openecomp.portalsdk.core.restful.client;
21
22 import java.io.IOException;
23 import java.net.URI;
24 import java.net.URISyntaxException;
25
26 import javax.servlet.http.HttpServletResponse;
27
28 import org.apache.http.Consts;
29 import org.apache.http.HttpEntity;
30 import org.apache.http.client.ClientProtocolException;
31 import org.apache.http.client.methods.CloseableHttpResponse;
32 import org.apache.http.client.methods.HttpGet;
33 import org.apache.http.client.methods.HttpPost;
34 import org.apache.http.entity.ContentType;
35 import org.apache.http.entity.StringEntity;
36 import org.apache.http.impl.client.CloseableHttpClient;
37 import org.apache.http.impl.client.HttpClients;
38 import org.apache.http.util.EntityUtils;
39 import org.openecomp.portalsdk.core.domain.App;
40 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
41 import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
42 import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
43 import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
44 import org.openecomp.portalsdk.core.service.AppService;
45 import org.springframework.beans.factory.annotation.Autowired;
46 import org.springframework.stereotype.Component;
47
48 /**
49  * Provides a basic client to access a REST endpoint at the Portal via get or
50  * post. Usage caveats:
51  * <OL>
52  * <LI>Must be auto-wired by Spring, because this in turn auto-wires a
53  * data-access service to read application credentials from the FN_APP table.
54  * <LI>If HTTP access is used and the server uses a self-signed certificate, the
55  * local trust store must be extended appropriately. The HTTP client throws
56  * exceptions if the JVM cannot validate the server certificate.
57  * </OL>
58  */
59 @Component
60 public class PortalRestClientBase {
61
62         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalRestClientBase.class);
63
64         @Autowired
65         AppService appService;
66
67         /**
68          * Constructs and sends a GET request for the URI, with REST application
69          * credentials in the header as the Portal expects.
70          * 
71          * @param uri
72          *            URI of the service
73          * @return Result of the get; null if an error happens
74          * @throws URISyntaxException
75          * @throws IOException
76          * @throws ClientProtocolException
77          */
78         public HttpStatusAndResponse getRestWithCredentials(final URI uri) throws Exception {
79
80                 String uebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
81                 App app = appService.getDefaultApp();
82                 if (uebKey == null || app == null || app.getUsername() == null || app.getAppPassword() == null)
83                         throw new Exception("Missing one or more required properties and/or database entries");
84                 String decryptedPassword = CipherUtil.decrypt(app.getAppPassword());
85                 CloseableHttpClient httpClient = HttpClients.createDefault();
86                 HttpGet httpGet = new HttpGet(uri);
87                 httpGet.setHeader("uebkey", uebKey);
88                 httpGet.setHeader("username", app.getUsername());
89                 httpGet.setHeader("password", decryptedPassword);
90
91                 String responseJson = null;
92                 CloseableHttpResponse response = null;
93                 try {
94                         logger.info(EELFLoggerDelegate.debugLogger, "GET from " + uri);
95                         response = httpClient.execute(httpGet);
96                         logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine());
97                         if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
98                             logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine().toString());
99                         HttpEntity entity = response.getEntity();
100                         if (entity == null) {
101                                 logger.info(EELFLoggerDelegate.debugLogger, "Entity is null!");
102                         } else {
103                                 // entity content length is never set.
104                                 // this naively tries to read everything.
105                                 responseJson = EntityUtils.toString(entity);
106                                 logger.info(EELFLoggerDelegate.debugLogger, responseJson);
107                                 EntityUtils.consume(entity);
108                         }
109                 } finally {
110                         if (response != null)
111                                 response.close();
112                 }
113                 if (response == null)
114                         return null;
115                 return new HttpStatusAndResponse(response.getStatusLine().getStatusCode(), responseJson);
116         }
117
118         /**
119          * Constructs and sends a POST request using the specified body, with REST
120          * application credentials in the header as the Portal expects.
121          * 
122          * @param uri
123          *            REST endpoint
124          * @param json
125          *            Content to post
126          * @return Result of the post; null if an error happens
127          * @throws Exception
128          */
129         public HttpStatusAndResponse postRestWithCredentials(final URI uri, final String json) throws Exception {
130
131                 String uebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
132                 App app = appService.getDefaultApp();
133                 if (uebKey == null || app == null || app.getUsername() == null || app.getAppPassword() == null)
134                         throw new Exception("Missing one or more required properties and/or database entries");
135
136                 CloseableHttpClient httpClient = HttpClients.createDefault();
137                 HttpPost httpPost = new HttpPost(uri);
138                 httpPost.setHeader("uebkey", uebKey);
139                 httpPost.setHeader("username", app.getUsername());
140                 httpPost.setHeader("password", app.getAppPassword());
141
142                 StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8));
143                 httpPost.setEntity(postEntity);
144
145                 String responseJson = null;
146                 CloseableHttpResponse response = null;
147                 try {
148                         logger.info(EELFLoggerDelegate.debugLogger, "POST to " + uri);
149                         response = httpClient.execute(httpPost);
150                         logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine());
151                         if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
152                                 throw new Exception("Status is " + response.getStatusLine().toString());
153
154                         HttpEntity entity = response.getEntity();
155                         if (entity == null) {
156                                 logger.info(EELFLoggerDelegate.debugLogger, "Entity is null!");
157                         } else {
158                                 // entity content length is never set.
159                                 // this naively tries to read everything.
160                                 responseJson = EntityUtils.toString(entity);
161                                 logger.info(EELFLoggerDelegate.debugLogger, responseJson);
162                                 EntityUtils.consume(entity);
163                         }
164                 } finally {
165                         if (response != null)
166                                 response.close();
167                 }
168                 return new HttpStatusAndResponse(response.getStatusLine().getStatusCode(), responseJson);
169         }
170
171 }