Search in sources :

Example 91 with ExecutionException

use of java.util.concurrent.ExecutionException in project che by eclipse.

the class LocalVirtualFileSystem method getFileLock.

private FileLock getFileLock(LocalVirtualFile virtualFile) throws ServerException {
    final PathLockFactory.PathLock lockFilePathLock = pathLockFactory.getLock(virtualFile.getPath(), true).acquire(WAIT_FOR_FILE_LOCK_TIMEOUT);
    try {
        final FileLock lock;
        try {
            lock = lockTokensCache.get(virtualFile.getPath());
        } catch (ExecutionException e) {
            String errorMessage = String.format("Unable get lock of file '%s'", virtualFile.getPath());
            LOG.error(errorMessage + "\n" + e.getCause().getMessage(), e.getCause());
            throw new ServerException(errorMessage);
        }
        if (NO_LOCK == lock) {
            return lock;
        }
        if (lock.getExpired() < System.currentTimeMillis()) {
            final File fileLockIoFile = getFileLockIoFile(virtualFile.getPath());
            if (!fileLockIoFile.delete()) {
                if (fileLockIoFile.exists()) {
                    FileCleaner.addFile(fileLockIoFile);
                    LOG.warn("Unable delete lock file %s", fileLockIoFile);
                }
            }
            lockTokensCache.put(virtualFile.getPath(), NO_LOCK);
            return NO_LOCK;
        }
        return lock;
    } finally {
        lockFilePathLock.release();
    }
}
Also used : PathLockFactory(org.eclipse.che.api.vfs.PathLockFactory) ServerException(org.eclipse.che.api.core.ServerException) ExecutionException(java.util.concurrent.ExecutionException) VirtualFile(org.eclipse.che.api.vfs.VirtualFile) File(java.io.File)

Example 92 with ExecutionException

use of java.util.concurrent.ExecutionException in project che by eclipse.

the class DockerConnector method pull.

/**
     * Pull an image from registry.
     * To pull from private registry use registry.address:port/image as image.
     *
     * @param progressMonitor
     *         ProgressMonitor for images creation process
     * @param dockerDaemonUri
     *         docker service URI
     * @throws IOException
     *          when a problem occurs with docker api calls
     */
protected void pull(final PullParams params, final ProgressMonitor progressMonitor, final URI dockerDaemonUri) throws IOException {
    try (DockerConnection connection = connectionFactory.openConnection(dockerDaemonUri).method("POST").path(apiVersionPathPrefix + "/images/create").query("fromImage", params.getFullRepo()).header("X-Registry-Auth", authResolver.getXRegistryAuthHeaderValue(params.getRegistry(), params.getAuthConfigs()))) {
        addQueryParamIfNotNull(connection, "tag", params.getTag());
        final DockerResponse response = connection.request();
        if (OK.getStatusCode() != response.getStatus()) {
            throw getDockerException(response);
        }
        try (InputStream responseStream = response.getInputStream()) {
            JsonMessageReader<ProgressStatus> progressReader = new JsonMessageReader<>(responseStream, ProgressStatus.class);
            // Here do some trick to be able interrupt output streaming process.
            // Current unix socket implementation of DockerConnection doesn't react to interruption.
            // So to be able to close unix socket connection and free resources we use main thread.
            // In case of any exception main thread cancels future and close connection.
            // If Docker connection implementation supports interrupting it will stop streaming on interruption,
            // if not it will be stopped by closure of unix socket
            Future<Object> pullFuture = executor.submit(() -> {
                ProgressStatus progressStatus;
                while ((progressStatus = progressReader.next()) != null) {
                    progressMonitor.updateProgress(progressStatus);
                }
                return null;
            });
            // perform get to be able to get execution exception
            pullFuture.get();
        } catch (ExecutionException e) {
            // unwrap exception thrown by task with .getCause()
            throw new DockerException(e.getCause().getLocalizedMessage(), 500);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new DockerException("Docker image pulling was interrupted", 500);
        }
    }
}
Also used : DockerConnection(org.eclipse.che.plugin.docker.client.connection.DockerConnection) DockerException(org.eclipse.che.plugin.docker.client.exception.DockerException) ProgressStatus(org.eclipse.che.plugin.docker.client.json.ProgressStatus) DockerResponse(org.eclipse.che.plugin.docker.client.connection.DockerResponse) BufferedInputStream(java.io.BufferedInputStream) CloseConnectionInputStream(org.eclipse.che.plugin.docker.client.connection.CloseConnectionInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ExecutionException(java.util.concurrent.ExecutionException)

Example 93 with ExecutionException

use of java.util.concurrent.ExecutionException in project che by eclipse.

the class WorkspaceRuntimesTest method cancellationOfPendingStartTask.

@Test
public void cancellationOfPendingStartTask() throws Throwable {
    WorkspaceImpl workspace = newWorkspace("workspace", "env-name");
    when(sharedPool.submit(any())).thenReturn(Futures.immediateFuture(null));
    CompletableFuture<WorkspaceRuntimeImpl> cmpFuture = runtimes.startAsync(workspace, "env-name", false);
    // the real start is not being executed, fake sharedPool suppressed it
    // so the situation is the same to the one if the task is cancelled before
    // executor service started executing it
    runtimes.stop(workspace.getId());
    // start awaiting clients MUST receive interruption
    try {
        cmpFuture.get();
    } catch (ExecutionException x) {
        verifyCompletionException(cmpFuture, EnvironmentStartInterruptedException.class, "Start of environment 'env-name' in workspace 'workspace' is interrupted");
    }
    // completed clients receive interrupted exception and cancellation doesn't bother them
    try {
        captureAsyncTaskAndExecuteSynchronously();
    } catch (CancellationException cancelled) {
        assertEquals(cancelled.getMessage(), "Start of the workspace 'workspace' was cancelled");
    }
    verifyEventsSequence(event("workspace", WorkspaceStatus.STOPPED, WorkspaceStatus.STARTING, EventType.STARTING, null), event("workspace", WorkspaceStatus.STARTING, WorkspaceStatus.STOPPING, EventType.STOPPING, null), event("workspace", WorkspaceStatus.STOPPING, WorkspaceStatus.STOPPED, EventType.STOPPED, null));
}
Also used : WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) CancellationException(java.util.concurrent.CancellationException) EnvironmentStartInterruptedException(org.eclipse.che.api.environment.server.exception.EnvironmentStartInterruptedException) WorkspaceRuntimeImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceRuntimeImpl) ExecutionException(java.util.concurrent.ExecutionException) Test(org.testng.annotations.Test)

Example 94 with ExecutionException

use of java.util.concurrent.ExecutionException in project jetty.project by eclipse.

the class HttpClientTest method testEarlyEOF.

@Test
public void testEarlyEOF() throws Exception {
    start(new AbstractHandler() {

        @Override
        public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            // Promise some content, then flush the headers, then fail to send the content.
            response.setContentLength(16);
            response.flushBuffer();
            throw new NullPointerException("Explicitly thrown by test");
        }
    });
    try (StacklessLogging stackless = new StacklessLogging(org.eclipse.jetty.server.HttpChannel.class)) {
        client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).timeout(60, TimeUnit.SECONDS).send();
        Assert.fail();
    } catch (ExecutionException x) {
    // Expected.
    }
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Example 95 with ExecutionException

use of java.util.concurrent.ExecutionException in project jetty.project by eclipse.

the class ThreadLimitHandler method handle.

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    // Allow ThreadLimit to be enabled dynamically without restarting server
    if (!_enabled) {
        // if disabled, handle normally
        super.handle(target, baseRequest, request, response);
    } else {
        // Get the remote address of the request
        Remote remote = getRemote(baseRequest);
        if (remote == null) {
            // if remote is not known, handle normally
            super.handle(target, baseRequest, request, response);
        } else {
            // Do we already have a future permit from a previous invocation?
            Closeable permit = (Closeable) baseRequest.getAttribute(PERMIT);
            try {
                if (permit != null) {
                    // Yes, remove it from any future async cycles.
                    baseRequest.removeAttribute(PERMIT);
                } else {
                    // No, then lets try to acquire one
                    CompletableFuture<Closeable> future_permit = remote.acquire();
                    // Did we get a permit?
                    if (future_permit.isDone()) {
                        // yes
                        permit = future_permit.get();
                    } else {
                        if (LOG.isDebugEnabled())
                            LOG.debug("Threadlimited {} {}", remote, target);
                        // No, lets asynchronously suspend the request
                        AsyncContext async = baseRequest.startAsync();
                        // let's never timeout the async.  If this is a DOS, then good to make them wait, if this is not
                        // then give them maximum time to get a thread.
                        async.setTimeout(0);
                        // dispatch the request when we do eventually get a pass
                        future_permit.thenAccept(c -> {
                            baseRequest.setAttribute(PERMIT, c);
                            async.dispatch();
                        });
                        return;
                    }
                }
                // Use the permit
                super.handle(target, baseRequest, request, response);
            } catch (InterruptedException | ExecutionException e) {
                throw new ServletException(e);
            } finally {
                if (permit != null)
                    permit.close();
            }
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) Closeable(java.io.Closeable) AsyncContext(javax.servlet.AsyncContext) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

ExecutionException (java.util.concurrent.ExecutionException)1341 IOException (java.io.IOException)367 Test (org.junit.Test)335 TimeoutException (java.util.concurrent.TimeoutException)258 ArrayList (java.util.ArrayList)237 Future (java.util.concurrent.Future)218 ExecutorService (java.util.concurrent.ExecutorService)152 CountDownLatch (java.util.concurrent.CountDownLatch)103 List (java.util.List)98 CancellationException (java.util.concurrent.CancellationException)98 Callable (java.util.concurrent.Callable)97 Test (org.testng.annotations.Test)78 HashMap (java.util.HashMap)69 Map (java.util.Map)65 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)64 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)63 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)56 ParallelTest (com.hazelcast.test.annotation.ParallelTest)47 QuickTest (com.hazelcast.test.annotation.QuickTest)47 UncheckedExecutionException (com.google.common.util.concurrent.UncheckedExecutionException)46