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.apache.flume.sink.hdfs.BucketWriter.java

/**
 * Execute the callable on a separate thread and wait for the completion for
 * the specified amount of time in milliseconds. In case of timeout cancel
 * the callable and throw an IOException
 *//* w w w. j ava  2 s . c  om*/
private <T> T callWithTimeout(final CallRunner<T> callRunner) throws IOException, InterruptedException {
    Future<T> future = callTimeoutPool.submit(new Callable<T>() {
        @Override
        public T call() throws Exception {
            return proxyUser.execute(new PrivilegedExceptionAction<T>() {
                @Override
                public T run() throws Exception {
                    return callRunner.call();
                }
            });
        }
    });
    try {
        if (callTimeout > 0) {
            return future.get(callTimeout, TimeUnit.MILLISECONDS);
        } else {
            return future.get();
        }
    } catch (TimeoutException eT) {
        future.cancel(true);
        sinkCounter.incrementConnectionFailedCount();
        throw new IOException("Callable timed out after " + callTimeout + " ms" + " on file: " + bucketPath,
                eT);
    } catch (ExecutionException e1) {
        sinkCounter.incrementConnectionFailedCount();
        Throwable cause = e1.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        } else if (cause instanceof InterruptedException) {
            throw (InterruptedException) cause;
        } else if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        } else if (cause instanceof Error) {
            throw (Error) cause;
        } else {
            throw new RuntimeException(e1);
        }
    } catch (CancellationException ce) {
        throw new InterruptedException("Blocked callable interrupted by rotation event");
    } catch (InterruptedException ex) {
        LOG.warn("Unexpected Exception " + ex.getMessage(), ex);
        throw ex;
    }
}

From source file:org.auraframework.integration.test.service.ServerServiceImplTest.java

/**
 * Unhandled exceptions such has InterruptedException should set response status to 500 for JS (and CSS)
 * so it doesn't cache in browser, appcache, etc
 *//*  w  ww. j  a  v a2  s.  c om*/
@Test
public void testHandleInterruptedException() throws Exception {
    PrintWriter writer = mock(PrintWriter.class);
    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    HttpServletResponse mockResponse = mock(HttpServletResponse.class);
    ContextService mockContextService = mock(ContextService.class);
    AuraContext mockContext = mock(AuraContext.class);
    ConfigAdapter mockConfigAdapter = mock(ConfigAdapter.class);
    InstanceStack mockInstanceStack = mock(InstanceStack.class);
    List<String> stack = Lists.newArrayList();
    SerializationService mockSerializationService = mock(SerializationService.class);

    Mockito.when(mockResponse.getWriter()).thenReturn(writer);
    // for JS, SC_INTERNAL_SERVER_ERROR
    Mockito.when(mockContext.getFormat()).thenReturn(AuraContext.Format.JS);
    Mockito.when(mockContext.getMode()).thenReturn(Mode.PROD);
    Mockito.when(mockContext.getInstanceStack()).thenReturn(mockInstanceStack);
    Mockito.when(mockConfigAdapter.isProduction()).thenReturn(true);
    Mockito.when(mockInstanceStack.getStackInfo()).thenReturn(stack);
    Mockito.when(mockContextService.getCurrentContext()).thenReturn(mockContext);

    Throwable exception = new InterruptedException("opps");

    ServletUtilAdapterImpl adapter = new ServletUtilAdapterImpl();
    adapter.setContextService(mockContextService);
    adapter.setConfigAdapter(mockConfigAdapter);
    adapter.setSerializationService(mockSerializationService);
    adapter.handleServletException(exception, true, mockContext, mockRequest, mockResponse, true);

    Mockito.verify(mockResponse).setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    Mockito.verify(mockContextService, atLeastOnce()).endContext();
}

From source file:org.onosproject.p4runtime.ctl.P4RuntimeClientImpl.java

@Override
public void shutdown() {

    log.info("Shutting down client for {}...", deviceId);

    writeLock.lock();/*from   w w w  .  j a  v  a 2  s  .co  m*/
    try {
        if (streamRequestObserver != null) {
            streamRequestObserver.onCompleted();
            cancellableContext.cancel(new InterruptedException("Requested client shutdown"));
        }

        this.executorService.shutdown();
        try {
            executorService.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.warn("Executor service didn't shutdown in time.");
            Thread.currentThread().interrupt();
        }
    } finally {
        writeLock.unlock();
    }
}

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

/**
 * Unhandled exceptions such has InterruptedException should set response status to 500 for JS (and CSS)
 * so it doesn't cache in browser, appcache, etc
 *//*from w ww  . j  a va  2 s  . co m*/
@Test
public void testHandleJSExceptionManifestEnabled() 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);
    InstanceStack mockInstanceStack = Mockito.mock(InstanceStack.class);
    List<String> stack = Lists.newArrayList();
    SerializationService mockSerializationService = Mockito.mock(SerializationService.class);
    ManifestUtil mockManifestUtil = Mockito.mock(ManifestUtil.class);

    Mockito.when(mockResponse.getWriter()).thenReturn(writer);
    Mockito.when(mockContext.getFormat()).thenReturn(AuraContext.Format.JS);
    Mockito.when(mockContext.getMode()).thenReturn(Mode.PROD);
    Mockito.when(mockContext.getInstanceStack()).thenReturn(mockInstanceStack);
    Mockito.when(mockConfigAdapter.isProduction()).thenReturn(true);
    Mockito.when(mockInstanceStack.getStackInfo()).thenReturn(stack);
    Mockito.when(mockContextService.getCurrentContext()).thenReturn(mockContext);
    Mockito.when(mockManifestUtil.isManifestEnabled()).thenReturn(true);
    Throwable exception = new InterruptedException("opps");

    ServletUtilAdapterImpl adapter = new ServletUtilAdapterImpl();
    adapter.setContextService(mockContextService);
    adapter.setConfigAdapter(mockConfigAdapter);
    adapter.setSerializationService(mockSerializationService);
    adapter.setManifestUtil(mockManifestUtil);
    adapter.handleServletException(exception, true, mockContext, mockRequest, mockResponse, true);

    // for JS with appCache enabled, SC_INTERNAL_SERVER_ERROR
    Mockito.verify(mockResponse).setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    Mockito.verify(mockContextService, Mockito.atLeastOnce()).endContext();
}

From source file:org.auraframework.integration.test.service.ServerServiceImplTest.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 .  j a  v  a2  s.co m*/
@Test
public void testHandleExceptionDeathCaught() throws Exception {
    PrintWriter writer = mock(PrintWriter.class);
    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    HttpServletResponse mockResponse = mock(HttpServletResponse.class);
    ContextService mockContextService = mock(ContextService.class);
    AuraContext mockContext = mock(AuraContext.class);
    ConfigAdapter mockConfigAdapter = mock(ConfigAdapter.class);
    ExceptionAdapter mockExceptionAdapter = mock(ExceptionAdapter.class);

    Throwable firstException = new EmptyStackException();

    Mockito.when(mockResponse.getWriter()).thenReturn(writer);
    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 = 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(1)).handleException(handledException.capture());

    assertTrue("Should handle EmptyStackException", handledException.getValue() instanceof EmptyStackException);

    Mockito.verify(mockResponse, atLeastOnce()).setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    Mockito.verify(mockContextService, atLeastOnce()).endContext();
}

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

@Test
public void testHandleJSExceptionManifestDisabled() 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);
    InstanceStack mockInstanceStack = Mockito.mock(InstanceStack.class);
    List<String> stack = Lists.newArrayList();
    SerializationService mockSerializationService = Mockito.mock(SerializationService.class);
    ManifestUtil mockManifestUtil = Mockito.mock(ManifestUtil.class);

    Mockito.when(mockResponse.getWriter()).thenReturn(writer);
    Mockito.when(mockContext.getFormat()).thenReturn(AuraContext.Format.JS);
    Mockito.when(mockContext.getMode()).thenReturn(Mode.PROD);
    Mockito.when(mockContext.getInstanceStack()).thenReturn(mockInstanceStack);
    Mockito.when(mockConfigAdapter.isProduction()).thenReturn(true);
    Mockito.when(mockInstanceStack.getStackInfo()).thenReturn(stack);
    Mockito.when(mockContextService.getCurrentContext()).thenReturn(mockContext);
    Mockito.when(mockManifestUtil.isManifestEnabled()).thenReturn(false);
    Throwable exception = new InterruptedException("opps");

    ServletUtilAdapterImpl adapter = new ServletUtilAdapterImpl();
    adapter.setContextService(mockContextService);
    adapter.setConfigAdapter(mockConfigAdapter);
    adapter.setSerializationService(mockSerializationService);
    adapter.setManifestUtil(mockManifestUtil);
    adapter.handleServletException(exception, true, mockContext, mockRequest, mockResponse, true);

    // for JS with appCache disabled, SC_OK
    Mockito.verify(mockResponse).setStatus(HttpStatus.SC_OK);
    Mockito.verify(mockResponse).setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store");
    Mockito.verify(mockContextService, Mockito.atLeastOnce()).endContext();
}

From source file:org.auraframework.integration.test.service.ServerServiceImplTest.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 w  w.j  a va2  s  . com*/
@Test
public void testHandleExceptionDoubleDeathCaught() throws Exception {
    PrintWriter writer = mock(PrintWriter.class);
    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    HttpServletResponse mockResponse = mock(HttpServletResponse.class);
    ContextService mockContextService = mock(ContextService.class);
    AuraContext mockContext = mock(AuraContext.class);
    ConfigAdapter mockConfigAdapter = mock(ConfigAdapter.class);
    ExceptionAdapter mockExceptionAdapter = 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(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 = 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());
    Mockito.verify(mockResponse, atLeastOnce()).setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    Mockito.verify(mockContextService, atLeastOnce()).endContext();
}

From source file:net.yacy.peers.Protocol.java

private static void remoteSearchProcess(final SearchEvent event, final int count, final long time,
        final String wordhashes, final Seed target, final Blacklist blacklist, final SearchResult result)
        throws SpaceExceededException, InterruptedException {

    // create containers
    final int words = wordhashes.length() / Word.commonHashLength;
    assert words > 0 : "wordhashes = " + wordhashes;
    final List<ReferenceContainer<WordReference>> container = new ArrayList<ReferenceContainer<WordReference>>(
            words);/*from   w w w  .j a  v a  2s.  c o m*/
    for (int i = 0; i < words; i++) {
        container.add(ReferenceContainer.emptyContainer(Segment.wordReferenceFactory,
                ASCII.getBytes(
                        wordhashes.substring(i * Word.commonHashLength, (i + 1) * Word.commonHashLength)),
                count)); // throws SpaceExceededException
    }

    // insert results to containers
    int term = count;
    Map<String, LinkedHashSet<String>> snip;
    if (event.addResultsToLocalIndex) {
        snip = null;
    } else {
        snip = new HashMap<String, LinkedHashSet<String>>(); // needed to display nodestack results
    }
    List<URIMetadataNode> storeDocs = new ArrayList<URIMetadataNode>(result.links.size());
    for (final URIMetadataNode urlEntry : result.links) {
        if (term-- <= 0) {
            break; // do not process more that requested (in case that evil peers fill us up with rubbish)
        }
        // get one single search result
        if (urlEntry == null) {
            continue;
        }
        assert (urlEntry.hash().length == 12) : "urlEntry.hash() = " + ASCII.String(urlEntry.hash());
        if (urlEntry.hash().length != 12) {
            continue; // bad url hash
        }
        if (blacklist.isListed(BlacklistType.SEARCH, urlEntry.url())) {
            if (Network.log.isInfo()) {
                Network.log.info("remote search: filtered blacklisted url " + urlEntry.url().toNormalform(true)
                        + " from peer " + target.getName());
            }
            continue; // block with backlist
        }

        final String urlRejectReason = Switchboard.getSwitchboard().crawlStacker
                .urlInAcceptedDomain(urlEntry.url());
        if (urlRejectReason != null) {
            if (Network.log.isInfo()) {
                Network.log.info("remote search: rejected url '" + urlEntry.url().toNormalform(true) + "' ("
                        + urlRejectReason + ") from peer " + target.getName());
            }
            continue; // reject url outside of our domain
        }

        // save the url entry
        final Reference entry = urlEntry.word();
        if (entry == null) {
            if (Network.log.isWarn()) {
                Network.log.warn("remote search: no word attached from peer " + target.getName() + ", version "
                        + target.getVersion());
            }
            continue; // no word attached
        }

        // the search-result-url transports all the attributes of word indexes
        if (!Base64Order.enhancedCoder.equal(entry.urlhash(), urlEntry.hash())) {
            Network.log.info("remote search: url-hash " + ASCII.String(urlEntry.hash())
                    + " does not belong to word-attached-hash " + ASCII.String(entry.urlhash()) + "; url = "
                    + urlEntry.url().toNormalform(true) + " from peer " + target.getName());
            continue; // spammed
        }

        // passed all checks, store url
        storeDocs.add(urlEntry);
        ResultURLs.stack(ASCII.String(urlEntry.url().hash()), urlEntry.url().getHost(),
                event.peers.mySeed().hash.getBytes(), UTF8.getBytes(target.hash), EventOrigin.QUERIES);

        if (urlEntry.snippet() != null && urlEntry.snippet().length() > 0
                && !urlEntry.snippet().equals("null")) {
            // we don't store the snippets along the url entry,
            // because they are search-specific.
            // instead, they are placed in a snipped-search cache.
            // System.out.println("--- RECEIVED SNIPPET '" + urlEntry.snippet() + "'");
            TextSnippet.snippetsCache.put(wordhashes, ASCII.String(urlEntry.hash()), urlEntry.snippet());
            // add snippet for snippethandling for nodestack entries (used if not stored to index)
            if (!event.addResultsToLocalIndex) {
                // TODO: must have a snippet even to get the snippetcache entry back when adding to nodestack
                LinkedHashSet<String> sniptxt = new LinkedHashSet<String>();
                sniptxt.add(urlEntry.snippet());
                snip.put(ASCII.String(urlEntry.hash()), sniptxt);
            }
        }

        // add the url entry to the word indexes
        for (final ReferenceContainer<WordReference> c : container) {
            try {
                c.add(entry);
            } catch (final SpaceExceededException e) {
                ConcurrentLog.logException(e);
                break;
            }
        }
    }

    // store remote result to local result container
    // insert one container into the search result buffer
    // one is enough, only the references are used, not the word
    if (event.addResultsToLocalIndex) {
        /*
         * Current thread might be interrupted by SearchEvent.cleanup()
         */
        if (Thread.interrupted()) {
            throw new InterruptedException("solrQuery interrupted");
        }
        WriteMetadataNodeToLocalIndexThread writerToLocalIndex = new WriteMetadataNodeToLocalIndexThread(
                event.query.getSegment(), storeDocs);
        writerToLocalIndex.start();
        try {
            writerToLocalIndex.join();
        } catch (InterruptedException e) {
            /*
             * Current thread interruption might happen while waiting
             * for writeToLocalIndexThread.
             */
            writerToLocalIndex.stopWriting();
            throw new InterruptedException("remoteProcess stopped!");
        }
        event.addRWIs(container.get(0), false, target.getName() + "/" + target.hash, result.totalCount, time);
    } else {
        // feed results as nodes (SolrQuery results) which carry metadata,
        // to prevent a call to getMetaData for RWI results, which would fail (if no metadata in index and no display of these results)
        event.addNodes(storeDocs, null, snip, false, target.getName() + "/" + target.hash, count, true);
    }
    event.addFinalize();
    event.addExpectedRemoteReferences(-count);

    // insert the containers to the index
    for (final ReferenceContainer<WordReference> c : container) {
        try {
            event.query.getSegment().storeRWI(c);
        } catch (final Exception e) {
            ConcurrentLog.logException(e);
        }
    }

    // integrate remote top-words/topics
    if (result.references != null && result.references.length > 0) {
        Network.log.info(
                "remote search: peer " + target.getName() + " sent " + result.references.length + " topics");
        // add references twice, so they can be counted (must have at least 2 entries)
        synchronized (event) {
            event.addTopic(result.references);
            event.addTopic(result.references);
        }
    }
    Network.log.info("remote search: peer " + target.getName() + " sent " + container.get(0).size() + "/"
            + result.totalCount + " references");
}

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

/**
 * Wakeup server. This method returns after actual connection status is changed or timeout.
 * Used by jelly.//from  w ww. jav a  2  s  .  co  m
 *
 * @return connection status.
 */
public JSONObject doWakeup() {
    Timer timer = new Timer();
    try {
        startConnection();

        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)) {
            timeoutWakeup = false;
            setConnectionResponse(START_SUCCESS);
        } else {
            timeoutWakeup = true;
            throw new InterruptedException("time out.");
        }
    } catch (Exception ex) {
        setConnectionResponse(START_FAILURE);
        logger.error("Could not start 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.apache.geode.distributed.internal.membership.gms.membership.GMSJoinLeave.java

boolean prepareView(NetView view, List<InternalDistributedMember> newMembers) throws InterruptedException {
    // GEODE-2193 - don't send a view with new members if we're shutting down
    if (isShuttingDown()) {
        throw new InterruptedException("shutting down");
    }/*w  ww.  ja  va2s  .c  o  m*/
    return sendView(view, true, this.prepareProcessor);
}