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.greplin.gec.GecLogbackAppender.java

/**
 * Writes a formatted msg for errors that don't have exceptions.
 *
 * @param message the log message//from   w  w  w.  j  av a2  s . c  om
 * @param level   the error level
 * @param out     the destination
 * @throws IOException if there are IO errors in the destination
 */
void writeFormattedException(final String message, final Level level, final Writer out) throws IOException {
    JsonGenerator generator = new JsonFactory().createJsonGenerator(out);

    String backtrace = GecLogbackAppender.getStackTrace(new Throwable());
    String[] lines = backtrace.split("\n");
    StringBuilder builder = new StringBuilder();
    for (String line : lines) {
        if (!line.contains("com.greplin.gec.GecLogbackAppender.")) {
            builder.append(line);
            builder.append("\n");
        }
    }
    backtrace = builder.toString();

    generator.writeStartObject();
    generator.writeStringField("project", this.project);
    generator.writeStringField("environment", this.environment);
    generator.writeStringField("serverName", this.serverName);
    generator.writeStringField("backtrace", backtrace);
    generator.writeStringField("message", message);
    generator.writeStringField("logMessage", message);
    generator.writeStringField("type", "N/A");
    if (level != Level.ERROR) {
        generator.writeStringField("errorLevel", level.toString());
    }
    writeContext(generator);
    generator.writeEndObject();
    generator.close();
}

From source file:io.stallion.services.Log.java

public static void warn(String message, Object... args) {
    if (getLogLevel().intValue() > Level.WARNING.intValue()) {
        return;//from   ww  w  .  java2s  .co m
    }
    Throwable t = new Throwable();
    StackTraceElement stackTraceElement = t.getStackTrace()[1];
    String clz = stackTraceElement.getClassName().replace("io.stallion.", "");
    String method = stackTraceElement.getMethodName() + ":" + t.getStackTrace()[1].getLineNumber();
    logger.logp(Level.WARNING, clz, method, message, args);

}

From source file:com.cisco.dbds.utils.logging.LogHandler.java

/**
 * In Stack trace the first element will be the current object invoked(which
 * is always the logger object) The first element will be the caller object.
 *
 * @return the current method info/*from w  w w . ja  va2 s .c o  m*/
 */
private static String getCurrentMethodInfo() {
    Throwable t = new Throwable();
    StackTraceElement[] elements = t.getStackTrace();
    // String calleeMethod = elements[0].getMethodName();
    String callerMethodName = elements[3].getMethodName();
    String[] classNames = elements[3].getClassName().split("\\.");
    String callerClassName = classNames[classNames.length - 1];
    return callerClassName + ": " + callerMethodName + "(): ";
}

From source file:org.coconut.core.LoggersTest.java

public void testIgnoreLog(Logger log) {
    SystemErrOutHelper outStr = SystemErrOutHelper.get();
    SystemErrOutHelper errStr = SystemErrOutHelper.getErr();
    try {//from   w  w w.  java 2 s .  co  m
        Throwable t = new Throwable();
        testLevelOn(log, Logger.Level.Fatal.getLevel() + 1);
        log.trace("trace test a");
        log.trace("trace test b", t);
        log.debug("debug test a");
        log.debug("debug test b", t);
        log.info("info test a");
        log.info("info test b", t);
        log.warn("warn test a");
        log.warn("warn test b", t);
        log.error("error test a");
        log.error("error test b", t);
        log.fatal("fatal test a");
        log.fatal("fatal test b", t);
        assertEquals(outStr.last.getLast(), "");
        assertEquals(errStr.last.getLast(), "");
    } finally {
        outStr.terminate();
        errStr.terminate();
    }
}

From source file:org.codehaus.plexus.archiver.zip.ZipArchiverTest.java

public void testCreateArchiveWithDetectedModes() throws Exception {

    String[] executablePaths = { "path/to/executable", "path/to/executable.bat" };

    String[] confPaths = { "path/to/etc/file", "path/to/etc/file2" };

    String[] logPaths = { "path/to/logs/log.txt" };

    int exeMode = 0777;
    int confMode = 0600;
    int logMode = 0640;

    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
        StackTraceElement e = new Throwable().getStackTrace()[0];
        System.out//from   ww  w .  j a v  a 2s.  c  o  m
                .println("Cannot execute test: " + e.getMethodName() + " on " + System.getProperty("os.name"));
        return;
    }

    File tmpDir = null;
    try {
        tmpDir = File.createTempFile("zip-with-chmod.", ".dir");
        tmpDir.delete();

        tmpDir.mkdirs();

        for (String executablePath : executablePaths) {
            writeFile(tmpDir, executablePath, exeMode);
        }

        for (String confPath : confPaths) {
            writeFile(tmpDir, confPath, confMode);
        }

        for (String logPath : logPaths) {
            writeFile(tmpDir, logPath, logMode);
        }

        {
            Map<String, PlexusIoResourceAttributes> attributesByPath = PlexusIoResourceAttributeUtils
                    .getFileAttributesByPath(tmpDir);
            for (String path : executablePaths) {
                PlexusIoResourceAttributes attrs = attributesByPath.get(path);
                if (attrs == null) {
                    attrs = attributesByPath.get(new File(tmpDir, path).getAbsolutePath());
                }

                assertNotNull(attrs);
                assertEquals("Wrong mode for: " + path + "; expected: " + exeMode, exeMode,
                        attrs.getOctalMode());
            }

            for (String path : confPaths) {
                PlexusIoResourceAttributes attrs = attributesByPath.get(path);
                if (attrs == null) {
                    attrs = attributesByPath.get(new File(tmpDir, path).getAbsolutePath());
                }

                assertNotNull(attrs);
                assertEquals("Wrong mode for: " + path + "; expected: " + confMode, confMode,
                        attrs.getOctalMode());
            }

            for (String path : logPaths) {
                PlexusIoResourceAttributes attrs = attributesByPath.get(path);
                if (attrs == null) {
                    attrs = attributesByPath.get(new File(tmpDir, path).getAbsolutePath());
                }

                assertNotNull(attrs);
                assertEquals("Wrong mode for: " + path + "; expected: " + logMode, logMode,
                        attrs.getOctalMode());
            }
        }

        File zipFile = getTestFile("target/output/zip-with-modes.zip");

        ZipArchiver archiver = getZipArchiver(zipFile);

        archiver.addDirectory(tmpDir);
        archiver.createArchive();

        assertTrue(zipFile.exists());

        File zipFile2 = getTestFile("target/output/zip-with-modes-L2.zip");

        archiver = getZipArchiver();
        archiver.setDestFile(zipFile2);

        archiver.addArchivedFileSet(zipFile);
        archiver.createArchive();

        ZipFile zf = new ZipFile(zipFile2);

        for (String path : executablePaths) {
            ZipArchiveEntry ze = zf.getEntry(path);

            int mode = ze.getUnixMode() & UnixStat.PERM_MASK;

            assertEquals("Wrong mode for: " + path + "; expected: " + exeMode, exeMode, mode);
        }

        for (String path : confPaths) {
            ZipArchiveEntry ze = zf.getEntry(path);

            int mode = ze.getUnixMode() & UnixStat.PERM_MASK;

            assertEquals("Wrong mode for: " + path + "; expected: " + confMode, confMode, mode);
        }

        for (String path : logPaths) {
            ZipArchiveEntry ze = zf.getEntry(path);

            int mode = ze.getUnixMode() & UnixStat.PERM_MASK;

            assertEquals("Wrong mode for: " + path + "; expected: " + logMode, logMode, mode);
        }
    } finally {
        if (tmpDir != null && tmpDir.exists()) {
            try {
                FileUtils.forceDelete(tmpDir);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:info.magnolia.test.mock.AbstractComponentProvider.java

@Override
public synchronized <T> T newInstance(Class<T> type, Object... parameters) {
    if (type == null) {
        log.error("type can't be null", new Throwable());
        return null;
    }//from www .  j  a  v a2  s.c o m

    List<Class<?>> stack = creationStack.get();
    try {

        if (stack == null) {
            stack = new ArrayList<Class<?>>();
            stack.add(type);
            creationStack.set(stack);
        } else if (stack.contains(type)) {
            throw new CircularDependencyException(type, stack);
        } else {
            stack.add(type);
        }

        ComponentDefinition<T> definition = getComponentDefinition(type);
        if (definition == null) {
            if (parent != null) {
                return parent.newInstance(type, parameters);
            }
            if (!Classes.isConcrete(type)) {
                throw new MgnlInstantiationException("No concrete implementation defined for " + type);
            }
            return createInstance(type, parameters);
        }
        if (definition.isFactory()) {
            return this.<T>instantiateFactoryIfNecessary(definition).newInstance();
        }
        return createInstance(definition.getImplementationType(), parameters);
    } catch (Exception e) {
        if (e instanceof MgnlInstantiationException) {
            throw (MgnlInstantiationException) e;
        }
        throw new MgnlInstantiationException("Can't instantiate an implementation of this class ["
                + type.getName() + "]: " + ExceptionUtils.getMessage(e), e);
    } finally {
        stack.remove(type);
        if (stack.isEmpty()) {
            creationStack.remove();
        }
    }
}

From source file:edu.umn.msi.tropix.common.logging.ExceptionUtilsTest.java

@Test(groups = "unit")
public void convert() {
    final IOException ioException = new FileNotFoundException();

    final RuntimeException re = ExceptionUtils.convertException(ioException, RuntimeException.class);
    assert re.getCause().equals(ioException);
    final IllegalStateException ie = ExceptionUtils.convertException(ioException, "Moo",
            IllegalStateException.class);
    assert ie.getCause().equals(ioException) && ie.getMessage().equals("Moo");
    final FileNotFoundException fe = ExceptionUtils.convertException(ioException, FileNotFoundException.class);
    assert fe == ioException;

    ExceptionUtils.ExceptionConversionException ee = null;
    try {//from w  w  w. j a v a 2s.  c om
        ExceptionUtils.convertException(new Throwable(), NullPointerException.class);
    } catch (final ExceptionUtils.ExceptionConversionException iee) {
        ee = iee;
    }
    assert ee != null;
}

From source file:com.l2jfree.L2AutoInitialization.java

private static StackTraceElement getCaller() {
    StackTraceElement[] stack = new Throwable().getStackTrace();

    for (int i = stack.length - 1; i >= 0; i--) {
        if (stack[i].getClassName().startsWith("java.io.")
                || stack[i].getMethodName().equals("printStackTrace"))
            return stack[L2Math.limit(0, i + 1, stack.length - 1)];

        if (stack[i].getMethodName().equals("dispatchUncaughtException"))
            break;
    }/*from   w  ww  . j  a  va  2 s.  c  om*/

    return null;
}

From source file:com.eggwall.AdkUnoUsbHostExample.control.AccessoryService.java

/**
 * Handle the request from the UI.  You can modify this method to account for what your UI is asking
 * to do, and translate this into accessory control messages, if needed.
 * @param request integers from the {@link #REQUEST_LED_OFF} or {@link #REQUEST_LED_ON} to control
 *                the LED./* w  w w  . ja  v a2  s  .  c  om*/
 * @return
 */
public boolean handleRequest(int request) {
    switch (request) {
    case REQUEST_LED_OFF:
        if (mControl != null) {
            mControl.sendMessage(LED_ON);
        }
        break;
    case REQUEST_LED_ON:
        if (mControl != null) {
            mControl.sendMessage(LED_OFF);
        }
        break;
    default:
        Log.wtf(TAG, "Sent the wrong message " + request, new Throwable());
        break;
    }
    return false;
}

From source file:com.cloud.utils.exception.CSExceptionErrorCode.java

public static String getCurMethodName() {
    StackTraceElement stackTraceCalls[] = (new Throwable()).getStackTrace();
    return stackTraceCalls[1].toString();
}