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:org.apache.usergrid.java.client.response.UsergridResponse.java

@NotNull
public static UsergridResponse fromException(@Nullable final UsergridClient client,
        @NotNull final Exception ex) {
    final UsergridResponse response = new UsergridResponse();
    response.client = client;/*w  w  w .ja v  a  2s.  c o m*/
    final UsergridResponseError responseError = new UsergridResponseError();
    responseError.setErrorDescription(ex.getMessage());
    if (ex.getClass() != null) {
        responseError.setErrorName(ex.getClass().toString());
    }
    if (ex.getCause() != null) {
        responseError.setErrorException(ex.getCause().toString());
    }
    response.responseError = responseError;
    return response;
}

From source file:fr.paris.lutece.portal.service.search.IndexationService.java

/**
 * Log an exception/* w ww.ja v a2  s  .com*/
 * @param strTitle The title of the error
 * @param e The exception to log
 * @param strMessage The message
 */
private static void error(String strTitle, Exception e, String strMessage) {
    _sbLogs.append("<strong class=\"alert\">");
    _sbLogs.append(strTitle);
    _sbLogs.append(" - ERROR : ");
    _sbLogs.append(e.getMessage());

    if (e.getCause() != null) {
        _sbLogs.append(" : ");
        _sbLogs.append(e.getCause().getMessage());
    }

    if (StringUtils.isNotBlank(strMessage)) {
        _sbLogs.append(" - ").append(strMessage);
    }

    _sbLogs.append("</strong>\r\n");
    AppLogService.error("Indexing error : " + e.getMessage(), e);
}

From source file:com.stimulus.archiva.service.MessageService.java

protected static void archive(Principal principal, Email message, boolean retry) throws Exception {

    if (Config.getShutdown()) {
        throw new ArchiveException(Config.getConfig().getProductName() + " is shutdown",
                ArchiveException.RecoveryDirective.RETRYLATER);
    }//ww  w.  ja va  2 s . co  m

    Volumes vols = Config.getConfig().getVolumes();

    try {
        if (Config.getConfig().getArchiver().insertMessage(message)) {
            try {
                Config.getConfig().getIndex().indexMessage(message);
            } catch (OutOfMemoryError ofme) {
                logger.debug("failed index message: out of memory", ofme);
            } catch (Throwable t) {
                logger.debug("failed index message:" + t.getMessage(), t);
            }
        }
    } catch (Exception e) {
        if (e.getCause() instanceof IOException && e.getMessage().contains("space")) {
            logger.error("must close volume (out of disk space)", e);
            closeVolume(vols, message.getEmailID().getVolume());
            if (!retry)
                archive(principal, message, true); // retry
        }
        audit.error("fail archive email {" + message + ", " + principal + "}");
        throw e;
    }
    audit.info("archive email {" + message + ", " + principal + "}");
    logger.debug("archive email {" + message + ", " + principal + "}");
}

From source file:io.hummer.util.ws.AbstractNode.java

@SuppressWarnings("all")
public static void deploy(final Object service, String url, Handler<?>... handler)
        throws AbstractNodeException {

    long t1 = System.currentTimeMillis();

    try {// w  ww.  j a va  2  s. c o  m

        URL u = new URL(url);

        if (strUtil.isEmpty(System.getProperty(SYSPROP_HTTP_SERVER_PROVIDER_CLASS))) {
            System.setProperty(SYSPROP_HTTP_SERVER_PROVIDER_CLASS, JettyHttpServerProvider.class.getName());
        }

        ContextHandlerCollection chc = new ContextHandlerCollection();

        // disable log output from Metro and Jetty
        java.util.logging.Logger.getAnonymousLogger().getParent().setLevel(Level.WARNING);
        Class<?> cls3 = org.eclipse.jetty.server.Server.class;
        Class<?> cls4 = org.eclipse.jetty.server.AbstractConnector.class;
        org.apache.log4j.Level lev3 = Logger.getLogger(cls3).getLevel();
        org.apache.log4j.Level lev4 = Logger.getLogger(cls4).getLevel();
        Logger.getLogger(cls3).setLevel(org.apache.log4j.Level.WARN);
        Logger.getLogger(cls4).setLevel(org.apache.log4j.Level.WARN);

        JettyHttpServer httpServer = httpServers.get(u.getPort());
        Server server = servers.get(u.getPort());
        if (httpServer == null) {
            org.eclipse.jetty.util.log.Log.setLog(new Slf4jLog());
            server = new Server(u.getPort());

            SelectChannelConnector connector = new SelectChannelConnector();
            connector.setPort(u.getPort());
            connector.setAcceptQueueSize(1000);
            connector.setThreadPool(new ExecutorThreadPool(GlobalThreadPool.getExecutorService()));
            server.setConnectors(new Connector[] { connector });

            server.setHandler(chc);

            httpServer = new JettyHttpServer(server, true);

            httpServers.put(u.getPort(), httpServer);
            servers.put(u.getPort(), server);

            if (!server.isStarted())
                server.start();
        }

        JettyHttpContext wsContext1 = (JettyHttpContext) httpServer.createContext(u.getPath());
        Endpoint endpoint = Endpoint.create(service);
        if (service instanceof AbstractNode) {
            if (((AbstractNode) service).endpoint != null)
                logger.warn("AbstractNode " + service + " has apparently been double-deployed, "
                        + "because there already exists an endpoint for this instance.");
            ((AbstractNode) service).endpoint = endpoint;
        }

        // add JAX-WS handlers (e.g., needed for TeCoS invocation intercepting...)
        List<Handler> handlers = endpoint.getBinding().getHandlerChain();
        handlers.addAll(Arrays.asList(handler));
        endpoint.getBinding().setHandlerChain(handlers);
        if (service instanceof AbstractNode) {
            AbstractNode a = (AbstractNode) service;
            for (Handler h : handlers)
                if (!a.activeHandlers.contains(h))
                    a.activeHandlers.add(h);
        }

        Class<?> cls1 = org.eclipse.jetty.util.component.AbstractLifeCycle.class;
        Class<?> cls2 = org.eclipse.jetty.server.handler.ContextHandler.class;
        org.apache.log4j.Level lev1 = Logger.getLogger(cls1).getLevel();
        org.apache.log4j.Level lev2 = Logger.getLogger(cls2).getLevel();
        try {
            String bindUrl = u.getProtocol() + "://0.0.0.0:" + u.getPort() + u.getPath();
            if (u.getQuery() != null) {
                bindUrl += "?" + u.getQuery();
            }
            Logger.getLogger(cls1).setLevel(org.apache.log4j.Level.OFF);
            Logger.getLogger(cls2).setLevel(org.apache.log4j.Level.WARN);
            logger.info("Binding service to " + bindUrl);
            endpoint.publish(bindUrl);
        } catch (Exception e) {
            if (e instanceof BindException || (e.getCause() != null && e.getCause() instanceof BindException)
                    || (e.getCause() != null && e.getCause().getCause() != null
                            && e.getCause().getCause() instanceof BindException)) {
                /** we expect a BindException here, just swallow */
            } else {
                logger.warn("Unexpected error.", e);
            }
        } finally {
            Logger.getLogger(cls1).setLevel(lev1);
            Logger.getLogger(cls2).setLevel(lev2);
            Logger.getLogger(cls3).setLevel(lev3);
            Logger.getLogger(cls4).setLevel(lev4);
        }

        Field f = endpoint.getClass().getDeclaredField("actualEndpoint");
        f.setAccessible(true);

        // DO NOT do this (the two lines below), because HttpEndpoint creates some nasty 
        // compile-time dependencies with respect to JAXWS-RT. At runtime, we can (hopefully) 
        // assume that this class is present, in all newer Sun JVM implementations..
        //HttpEndpoint httpEndpoint = (HttpEndpoint)f.get(e1);
        //httpEndpoint.publish(wsContext1);
        Object httpEndpoint = f.get(endpoint);
        httpEndpoint.getClass().getMethod("publish", Object.class).invoke(httpEndpoint, wsContext1);

        Endpoint e2 = Endpoint.create(new CrossdomainXML());
        JettyHttpContext wsContext2 = (JettyHttpContext) httpServer.createContext("/crossdomain.xml");
        e2.publish(wsContext2);

        // Also deploy as RESTful service..
        if (service instanceof AbstractNode) {
            AbstractNode node = (AbstractNode) service;
            if (node.isRESTfulService()) {
                String path = u.getPath();
                if (!path.contains("/"))
                    path = "/";
                path = "/rest";
                String wadlURL = netUtil.getUrlBeforePath(u) + path + "/application.wadl";
                if (logger.isDebugEnabled())
                    logger.debug("Deploying node as RESTful service: " + wadlURL);
                JettyHttpContext wsContext3 = (JettyHttpContext) httpServer.createContext(path);

                ResourceConfig rc = new PackagesResourceConfig(service.getClass().getPackage().getName(),
                        AbstractNode.class.getPackage().getName());
                HttpHandler h = RuntimeDelegate.getInstance().createEndpoint(rc, HttpHandler.class);
                wsContext3.setHandler(h);
                node.setWadlURL(wadlURL);
            }
            deployedNodes.put(url, node);
        }

        final HttpHandler h = wsContext1.getHandler();
        wsContext1.setHandler(new HttpHandler() {
            public void handle(com.sun.net.httpserver.HttpExchange ex) throws IOException {

                if (!ex.getRequestMethod().equals("OPTIONS")) {
                    addCORSHeaders(ex);
                    h.handle(ex);
                    //System.out.println(ex.getRequestMethod() + ": " + ex.getResponseHeaders() + " - " + new HashMap<>(ex.getResponseHeaders()));
                    return;
                }

                if (ex.getRequestMethod().equals("OPTIONS")) {
                    addCORSHeaders(ex);
                    ex.sendResponseHeaders(200, -1);
                    ex.getResponseBody().close();
                    return;
                }
                //System.out.println(new HashMap<>(ex.getResponseHeaders()));
            }
        });

        // add shutdown task for this node
        if (service instanceof AbstractNode) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    try {
                        Runnable r = ((AbstractNode) service).getTerminateTask(null);
                        if (r != null)
                            r.run();
                    } catch (Exception e) {
                    }
                }
            });
        }

    } catch (Exception e) {
        throw new AbstractNodeException(e);
    }

    long diff = System.currentTimeMillis() - t1;
    logger.info("Deployment took " + diff + "ms");

}

From source file:cn.quickj.Setting.java

private static void loadApplicationConfig() {
    XMLConfiguration config;/*from   w  w  w  . j a  v  a  2  s . co  m*/
    try {
        config = new XMLConfiguration();
        // ??????
        config.setDelimiterParsingDisabled(true);
        String appconfigPath = webRoot + "WEB-INF/appconfig.xml";
        config.load(appconfigPath);
    } catch (Exception e) {
        config = null;
    }
    String className = null;
    if (config != null)
        className = config.getString("class", null);
    if (className != null) {
        try {
            Class<?> clazz = Class.forName(className);
            appconfig = (ApplicationConfig) clazz.newInstance();
            appconfig.init(config);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("?appconfig.xml?!" + e.getCause());
            appconfig = null;
        }
    }
}

From source file:DDTTestRunner.java

public static void addElement(String key, WebElement value) {
    String result = "";
    String tmp = key.toLowerCase();
    try {/*from ww w  .  jav a2  s  . co  m*/
        if ((getElementsMap().get(tmp) != null))
            getElementsMap().remove(tmp);

        getElementsMap().put(tmp, value);
        result = "Element " + Util.sq(key.toLowerCase()) + " (re)set in the Elements map to "
                + Util.sq(value.toString());
    } catch (Exception e) {
        result = e.getCause().toString();
    } finally {
        System.out.println(result);
    }
}

From source file:com.ctrip.infosec.rule.resource.Counter.java

/**
 * /*from   w  w w  . j a  va  2  s .  co  m*/
 *
 * @param policyNo ?
 * @param kvData ?
 * @return
 */
public static PolicyExecuteResponse execute(String policyNo, Map<String, ?> kvData) {
    check();
    beforeInvoke("Counter.execute");
    PolicyExecuteResponse response = null;
    PolicyExecuteRequest policyExecuteRequest = new PolicyExecuteRequest();
    policyExecuteRequest.setPolicyNo(policyNo);
    policyExecuteRequest.setKvData(kvData);
    try {
        // TraceLogger
        if (StringUtils.isNotBlank(TraceLogger.getEventId())
                && StringUtils.isNotBlank(TraceLogger.getTransId())) {

            TraceLoggerHeader header = new TraceLoggerHeader();
            header.setEventId(TraceLogger.getEventId());
            if (TraceLogger.hasNestedTrans()) {
                header.setParentTransId(TraceLogger.getNestedTransId());
            } else {
                header.setParentTransId(TraceLogger.getTransId());
            }
            policyExecuteRequest.setTraceLoggerHeader(header);
        }

        //            if (Contexts.isAsync()) {
        //                String responseTxt = Request.Post(urlPrefix + "/rest/execute")
        //                        .addHeader("Content-Type", "application/json")
        //                        .addHeader("Accept-Encoding", "utf-8")
        //                        .bodyString(JSON.toJSONString(policyExecuteRequest), ContentType.APPLICATION_JSON)
        //                        .connectTimeout(1000)
        //                        .socketTimeout(5000)
        //                        .execute().returnContent().asString();
        //                response = JSON.parseObject(responseTxt, PolicyExecuteResponse.class);
        //            } else {
        //                FlowPolicyRemoteServiceV2 flowPolicyRemoteService = SpringContextHolder.getBean(FlowPolicyRemoteServiceV2.class);
        //                response = flowPolicyRemoteService.execute(policyExecuteRequest);
        //            }
        CounterExecuteCommand command = new CounterExecuteCommand(policyExecuteRequest, Contexts.isAsync());
        response = command.execute();

    } catch (Exception ex) {
        fault("Counter.execute");
        logger.error(Contexts.getLogPrefix() + "Counter.execute.", ex);
        TraceLogger.traceLog(
                ">> [" + policyExecuteRequest.getPolicyNo() + "] Counter.execute. "
                        + (ex.getCause() != null ? ex.getCause().toString() : ex.toString()));
        response = new PolicyExecuteResponse();
        response.setErrorCode(ErrorCode.EXCEPTION.getCode());
        response.setErrorMessage(ex.getMessage());
    } finally {
        afterInvoke("Counter.execute");
    }
    return response;
}

From source file:com.ctrip.infosec.rule.resource.Counter.java

public static FlowQueryResponse queryFlowData(FlowQueryRequest flowQueryRequest) {
    check();//from   w w  w.j  a v  a  2  s.  c o m
    beforeInvoke("Counter.queryFlowData");
    FlowQueryResponse response = null;
    try {

        // TraceLogger
        if (StringUtils.isNotBlank(TraceLogger.getEventId())
                && StringUtils.isNotBlank(TraceLogger.getTransId())) {

            TraceLoggerHeader header = new TraceLoggerHeader();
            header.setEventId(TraceLogger.getEventId());
            if (TraceLogger.hasNestedTrans()) {
                header.setParentTransId(TraceLogger.getNestedTransId());
            } else {
                header.setParentTransId(TraceLogger.getTransId());
            }
            flowQueryRequest.setTraceLoggerHeader(header);
        }

        // PolicyOrRuleNo
        if (StringUtils.isNotBlank(Contexts.getPolicyOrRuleNo())) {
            flowQueryRequest.setPolicyOrRuleNo(Contexts.getPolicyOrRuleNo());
        }

        //            if (Contexts.isAsync()) {
        //                String responseTxt = Request.Post(urlPrefix + "/rest/queryFlowData")
        //                        .addHeader("Content-Type", "application/json")
        //                        .addHeader("Accept-Encoding", "utf-8")
        //                        .bodyString(JSON.toJSONString(flowQueryRequest), ContentType.APPLICATION_JSON)
        //                        .connectTimeout(1000)
        //                        .socketTimeout(5000)
        //                        .execute().returnContent().asString();
        //                response = JSON.parseObject(responseTxt, FlowQueryResponse.class);
        //            } else {
        //                FlowPolicyRemoteServiceV2 flowPolicyRemoteService = SpringContextHolder.getBean(FlowPolicyRemoteServiceV2.class);
        //                response = flowPolicyRemoteService.queryFlowData(flowQueryRequest);
        //            }
        CounterQueryFlowDataCommand command = new CounterQueryFlowDataCommand(flowQueryRequest,
                Contexts.isAsync());
        response = command.execute();

    } catch (Exception ex) {
        fault("Counter.queryFlowData");
        logger.error(Contexts.getLogPrefix() + "Counter.queryFlowData.", ex);
        TraceLogger.traceLog(
                ">> [" + flowQueryRequest.getFlowNo() + "] Counter.queryFlowData. "
                        + (ex.getCause() != null ? ex.getCause().toString() : ex.toString()));
        response = new FlowQueryResponse();
        response.setErrorCode(ErrorCode.EXCEPTION.getCode());
        response.setErrorMessage(ex.getMessage());
    } finally {
        afterInvoke("Counter.queryFlowData");
    }
    return response;
}

From source file:com.emcopentechnologies.viprcloudstorage.WAStorageClient.java

/**
 * Blob download from storage/*from  w  w  w.j  a  v  a 2 s.  c  o m*/
 * 
 * @param blob
 * @param downloadDir
 * @param listener
 * @throws URISyntaxException
 * @throws StorageException
 * @throws IOException
 * @throws InterruptedException
 */
private static void downloadBlob(CloudBlob blob, FilePath downloadDir, BuildListener listener)
        throws WAStorageException {
    OutputStream fos = null;
    try {
        FilePath downloadFile = new FilePath(downloadDir, blob.getName());

        // fos = new FileOutputStream(downloadDir + File.separator +
        // blob.getName());
        fos = downloadFile.write();

        long startTime = System.currentTimeMillis();

        blob.download(fos, null, getBlobRequestOptions(), null);

        long endTime = System.currentTimeMillis();

        listener.getLogger().println("blob " + blob.getName() + " is downloaded to " + downloadDir + " in "
                + getTime(endTime - startTime));
    } catch (Exception e) {
        e.printStackTrace();
        throw new WAStorageException(e.getMessage(), e.getCause());
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {

        }

    }

}

From source file:com.emcopentechnologies.viprcloudstorage.WAStorageClient.java

/**
 * Downloads from Cloud blob//  w ww  .ja va 2s . c  o m
 * 
 * @param build
 * @param listener
 * @param strAcc
 * @param expContainerName
 * @param blobName
 * @param downloadDirLoc
 * @return
 * @throws WAStorageException
 */
public static int download(AbstractBuild<?, ?> build, BuildListener listener, StorageAccountInfo strAcc,
        String expContainerName, String blobName, String downloadDirLoc) throws WAStorageException {

    int filesDownloaded = 0;
    FilePath downloadDir = null;

    try {
        FilePath workspacePath = build.getWorkspace();
        if (workspacePath == null) {
            listener.getLogger().println(Messages.CloudStorageBuilder_ws_na());
            return filesDownloaded;
        }

        if (Utils.isNullOrEmpty(downloadDirLoc)) {
            downloadDir = workspacePath;
        } else {
            downloadDir = new FilePath(workspacePath, downloadDirLoc);
        }

        if (!downloadDir.exists()) {
            downloadDir.mkdirs();
        }

        listener.getLogger().println(Messages.CloudStorageBuilder_downloading());

        CloudBlobContainer container = WAStorageClient.getBlobContainerReference(strAcc.getStorageAccName(),
                strAcc.getStorageAccountKey(), strAcc.getBlobEndPointURL(), expContainerName, false, true,
                null);

        filesDownloaded = downloadBlobs(container, blobName, downloadDir, listener);

    } catch (Exception e) {
        e.printStackTrace();
        throw new WAStorageException(e.getMessage(), e.getCause());
    }
    return filesDownloaded;

}