2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4 * Copyright (c) 2011-2015 Oracle and/or its affiliates. All rights reserved.
6 * The contents of this file are subject to the terms of either the GNU
7 * General Public License Version 2 only ("GPL") or the Common Development
8 * and Distribution License("CDDL") (collectively, the "License"). You
9 * may not use this file except in compliance with the License. You can
10 * obtain a copy of the License at
11 * http://glassfish.java.net/public/CDDL+GPL_1_1.html
12 * or packager/legal/LICENSE.txt. See the License for the specific
13 * language governing permissions and limitations under the License.
15 * When distributing the software, include this License Header Notice in each
16 * file and include the License file at packager/legal/LICENSE.txt.
18 * GPL Classpath Exception:
19 * Oracle designates this particular file as subject to the "Classpath"
20 * exception as provided by Oracle in the GPL Version 2 section of the License
21 * file that accompanied this code.
24 * If applicable, add the following below the License Header, with the fields
25 * enclosed by brackets [] replaced by your own identifying information:
26 * "Portions Copyright [year] [name of copyright owner]"
29 * If you wish your version of this file to be governed by only the CDDL or
30 * only the GPL Version 2, indicate your decision by adding "[Contributor]
31 * elects to include this software in this distribution under the [CDDL or GPL
32 * Version 2] license." If you don't indicate a single choice of license, a
33 * recipient has the option to distribute your version of this file under
34 * either the CDDL, the GPL Version 2 or to extend the choice of license to
35 * its licensees as provided above. However, if you add GPL Version 2 code
36 * and therefore, elected the GPL Version 2 license, then the option applies
37 * only if the new code is made subject to such option by the copyright
40 package org.openhab.binding.lametrictime.api.filter;
42 import java.io.BufferedInputStream;
43 import java.io.ByteArrayOutputStream;
44 import java.io.FilterOutputStream;
45 import java.io.IOException;
46 import java.io.InputStream;
47 import java.io.OutputStream;
49 import java.nio.charset.Charset;
50 import java.util.Comparator;
51 import java.util.List;
54 import java.util.TreeSet;
55 import java.util.concurrent.atomic.AtomicLong;
56 import java.util.logging.Logger;
58 import javax.annotation.Priority;
59 import javax.ws.rs.WebApplicationException;
60 import javax.ws.rs.client.ClientRequestContext;
61 import javax.ws.rs.client.ClientRequestFilter;
62 import javax.ws.rs.client.ClientResponseContext;
63 import javax.ws.rs.client.ClientResponseFilter;
64 import javax.ws.rs.container.ContainerRequestContext;
65 import javax.ws.rs.container.ContainerRequestFilter;
66 import javax.ws.rs.container.ContainerResponseContext;
67 import javax.ws.rs.container.ContainerResponseFilter;
68 import javax.ws.rs.container.PreMatching;
69 import javax.ws.rs.core.MediaType;
70 import javax.ws.rs.core.MultivaluedMap;
71 import javax.ws.rs.ext.WriterInterceptor;
72 import javax.ws.rs.ext.WriterInterceptorContext;
75 * Universal logging filter.
77 * Can be used on client or server side. Has the highest priority.
79 * @author Pavel Bucek (pavel.bucek at oracle.com)
80 * @author Martin Matula
83 @Priority(Integer.MIN_VALUE)
84 public final class LoggingFilter implements ContainerRequestFilter, ClientRequestFilter, ContainerResponseFilter,
85 ClientResponseFilter, WriterInterceptor {
87 public static final Charset UTF8 = Charset.forName("UTF-8");
89 private static final Logger LOGGER = Logger.getLogger(LoggingFilter.class.getName());
90 private static final String NOTIFICATION_PREFIX = "* ";
91 private static final String REQUEST_PREFIX = "> ";
92 private static final String RESPONSE_PREFIX = "< ";
93 private static final String ENTITY_LOGGER_PROPERTY = LoggingFilter.class.getName() + ".entityLogger";
94 private static final String LOGGING_ID_PROPERTY = LoggingFilter.class.getName() + ".id";
96 private static final Comparator<Map.Entry<String, List<String>>> COMPARATOR = new Comparator<Map.Entry<String, List<String>>>() {
99 public int compare(final Map.Entry<String, List<String>> o1, final Map.Entry<String, List<String>> o2) {
100 return o1.getKey().compareToIgnoreCase(o2.getKey());
104 private static final int DEFAULT_MAX_ENTITY_SIZE = 8 * 1024;
107 private final Logger logger;
108 private final AtomicLong _id = new AtomicLong(0);
109 private final boolean printEntity;
110 private final int maxEntitySize;
113 * Create a logging filter logging the request and response to a default JDK
114 * logger, named as the fully qualified class name of this class. Entity
115 * logging is turned off by default.
117 public LoggingFilter() {
122 * Create a logging filter with custom logger and custom settings of entity
125 * @param logger the logger to log requests and responses.
126 * @param printEntity if true, entity will be logged as well up to the default maxEntitySize, which is 8KB
128 public LoggingFilter(final Logger logger, final boolean printEntity) {
129 this.logger = logger;
130 this.printEntity = printEntity;
131 this.maxEntitySize = DEFAULT_MAX_ENTITY_SIZE;
135 * Creates a logging filter with custom logger and entity logging turned on, but potentially limiting the size
136 * of entity to be buffered and logged.
138 * @param logger the logger to log requests and responses.
139 * @param maxEntitySize maximum number of entity bytes to be logged (and buffered) - if the entity is larger,
140 * logging filter will print (and buffer in memory) only the specified number of bytes
141 * and print "...more..." string at the end. Negative values are interpreted as zero.
143 public LoggingFilter(final Logger logger, final int maxEntitySize) {
144 this.logger = logger;
145 this.printEntity = true;
146 this.maxEntitySize = Math.max(0, maxEntitySize);
149 private void log(final StringBuilder b) {
150 if (logger != null) {
151 logger.info(b.toString());
155 private StringBuilder prefixId(final StringBuilder b, final long id) {
156 b.append(Long.toString(id)).append(" ");
160 private void printRequestLine(final StringBuilder b, final String note, final long id, final String method,
162 prefixId(b, id).append(NOTIFICATION_PREFIX).append(note).append(" on thread ")
163 .append(Thread.currentThread().getName()).append("\n");
164 prefixId(b, id).append(REQUEST_PREFIX).append(method).append(" ").append(uri.toASCIIString()).append("\n");
167 private void printResponseLine(final StringBuilder b, final String note, final long id, final int status) {
168 prefixId(b, id).append(NOTIFICATION_PREFIX).append(note).append(" on thread ")
169 .append(Thread.currentThread().getName()).append("\n");
170 prefixId(b, id).append(RESPONSE_PREFIX).append(Integer.toString(status)).append("\n");
173 private void printPrefixedHeaders(final StringBuilder b, final long id, final String prefix,
174 final MultivaluedMap<String, String> headers) {
175 for (final Map.Entry<String, List<String>> headerEntry : getSortedHeaders(headers.entrySet())) {
176 final List<?> val = headerEntry.getValue();
177 final String header = headerEntry.getKey();
179 if (val.size() == 1) {
180 prefixId(b, id).append(prefix).append(header).append(": ").append(val.get(0)).append("\n");
182 final StringBuilder sb = new StringBuilder();
184 for (final Object s : val) {
191 prefixId(b, id).append(prefix).append(header).append(": ").append(sb.toString()).append("\n");
196 private Set<Map.Entry<String, List<String>>> getSortedHeaders(final Set<Map.Entry<String, List<String>>> headers) {
197 final TreeSet<Map.Entry<String, List<String>>> sortedHeaders = new TreeSet<Map.Entry<String, List<String>>>(
199 sortedHeaders.addAll(headers);
200 return sortedHeaders;
203 private InputStream logInboundEntity(final StringBuilder b, InputStream stream, final Charset charset)
205 if (!stream.markSupported()) {
206 stream = new BufferedInputStream(stream);
208 stream.mark(maxEntitySize + 1);
209 final byte[] entity = new byte[maxEntitySize + 1];
210 final int entitySize = stream.read(entity);
211 b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize), charset));
212 if (entitySize > maxEntitySize) {
213 b.append("...more...");
221 public void filter(final ClientRequestContext context) throws IOException {
222 final long id = _id.incrementAndGet();
223 context.setProperty(LOGGING_ID_PROPERTY, id);
225 final StringBuilder b = new StringBuilder();
227 printRequestLine(b, "Sending client request", id, context.getMethod(), context.getUri());
228 printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getStringHeaders());
230 if (printEntity && context.hasEntity()) {
231 final OutputStream stream = new LoggingStream(b, context.getEntityStream());
232 context.setEntityStream(stream);
233 context.setProperty(ENTITY_LOGGER_PROPERTY, stream);
234 // not calling log(b) here - it will be called by the interceptor
241 public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext)
243 final Object requestId = requestContext.getProperty(LOGGING_ID_PROPERTY);
244 final long id = requestId != null ? (Long) requestId : _id.incrementAndGet();
246 final StringBuilder b = new StringBuilder();
248 printResponseLine(b, "Client response received", id, responseContext.getStatus());
249 printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getHeaders());
251 if (printEntity && responseContext.hasEntity()) {
252 responseContext.setEntityStream(
253 logInboundEntity(b, responseContext.getEntityStream(), getCharset(responseContext.getMediaType())));
260 public void filter(final ContainerRequestContext context) throws IOException {
261 final long id = _id.incrementAndGet();
262 context.setProperty(LOGGING_ID_PROPERTY, id);
264 final StringBuilder b = new StringBuilder();
266 printRequestLine(b, "Server has received a request", id, context.getMethod(),
267 context.getUriInfo().getRequestUri());
268 printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getHeaders());
270 if (printEntity && context.hasEntity()) {
271 context.setEntityStream(logInboundEntity(b, context.getEntityStream(), getCharset(context.getMediaType())));
278 public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
280 final Object requestId = requestContext.getProperty(LOGGING_ID_PROPERTY);
281 final long id = requestId != null ? (Long) requestId : _id.incrementAndGet();
283 final StringBuilder b = new StringBuilder();
285 printResponseLine(b, "Server responded with a response", id, responseContext.getStatus());
286 printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getStringHeaders());
288 if (printEntity && responseContext.hasEntity()) {
289 final OutputStream stream = new LoggingStream(b, responseContext.getEntityStream());
290 responseContext.setEntityStream(stream);
291 requestContext.setProperty(ENTITY_LOGGER_PROPERTY, stream);
292 // not calling log(b) here - it will be called by the interceptor
299 public void aroundWriteTo(final WriterInterceptorContext writerInterceptorContext)
300 throws IOException, WebApplicationException {
301 final LoggingStream stream = (LoggingStream) writerInterceptorContext.getProperty(ENTITY_LOGGER_PROPERTY);
302 writerInterceptorContext.proceed();
303 if (stream != null) {
304 log(stream.getStringBuilder(getCharset(writerInterceptorContext.getMediaType())));
308 private class LoggingStream extends FilterOutputStream {
310 private final StringBuilder b;
311 private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
313 LoggingStream(final StringBuilder b, final OutputStream inner) {
319 StringBuilder getStringBuilder(final Charset charset) {
320 // write entity to the builder
321 final byte[] entity = baos.toByteArray();
323 b.append(new String(entity, 0, Math.min(entity.length, maxEntitySize), charset));
324 if (entity.length > maxEntitySize) {
325 b.append("...more...");
333 public void write(final int i) throws IOException {
334 if (baos.size() <= maxEntitySize) {
342 * Get the character set from a media type.
344 * The character set is obtained from the media type parameter "charset".
345 * If the parameter is not present the {@link #UTF8} charset is utilized.
347 * @param m the media type.
348 * @return the character set.
350 public static Charset getCharset(MediaType m) {
351 String name = (m == null) ? null : m.getParameters().get(MediaType.CHARSET_PARAMETER);
352 return (name == null) ? UTF8 : Charset.forName(name);