Example usage for java.lang RuntimeException getCause

List of usage examples for java.lang RuntimeException getCause

Introduction

In this page you can find the example usage for java.lang RuntimeException 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:ome.services.RawFileBean.java

@RolesAllowed("user")
@Transactional(readOnly = false)/*from  w  w w  .  j a  v  a  2 s.c o m*/
public synchronized OriginalFile save() {
    if (isModified()) {
        Long id = (file == null) ? null : file.getId();
        if (id == null) {
            return null;
        }

        String path = ioService.getFilesPath(id);
        try {

            byte[] hash = Utils.pathToSha1(path);
            file.setSha1(Utils.bytesToHex(hash));

            long size = new File(path).length();
            file.setSize(size);

        } catch (RuntimeException re) {
            // ticket:3140
            if (re.getCause() instanceof FileNotFoundException) {
                String msg = "Cannot find path. Deleted? " + path;
                log.warn(msg);
                clean(); // Prevent a second exception on close.
                throw new ResourceError(msg);
            }
            throw re;
        }

        iUpdate.flush();
        modified = false;

        return new ShallowCopy().copy(file);
    }
    return null;
}

From source file:org.apache.tuscany.sca.binding.jsonrpc.provider.JsonRpcServlet.java

private JsonRpc10Response invoke(JsonRpc10Request request) throws Exception {
    if (request.isNotification()) {
        return null;
    }/*  ww w.j  ava  2  s  .co m*/
    // invoke the request
    String method = request.getMethod();
    Object[] params = request.getParams();

    Object result = null;
    Operation jsonOperation = findOperation(method);

    // Invoke the get operation on the service implementation
    Message requestMessage = messageFactory.createMessage();
    requestMessage.setOperation(jsonOperation);

    requestMessage.getHeaders().put("RequestMessage", request);
    if (jsonOperation.getInputWrapper().getDataBinding().equals(JSONDataBinding.NAME)) {
        requestMessage.setBody(new Object[] { JacksonHelper.toString(request.getJsonNode()) });
    } else {
        requestMessage.setBody(params);
    }

    Message responseMessage = null;
    try {

        //result = wire.invoke(jsonOperation, args);
        responseMessage = endpoint.getInvocationChain(jsonOperation).getHeadInvoker().invoke(requestMessage);
    } catch (RuntimeException e) {
        if (e.getCause() instanceof LoginException) {
            throw e;
        } else {
            JsonRpc10Response error = new JsonRpc10Response(request.getId(), e);
            return error;
        }
    }

    if (!responseMessage.isFault()) {
        if (jsonOperation.getOutputWrapper().getDataBinding().equals(JSONDataBinding.NAME)) {
            result = responseMessage.getBody();
            return new JsonRpc10Response((ObjectNode) JacksonHelper.MAPPER.readTree(result.toString()));
        } else {
            if (jsonOperation.getOutputType().getLogical().size() == 0) {
                // void operation (json-rpc notification)
                JsonRpc10Response response = new JsonRpc10Response(request.getId(),
                        JsonNodeFactory.instance.nullNode());
                return response;

            } else {
                // regular operation returning some value
                result = responseMessage.getBody();
                JsonRpc10Response response = new JsonRpc10Response(request.getId(), (JsonNode) result);
                //get response to send to client
                return response;
            }
        }

    } else {
        //exception thrown while executing the invocation
        Throwable exception = (Throwable) responseMessage.getBody();

        JsonRpc10Response error = new JsonRpc10Response(request.getId(), exception);
        return error;
    }

}

From source file:net.sourceforge.pmd.ant.internal.PMDTaskImpl.java

private void handleError(RuleContext ctx, Report errorReport, RuntimeException pmde) {

    pmde.printStackTrace();//  w  ww .  ja v  a 2 s  . c o m
    project.log(pmde.toString(), Project.MSG_VERBOSE);

    Throwable cause = pmde.getCause();

    if (cause != null) {
        try (StringWriter strWriter = new StringWriter();
                PrintWriter printWriter = new PrintWriter(strWriter)) {
            cause.printStackTrace(printWriter);
            project.log(strWriter.toString(), Project.MSG_VERBOSE);
        } catch (IOException e) {
            project.log("Error while closing stream", e, Project.MSG_ERR);
        }
        if (StringUtils.isNotBlank(cause.getMessage())) {
            project.log(cause.getMessage(), Project.MSG_VERBOSE);
        }
    }

    if (failOnError) {
        throw new BuildException(pmde);
    }
    errorReport.addError(new Report.ProcessingError(pmde, ctx.getSourceCodeFilename()));
}

From source file:org.apache.tuscany.sca.binding.jsonrpc.provider.JsonRpcServlet.java

private JsonRpcResponse invoke(JsonRpc20Request request) throws Exception {
    if (request.isNotification()) {
        return null;
    }/* w w w  .j  av a 2s .c  o m*/
    // invoke the request
    String method = request.getMethod();
    Object[] params = request.getParams();

    Object result = null;
    Operation jsonOperation = findOperation(method);

    // Invoke the get operation on the service implementation
    Message requestMessage = messageFactory.createMessage();
    requestMessage.setOperation(jsonOperation);

    requestMessage.getHeaders().put("RequestMessage", request);

    if (jsonOperation.getInputWrapper().getDataBinding().equals(JSONDataBinding.NAME)) {
        requestMessage.setBody(new Object[] { JacksonHelper.toString(request.getJsonNode()) });
    } else {
        requestMessage.setBody(params);
    }
    requestMessage.setBody(params);

    Message responseMessage = null;
    try {

        //result = wire.invoke(jsonOperation, args);
        responseMessage = endpoint.getInvocationChain(jsonOperation).getHeadInvoker().invoke(requestMessage);
    } catch (RuntimeException re) {
        if (re.getCause() instanceof javax.security.auth.login.LoginException) {
            throw re;
        } else {
            JsonRpc20Error error = new JsonRpc20Error(request.getId(), re);
            return error;
        }
    }

    if (!responseMessage.isFault()) {
        if (jsonOperation.getOutputWrapper().getDataBinding().equals(JSONDataBinding.NAME)) {
            result = responseMessage.getBody();
            return new JsonRpc20Response((ObjectNode) JacksonHelper.MAPPER.readTree(result.toString()));
        } else {
            if (jsonOperation.getOutputType().getLogical().size() == 0) {
                // void operation (json-rpc notification)
                try {
                    JsonRpc20Response response = new JsonRpc20Response(request.getId(), null);
                    return response;
                } catch (Exception e) {
                    throw new ServiceRuntimeException("Unable to create JSON response", e);
                }

            } else {
                // regular operation returning some value
                try {
                    result = responseMessage.getBody();
                    JsonRpc20Response response = new JsonRpc20Response(request.getId(), (JsonNode) result);
                    //get response to send to client
                    return response;
                } catch (Exception e) {
                    throw new ServiceRuntimeException("Unable to create JSON response", e);
                }
            }
        }

    } else {
        //exception thrown while executing the invocation
        Throwable exception = (Throwable) responseMessage.getBody();

        JsonRpc20Error error = new JsonRpc20Error(request.getId(), exception);
        return error;
    }

}

From source file:org.jbosson.plugins.amq.ArtemisServerComponent.java

protected void internalStart() throws Exception {
    Configuration pluginConfig = context.getPluginConfiguration();
    String connectionTypeDescriptorClassName = pluginConfig.getSimple(JMXDiscoveryComponent.CONNECTION_TYPE)
            .getStringValue();// ww w  .j  a va 2  s. c  om
    if (JMXDiscoveryComponent.PARENT_TYPE.equals(connectionTypeDescriptorClassName)) {
        // Our parent is itself a JMX component, so just reuse its connection.
        this.connection = ((JMXComponent) context.getParentResourceComponent()).getEmsConnection();
        this.connectionProvider = this.connection.getConnectionProvider();
    } else {
        final File tempDir = this.context.getTemporaryDirectory();
        try {
            this.connectionProvider = ConnectionProviderFactory.createConnectionProvider(pluginConfig,
                    this.context.getNativeProcess(), tempDir);
        } catch (RuntimeException e) {
            // check if Attach API failed, since this resource may have been discovered using jvmstat API
            // avoid loading AttachNotSupportedException class, since its optional
            if (e.getCause() != null && e.getCause().getClass().getName()
                    .equals(ArtemisServerDiscoveryComponent.ATTACH_NOT_SUPPORTED_EXCEPTION_CLASS_NAME)) {

                // create a connection provider using JvmStatUtility
                final Class<?> connectionTypeDescriptorClass;
                connectionTypeDescriptorClass = Class.forName(connectionTypeDescriptorClassName);
                ConnectionTypeDescriptor connectionType = (ConnectionTypeDescriptor) connectionTypeDescriptorClass
                        .newInstance();

                // create connection provider settings
                ConnectionSettings settings = new ConnectionSettings();
                if (!(connectionType instanceof J2SE5ConnectionTypeDescriptor)) {
                    throw new Exception(
                            "Unsupported connection type descriptor " + connectionTypeDescriptorClass);
                }
                settings.setConnectionType(connectionType);

                // get service URL using jvmstat
                final JMXServiceURL jmxServiceURL = JvmStatUtility
                        .extractJMXServiceURL(context.getNativeProcess());
                if (jmxServiceURL == null) {
                    throw new Exception("Failed to get JMX service URL using jvmstat");
                }
                settings.setServerUrl(jmxServiceURL.toString());

                settings.getControlProperties().setProperty(ConnectionFactory.COPY_JARS_TO_TEMP,
                        String.valueOf(Boolean.TRUE));
                settings.getControlProperties().setProperty(ConnectionFactory.JAR_TEMP_DIR,
                        tempDir.getAbsolutePath());

                ConnectionFactory connectionFactory = new ConnectionFactory();
                connectionFactory.discoverServerClasses(settings);

                connectionProvider = connectionFactory.getConnectionProvider(settings);

            } else {
                // re-throw
                throw e;
            }
        }
        this.connection = this.connectionProvider.connect();
        this.connection.loadSynchronous(false);
    }
}

From source file:com.rackspacecloud.blueflood.io.serializers.SerializationTest.java

@Test
public void testFullResSerializationAndDeserialization() throws IOException {
    // if the GENERATE_SERIALIZATION flag is set, save everything.
    if (System.getProperty("GENERATE_FULL_RES_SERIALIZATION") != null) {
        OutputStream os = new FileOutputStream(
                "src/test/resources/serializations/full_version_" + Constants.VERSION_1_FULL_RES + ".bin",
                false);/*from   www.  ja va 2 s.  co m*/
        for (Object o : toSerializeFull) {
            // encode as base64 to make reading the file easier.
            os.write(
                    Base64.encodeBase64(NumericSerializer.serializerFor(Object.class).toByteBuffer(o).array()));
            os.write("\n".getBytes());
        }
        os.close();
    }

    Assert.assertTrue(new File("src/test/resources/serializations").exists());

    // ensure we can read historical serializations.
    int version = 0; // versions before this are illegal.
    int maxVersion = Constants.VERSION_1_FULL_RES;
    while (version <= maxVersion) {
        BufferedReader reader = new BufferedReader(
                new FileReader("src/test/resources/serializations/full_version_" + version + ".bin"));
        for (int i = 0; i < toSerializeFull.length; i++)
            try {
                // we used to allow deserializing strings, but we don't anymore.
                // catch that error and assert it happens only when expected.
                ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
                Assert.assertEquals(String.format("broken at version %d", version),
                        NumericSerializer.serializerFor(Object.class).fromByteBuffer(byteBuffer),
                        toSerializeFull[i]);
            } catch (RuntimeException ex) {
                Assert.assertEquals(ex.getCause().getClass(), UnexpectedStringSerializationException.class);
                Assert.assertEquals(3, i);
                Assert.assertTrue(toSerializeFull[i] instanceof String);
            }
        version += 1;
    }

    // ensure that current round-tripping isn't broken.
    for (Object o : toSerializeFull) {
        // skip the string (we used to allow this).
        if (o instanceof String)
            continue; // we don't serialize those any more.
        ByteBuffer serialized = NumericSerializer.serializerFor(Object.class).toByteBuffer(o);
        Assert.assertEquals(o, NumericSerializer.serializerFor(Object.class).fromByteBuffer(serialized));
    }
}

From source file:org.kuali.rice.kew.routeheader.dao.impl.DocumentRouteHeaderDAOOjbImpl.java

public void saveRouteHeader(DocumentRouteHeaderValue routeHeader) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("About to Save the route Header: " + routeHeader.getDocumentId() + " / version="
                + routeHeader.getVersionNumber());
        DocumentRouteHeaderValue currHeader = findRouteHeader(routeHeader.getDocumentId());
        if (currHeader != null) {
            LOG.debug("Current Header Version: " + currHeader.getVersionNumber());
            //                for ( SearchableAttributeValue s : currHeader.get() ) {
            //                    LOG.debug( "SA: " + s.getSearchableAttributeValueId() + " / version=" + s.get )
            //                }
        } else {//from   www .  j  a va2 s  . co  m
            LOG.debug("Current Header: null");
        }
        LOG.debug(ExceptionUtils.getStackTrace(new Throwable()));
    }
    try {
        getPersistenceBrokerTemplate().store(routeHeader);
        routeHeader.getDocumentContent().setDocumentId(routeHeader.getDocumentId());
        getPersistenceBrokerTemplate().store(routeHeader.getDocumentContent());
    } catch (RuntimeException ex) {
        if (ex.getCause() instanceof OptimisticLockException) {
            LOG.error("Optimistic Locking Exception saving document header or content. Offending object: "
                    + ((OptimisticLockException) ex.getCause()).getSourceObject() + "; DocumentId = "
                    + routeHeader.getDocumentId() + " ;  Version Number = " + routeHeader.getVersionNumber());
        }
        LOG.error("Unable to save document header or content. Route Header: " + routeHeader, ex);
        throw ex;
    }
}

From source file:net.solarnetwork.node.rfxcom.RFXCOMTransceiver.java

@Override
public List<SettingSpecifier> getSettingSpecifiers() {
    List<SettingSpecifier> results = new ArrayList<SettingSpecifier>(20);
    results.add(// w  ww. j  ava 2s.  com
            new BasicTextFieldSettingSpecifier("dataCollectorFactory.propertyFilters['UID']", "/dev/ttyUSB0"));

    if (status == null) {
        try {
            updateStatus();
        } catch (RuntimeException e) {
            log.warn("Unable to update RFXCOM status", e.getCause());
        }
    }
    if (status != null) {
        log.debug("RFXCOM status: firmware {}, product {}, Oregon {}",
                new Object[] { status.getFirmwareVersion(), status.getTransceiverType().getDescription(),
                        status.isOregonEnabled() });

        results.add(new BasicTitleSettingSpecifier("firmwareVersion",
                (status == null ? "N/A" : String.valueOf(status.getFirmwareVersion())), true));
        results.add(new BasicTitleSettingSpecifier("transceiverType",
                (status == null ? "N/A" : status.getTransceiverType().getDescription()), true));

        PropertyAccessor bean = (status == null ? null : PropertyAccessorFactory.forBeanPropertyAccess(status));
        addToggleSetting(results, bean, "ACEnabled");
        addToggleSetting(results, bean, "ADEnabled");
        addToggleSetting(results, bean, "ARCEnabled");
        addToggleSetting(results, bean, "ATIEnabled");
        addToggleSetting(results, bean, "FS20Enabled");
        addToggleSetting(results, bean, "hidekiEnabled");
        addToggleSetting(results, bean, "homeEasyEUEnabled");
        addToggleSetting(results, bean, "ikeaKopplaEnabled");
        addToggleSetting(results, bean, "laCrosseEnabled");
        addToggleSetting(results, bean, "mertikEnabled");
        addToggleSetting(results, bean, "oregonEnabled");
        addToggleSetting(results, bean, "proGuardEnabled");
        addToggleSetting(results, bean, "visonicEnabled");
        addToggleSetting(results, bean, "x10Enabled");

        addToggleSetting(results, bean, "undecodedMode");
    }

    results.addAll(SerialPortBeanParameters
            .getDefaultSettingSpecifiers(RFXCOMTransceiver.getDefaultSerialParameters(), "serialParams."));
    return results;
}

From source file:org.apache.manifoldcf.agents.output.solr.HttpPoster.java

/** Handle a RuntimeException.
* Unfortunately, SolrCloud 4.6.x throws RuntimeExceptions whenever ZooKeeper is not happy.
* We have to catch these too.  I've logged a ticket: SOLR-5678.
*///  w  w w  . j  a  va2s  .  c o m
protected static void handleRuntimeException(RuntimeException e, String context)
        throws ManifoldCFException, ServiceInterruption {
    Throwable childException = e.getCause();
    if (childException != null && childException instanceof java.util.concurrent.TimeoutException) {
        Logging.ingest.warn("SolrJ runtime exception during " + context + ": " + childException.getMessage(),
                childException);
        long currentTime = System.currentTimeMillis();
        throw new ServiceInterruption(childException.getMessage(), childException,
                currentTime + interruptionRetryTime, currentTime + 2L * 60L * 60000L, -1, true);
    }
    throw e;
}

From source file:com.haulmont.cuba.web.security.ConnectionImpl.java

protected void rethrowLoginException(RuntimeException e) throws LoginException {
    Throwable cause = e.getCause();
    if (cause instanceof LoginException) {
        throw (LoginException) cause;
    } else {/*from   w ww. j  a v  a  2 s  .c  om*/
        throw e;
    }
}