Example usage for java.lang InterruptedException getMessage

List of usage examples for java.lang InterruptedException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:de.hpi.i2b2.girix.GIRIXService.java

private OMElement execute(RequestHandler handler, RequestMessageType message) throws I2B2Exception {

    // Extract wait time. If no waitTime is given it defaults to 0 which is equivalent to an infinite waitTime
    long waitTime = 0;
    if (message.getRequestHeader() != null) {
        waitTime = message.getRequestHeader().getResultWaittimeMs();
    }/*from   w  w w  .j a v a2 s  .  co m*/

    // Do query processing inside thread, so that service could send back message with timeout error
    String unknownErrorMessage = "Error message delivered from the remote server: Unknown exception. See log file for stack trace.";
    ExecutorRunnable er = new ExecutorRunnable();
    er.setInput(message);
    er.setRequestHandler(handler);
    Thread t = new Thread(er);
    String girixDataResponse = null;
    // Start thread...
    synchronized (t) {
        t.start();
        // ...meanwhile in main thread: count time and check for timeout
        try {
            long startTime = System.currentTimeMillis();
            long deltaTime = -1;
            while ((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) {
                if (waitTime > 0) {
                    t.wait(waitTime - deltaTime);
                    deltaTime = System.currentTimeMillis() - startTime;
                } else {
                    // wait until job is completed
                    t.wait();
                }
            }
            // Now try to extract the result...
            girixDataResponse = er.getOutputString();
            // ...which is null if there was an error
            if (girixDataResponse == null) {
                // Error case 1: There was an exception during thread execution
                if (er.getJobException() != null) {
                    // Error case 1.1: Causing exception was set -> Default unknown error message & logging stack trace
                    if (er.getJobException().getCause() != null) {
                        log.error("Exception stack trace:\n"
                                + GIRIXUtil.getStackTraceAsString(er.getJobException()));
                        ResponseMessageType responseMsgType = MessageUtil.doBuildErrorResponseMessageType(null,
                                unknownErrorMessage);
                        girixDataResponse = MessageUtil.convertResponseMessageTypeToXML(responseMsgType);
                    } else {
                        // Error case 1.2: Causing exception wasn't set -> Custom error message. Logging is done by throwing method
                        ResponseMessageType responseMsgType = MessageUtil.doBuildErrorResponseMessageType(null,
                                er.getJobException().getMessage());
                        girixDataResponse = MessageUtil.convertResponseMessageTypeToXML(responseMsgType);
                    }
                    // Error case 2: Timeout
                } else if (er.isJobCompleteFlag() == false) {
                    String timeOuterror = "Remote server timed out \nResult waittime = " + waitTime
                            + " ms elapsed\nPlease try again";
                    log.error(timeOuterror);
                    log.debug("girix waited " + deltaTime + "ms for "
                            + er.getRequestHandler().getClass().getName());
                    ResponseMessageType responseMsgType = MessageUtil.doBuildErrorResponseMessageType(null,
                            timeOuterror);
                    girixDataResponse = MessageUtil.convertResponseMessageTypeToXML(responseMsgType);
                    // Error case 3: Result was set to null by the thread
                } else {
                    log.error("girix data response is null");
                    log.debug("girix waited " + deltaTime + "ms for "
                            + er.getRequestHandler().getClass().getName());
                    ResponseMessageType responseMsgType = MessageUtil.doBuildErrorResponseMessageType(null,
                            "Error message delivered from the remote server: Result was set to null.");
                    girixDataResponse = MessageUtil.convertResponseMessageTypeToXML(responseMsgType);
                }
            }
        } catch (InterruptedException e) {
            log.error(e.getMessage());
            throw new I2B2Exception("Thread error while running GIRIX job");
        } finally {
            t.interrupt();
            er = null;
            t = null;
        }
    }
    // Send back answer. girixDataResponse contains either an error message or the proper response if there was no critical error
    return MessageUtil.convertXMLToOMElement(girixDataResponse);
}

From source file:Main.java

public void run() {
    try {//from   w w w  .java  2 s .c o m
        System.out.print(Thread.currentThread().getName());
        System.out.println(" executing...");

        while (true) {
            Thread.sleep(500);
        }
    } catch (InterruptedException e) {
        Thread currThread = Thread.currentThread();
        System.out.print(currThread.getName());
        System.out.println(" interrupted:" + e.toString());

        // rethrow the exception
        throw new RuntimeException(e.getMessage());
    }
}

From source file:es.udc.gii.rosamituscma.CMARosaMitusEvolutionaryAlgorithm.java

@Override
protected synchronized void reproduce(Population population) {

    while (buffer_population.size() < this.getPopulation().getSize()) {
        try {/*from   w  ww.  j  a va  2s .com*/
            wait(1000);
        } catch (InterruptedException ex) {
            System.out.println(
                    "Exception at CMARosaMitusEvolutionaryAlgorithm reproduce phase: " + ex.getMessage());
            System.exit(0);
        }
    }

    //La poblacin buffer es la que tiene la informacin de la calidad:
    List<Individual> sub_population = this.buffer_population.subList(0, this.getPopulation().getSize());
    for (int i = 0; i < sub_population.size(); i++) {
        population.getIndividuals().set(i, (Individual) sub_population.get(i).clone());
    }
    if (this.getReproductionChain() != null) {
        population.setIndividuals(this.getReproductionChain().execute(this, population));
    }
    synchronized (this.buffer_population) {
        for (int i = 0; i < this.getPopulation().getSize(); i++) {
            this.buffer_population.remove(0);
        }
        System.gc();
    }

}

From source file:net.geoprism.gis.geoserver.CleanupRunnable.java

@Override
public void run() {
    while (this.isRunning()) {
        try {//w  w  w. j  ava2 s .  c o m
            Thread.sleep(DELAY);
        } catch (InterruptedException e) {
        }

        try {
            CleanupFacade.cleanupUnusedLayers();
            CleanupFacade.cleanupUnusedFiles();
        } catch (Exception e) {
            log.error(e.getMessage(), e);

            e.printStackTrace();
        }
    }
}

From source file:ch.cyberduck.core.http.DelayedHttpMultipartEntity.java

public void writeTo(final OutputStream out) throws IOException {
    try {/*  www .  j ava  2s  .  c  o  m*/
        stream = new OutputStream() {
            private final AtomicBoolean close = new AtomicBoolean();

            @Override
            public void write(final byte[] b, final int off, final int len) throws IOException {
                out.write(b, off, len);
            }

            @Override
            public void write(final int b) throws IOException {
                out.write(b);
            }

            @Override
            public void write(final byte[] b) throws IOException {
                out.write(b);
            }

            @Override
            public void close() throws IOException {
                if (close.get()) {
                    log.warn(String.format("Skip double close of stream %s", this));
                    return;
                }
                try {
                    out.write(footer);
                    super.close();
                } finally {
                    // Signal finished writing to stream
                    exit.countDown();
                    close.set(true);
                }
            }
        };
        stream.write(header);
    } finally {
        final CountDownLatch entry = this.getEntry();
        // Signal stream is ready for writing
        entry.countDown();
    }
    // Wait for signal when content has been written to the pipe
    try {
        exit.await();
    } catch (InterruptedException e) {
        log.error(String.format("Error waiting for exit signal %s", e.getMessage()));
        throw new IOException(e);
    }
    // Entity written to server
    consumed = true;
}

From source file:edu.lternet.pasta.portal.search.BrowseCrawlerServlet.java

/**
 * Runs the BrowseCrawler main program in a separate thread. 
 *//*from   w  w  w.  j  a va  2 s. c  o  m*/
public void run() {
    long delta; // endTime - startTime
    long endTime; // time that a crawl completes
    final long oneHour = (60 * 60 * 1000); // milliseconds in one hour
    long periodSleepTime; // time to sleep between crawls
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
    long startTime; // time that a crawl starts
    final long tenMinutes = (10 * 60 * 1000); // milliseconds in ten minutes

    while (keepRunning) {
        Date now = new Date();
        logger.debug("Checking crawl critieria at time: " + simpleDateFormat.format(now));
        if (checkCrawlCriteria()) {
            logger.info("Initiating new crawl.");
            startTime = System.currentTimeMillis();
            initiateNewCrawl();
            endTime = System.currentTimeMillis();
            delta = endTime - startTime;

            try {
                periodSleepTime = (crawlPeriod * oneHour) - delta;
                logger.info("Crawl completed. Sleeping for " + periodSleepTime + " milliseconds.");
                Thread.sleep(periodSleepTime);
            } catch (InterruptedException e) {
                logger.warn("InterruptedException: " + e.getMessage());
            }
        } else {
            logger.debug("Crawl criteria failed. Sleeping for ten minutes.");
            try {
                Thread.sleep(tenMinutes);
            } catch (InterruptedException e) {
                logger.error("InterruptedException: " + e.getMessage());
            }
        }
    }
}

From source file:eu.scidipes.toolkits.pawebapp.preservation.PreservationJobImpl.java

@Override
public void run() {

    LOG.info(format("Preservation job for dataset: '%s' started", dataset.getDatasetName()));

    final int numJobItems = preservationJobItemMap.size();

    for (int i = 0; i < numJobItems; i++) {
        try {/*ww  w  .j a  va2 s.com*/
            final PreservationJobItemResult<Preservable, ?> presObj = completionService.take().get();
            preservationJobItemMap.put(presObj.getPreservable(), presObj);

            LOG.debug("Added ({}) to preservationJobItemMap", presObj);

        } catch (final InterruptedException e) {
            LOG.error(e.getMessage(), e);
            Thread.currentThread().interrupt();
        } catch (final ExecutionException e) {
            LOG.error(e.getMessage(), e);
            final Throwable cause = e.getCause();

            if (cause instanceof PreservationStorageException) {
                /* Wrap the preservation exception in a job item and add to the list: */
                final PreservationStorageException pse = (PreservationStorageException) cause;

                LOG.error(pse.getCause().getMessage(), pse.getCause());

                preservationJobItemMap.put(pse.getPreservable(),
                        new PreservationJobItemResultImpl(pse.getPreservable(), pse.getCause()));
            } else {
                throw launderThrowable(cause);
            }
        }
        completed.incrementAndGet();
    }

    LOG.info(format(
            "Preservation job for dataset: '%s' finished preserving %d manifests, digital objects and RILs",
            dataset.getDatasetName(), Integer.valueOf(numJobItems)));

    /* Update the RILs in the persistence context: */
    for (final DatasetRIL ril : dataset.getRils()) {
        datasetRepo.updateDatasetRIL((UploadRepInfoLabel) ril.getRil(), ril.getRilCPID());
    }

    datasetRepo.save((FormsBundleImpl) dataset);
}

From source file:ch.cyberduck.core.PathTest.java

@Test
public void testTransferInterrupt() throws Exception {
    final Path p = new NullPath("/t", Path.FILE_TYPE);
    final TransferStatus status = new TransferStatus();
    final CyclicBarrier lock = new CyclicBarrier(2);
    final CyclicBarrier exit = new CyclicBarrier(2);
    status.setLength(432768L);//from   ww  w .  j  a  v a  2s . c o m
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                p.transfer(new NullInputStream(status.getLength()), new NullOutputStream(),
                        new StreamListener() {
                            @Override
                            public void bytesSent(long bytes) {
                                //
                            }

                            @Override
                            public void bytesReceived(long bytes) {
                                try {
                                    lock.await();
                                    exit.await();
                                } catch (InterruptedException e) {
                                    fail(e.getMessage());
                                } catch (BrokenBarrierException e) {
                                    fail(e.getMessage());
                                }
                            }
                        }, -1, status);
            } catch (IOException e) {
                assertTrue(e instanceof ConnectionCanceledException);
            }
        }
    }).start();
    lock.await();
    status.setCanceled();
    exit.await();
    assertFalse(status.isComplete());
    assertTrue(status.isCanceled());
    assertEquals(32768L, status.getCurrent());
}

From source file:com.cws.esolutions.agent.processors.impl.ApplicationManagerProcessorImpl.java

/**
 * @see com.cws.esolutions.agent.processors.interfaces.IApplicationManagerProcessor#installApplication(com.cws.esolutions.agent.processors.dto.ApplicationManagerRequest)
 *//* w  ww.  j ava 2  s.c  om*/
public ApplicationManagerResponse installApplication(final ApplicationManagerRequest request)
        throws ApplicationManagerException {
    final String methodName = IApplicationManagerProcessor.CNAME
            + "#installApplication(final ApplicationManagerRequest request) throws ApplicationManagerException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ApplicationManagerRequest: {}", request);
    }

    BufferedWriter writer = null;
    ApplicationManagerResponse response = new ApplicationManagerResponse();

    final double version = request.getVersion();
    final DefaultExecutor executor = new DefaultExecutor();
    final String installerOptions = request.getInstallerOptions();
    final File installPath = FileUtils.getFile(request.getInstallPath());
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000);
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    final File packageInstaller = FileUtils.getFile(request.getPackageInstaller());

    if (DEBUG) {
        DEBUGGER.debug("double: {}", version);
        DEBUGGER.debug("DefaultExecutor: {}", executor);
        DEBUGGER.debug("String: {}", installerOptions);
        DEBUGGER.debug("File: {}", installPath);
        DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
        DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
        DEBUGGER.debug("File:{}", packageInstaller);
    }

    try {
        if (!(packageInstaller.canExecute())) {
            throw new ApplicationManagerException("Unable to execute package installer. Cannot continue.");
        }

        if (!(installPath.canWrite()) && (!(installPath.mkdirs()))) {
            throw new ApplicationManagerException("Unable to create installation target. Cannot continue.");
        }

        CommandLine command = CommandLine.parse(packageInstaller.getAbsolutePath());
        command.addArgument(installerOptions, false);
        command.addArgument(request.getPackageLocation(), false);

        if (DEBUG) {
            DEBUGGER.debug("CommandLine: {}", command);
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        streamHandler.start();

        executor.setWatchdog(watchdog);
        executor.setStreamHandler(streamHandler);

        if (DEBUG) {
            DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
            DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
            DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
            DEBUGGER.debug("DefaultExecutor: {}", executor);
        }

        executor.execute(command, resultHandler);

        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();

        writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + request.getPackageName() + ".log"));
        writer.write(outputStream.toString());
        writer.flush();

        if (DEBUG) {
            DEBUGGER.debug("exitCode: {}", exitCode);
        }

        if (executor.isFailure(exitCode)) {
            throw new ApplicationManagerException("Application installation failed: Result Code: " + exitCode);
        }

        response.setResponse(outputStream.toString());
        response.setRequestStatus(AgentStatus.SUCCESS);
    } catch (ExecuteException eex) {
        ERROR_RECORDER.error(eex.getMessage(), eex);

        throw new ApplicationManagerException(eex.getMessage(), eex);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new ApplicationManagerException(iox.getMessage(), iox);
    } catch (InterruptedException ix) {
        ERROR_RECORDER.error(ix.getMessage(), ix);

        throw new ApplicationManagerException(ix.getMessage(), ix);
    } finally {
        try {
            writer.close();
        } catch (IOException iox) {
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return response;
}

From source file:org.yamj.filescanner.service.LibrarySendScheduler.java

@Async
@Scheduled(initialDelay = 10000, fixedDelay = 15000)
public void sendLibraries() {
    if (retryCount.get() > RETRY_MAX) {
        LOG.info("Maximum number of retries ({}) exceeded. No further processing attempted.", RETRY_MAX);
        for (Library library : libraryCollection.getLibraries()) {
            library.setSendingComplete(Boolean.TRUE);
        }/*  ww  w  .ja va 2s .c om*/
        return;
    }

    LOG.info("There are {} libraries to process, there have been {} consecutive failed attempts to send.",
            libraryCollection.size(), retryCount.get());
    LOG.info("There are {} items currently queued to be sent to core.", runningCount.get());

    for (Library library : libraryCollection.getLibraries()) {
        library.getStatistics().setTime(TimeType.SENDING_START);
        LOG.info("  {} has {} directories and the file scanner has {} scanning.",
                library.getImportDTO().getBaseDirectory(), library.getDirectories().size(),
                library.isScanningComplete() ? "finished" : "not finished");
        try {
            for (Map.Entry<String, Future<StatusType>> entry : library.getDirectoryStatus().entrySet()) {
                LOG.info("    {}: {}", entry.getKey(),
                        entry.getValue().isDone() ? entry.getValue().get() : "Being processed");

                if (checkStatus(library, entry.getValue(), entry.getKey())) {
                    LOG.debug("Sucessfully sent file to server, resetting retry count to 0 from {}.",
                            retryCount.getAndSet(0));
                } else {
                    // Make sure this is set to false
                    library.setSendingComplete(Boolean.FALSE);
                    LOG.warn("Failed to send a file, this was failed attempt #{}. Waiting until next run...",
                            retryCount.incrementAndGet());
                    return;
                }
            }

            // When we reach this point we should have completed the library sending
            LOG.info("Sending complete for {}", library.getImportDTO().getBaseDirectory());
            library.setSendingComplete(Boolean.TRUE);
            library.getStatistics().setTime(TimeType.SENDING_END);
        } catch (InterruptedException ex) {
            LOG.info("InterruptedException: {}", ex.getMessage());
        } catch (ExecutionException ex) {
            LOG.info("ExecutionException: {}", ex.getMessage());
        }
    }
}