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.evolveum.midpoint.test.IntegrationTestTools.java

public static void checkShadow(ShadowType shadowType, ResourceType resourceType,
        RepositoryService repositoryService, ObjectChecker<ShadowType> checker,
        MatchingRule<String> uidMatchingRule, PrismContext prismContext, OperationResult parentResult)
        throws SchemaException {
    LOGGER.trace("Checking shadow:\n{}", shadowType.asPrismObject().debugDump());
    shadowType.asPrismObject().checkConsistence(true, true, ConsistencyCheckScope.THOROUGH);
    assertNotNull("no OID", shadowType.getOid());
    assertNotNull("no name", shadowType.getName());
    assertEquals(resourceType.getOid(), shadowType.getResourceRef().getOid());
    PrismContainer<?> attrs = shadowType.asPrismObject().findContainer(ShadowType.F_ATTRIBUTES);
    assertNotNull("no attributes", attrs);
    assertFalse("empty attributes", attrs.isEmpty());

    RefinedResourceSchema rschema = RefinedResourceSchema.getRefinedSchema(resourceType);
    ObjectClassComplexTypeDefinition objectClassDef = rschema.findObjectClassDefinition(shadowType);
    assertNotNull("cannot determine object class for " + shadowType, objectClassDef);

    String icfUid = ShadowUtil.getSingleStringAttributeValue(shadowType, SchemaTestConstants.ICFS_UID);
    if (icfUid == null) {
        Collection<? extends ResourceAttributeDefinition> identifierDefs = objectClassDef.getIdentifiers();
        assertFalse("No identifiers for " + objectClassDef, identifierDefs == null || identifierDefs.isEmpty());
        for (ResourceAttributeDefinition idDef : identifierDefs) {
            String id = ShadowUtil.getSingleStringAttributeValue(shadowType, idDef.getName());
            assertNotNull("No identifier " + idDef.getName() + " in " + shadowType, id);
        }//  www. j  a v  a2s . c  o m
    }

    String resourceOid = ShadowUtil.getResourceOid(shadowType);
    assertNotNull("No resource OID in " + shadowType, resourceOid);

    assertNotNull("Null OID in " + shadowType, shadowType.getOid());
    PrismObject<ShadowType> repoShadow = null;
    try {
        repoShadow = repositoryService.getObject(ShadowType.class, shadowType.getOid(), null, parentResult);
    } catch (Exception e) {
        AssertJUnit.fail("Got exception while trying to read " + shadowType + ": " + e.getCause() + ": "
                + e.getMessage());
    }

    checkShadowUniqueness(shadowType, objectClassDef, repositoryService, uidMatchingRule, prismContext,
            parentResult);

    String repoResourceOid = ShadowUtil.getResourceOid(repoShadow.asObjectable());
    assertNotNull("No resource OID in the repository shadow " + repoShadow);
    assertEquals("Resource OID mismatch", resourceOid, repoResourceOid);

    try {
        repositoryService.getObject(ResourceType.class, resourceOid, null, parentResult);
    } catch (Exception e) {
        AssertJUnit.fail("Got exception while trying to read resource " + resourceOid
                + " as specified in current shadow " + shadowType + ": " + e.getCause() + ": "
                + e.getMessage());
    }

    if (checker != null) {
        checker.check(shadowType);
    }
}

From source file:edu.indiana.dlib.avalon.HydrantWorkflowListener.java

private void pingHydrant(String pid, long workflowId) {
    logger.trace("Starting to ping Hydrant: " + pid + " " + workflowId);
    try {/*from  w w w  .  jav a  2 s. c  om*/
        String url = UrlSupport.concat(new String[] { hydrantUrl, "master_files", pid });
        MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
        HttpClient client = new HttpClient(mgr);

        PutMethod put = new PutMethod(url);

        Part[] parts = { new StringPart("workflow_id", String.valueOf(workflowId)), };
        put.setRequestEntity(new MultipartRequestEntity(parts, put.getParams()));
        logger.trace("About to ping Hydrant");
        int status = client.executeMethod(put);
        logger.debug("Got status: " + status);
        logger.trace("Got response body: " + put.getResponseBodyAsString());
    } catch (Exception e) {
        logger.debug("Exception pinging Hydrant: " + e.getCause(), e);
    }
}

From source file:dk.teachus.backend.bean.impl.SpringMailBean.java

public void sendMail(final InternetAddress sender, final InternetAddress recipient, final String subject,
        final String body, final Type mailType) throws MailException {
    try {//w ww.  j  a v a  2  s  .  c  om
        mailSender.send(new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false, "UTF-8");

                message.setFrom(sender);
                message.addTo(recipient);
                message.setSubject(subject);

                switch (mailType) {
                case HTML:
                    message.setText(body, true);
                    break;
                default:
                    message.setText(body);
                    break;
                }
            }
        });
    } catch (MailSendException e) {
        Map<?, ?> failedMessages = e.getFailedMessages();

        if (failedMessages != null && failedMessages.isEmpty() == false) {
            Object object = failedMessages.values().iterator().next();
            if (object != null) {
                Exception mailException = (Exception) object;
                if (mailException.getCause() instanceof SMTPAddressFailedException) {
                    throw new RecipientErrorMailException(e);
                }
            }
        }

        throw new MailException(e);
    }
}

From source file:be.wegenenverkeer.common.resteasy.mapper.UnhandledExceptionMapper.java

@Override
public Response toResponse(Exception exception) {
    if (exception.getCause() != null && exception.getCause() instanceof ServiceException) {
        ServiceException se = (ServiceException) exception.getCause();
        return serviceExceptionMapper.toResponse(se);
    } else if (exception.getCause() != null && exception.getCause() instanceof ValidationException) {
        ValidationException ve = (ValidationException) exception.getCause();
        return validationExceptionMapper.toResponse(ve);
    } else if (exception instanceof NotFoundException) {
        NotFoundException nfe = (NotFoundException) exception;
        return notFoundExceptionMapper.toResponse(nfe);
    } else if (exception instanceof AuthException) {
        AuthException ae = (AuthException) exception;
        return authExceptionMapper.toResponse(ae);
    } else if (exception instanceof javax.ws.rs.NotFoundException) {
        javax.ws.rs.NotFoundException nfe = (javax.ws.rs.NotFoundException) exception;
        return jaxRsNotFoundExceptionMapper.toResponse(nfe);
    } else if (exception instanceof org.jboss.resteasy.spi.NotFoundException) {
        org.jboss.resteasy.spi.NotFoundException nfe = (org.jboss.resteasy.spi.NotFoundException) exception;
        return resteasyNotFoundExceptionMapper.toResponse(nfe);
    } else if (exception instanceof AuthenticationException) {
        AuthenticationException ae = (AuthenticationException) exception;
        return authenticationExceptionMapper.toResponse(ae);
    } else if (exception instanceof ConstraintViolationException) {
        ConstraintViolationException cve = (ConstraintViolationException) exception;
        return constraintViolationExceptionMapper.toResponse(cve);
    } else if (exception instanceof MethodConstraintViolationException) {
        MethodConstraintViolationException mcve = (MethodConstraintViolationException) exception;
        return methodConstraintViolationExceptionMapper.toResponse(mcve);
    } else if (exception instanceof ConflictException) {
        ConflictException conflictException = (ConflictException) exception;
        return conflictExceptionMapper.toResponse(conflictException);
    } else {//from   w w  w  .  j a  va2s.  com
        preProcessLoggingInterceptor.postProcessError(exception, "Kritische fout gedetecteerd:");
        ExceptionUtil eu = new ExceptionUtil(exception);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity("{ \"error\" : {\"\":[\"" + eu.getEscapedConcatenatedMessage() + "\"]}}")
                .header("Access-Control-Allow-Origin", request.getHeader("Origin"))
                .header("Access-Control-Allow-Credentials", true).build();
    }
}

From source file:com.sixt.service.framework.jetty.RpcReadException.java

public String toJson(HttpServletRequest req) {
    JsonObject obj = new JsonObject();

    Enumeration<String> h = req.getHeaderNames();
    while (h.hasMoreElements()) {
        String hKey = h.nextElement();
        String hValue = req.getHeader(hKey);
        obj.addProperty("request_header_" + hKey, hValue);
    }//  w ww  .jav  a2 s  .  c om

    obj.addProperty("exception_message", this.getMessage());
    obj.addProperty("request_query_string", req.getQueryString());
    obj.addProperty("request_url", req.getRequestURL().toString());
    obj.addProperty("request_remote_addr", req.getRemoteAddr());
    obj.addProperty("request_remote_port", req.getRemotePort());
    obj.addProperty("request_remote_host", req.getRemoteHost());
    obj.addProperty("request_remote_user", req.getRemoteUser());

    String readBody = "success";
    // read the whole remaining body and put the joined base64 encoded message into the json object
    try {
        byte[] ba = IOUtils.toByteArray(this.in);
        byte[] combined;
        if ((ba != null) && (this.incomplete != null)) {
            combined = new byte[ba.length + this.incomplete.length];
            System.arraycopy(incomplete, 0, combined, 0, this.incomplete.length);
            System.arraycopy(ba, 0, combined, this.incomplete.length, ba.length);
            obj.addProperty("request_body", Base64.getEncoder().encodeToString(combined));
        } else if (ba != null) {
            combined = ba;
        } else if (this.incomplete != null) {
            combined = this.incomplete;
        } else {
            readBody = "body is empty";
        }
    } catch (Exception ex) {
        readBody = String.format("failed because: %s", ex.getCause());
    }
    obj.addProperty("read_body", readBody);

    return obj.toString();
}

From source file:org.sarons.spring4me.web.page.tag.vm.PlaceholderDirective.java

@Override
public boolean render(final InternalContextAdapter context, Writer writer, Node node)
        throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
    String groupId = null;/*from   ww  w . ja v  a2s  . co  m*/
    //
    int num = node.jjtGetNumChildren();
    //
    if (num > 0 && node.jjtGetChild(0) != null) {
        groupId = String.valueOf(node.jjtGetChild(0).value(context));
    }
    //
    Assert.notNull(groupId, "Argument group id can not be null!");
    //
    PageConfig pageConfig = (PageConfig) context.get(PageConfig.KEY);
    //
    PlaceholderProcessor pp = new PlaceholderProcessor(pageConfig);
    pp.setCallback(new PlaceholderCallback() {

        public HttpWidget getHttpWidget(WidgetConfig widgetConfig) throws Exception {
            String httpWidgetKey = WidgetUtils.generateHttpWidgetKey(widgetConfig);
            return (HttpWidget) context.get(httpWidgetKey);
        }

    });
    //
    try {
        pp.process(writer, groupId);
        return true;
    } catch (Exception e) {
        throw new PlaceholderException(e.getMessage(), e.getCause());
    }
}

From source file:gobblin.source.extractor.extract.google.GoogleAnalyticsUnsampledExtractorTest.java

public void testPollForCompletionFailure() throws IOException {
    wuState = new WorkUnitState();
    wuState.setProp(POLL_RETRY_PREFIX + RETRY_TIME_OUT_MS, TimeUnit.SECONDS.toMillis(30L));
    wuState.setProp(POLL_RETRY_PREFIX + RETRY_INTERVAL_MS, 1L);
    GoogleAnalyticsUnsampledExtractor extractor = setup(ReportCreationStatus.FAILED, wuState, false);

    UnsampledReport requestedReport = new UnsampledReport().setAccountId("testAccountId")
            .setWebPropertyId("testWebPropertyId").setProfileId("testProfileId").setId("testId");

    try {//  w ww .  j  av  a2 s.c  om
        extractor.pollForCompletion(wuState, gaService, requestedReport);
        Assert.fail("Should have failed with failed status");
    } catch (Exception e) {
        Assert.assertTrue(e.getCause().getCause() instanceof NonTransientException);
    }
    verify(getReq, atLeast(5)).execute();
}

From source file:org.sarons.spring4me.web.page.tag.ftl.PlaceholderDirectiveModel.java

@SuppressWarnings("rawtypes")
public void execute(final Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {
    local.set(env);/*from   w w w  .  j  av  a  2 s.c  om*/
    //
    String groupId = null;
    //
    if (params.containsKey(PARAM_GROUP_ID)) {
        groupId = params.get(PARAM_GROUP_ID).toString();
    }
    //
    Assert.notNull(groupId, "Argument groupId can not be null!");
    //
    BeanModel pageConfigBeanModel = (BeanModel) env.getDataModel().get(PageConfig.KEY);
    PageConfig pageConfig = (PageConfig) pageConfigBeanModel.getWrappedObject();
    //
    PlaceholderProcessor pp = new PlaceholderProcessor(pageConfig);
    pp.setCallback(new PlaceholderCallback() {

        public HttpWidget getHttpWidget(WidgetConfig widgetConfig) throws Exception {
            String httpWidgetKey = WidgetUtils.generateHttpWidgetKey(widgetConfig);
            BeanModel httpWidgetBeanModel = (BeanModel) env.getDataModel().get(httpWidgetKey);
            HttpWidget httpWidget = null;
            if (httpWidgetBeanModel != null) {
                httpWidget = (HttpWidget) httpWidgetBeanModel.getWrappedObject();
            }
            return httpWidget;
        }

    });
    //
    try {
        pp.process(env.getOut(), groupId);
    } catch (Exception e) {
        throw new PlaceholderException(e.getMessage(), e.getCause());
    }
}

From source file:interactivespaces.util.resource.ManagedResourcesTest.java

/**
 * Test that a broken startup works./*from   w  w  w.j  ava 2 s  . c om*/
 */
@Test
public void testBrokenStartup() {

    ManagedResource resource1 = Mockito.mock(ManagedResource.class);
    ManagedResource resource2 = Mockito.mock(ManagedResource.class);
    ManagedResource resource3 = Mockito.mock(ManagedResource.class);

    Exception e = new RuntimeException();
    Mockito.doThrow(e).when(resource2).startup();

    resources.addResource(resource1);
    resources.addResource(resource2);
    resources.addResource(resource3);

    try {
        resources.startupResources();

        fail();
    } catch (Exception e1) {
        assertEquals(e, e1.getCause());
    }

    Mockito.verify(resource1, Mockito.times(1)).startup();
    Mockito.verify(resource1, Mockito.times(1)).shutdown();
    Mockito.verify(resource2, Mockito.times(1)).startup();
    Mockito.verify(resource2, Mockito.never()).shutdown();
    Mockito.verify(resource3, Mockito.never()).startup();
    Mockito.verify(resource3, Mockito.never()).shutdown();
}

From source file:com.bacic5i5j.framework.view.VelocityViewFactory.java

@Inject
public VelocityViewFactory() {
    PropertiesConfiguration _config = Gemini.instance.getConfig();
    String templatePath = "/WEB-INF/pages";
    if (_config != null) {
        String _template_path = _config.getString("webapp.template");
        if (_template_path != null && !"".equals(_template_path.trim())) {
            templatePath = _template_path;
        }//from  ww w .  j a v a2s .  c  om
    }

    Properties ps = new Properties();
    ps.setProperty("resource.loader", "file");
    ps.setProperty("file.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
    ps.setProperty("file.resource.loader.path", templatePath);
    ps.setProperty("file.resource.loader.cache", "false");
    ps.setProperty("file.resource.loader.modificationCheckInterval", "2");
    ps.setProperty("input.encoding", "UTF-8");
    ps.setProperty("output.encoding", "UTF-8");
    ps.setProperty("default.contentType", "text/html; charset=UTF-8");
    ps.setProperty("velocimarco.library.autoreload", "true");
    ps.setProperty("runtime.log.error.stacktrace", "false");
    ps.setProperty("runtime.log.warn.stacktrace", "false");
    ps.setProperty("runtime.log.info.stacktrace", "false");
    ps.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
    ps.setProperty("runtime.log.logsystem.log4j.category", "velocity_log");

    velocityEngine = new VelocityEngine();

    try {
        velocityEngine.init(ps);
        EasyFactoryConfiguration config = new EasyFactoryConfiguration();
        config.toolbox("application").tool("number", NumberTool.class).tool("date", DateTool.class);
        toolManager.configure(config);
        toolManager.setVelocityEngine(velocityEngine);
    } catch (Exception e) {
        logger.error(e.getMessage() + " : " + e.getCause());
    }
}