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.greenpepper.runner.CommandLineRunnerTest.java

@Test
public void testThatDebugModeAllowToSeeWholeStackTrace() throws Exception {

    String input = getResourcePath("/specs/ABankSample.html");
    File outputFile = outputFile("report.html");

    CommandLineRunner commandLineRunner = new CommandLineRunner();
    commandLineRunner.run("--debug", input, outputFile.getAbsolutePath());

    try {/*w  ww  .ja v a  2  s .  co  m*/
        throw new Exception(new Throwable(""));
    } catch (Exception e) {
        assertTrue(countLines(ExceptionUtils.stackTrace(e.getCause(), "\n", 2)) > 2 + 1);
    }

}

From source file:com.alliander.osgp.adapter.protocol.oslp.elster.infra.networking.OslpChannelHandlerClient.java

private void write(final ChannelFuture channelFuture, final InetSocketAddress address,
        final OslpEnvelope request) throws IOException {
    final Channel channel = channelFuture.getChannel();

    if (channel != null && channel.isConnected()) {
        LOGGER.info("{} Connection established to: {}", channelFuture.getChannel().getId(), address);
    } else {//from w w  w.j  av a 2s  .  co m
        LOGGER.info("The connection for device {} is not successfull", request.getDeviceId());
        LOGGER.warn("{} Unable to connect to: {}", channelFuture.getChannel().getId(), address);
        throw new IOException("Channel - Unable to connect");
    }

    try {
        channel.write(request);

    } catch (final Exception e) {
        LOGGER.error("{} Exception while writing request: {}", channelFuture.getChannel().getId(), e.getCause(),
                e);
        this.callbackHandlers.remove(channel.getId());

        throw e;
    }
}

From source file:com.taobao.datax.plugins.reader.sqlserverreader.SqlServerReader.java

@Override
public int prepare(PluginParam param) {
    try {//from w  w  w .  j  a v  a  2 s  . c om
        DBSource.register(this.getClass(), this.ip, this.port, this.database, this.genProperties());
    } catch (Exception e) {
        logger.error(ExceptionTracker.trace(e));
        throw new DataExchangeException(e.getCause());
    }
    return PluginStatus.SUCCESS.value();
}

From source file:com.taobao.datax.plugins.reader.sqlserverreader.SqlServerReader.java

@Override
public int connect() {
    try {//from  w  ww .  j ava  2s.  c  o  m
        this.connection = DBSource.getConnection(this.getClass(), this.ip, this.port, this.database);
    } catch (Exception e) {
        logger.error(ExceptionTracker.trace(e));
        throw new DataExchangeException(e.getCause());
    }
    return PluginStatus.SUCCESS.value();
}

From source file:gov.gtas.job.scheduler.LoaderScheduler.java

/**
 * Loader Scheduler running on configured schedule
 *///w w w.ja  v a 2  s. c  o m
@Scheduled(fixedDelayString = "${loader.fixedDelay.in.milliseconds}", initialDelayString = "${loader.initialDelay.in.milliseconds}")
public void jobScheduling() {
    logger.info("entering jobScheduling()");

    boolean exitStatus = false;
    Path dInputDir = Paths.get(messageOriginDir).normalize();
    File inputDirFile = dInputDir.toFile();
    Path dOutputDir = Paths.get(messageProcessedDir).normalize();
    File outputDirFile = dOutputDir.toFile();

    if (!inputDirFile.exists() || !outputDirFile.exists()) {
        logger.error("directory does not exist.");
        Exception fileNotExist = new RuntimeException("directory does not exist.");
        ErrorDetailInfo errInfo = ErrorHandlerFactory.createErrorDetails(fileNotExist);
        errorPersistenceService.create(errInfo);
        exitStatus = true;
    } else if (!inputDirFile.isDirectory() || !outputDirFile.isDirectory()) {
        logger.error("Not a directory: '" + inputDirFile + "'");
        Exception notADirectory = new RuntimeException("Not a directory.");
        ErrorDetailInfo errInfo = ErrorHandlerFactory.createErrorDetails(notADirectory);
        errorPersistenceService.create(errInfo);
        exitStatus = true;
    }
    if (exitStatus) {
        Thread.currentThread().interrupt();
    }

    LoaderStatistics stats = new LoaderStatistics();
    if (inputType.equalsIgnoreCase(InputType.TWO_DIRS.name())) {
        processInputAndOutputDirectories(dInputDir, dOutputDir, stats);
    } else {
        logger.warn("No inputType selection.");
    }
    writeAuditLog(stats);

    logger.info("entering rule running portion of jobScheduling()");
    try {
        targetingService.preProcessing();
        Set<Long> uniqueFlights = targetingService.runningRuleEngine();
    } catch (Exception exception) {
        logger.error(exception.getCause().getMessage());
        ErrorDetailInfo errInfo = ErrorHandlerFactory
                .createErrorDetails(RuleServiceConstants.RULE_ENGINE_RUNNER_ERROR_CODE, exception);
        errorPersistenceService.create(errInfo);
    }
    logger.info("exiting rule running portion of jobScheduling()");

    logger.info("exiting jobScheduling()");
}

From source file:controller.addGame.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                if (fileItem.isFormField()) {
                    processFormField(fileItem);
                } else {
                    flItem = fileItem;//  ww  w . j a v a2s  .c o  m
                }
            }
        }

        Connect obj_con = new Connect();
        Connection con = obj_con.Open();

        String sql = "insert into Application_Names values(?,?,?)";
        String sql1 = "insert into required_Minimum values(?,?,?,?,?,?)";
        String sql2 = "insert into required_Recomended values(?,?,?,?,?,?)";

        PreparedStatement pr = con.prepareStatement(sql);
        PreparedStatement pr1 = con.prepareStatement(sql1);
        PreparedStatement pr2 = con.prepareStatement(sql2);

        pr.setString(1, AppName);
        pr.setString(2, Code);
        pr.setString(3, Code);

        pr1.setString(1, Code);
        pr1.setString(2, MinGpu);
        pr1.setInt(3, MinGpuLvl);
        pr1.setString(4, MinCpu);
        pr1.setInt(5, RecCpuLvl);
        pr1.setInt(6, MinRam);

        pr2.setString(1, Code);
        pr2.setString(2, RecGpu);
        pr2.setInt(3, RecGpuLvl);
        pr2.setString(4, RecCpu);
        pr2.setInt(5, RecCpuLvl);
        pr2.setInt(6, RecRam);

        int a = pr.executeUpdate();
        int b = pr1.executeUpdate();
        int c = pr2.executeUpdate();

        if (a > 0 && b > 0 && c > 0) {
            RequestDispatcher rd = request.getRequestDispatcher("viewGames.jsp");
            request.setAttribute("return", "Added Item Succesfully.");
            rd.forward(request, response);

            pr.close();
            pr1.close();
            pr2.close();
            con.close();
        } else {
            RequestDispatcher rd = request.getRequestDispatcher("addGame.jsp");
            request.setAttribute("return", "Added Item Succesfully.");
            rd.forward(request, response);
        }

    } catch (Exception e) {
        System.out.println(e.getCause());
    }
}

From source file:se.inera.axel.shs.broker.rs.internal.SynchBrokerRouteBuilderTest.java

@DirtiesContext
@Test/* ww w .ja  v  a2 s .  com*/
public void requestShouldNotBeRoutedWhenAgreementValidationFails() {
    final ShsMessage requestShsMessage = makeRequestShsMessage();

    // Simulate a failure in route processing by means of throwing an exception
    doThrow(new MissingAgreementException("no agreement found")).when(agreementService)
            .validateAgreement(any(ShsLabel.class));

    reset(shsRouter);

    try {
        camel.requestBody("direct-vm:shs:synch", requestShsMessage);
        Assert.fail("Did not throw exception when expected to");
    } catch (Exception e) {
        assertThat(e.getCause(), instanceOf(MissingAgreementException.class));
    }
    verify(shsRouter, never()).isLocal(any(se.inera.axel.shs.xml.label.ShsLabel.class));
}

From source file:org.openmrs.web.controller.report.ReportSchemaXmlFormController.java

/**
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 *//*from   ww  w  .  jav  a 2 s  . c o  m*/
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object commandObject,
        BindException errors) throws Exception {
    ReportSchemaXml reportSchemaXml = (ReportSchemaXml) commandObject;
    ReportService reportService = (ReportService) Context.getService(ReportService.class);

    try {
        // create a new object out of their xml in order to verify xml and copy out the id/name/desc
        ReportSchema schema = reportService.getReportSchema(reportSchemaXml);

        // if the user changed the reportSchemaId to create a new one, create a new object here 
        // so hibernate doesn't complain
        if (reportSchemaXml.getReportSchemaId() != null
                && !schema.getReportSchemaId().equals(reportSchemaXml.getReportSchemaId())) {
            String xml = reportSchemaXml.getXml();
            reportSchemaXml = new ReportSchemaXml();
            reportSchemaXml.setXml(xml);
        }

        reportSchemaXml.populateFromReportSchema(schema);

        // save the xml to the database
        reportService.saveReportSchemaXml(reportSchemaXml);

    } catch (Exception ex) {
        log.warn("Exception building ReportSchema from XML", ex);
        if (ex.getCause() != null) {
            Throwable temp = ex.getCause();
            while (temp.getCause() != null)
                temp = temp.getCause();
            errors.rejectValue("xml", temp.getMessage());
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append("Invalid XML content<br/>");
            sb.append(ex).append("<br/>");
            for (StackTraceElement e : ex.getStackTrace())
                sb.append(e.toString()).append("<br/>");
            errors.rejectValue("xml", sb.toString());
        }
        return showForm(request, response, errors);
    }

    HttpSession httpSession = request.getSession();
    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "reportingcompatibility.Report.manageSchema.saved");
    return new ModelAndView(new RedirectView(getSuccessView()));
}

From source file:at.ac.tuwien.dsg.rSybl.cloudInteractionUnit.enforcementPlugins.governance.GovOpsPlugin.java

public boolean setProto(Node entity, String protocol, GovernanceScope governanceScope) {
    System.err.println("Called method setProto with parameters protocol=" + protocol + " governanceScope="
            + governanceScope);//from www . j a  v a 2s . c o  m
    String governanceUncertainty = governanceScope.getConsideringUncertainty().replace("=", ":").replace("AND",
            ",");
    String response = "";
    String response1 = "";
    try {
        response = callPOSTMethod("/governanceScope/setProcessProps/setProto", "application/json",
                governanceUncertainty);
        response1 = callPOSTMethod("/governanceScope/invokeScope/setProto" + "/" + governanceScope.getQuery()
                + "/" + "cChangeProto" + "/change?proto=" + protocol, "application/json", "");
    } catch (Exception e) {
        RuntimeLogger.logger.error(e.getCause());
        return false;
    }
    System.out.println(response);
    System.out.println(response1);
    return true;

}

From source file:at.ac.tuwien.dsg.rSybl.cloudInteractionUnit.enforcementPlugins.governance.GovOpsPlugin.java

public boolean updatePollRate(Node entity, String pollRate, GovernanceScope governanceScope) {
    System.err.println("Called method update poll rate with parameters pollRate=" + pollRate
            + " governanceScope=" + governanceScope);
    String governanceUncertainty = governanceScope.getConsideringUncertainty().replace("=", ":").replace("AND",
            ",");
    String response = "";
    String response1 = "";
    try {/*from   ww  w. j av  a 2  s  .c om*/
        response = callPOSTMethod("/governanceScope/setProcessProps/setSensorRate", "application/json",
                governanceUncertainty);
        response1 = callPOSTMethod("/governanceScope/invokeScope/setSensorRate" + "/"
                + governanceScope.getQuery() + "/" + "cChangeSensorRate" + "/update?interval=" + pollRate,
                "application/json", "");
    } catch (Exception e) {
        RuntimeLogger.logger.error(e.getCause());
        return false;
    }
    System.out.println(response);
    System.out.println(response1);
    return true;
}