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.trendmicro.hdfs.webdav.HDFSWebDAVServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug(request.getMethod() + " for '" + request.getRequestURI() + "' from " + request.getRemoteUser()
                + " at " + request.getRemoteAddr());
    }/*from  w w  w  . ja v  a 2s  . c  o  m*/
    try {
        super.service(request, response);
    } catch (Exception e) {
        if (e instanceof AccessControlException || e.getCause() instanceof AccessControlException) {
            LOG.info("Insufficient permissions for request for '" + request.getRequestURI() + "' from "
                    + request.getRemoteUser() + " at " + request.getRemoteAddr());
            if (request.getMethod().equalsIgnoreCase("GET")) {
                // Provide a plain 401 response for GETs
                new WebdavResponseImpl(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            } else {
                // Otherwise send a multistatus response
                MultiStatus ms = new MultiStatus();
                ms.addResponse(new MultiStatusResponse(request.getRequestURL().toString(), 401,
                        "You do not have permission to access this resource."));
                new WebdavResponseImpl(response).sendMultiStatus(ms);
            }
        } else {
            LOG.warn("Exception processing request for '" + request.getRequestURI() + "' from "
                    + request.getRemoteUser() + " at " + request.getRemoteAddr() + " authType "
                    + request.getAuthType(), e);
            new WebdavResponseImpl(response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:io.cloudslang.content.database.services.databases.MSSqlDatabase.java

@Override
public List<String> setUp(@NotNull final SQLInputs sqlInputs) {
    try {/*from w w w  . j av a2 s . c o m*/
        final List<String> dbUrls = new ArrayList<>();
        // todo ask eugen if need to check class
        if (sqlInputs.getDbClass() != null && sqlInputs.getDbClass().equals(SQLSERVER_JDBC_DRIVER)) {
            if (isNoneEmpty(sqlInputs.getDbUrl())) {
                final String dbUrl = MSSqlDatabase.addSslEncryptionToConnection(sqlInputs.isTrustAllRoots(),
                        sqlInputs.getTrustStore(), sqlInputs.getTrustStorePassword(), sqlInputs.getDbUrl());
                dbUrls.add(dbUrl);

            }
        }

        loadJdbcDriver(sqlInputs.getDbClass(), sqlInputs.getAuthenticationType(),
                sqlInputs.getAuthLibraryPath());

        String host;

        //compute the host value that will be used in the url
        String[] serverInstanceComponents = null;
        if (sqlInputs.getDbServer().contains(BACK_SLASH)) { //instance is included in the dbServer value
            serverInstanceComponents = sqlInputs.getDbServer().split("\\\\");
            host = serverInstanceComponents[0];
        } else {
            host = sqlInputs.getDbServer();
        }
        final Address address = new Address(host);
        host = address.getURIIPV6Literal();

        //instance is included in the host name
        //todo check if mssql dbName can be null, the other operation "supported" it
        if (isValidAuthType(sqlInputs.getAuthenticationType())) {
            final StringBuilder dbUrlMSSQL = new StringBuilder(Constants.MSSQL_URL + host + COLON
                    + sqlInputs.getDbPort() + SEMI_COLON + DATABASE_NAME_CAP + EQUALS + sqlInputs.getDbName());

            if (serverInstanceComponents != null) {
                dbUrlMSSQL.append(SEMI_COLON + INSTANCE + EQUALS).append(serverInstanceComponents[1]);
            } else if (isNoneEmpty(sqlInputs.getInstance())) {
                dbUrlMSSQL.append(SEMI_COLON + INSTANCE + EQUALS).append(sqlInputs.getInstance());
            }
            if (AUTH_WINDOWS.equalsIgnoreCase(sqlInputs.getAuthenticationType())) {
                dbUrlMSSQL.append(SEMI_COLON + INTEGRATED_SECURITY + EQUALS).append(TRUE);
            }
            final String connectionString = addSslEncryptionToConnection(sqlInputs.isTrustAllRoots(),
                    sqlInputs.getTrustStore(), sqlInputs.getTrustStorePassword(), dbUrlMSSQL.toString());
            //                sqlInputs.getDbUrls().add(connectionString);

            dbUrls.add(connectionString);

        } else {
            throw new SQLException(INVALID_AUTHENTICATION_TYPE_FOR_MS_SQL + sqlInputs.getAuthenticationType());
        }

        return dbUrls;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e.getCause());
    }
}

From source file:com.leo.cattle.data.net.RestApiImpl.java

@RxLogObservable
@Override//w ww . j a va2 s  . co  m
public Observable<List<ChatSessionEntity>> sessionEntityList(String token) {
    return Observable.create(subscriber -> {
        if (isThereInternetConnection()) {
            try {
                String responseUserEntities = getChatSessionEntitiesFromApi(token);
                if (responseUserEntities != null) {
                    subscriber.onNext(
                            sessionEntityJsonMapper.transformChatSessionEntityCollection(responseUserEntities));
                    subscriber.onCompleted();
                } else {
                    subscriber.onError(new NetworkConnectionException());
                }
            } catch (Exception e) {
                subscriber.onError(new NetworkConnectionException(e.getCause()));
            }
        } else {
            subscriber.onError(new NetworkConnectionException());
        }
    });
}

From source file:be.bittich.quote.controller.impl.DefaultExceptionHandler.java

@RequestMapping(produces = APPLICATION_JSON)
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public @ResponseBody Map<String, Object> handleUncaughtException(Exception ex) throws IOException {
    Map<String, Object> map = newHashMap();
    map.put("error", "Unknown Error");
    if (ex.getCause() != null) {
        map.put("cause", ex.getCause().getMessage());
    } else {//from   ww w.  j  a v  a  2 s  .  c om
        map.put("cause", ex.getMessage());
    }
    return map;
}

From source file:com.dishant.iot.smarthome.publisher.SmarthomePublisher.java

@Override
public void sensorChanged(String sensorName, Object newValue) {
    if (m_dataTransport != null && !m_dataTransport.isConnected()) {
        s_logger.error("No connected data transport - enable auto reconnect to re-establish connection");
    }//from  ww w.ja  v  a  2s .  com

    // Publish topic
    String topic = m_topicPrefix + "update";

    // Message payload
    String payload = "{\"state\": {\"reported\": {\"" + sensorName + "\": " + newValue.toString() + "}}}";

    try {
        // Publish the message
        m_dataTransport.publish(topic, payload.getBytes(), m_qos, m_retain);
        s_logger.info("Published to {} message: {}", new Object[] { topic, payload });
    } catch (Exception e) {
        s_logger.error("Cannot publish to topic: {} reason: {}", new Object[] { topic, e.getCause() });
    }
}

From source file:com.alibaba.jstorm.yarn.appmaster.JstormMaster.java

private static void publishContainerStartEvent(final TimelineClient timelineClient, Container container,
        String domainId, UserGroupInformation ugi) {
    final TimelineEntity entity = new TimelineEntity();
    entity.setEntityId(container.getId().toString());
    entity.setEntityType(DSEntity.DS_CONTAINER.toString());
    entity.setDomainId(domainId);//from  w  ww  .  j  a v a  2 s.  c om
    entity.addPrimaryFilter(JOYConstants.USER, ugi.getShortUserName());
    TimelineEvent event = new TimelineEvent();
    event.setTimestamp(System.currentTimeMillis());
    event.setEventType(DSEvent.DS_CONTAINER_START.toString());
    event.addEventInfo(JOYConstants.NODE, container.getNodeId().toString());
    event.addEventInfo(JOYConstants.RESOURCES, container.getResource().toString());
    entity.addEvent(event);

    try {
        ugi.doAs(new PrivilegedExceptionAction<TimelinePutResponse>() {
            @Override
            public TimelinePutResponse run() throws Exception {
                return timelineClient.putEntities(entity);
            }
        });
    } catch (Exception e) {
        LOG.error("Container start event could not be published for " + container.getId().toString(),
                e instanceof UndeclaredThrowableException ? e.getCause() : e);
    }
}

From source file:de.weltraumschaf.groundzero.GroundZero.java

/**
 * Find the command line arguments./*from w ww  . jav a2s.  c o m*/
 *
 * @throws ApplicationException if command line arguments were not possible to parse
 */
void examineCommandLineOptions() throws ApplicationException {
    final String envStrategy = getEnv();

    final Strategy strategy;

    if (Strategy.COMMONS.toString().equalsIgnoreCase(envStrategy)) {
        strategy = Strategy.COMMONS;
    } else if (Strategy.JCOMMANDER.toString().equalsIgnoreCase(envStrategy)) {
        strategy = Strategy.JCOMMANDER;
    } else {
        strategy = Strategy.COMMONS;
        getIoStreams().errorln(
                String.format("Warning: Unsupported strategy '%s' Fall back to '%s'.", envStrategy, strategy));
    }

    optionsSetup = OptionsSetups.create(strategy);

    try {
        options = optionsSetup.parse(getArgs());
    } catch (Exception ex) {
        throw new ApplicationException(ExitCodeImpl.BAD_ARGUMENTS, ex.getMessage(), ex.getCause());
    }

    if (options.isDebug()) {
        getIoStreams().println(String.format("Used CLI options:\n%s", options));
    }
}

From source file:com.suramericana.controller.checkout.CheckoutController.java

@RequestMapping(value = "/complete", method = RequestMethod.POST)
public String completeCheckout(HttpServletRequest request, HttpServletResponse response, Model model,
        @ModelAttribute("orderInfoForm") OrderInfoForm orderInfoForm,
        @ModelAttribute("shippingInfoForm") ShippingInfoForm shippingForm,
        @ModelAttribute("billingInfoForm") BillingInfoForm billingForm, BindingResult result)
        throws CheckoutException, PricingException, ServiceException {

    prepopulateCheckoutForms(CartState.getCart(), null, shippingForm, billingForm);
    Order cart = CartState.getCart();//from   ww w . j  av  a 2s  .  c om
    if (cart != null) {

        Map<PaymentInfo, Referenced> payments = new HashMap<PaymentInfo, Referenced>();

        orderService.removePaymentsFromOrder(cart, SuraCajaSapPaymentInfoType.CAJA_SAP);

        if (billingForm.isUseShippingAddress()) {
            copyShippingAddressToBillingAddress(cart, billingForm);
        }

        suraBillingInfoFormValidator.validate(billingForm, result);
        if (result.hasErrors()) {
            populateModelWithShippingReferenceData(request, model);
            return getCheckoutView();
        }

        String uniqueReferenceNumber = String.valueOf(cart.getId());

        PaymentInfo paymentInfoCajaSap = (PaymentInfo) paymentInfoService.create();
        paymentInfoCajaSap.setAddress(billingForm.getAddress());
        cart.getPaymentInfos().add(paymentInfoCajaSap);

        paymentInfoCajaSap.setType(SuraCajaSapPaymentInfoType.CAJA_SAP);
        paymentInfoCajaSap.setOrder(cart);
        paymentInfoCajaSap.setAmount(cart.getTotal());
        paymentInfoCajaSap.setReferenceNumber(uniqueReferenceNumber);

        payments.put(paymentInfoCajaSap, paymentInfoCajaSap.createEmptyReferenced());

        cart.getPaymentInfos().add(paymentInfoCajaSap);

        try {
            CheckoutResponse checkoutResponse = checkoutService.performCheckout(cart, payments);
        } catch (Exception e) {
            if (e.getCause() instanceof BasicInventoryUnavailableException) {
                BasicInventoryUnavailableException inventoryException = (BasicInventoryUnavailableException) e
                        .getCause();
                model.addAttribute("errorInventorySkuId", inventoryException.getSkuId().toString());
                model.addAttribute("errorInventoryAvail", inventoryException.getQuantityAvailable());
                return "redirect:/checkout";
            }
        }

        return getConfirmationView(cart.getOrderNumber());
    }

    return getCartPageRedirect();
}

From source file:cc.kune.core.server.manager.file.FileUploadManagerAbstract.java

/**
 * On other exception./* w  ww.  j a va2s  .co m*/
 * 
 * @param response
 *          the response
 * @param e
 *          the e
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
protected void onOtherException(final HttpServletResponse response, final Exception e) throws IOException {
    LOG.info("Exception: " + e.getCause());
    e.printStackTrace();
    doResponse(response, null);
}

From source file:com.googlecode.struts2gwtplugin.interceptor.GWTServlet.java

public String processCall(String payload) throws SerializationException {

    // default return value - Should this be something else?
    // no known constants to use in this case
    String result = null;/*from w w  w .j a v  a2s .  c  o  m*/

    // get the RPC Request from the request data
    //RPCRequest rpcRequest= RPC.decodeRequest(payload);
    RPCRequest rpcRequest = RPC.decodeRequest(payload, null, this);

    onAfterRequestDeserialized(rpcRequest);

    // get the parameter types for the method look-up
    Class<?>[] paramTypes = rpcRequest.getMethod().getParameterTypes();
    paramTypes = rpcRequest.getMethod().getParameterTypes();

    // we need to get the action method from Struts
    Method method = findInterfaceMethod(actionInvocation.getAction().getClass(),
            rpcRequest.getMethod().getName(), paramTypes, true);

    // if the method is null, this may be a hack attempt
    // or we have some other big problem
    if (method == null) {
        // present the params
        StringBuffer params = new StringBuffer();
        for (int i = 0; i < paramTypes.length; i++) {
            params.append(paramTypes[i]);
            if (i < paramTypes.length - 1) {
                params.append(", ");
            }
        }

        // throw a security exception, could be attempted hack
        throw new GWTServletException("Failed to locate method " + rpcRequest.getMethod().getName() + "("
                + params + ") on interface " + actionInvocation.getAction().getClass().getName()
                + " requested through interface " + rpcRequest.getClass().getName());
    }

    Object callResult = null;
    try {
        callResult = method.invoke(actionInvocation.getAction(), rpcRequest.getParameters());
        // package  up response for GWT
        result = RPC.encodeResponseForSuccess(method, callResult);

    } catch (Exception e) {
        // check for checked exceptions
        if (e.getCause() != null) {
            log.error("Struts2GWT exception", e.getCause());
            Throwable cause = e.getCause();
            boolean found = false;
            for (Class<?> checkedException : rpcRequest.getMethod().getExceptionTypes()) {
                if (cause.getClass().equals(checkedException)) {
                    found = true;
                    break;
                }
            }
            if (!found) {

                throw new Struts2GWTBridgeException("Unhandled exception!", cause);
            }
            result = RPC.encodeResponseForFailure(null, e.getCause(), rpcRequest.getSerializationPolicy());
        } else {
            throw new Struts2GWTBridgeException("Unable to serialize the exception.", e);
        }
    }

    // return our response
    return result;
}