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.auraframework.impl.adapter.ServletUtilAdapterImplUnitTest.java

/**
 * Verifies first exception within handleServletException is caught and processed
 * we throw 'EmptyStackException' when getting InstanceStack, then verify
 * exceptionAdapter.handleException(death) is called with it
 *//*from  ww w .ja va 2  s .c o  m*/
@Test
public void testHandleExceptionDeathCaught() throws Exception {
    PrintWriter writer = Mockito.mock(PrintWriter.class);
    HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
    ContextService mockContextService = Mockito.mock(ContextService.class);
    AuraContext mockContext = Mockito.mock(AuraContext.class);
    ConfigAdapter mockConfigAdapter = Mockito.mock(ConfigAdapter.class);
    ExceptionAdapter mockExceptionAdapter = Mockito.mock(ExceptionAdapter.class);

    Throwable firstException = new EmptyStackException();

    Mockito.when(mockResponse.getWriter()).thenReturn(writer);
    Mockito.when(mockResponse.getStatus()).thenReturn(HttpStatus.SC_OK);
    Mockito.when(mockContext.getFormat()).thenReturn(AuraContext.Format.JSON);
    Mockito.when(mockContext.getMode()).thenReturn(Mode.PROD);
    Mockito.when(mockConfigAdapter.isProduction()).thenReturn(true);
    Mockito.when(mockContextService.getCurrentContext()).thenReturn(mockContext);
    Mockito.when(mockContext.getInstanceStack()).thenThrow(firstException);

    Throwable exception = new InterruptedException("opps");

    ServletUtilAdapterImpl adapter = Mockito.spy(new ServletUtilAdapterImpl());
    adapter.setContextService(mockContextService);
    adapter.setConfigAdapter(mockConfigAdapter);
    adapter.setExceptionAdapter(mockExceptionAdapter);
    adapter.handleServletException(exception, true, mockContext, mockRequest, mockResponse, true);

    ArgumentCaptor<Throwable> handledException = ArgumentCaptor.forClass(Throwable.class);
    Mockito.verify(mockExceptionAdapter, Mockito.times(2)).handleException(handledException.capture());

    assertTrue("Should handle EmptyStackException",
            handledException.getAllValues().get(1) instanceof EmptyStackException);

    Mockito.verify(mockResponse, Mockito.atLeastOnce()).setStatus(HttpStatus.SC_OK);
    Mockito.verify(mockContextService, Mockito.atLeastOnce()).endContext();
    Mockito.verify(adapter, Mockito.times(1)).setNoCache(mockResponse);
}

From source file:org.apache.geode.distributed.internal.membership.gms.membership.GMSJoinLeave.java

void sendView(NetView view, List<InternalDistributedMember> newMembers) throws InterruptedException {
    if (isShuttingDown()) {
        throw new InterruptedException("shutting down");
    }//from w w w  . ja  va2s.  co m
    sendView(view, false, this.viewProcessor);
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.GerritServer.java

/**
 * Server to sleep. This method returns actual connection status is changed or timeout.
 * Used by jelly./*from   ww w.j a va 2s.c o  m*/
 *
 * @return connection status.
 */
public JSONObject doSleep() {
    Timer timer = new Timer();
    try {
        stopConnection();

        final CountDownLatch responseLatch = new CountDownLatch(RESPONSE_COUNT);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (gerritConnectionListener == null || !gerritConnectionListener.isConnected()) {
                    responseLatch.countDown();
                }
            }
        }, RESPONSE_INTERVAL_MS, RESPONSE_INTERVAL_MS);

        if (responseLatch.await(RESPONSE_TIMEOUT_S, TimeUnit.SECONDS)) {
            setConnectionResponse(STOP_SUCCESS);
        } else {
            throw new InterruptedException("time out.");
        }
    } catch (Exception ex) {
        setConnectionResponse(STOP_FAILURE);
        logger.error("Could not stop connection. ", ex);
    }
    timer.cancel();

    JSONObject obj = new JSONObject();
    String status = "down";
    if (gerritConnectionListener != null) {
        if (gerritConnectionListener.isConnected()) {
            status = "up";
        }
    }
    obj.put("status", status);
    return obj;
}

From source file:org.alfresco.extension.bulkfilesystemimport.impl.AbstractBulkFilesystemImporter.java

private final void importImportableItemMetadata(final NodeRef nodeRef, final File parentFile,
        final MetadataLoader.Metadata metadata) throws InterruptedException {
    importStatus.setCurrentFileBeingProcessed(getFileName(parentFile) + " (metadata)");

    // Attach aspects
    if (metadata.getAspects() != null) {
        for (final QName aspect : metadata.getAspects()) {
            if (importStatus.isStopping() || Thread.currentThread().isInterrupted())
                throw new InterruptedException(
                        Thread.currentThread().getName() + " was interrupted.  Terminating early.");

            if (log.isDebugEnabled())
                log.debug("Attaching aspect '" + String.valueOf(aspect) + "' to node '"
                        + String.valueOf(nodeRef) + "'.");

            nodeService.addAspect(nodeRef, aspect, null); // Note: we set the aspect's properties separately, hence null for the third parameter
        }//from  w  ww.j  ava  2  s . c o  m
    }

    // Set property values for both the type and any aspect(s)
    if (metadata.getProperties() != null) {
        if (log.isDebugEnabled())
            log.debug("Adding properties to node '" + String.valueOf(nodeRef) + "':\n"
                    + mapToString(metadata.getProperties()));

        try {
            nodeService.addProperties(nodeRef, metadata.getProperties());
        } catch (final InvalidNodeRefException inre) {
            if (!nodeRef.equals(inre.getNodeRef())) {
                // Caused by an invalid NodeRef in the metadata (e.g. in an association)
                throw new IllegalStateException(
                        "Invalid nodeRef found in metadata for '" + getFileName(parentFile) + "'.  "
                                + "Probable cause: an association is being populated via metadata, but the "
                                + "NodeRef for the target of that association ('" + inre.getNodeRef()
                                + "') is invalid.  " + "Please double check your metadata file and try again.",
                        inre);
            } else {
                // Logic bug in the BFSIT.  :-(
                throw inre;
            }
        }
    }
}

From source file:info.ajaxplorer.synchro.SyncJob.java

protected void listDirRecursive(File directory, Node root, List<Node> accumulator, boolean save,
        List<Node> previousSnapshot) throws InterruptedException, SQLException {

    if (this.interruptRequired) {
        throw new InterruptedException("Interrupt required");
    }/*from   w w  w . j a v  a 2  s.c o  m*/
    //Logger.getRootLogger().info("Searching "+directory.getAbsolutePath());
    File[] children = directory.listFiles();
    String[] start = Manager.getInstance().EXCLUDED_FILES_START;
    String[] end = Manager.getInstance().EXCLUDED_FILES_END;
    for (int i = 0; i < children.length; i++) {
        boolean ignore = false;
        for (int j = 0; j < start.length; j++) {
            if (children[i].getName().startsWith(start[j])) {
                ignore = true;
                break;
            }
        }
        if (ignore)
            continue;
        for (int j = 0; j < end.length; j++) {
            if (children[i].getName().endsWith(end[j])) {
                ignore = true;
                break;
            }
        }
        if (ignore)
            continue;
        Node newNode = new Node(Node.NODE_TYPE_ENTRY, children[i].getName(), root);
        if (save)
            nodeDao.create(newNode);
        String p = children[i].getAbsolutePath().substring(root.getPath(true).length()).replace("\\", "/");
        newNode.setPath(p);
        newNode.properties = nodeDao.getEmptyForeignCollection("properties");
        newNode.setLastModified(new Date(children[i].lastModified()));
        if (children[i].isDirectory()) {
            listDirRecursive(children[i], root, accumulator, save, previousSnapshot);
        } else {
            newNode.addProperty("bytesize", String.valueOf(children[i].length()));
            String md5 = null;

            if (previousSnapshot != null) {
                //Logger.getRootLogger().info("Searching node in previous snapshot for " + p);
                Iterator<Node> it = previousSnapshot.iterator();
                while (it.hasNext()) {
                    Node previous = it.next();
                    if (previous.getPath(true).equals(p)) {
                        if (previous.getLastModified().equals(newNode.getLastModified()) && previous
                                .getPropertyValue("bytesize").equals(newNode.getPropertyValue("bytesize"))) {
                            md5 = previous.getPropertyValue("md5");
                            //Logger.getRootLogger().info("-- Getting md5 from previous snapshot");
                        }
                        break;
                    }
                }
            }
            if (md5 == null) {
                //Logger.getRootLogger().info("-- Computing new md5");
                md5 = computeMD5(children[i]);
            }
            newNode.addProperty("md5", md5);
            newNode.setLeaf();
        }
        if (save)
            nodeDao.update(newNode);
        if (accumulator != null) {
            accumulator.add(newNode);
        }
        long totalMemory = Runtime.getRuntime().totalMemory();
        long currentMemory = Runtime.getRuntime().freeMemory();
        long percent = (currentMemory * 100 / totalMemory);
        //Logger.getRootLogger().info( percent + "%");
        if (percent <= 5) {
            //System.gc();
        }
    }

}

From source file:com.spotify.docker.client.DefaultDockerClient.java

private RuntimeException propagate(final String method, final WebTarget resource, final Exception e)
        throws DockerException, InterruptedException {
    Throwable cause = e.getCause();

    // Sometimes e is a org.glassfish.hk2.api.MultiException
    // which contains the cause we're actually interested in.
    // So we unpack it here.
    if (e instanceof MultiException) {
        cause = cause.getCause();/*from   w w w  . j ava 2s  .c om*/
    }

    Response response = null;
    if (cause instanceof ResponseProcessingException) {
        response = ((ResponseProcessingException) cause).getResponse();
    } else if (cause instanceof WebApplicationException) {
        response = ((WebApplicationException) cause).getResponse();
    } else if ((cause instanceof ProcessingException) && (cause.getCause() != null)) {
        // For a ProcessingException, The exception message or nested Throwable cause SHOULD contain
        // additional information about the reason of the processing failure.
        cause = cause.getCause();
    }

    if (response != null) {
        throw new DockerRequestException(method, resource.getUri(), response.getStatus(), message(response),
                cause);
    } else if ((cause instanceof SocketTimeoutException) || (cause instanceof ConnectTimeoutException)) {
        throw new DockerTimeoutException(method, resource.getUri(), e);
    } else if ((cause instanceof InterruptedIOException) || (cause instanceof InterruptedException)) {
        throw new InterruptedException("Interrupted: " + method + " " + resource);
    } else {
        throw new DockerException(e);
    }
}

From source file:org.auraframework.impl.adapter.ServletUtilAdapterImplUnitTest.java

/**
 * Verifies second exception within handleServletException is caught and processed
 * we throw 'EmptyStackException' when getting InstanceStack, when
 * exceptionAdapter.handleException(death) handle the exception,
 * we throw second exception, then verify we printout the error message to response's writer
 *///from w ww  .  j ava2 s  .  c  om
@Test
public void testHandleExceptionDoubleDeathCaught() throws Exception {
    PrintWriter writer = Mockito.mock(PrintWriter.class);
    HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
    ContextService mockContextService = Mockito.mock(ContextService.class);
    AuraContext mockContext = Mockito.mock(AuraContext.class);
    ConfigAdapter mockConfigAdapter = Mockito.mock(ConfigAdapter.class);
    ExceptionAdapter mockExceptionAdapter = Mockito.mock(ExceptionAdapter.class);

    Throwable firstException = new EmptyStackException();
    String ccmeMsg = "double dead";
    Throwable secondException = new ConcurrentModificationException("double dead");

    Mockito.when(mockResponse.getWriter()).thenReturn(writer);
    Mockito.when(mockResponse.getStatus()).thenReturn(HttpStatus.SC_OK);
    Mockito.when(mockContext.getFormat()).thenReturn(AuraContext.Format.HTML);
    Mockito.when(mockContext.getMode()).thenReturn(Mode.DEV);
    Mockito.when(mockConfigAdapter.isProduction()).thenReturn(false);
    Mockito.when(mockContextService.getCurrentContext()).thenReturn(mockContext);
    Mockito.when(mockContext.getInstanceStack()).thenThrow(firstException);
    Mockito.when(mockExceptionAdapter.handleException(firstException)).thenThrow(secondException);

    Throwable exception = new InterruptedException("opps");

    ServletUtilAdapterImpl adapter = Mockito.spy(new ServletUtilAdapterImpl());
    adapter.setContextService(mockContextService);
    adapter.setConfigAdapter(mockConfigAdapter);
    adapter.setExceptionAdapter(mockExceptionAdapter);
    adapter.handleServletException(exception, true, mockContext, mockRequest, mockResponse, true);

    ArgumentCaptor<String> exceptionMessage = ArgumentCaptor.forClass(String.class);
    Mockito.verify(writer, Mockito.times(1)).println(exceptionMessage.capture());

    assertEquals(ccmeMsg, exceptionMessage.getValue());
    // in this case we return SC_OK, and we set non-cacheable.
    Mockito.verify(mockResponse, Mockito.atLeastOnce()).setStatus(HttpStatus.SC_OK);
    Mockito.verify(mockContextService, Mockito.atLeastOnce()).endContext();
    Mockito.verify(adapter, Mockito.atLeastOnce()).setNoCache(mockResponse);
}

From source file:com.threerings.getdown.data.Application.java

/**
 * Verifies the code and media resources associated with this application. A list of resources
 * that do not exist or fail the verification process will be returned. If all resources are
 * ready to go, null will be returned and the application is considered ready to run.
 *
 * @param obs a progress observer that will be notified of verification progress. NOTE: this
 * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
 * you have to take care to get back to your UI thread.
 * @param alreadyValid if non-null a 1 element array that will have the number of "already
 * validated" resources filled in.//from  w  ww  . j ava2s. c o m
 * @param unpacked a set to populate with unpacked resources.
 */
public List<Resource> verifyResources(ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked)
        throws InterruptedException {
    List<Resource> rsrcs = getAllActiveResources();
    List<Resource> failures = new ArrayList<Resource>();

    // obtain the sizes of the resources to validate
    long[] sizes = new long[rsrcs.size()];
    for (int ii = 0; ii < sizes.length; ii++) {
        sizes[ii] = rsrcs.get(ii).getLocal().length();
    }

    ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
    boolean noUnpack = SysProps.noUnpack();
    for (int ii = 0; ii < sizes.length; ii++) {
        Resource rsrc = rsrcs.get(ii);
        if (Thread.interrupted()) {
            throw new InterruptedException("m.applet_stopped");
        }

        ProgressObserver robs = pagg.startElement(ii);
        if (rsrc.isMarkedValid()) {
            if (alreadyValid != null) {
                alreadyValid[0]++;
            }
            robs.progress(100);
            continue;
        }

        try {
            if (_digest.validateResource(rsrc, robs)) {
                // unpack this resource if appropriate
                if (noUnpack || !rsrc.shouldUnpack()) {
                    // finally note that this resource is kosher
                    rsrc.markAsValid();
                    continue;
                }
                if (rsrc.unpack()) {
                    unpacked.add(rsrc);
                    rsrc.markAsValid();
                    continue;
                }
                log.info("Failure unpacking resource", "rsrc", rsrc);
            }

        } catch (Exception e) {
            log.info("Failure validating resource. Requesting redownload...", "rsrc", rsrc, "error", e);

        } finally {
            robs.progress(100);
        }
        failures.add(rsrc);
    }

    return (failures.size() == 0) ? null : failures;
}

From source file:org.apache.hadoop.hdfs.DFSInputStream.java

private ByteBuffer getFirstToComplete(CompletionService<ByteBuffer> hedgedService,
        ArrayList<Future<ByteBuffer>> futures) throws InterruptedException {
    if (futures.isEmpty()) {
        throw new InterruptedException("let's retry");
    }/*from  w w  w.j  a v a  2s  . com*/
    Future<ByteBuffer> future = null;
    try {
        future = hedgedService.take();
        ByteBuffer bb = future.get();
        futures.remove(future);
        return bb;
    } catch (ExecutionException e) {
        // already logged in the Callable
        futures.remove(future);
    } catch (CancellationException ce) {
        // already logged in the Callable
        futures.remove(future);
    }
    throw new InterruptedException("let's retry");
}