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.chiorichan.factory.ScriptingFactory.java

public ScriptingResult eval(ScriptingContext context) {
    ScriptingResult result = context.result();

    context.factory(this);
    context.charset(charset);//from w ww.j  a v a2 s.c om
    context.baseSource(new String(context.readBytes(), charset));
    binding.setVariable("__FILE__", context.filename() == null ? "<no file>" : context.filename());

    if (result.hasNonIgnorableExceptions())
        return result;

    try {
        String name = "EvalScript" + SecureFunc.rand(8) + ".chi";
        if (!context.isVirtual()) {
            String rel = FileFunc.relPath(context.file().getParentFile(), context.site().directory())
                    .replace('\\', '.').replace('/', '.');
            context.cache(
                    new File(context.cache(), rel.contains(".") ? rel.substring(0, rel.indexOf(".")) : rel));
            context.scriptPackage(rel.contains(".") ? rel.substring(rel.indexOf(".") + 1) : "");
            name = context.file().getName();
        }

        context.scriptName(name);
        stackFactory.stack(name, context);

        PreEvalEvent preEvent = new PreEvalEvent(context);
        try {
            EventBus.instance().callEventWithException(preEvent);
        } catch (Exception e) {
            if (context.result().handleException(e.getCause() == null ? e : e.getCause(), context))
                return result;
        }

        if (preEvent.isCancelled())
            if (context.result().handleException(new ScriptingException(ReportingLevel.E_ERROR,
                    "Evaluation was cancelled by an internal event"), context))
                return result;

        if (engines.size() == 0)
            compileEngines(context);

        if (engines.size() > 0)
            for (Entry<ScriptingEngine, List<String>> entry : engines.entrySet())
                if (entry.getValue() == null || entry.getValue().isEmpty()
                        || entry.getValue().contains(context.shell().toLowerCase()))
                    try {
                        bufferStack.add(output.copy());
                        output.clear();
                        String hash = context.bufferHash();
                        entry.getKey().eval(context);
                        if (context.bufferHash().equals(hash))
                            context.resetAndWrite(output);
                        else
                            context.write(output);
                        output.clear();
                        output.writeBytes(bufferStack.remove(bufferStack.size() - 1));
                        break;
                    } catch (Throwable cause) {
                        if (context.result().handleException(cause, context))
                            return result;
                    }

        PostEvalEvent postEvent = new PostEvalEvent(context);
        try {
            EventBus.instance().callEventWithException(postEvent);
        } catch (EventException e) {
            if (context.result().handleException(e.getCause() == null ? e : e.getCause(), context))
                return result;
        }
    } finally {
        stackFactory.unstack();
    }

    return result.success(true);
}

From source file:com.gisgraphy.fulltext.FullTextSearchEngine.java

public List<? extends GisFeature> executeQueryToDatabaseObjects(FulltextQuery query) throws ServiceException {
    statsUsageService.increaseUsage(StatsUsageType.FULLTEXT);
    Assert.notNull(query, "Can not execute a null query");
    String queryString = ZipcodeNormalizer.normalize(query.getQuery(), query.getCountryCode());
    query.withQuery(queryString);/*from  www  .  jav a  2s. co m*/
    ModifiableSolrParams params = FulltextQuerySolrHelper.parameterize(query);
    List<GisFeature> gisFeatureList = new ArrayList<GisFeature>();
    QueryResponse results = null;
    try {
        results = solrClient.getServer().query(params);
        if (!disableLogging) {
            logger.info(query + " took " + (results.getQTime()) + " ms and returns "
                    + results.getResults().getNumFound() + " results");
        }

        List<Long> ids = new ArrayList<Long>();
        for (SolrDocument doc : results.getResults()) {
            ids.add((Long) doc.getFieldValue(FullTextFields.FEATUREID.getValue()));
        }

        gisFeatureList = gisFeatureDao.listByFeatureIds(ids);
    } catch (Exception e) {
        logger.error("An error has occurred during fulltext search to database object for query " + query
                + " : " + e.getCause().getMessage(), e);
        throw new FullTextSearchException(e);
    }

    return gisFeatureList;
}

From source file:com.quatico.base.aem.test.api.builders.AbstractBuilder.java

@Override
public T build() throws Exception {
    T value = getResult();/*from  w ww  .  j a  v  a 2 s  .  c o  m*/
    try {
        children.values().forEach(cur -> cur.forEach(builder -> {
            try {
                builder.build();
            } catch (ClassCastException ignored) {
                // continue with remaining
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }));
    } catch (RuntimeException ex) {
        throw (Exception) ex.getCause();
    }

    if (value != null) {
        result = value;
    } else {
        result = internalBuild();
    }
    return result;
}

From source file:net.orfjackal.retrolambda.test.TryWithResourcesTest.java

@Test
public void suppressed_exceptions() {
    Exception thrown;
    try {//from  ww  w  .j av  a 2s.co  m
        try (ThrowSecondaryExceptionOnClose c = new ThrowSecondaryExceptionOnClose()) {
            throw new PrimaryException();
        }
    } catch (Exception e) {
        thrown = e;
    }

    assertThat("thrown", thrown, is(instanceOf(PrimaryException.class)));
    assertThat("cause", thrown.getCause(), is(nullValue()));

    // On Java 6 and lower we will swallow the suppressed exception, because the API does not exist,
    // but on Java 7 we want to keep the original behavior.
    if (SystemUtils.isJavaVersionAtLeast(1.7f)) {
        assertThat("suppressed", thrown.getSuppressed(), arrayContaining(instanceOf(SecondaryException.class)));
    }
}

From source file:com.capitalone.dashboard.client.team.TeamDataClientImpl.java

/**
 * Updates the MongoDB with a JSONArray received from the source system
 * back-end with story-based data.//  w  ww .ja v a  2 s  .c  om
 * 
 * @param tmpMongoDetailArray
 *            A JSON response in JSONArray format from the source system
 * @param featureCollector
 * @return
 * @return
 */
protected void updateMongoInfo(JSONArray tmpMongoDetailArray) {
    try {
        JSONObject dataMainObj = new JSONObject();
        for (int i = 0; i < tmpMongoDetailArray.size(); i++) {
            if (dataMainObj != null) {
                dataMainObj.clear();
            }
            dataMainObj = (JSONObject) tmpMongoDetailArray.get(i);
            ScopeOwnerCollectorItem team = new ScopeOwnerCollectorItem();

            /*
             * Checks to see if the available asset state is not active from
             * the V1 Response and removes it if it exists and not active:
             */
            if (!TOOLS.sanitizeResponse((String) dataMainObj.get("AssetState")).equalsIgnoreCase("Active")) {

                this.removeInactiveScopeOwnerByTeamId(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid")));

            } else {
                boolean deleted = this
                        .removeExistingEntity(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid")));
                // Id
                if (deleted) {
                    team.setId(this.getOldTeamId());
                    team.setEnabled(this.isOldTeamEnabledState());
                }

                // collectorId
                team.setCollectorId(featureCollectorRepository.findByName(Constants.VERSIONONE).getId());

                // teamId
                team.setTeamId(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid")));

                // name
                team.setName(TOOLS.sanitizeResponse((String) dataMainObj.get("Name")));

                // changeDate;
                team.setChangeDate(
                        TOOLS.toCanonicalDate(TOOLS.sanitizeResponse((String) dataMainObj.get("ChangeDate"))));

                // assetState
                team.setAssetState(TOOLS.sanitizeResponse((String) dataMainObj.get("AssetState")));

                // isDeleted;
                team.setIsDeleted(TOOLS.sanitizeResponse((String) dataMainObj.get("IsDeleted")));

                try {
                    teamRepo.save(team);
                } catch (Exception e) {
                    LOGGER.error(
                            "Unexpected error caused when attempting to save data\nCaused by: " + e.getCause(),
                            e);
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("FAILED: " + e.getMessage() + ", " + e.getClass(), e);
    }
}

From source file:co.turnus.trace.io.XmlTraceStreamWriter.java

public void close() {
    try {/* w  w  w  . j  a  v a  2  s.  co  m*/
        writeEndDocument();
        writer.flush();
        writer.close();
        stream.close();
    } catch (Exception e) {
        throw new TurnusRuntimeException("Trace Writer Error: " + e.getLocalizedMessage(), e.getCause());
    }
}

From source file:eu.learnpad.simulator.mon.rules.DroolsRulesManager.java

@Override
public void insertRule(final String rule, final String ruleName)
        throws IncorrectRuleFormatException, UnknownMethodCallRuleException {
    try {//  ww  w.j a v a2 s.  c o  m
        Long now = System.currentTimeMillis();
        kbuilder.add(ResourceFactory.newByteArrayResource(rule.trim().getBytes()), ResourceType.DRL);
        DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Time Elapsed for loading one rule: " + (System.currentTimeMillis() - now));
    } catch (Exception droolsExceptionOnLoading) {
        DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getCanonicalName(),
                droolsExceptionOnLoading.getCause() + "\n" + droolsExceptionOnLoading.getMessage());
        throw new UnknownMethodCallRuleException();
    }

    if (kbuilder.getErrors().size() > 0)
        throw new IncorrectRuleFormatException(kbuilder.getErrors());
}

From source file:co.turnus.trace.io.XmlTraceStreamWriter.java

private void writeEndDocument() {
    try {//  w  w w  . j  a v  a  2s. c  om
        // </trace>
        writer.writeEndElement();
        // close the document
        writer.writeEndDocument();

    } catch (Exception e) {

        throw new TurnusRuntimeException("Trace Writer Error: " + e.getLocalizedMessage(), e.getCause());
    }
}

From source file:com.liferay.faces.bridge.model.UploadedFileFactoryImpl.java

@Override
public UploadedFile getUploadedFile(Exception e) {

    UploadedFile uploadedFile = null;// ww  w.j  ava 2 s . c  o  m
    FileUploadException fileUploadException = null;

    if (e instanceof FileUploadException) {
        fileUploadException = (FileUploadException) e;
    }

    if (e instanceof FileUploadIOException) {
        Throwable causeThrowable = e.getCause();

        if (causeThrowable instanceof FileUploadException) {
            fileUploadException = (FileUploadException) causeThrowable;
        }
    }

    if (fileUploadException != null) {

        if (fileUploadException instanceof SizeLimitExceededException) {
            uploadedFile = new UploadedFileErrorImpl(fileUploadException.getMessage(),
                    UploadedFile.Status.REQUEST_SIZE_LIMIT_EXCEEDED);
        } else if (fileUploadException instanceof FileSizeLimitExceededException) {
            uploadedFile = new UploadedFileErrorImpl(fileUploadException.getMessage(),
                    UploadedFile.Status.FILE_SIZE_LIMIT_EXCEEDED);
        } else {
            uploadedFile = new UploadedFileErrorImpl(fileUploadException.getMessage());
        }
    } else {
        uploadedFile = new UploadedFileErrorImpl(e.getMessage());
    }

    return uploadedFile;
}

From source file:com.ms.commons.summer.web.handler.ComponentMethodHandlerAdapter.java

@SuppressWarnings("unchecked")
private Object invokeNamedMethod(Object handle, Method method, ExtendedModelMap model,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    Object object = checkToken(handle, method, model, request, response);
    if (object != null) {
        return object;
    }//from  ww w. ja  v a 2  s.  c  o m
    Object[] args = DataBinderUtil.getArgs(method, model, request, response, this.getClass());
    // 
    try {
        return method.invoke(handle, args);
    } catch (Exception e) {
        Throwable cause = e.getCause();
        if (cause != null && cause instanceof Exception) {
            throw (Exception) cause;
        }
        throw e;
    }
}