ConsoleDebugger.java

  1. /**
  2.  *
  3.  * Copyright the original author or authors
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.jivesoftware.smack.debugger;

  18. import java.text.SimpleDateFormat;
  19. import java.util.Date;

  20. import org.jivesoftware.smack.XMPPConnection;
  21. import org.jivesoftware.smack.util.ExceptionUtil;

  22. /**
  23.  * Very simple debugger that prints to the console (stdout) the sent and received stanzas. Use
  24.  * this debugger with caution since printing to the console is an expensive operation that may
  25.  * even block the thread since only one thread may print at a time.
  26.  * <p>
  27.  * It is possible to not only print the raw sent and received stanzas but also the interpreted
  28.  * packets by Smack. By default,interpreted packets won't be printed. To enable this feature
  29.  * just change the <code>printInterpreted</code> static variable to <code>true</code>.
  30.  * </p>
  31.  *
  32.  * @author Gaston Dombiak
  33.  */
  34. public class ConsoleDebugger extends AbstractDebugger {
  35.     private final SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss.S");

  36.     public ConsoleDebugger(XMPPConnection connection) {
  37.         super(connection);
  38.     }

  39.     @Override
  40.     protected void log(String logMessage) {
  41.         String formatedDate;
  42.         synchronized (dateFormatter) {
  43.             formatedDate = dateFormatter.format(new Date());
  44.         }
  45.         // CHECKSTYLE:OFF
  46.         System.out.println(formatedDate + ' ' + logMessage);
  47.         // CHECKSTYLE:ON
  48.     }

  49.     @Override
  50.     protected void log(String logMessage, Throwable throwable) {
  51.         String stacktrace = ExceptionUtil.getStackTrace(throwable);
  52.         log(logMessage + '\n' + stacktrace);
  53.     }

  54.     public static final class Factory implements SmackDebuggerFactory {

  55.         public static final SmackDebuggerFactory INSTANCE = new Factory();

  56.         private Factory() {
  57.         }

  58.         @Override
  59.         public SmackDebugger create(XMPPConnection connection) throws IllegalArgumentException {
  60.             return new ConsoleDebugger(connection);
  61.         }

  62.     }
  63. }