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.baidu.qa.service.test.parser.CaseFolderParserImpl.java

/**
 * case???//from   w  w  w .  j a v a  2  s.  c  o  m
 * @param casepath
 * @return
 */
private CaseData parseCaseinfo(CaseData casedata, String casepath) {

    try {
        File[] inputfiles = FileUtil.getFiles(casepath + Constant.FILENAME_INPUT);

        File inputfile = null;
        for (File f : inputfiles) {
            String suffix = FileUtil.getFileSuffix(f);

            if (suffix.trim().equalsIgnoreCase(Constant.FILE_TYPE_INPUT)
                    || (suffix.trim().equalsIgnoreCase(Constant.FILE_TYPE_SOAP))
                    || (suffix.trim().equalsIgnoreCase(Constant.FILE_TYPE_INPUT_JSON))
                    || (suffix.trim().equalsIgnoreCase(Constant.FILE_TYPE_TPL))) {
                inputfile = f;
            }
        }

        if (inputfile != null) {
            FileCharsetDetector det = new FileCharsetDetector();
            try {
                String oldcharset = det.guestFileEncoding(inputfile);
                if (oldcharset.equalsIgnoreCase("UTF-8") == false)
                    FileUtil.transferFile(inputfile, oldcharset, "UTF-8");
            } catch (Exception ex) {
                log.error("[change expect file charset error]:" + ex);
                throw new RuntimeException("change expect file charset error", ex.getCause());
            }
        }

        //tpl?casedata
        casedata.setInputFile(inputfile);
        // ?propertiesxml?
        if (inputfile != null && FileUtil.getFileSuffix(inputfile).equalsIgnoreCase(Constant.FILE_TYPE_INPUT)) {
            casedata.setInput();
        } else if (inputfile != null
                && FileUtil.getFileSuffix(inputfile).equalsIgnoreCase(Constant.FILE_TYPE_INPUT_JSON)) {
            casedata.setInputJson(FileUtil.readFileByLines(inputfile));
        }

    } catch (Exception ex) {
        log.error("[parse " + Constant.FILENAME_INPUT + " error]:", ex);
        throw new RuntimeException("parse case info error", ex.getCause());
    }

    // ?
    File expect = new File(casepath + Constant.FILENAME_EXPECT);
    if (expect.exists()) {
        casedata.setExpect(expect.listFiles());
    }
    // ??SetUpTearDownSetupsetup...
    if (new File(casepath + Constant.FILENAME_SETUP).exists()) {
        casedata.setSetup(FileUtil.getFiles(casepath + Constant.FILENAME_SETUP));
    } else if (new File(casepath + "/Setup").exists()) {
        casedata.setSetup(FileUtil.getFiles(casepath + "/Setup"));
    } else if (new File(casepath + "/setup").exists()) {
        casedata.setSetup(FileUtil.getFiles(casepath + "/setup"));
    }
    if (new File(casepath + Constant.FILENAME_TEARDOWN).exists()) {
        casedata.setTeardown(FileUtil.getFiles(casepath + Constant.FILENAME_TEARDOWN));
    } else if (new File(casepath + "/Teardown").exists()) {
        casedata.setTeardown(FileUtil.getFiles(casepath + "/Teardown"));
    } else if (new File(casepath + "/teardown").exists()) {
        casedata.setTeardown(FileUtil.getFiles(casepath + "/teardown"));
    }

    casedata.setCaselocation(casepath);
    return casedata;
}

From source file:com.justcloud.osgifier.servlet.OsgifierServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = buildUrl(req);//from   www . jav  a 2s . c o m
    Map<String, ?> params = new HashMap<String, Object>();

    Map<String, String> resultMap = new HashMap<String, String>();

    try {
        params = deserializer.deserialize(req.getReader());
        if ("/login".equals(path)) {
            SessionService sessionService = (SessionService) findInstance(SessionServiceImpl.class);
            User user = sessionService.login((String) params.get("username"), (String) params.get("password"));
            resultMap.put("outcome", "success");
            req.getSession().setAttribute("user", user);
            if (user != null) {
                resultMap.put("result", serializer.deepSerialize(user));
            }
        } else if ("/logout".equals(path)) {
            req.getSession().removeAttribute("user");
            req.getSession().invalidate();
            resultMap.put("outcome", "success");
        } else {
            Method m = findRestMethod(RESTMethod.POST, path);
            @SuppressWarnings("unchecked")
            Service instance = findInstance((Class<? extends Service>) m.getDeclaringClass());
            Object args[] = new Object[m.getParameterTypes().length];

            int i = 0;

            for (Annotation[] annotations : m.getParameterAnnotations()) {
                RESTParam restAnnotation = null;

                for (Annotation a : annotations) {
                    if (a.annotationType() == RESTParam.class) {
                        restAnnotation = (RESTParam) a;
                        break;
                    }
                }
                if (restAnnotation == null) {
                    throw new RuntimeException("REST method has non REST annotated parameter");
                }
                Class<?> targetClass = m.getParameterTypes()[i];
                Object value;
                if (restAnnotation.session()) {
                    value = convert(req.getSession().getAttribute(restAnnotation.value()), targetClass);
                } else {
                    value = convert(params.get(restAnnotation.value()), targetClass);
                }
                if (value == null) {
                    throw new RuntimeException(
                            "Parameter " + restAnnotation.value() + " not found in request for " + path);
                }
                args[i++] = value;
            }

            Object result = m.invoke(instance, args);
            resultMap.put("outcome", "success");
            if (result != null) {
                resultMap.put("result", serializer.deepSerialize(result));
            }
        }

    } catch (Exception e) {
        Throwable t = e;
        if (e instanceof InvocationTargetException) {
            t = e.getCause();
        }
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);

        t.printStackTrace(writer);

        resultMap.put("outcome", "error");
        resultMap.put("message", t.getMessage());
        resultMap.put("type", t.getClass().getCanonicalName());
        resultMap.put("stacktrace", stringWriter.getBuffer().toString());
    }

    resp.setContentType("application/json");
    resp.setCharacterEncoding("UTF-8");

    serializer.deepSerialize(resultMap, resp.getWriter());
}

From source file:com.amazonaws.mobileconnectors.s3.transferutility.DownloadTask.java

/**
 * Runs download task and returns whether successfully downloaded.
 *//* w  w  w  .  j a v  a 2s .  c o  m*/
@Override
public Boolean call() throws Exception {
    if (!networkInfo.isNetworkConnected()) {
        updater.updateState(download.id, TransferState.WAITING_FOR_NETWORK);
        return false;
    }
    updater.updateState(download.id, TransferState.IN_PROGRESS);

    final GetObjectRequest getObjectRequest = new GetObjectRequest(download.bucketName, download.key);
    TransferUtility.appendTransferServiceUserAgentString(getObjectRequest);
    final File file = new File(download.file);
    final long bytesCurrent = file.length();
    if (bytesCurrent > 0) {
        LOGGER.debug(String.format("Resume transfer %d from %d bytes", download.id, bytesCurrent));
        /*
         * Setting the last byte position to ?1 means downloading the object
         * from bytesCurrent to the end.
         */
        getObjectRequest.setRange(bytesCurrent, -1);
    }
    getObjectRequest.setGeneralProgressListener(updater.newProgressListener(download.id));

    try {
        final S3Object object = s3.getObject(getObjectRequest);
        if (object == null) {
            updater.throwError(download.id, new IllegalStateException("AmazonS3.getObject returns null"));
            updater.updateState(download.id, TransferState.FAILED);
            return false;
        }

        final long bytesTotal = object.getObjectMetadata().getInstanceLength();
        updater.updateProgress(download.id, bytesCurrent, bytesTotal);
        saveToFile(object.getObjectContent(), file);
        updater.updateProgress(download.id, bytesTotal, bytesTotal);
        updater.updateState(download.id, TransferState.COMPLETED);
        return true;
    } catch (final Exception e) {
        if (RetryUtils.isInterrupted(e)) {
            /*
             * thread is interrupted by user. don't update the state as it's
             * set by caller who interrupted
             */
            LOGGER.debug("Transfer " + download.id + " is interrupted by user");
        } else if (e.getCause() != null
                && (e.getCause() instanceof IOException || e.getCause() instanceof AmazonClientException)
                && !networkInfo.isNetworkConnected()) {
            LOGGER.debug("Transfer " + download.id + " waits for network");
            updater.updateState(download.id, TransferState.WAITING_FOR_NETWORK);
        } else {
            LOGGER.debug("Failed to download: " + download.id + " due to " + e.getMessage());
            updater.throwError(download.id, e);
            updater.updateState(download.id, TransferState.FAILED);
        }
    }
    return false;
}

From source file:com.nextdoor.bender.ipc.s3.S3TransporterTest.java

@Test(expected = TransportException.class)
public void testAmazonClientException() throws TransportException, IllegalStateException, IOException {
    /*//from w  ww.jav  a 2  s  .  co  m
     * Create mock client, requets, and replies
     */
    AmazonS3Client mockClient = mock(AmazonS3Client.class);
    UploadPartResult uploadResult = new UploadPartResult();
    uploadResult.setETag("foo");
    doThrow(new AmazonClientException("expected")).when(mockClient).uploadPart(any(UploadPartRequest.class));

    InitiateMultipartUploadResult initUploadResult = new InitiateMultipartUploadResult();
    initUploadResult.setUploadId("123");
    doReturn(initUploadResult).when(mockClient)
            .initiateMultipartUpload(any(InitiateMultipartUploadRequest.class));

    /*
     * Fill buffer with mock data
     */
    S3TransportBuffer buffer = new S3TransportBuffer(1000, false, new S3TransportSerializer());
    InternalEvent mockIevent = mock(InternalEvent.class);
    doReturn("foo").when(mockIevent).getSerialized();

    /*
     * Create transport
     */
    Map<String, MultiPartUpload> multiPartUploads = new HashMap<String, MultiPartUpload>(0);
    S3Transport transport = new S3Transport(mockClient, "bucket", "basepath", false, multiPartUploads);

    /*
     * Do actual test
     */
    buffer.add(mockIevent);
    LinkedHashMap<String, String> partitions = new LinkedHashMap<String, String>();
    partitions.put(S3Transport.FILENAME_KEY, "a_filename");

    ArgumentCaptor<UploadPartRequest> argument = ArgumentCaptor.forClass(UploadPartRequest.class);
    try {
        transport.sendBatch(buffer, partitions, new TestContext());
    } catch (Exception e) {
        assertEquals(e.getCause().getClass(), AmazonClientException.class);
        throw e;
    }
}

From source file:org.dspace.services.events.SystemEventService.java

/**
 * Checks to see if the filtering in the given listener allows the 
 * event to be received./*from  w  w  w  . jav  a  2s  . c om*/
 * 
 * @param listener an event listener
 * @param event an event
 * @return true if the event should be received, false if the event is filtered out
 */
private boolean filterEvent(EventListener listener, Event event) {
    if (listener == null || event == null) {
        return false;
    }
    // filter the event if the listener has filter rules
    boolean allowName = true;
    try {
        String[] namePrefixes = listener.getEventNamePrefixes();
        if (namePrefixes != null && namePrefixes.length > 0) {
            allowName = false;
            for (String namePrefix : namePrefixes) {
                String eventName = event.getName();
                if (namePrefix != null && namePrefix.length() > 0 && eventName.startsWith(namePrefix)) {
                    allowName = true;
                    break;
                }
            }
        }
    } catch (Exception e1) {
        log.warn("Listener (" + listener + ")[" + listener.getClass().getName()
                + "] failure calling getEventNamePrefixes: " + e1.getMessage() + ":" + e1.getCause());
    }
    boolean allowResource = true;
    try {
        String resourcePrefix = listener.getResourcePrefix();
        if (resourcePrefix != null && resourcePrefix.length() > 0) {
            allowResource = false;
            String resRef = event.getResourceReference();
            if (resRef == null) {
                // null references default to unfiltered
                allowResource = true;
            } else {
                if (resRef.startsWith(resourcePrefix)) {
                    allowResource = true;
                }
            }
        }
    } catch (Exception e1) {
        log.warn("Listener (" + listener + ")[" + listener.getClass().getName()
                + "] failure calling getResourcePrefix: " + e1.getMessage() + ":" + e1.getCause());
    }

    return allowName && allowResource;
}

From source file:hoot.services.db.DbUtils.java

public static void deleteOSMRecord(Connection conn, Long mapId) throws Exception {
    try {/*from   w w w.j a  v  a2 s .c o  m*/
        deleteMapRelatedTablesByMapId(mapId);

        conn.setAutoCommit(false);
        Configuration configuration = getConfiguration();

        QMaps maps = QMaps.maps;
        new SQLDeleteClause(conn, configuration, maps).where(maps.id.eq(mapId)).execute();

        QReviewItems reviewItems = QReviewItems.reviewItems;
        new SQLDeleteClause(conn, configuration, reviewItems).where(reviewItems.mapId.eq(mapId)).execute();

        QElementIdMappings elementIdMappings = QElementIdMappings.elementIdMappings;
        new SQLDeleteClause(conn, configuration, elementIdMappings).where(elementIdMappings.mapId.eq(mapId))
                .execute();

        QReviewMap reviewMap = QReviewMap.reviewMap;
        new SQLDeleteClause(conn, configuration, reviewMap).where(reviewMap.mapId.eq(mapId)).execute();

        conn.commit();
    } catch (Exception e) {
        String msg = "Error deleting OSM record.  ";
        msg += "  " + e.getCause().getMessage();

        throw new Exception(msg);
    } finally {
        conn.setAutoCommit(true);
    }
}

From source file:hoot.services.db.DbUtils.java

public static void deleteOSMRecordByName(Connection conn, String mapName) throws Exception {
    try {/*w w  w . j a v  a 2s  .c o  m*/
        Configuration configuration = getConfiguration();

        QMaps maps = QMaps.maps;
        List<Long> mapIds = new SQLQuery(conn, configuration).from(maps)
                .where(maps.displayName.equalsIgnoreCase(mapName)).list(maps.id);

        if (mapIds.size() > 0) {
            Long mapId = mapIds.get(0);
            deleteMapRelatedTablesByMapId(mapId);

            conn.setAutoCommit(false);

            ListSubQuery<Long> res = new SQLSubQuery().from(maps)
                    .where(maps.displayName.equalsIgnoreCase(mapName)).list(maps.id);

            new SQLDeleteClause(conn, configuration, maps).where(maps.displayName.eq(mapName)).execute();

            QReviewItems reviewItems = QReviewItems.reviewItems;
            new SQLDeleteClause(conn, configuration, reviewItems).where(reviewItems.mapId.in(res)).execute();

            QElementIdMappings elementIdMappings = QElementIdMappings.elementIdMappings;
            new SQLDeleteClause(conn, configuration, elementIdMappings).where(elementIdMappings.mapId.in(res))
                    .execute();

            QReviewMap reviewMap = QReviewMap.reviewMap;
            new SQLDeleteClause(conn, configuration, reviewMap).where(reviewMap.mapId.in(res)).execute();

            conn.commit();
        }
    } catch (Exception e) {
        String msg = "Error deleting OSM record.  ";
        if (e.getCause() instanceof BatchUpdateException) {
            BatchUpdateException batchException = (BatchUpdateException) e.getCause();
            msg += "  " + batchException.getNextException().getMessage();
        }
        throw new Exception(msg);
    }
}

From source file:com.taobao.datax.plugins.writer.mysqlwriter.MysqlWriter.java

@Override
public int prepare(PluginParam param) {
    this.setParam(param);

    DBSource.register(this.sourceUniqKey, this.genProperties());

    if (StringUtils.isBlank(this.pre))
        return PluginStatus.SUCCESS.value();

    Statement stmt = null;//from  w w w .  j  a  v a 2  s . c  o  m
    try {
        this.connection = DBSource.getConnection(this.sourceUniqKey);

        stmt = this.connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

        for (String subSql : this.pre.split(";")) {
            this.logger.info(String.format("Excute prepare sql %s .", subSql));
            stmt.execute(subSql);
        }

        return PluginStatus.SUCCESS.value();
    } catch (Exception e) {
        throw new DataExchangeException(e.getCause());
    } finally {
        try {
            if (null != stmt) {
                stmt.close();
            }
            if (null != this.connection) {
                this.connection.close();
                this.connection = null;
            }
        } catch (SQLException e) {
        }
    }
}

From source file:com.newatlanta.appengine.datastore.CachingDatastoreService.java

@Override
@SuppressWarnings("unchecked")
public List<Key> put(Iterable<Entity> entities) {
    Map<Key, Entity> entityMap = getEntityMap(entities);
    MemcacheService memcache = getMemcacheService();
    memcache.setErrorHandler(new StrictErrorHandler());
    try {/* w  w w  .  j a  va  2  s . c  o m*/
        memcache.putAll((Map) entityMap, expiration);
        if ((cacheOption == CacheOption.WRITE_BEHIND) && watchDogIsAlive()) {
            List<Key> keyList = new ArrayList<Key>(entityMap.keySet());
            queue.add(payload(serialize(keyList), TASK_CONTENT_TYPE));
            return keyList;
        }
    } catch (Exception e) {
        log.warning(e.getCause() != null ? e.getCause().getMessage() : e.getMessage());
        memcache.deleteAll((Collection) entityMap.keySet());
    }
    // if WRITE_THROUGH, or failed to write memcache, or failed to queue
    // write-behind task, then write directly to datastore
    return getDatastoreService().put(entities);
}

From source file:org.pentaho.di.ui.core.dialog.ErrorDialogTest.java

@Test
public void setErrorTextWithCauseMessageException() {
    ClientProtocolException cpe = new ClientProtocolException("causeMessage");
    Exception e = new KettleException("kettleMessage", cpe);

    StringBuilder text = new StringBuilder();
    StringBuilder details = new StringBuilder();

    ErrorDialog dialog = mock(ErrorDialog.class);
    doCallRealMethod().when(dialog).handleException(anyString(), any(Exception.class), any(StringBuilder.class),
            any(StringBuilder.class));

    dialog.handleException("argMessage", e, text, details);

    Throwable cause = e.getCause();

    assertEquals(text.toString(), cause.getMessage().toString());

}