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.text.SimpleDateFormat;
020import java.util.Date;
021
022import org.jivesoftware.smack.XMPPConnection;
023import org.jivesoftware.smack.util.ExceptionUtil;
024
025/**
026 * Very simple debugger that prints to the console (stdout) the sent and received stanzas. Use
027 * this debugger with caution since printing to the console is an expensive operation that may
028 * even block the thread since only one thread may print at a time.
029 * <p>
030 * It is possible to not only print the raw sent and received stanzas but also the interpreted
031 * packets by Smack. By default,interpreted packets won't be printed. To enable this feature
032 * just change the <code>printInterpreted</code> static variable to <code>true</code>.
033 * </p>
034 *
035 * @author Gaston Dombiak
036 */
037public class ConsoleDebugger extends AbstractDebugger {
038    private final SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss.S");
039
040    public ConsoleDebugger(XMPPConnection connection) {
041        super(connection);
042    }
043
044    @SuppressWarnings("JavaUtilDate")
045    @Override
046    protected void log(String logMessage) {
047        String formatedDate;
048        synchronized (dateFormatter) {
049            formatedDate = dateFormatter.format(new Date());
050        }
051        // CHECKSTYLE:OFF
052        System.out.println(formatedDate + ' ' + logMessage);
053        // CHECKSTYLE:ON
054    }
055
056    @Override
057    protected void log(String logMessage, Throwable throwable) {
058        String stacktrace = ExceptionUtil.getStackTrace(throwable);
059        log(logMessage + '\n' + stacktrace);
060    }
061
062    public static final class Factory implements SmackDebuggerFactory {
063
064        public static final SmackDebuggerFactory INSTANCE = new Factory();
065
066        private Factory() {
067        }
068
069        @Override
070        public SmackDebugger create(XMPPConnection connection) throws IllegalArgumentException {
071            return new ConsoleDebugger(connection);
072        }
073
074    }
075}