/* 
 * Copyright 2014 Guillaume Masclet <guillaume.masclet@yahoo.fr>.
 *
 * 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.
 */
package org.elasticlib.common.client;

import com.google.common.base.Joiner;
import static java.lang.System.lineSeparator;
import java.util.List;
import java.util.Map.Entry;
import javax.annotation.Priority;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.MultivaluedMap;
import org.glassfish.jersey.internal.util.collection.StringIgnoreCaseKeyComparator;

/**
 * A filter that logs HTTP requests and reponses.
 */
@PreMatching
@Priority(Integer.MIN_VALUE)
public class ClientLoggingFilter implements ClientRequestFilter, ClientResponseFilter {

    private static final String SPACE = " ";
    private static final String DASH = " - ";
    private static final String REQUEST_PREFIX = "> ";
    private static final String RESPONSE_PREFIX = "< ";

    private final LoggingHandler handler;

    /**
     * Constructor.
     *
     * @param handler Logging adapter.
     */
    ClientLoggingFilter(LoggingHandler handler) {
        this.handler = handler;
    }

    @Override
    public void filter(ClientRequestContext context) {
        StringBuilder builder = new StringBuilder()
                .append(REQUEST_PREFIX)
                .append(context.getMethod())
                .append(SPACE)
                .append(context.getUri().toASCIIString())
                .append(lineSeparator());

        printPrefixedHeaders(builder, REQUEST_PREFIX, context.getStringHeaders());

        handler.logRequest(builder.toString());
    }

    @Override
    public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) {
        StringBuilder builder = new StringBuilder()
                .append(RESPONSE_PREFIX)
                .append(responseContext.getStatus())
                .append(DASH)
                .append(responseContext.getStatusInfo().getReasonPhrase())
                .append(lineSeparator());

        printPrefixedHeaders(builder, RESPONSE_PREFIX, responseContext.getHeaders());

        handler.logResponse(builder.toString());
    }

    private void printPrefixedHeaders(StringBuilder builder, String prefix, MultivaluedMap<String, String> headers) {
        headers.entrySet()
                .stream()
                .sorted((o1, o2) -> StringIgnoreCaseKeyComparator.SINGLETON.compare(o1.getKey(), o2.getKey()))
                .forEach(header -> {
                    builder.append(prefix)
                    .append(header.getKey())
                    .append(": ")
                    .append(value(header))
                    .append(lineSeparator());
                });
    }

    private static String value(Entry<String, List<String>> header) {
        if (header.getValue().size() == 1) {
            return header.getValue().get(0);
        }
        return Joiner.on(',').join(header.getValue());
    }
}

@@ -1,11 +1,10 @@
 /*
- 
 %0A * Copy
@@ -675,37 +675,36 @@
 ort 
-com.google.common.base.J
+static java.lang.String.j
 oin
-er
 ;%0Aim
@@ -768,40 +768,36 @@
 til.
-List;%0Aimport java.util.Map.Entry
+concurrent.atomic.AtomicLong
 ;%0Aim
@@ -1463,24 +1463,115 @@
 SH = %22 - %22;%0A
+    private static final String COLON = %22: %22;%0A    private static final String COMMA = %22,%22;%0A
     private 
@@ -1668,16 +1668,166 @@
  = %22%3C %22;
+%0A    private static final String ID_PROPERTY = ClientLoggingFilter.class.getName() + %22.id%22;%0A    private static final AtomicLong ID = new AtomicLong();
 %0A%0A    pr
@@ -2095,32 +2095,133 @@
 text context) %7B%0A
+        long currentId = ID.incrementAndGet();%0A        context.setProperty(ID_PROPERTY, currentId);%0A%0A
         StringBu
@@ -2228,32 +2228,39 @@
 ilder builder = 
+prefix(
 new StringBuilde
@@ -2266,33 +2266,21 @@
 er()
-%0A                .append(
+, currentId, 
 REQU
@@ -2505,16 +2505,27 @@
 builder,
+ currentId,
  REQUEST
@@ -2725,32 +2725,106 @@
 ponseContext) %7B%0A
+        long currentId = (long) requestContext.getProperty(ID_PROPERTY);%0A%0A
         StringBu
@@ -2839,16 +2839,23 @@
 ilder = 
+prefix(
 new Stri
@@ -2869,33 +2869,21 @@
 er()
-%0A                .append(
+, currentId, 
 RESP
@@ -3133,16 +3133,27 @@
 builder,
+ currentId,
  RESPONS
@@ -3262,16 +3262,23 @@
 private 
+static 
 void pri
@@ -3321,23 +3321,167 @@
 der,
- String prefix,
+%0A                                             long id,%0A                                             String prefix,%0A                                            
  Mul
@@ -3601,14 +3601,12 @@
 ed((
-o1, o2
+x, y
 ) -%3E
@@ -3658,10 +3658,9 @@
 are(
-o1
+x
 .get
@@ -3670,10 +3670,9 @@
 (), 
-o2
+y
 .get
@@ -3740,23 +3740,28 @@
     
-builder.append(
+prefix(builder, id, 
 pref
@@ -3837,20 +3837,21 @@
 .append(
-%22: %22
+COLON
 )%0A      
@@ -3876,20 +3876,37 @@
 end(
-value(header
+join(COMMA, header.getValue()
 ))%0A 
@@ -4006,142 +4006,151 @@
 ring
- value(Entry%3CString, List%3CString%3E%3E header) %7B%0A        if (header.getValue().size() == 1) %7B%0A            return header.getValue().get(0);
+Builder prefix(StringBuilder builder, long id, String prefix) %7B%0A        return builder.append(Long.toString(id))%0A                .append(SPACE)
 %0A   
@@ -4158,18 +4158,16 @@
     
-%7D%0A
         
 retu
@@ -4166,52 +4166,22 @@
     
-return Joiner.on(',').join(header.getValue()
+.append(prefix
 );%0A 

Add identifiers to logged requests and responses