Example usage for java.lang Exception getCause

List of usage examples for java.lang Exception getCause

Introduction

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

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:com.qwazr.utils.ExceptionUtils.java

public static Exception getCauseIfException(Exception e) {
    if (e == null)
        return null;
    Throwable cause = e.getCause();
    return cause instanceof Exception ? (Exception) cause : e;
}

From source file:Main.java

/**
 * Is the given {@link Exception} due to a 401 Unauthorized API response?
 *
 * @param e/* w  w w.j a  v a  2s.  c o m*/
 * @return true if 401, false otherwise
 */
public static boolean isUnauthorized(final Exception e) {
    String message = null;
    if (e instanceof IOException)
        message = e.getMessage();
    final Throwable cause = e.getCause();
    if (cause instanceof IOException) {
        String causeMessage = cause.getMessage();
        if (!TextUtils.isEmpty(causeMessage))
            message = causeMessage;
    }

    if (TextUtils.isEmpty(message))
        return false;

    if ("Received authentication challenge is null".equals(message))
        return true;
    return "No authentication challenges found".equals(message);

}

From source file:com.amalto.core.initdb.InitDBUtil.java

public static void init() {
    InputStream dbIn = null;/*from  w w w  . j av  a2s.  c om*/
    InputStream edbIn = null;
    try {
        dbIn = InitDBUtil.class.getResourceAsStream(INIT_DB_CONFIG);
        edbIn = InitDBUtil.class.getResourceAsStream(INIT_DB_EXTENSION_CONFIG);
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        parseInitMap(dbIn, builder, initDB);
        if (edbIn != null) {
            useExtension = true;
            logger.info("Use Extension..."); //$NON-NLS-1$
            initDB.remove("amaltoOBJECTSRole"); //$NON-NLS-1$
            parseInitMap(edbIn, builder, initExtensionDB);
        }
    } catch (Exception e) {
        logger.error(e.getCause());
    } finally {
        if (dbIn != null) {
            try {
                dbIn.close();
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Could not close stream.", e); //$NON-NLS-1$
                }
            }
        }
        if (edbIn != null) {
            try {
                edbIn.close();
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Could not close stream.", e); //$NON-NLS-1$
                }
            }
        }
    }
}

From source file:me.Laubi.MineMaze.SubCommands.java

@SubCommand(alias = "maze", permission = "worldedit.minemaze.generate", author = "Laubi", description = "Create you own maze")
public static void maze(LocalPlayer player, CommandHandler handler, MineMazePlugin plugin) {
    final WorldEdit we = plugin.getWorldEdit();
    try {//from w  w w  . j  a va  2 s .  c o m
        Method mazeGen;
        LocalSession session;
        Region r;

        r = (session = we.getSession(player)).getSelection(player.getWorld());

        if (handler.containsArgument("gen")) {
            mazeGen = plugin.getMazeGeneratorByAlias(handler.getArgumentValue("gen"));
        } else {
            mazeGen = plugin.getMazeGenerators()
                    .get(MineMazePlugin.rnd.nextInt(plugin.getMazeGenerators().size()));
        }

        if (mazeGen == null)
            throw new MineMazeException("Could not find the choosen mazegenerator");

        if (!validateRegion(r, mazeGen)) {
            throw new MineMazeException("Your selection doesn't fit the requirements!");
        }

        try {
            Maze maze = (Maze) mazeGen.invoke(null, player, handler, we, new Maze(r));

            EditSession edit = session.createEditSession(player);
            edit.enableQueue();
            session.tellVersion(player);
            int affected = 0;

            for (int x = 0; x < maze.getWidth(); x++) {
                for (int y = 0; y < maze.getHeight(); y++) {
                    for (int z = 0; z < maze.getLength(); z++) {
                        Vector v = new Vector(x, y, z);
                        if (edit.setBlock(r.getMinimumPoint().add(v), maze.get(v))) {
                            affected++;
                        }
                    }
                }
            }
            session.remember(edit);
            edit.flushQueue();
            we.flushBlockBag(player, edit);
            player.print(affected + " block(s) have been changed.");
        } catch (Exception e) {
            throw e.getCause();
        }
    } catch (IncompleteRegionException e) {
        player.printError("Make a region selection first.");
    } catch (NumberFormatException e) {
        player.printError("Number expected; string given.");
    } catch (MaxChangedBlocksException e) {
        player.printError("Max blocks changed in an operation reached (" + e.getBlockLimit() + ").");
    } catch (UnknownItemException e) {
        player.printError("Block name '" + e.getID() + "' was not recognized.");
    } catch (InvalidItemException e) {
        player.printError(e.getMessage());
    } catch (DisallowedItemException e) {
        player.printError("Block '" + e.getID() + "' not allowed (see WorldEdit configuration).");
    } catch (MineMazeException e) {
        player.printError(e.getMessage());
    } catch (Throwable e) {
        player.printError("Please report this error: [See console]");
        player.printRaw(e.getClass().getName() + ": " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.doubotis.restwrapper.data.JObjectResponse.java

public static JObjectResponse fromException(Exception exception, boolean showStackTrace) {
    JObjectResponse r = new JObjectResponse(false);

    StringWriter sw = null;//from w  w w . jav  a  2  s . co  m
    if (exception instanceof HTTPException && exception.getCause() != null) {
        sw = new StringWriter();
        exception.getCause().printStackTrace(new PrintWriter(sw));
    } else {
        sw = new StringWriter();
        exception.printStackTrace(new PrintWriter(sw));
    }

    if (showStackTrace)
        r.put("stacktrace", sw.toString());
    r.put("message", exception.getMessage());
    r.put("status", "ko");
    return r;
}

From source file:es.eucm.rage.realtime.PerformanceDataTest.java

static void runProducer(final Map trace) {

    try {//from   ww  w.  j  a v a  2s . c o m
        String msg = gson.toJson(trace, Map.class);
        String index = "test";
        final ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, index, msg);

        producer.send(record).get();

    } catch (Exception e) {
        assertTrue("Error sending to Kafka " + e.getMessage() + " cause " + e.getCause(), false);
    } finally {
        producer.flush();
        // producer.close();
    }
}

From source file:csiro.pidsvc.helper.Http.java

/**
 * Return specific HTTP response code and add a message to HTTP header.
 * /*  ww  w.  ja v  a  2 s .co m*/
 * @param response HttpServletResponse object.
 * @param httpResponseCode HTTP response code.
 * @param exception Exception object.
 */
public static void returnErrorCode(HttpServletResponse response, int httpResponseCode, Exception exception) {
    try {
        String message = (exception.getMessage() == null ? "" : exception.getMessage())
                + (exception.getCause() == null ? "" : "\n" + exception.getCause().getMessage());

        StringWriter sw = new StringWriter();
        exception.printStackTrace(new PrintWriter(sw));

        response.addHeader(PID_SERVICE_ERROR_HTTP_HEADER, message);
        response.addHeader(PID_SERVICE_MSG_HTTP_HEADER, sw.toString());
        response.sendError(httpResponseCode, exception.getMessage());
    } catch (IOException e) {
        _logger.debug(e);
    }
}

From source file:com.aurel.track.util.HTMLDiff.java

public static String makeDiff(String newValue, String oldValue, Locale locale) throws URISyntaxException {
    boolean htmlOut = true;
    if (newValue == null) {
        newValue = "";
    } else {/* w w w.  j  a  v a 2 s. co m*/
        newValue = newValue.replaceAll("&nbsp;", " ");
    }
    if (oldValue == null || (oldValue != null && oldValue.length() == 0)) {
        return newValue;
    } else {
        oldValue = oldValue.replaceAll("&nbsp;", " ");
    }

    try {
        SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();

        TransformerHandler result = tf.newTransformerHandler();
        StringWriter stringWriter = new StringWriter();
        result.setResult(new StreamResult(stringWriter));

        XslFilter filter = new XslFilter();

        ContentHandler postProcess = htmlOut ? filter.xsl(result, "com/aurel/track/util/htmlheader.xsl")
                : result;

        String prefix = "diff";

        HtmlCleaner cleaner = new HtmlCleaner();

        InputSource oldSource = new InputSource(new StringReader(oldValue));
        InputSource newSource = new InputSource(new StringReader(newValue));

        DomTreeBuilder oldHandler = new DomTreeBuilder();
        cleaner.cleanAndParse(oldSource, oldHandler);
        TextNodeComparator leftComparator = new TextNodeComparator(oldHandler, locale);

        DomTreeBuilder newHandler = new DomTreeBuilder();
        cleaner.cleanAndParse(newSource, newHandler);
        TextNodeComparator rightComparator = new TextNodeComparator(newHandler, locale);

        postProcess.startDocument();
        postProcess.startElement("", "diffreport", "diffreport", new AttributesImpl());
        postProcess.startElement("", "diff", "diff", new AttributesImpl());
        HtmlSaxDiffOutput output = new HtmlSaxDiffOutput(postProcess, prefix);

        HTMLDiffer differ = new HTMLDiffer(output);
        differ.diff(leftComparator, rightComparator);
        postProcess.endElement("", "diff", "diff");
        postProcess.endElement("", "diffreport", "diffreport");
        postProcess.endDocument();
        return stringWriter.toString();
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
        if (e.getCause() != null) {
            LOGGER.error(ExceptionUtils.getStackTrace(e.getCause()));
        }
        if (e instanceof SAXException) {
            LOGGER.error(ExceptionUtils.getStackTrace(((SAXException) e).getException()));
        }
    }
    return null;
}

From source file:com.infinities.skyport.timeout.ServiceProviderTimeLimiter.java

private static Exception throwCause(Exception e, boolean combineStackTraces) throws Exception {
    Throwable cause = e.getCause();
    if (cause == null) {
        throw e;//from   w  w  w . j av a2  s .  c  o  m
    }
    if (combineStackTraces) {
        StackTraceElement[] combined = ObjectArrays.concat(cause.getStackTrace(), e.getStackTrace(),
                StackTraceElement.class);
        cause.setStackTrace(combined);
    }
    if (cause instanceof Exception) {
        throw (Exception) cause;
    }
    if (cause instanceof Error) {
        throw (Error) cause;
    }
    // The cause is a weird kind of Throwable, so throw the outer exception.
    throw e;
}

From source file:com.taobao.datax.engine.tools.JobConfGenDriver.java

private static int genXmlFile(String filename, ClassNode reader, ClassNode writer) throws IOException {

    Document document = DocumentHelper.createDocument();
    Element jobsElement = document.addElement("jobs");
    Element jobElement = jobsElement.addElement("job");
    String id = reader.getName() + "_to_" + writer.getName() + "_job";
    jobElement.addAttribute("id", id);

    /**/*w w  w . j  a v a2 s.c  o m*/
     * ?readerxml
     */
    Element readerElement = jobElement.addElement("reader");
    Element plugin_Element = readerElement.addElement("plugin");
    plugin_Element.setText(reader.getName());

    ClassNode readerNode = reader;
    Element tempElement = null;

    List<ClassMember> members = readerNode.getAllMembers();
    for (ClassMember member : members) {
        StringBuilder command = new StringBuilder("\n");

        Set<String> set = member.getAllKeys();
        String value = "";
        for (String key : set) {
            value = member.getAttr("default");
            command.append(key).append(":").append(member.getAttr(key)).append("\n");
        }
        readerElement.addComment(command.toString());

        String keyName = member.getName();
        keyName = keyName.substring(1, keyName.length() - 1);
        tempElement = readerElement.addElement("param");
        tempElement.addAttribute("key", keyName);

        if (value == null || "".equals(value)) {
            value = "?";
        }
        tempElement.addAttribute("value", value);
    }

    /**
     * ?writerxml
     */
    Element writerElement = jobElement.addElement("writer");
    plugin_Element = writerElement.addElement("plugin");
    plugin_Element.setText(writer.getName());

    members = writer.getAllMembers();
    for (ClassMember member : members) {
        StringBuilder command = new StringBuilder("\n");
        Set<String> set = member.getAllKeys();

        String value = "";
        for (String key : set) {
            value = member.getAttr("default");
            command.append(key).append(":").append(member.getAttr(key)).append("\n");
        }
        writerElement.addComment(command.toString());

        String keyName = member.getName();
        keyName = keyName.substring(1, keyName.length() - 1);
        tempElement = writerElement.addElement("param");
        tempElement.addAttribute("key", keyName);

        if (value == null || "".equals(value)) {
            value = "?";
        }
        tempElement.addAttribute("value", value);
    }

    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writerOfXML = new XMLWriter(new FileWriter(new File(filename)), format);
        writerOfXML.write(document);
        writerOfXML.close();
    } catch (Exception ex) {
        throw new IOException(ex.getCause());
    }

    return 0;
}