Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 2010-2011 Oracle and/or its affiliates. All rights reserved.
   *
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common Development
   * and Distribution License("CDDL") (collectively, the "License").  You
   * may not use this file except in compliance with the License.  You can
  * obtain a copy of the License at
  * http://glassfish.java.net/public/CDDL+GPL_1_1.html
  * or packager/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  *
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at packager/legal/LICENSE.txt.
  *
  * GPL Classpath Exception:
  * Oracle designates this particular file as subject to the "Classpath"
  * exception as provided by Oracle in the GPL Version 2 section of the License
  * file that accompanied this code.
  *
  * Modifications:
  * If applicable, add the following below the License Header, with the fields
  * enclosed by brackets [] replaced by your own identifying information:
  * "Portions Copyright [year] [name of copyright owner]"
  *
  * Contributor(s):
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
  */
 package com.sun.jersey.api.container.filter;
 
 import java.util.List;
 import java.util.Map;
A logging filter.

The request headers, request entity, response headers and response entity will be logged. By default logging will be output to System.out.

When an application is deployed as a Servlet or Filter this Jersey filter can be registered using the following initialization parameters:

     <init-param>
         <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
         <param-value>com.sun.jersey.api.container.filter.LoggingFilter</param-value>
     </init-param&gt
     <init-param&gt
         <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
         <param-value>com.sun.jersey.api.container.filter.LoggingFilter</param-value>
     </init-param>
 

The logging of entities may be disabled by setting the feature FEATURE_LOGGING_DISABLE_ENTITY to true. When an application is deployed as a Servlet or Filter this feature can be registered using the following initialization parameter:

     <init-param>
         <param-name>com.sun.jersey.config.feature.logging.DisableEntitylogging</param-name>
         <param-value>true</param-value>
     </init-param&gt
 

Author(s):
Paul.Sandoz@Sun.Com
See also:
com.sun.jersey.api.container.filter
 
 public class LoggingFilter implements ContainerRequestFilterContainerResponseFilter {
    
If true the request and response entities (if present) will not be logged. If false the request and response entities will be logged.

The default value is false.

    public static final String FEATURE_LOGGING_DISABLE_ENTITY
            = "com.sun.jersey.config.feature.logging.DisableEntitylogging";
    private static final Logger LOGGER = Logger.getLogger(LoggingFilter.class.getName());
    private static final String NOTIFICATION_PREFIX = "* ";
    
    private static final String REQUEST_PREFIX = "> ";
    
    private static final String RESPONSE_PREFIX = "< ";
    private final Logger logger;
    private @Context HttpContext hc;
    
    private @Context ResourceConfig rc;
    private long id = 0;

    
Create a logging filter logging the request and response to a default JDK logger, named as the fully qualified class name of this class.
    public LoggingFilter() {
        this();
    }

    
Create a logging filter logging the request and response to a JDK logger.

Parameters:
logger the logger to log requests and responses.
    public LoggingFilter(Logger logger) {
        this. = logger;
    }
    private synchronized void setId() {
        if ( .getProperties().get("request-id") == null) {
            .getProperties().put("request-id", Long.toString(++));
        }
    }
    private StringBuilder prefixId(StringBuilder b) {
        b.append(.getProperties().get("request-id").toString()).
                append(" ");
        return b;
    }
    
    public ContainerRequest filter(ContainerRequest request) {
        setId();
        final StringBuilder b = new StringBuilder();
        printRequestLine(brequest);
        printRequestHeaders(brequest.getRequestHeaders());
            .info(b.toString());
            return request;
        } else {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream in = request.getEntityInputStream();
            try {
                if(in.available() > 0) {
                    ReaderWriter.writeTo(inout);
                    byte[] requestEntity = out.toByteArray();
                    printEntity(brequestEntity);
                    request.setEntityInputStream(new ByteArrayInputStream(requestEntity));
                }
                return request;
            } catch (IOException ex) {
                throw new ContainerException(ex);
            } finally {
                .info(b.toString());
            }
        }
    }
    
    private void printRequestLine(StringBuilder bContainerRequest request) {
        prefixId(b).append().append("Server in-bound request").append('\n');
        prefixId(b).append().append(request.getMethod()).append(" ").
                append(request.getRequestUri().toASCIIString()).append('\n');
    }
    
    private void printRequestHeaders(StringBuilder bMultivaluedMap<StringStringheaders) {
        for (Map.Entry<StringList<String>> e : headers.entrySet()) {
            String header = e.getKey();
            for (String value : e.getValue()) {
                prefixId(b).append().append(header).append(": ").
                        append(value).append('\n');
            }
        }
        prefixId(b).append().append('\n');
    }
    private void printEntity(StringBuilder bbyte[] entitythrows IOException {
        if (entity.length == 0)
            return;
        b.append(new String(entity)).append("\n");
    }
    private final class Adapter implements ContainerResponseWriter {
        private final ContainerResponseWriter crw;
        private final boolean disableEntity;
        private long contentLength;
        private ContainerResponse response;
        private ByteArrayOutputStream baos;
        private StringBuilder b = new StringBuilder();
        Adapter(ContainerResponseWriter crw) {
            this. = crw;
        }
        
        public OutputStream writeStatusAndHeaders(long contentLengthContainerResponse responsethrows IOException {
            printResponseLine(response);
            printResponseHeaders(response.getHttpHeaders());
            if () {
                .info(.toString());
                return .writeStatusAndHeaders(contentLengthresponse);
            } else {
                this. = contentLength;
                this. = response;
                return this. = new ByteArrayOutputStream();
            }
        }
        public void finish() throws IOException {
            if (!) {
                byte[] entity = .toByteArray();
                printEntity(entity);
                // Output to log
                .info(.toString());
                // Write out the headers and buffered entity
                OutputStream out = .writeStatusAndHeaders();
                out.write(entity);
            }
            .finish();
        }
    }
    public ContainerResponse filter(ContainerRequest requestContainerResponse response) {
        setId();
        response.setContainerResponseWriter(
                new Adapter(response.getContainerResponseWriter()));
        return response;
    }
    
    private void printResponseLine(StringBuilder bContainerResponse response) {
            append("Server out-bound response").append('\n');
        prefixId(b).append().append(Integer.toString(response.getStatus())).append('\n');
    }
    
    private void printResponseHeaders(StringBuilder bMultivaluedMap<StringObjectheaders) {
        for (Map.Entry<StringList<Object>> e : headers.entrySet()) {
            String header = e.getKey();
            for (Object value : e.getValue()) {
                prefixId(b).append().append(header).append(": ").
                        append(ContainerResponse.getHeaderValue(value)).append('\n');
            }
        }
        prefixId(b).append().append('\n');
    } 
New to GrepCode? Check out our FAQ X