Example usage for java.lang Throwable Throwable

List of usage examples for java.lang Throwable Throwable

Introduction

In this page you can find the example usage for java.lang Throwable Throwable.

Prototype

public Throwable(Throwable cause) 

Source Link

Document

Constructs a new throwable with the specified cause and a detail message of (cause==null ?

Usage

From source file:ch.flashcard.HibernateDetachUtility.java

public static void nullOutUninitializedFields(Object value, SerializationType serializationType)
        throws Exception {
    long start = System.currentTimeMillis();
    Map<Integer, Object> checkedObjectMap = new HashMap<Integer, Object>();
    Map<Integer, List<Object>> checkedObjectCollisionMap = new HashMap<Integer, List<Object>>();
    nullOutUninitializedFields(value, checkedObjectMap, checkedObjectCollisionMap, 10, serializationType);
    long duration = System.currentTimeMillis() - start;

    if (dumpStackOnThresholdLimit) {
        int numObjectsProcessed = checkedObjectMap.size();
        if (duration > millisThresholdLimit || numObjectsProcessed > sizeThresholdLimit) {
            String rootObjectString = (value != null) ? value.getClass().toString() : "null";
            LOG.warn("Detached [" + numObjectsProcessed + "] objects in [" + duration + "]ms from root object ["
                    + rootObjectString + "]", new Throwable("HIBERNATE DETACH UTILITY STACK TRACE"));
        }//  w  ww  .ja  v  a 2  s .c om
    } else {
        // 10s is really long, log SOMETHING
        if (duration > 10000L && LOG.isDebugEnabled()) {
            LOG.debug("Detached [" + checkedObjectMap.size() + "] objects in [" + duration + "]ms");
        }
    }

    // help the garbage collector be clearing these before we leave
    checkedObjectMap.clear();
    checkedObjectCollisionMap.clear();
}

From source file:org.drools.workbench.screens.dtablexls.backend.server.DecisionTableXLSServiceImplTest.java

private void testInvalidTable(Consumer<DecisionTableXLSServiceImpl> serviceConsumer) throws IOException {
    this.service = getServiceWithValidationOverride((tempFile) -> {
        // mock an invalid file
        Throwable t = new Throwable("testing invalid xls dt creation");
        throw new DecisionTableParseException("DecisionTableParseException: " + t.getMessage(), t);
    });//from w w w .ja  va2 s .co m

    mockStatic(IOUtils.class);
    when(IOUtils.copy(any(InputStream.class), any(OutputStream.class))).thenReturn(0);
    try {
        serviceConsumer.accept(service);
    } catch (RuntimeException e) {
        // this is expected correct behavior
    }
    verify(ioService, never()).newOutputStream(any(org.uberfire.java.nio.file.Path.class),
            any(CommentedOption.class));
    verifyStatic(never());
}

From source file:fr.gael.dhus.server.http.valve.AccessValve.java

@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
    // valve disabled or previous valve sent an error, return
    if (!isEnable() || response.isError()) {
        getNext().invoke(request, response);
        return;/*from   w  ww  . java 2 s .  c  o  m*/
    }

    final AccessInformation ai = new AccessInformation();
    ai.setConnectionStatus(new PendingConnectionStatus());

    // To be sure not to retrieve the same date trough concurrency calls.
    synchronized (this) {
        ai.setStartTimestamp(System.nanoTime());
        ai.setStartDate(new Date());
    }
    try {
        this.doLog(request, response, ai);
    } finally {
        Element cached_element = new Element(UUID.randomUUID(), ai);
        getCache().put(cached_element);

        try {
            // Log of the pending request command.
            if (isUseLogger())
                LOGGER.info("Access " + ai);

            getNext().invoke(request, response);
        } catch (Throwable e) {
            response.addHeader("cause-message", e.getClass().getSimpleName() + " : " + e.getMessage());
            //ai.setConnectionStatus(new FailureConnectionStatus(e));
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            //throw e;
        } finally {
            ai.setReponseSize(response.getContentLength());
            ai.setWrittenResponseSize(response.getContentWritten());

            if (response.getStatus() >= 400) {
                String message = RequestUtil.filter(response.getMessage());
                if (message == null) {
                    // The cause-message has been inserted into the reponse header
                    // at error handler time. It no message is retrieved in the
                    // standard response, the cause-message is used.
                    message = response.getHeader("cause-message");
                }
                Throwable throwable = null;
                if (message != null)
                    throwable = new Throwable(message);
                else
                    throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
                if (throwable == null)
                    throwable = new Throwable();

                ai.setConnectionStatus(new FailureConnectionStatus(throwable));
            } else
                ai.setConnectionStatus(new SuccessConnectionStatus());

            ai.setEndTimestamp(System.nanoTime());
            if ((getPattern() == null) || ai.getRequest().matches(getPattern())) {
                cached_element.updateUpdateStatistics();
                if (isUseLogger())
                    LOGGER.info("Access " + ai);
            }
        }
    }
}

From source file:org.terasoluna.gfw.functionaltest.app.exceptionhandling.ExceptionHandlingController.java

@RequestMapping(value = "3_4", method = RequestMethod.GET)
public String servletFrameworkHandling_03_04() {

    exceptionHandlingService.throwException(
            new SystemException("e.xx.xxx", "3_4 SystemException", new Throwable("create throwable")));

    return "exceptionhandling/index";
}

From source file:com.example.download.DownloadThread.java

/**
 * Executes the download in a separate thread
 *//*www  .j  av  a  2s . c o m*/
public void run() {

    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo);
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = DownloadManager.Impl.STATUS_UNKNOWN_ERROR;

    try {
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, com.example.util.Utils.sLogTag);
        wakeLock.acquire();

        Utils.D("initiating download for " + mInfo.mUri);

        client = HttpClientFactory.get().getHttpClient();

        boolean finished = false;
        while (!finished) {

            Utils.D("Initiating request for download " + mInfo.mId + " url " + mInfo.mUri);

            HttpGet request = new HttpGet(state.mRequestUri);
            try {
                executeDownload(state, client, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                request.abort();
                request = null;
            }
        }

        Utils.D("download completed for " + mInfo.mUri);

        if (!checkFile(state)) {
            throw new Throwable("File MD5 code is not the same as server");
        }

        finalizeDestinationFile(state);
        finalStatus = DownloadManager.Impl.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Utils.W("Aborting request for download " + mInfo.mId + " url: " + mInfo.mUri + " : "
                + error.getMessage());
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { //sometimes the socket code throws unchecked exceptions
        Utils.W("Exception for id " + mInfo.mId + " url: " + mInfo.mUri + ": " + ex);
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            client = null;
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount,
                state.mGotData, state.mFilename, state.mNewUri, state.mMimeType);
        mInfo.mHasActiveThread = false;
    }
}

From source file:com.mappn.gfan.common.download.DownloadThread.java

/**
 * Executes the download in a separate thread
 *//* w  ww . ja  v  a  2 s .c o m*/
public void run() {

    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo);
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = DownloadManager.Impl.STATUS_UNKNOWN_ERROR;

    try {
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, com.mappn.gfan.common.util.Utils.sLogTag);
        wakeLock.acquire();

        Utils.D("initiating download for " + mInfo.mUri);

        client = HttpClientFactory.get().getHttpClient();

        boolean finished = false;
        while (!finished) {

            Utils.D("Initiating request for download " + mInfo.mId + " url " + mInfo.mUri);

            HttpGet request = new HttpGet(state.mRequestUri);
            try {
                executeDownload(state, client, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                request.abort();
                request = null;
            }
        }

        Utils.D("download completed for " + mInfo.mUri);

        if (!checkFile(state)) {
            throw new Throwable("File MD5 code is not the same as server");
        }

        finalizeDestinationFile(state);
        finalStatus = DownloadManager.Impl.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Utils.W("Aborting request for download " + mInfo.mId + " url: " + mInfo.mUri + " : "
                + error.getMessage());
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { //sometimes the socket code throws unchecked exceptions
        Utils.W("Exception for id " + mInfo.mId + " url: " + mInfo.mUri + ": " + ex);
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            client = null;
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount,
                state.mGotData, state.mFilename, state.mNewUri, state.mMimeType);
        mInfo.mHasActiveThread = false;
    }
}

From source file:com.lan.nicehair.common.download.DownloadThread.java

/**
 * Executes the download in a separate thread
 *///from w  ww.  jav  a2s. c om
public void run() {

    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo);
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = DownloadManager.Impl.STATUS_UNKNOWN_ERROR;

    try {
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        wakeLock.acquire();

        AppLog.d(TAG, "initiating download for " + mInfo.mUri);

        client = HttpClientFactory.get().getHttpClient();

        boolean finished = false;
        while (!finished) {

            AppLog.d(TAG, "Initiating request for download " + mInfo.mId + " url " + mInfo.mUri);

            HttpGet request = new HttpGet(state.mRequestUri);
            try {
                executeDownload(state, client, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                request.abort();
                request = null;
            }
        }

        AppLog.d(TAG, "download completed for " + mInfo.mUri);

        if (!checkFile(state)) {
            throw new Throwable("File MD5 code is not the same as server");
        }

        finalizeDestinationFile(state);
        finalStatus = DownloadManager.Impl.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        AppLog.e(TAG, "Aborting request for download " + mInfo.mId + " url: " + mInfo.mUri + " : "
                + error.getMessage());
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { //sometimes the socket code throws unchecked exceptions
        AppLog.e(TAG, "Exception for id " + mInfo.mId + " url: " + mInfo.mUri + ": " + ex);
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            client = null;
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount,
                state.mGotData, state.mFilename, state.mNewUri, state.mMimeType);
        mInfo.mHasActiveThread = false;
    }
}

From source file:io.openkit.OKScore.java

private void submitScoreBase(final ScoreRequestResponseHandler responseHandler) {
    try {/*  w w  w.  j  ava2 s.c  o m*/
        JSONObject scoreJSON = getScoreAsJSON();

        JSONObject requestParams = new JSONObject();
        requestParams.put("app_key", OpenKit.getAppKey());
        requestParams.put("score", scoreJSON);

        OKHTTPClient.postJSON("/scores", requestParams, new OKJsonHttpResponseHandler() {

            @Override
            public void onSuccess(JSONObject object) {
                OKScore.this.setSubmitted(true);
                responseHandler.onSuccess();
            }

            @Override
            public void onSuccess(JSONArray array) {
                //This should not be called, submitting a score should
                // not return an array, so this is an errror case
                OKScore.this.setSubmitted(false);
                responseHandler.onFailure(new Throwable(
                        "Unknown error from OpenKit servers. Received an array when expecting an object"));
            }

            @Override
            public void onFailure(Throwable error, String content) {
                OKScore.this.setSubmitted(false);
                OKUserUtilities.checkIfErrorIsUnsubscribedUserError(error);
                responseHandler.onFailure(error);
            }

            @Override
            public void onFailure(Throwable e, JSONArray errorResponse) {
                OKScore.this.setSubmitted(false);
                OKUserUtilities.checkIfErrorIsUnsubscribedUserError(e);
                responseHandler.onFailure(e);
            }

            @Override
            public void onFailure(Throwable e, JSONObject errorResponse) {
                OKScore.this.setSubmitted(false);
                OKUserUtilities.checkIfErrorIsUnsubscribedUserError(e);
                responseHandler.onFailure(e);
            }
        });

    } catch (JSONException e) {
        responseHandler.onFailure(new Throwable("OpenKit JSON parsing error"));
        OKScore.this.setSubmitted(false);
    }

}

From source file:com.amazonaws.services.kinesis.multilang.StreamingRecordProcessorTest.java

@Test
public void processorPhasesTest() throws InterruptedException, ExecutionException {

    Answer<StatusMessage> answer = new Answer<StatusMessage>() {

        StatusMessage[] answers = new StatusMessage[] { new StatusMessage(InitializeMessage.ACTION),
                new StatusMessage(ProcessRecordsMessage.ACTION),
                new StatusMessage(ProcessRecordsMessage.ACTION), new StatusMessage(ShutdownMessage.ACTION) };

        int callCount = 0;

        @Override/*from w ww . jav a 2s. c o  m*/
        public StatusMessage answer(InvocationOnMock invocation) throws Throwable {
            if (callCount < answers.length) {
                return answers[callCount++];
            } else {
                throw new Throwable("Too many calls to getNextStatusMessage");
            }
        }
    };

    phases(answer);

    Mockito.verify(messageWriter, Mockito.times(1)).writeInitializeMessage(shardId);
    Mockito.verify(messageWriter, Mockito.times(2)).writeProcessRecordsMessage(Mockito.anyList());
    Mockito.verify(messageWriter, Mockito.times(1)).writeShutdownMessage(ShutdownReason.ZOMBIE);
}

From source file:com.mellanox.r4h.LeaseRenewer.java

private LeaseRenewer(Factory.Key factorykey) {
    this.factorykey = factorykey;
    unsyncSetGraceSleepPeriod(LEASE_RENEWER_GRACE_DEFAULT);

    if (LOG.isTraceEnabled()) {
        instantiationTrace = StringUtils.stringifyException(new Throwable("TRACE"));
    } else {/*www .  j a  v  a 2 s.  c o m*/
        instantiationTrace = null;
    }
}