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(String s) 

Source Link

Document

Constructs an InterruptedException with the specified detail message.

Usage

From source file:org.archive.io.RecordingInputStream.java

/**
 * Read all of a stream (Or read until we timeout or have read to the max).
 * @param softMaxLength Maximum length to read; if zero or < 0, then no 
 * limit. If met, return normally. //from www.  j a  v a  2s  .c o m
 * @throws IOException failed read.
 * @throws RecorderLengthExceededException
 * @throws RecorderTimeoutException
 * @throws InterruptedException
 * @deprecated
 */
public void readFullyOrUntil(long softMaxLength)
        throws IOException, RecorderLengthExceededException, RecorderTimeoutException, InterruptedException {
    // Check we're open before proceeding.
    if (!isOpen()) {
        // TODO: should this be a noisier exception-raising error? 
        return;
    }

    long totalBytes = 0L;
    long bytesRead = -1L;
    long maxToRead = -1;
    while (true) {
        try {
            // read no more than soft max
            maxToRead = (softMaxLength <= 0) ? drainBuffer.length
                    : Math.min(drainBuffer.length, softMaxLength - totalBytes);
            // nor more than hard max
            maxToRead = Math.min(maxToRead, recordingOutputStream.getRemainingLength());
            // but always at least 1 (to trigger hard max exception
            maxToRead = Math.max(maxToRead, 1);

            bytesRead = read(drainBuffer, 0, (int) maxToRead);
            if (bytesRead == -1) {
                break;
            }
            totalBytes += bytesRead;

            if (Thread.interrupted()) {
                throw new InterruptedException("Interrupted during IO");
            }
        } catch (SocketTimeoutException e) {
            // A socket timeout is just a transient problem, meaning
            // nothing was available in the configured  timeout period,
            // but something else might become available later.
            // Take this opportunity to check the overall 
            // timeout (below).  One reason for this timeout is 
            // servers that keep up the connection, 'keep-alive', even
            // though we asked them to not keep the connection open.
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "socket timeout", e);
            }
            // check for interrupt
            if (Thread.interrupted()) {
                throw new InterruptedException("Interrupted during IO");
            }
            // check for overall timeout
            recordingOutputStream.checkLimits();
        } catch (SocketException se) {
            throw se;
        } catch (NullPointerException e) {
            // [ 896757 ] NPEs in Andy's Th-Fri Crawl.
            // A crawl was showing NPE's in this part of the code but can
            // not reproduce.  Adding this rethrowing catch block w/
            // diagnostics to help should we come across the problem in the
            // future.
            throw new NullPointerException(
                    "Stream " + this.in + ", " + e.getMessage() + " " + Thread.currentThread().getName());
        }

        // if have read 'enough', just finish
        if (softMaxLength > 0 && totalBytes >= softMaxLength) {
            break; // return
        }
    }
}

From source file:com.sap.research.connectivity.gw.GWOperationsUtils.java

public String getMetadataString(String url, String user, String pass, String host, String port, int timeOut)
        throws Exception {
    String returnString = "";

    try {/*from   w w w  .  j  a va2  s  . co m*/
        String execArgs[] = new String[] { "java", "-jar",
                System.getProperty("user.home") + SEPARATOR + "appToRetrieveOdataMetadata.jar", url, user, pass,
                host, port };

        final Process theProcess = Runtime.getRuntime().exec(execArgs);

        Callable<String> call = new Callable<String>() {
            public String call() throws Exception {
                String returnString = "";
                try {
                    BufferedReader inStream = new BufferedReader(
                            new InputStreamReader(theProcess.getInputStream()));
                    returnString = IOUtils.toString(inStream);
                    IOUtils.closeQuietly(inStream);
                    //if (theProcess.exitValue() != 0)
                    theProcess.waitFor();
                } catch (InterruptedException e) {
                    throw new TimeoutException();
                    //log.severe("The call to the Gateway Service was interrupted.");
                }
                return returnString;
            }
        };

        final ExecutorService theExecutor = Executors.newSingleThreadExecutor();
        Future<String> futureResultOfCall = theExecutor.submit(call);
        try {
            returnString = futureResultOfCall.get(timeOut, TimeUnit.SECONDS);
        } catch (TimeoutException ex) {
            throw new TimeoutException(
                    "The Gateway Service call timed out. Please try again or check your settings.");
        } catch (ExecutionException ex) {
            throw new RuntimeException("The Gateway Service call did not complete due to an execution error. "
                    + ex.getCause().getLocalizedMessage());
        } finally {
            theExecutor.shutdownNow();
        }
    } catch (InterruptedException ex) {
        throw new InterruptedException(
                "The Gateway Service call did not complete due to an unexpected interruption.");
    } catch (IOException e) {
        throw new IOException("Error when retrieving metadata from the Gateway Service.");
    }

    return returnString;
}

From source file:org.construct_infrastructure.io.MessageReader.java

/**
 * Returns the next message available. Will block if no messages are avaialable.
 * //from  w ww. ja v a  2s.  co m
 * @return the next message available.
 * @throws InterruptedException
 *            if the message reader is instructed to close.
 */
public Message getMessage() throws InterruptedException, TimeoutException {
    while (!available()) {
        synchronized (this) {
            wait(ONE_HUNDRED);
        }
        if (!my_keepReading) {
            throw new InterruptedException("MessageReader instructed to close");
        }
        // System.err.println(this + " - " + (my_timeout - splitTime));
        if (hasTimedOut()) {
            my_errorOccured = true;
            throw new TimeoutException("Socket Timeout Occured (" + my_timeout + ")");
        }
    }
    // Remove the message at the head of the list and return
    final Message message = (Message) my_messageList.get(0);
    my_messageList.remove(0);
    my_stopwatch.stop();
    my_stopwatch.reset();
    my_stopwatch.start();
    return message;
}

From source file:org.rhq.core.pc.operation.OperationInvocation.java

/**
 * This actually invokes the plugin's operation facet and executes the operation. If it does not finish before the
 * timeout expires, the timer task will {@link #markAsTimedOut()} interrupt this thread}. This thread will also be
 * interrupted if the operation was {@link #markAsCanceled() canceled}.
 *
 * @see java.lang.Runnable#run()// w w w  .ja  v  a 2s  .  co  m
 */
public void run() {
    Configuration result = null;
    String errorMessage = null;
    Throwable failure = null;
    long finishedTime;

    try {
        boolean canContinue = markAsRunning(Thread.currentThread());

        // We are at the point of no return now. If someone tries to cancel us, its up to
        // the plugin writer of the operation facet to handle the interrupt exception, if applicable.

        if (canContinue) {
            // call the plugin component's operation facet to actually execute the operation
            Configuration parameters = (parameterConfig != null) ? parameterConfig : new Configuration();
            OperationResult opResult = operationComponent.invokeOperation(operationName, parameters);

            // allow a plugin to return a null (aka void) result set
            result = (opResult != null) ? opResult.getComplexResults() : null;
            if (result != null) {
                if (this.operationDefinition != null) {
                    if (this.operationDefinition.getResultsConfigurationDefinition() != null) {
                        // Normalize the result Configuration.
                        ConfigurationUtility.normalizeConfiguration(result,
                                operationDefinition.getResultsConfigurationDefinition());
                        // TODO: Validate the result Configuration?
                    } else if (!result.getProperties().isEmpty()) {
                        log.error("Plugin error: Operation [" + this.operationDefinition.getName()
                                + "] is defined as returning no results, but it returned non-null results: "
                                + result.toString(true));
                        result = null; // Don't return results that the GUI won't be able to display anyway.
                    }
                }
                errorMessage = opResult.getErrorMessage();
            }
        } else {
            failure = new InterruptedException("Operation was aborted before it started.");
        }
    } catch (Throwable t) {
        failure = t;
    } finally {
        // IT IS IMPORTANT THAT THIS FINALLY CLAUSE NOT THROW EXCEPTIONS.  EVERYTHING IN HERE
        // MUST EXECUTE PROPERLY OR ELSE THE OPERATION MANAGER WILL NOT EXECUTE OPERATIONS PROPERLY

        // Note: if the timer triggers in the nanoseconds between the above and our mark here
        // then the timer task will erroneously cause us to send out a timeout message to the server. I know of no
        // way to prevent this right now.  This will be a rare occurrence, but not an impossibility.
        markAsFinished();
        timerTask.cancel();

        // remember the time we finished - to ensure our times are in order,
        // be sure we mark this time before we allow the gateway to submit the next operation to the thread pool
        finishedTime = System.currentTimeMillis();

        // before taking the time to send the request up to the server, let's allow the next
        // operation in the queue to get executed right now.  Make sure this always is called,
        // otherwise, no other operations on the resource will be allowed
        operationThreadPoolGateway.operationCompleted(this);
    }

    // if we have a server that we need to tell, notify it of the results/failure/cancellation/timeout
    if (operationServerService != null) {
        if (failure == null) {
            // Note that even if the operation was canceled and/or timed out, we may still get here.
            // This happens if either the plugin quickly finished before we received the order to cancel
            // or the plugin ignored the order to cancel (i.e. the thread interrupt) and finished doing
            // what it was doing anyway.  In either case, the operation really did succeed (it was not
            // canceled) so we need to indicate this via calling operationSucceeded
            if (errorMessage == null) {
                try {
                    operationServerService.operationSucceeded(jobId, result, invocationTime, finishedTime);
                } catch (Throwable t) {
                    log.error("Failed to send operation succeeded message to server. resource=[" + resourceId
                            + "], operation=[" + operationName + "], jobId=[" + jobId + "]", t);
                }
            } else {
                ExceptionPackage errorResults = new ExceptionPackage(Severity.Severe,
                        new Exception(errorMessage));
                try {
                    operationServerService.operationFailed(jobId, result, errorResults, invocationTime,
                            finishedTime);
                } catch (Throwable t) {
                    log.error("Failed to send operation failed message to server. resource=[" + resourceId
                            + "], operation=[" + operationName + "], jobId=[" + jobId + "]", t);
                }
            }
        } else {
            if (status.contains(Status.TIMED_OUT)) {
                try {
                    operationServerService.operationTimedOut(jobId, invocationTime, finishedTime);
                } catch (Throwable t) {
                    log.error("Failed to send operation timed out message to server. resource=[" + resourceId
                            + "], operation=[" + operationName + "], jobId=[" + jobId + "]", t);
                }
            } else {
                ExceptionPackage errorResults;

                if (status.contains(Status.CANCELED)) {
                    errorResults = new ExceptionPackage(Severity.Info, new Exception("Canceled", failure));
                } else {
                    errorResults = new ExceptionPackage(Severity.Severe, failure);
                }

                try {
                    operationServerService.operationFailed(jobId, null, errorResults, invocationTime,
                            finishedTime);
                } catch (Throwable t) {
                    log.error("Failed to send operation failed message to server. resource=[" + resourceId
                            + "], operation=[" + operationName + "], jobId=[" + jobId + "], operation-error=["
                            + errorResults.toString() + "]", t);
                }
            }
        }
    }

    return;
}

From source file:org.kawanfw.file.api.util.client.StreamsTransferWithProgress.java

/**
 * /*from  w ww  . java2s .  c  o  m*/
 * Uploads a list of input stream on the remote server using
 * {@code RemoteOutputStream}.
 * 
 * @param inStreams
 *            the input stream to upload
 * @param inStreamsLength the lengths of the input streams
 * @param remoteFiles
 *            the corresponding server file names
 * @param totalLength
 *            the total lenth of files.
 * 
 * @throws IllegalArgumentException
 * @throws InvalidLoginException
 * @throws FileNotFoundException
 * @throws UnknownHostException
 * @throws ConnectException
 * @throws SocketException
 * @throws RemoteException
 * @throws IOException
 * @throws InterruptedException
 */
public void upload(List<InputStream> inStreams, List<Long> inStreamsLength, List<OutputStream> outStreams,
        long totalLength)
        throws IllegalArgumentException, InvalidLoginException, FileNotFoundException, UnknownHostException,
        ConnectException, SocketException, RemoteException, IOException, InterruptedException {

    if (inStreams == null) {
        throw new IllegalArgumentException("instreams can not be null!");
    }

    if (outStreams == null) {
        throw new IllegalArgumentException("outStreams can not be null!");
    }

    // Inside InputStream in inStreams may be null, so no test

    InputStream in = null;
    OutputStream out = null;

    for (int i = 0; i < inStreams.size(); i++) {

        // Do not reupload an uploaded stream that is closed!
        if (inStreams.get(i) == null) {
            continue;
        }

        try {

            String remoteFile = ((RemoteOutputStream) outStreams.get(i)).getPathname();
            debug("Uploading stream with RemoteInputStream: " + remoteFile + " progress: " + progress.get());
            currentPathnameUpload = remoteFile;

            in = inStreams.get(i);
            out = outStreams.get(i);

            int tempLen = 0;
            byte[] buffer = new byte[1024 * 4];
            int n = 0;

            while ((n = in.read(buffer)) != -1) {
                tempLen += n;

                if (totalLength > 0 && tempLen > totalLength / 100) {
                    tempLen = 0;
                    int cpt = progress.get();
                    cpt++;

                    // Update the progress value for progress
                    // indicator
                    progress.set(Math.min(99, cpt));
                }

                // If progress indicatos says that user has cancelled the
                // download, stop now!
                if (cancelled.get()) {
                    throw new InterruptedException("File upload cancelled by user.");
                }

                out.write(buffer, 0, n);
            }

        } finally {
            inStreams.set(i, null);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }
}

From source file:org.alfresco.extension.bulkimport.source.fs.DirectoryAnalyser.java

private Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> constructImportItems(
        final String sourceRelativeParentDirectory,
        final Map<String, SortedMap<BigDecimal, Pair<File, File>>> categorisedFiles)
        throws InterruptedException {
    Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> result = null;

    if (categorisedFiles != null) {
        final List<FilesystemBulkImportItem> directoryItems = new ArrayList<>();
        final List<FilesystemBulkImportItem> fileItems = new ArrayList<>();

        result = new Pair<>(directoryItems, fileItems);

        for (final String parentName : categorisedFiles.keySet()) {
            if (importStatus.isStopping() || Thread.currentThread().isInterrupted())
                throw new InterruptedException(
                        Thread.currentThread().getName() + " was interrupted. Terminating early.");

            final SortedMap<BigDecimal, Pair<File, File>> itemVersions = categorisedFiles.get(parentName);
            final NavigableSet<FilesystemBulkImportItemVersion> versions = constructImportItemVersions(
                    itemVersions);/*from  w ww.ja  va 2  s  . c om*/
            final boolean isDirectory = versions.last().isDirectory();
            final FilesystemBulkImportItem item = new FilesystemBulkImportItem(parentName, isDirectory,
                    sourceRelativeParentDirectory, versions);

            if (isDirectory) {
                directoryItems.add(item);
            } else {
                fileItems.add(item);
            }
        }
    }

    return (result);
}

From source file:org.apache.hive.hcatalog.templeton.JobRequestExecutor.java

public T execute(JobCallable<T> jobExecuteCallable)
        throws InterruptedException, TimeoutException, TooManyRequestsException, ExecutionException {
    /*/*w w  w  .  j a v  a2 s.  co  m*/
     * The callable shouldn't be null to execute. The thread pool also should be configured
     * to execute requests.
     */
    assert (jobExecuteCallable != null);
    assert (this.jobExecutePool != null);

    String type = this.requestType.toString().toLowerCase();

    String retryMessageForConcurrentRequests = "Please wait for some time before retrying "
            + "the operation. Please refer to the config " + concurrentRequestsConfigName
            + " to configure concurrent requests.";

    LOG.debug("Starting new " + type + " job request with time out " + this.requestExecutionTimeoutInSec
            + "seconds.");
    Future<T> future = null;

    try {
        future = this.jobExecutePool.submit(jobExecuteCallable);
    } catch (RejectedExecutionException rejectedException) {
        /*
         * Not able to find thread to execute the job request. Raise Busy exception and client
         * can retry the operation.
         */
        String tooManyRequestsExceptionMessage = "Unable to service the " + type + " job request as "
                + "templeton service is busy with too many " + type + " job requests. "
                + retryMessageForConcurrentRequests;

        LOG.warn(tooManyRequestsExceptionMessage);
        throw new TooManyRequestsException(tooManyRequestsExceptionMessage);
    }

    T result = null;

    try {
        result = this.requestExecutionTimeoutInSec > 0
                ? future.get(this.requestExecutionTimeoutInSec, TimeUnit.SECONDS)
                : future.get();
    } catch (TimeoutException e) {
        /*
         * See if the execution thread has just completed operation and result is available.
         * If result is available then return the result. Otherwise, raise exception.
         */
        if ((result = tryGetJobResultOrSetJobStateFailed(jobExecuteCallable)) == null) {
            String message = this.requestType + " job request got timed out. Please wait for some time "
                    + "before retrying the operation. Please refer to the config " + jobTimeoutConfigName
                    + " to configure job request time out.";
            LOG.warn(message);

            /*
             * Throw TimeoutException to caller.
             */
            throw new TimeoutException(message);
        }
    } catch (InterruptedException e) {
        /*
         * See if the execution thread has just completed operation and result is available.
         * If result is available then return the result. Otherwise, raise exception.
         */
        if ((result = tryGetJobResultOrSetJobStateFailed(jobExecuteCallable)) == null) {
            String message = this.requestType + " job request got interrupted. Please wait for some time "
                    + "before retrying the operation.";
            LOG.warn(message);

            /*
             * Throw TimeoutException to caller.
             */
            throw new InterruptedException(message);
        }
    } catch (CancellationException e) {
        /*
         * See if the execution thread has just completed operation and result is available.
         * If result is available then return the result. Otherwise, raise exception.
         */
        if ((result = tryGetJobResultOrSetJobStateFailed(jobExecuteCallable)) == null) {
            String message = this.requestType + " job request got cancelled and thread got interrupted. "
                    + "Please wait for some time before retrying the operation.";
            LOG.warn(message);

            throw new InterruptedException(message);
        }
    } finally {
        /*
         * If the thread is still active and needs to be cancelled then cancel it. This may
         * happen in case task got interrupted, or timed out.
         */
        if (enableCancelTask) {
            cancelExecutePoolThread(future);
        }
    }

    LOG.debug("Completed " + type + " job request.");

    return result;
}

From source file:org.apache.hadoop.hdfs.server.blockmanagement.CacheReplicationMonitor.java

private void rescan() throws InterruptedException {
    scannedDirectives = 0;/* www. ja  v a  2  s .  co  m*/
    scannedBlocks = 0;
    namesystem.writeLock();
    try {
        if (shutdown) {
            throw new InterruptedException("CacheReplicationMonitor was " + "shut down.");
        }
        resetStatistics();
        rescanCacheDirectives();
        rescanCachedBlockMap();
        blockManager.getDatanodeManager().resetLastCachingDirectiveSentTime();
    } finally {
        namesystem.writeUnlock();
    }
}

From source file:org.apache.giraph.rexster.utils.RexsterUtils.java

/**
 * Opens an HTTP connection to the specified Rexster server.
 *
 * @param conf giraph configuration/*  w  w  w  .ja v  a  2 s . co m*/
 * @param type either edge or vertex
 * @return  the object used to populate the HTTP response content
 */
// CHECKSTYLE: stop IllegalCatch
public static HttpURLConnection openOutputConnection(ImmutableClassesGiraphConfiguration conf, String type)
        throws InterruptedException {

    String uriFormat = "/graphs/%s/tp/giraph/%s/";
    String endpoint = GIRAPH_REXSTER_HOSTNAME.get(conf);
    boolean isSsl = GIRAPH_REXSTER_USES_SSL.get(conf);
    int port = GIRAPH_REXSTER_PORT.get(conf);
    String graph = GIRAPH_REXSTER_OUTPUT_GRAPH.get(conf);

    try {
        URL url = new URL(isSsl ? "https" : "http", endpoint, port, String.format(uriFormat, graph, type));
        LOG.info(url);

        String username = GIRAPH_REXSTER_USERNAME.get(conf);
        String password = GIRAPH_REXSTER_PASSWORD.get(conf);
        String auth = getHTTPAuthString(username, password);

        HttpURLConnection connection = createConnection(url, "POST", auth);
        connection.setRequestProperty("Content-Type", "application/json; cherset=UTF-8");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        return connection;
    } catch (Exception e) {
        throw new InterruptedException(e.getMessage());
    }
}