Example usage for java.lang Throwable Throwable

List of usage examples for java.lang Throwable Throwable

Introduction

In this page you can find the example usage for java.lang Throwable Throwable.

Prototype

public Throwable() 

Source Link

Document

Constructs a new throwable with null as its detail message.

Usage

From source file:com.amazonaws.services.kinesis.multilang.messages.MessageTest.java

@Test
public void toStringTest() {
    Message[] messages = new Message[] { new CheckpointMessage("1234567890", null),
            new InitializeMessage("shard-123"), new ProcessRecordsMessage(new ArrayList<Record>() {
                {//from   ww  w . j a  v a  2 s . co m
                    this.add(new Record() {
                        {
                            this.withData(ByteBuffer.wrap("cat".getBytes()));
                            this.withPartitionKey("cat");
                            this.withSequenceNumber("555");
                        }
                    });
                }
            }), new ShutdownMessage(ShutdownReason.ZOMBIE), new StatusMessage("processRecords"),
            new InitializeMessage(), new ProcessRecordsMessage() };

    for (int i = 0; i < messages.length; i++) {
        Assert.assertTrue("Each message should contain the action field",
                messages[i].toString().contains("action"));
    }

    // Hit this constructor
    JsonFriendlyRecord defaultJsonFriendlyRecord = new JsonFriendlyRecord();
    Assert.assertNull(defaultJsonFriendlyRecord.getPartitionKey());
    Assert.assertNull(defaultJsonFriendlyRecord.getData());
    Assert.assertNull(defaultJsonFriendlyRecord.getSequenceNumber());
    Assert.assertNull(new ShutdownMessage(null).getReason());

    // Hit the bad object mapping path
    Message withBadMapper = new Message() {
    }.withObjectMapper(new ObjectMapper() {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        @Override
        public String writeValueAsString(Object m) throws JsonProcessingException {
            throw new JsonProcessingException(new Throwable()) {
            };
        }
    });
    String s = withBadMapper.toString();
    Assert.assertNotNull(s);
}

From source file:io.kahu.hawaii.rest.AbstractController.java

protected RequestLogBuilder requestLog() {

    String method = new Throwable().getStackTrace()[1].getMethodName();
    String type = logTypePrefix + "." + method;
    RequestLogBuilder builder = new RequestLogBuilder(logManager, type);

    try {//from  w  w  w .  java  2s . co m
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();

        // path variables
        Map<String, String> pathVariables = (Map<String, String>) request
                .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        if (pathVariables != null) {
            for (Map.Entry<String, String> entry : pathVariables.entrySet()) {
                builder.param(entry.getKey(), entry.getValue());
            }
        }

        // request parameters
        Enumeration<?> requestParameters = request.getParameterNames();
        while (requestParameters.hasMoreElements()) {
            String key = (String) requestParameters.nextElement();
            String[] values = request.getParameterValues(key);
            builder.param(key, values);
        }

    } catch (Throwable t) {
        logManager.warn(CoreLoggers.SERVER, "Unable to log request", t);
        // ignore
    }
    return builder.excludeParam("_");
}

From source file:org.eclipse.vjet.dsf.common.trace.DefaultTracer.java

public void enterMethod(final Object caller, final String msg) {

    if (!m_traceEnabled) {
        return;/*from w  w w  . j ava 2s  .  com*/
    }

    if (caller == null) {
        return;
    }

    final Throwable t = new Throwable();
    t.fillInStackTrace();

    final String clsName = getClassName(caller);
    final String methodName = getMethodName(caller, t);

    push(clsName + DOT + methodName);

    dispatch(new WriterInvoker() {
        public void process(ITraceWriter w) {
            w.handleEnterMethod(m_traceDepth, clsName, methodName, msg);
        }
    });
}

From source file:jetbrains.exodus.core.execution.locks.DebugLatch.java

private void gatherOwnerInfo() {
    acquireTime = new Date();
    acquireTrace = new Throwable().getStackTrace();
}

From source file:test.org.tradex.camel.TestCaseAppContextBuilder.java

/**
 * Builds an application context reading the file from the passed path
 * @param path The path of the app context xml
 * @return the built app context/*from w  w  w.  j  ava2  s  .c om*/
 */
public static GenericXmlApplicationContext buildFor(String path) {
    if (path == null)
        throw new IllegalArgumentException("Passed path was null", new Throwable());
    File springXml = new File(path);
    if (!springXml.canRead()) {
        throw new RuntimeException("Failed to read Spring XML file at [" + springXml + "]", new Throwable());
    }
    try {
        return service(new GenericXmlApplicationContext(
                new FileSystemResource[] { new FileSystemResource(springXml.getAbsoluteFile()) }));
    } catch (Throwable t) {
        LOG.fatal("Failed to boot app context", t);
        throw new RuntimeException("Failed to boot app context", t);
    }
}

From source file:net.ymate.platform.log.jcl.JCLogger.java

/**
 * ??/*from  w  ww .jav  a 2 s.com*/
 *
 * @return ??className.methodName:lineNumber?NO_STACK_TRACE:-1
 */
protected String __doMakeCallerInfo() {
    StackTraceElement[] _stacks = new Throwable().getStackTrace();
    // ???
    if (_stacks.length > 3) {
        StackTraceElement _element = _stacks[3];
        return StringUtils.substringBeforeLast(_element.getClassName(), ".").concat(".")
                .concat(_element.getMethodName()).concat(":")
                .concat(_element.getLineNumber() + StringUtils.EMPTY);
    }
    return "NO_STACK_TRACE:-1";
}

From source file:com.screenslicer.common.Log.java

public static void warn(String message) {
    if (logger == null) {
        init("screenslicer", true);
    }/*  w w  w  .j a va  2 s . c o  m*/
    logger.log(Level.WARNING,
            "Message \"" + message + "\" ~ Current stack: " + ExceptionUtils.getStackTrace(new Throwable()));
}

From source file:chat.ServletLog.java

protected void log(Level l, Object message, Throwable t) {
    if (t == null && message instanceof Throwable) {
        t = (Throwable) message;//from  w ww . j  a va  2  s . c o m
        message = "";
    }

    StringBuilder s = new StringBuilder(format);
    int i = s.indexOf(FORMAT_DATE);
    if (i >= 0)
        s.replace(i, i + FORMAT_DATE.length(), DATE.format(new Date()));
    i = s.indexOf(FORMAT_LEVEL);
    if (i >= 0)
        s.replace(i, i + FORMAT_LEVEL.length(), l.name());
    i = s.indexOf(FORMAT_LOG);
    if (i >= 0)
        s.replace(i, i + FORMAT_LOG.length(), String.valueOf(message));
    i = s.indexOf(FORMAT_CALL);
    if (i >= 0) {
        StackTraceElement[] stack = new Throwable().getStackTrace();
        // Caller is the third element
        String clazz = "unknown";
        String method = "unknown";
        if (stack != null && stack.length > 2) {
            clazz = stack[2].getClassName();
            method = stack[2].getMethodName();
        }
        s.replace(i, i + FORMAT_CALL.length(), clazz + '-' + method);
    }
    if (logger != null)
        logger.log(s.toString(), t);
    else {
        if (t != null) {
            StringWriter ts = new StringWriter(1024);
            PrintWriter tp = new PrintWriter(ts);
            t.printStackTrace(tp);
            tp.close();
            s.append("\n ").append(ts.toString());
        }
        (l.ordinal() <= Level.debug.ordinal() ? System.out : System.err).println(s);
    }
}

From source file:com.opentable.logging.LogMetadataTest.java

@Test
public void testSimpleMetadata() throws Exception {
    context.getLogger("test").info(LogMetadata.of("metadataTest", "Win!"), "Test {}!", "message");
    context.getLogger("test").warn(LogMetadata.of("foo", "bar").and("bar", "baz"), "again", new Throwable());
    assertEquals(2, serializedEvents.size());
    assertEquals("Win!", serializedEvents.get(0).get("metadataTest").textValue());
    assertEquals("bar", serializedEvents.get(1).get("foo").textValue());
    assertEquals("baz", serializedEvents.get(1).get("bar").textValue());
}

From source file:com.opentable.logging.KafkaAppenderTest.java

@Test(timeout = 10000)
public void testLog() throws Exception {
    AdminUtils.createTopic(kafka.getServer().zkClient(), "logs", 1, 1, new Properties());
    Thread.sleep(2000);/*w w w.  j a  va  2 s .  c o m*/
    context.getLogger("test").info("Herro!");
    context.getLogger("womp").warn("flop", new Throwable());

    // Ensure we flush our buffers
    context.stop();

    final CommonLogFields log1, log2;

    ConsumerConnector consumer = createConsumer();

    final List<KafkaStream<byte[], byte[]>> streams = consumer
            .createMessageStreams(Collections.singletonMap("logs", 1)).get("logs");
    final KafkaStream<byte[], byte[]> stream = Iterables.getOnlyElement(streams);
    final ConsumerIterator<byte[], byte[]> iterator = stream.iterator();

    System.out.println("read 0");
    log1 = read(iterator.next().message());
    System.out.println("read 1");
    log2 = read(iterator.next().message());
    System.out.println("read 2");

    consumer.shutdown();

    assertEquals("Herro!", log1.getMessage());
    assertEquals("test", log1.getLogClass());
    assertEquals("INFO", log1.getSeverity());

    assertEquals("flop", log2.getMessage());
    assertEquals("womp", log2.getLogClass());
    assertEquals("WARN", log2.getSeverity());
}