]> git.basschouten.com Git - openhab-addons.git/blob
7b355cbd2f1d23fcd8256e1e308f5fac8b9f0933
[openhab-addons.git] /
1 /*
2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3  *
4  * Copyright (c) 2011-2015 Oracle and/or its affiliates. All rights reserved.
5  *
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.
14  *
15  * When distributing the software, include this License Header Notice in each
16  * file and include the License file at packager/legal/LICENSE.txt.
17  *
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.
22  *
23  * Modifications:
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]"
27  *
28  * Contributor(s):
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
38  * holder.
39  */
40 package org.openhab.binding.lametrictime.api.filter;
41
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;
48 import java.net.URI;
49 import java.nio.charset.Charset;
50 import java.util.Comparator;
51 import java.util.List;
52 import java.util.Map;
53 import java.util.Set;
54 import java.util.TreeSet;
55 import java.util.concurrent.atomic.AtomicLong;
56 import java.util.logging.Logger;
57
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;
73
74 /**
75  * Universal logging filter.
76  * <p/>
77  * Can be used on client or server side. Has the highest priority.
78  *
79  * @author Pavel Bucek (pavel.bucek at oracle.com)
80  * @author Martin Matula
81  */
82 @PreMatching
83 @Priority(Integer.MIN_VALUE)
84 public final class LoggingFilter implements ContainerRequestFilter, ClientRequestFilter, ContainerResponseFilter,
85         ClientResponseFilter, WriterInterceptor {
86
87     public static final Charset UTF8 = Charset.forName("UTF-8");
88
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";
95
96     private static final Comparator<Map.Entry<String, List<String>>> COMPARATOR = new Comparator<Map.Entry<String, List<String>>>() {
97
98         @Override
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());
101         }
102     };
103
104     private static final int DEFAULT_MAX_ENTITY_SIZE = 8 * 1024;
105
106     //
107     private final Logger logger;
108     private final AtomicLong _id = new AtomicLong(0);
109     private final boolean printEntity;
110     private final int maxEntitySize;
111
112     /**
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.
116      */
117     public LoggingFilter() {
118         this(LOGGER, false);
119     }
120
121     /**
122      * Create a logging filter with custom logger and custom settings of entity
123      * logging.
124      *
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
127      */
128     public LoggingFilter(final Logger logger, final boolean printEntity) {
129         this.logger = logger;
130         this.printEntity = printEntity;
131         this.maxEntitySize = DEFAULT_MAX_ENTITY_SIZE;
132     }
133
134     /**
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.
137      *
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.
142      */
143     public LoggingFilter(final Logger logger, final int maxEntitySize) {
144         this.logger = logger;
145         this.printEntity = true;
146         this.maxEntitySize = Math.max(0, maxEntitySize);
147     }
148
149     private void log(final StringBuilder b) {
150         if (logger != null) {
151             logger.info(b.toString());
152         }
153     }
154
155     private StringBuilder prefixId(final StringBuilder b, final long id) {
156         b.append(Long.toString(id)).append(" ");
157         return b;
158     }
159
160     private void printRequestLine(final StringBuilder b, final String note, final long id, final String method,
161             final URI uri) {
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");
165     }
166
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");
171     }
172
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();
178
179             if (val.size() == 1) {
180                 prefixId(b, id).append(prefix).append(header).append(": ").append(val.get(0)).append("\n");
181             } else {
182                 final StringBuilder sb = new StringBuilder();
183                 boolean add = false;
184                 for (final Object s : val) {
185                     if (add) {
186                         sb.append(',');
187                     }
188                     add = true;
189                     sb.append(s);
190                 }
191                 prefixId(b, id).append(prefix).append(header).append(": ").append(sb.toString()).append("\n");
192             }
193         }
194     }
195
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>>>(
198                 COMPARATOR);
199         sortedHeaders.addAll(headers);
200         return sortedHeaders;
201     }
202
203     private InputStream logInboundEntity(final StringBuilder b, InputStream stream, final Charset charset)
204             throws IOException {
205         if (!stream.markSupported()) {
206             stream = new BufferedInputStream(stream);
207         }
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...");
214         }
215         b.append('\n');
216         stream.reset();
217         return stream;
218     }
219
220     @Override
221     public void filter(final ClientRequestContext context) throws IOException {
222         final long id = _id.incrementAndGet();
223         context.setProperty(LOGGING_ID_PROPERTY, id);
224
225         final StringBuilder b = new StringBuilder();
226
227         printRequestLine(b, "Sending client request", id, context.getMethod(), context.getUri());
228         printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getStringHeaders());
229
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
235         } else {
236             log(b);
237         }
238     }
239
240     @Override
241     public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext)
242             throws IOException {
243         final Object requestId = requestContext.getProperty(LOGGING_ID_PROPERTY);
244         final long id = requestId != null ? (Long) requestId : _id.incrementAndGet();
245
246         final StringBuilder b = new StringBuilder();
247
248         printResponseLine(b, "Client response received", id, responseContext.getStatus());
249         printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getHeaders());
250
251         if (printEntity && responseContext.hasEntity()) {
252             responseContext.setEntityStream(
253                     logInboundEntity(b, responseContext.getEntityStream(), getCharset(responseContext.getMediaType())));
254         }
255
256         log(b);
257     }
258
259     @Override
260     public void filter(final ContainerRequestContext context) throws IOException {
261         final long id = _id.incrementAndGet();
262         context.setProperty(LOGGING_ID_PROPERTY, id);
263
264         final StringBuilder b = new StringBuilder();
265
266         printRequestLine(b, "Server has received a request", id, context.getMethod(),
267                 context.getUriInfo().getRequestUri());
268         printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getHeaders());
269
270         if (printEntity && context.hasEntity()) {
271             context.setEntityStream(logInboundEntity(b, context.getEntityStream(), getCharset(context.getMediaType())));
272         }
273
274         log(b);
275     }
276
277     @Override
278     public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
279             throws IOException {
280         final Object requestId = requestContext.getProperty(LOGGING_ID_PROPERTY);
281         final long id = requestId != null ? (Long) requestId : _id.incrementAndGet();
282
283         final StringBuilder b = new StringBuilder();
284
285         printResponseLine(b, "Server responded with a response", id, responseContext.getStatus());
286         printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getStringHeaders());
287
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
293         } else {
294             log(b);
295         }
296     }
297
298     @Override
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())));
305         }
306     }
307
308     private class LoggingStream extends FilterOutputStream {
309
310         private final StringBuilder b;
311         private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
312
313         LoggingStream(final StringBuilder b, final OutputStream inner) {
314             super(inner);
315
316             this.b = b;
317         }
318
319         StringBuilder getStringBuilder(final Charset charset) {
320             // write entity to the builder
321             final byte[] entity = baos.toByteArray();
322
323             b.append(new String(entity, 0, Math.min(entity.length, maxEntitySize), charset));
324             if (entity.length > maxEntitySize) {
325                 b.append("...more...");
326             }
327             b.append('\n');
328
329             return b;
330         }
331
332         @Override
333         public void write(final int i) throws IOException {
334             if (baos.size() <= maxEntitySize) {
335                 baos.write(i);
336             }
337             out.write(i);
338         }
339     }
340
341     /**
342      * Get the character set from a media type.
343      * <p>
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.
346      *
347      * @param m the media type.
348      * @return the character set.
349      */
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);
353     }
354
355 }