import java.io.IOException;
import java.util.Map;
+import java.util.Map.Entry;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
public class RESTManager {
- private static final Logger logger = LoggerFactory.getLogger(RESTManager.class);
-
- public class Pair<A, B> {
- public final A a;
- public final B b;
-
- public Pair(A a, B b) {
- this.a = a;
- this.b = b;
- }
- }
-
- public Pair<Integer, String> post(String url, String username, String password, Map<String, String> headers, String contentType, String body) {
- CredentialsProvider credentials = new BasicCredentialsProvider();
- credentials.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
-
- logger.debug("HTTP REQUEST: {} -> {} {} -> {}", url, username, ((password!=null)?password.length():"-"), contentType);
- if (headers != null) {
- logger.debug("Headers: ");
- headers.forEach((name, value) -> {
- logger.debug("{} -> {}", name, value);
- });
- }
- logger.debug(body);
-
- try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentials).build()) {
-
- HttpPost post = new HttpPost(url);
- if (headers != null) {
- for (String key : headers.keySet()) {
- post.addHeader(key, headers.get(key));
- }
- }
- post.addHeader("Content-Type", contentType);
-
- StringEntity input = new StringEntity(body);
- input.setContentType(contentType);
- post.setEntity(input);
-
- HttpResponse response = client.execute(post);
- if (response != null) {
- String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
- logger.debug("HTTP POST Response Status Code: {}", response.getStatusLine().getStatusCode());
- logger.debug("HTTP POST Response Body:");
- logger.debug(returnBody);
-
- return new Pair<Integer, String>(response.getStatusLine().getStatusCode(), returnBody);
- } else {
- logger.error("Response from {} is null", url);
- return null;
- }
- } catch (Exception e) {
- logger.error("Failed to POST to {}",url,e);
- return null;
- }
- }
-
- public Pair<Integer, String> get(String url, String username, String password, Map<String, String> headers) {
-
- CredentialsProvider credentials = new BasicCredentialsProvider();
- credentials.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
-
- try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentials).build()) {
-
- HttpGet get = new HttpGet(url);
- if (headers != null) {
- for (String key : headers.keySet()) {
- get.addHeader(key, headers.get(key));
- }
- }
-
- HttpResponse response = client.execute(get);
-
- String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
-
- logger.debug("HTTP GET Response Status Code: {}", response.getStatusLine().getStatusCode());
- logger.debug("HTTP GET Response Body:");
- logger.debug(returnBody);
-
- return new Pair<Integer, String>(response.getStatusLine().getStatusCode(), returnBody);
- } catch (IOException e) {
- logger.error("Failed to GET to {}",url,e);
- return null;
- }
- }
+ private static final Logger logger = LoggerFactory.getLogger(RESTManager.class);
+
+ public class Pair<A, B> {
+ public final A a;
+ public final B b;
+
+ public Pair(A a, B b) {
+ this.a = a;
+ this.b = b;
+ }
+ }
+
+ public Pair<Integer, String> post(String url, String username, String password,
+ Map<String, String> headers, String contentType, String body) {
+ CredentialsProvider credentials = new BasicCredentialsProvider();
+ credentials.setCredentials(AuthScope.ANY,
+ new UsernamePasswordCredentials(username, password));
+
+ logger.debug("HTTP REQUEST: {} -> {} {} -> {}", url, username,
+ ((password != null) ? password.length() : "-"), contentType);
+ if (headers != null) {
+ logger.debug("Headers: ");
+ headers.forEach((name, value) -> logger.debug("{} -> {}", name, value));
+ }
+ logger.debug(body);
+
+ try (CloseableHttpClient client =
+ HttpClientBuilder.create().setDefaultCredentialsProvider(credentials).build()) {
+
+ HttpPost post = new HttpPost(url);
+ if (headers != null) {
+ for (Entry<String, String> entry : headers.entrySet()) {
+ post.addHeader(entry.getKey(), headers.get(entry.getKey()));
+ }
+ }
+ post.addHeader("Content-Type", contentType);
+
+ StringEntity input = new StringEntity(body);
+ input.setContentType(contentType);
+ post.setEntity(input);
+
+ HttpResponse response = client.execute(post);
+ if (response != null) {
+ String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
+ logger.debug("HTTP POST Response Status Code: {}",
+ response.getStatusLine().getStatusCode());
+ logger.debug("HTTP POST Response Body:");
+ logger.debug(returnBody);
+
+ return new Pair<>(response.getStatusLine().getStatusCode(),
+ returnBody);
+ }
+ else {
+ logger.error("Response from {} is null", url);
+ return null;
+ }
+ }
+ catch (Exception e) {
+ logger.error("Failed to POST to {}", url, e);
+ return null;
+ }
+ }
+
+ public Pair<Integer, String> get(String url, String username, String password,
+ Map<String, String> headers) {
+
+ CredentialsProvider credentials = new BasicCredentialsProvider();
+ credentials.setCredentials(AuthScope.ANY,
+ new UsernamePasswordCredentials(username, password));
+
+ try (CloseableHttpClient client =
+ HttpClientBuilder.create().setDefaultCredentialsProvider(credentials).build()) {
+
+ HttpGet get = new HttpGet(url);
+ if (headers != null) {
+ for (Entry<String, String> entry : headers.entrySet()) {
+ get.addHeader(entry.getKey(), headers.get(entry.getKey()));
+ }
+ }
+
+ HttpResponse response = client.execute(get);
+
+ String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
+
+ logger.debug("HTTP GET Response Status Code: {}",
+ response.getStatusLine().getStatusCode());
+ logger.debug("HTTP GET Response Body:");
+ logger.debug(returnBody);
+
+ return new Pair<>(response.getStatusLine().getStatusCode(), returnBody);
+ }
+ catch (IOException e) {
+ logger.error("Failed to GET to {}", url, e);
+ return null;
+ }
+ }
}
--- /dev/null
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * rest\r
+ * ================================================================================\r
+ * \r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.onap.policy.rest;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+import static org.junit.Assert.assertTrue;\r
+\r
+import org.junit.Test;\r
+import org.onap.policy.rest.RESTManager.Pair;\r
+\r
+public class TestGet {\r
+\r
+ @Test(expected = NullPointerException.class)\r
+ public void testUrlNull() {\r
+ RESTManager mgr = new RESTManager();\r
+ mgr.get(null, "user", null, null);\r
+ }\r
+\r
+ @Test(expected = IllegalArgumentException.class)\r
+ public void testUsernameNull() {\r
+ RESTManager mgr = new RESTManager();\r
+ mgr.get("nothing", null, null, null);\r
+ }\r
+\r
+ @Test\r
+ public void testUrlExampleOrg() {\r
+ RESTManager mgr = new RESTManager();\r
+\r
+ Pair<Integer, String> result = mgr.get("http://www.example.org", "user", null, null);\r
+ assertEquals((Integer)200, result.a);\r
+ assertTrue(result.b != null);\r
+ assertTrue(result.b.length() > 0);\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * rest\r
+ * ================================================================================\r
+ * \r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.onap.policy.rest;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+\r
+import org.junit.Test;\r
+import org.onap.policy.rest.RESTManager.Pair;\r
+\r
+public class TestPair {\r
+\r
+ @Test\r
+ public void testPair() {\r
+ RESTManager mgr = new RESTManager();\r
+\r
+ Pair<Integer, Integer> pii = mgr.new Pair<>(1, 2);\r
+ assertEquals((Integer) 1, (Integer) pii.a);\r
+ assertEquals((Integer) 2, (Integer) pii.b);\r
+\r
+ Pair<Integer, String> pis = mgr.new Pair<>(1, "test");\r
+ assertEquals((Integer) 1, (Integer) pis.a);\r
+ assertEquals("test", pis.b);\r
+ }\r
+}\r
--- /dev/null
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * rest\r
+ * ================================================================================\r
+ * \r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.onap.policy.rest;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+\r
+import org.junit.Test;\r
+import org.onap.policy.rest.RESTManager.Pair;\r
+\r
+public class TestPost {\r
+\r
+ @Test(expected = IllegalArgumentException.class)\r
+ public void testUsernameNull() {\r
+ RESTManager mgr = new RESTManager();\r
+ mgr.post("nothing", null, null, null, null, null);\r
+ }\r
+\r
+ @Test\r
+ public void testBodyNull() {\r
+ RESTManager mgr = new RESTManager();\r
+ Pair<Integer, String> result = mgr.post("http://www.example.org", "user", null, null, null, null);\r
+ assertEquals(null, result);\r
+ }\r
+}\r