@Test
  public void testGetFilterChain() throws Exception {
    mockBundleWiring();

    CaptureHandler captureHandler =
        JDKLoggerTestUtil.configureJDKLogger(MockLoggingFilter.class.getName(), Level.INFO);

    try {
      List<LogRecord> logRecords = captureHandler.getLogRecords();

      String cssFilterName = "CSS Filter";

      registerFilter(cssFilterName, new MockLoggingFilter(cssFilterName), null, "/css/*");

      String jsFilterName = "JS Filter";

      registerFilter(jsFilterName, new MockLoggingFilter(jsFilterName), null, "/js/*");

      FilterChain filterChain = _bundleServletContext.getFilterChain("/js/main.js");

      Assert.assertNotNull(filterChain);

      filterChain.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse());

      Assert.assertEquals(1, logRecords.size());

      LogRecord logRecord = logRecords.get(0);

      Assert.assertEquals(jsFilterName, logRecord.getMessage());

      verifyBundleWiring();
    } finally {
      captureHandler.close();
    }
  }
Пример #2
0
 @Override
 @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
 public synchronized String format(final LogRecord record) {
   dat.setTime(record.getMillis());
   String source;
   if (record.getSourceClassName() != null) {
     source = record.getSourceClassName();
     if (record.getSourceMethodName() != null) {
       source += "#" + record.getSourceMethodName();
     }
   } else {
     source = record.getLoggerName();
   }
   String message = formatMessage(record);
   String throwable = "";
   if (record.getThrown() != null) {
     StringWriter sw = new StringWriter();
     PrintWriter pw = new PrintWriter(sw);
     pw.println();
     record.getThrown().printStackTrace(pw);
     pw.close();
     throwable = sw.toString();
   }
   return String.format(
       FORMAT,
       dat,
       source,
       record.getLoggerName(),
       record.getLevel().getLocalizedName(),
       message,
       throwable);
 }
  public void log(LogRecord record) {
    if (logToFile != null) {
      logToFile(record);
    }

    if (ignoreLogging) return;

    CapedwarfRequestLogs requestLogs = getCurrentRequestLogs();
    if (requestLogs != null) {
      CapedwarfAppLogLine capedwarfAppLogLine =
          new CapedwarfAppLogLine(getCurrentRequestId(), record.getSequenceNumber());
      AppLogLine appLogLine = capedwarfAppLogLine.getAppLogLine();
      appLogLine.setLogLevel(getLogLevel(record));
      appLogLine.setLogMessage(
          record.getSourceClassName()
              + " "
              + record.getSourceMethodName()
              + ": "
              + getFormattedMessage(record)
              + "\n");
      appLogLine.setTimeUsec(record.getMillis() * 1000);
      logWriter.put(capedwarfAppLogLine);

      requestLogs.logLineAdded(appLogLine);
      logWriter.put(requestLogs);
    }
  }
Пример #4
0
  public String format(LogRecord record) {
    StringBuffer line = new StringBuffer();

    switch (type) {
      case FILE:
        line.append(currentDateString());
        line.append(" - ");
        line.append(record.getLevel().getName());
        line.append(" - ");
        line.append(record.getMessage());
        line.append(LF);
        break;

      case CONSOLE:
      default:
        line.append(record.getMessage());
        line.append(LF);
        break;
    }

    Throwable thrown = record.getThrown();
    if (thrown != null) {
      line.append(toString(thrown));
    }

    return line.toString();
  }
    public synchronized void publish(LogRecord rec) {
      if ("133616 - checking invalid".equals(rec.getMessage())) {
        Thread lockingThread =
            new Thread(
                new Runnable() {

                  public void run() {
                    try {
                      fileObject.lock().releaseLock();
                    } catch (IOException ex) {
                      fail(ex.getMessage());
                    }
                  }
                },
                "Locking");
        lockingThread.start();
        try {
          wait();
        } catch (InterruptedException ex) {
          fail(ex.getMessage());
        }
      }
      if ("133616 - in lock".equals(rec.getMessage())) {
        notify();
      }
    }
    public SVNNodeKind checkRepositoryPath(
        SCMSourceOwner context, SVNURL repoURL, StandardCredentials credentials)
        throws SVNException {
      SVNRepository repository = null;

      try {
        repository =
            getRepository(
                context, repoURL, credentials, Collections.<String, Credentials>emptyMap(), null);
        repository.testConnection();

        long rev = repository.getLatestRevision();
        String repoPath = getRelativePath(repoURL, repository);
        return repository.checkPath(repoPath, rev);
      } catch (SVNException e) {
        if (LOGGER.isLoggable(Level.FINE)) {
          LogRecord lr =
              new LogRecord(
                  Level.FINE, "Could not check repository path {0} using credentials {1} ({2})");
          lr.setThrown(e);
          lr.setParameters(
              new Object[] {
                repoURL,
                credentials == null ? null : CredentialsNameProvider.name(credentials),
                credentials
              });
          LOGGER.log(lr);
        }
        throw e;
      } finally {
        if (repository != null) repository.closeSession();
      }
    }
    @Override
    public String format(LogRecord record) {

      StringBuilder stringBuilder = new StringBuilder("[");
      stringBuilder.append(simpleDateFormat.format(new Date(record.getMillis()))).append("]");
      stringBuilder.append(" [TID:").append(getThreadId()).append("] [");
      stringBuilder.append(getCallingInfo(7));
      stringBuilder
          .append("[")
          .append(record.getLevel().getLocalizedName())
          .append("]: ")
          .append(formatMessage(record))
          .append(LINE_SEPARATOR);

      if (record.getThrown() != null) {

        try {
          StringWriter sw = new StringWriter();
          PrintWriter pw = new PrintWriter(sw);
          record.getThrown().printStackTrace(pw);
          pw.close();
          stringBuilder.append(sw.toString());
        } catch (Exception ex) {
          // ignore
        }
      }

      return stringBuilder.toString();
    }
Пример #8
0
  public static void testLoggingSuppressor() throws IOException {
    TestLogHandler logHandler = new TestLogHandler();

    Closeables.logger.addHandler(logHandler);
    try {
      Closer closer = new Closer(new Closer.LoggingSuppressor());

      TestCloseable c1 = closer.register(TestCloseable.throwsOnClose(new IOException()));
      TestCloseable c2 = closer.register(TestCloseable.throwsOnClose(new RuntimeException()));
      try {
        throw closer.rethrow(new IOException("thrown"), IOException.class);
      } catch (IOException expected) {
      }

      assertTrue(logHandler.getStoredLogRecords().isEmpty());

      closer.close();

      assertEquals(2, logHandler.getStoredLogRecords().size());

      LogRecord record = logHandler.getStoredLogRecords().get(0);
      assertEquals("Suppressing exception thrown when closing " + c2, record.getMessage());

      record = logHandler.getStoredLogRecords().get(1);
      assertEquals("Suppressing exception thrown when closing " + c1, record.getMessage());
    } finally {
      Closeables.logger.removeHandler(logHandler);
    }
  }
Пример #9
0
  // this method is called for every log records
  public String format(LogRecord rec) {
    StringBuffer buf = new StringBuffer(1000);
    buf.append("<tr>\n");

    // colorize any levels >= WARNING in red
    if (rec.getLevel().intValue() >= Level.WARNING.intValue()) {
      buf.append("\t<td style=\"color:red\">");
      buf.append("<b>");
      buf.append(rec.getLevel());
      buf.append("</b>");
    } else {
      buf.append("\t<td>");
      buf.append(rec.getLevel());
    }

    buf.append("</td>\n");
    buf.append("\t<td>");
    buf.append(calcDate(rec.getMillis()));
    buf.append("</td>\n");
    buf.append("\t<td>");
    buf.append(formatMessage(rec));
    buf.append("</td>\n");
    buf.append("</tr>\n");

    return buf.toString();
  }
Пример #10
0
 public List<String> messages() {
   List<String> result = new ArrayList<String>();
   for (LogRecord record : records) {
     result.add(record.getMessage());
   }
   return result;
 }
Пример #11
0
  @Override
  public String format(LogRecord record) {
    StringBuilder sb = new StringBuilder();

    sb.append(new SimpleDateFormat("HH:mm:ss").format(new Date(record.getMillis())))
        .append(" ")
        .append(record.getLevel().getLocalizedName())
        .append(": ")
        .append(formatMessage(record))
        .append(LINE_SEPARATOR);

    if (record.getThrown() != null) {
      try {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        record.getThrown().printStackTrace(pw);
        pw.close();
        sb.append(sw.toString());
      } catch (Exception ex) {
        // ignore
      }
    }

    return sb.toString();
  }
  /*
   * (non-Javadoc)
   *
   * @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
   */
  @Override
  public String format(final LogRecord logRecord) {
    //		Date recordDate = new Date(logRecord.getMillis());
    StringBuffer sb = new StringBuffer();
    try {
      // TIME and LEVEL is already at the console
      //			sb.append(LogUtils.dateToString(recordDate, UTC_Format));
      //			sb.append(" [");
      //			sb.append(logRecord.getLevel().getName());
      //			sb.append("]: ");

      //
      sb.append(logRecord.getMessage());

      sb.append("\n   (source:");
      sb.append(logRecord.getSourceClassName());
      sb.append('.');
      sb.append(logRecord.getSourceMethodName());
      if (logRecord.getThrown() != null) {
        sb.append(" - See IBM_TECHNICAL_SUPPORT\\org.openntf.log.X.Y.txt for full stack trace.");
      }
      sb.append(")");
    } catch (Throwable t) {
      System.out.println(
          "Error trying to format output for error handling. Resorting to standard stack trace...");
      t.printStackTrace();
    }
    return sb.toString();
  }
 /**
  * Creates a pooled connection object with the properties specified.
  *
  * @param props properties for the Type 4 connection
  * @see #HPT4ConnectionPoolDataSource()
  * @link T4Properties
  */
 public HPT4ConnectionPoolDataSource(Properties props) {
   super(props);
   if (getT4LogLevel() != Level.OFF) setupLogFileHandler();
   if (t4Logger_.isLoggable(Level.FINE) == true) {
     Object p[] = T4LoggingUtilities.makeParams(null, props);
     t4Logger_.logp(
         Level.FINE,
         "HPT4ConnectionPoolDataSource",
         "HPT4ConnectionPoolDataSource",
         "Note, super called before this.",
         p);
   }
   try {
     if (getLogWriter() != null) {
       LogRecord lr = new LogRecord(Level.FINE, "");
       Object p[] = T4LoggingUtilities.makeParams(null, props);
       lr.setParameters(p);
       lr.setSourceClassName("HPT4ConnectionPoolDataSource");
       lr.setSourceMethodName("");
       T4LogFormatter lf = new T4LogFormatter();
       String temp = lf.format(lr);
       getLogWriter().println(temp);
     }
   } catch (SQLException se) {
     // ignore
   }
 }
  @AdviseWith(adviceClasses = PropsUtilAdvice.class)
  @Test
  public void testInvalidSettingWithLog() {
    CaptureHandler captureHandler = _doTestInvalidSetting(Level.WARNING);

    try {
      List<LogRecord> logRecords = captureHandler.getLogRecords();

      Assert.assertEquals(2, logRecords.size());

      LogRecord logRecord1 = logRecords.get(0);

      Assert.assertEquals(
          PropsKeys.BUFFERED_INCREMENT_THREADPOOL_KEEP_ALIVE_TIME + "[]=-3. Auto reset to 0.",
          logRecord1.getMessage());

      LogRecord logRecord2 = logRecords.get(1);

      Assert.assertEquals(
          PropsKeys.BUFFERED_INCREMENT_THREADPOOL_MAX_SIZE + "[]=-4. Auto reset to 1.",
          logRecord2.getMessage());
    } finally {
      captureHandler.close();
    }
  }
Пример #15
0
 @Override
 public String format(final LogRecord record) {
   // Replace [Type, JavaType] -> its debug string!
   final Object[] params = record.getParameters();
   if (null != params) {
     for (int i = params.length - 1; 0 <= i; i--) {
       final Object o = params[i];
       if (o instanceof Type) {
         params[i] = ((Type) o).getDebugString();
       } else if (o instanceof JavaType) {
         params[i] = ((JavaType) o).getDebugString();
       } else if (o instanceof AliasedSymbol) {
         params[i] = ((AliasedSymbol) o).getAliasedString();
       }
     }
   }
   final StringBuilder sb = new StringBuilder(256);
   if (null != astLocus) {
     astLocus.toString(sb, getCanonicalName(record.getLevel()), GlueGen.debug()).append(": ");
   }
   if (GlueGen.debug()) {
     sb.append(simpleClassName).append(": ");
   }
   sb.append(formatMessage(record)).append("\n");
   return sb.toString();
 }
Пример #16
0
 /**
  * Logs a debug message for {@link #getServiceProvider} method. Note: we are not required to
  * insert the method name ({@code "GetServiceProvider"}) in the message because it is part of the
  * informations already stored by {@link LogRecord}, and formatted by the default {@link
  * java.util.logging.SimpleFormatter}.
  *
  * @param status {@code "ENTRY"}, {@code "RETURN"} or {@code "THROW"}, according {@link Logger}
  *     conventions.
  * @param category The category given to the {@link #getServiceProvider} method.
  * @param key The key being examined, or {@code null}.
  * @param message Optional message, or {@code null} if none.
  * @param type Optional class to format after the message, or {@code null}.
  */
 private static void debug(
     final String status,
     final Class<?> category,
     final Hints.Key key,
     final String message,
     final Class type) {
   final StringBuilder buffer = new StringBuilder(status);
   buffer
       .append(Utilities.spaces(Math.max(1, 7 - status.length())))
       .append('(')
       .append(Classes.getShortName(category));
   if (key != null) {
     buffer.append(", ").append(key);
   }
   buffer.append(')');
   if (message != null) {
     buffer.append(": ").append(message);
   }
   if (type != null) {
     buffer.append(' ').append(Classes.getShortName(type)).append('.');
   }
   final LogRecord record = new LogRecord(DEBUG_LEVEL, buffer.toString());
   record.setSourceClassName(FactoryRegistry.class.getName());
   record.setSourceMethodName("getServiceProvider");
   record.setLoggerName(LOGGER.getName());
   LOGGER.log(record);
 }
Пример #17
0
  public final Client performLogin(final ServerLogin login) throws RjException, LoginException {
    String client = null;
    try {
      client = getCallingClient();
      if (login.getId() != this.pendingLoginId || !client.equals(this.pendingLoginClient)) {
        throw new FailedLoginException("Login process was interrupted by another client.");
      }

      login.readAnswer(this.usePubkeyExchange ? this.pendingLoginKeyPair.getPrivate() : null);
      this.pendingLoginKeyPair = null;
      final String name = doPerformLogin(login.getCallbacks());

      LOGGER.log(
          Level.INFO,
          "{0} performing login completed successfull: {1} ({2}).",
          new Object[] {this.logPrefix, name, client});
      return new Client(name, getCallingClient(), (byte) 0);
    } catch (final Exception e) {
      if (e instanceof LoginException) {
        final LogRecord log = new LogRecord(Level.INFO, "{0} performing login failed ({1}).");
        log.setParameters(new Object[] {this.logPrefix, client});
        log.setThrown(e);
        LOGGER.log(log);
        throw (LoginException) e;
      }
      if (e instanceof RjException) {
        throw (RjException) e;
      }
      throw new RjException(
          "An unexpected error occurred when validating the login credential.", e);
    } finally {
      System.gc();
    }
  }
Пример #18
0
  @Override
  public String format(LogRecord event) {
    final StringBuilder html = new StringBuilder();
    html.append(getHtmlPrefix(event));
    html.append(getRecordInfo(event, "<br>"));
    html.append(getEscaped(event.getMessage()));
    if (showStackTraces && event.getThrown() != null) {
      html.append("<br>");
      event
          .getThrown()
          .printStackTrace(
              new StackTracePrintStream(html) {
                @Override
                public void append(String str) {
                  html.append(getEscaped(str));
                }

                @Override
                public void newLine() {
                  html.append("<br>");
                }
              });
    }
    html.append(getHtmlSuffix(event));
    return html.toString();
  }
Пример #19
0
 public String format(LogRecord record) {
   Object[] arguments = new Object[3];
   arguments[0] = record.getLoggerName();
   arguments[1] = record.getLevel();
   arguments[2] = record.getMessage();
   return messageFormat.format(arguments);
 }
Пример #20
0
  /** Infer a caller, ignoring logging-related classes. */
  private final void inferCallerELKI() {
    needToInferCaller = false;
    StackTraceElement stack[] = (new Throwable()).getStackTrace();
    int ix = 0;
    // skip back to the logger.
    while (ix < stack.length) {
      StackTraceElement frame = stack[ix];
      final String cls = frame.getClassName();
      if (cls.equals(START_TRACE_AT)) {
        break;
      }
      ix++;
    }
    // skip further back through helper functions
    while (ix < stack.length) {
      StackTraceElement frame = stack[ix];
      final String cls = frame.getClassName();

      boolean ignore = false;
      for (int i = 0; i < IGNORE_CLASSES.length; i++) {
        if (cls.equals(IGNORE_CLASSES[i])) {
          ignore = true;
          break;
        }
      }
      if (!ignore) {
        super.setSourceClassName(frame.getClassName());
        super.setSourceMethodName(frame.getMethodName());
        break;
      }
      ix++;
    }
  }
Пример #21
0
  private void validateNullableWarns(Injector injector, Dependency<?> dependency) {
    final List<LogRecord> logRecords = Lists.newArrayList();
    final Handler fakeHandler =
        new Handler() {
          @Override
          public void publish(LogRecord logRecord) {
            logRecords.add(logRecord);
          }

          @Override
          public void flush() {}

          @Override
          public void close() throws SecurityException {}
        };
    Logger.getLogger(Guice.class.getName()).addHandler(fakeHandler);
    try {
      injector.getInstance(Integer.class); // no exception, but assert it does log.
      LogRecord record = Iterables.getOnlyElement(logRecords);
      assertEquals(
          "Guice injected null into {0} (a {1}), please mark it @Nullable."
              + " Use -Dguice_check_nullable_provides_params=ERROR to turn this into an"
              + " error.",
          record.getMessage());
      assertEquals(Errors.convert(dependency.getKey()), record.getParameters()[1]);
    } finally {
      Logger.getLogger(Guice.class.getName()).removeHandler(fakeHandler);
    }
  }
Пример #22
0
  @Override
  public String format(LogRecord record) {
    ChatArguments args = LOG_TEMPLATE.getArguments();
    ChatArguments level = colorizeLevel(record.getLevel());
    args.setPlaceHolder(LEVEL, level);
    if (record instanceof FormattedLogRecord) {
      args.setPlaceHolder(MESSAGE, ((FormattedLogRecord) record).getFormattedMessage());
    } else {
      args.setPlaceHolder(MESSAGE, new ChatArguments(super.formatMessage(record) + '\n'));
    }

    if (record.getThrown() != null) {
      StringWriter writer = new StringWriter();
      record.getThrown().printStackTrace(new PrintWriter(writer));
      String[] lines = writer.getBuffer().toString().split("\n");
      for (String line : lines) {
        args.append(
            LOG_TEMPLATE
                .getArguments()
                .setPlaceHolder(LEVEL, level)
                .setPlaceHolder(MESSAGE, new ChatArguments(line))
                .asString(handlerId));
        args.append('\n');
      }
    }
    args.append(ChatStyle.RESET);
    return args.asString(handlerId);
  }
  private void testResumeException(final String path, final String entity) throws Exception {
    final WebTarget errorResource = target("errorResource");

    final Future<Response> suspended = errorResource.path("suspend").request().async().get();
    final Response response = errorResource.path(path).request().get();

    assertThat(response.getStatus(), equalTo(200));
    assertThat(response.readEntity(String.class), equalTo("ok"));

    final Response suspendedResponse = suspended.get();

    assertThat(suspendedResponse.getStatus(), equalTo(500));
    if (entity != null) {
      assertThat(suspendedResponse.readEntity(String.class), equalTo(entity));
    }

    suspendedResponse.close();

    // Check there is no NPE.
    for (final LogRecord record : getLoggedRecords()) {
      final Throwable thrown = record.getThrown();
      if (thrown != null && thrown instanceof NullPointerException) {
        fail("Unexpected NPE.");
      }
    }
  }
  /**
   * Returns all the properties associated with this <code>ConnectionPoolDataSource</code>.
   *
   * @return Reference Object containing all the Type 4 property references.
   * @throws NamingException
   */
  public Reference getReference() throws NamingException {
    if (t4Logger_ != null && t4Logger_.isLoggable(Level.FINE) == true) {
      Object p[] = T4LoggingUtilities.makeParams(null);
      t4Logger_.logp(Level.FINE, "HPT4ConnectionPoolDataSource", "getReference", "", p);
    }
    try {
      if (getLogWriter() != null) {
        LogRecord lr = new LogRecord(Level.FINE, "");
        Object p[] = T4LoggingUtilities.makeParams(null);
        lr.setParameters(p);
        lr.setSourceClassName("HPT4ConnectionPoolDataSource");
        lr.setSourceMethodName("getReference");
        T4LogFormatter lf = new T4LogFormatter();
        String temp = lf.format(lr);
        getLogWriter().println(temp);
      }
    } catch (SQLException se) {
      // ignore
    }

    Reference ref =
        new Reference(
            this.getClass().getName(),
            "org.trafodion.jdbc.t4.HPT4ConnectionPoolDataSourceFactory",
            null);
    ref = addReferences(ref);
    ref.add(new StringRefAddr("propertyCycle", Integer.toString(propertyCycle_)));
    return ref;
  }
Пример #25
0
 /** Log the specified message after all provider for a given category have been registered. */
 private static void log(final String method, final StringBuilder message) {
   final LogRecord record = new LogRecord(Level.CONFIG, message.toString());
   record.setSourceClassName(FactoryRegistry.class.getName());
   record.setSourceMethodName(method);
   record.setLoggerName(LOGGER.getName());
   LOGGER.log(record);
 }
Пример #26
0
 /**
  * Log a LogRecord.
  *
  * @param record The LogRecord to be published
  */
 @Override
 public void log(LogRecord record) {
   if (record.getThrown() != null) {
     getContext().log(record.getMessage(), record.getThrown());
   } else {
     getContext().log(record.getMessage());
   }
 }
  private LogRecord deobfuscateLogRecord(
      StackTraceDeobfuscator deobfuscator, LogRecord lr, String strongName) {
    if (lr.getThrown() != null && strongName != null) {
      deobfuscator.deobfuscateStackTrace(lr.getThrown(), strongName);
    }

    return lr;
  }
Пример #28
0
 @Override
 public void publish(LogRecord record) {
   if ((record.getLevel().intValue() > Level.INFO.intValue())
       && thrown == null
       && record.getThrown() != null) {
     thrown = record.getThrown();
   }
 }
Пример #29
0
 public String format(LogRecord record) {
   StringBuilder s = new StringBuilder(1000);
   s.append("[").append(record.getLevel()).append("] ");
   s.append(df.format(new Date(record.getMillis()))).append(" : ");
   s.append(formatMessage(record));
   s.append(LINE_SEPARATOR);
   return s.toString();
 }
 protected void log(Level level, String message, Object[] params, Throwable cause) {
   if (logger.isLoggable(level)) {
     LogRecord record = new LogRecord(level, message);
     record.setParameters(params);
     record.setThrown(cause);
     logger.log(record);
   }
 }