summaryrefslogtreecommitdiffstats
path: root/openstack-client-connectors/jersey-connector
diff options
context:
space:
mode:
authorRob Daugherty <rd472p@att.com>2018-09-12 11:57:43 -0400
committerRob Daugherty <rd472p@att.com>2018-09-12 14:47:22 -0400
commite38ab31eecbcdbc3b3ea4b6001770e7100ef9240 (patch)
tree25ff5751ca2eda57c1f9179b94e165b81be2cecf /openstack-client-connectors/jersey-connector
parent69135296d0c23ad73efb813e56da65cf309c5986 (diff)
Remove unused connectors and modules
NexusIQ issue: org.codehaus.jackson Jersey 2.6 uses codehaus.jackson which has security vulnerabilities. Rather than upgrading the Jersey version, I'm totally removing the Jersey, Jersey2, and RESTEasy connectors. We don't use them. I'm also removing the console and examples modules. They haven't even been compiled in a long time. Unit test coverage will go up to 74%. Change-Id: Ie0145e56718adfe5ea7a677439564e7a25c73fe6 Issue-ID: SO-864 Signed-off-by: Rob Daugherty <rd472p@att.com>
Diffstat (limited to 'openstack-client-connectors/jersey-connector')
-rw-r--r--openstack-client-connectors/jersey-connector/pom.xml29
-rw-r--r--openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyConnector.java119
-rw-r--r--openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyLoggingFilter.java225
-rw-r--r--openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyResponse.java82
-rw-r--r--openstack-client-connectors/jersey-connector/src/main/resources/META-INF/services/com.woorea.openstack.base.client.OpenStackClientConnector1
-rw-r--r--openstack-client-connectors/jersey-connector/src/test/java/com/woorea/openstack/connector/JerseyLoggingFilterTest.java267
6 files changed, 0 insertions, 723 deletions
diff --git a/openstack-client-connectors/jersey-connector/pom.xml b/openstack-client-connectors/jersey-connector/pom.xml
deleted file mode 100644
index e942e8d..0000000
--- a/openstack-client-connectors/jersey-connector/pom.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.onap.so.libs.openstack-java-sdk</groupId>
- <artifactId>client-connectors</artifactId>
- <version>1.2.1-SNAPSHOT</version>
- </parent>
- <groupId>org.onap.so.libs.openstack-java-sdk.client-connectors</groupId>
- <artifactId>jersey-connector</artifactId>
- <name>OpenStack Jersey Connector</name>
- <description>OpenStack Jersey Connector</description>
- <dependencies>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-client</artifactId>
- <version>1.17.1</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-all</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-</project>
diff --git a/openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyConnector.java b/openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyConnector.java
deleted file mode 100644
index 770b4d8..0000000
--- a/openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyConnector.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * 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 com.woorea.openstack.connector;
-
-import java.util.List;
-import java.util.Map;
-import java.util.logging.Logger;
-
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.ext.ContextResolver;
-import javax.ws.rs.ext.Provider;
-
-import com.fasterxml.jackson.annotation.JsonRootName;
-import com.fasterxml.jackson.annotation.JsonInclude.Include;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.SerializationFeature;
-import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.UniformInterfaceException;
-import com.sun.jersey.api.client.WebResource;
-import com.sun.jersey.api.client.config.ClientConfig;
-import com.sun.jersey.api.client.config.DefaultClientConfig;
-import com.sun.jersey.client.impl.ClientRequestImpl;
-import com.sun.jersey.core.header.OutBoundHeaders;
-import com.woorea.openstack.base.client.OpenStackClientConnector;
-import com.woorea.openstack.base.client.OpenStackRequest;
-import com.woorea.openstack.base.client.OpenStackResponse;
-import com.woorea.openstack.base.client.OpenStackResponseException;
-
-public class JerseyConnector implements OpenStackClientConnector {
-
- protected Client client = null;
- protected boolean logPassword;
- private JerseyLoggingFilter logger = new JerseyLoggingFilter(Logger.getLogger("os"));
-
- public JerseyConnector() {
- ClientConfig clientConfig = new DefaultClientConfig();
- clientConfig.getClasses().add(JacksonJaxbJsonProvider.class);
- clientConfig.getClasses().add(OpenStackObjectMapper.class);
- client = Client.create(clientConfig);
- }
-
- @Override
- public <T> OpenStackResponse request(OpenStackRequest<T> request) {
- WebResource target = client.resource(request.endpoint()).path(request.path());
- for(Map.Entry<String, List<Object> > entry : request.queryParams().entrySet()) {
- for (Object o : entry.getValue()) {
- target = target.queryParam(entry.getKey(), String.valueOf(o));
- }
- }
- target.addFilter(logger);
- MultivaluedMap<String, Object> headers = new OutBoundHeaders();
- for(Map.Entry<String, List<Object>> h : request.headers().entrySet()) {
- for(Object v : h.getValue()) {
- headers.add(h.getKey(), v);
- }
- }
- if(request.entity() != null && request.entity().getContentType() != null) {
- headers.add("Content-Type", request.entity().getContentType());
- } else {
- headers.add("Content-Type", "application/json");
- }
- try {
- ClientResponse response;
- if (request.entity() != null && request.entity().getEntity() != null) {
- response = target.getHeadHandler().handle(new ClientRequestImpl(target.getURI(), request.method().name(), request.entity().getEntity(), headers));
- } else {
- response = target.getHeadHandler().handle(new ClientRequestImpl(target.getURI(), request.method().name(), null, headers));
- }
- return new JerseyResponse(response);
- } catch (UniformInterfaceException e) {
- throw new OpenStackResponseException(e.getResponse().getClientResponseStatus().getReasonPhrase(), e.getResponse().getStatus());
- }
- }
-
- @Provider
- public static class OpenStackObjectMapper implements ContextResolver<ObjectMapper> {
- static ObjectMapper DEFAULT_MAPPER;
- static ObjectMapper WRAPPED_MAPPER;
- static {
- DEFAULT_MAPPER = new ObjectMapper();
- DEFAULT_MAPPER.setSerializationInclusion(Include.NON_NULL);
- DEFAULT_MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
- DEFAULT_MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
- DEFAULT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
- DEFAULT_MAPPER.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
-
- WRAPPED_MAPPER = new ObjectMapper();
- WRAPPED_MAPPER.setSerializationInclusion(Include.NON_NULL);
- WRAPPED_MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
- WRAPPED_MAPPER.enable(SerializationFeature.WRAP_ROOT_VALUE);
- WRAPPED_MAPPER.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
- WRAPPED_MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
- WRAPPED_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
- WRAPPED_MAPPER.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
- }
-
- @Override
- public ObjectMapper getContext(Class<?> type) {
- return type.getAnnotation(JsonRootName.class) == null ? DEFAULT_MAPPER : WRAPPED_MAPPER;
- }
- }
-}
diff --git a/openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyLoggingFilter.java b/openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyLoggingFilter.java
deleted file mode 100644
index ffdeb83..0000000
--- a/openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyLoggingFilter.java
+++ /dev/null
@@ -1,225 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package com.woorea.openstack.connector;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.logging.Logger;
-
-import com.sun.jersey.api.client.AbstractClientRequestAdapter;
-import com.sun.jersey.api.client.ClientHandlerException;
-import com.sun.jersey.api.client.ClientRequest;
-import com.sun.jersey.api.client.ClientRequestAdapter;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.filter.ClientFilter;
-import com.sun.jersey.core.util.ReaderWriter;
-
-/**
- * A Jersey client filter that writes the request and response to a specified logger.
- */
-public class JerseyLoggingFilter extends ClientFilter {
-
- private final AtomicLong counter = new AtomicLong(0);
- private final Logger logger;
-
- /**
- * Constructor
- * @param logger the logger to which the request and response are written.
- */
- public JerseyLoggingFilter(Logger logger) {
- this.logger = logger;
- }
-
- @Override
- public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
- long id = counter.incrementAndGet();
- logRequest(id, request);
- ClientResponse response = getNext().handle(request);
- logResponse(id, response);
- return response;
- }
-
- /**
- * Logs a request.
- * @param id the request id (counter)
- * @param request the request
- */
- private void logRequest(long id, ClientRequest request) {
- StringBuilder builder = new StringBuilder();
-
- builder.append(String.valueOf(id));
- builder.append(" * Client out-bound request\n");
-
- builder.append(String.valueOf(id));
- builder.append(" > ");
- builder.append(request.getMethod());
- builder.append(" ");
- builder.append(request.getURI().toASCIIString());
- builder.append("\n");
-
- // Request headers
-
- for (Map.Entry<String, List<Object>> entry : request.getHeaders().entrySet()) {
- String header = entry.getKey();
- List<Object> values = entry.getValue();
-
- if (values.size() == 1) {
- builder.append(String.valueOf(id));
- builder.append(" > ");
- builder.append(header);
- builder.append(": ");
- builder.append(ClientRequest.getHeaderValue(values.get(0)));
- builder.append("\n");
- } else {
- StringBuilder buf = new StringBuilder();
- boolean first = true;
-
- for(Object value : values) {
- if (first) {
- first = false;
- } else {
- buf.append(",");
- }
-
- buf.append(ClientRequest.getHeaderValue(value));
- }
-
- builder.append(String.valueOf(id));
- builder.append(" > ");
- builder.append(header);
- builder.append(": ");
- builder.append(buf.toString());
- builder.append("\n");
- }
- }
-
- // Request body
-
- if (request.getEntity() != null) {
- request.setAdapter(new JerseyLoggingAdapter(request.getAdapter(), builder));
- } else {
- logger.info(builder.toString());
- }
- }
-
- /**
- * Logs a response.
- * @param id the request id (counter)
- * @param response the response
- */
- private void logResponse(long id, ClientResponse response) {
- StringBuilder builder = new StringBuilder();
-
- builder.append(String.valueOf(id));
- builder.append(" * Client in-bound response\n");
-
- builder.append(String.valueOf(id));
- builder.append(" < ");
- builder.append(String.valueOf(response.getStatus()));
- builder.append("\n");
-
- // Response headers
-
- for (Map.Entry<String, List<String>> entry : response.getHeaders().entrySet()) {
- String header = entry.getKey();
- for (String value : entry.getValue()) {
- builder.append(String.valueOf(id));
- builder.append(" < ");
- builder.append(header);
- builder.append(": ");
- builder.append(value).append("\n");
- }
- }
-
- // Response body
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- InputStream in = response.getEntityInputStream();
- try {
- ReaderWriter.writeTo(in, out);
-
- byte[] requestEntity = out.toByteArray();
- appendToBuffer(builder, requestEntity);
- response.setEntityInputStream(new ByteArrayInputStream(requestEntity));
- } catch (IOException ex) {
- throw new ClientHandlerException(ex);
- }
-
- logger.info(builder.toString());
- }
-
- /**
- * Appends bytes to the builder. If the bytes contain the password pattern,
- * the password is obliterated.
- * @param builder the builder
- * @param bytes the bytes to append
- */
- private void appendToBuffer(StringBuilder builder, byte[] bytes) {
- if (bytes.length != 0) {
- String s = new String(bytes);
- builder.append(s.replaceAll("\"password\".*:.*\"(.*)\"", "\"password\" : \"******\""));
- builder.append("\n");
- }
- }
-
- private class JerseyLoggingAdapter extends AbstractClientRequestAdapter {
- private final StringBuilder builder;
-
- JerseyLoggingAdapter(ClientRequestAdapter adapter, StringBuilder builder) {
- super(adapter);
- this.builder = builder;
- }
-
- @Override
- public OutputStream adapt(ClientRequest request, OutputStream out) throws IOException {
- return new JerseyLoggingOutputStream(getAdapter().adapt(request, out), builder);
- }
- }
-
- private class JerseyLoggingOutputStream extends OutputStream {
- private final OutputStream stream;
- private final StringBuilder builder;
- private final ByteArrayOutputStream logStream = new ByteArrayOutputStream();
-
- JerseyLoggingOutputStream(OutputStream stream, StringBuilder builder) {
- this.stream = stream;
- this.builder = builder;
- }
-
- @Override
- public void write(int value) throws IOException {
- logStream.write(value);
- stream.write(value);
- }
-
- @Override
- public void close() throws IOException {
- appendToBuffer(builder, logStream.toByteArray());
- logger.info(builder.toString());
- stream.close();
- }
- }
-} \ No newline at end of file
diff --git a/openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyResponse.java b/openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyResponse.java
deleted file mode 100644
index 5b01660..0000000
--- a/openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyResponse.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * 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 com.woorea.openstack.connector;
-
-/*
- * Modifications copyright (c) 2017 AT&T Intellectual Property
- */
-
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Map;
-
-import com.sun.jersey.api.client.ClientResponse;
-import com.woorea.openstack.base.client.OpenStackResponse;
-import com.woorea.openstack.base.client.OpenStackResponseException;
-
-public class JerseyResponse implements OpenStackResponse {
-
- private ClientResponse response;
-
- public JerseyResponse(ClientResponse response) {
- this.response = response;
- }
-
- @Override
- public <T> T getEntity(Class<T> returnType) {
- if(response.getStatus() >= 400) {
- throw new OpenStackResponseException(response.getClientResponseStatus().getReasonPhrase(),
- response.getStatus(), this);
- }
- if(response.hasEntity() && returnType != null && Void.class != returnType) {
- return response.getEntity(returnType);
- } else {
- return null;
- }
- }
-
- @Override
- public <T> T getErrorEntity(Class<T> returnType) {
- if(response.getStatus() >= 400 && response.hasEntity()) {
- return response.getEntity(returnType);
- }
- return null;
- }
-
- @Override
- public InputStream getInputStream() {
- if(response.hasEntity()) {
- return response.getEntityInputStream();
- } else {
- return null;
- }
- }
-
- @Override
- public String header(String name) {
- return response.getHeaders().getFirst(name);
- }
-
- @Override
- public Map<String, String> headers() {
- Map<String, String> headers = new HashMap<>();
- for(String k : response.getHeaders().keySet()) {
- headers.put(k, response.getHeaders().getFirst(k));
- }
- return headers;
- }
-}
diff --git a/openstack-client-connectors/jersey-connector/src/main/resources/META-INF/services/com.woorea.openstack.base.client.OpenStackClientConnector b/openstack-client-connectors/jersey-connector/src/main/resources/META-INF/services/com.woorea.openstack.base.client.OpenStackClientConnector
deleted file mode 100644
index 5b9a158..0000000
--- a/openstack-client-connectors/jersey-connector/src/main/resources/META-INF/services/com.woorea.openstack.base.client.OpenStackClientConnector
+++ /dev/null
@@ -1 +0,0 @@
-com.woorea.openstack.connector.JerseyConnector \ No newline at end of file
diff --git a/openstack-client-connectors/jersey-connector/src/test/java/com/woorea/openstack/connector/JerseyLoggingFilterTest.java b/openstack-client-connectors/jersey-connector/src/test/java/com/woorea/openstack/connector/JerseyLoggingFilterTest.java
deleted file mode 100644
index 3ebad7c..0000000
--- a/openstack-client-connectors/jersey-connector/src/test/java/com/woorea/openstack/connector/JerseyLoggingFilterTest.java
+++ /dev/null
@@ -1,267 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package com.woorea.openstack.connector;
-
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doCallRealMethod;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.lang.reflect.Method;
-import java.net.URI;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.logging.ConsoleHandler;
-import java.util.logging.Level;
-import java.util.logging.LogRecord;
-import java.util.logging.Logger;
-import java.util.logging.SimpleFormatter;
-
-import javax.ws.rs.core.MultivaluedMap;
-
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-
-import com.sun.jersey.api.client.ClientHandler;
-import com.sun.jersey.api.client.ClientRequest;
-import com.sun.jersey.api.client.ClientRequestAdapter;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.filter.ClientFilter;
-
-public class JerseyLoggingFilterTest {
-
- private static Logger logger;
- private static LogFormatter logFormatter;
-
- @BeforeClass
- public static void setUpClass() throws Exception {
- logger = Logger.getLogger(JerseyLoggingFilterTest.class.getSimpleName());
- logger.setLevel(Level.ALL);
- logger.setUseParentHandlers(false);
-
- ConsoleHandler handler = new ConsoleHandler();
- logFormatter = new LogFormatter();
- handler.setFormatter(logFormatter);
- handler.setLevel(Level.ALL);
- logger.addHandler(handler);
- }
-
- @Before
- public void setUpTest() {
- logFormatter.clearLog();
- }
-
- /**
- * Tests a scenario with no request content (GET).
- * @throws Exception for unexpected errors
- */
- @Test
- public void testGET() throws Exception {
- String responseContent = "<response>Hello, I am Eliza.</response>";
- execute("GET", "http://www.onap.org/eliza", null, responseContent);
- }
-
- /**
- * Tests a scenario with request content (POST).
- * @throws Exception for unexpected errors
- */
- @Test
- public void testPOST() throws Exception {
- String requestContent = "<request>I feel sad.</request>";
- String responseContent = "<response>Do you often feel sad?</response>";
- execute("POST", "http://www.onap.org/eliza", requestContent, responseContent);
- }
-
- /**
- * Runs a single test.
- * @param httpMethod any HTTP method (POST, GET, ...)
- * @param url any URL
- * @param requestContent mock request content, possibly null
- * @param responseContent mock response content, never null
- * @throws Exception for unexpected errors
- */
- private void execute(String httpMethod, String url, String requestContent, String responseContent)
- throws Exception {
- JerseyLoggingFilter loggingFilter = new JerseyLoggingFilter(logger);
-
- // Mock multi-valued and single valued request headers
-
- HashMap<String, List<Object>> requestHeaderMap = new HashMap<>();
- requestHeaderMap.put("Accept", Arrays.asList(new Object[]{"application/xml","application/json"}));
-
- if (requestContent != null) {
- requestHeaderMap.put("Content-Type", Arrays.asList(new Object[]{"application/xml"}));
- requestHeaderMap.put("Content-Length", Arrays.asList(new Object[]{String.valueOf(requestContent.length())}));
- }
-
- @SuppressWarnings("unchecked")
- MultivaluedMap<String, Object> requestHeaders = mock(MultivaluedMap.class);
- when(requestHeaders.entrySet()).thenReturn(requestHeaderMap.entrySet());
-
- // Mock the request object
-
- ClientRequest request = mock(TestClientRequest.class);
- when(request.getURI()).thenReturn(new URI(url));
- when(request.getMethod()).thenReturn(httpMethod);
- when(request.getHeaders()).thenReturn(requestHeaders);
-
- if (requestContent != null) {
- when(request.getEntity()).thenReturn(requestContent.getBytes("UTF-8"));
- }
-
- doCallRealMethod().when(request).setAdapter(any(ClientRequestAdapter.class));
- when(request.getAdapter()).thenCallRealMethod();
- request.setAdapter(new DefaultClientRequestAdapter());
-
- // Mock multi-valued and single valued response headers
-
- HashMap<String, List<String>> responseHeaderMap = new HashMap<>();
- responseHeaderMap.put("Cache-Control", Arrays.asList(new String[]{"no-cache","no-store"}));
- responseHeaderMap.put("Content-Type", Arrays.asList(new String[]{"application/xml"}));
- responseHeaderMap.put("Content-Length", Arrays.asList(new String[]{String.valueOf(responseContent.length())}));
- @SuppressWarnings("unchecked")
- MultivaluedMap<String, String> responseHeaders = mock(MultivaluedMap.class);
- when(responseHeaders.entrySet()).thenReturn(responseHeaderMap.entrySet());
-
- // Mock the response object
-
- ClientResponse response = mock(ClientResponse.class);
- when(response.getStatus()).thenReturn(200);
- when(response.getHeaders()).thenReturn(responseHeaders);
- when(response.getEntityInputStream()).thenReturn(
- new ByteArrayInputStream(responseContent.getBytes("UTF-8")));
-
- // Mock a handler that returns the response object and set
- // it to be the next filter after the logging filter.
-
- ClientFilter handler = mock(ClientFilter.class);
- when(handler.handle(request)).then(produceResponse(response));
- Method setNext = ClientFilter.class.getDeclaredMethod("setNext", new Class<?>[]{ClientHandler.class});
- setNext.setAccessible(true);
- setNext.invoke(loggingFilter, new Object[]{handler});
-
- // Run the request into the logging filter
-
- loggingFilter.handle(request);
-
- // Validate resulting the log content
-
- String log = logFormatter.getLog();
-
- assertContains(log, "* Client out-bound request");
- assertContains(log, "> " + httpMethod + " " + url);
-
- for (String header : requestHeaderMap.keySet()) {
- assertContains(log, "> " + header + ": ");
- }
-
- if (requestContent != null) {
- assertContains(log, requestContent);
- }
-
- assertContains(log, "* Client in-bound response");
- assertContains(log, "< 200");
-
- for (String header : responseHeaderMap.keySet()) {
- assertContains(log, "< " + header + ": ");
- }
-
- assertContains(log, responseContent);
- }
-
- private void assertContains(String log, String expect) {
- assertTrue("Log does not contain '" + expect + "'", log.contains(expect));
- }
-
- private class DefaultClientRequestAdapter implements ClientRequestAdapter {
- @Override
- public OutputStream adapt(ClientRequest request, OutputStream out) throws IOException {
- return out;
- }
- }
-
- private abstract class TestClientRequest extends ClientRequest {
- private ClientRequestAdapter adapter;
-
- @Override
- public ClientRequestAdapter getAdapter() {
- return adapter;
- }
-
- @Override
- public void setAdapter(ClientRequestAdapter adapter) {
- this.adapter = adapter;
- }
- }
-
- private Answer<ClientResponse> produceResponse(final ClientResponse response) {
- return new Answer<ClientResponse>() {
- public ClientResponse answer(InvocationOnMock invocation) throws IOException {
- ClientRequest request = (ClientRequest) invocation.getArguments()[0];
- byte[] entity = (byte[]) request.getEntity();
-
- if (entity != null) {
- ClientRequestAdapter adapter = request.getAdapter();
-
- OutputStream nullOutputStream = new OutputStream() {
- @Override
- public void write(int b) {
- // Discard
- }
- };
-
- OutputStream outputStream = adapter.adapt(request, nullOutputStream);
- outputStream.write(entity);
- outputStream.close();
- }
-
- return response;
- }
- };
- }
-
- private static class LogFormatter extends SimpleFormatter {
- StringBuilder buffer = new StringBuilder();
-
- public synchronized String getLog() {
- return buffer.toString();
- }
-
- public synchronized void clearLog() {
- buffer.setLength(0);
- }
-
- @Override
- public synchronized String format(LogRecord record) {
- String logData = super.format(record);
- buffer.append(logData);
- return logData;
- }
- }
-} \ No newline at end of file