001/**
002 *
003 * Copyright the original author or authors
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smack.debugger;
018
019import java.io.PrintWriter;
020import java.io.Reader;
021import java.io.StringWriter;
022import java.io.Writer;
023import java.text.SimpleDateFormat;
024import java.util.Date;
025
026import org.jivesoftware.smack.XMPPConnection;
027
028/**
029 * Very simple debugger that prints to the console (stdout) the sent and received stanzas. Use
030 * this debugger with caution since printing to the console is an expensive operation that may
031 * even block the thread since only one thread may print at a time.
032 * <p>
033 * It is possible to not only print the raw sent and received stanzas but also the interpreted
034 * packets by Smack. By default interpreted packets won't be printed. To enable this feature
035 * just change the <tt>printInterpreted</tt> static variable to <tt>true</tt>.
036 * </p>
037 *
038 * @author Gaston Dombiak
039 */
040public class ConsoleDebugger extends AbstractDebugger {
041    private final SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss");
042
043    public ConsoleDebugger(XMPPConnection connection, Writer writer, Reader reader) {
044        super(connection, writer, reader);
045    }
046
047    @Override
048    protected void log(String logMessage) {
049        String formatedDate;
050        synchronized (dateFormatter) {
051            formatedDate = dateFormatter.format(new Date());
052        }
053        // CHECKSTYLE:OFF
054        System.out.println(formatedDate + ' ' + logMessage);
055        // CHECKSTYLE:ON
056    }
057
058    @Override
059    protected void log(String logMessage, Throwable throwable) {
060        StringWriter sw = new StringWriter();
061        PrintWriter pw = new PrintWriter(sw);
062        // CHECKSTYLE:OFF
063        throwable.printStackTrace(pw);
064        // CHECKSTYLE:ON
065        log(logMessage + sw);
066    }
067
068}