Example usage for java.lang InterruptedException InterruptedException

List of usage examples for java.lang InterruptedException InterruptedException

Introduction

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

Prototype

public InterruptedException() 

Source Link

Document

Constructs an InterruptedException with no detail message.

Usage

From source file:no.sesat.search.mode.command.AbstractSearchCommand.java

/** If the command has been cancelled will throw the appropriate SearchCommandException.
 * Calling this method only makes sense once the call() method has been,
 *   otherwise it is guaranteed to throw the exception.
 * @throws SearchCommandException when cancellation has occurred.
 **//* w  ww . j a  va  2s  .c  om*/
private void checkForCancellation() throws SearchCommandException {
    if (isCancelled()) {
        throw new SearchCommandException("cancelled", new InterruptedException());
    }
}

From source file:org.eclipse.jubula.client.core.persistence.ProjectPM.java

/**
 * Handles a <code>PersistenceException</code>.
 * /* w w  w  .j a  va2s.  c  o m*/
 * @param mapperList The Parameter Name mapping list.
 * @param s The session.
 * @param tx The transaction.
 * @param e The exception.
 * @throws PMException if the rollback of the transaction fails.
 * @throws InterruptedException if the cause of the given exception was 
 *                              that the operation was canceled.
 * @throws PMSaveException wrapper for the Persistence exception.
 */
private static void handlePersistenceException(List<INameMapper> mapperList, EntityManager s,
        EntityTransaction tx, PersistenceException e)
        throws PMException, InterruptedException, PMSaveException {

    if (tx != null) {
        Persistor.instance().rollbackTransaction(s, tx);
    }
    if (e.getCause() instanceof InterruptedException) {

        GeneralStorage.getInstance().reset();
        for (INameMapper mapper : mapperList) {
            mapper.clearAllNames();
        }
        // Operation was canceled.
        throw new InterruptedException();
    }
    String msg = Messages.CantAttachProject + StringConstants.DOT;
    throw new PMSaveException(msg + e.getMessage(), MessageIDs.E_ATTACH_PROJECT);
}

From source file:com.ksc.http.KSCHttpClient.java

/**
 * Returns the response from executing one httpClientSettings request; or null for retry.
 *//*from  ww  w.  j av  a2s . c  o m*/
private <T> Response<T> executeOneRequest(final Request<?> request,
        final HttpResponseHandler<KscWebServiceResponse<T>> responseHandler,
        final HttpResponseHandler<KscServiceException> errorResponseHandler, final ExecutionContext execContext,
        final KscRequestMetrics kscRequestMetrics, ExecOneRequestParams execOneParams,
        List<RequestHandler2> requestHandlers) throws IOException, InterruptedException {
    if (execOneParams.isRetry()) {
        resetRequestInputStream(request);
    }
    checkInterrupted();
    if (requestLog.isDebugEnabled()) {
        requestLog.debug("Sending Request: " + request);
    }
    final AWSCredentials credentials = getCredentialsFromContext(execContext, kscRequestMetrics);
    final KscWebServiceRequest kscreq = request.getOriginalRequest();
    final ProgressListener listener = kscreq.getGeneralProgressListener();

    if (execOneParams.isRetry()) {
        pauseBeforeRetry(request, kscRequestMetrics, execOneParams, listener);
    }
    updateRetryHeaderInfo(request, execOneParams);

    // Sign the request if a signer was provided
    execOneParams.newSigner(request, execContext);
    if (execOneParams.signer != null && credentials != null) {
        kscRequestMetrics.startEvent(Field.RequestSigningTime);
        try {
            if (timeOffset != 0) {
                // Always use the client level timeOffset if it was
                // non-zero; Otherwise, we respect the timeOffset in the
                // request, which could have been externally configured (at
                // least for the 1st non-retry request).
                //
                // For retry due to clock skew, the timeOffset in the
                // request used for the retry is assumed to have been
                // adjusted when execution reaches here.
                request.setTimeOffset(timeOffset);
            }
            execOneParams.signer.sign(request, credentials);
        } finally {
            kscRequestMetrics.endEvent(Field.RequestSigningTime);
        }
    }

    checkInterrupted();
    execOneParams.newApacheRequest(httpRequestFactory, request, httpClientSettings);

    captureConnectionPoolMetrics(kscRequestMetrics);

    final HttpClientContext localRequestContext = ApacheUtils.newClientContext(httpClientSettings,
            ImmutableMapParameter.of(KscRequestMetrics.class.getSimpleName(), kscRequestMetrics));

    execOneParams.resetBeforeHttpRequest();
    publishProgress(listener, ProgressEventType.HTTP_REQUEST_STARTED_EVENT);
    kscRequestMetrics.startEvent(Field.HttpRequestTime);
    kscRequestMetrics.setCounter(Field.RetryCapacityConsumed, retryCapacity.consumedCapacity());

    /////////// Send HTTP request ////////////
    execContext.getClientExecutionTrackerTask().setCurrentHttpRequest(execOneParams.apacheRequest);
    final boolean isHeaderReqIdAvail;
    final HttpRequestAbortTaskTracker requestAbortTaskTracker = httpRequestTimer
            .startTimer(execOneParams.apacheRequest, getRequestTimeout(kscreq));

    try {
        execOneParams.apacheResponse = httpClient.execute(execOneParams.apacheRequest, localRequestContext);
        if (shouldBufferHttpEntity(responseHandler.needsConnectionLeftOpen(), execContext, execOneParams,
                requestAbortTaskTracker)) {
            execOneParams.apacheResponse
                    .setEntity(new BufferedHttpEntity(execOneParams.apacheResponse.getEntity()));
        }
        isHeaderReqIdAvail = logHeaderRequestId(execOneParams.apacheResponse);
    } catch (IOException ioe) {
        // Client execution timeouts take precedence as it's not retryable
        if (execContext.getClientExecutionTrackerTask().hasTimeoutExpired()) {
            throw new InterruptedException();
        } else if (requestAbortTaskTracker.httpRequestAborted()) {
            throw new HttpRequestTimeoutException(ioe);
        } else {
            throw ioe;
        }
    } finally {
        requestAbortTaskTracker.cancelTask();
        kscRequestMetrics.endEvent(Field.HttpRequestTime);
    }

    publishProgress(listener, ProgressEventType.HTTP_REQUEST_COMPLETED_EVENT);
    final StatusLine statusLine = execOneParams.apacheResponse.getStatusLine();
    final int statusCode = statusLine == null ? -1 : statusLine.getStatusCode();
    if (isRequestSuccessful(execOneParams.apacheResponse)) {
        kscRequestMetrics.addProperty(Field.StatusCode, statusCode);
        /*
         * If we get back any 2xx status code, then we know we should treat the service call as
         * successful.
         */
        execOneParams.leaveHttpConnectionOpen = responseHandler.needsConnectionLeftOpen();
        HttpResponse httpResponse = createResponse(execOneParams.apacheRequest, request,
                execOneParams.apacheResponse);
        T response = handleResponse(request, responseHandler, execOneParams.apacheRequest, httpResponse,
                execOneParams.apacheResponse, execContext, isHeaderReqIdAvail, requestHandlers);

        /*
         * If this was a successful retry attempt we'll release the full retry capacity that
         * the attempt originally consumed.  If this was a successful initial request
         * we return a lesser amount.
         */
        if (execOneParams.isRetry() && execContext.retryCapacityConsumed()) {
            retryCapacity.release(THROTTLED_RETRY_COST);
        } else {
            retryCapacity.release();
        }
        return new Response<T>(response, httpResponse);
    }
    if (isTemporaryRedirect(execOneParams.apacheResponse)) {
        /*
         * S3 sends 307 Temporary Redirects if you try to delete an EU bucket from the US
         * endpoint. If we get a 307, we'll point the HTTP method to the redirected location,
         * and let the next retry deliver the request to the right location.
         */
        Header[] locationHeaders = execOneParams.apacheResponse.getHeaders("location");
        String redirectedLocation = locationHeaders[0].getValue();
        if (log.isDebugEnabled())
            log.debug("Redirecting to: " + redirectedLocation);
        execOneParams.redirectedURI = URI.create(redirectedLocation);
        kscRequestMetrics.addPropertyWith(Field.StatusCode, statusCode)
                .addPropertyWith(Field.RedirectLocation, redirectedLocation)
                .addPropertyWith(Field.KSCRequestID, null);
        return null; // => retry
    }
    execOneParams.leaveHttpConnectionOpen = errorResponseHandler.needsConnectionLeftOpen();
    final KscServiceException ase = handleErrorResponse(request, errorResponseHandler,
            execOneParams.apacheRequest, execOneParams.apacheResponse);
    kscRequestMetrics.addPropertyWith(Field.KSCRequestID, ase.getRequestId())
            .addPropertyWith(Field.KSCErrorCode, ase.getErrorCode())
            .addPropertyWith(Field.StatusCode, ase.getStatusCode());
    // Check whether we should internally retry the auth error
    execOneParams.authRetryParam = null;
    AuthErrorRetryStrategy authRetry = execContext.getAuthErrorRetryStrategy();
    if (authRetry != null) {
        HttpResponse httpResponse = createResponse(execOneParams.apacheRequest, request,
                execOneParams.apacheResponse);
        execOneParams.authRetryParam = authRetry.shouldRetryWithAuthParam(request, httpResponse, ase);
    }
    if (execOneParams.authRetryParam == null
            && !shouldRetry(request.getOriginalRequest(), execOneParams, ase, execContext)) {
        throw ase;
    }
    // Comment out for now. Ref: CR2662349
    // Preserve the cause of retry before retrying
    // kscRequestMetrics.addProperty(RetryCause, ase);
    if (RetryUtils.isThrottlingException(ase)) {
        kscRequestMetrics.incrementCounterWith(Field.ThrottleException).addProperty(Field.ThrottleException,
                ase);
    }
    // Cache the retryable exception
    execOneParams.retriedException = ase;
    /*
     * Checking for clock skew error again because we don't want to set the global time offset
     * for every service exception.
     */
    if (RetryUtils.isClockSkewError(ase)) {
        int clockSkew = parseClockSkewOffset(execOneParams.apacheResponse, ase);
        SDKGlobalTime.setGlobalTimeOffset(timeOffset = clockSkew);
        request.setTimeOffset(timeOffset); // adjust time offset for the retry
    }
    return null; // => retry
}

From source file:org.eclipse.jubula.client.core.persistence.ProjectPM.java

/**
 * Handles the cancellation of an operation.
 * //from   ww w  . j  a v  a2  s.  com
 * @param mapperList The Parameter Name mapping list.
 * @param s The session.
 * @param tx The transaction.
 * @throws PMException if the transaction cannot be rolled back.
 * @throws InterruptedException to indicate that the operation was 
 *                              successfully canceled.
 */
private static void handleOperationCanceled(List<INameMapper> mapperList, EntityManager s, EntityTransaction tx)
        throws PMException, InterruptedException {

    if (tx != null) {
        Persistor.instance().rollbackTransaction(s, tx);
    }
    GeneralStorage.getInstance().reset();
    for (INameMapper mapper : mapperList) {
        mapper.clearAllNames();
    }
    // Operation was canceled.
    throw new InterruptedException();
}

From source file:fll.scheduler.GreedySolver.java

/**
 * @return if a solution has been found//from  w  w  w.j ava  2 s .  com
 * @throws InterruptedException if the solver was canceled
 */
private boolean scheduleNextStation() throws InterruptedException {
    if (null != checkCanceled && checkCanceled.isCanceled()) {
        throw new InterruptedException();
    }

    if (scheduleFinished()) {
        if (outputCurrentSolution()) {
            ++solutionsFound;
            LOGGER.info("Schedule finished num solutions: " + solutionsFound);

            return true;
        } else {
            return false;
        }
    }

    // find possible values
    final List<Integer> possibleSubjectiveStations = new ArrayList<Integer>();
    final List<Integer> subjectiveGroups = new ArrayList<Integer>();
    final int nextAvailableSubjSlot = findNextAvailableSubjectiveSlot(possibleSubjectiveStations,
            subjectiveGroups);

    final List<Integer> possiblePerformanceTables = new LinkedList<Integer>();
    final int nextAvailablePerfSlot = findNextAvailablePerformanceSlot(possiblePerformanceTables);

    if (Math.min(nextAvailablePerfSlot, nextAvailableSubjSlot) >= getNumTimeslots()) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Hit max timeslots");
        }
        return false;
    }

    if ((solverParameters.getSubjectiveFirst() && !subjectiveFinished())
            || (nextAvailableSubjSlot <= nextAvailablePerfSlot)) {
        // schedule a subjective station

        for (int i = 0; i < possibleSubjectiveStations.size(); ++i) {
            final int station = possibleSubjectiveStations.get(i);
            final int group = subjectiveGroups.get(i);

            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("subjective group: " + group + " station: " + station + " next available: "
                        + nextAvailableSubjSlot);
            }

            // mark the subjective station as used at this timeslot and advance the
            // next available slot
            // TODO: maybe should set value to nextAvailableSubjSlot + offset...
            subjectiveStations[group][station] += getSubjectiveAttemptOffset();
            if (checkSubjectiveBreaks(station, nextAvailableSubjSlot)) {
                final boolean result = schedSubj(group, station, nextAvailableSubjSlot);
                if (result) {
                    return true;
                } else if (nextAvailableSubjSlot >= getNumTimeslots()) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Hit max timeslots - schedNext subj");
                    }
                    return false;
                }

            } else {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Overlaps breaks, skipping");
                }
            }
        }
    } else {
        // schedule a performance station

        for (final int table : possiblePerformanceTables) {
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("performance table: " + table + " next available: " + nextAvailablePerfSlot);
            }

            // mark the performance station as used at this timeslot and advance the
            // next available slot
            final int checkTimeslot = performanceTables.get(table).remove(0);
            if (checkTimeslot != nextAvailablePerfSlot) {
                throw new FLLInternalException(String.format(
                        "Error the next available timeslot for the table (%d) doesn't match the one computed (%d)",
                        checkTimeslot, nextAvailablePerfSlot));
            }
            if (checkPerformanceBreaks(nextAvailablePerfSlot)) {
                final boolean result = schedPerf(table, nextAvailablePerfSlot);
                if (result) {
                    return true;
                } else if (nextAvailablePerfSlot >= getNumTimeslots()) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Hit max timeslots - schedNext perf");
                    }
                    return false;
                }
            } else {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Overlaps breaks, skipping");
                }
            }
        }
    }

    final boolean result = scheduleNextStation();
    if (!result || optimize) {
        // undo changes made above
        if (nextAvailableSubjSlot <= nextAvailablePerfSlot) {
            for (int i = 0; i < possibleSubjectiveStations.size(); ++i) {
                final int station = possibleSubjectiveStations.get(i);
                final int group = subjectiveGroups.get(i);
                subjectiveStations[group][station] -= getSubjectiveAttemptOffset();
            }
        } else {
            for (final int table : possiblePerformanceTables) {
                performanceTables.get(table).add(0, nextAvailablePerfSlot);
            }
        }
    }
    return result;

}

From source file:org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin.java

/**
 * Persist <code>path</code> as data directory and loads data from <code>path</code>. This method may block if other
 * jobs are running that modify tasks data. This method will only execute after all conflicting jobs have been
 * completed.// ww w  .j a  v  a 2s .c  om
 *
 * @throws CoreException
 *             in case setting of the data directory did not complete normally
 * @throws OperationCanceledException
 *             if the operation is cancelled by the user
 */
public void setDataDirectory(final String path) throws CoreException {
    Assert.isNotNull(path);
    IRunnableWithProgress runner = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                monitor.beginTask(Messages.TasksUiPlugin_Load_Data_Directory, IProgressMonitor.UNKNOWN);
                if (monitor.isCanceled()) {
                    throw new InterruptedException();
                }

                TasksUi.getTaskActivityManager().deactivateActiveTask();

                // set new preference in case of a change
                if (!path.equals(getDataDirectory())) {
                    getPreferenceStore().setValue(ITasksUiPreferenceConstants.PREF_DATA_DIR, path);
                }

                // reload data from new directory
                initializeDataSources();
            } finally {
                // FIXME roll back preferences change in case of an error?
                monitor.done();
            }
        }
    };

    IProgressService service = PlatformUI.getWorkbench().getProgressService();
    try {
        service.runInUI(service, runner, ITasksCoreConstants.ROOT_SCHEDULING_RULE);
    } catch (InvocationTargetException e) {
        throw new CoreException(
                new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Failed to set data directory", //$NON-NLS-1$
                        e.getCause()));
    } catch (InterruptedException e) {
        throw new OperationCanceledException();
    }
}

From source file:LinkedTransferQueue.java

/**
 * Transfers the element to a consumer, waiting if necessary to do so.
 *
 * <p>More precisely, transfers the specified element immediately
 * if there exists a consumer already waiting to receive it (in
 * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
 * else inserts the specified element at the tail of this queue
 * and waits until the element is received by a consumer.
 *
 * @throws NullPointerException if the specified element is null
 *//*w w  w  . j  a v  a 2 s.c  o m*/
public void transfer(E e) throws InterruptedException {
    if (xfer(e, true, SYNC, 0) != null) {
        Thread.interrupted(); // failure possible only due to interrupt
        throw new InterruptedException();
    }
}

From source file:LinkedTransferQueue.java

/**
 * Transfers the element to a consumer if it is possible to do so
 * before the timeout elapses.//from w  w w.j  a  v a2 s .c  om
 *
 * <p>More precisely, transfers the specified element immediately
 * if there exists a consumer already waiting to receive it (in
 * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
 * else inserts the specified element at the tail of this queue
 * and waits until the element is received by a consumer,
 * returning {@code false} if the specified wait time elapses
 * before the element can be transferred.
 *
 * @throws NullPointerException if the specified element is null
 */
public boolean tryTransfer(E e, long timeout, TimeUnit unit) throws InterruptedException {
    if (xfer(e, true, TIMED, unit.toNanos(timeout)) == null)
        return true;
    if (!Thread.interrupted())
        return false;
    throw new InterruptedException();
}

From source file:LinkedTransferQueue.java

public E take() throws InterruptedException {
    E e = xfer(null, false, SYNC, 0);//from   w ww  . ja v a2  s.  c o  m
    if (e != null)
        return e;
    Thread.interrupted();
    throw new InterruptedException();
}

From source file:LinkedTransferQueue.java

public E poll(long timeout, TimeUnit unit) throws InterruptedException {
    E e = xfer(null, false, TIMED, unit.toNanos(timeout));
    if (e != null || !Thread.interrupted())
        return e;
    throw new InterruptedException();
}