summaryrefslogtreecommitdiffstats
path: root/openstack-client-connectors/jersey-connector
diff options
context:
space:
mode:
authorseshukm <seshu.kumar.m@huawei.com>2018-07-25 19:32:59 +0800
committerseshukm <seshu.kumar.m@huawei.com>2018-07-25 19:32:59 +0800
commit9d07a8f00e984dd8d90356201e333cf3c808c7a3 (patch)
tree5f5ce4b06b90d5dc74826d4d36f9d16330e97a05 /openstack-client-connectors/jersey-connector
parent8a57851000af82011c19d8e55787cdae3623c65b (diff)
basic code refactoring client connector
Issue-ID: SO-729 Change-Id: If7331155e44582fcfeb1f7473ee42b1d8d55238a Signed-off-by: seshukm <seshu.kumar.m@huawei.com>
Diffstat (limited to 'openstack-client-connectors/jersey-connector')
-rw-r--r--openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyConnector.java132
-rw-r--r--openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyLoggingFilter.java362
-rw-r--r--openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyResponse.java86
-rw-r--r--openstack-client-connectors/jersey-connector/src/test/java/com/woorea/openstack/connector/JerseyLoggingFilterTest.java416
4 files changed, 498 insertions, 498 deletions
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
index eb1b3d5..ea22970 100644
--- 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
@@ -45,76 +45,76 @@ import com.woorea.openstack.base.client.OpenStackResponse;
import com.woorea.openstack.base.client.OpenStackResponseException;
public class JerseyConnector implements OpenStackClientConnector {
-
- protected Client client = null;
+
+ 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);
- }
+ 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());
- }
- }
+ @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(Inclusion.NON_NULL);
- DEFAULT_MAPPER.enable(SerializationConfig.Feature.INDENT_OUTPUT);
- DEFAULT_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
- DEFAULT_MAPPER.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
- DEFAULT_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
+ @Provider
+ public static class OpenStackObjectMapper implements ContextResolver<ObjectMapper> {
+ static ObjectMapper DEFAULT_MAPPER;
+ static ObjectMapper WRAPPED_MAPPER;
+ static {
+ DEFAULT_MAPPER = new ObjectMapper();
+ DEFAULT_MAPPER.setSerializationInclusion(Inclusion.NON_NULL);
+ DEFAULT_MAPPER.enable(SerializationConfig.Feature.INDENT_OUTPUT);
+ DEFAULT_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+ DEFAULT_MAPPER.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
+ DEFAULT_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
- WRAPPED_MAPPER = new ObjectMapper();
- WRAPPED_MAPPER.setSerializationInclusion(Inclusion.NON_NULL);
- WRAPPED_MAPPER.enable(SerializationConfig.Feature.INDENT_OUTPUT);
- WRAPPED_MAPPER.enable(SerializationConfig.Feature.WRAP_ROOT_VALUE);
- WRAPPED_MAPPER.enable(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE);
- WRAPPED_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
- WRAPPED_MAPPER.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
- WRAPPED_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
- }
-
- @Override
- public ObjectMapper getContext(Class<?> type) {
- return type.getAnnotation(JsonRootName.class) == null ? DEFAULT_MAPPER : WRAPPED_MAPPER;
- }
- }
+ WRAPPED_MAPPER = new ObjectMapper();
+ WRAPPED_MAPPER.setSerializationInclusion(Inclusion.NON_NULL);
+ WRAPPED_MAPPER.enable(SerializationConfig.Feature.INDENT_OUTPUT);
+ WRAPPED_MAPPER.enable(SerializationConfig.Feature.WRAP_ROOT_VALUE);
+ WRAPPED_MAPPER.enable(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE);
+ WRAPPED_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+ WRAPPED_MAPPER.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
+ WRAPPED_MAPPER.enable(DeserializationConfig.Feature.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
index 6d98005..ffdeb83 100644
--- 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
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -42,184 +42,184 @@ import com.sun.jersey.core.util.ReaderWriter;
*/
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();
- }
- }
+ 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
index b6ccd04..5b01660 100644
--- 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
@@ -30,53 +30,53 @@ import com.woorea.openstack.base.client.OpenStackResponseException;
public class JerseyResponse implements OpenStackResponse {
- private ClientResponse response;
+ private ClientResponse response;
- public JerseyResponse(ClientResponse response) {
- this.response = 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 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 <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 InputStream getInputStream() {
+ if(response.hasEntity()) {
+ return response.getEntityInputStream();
+ } else {
+ return null;
+ }
+ }
- @Override
- public String header(String name) {
- return response.getHeaders().getFirst(name);
- }
+ @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;
- }
+ @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/test/java/com/woorea/openstack/connector/JerseyLoggingFilterTest.java b/openstack-client-connectors/jersey-connector/src/test/java/com/woorea/openstack/connector/JerseyLoggingFilterTest.java
index 3bd0717..3ebad7c 100644
--- 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
@@ -56,212 +56,212 @@ 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;
- }
- }
+ 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