Example usage for java.util.concurrent ExecutionException ExecutionException

List of usage examples for java.util.concurrent ExecutionException ExecutionException

Introduction

In this page you can find the example usage for java.util.concurrent ExecutionException ExecutionException.

Prototype

public ExecutionException(String message, Throwable cause) 

Source Link

Document

Constructs an ExecutionException with the specified detail message and cause.

Usage

From source file:com.ebay.pulsar.analytics.memcachedcache.MemcachedCacheTest.java

@Test
public void MemcachedCache() {
    // MemcachedCacheConfig test
    final MemcachedCacheConfig mc = new MemcachedCacheConfig();
    mc.setMaxObjectSize(mc.getMaxObjectSize());
    mc.setMaxOperationQueueSize(mc.getMaxOperationQueueSize());
    mc.setMemcachedPrefix(mc.getMemcachedPrefix());
    mc.setReadBufferSize(mc.getReadBufferSize());
    mc.setTimeout(mc.getMaxObjectSize());
    Assert.assertTrue(mc.getHosts() == null);
    //ArrayList<String> al2 = new ArrayList<String>();
    //al2.add("localhost:8080");
    mc.setHosts("localhost:8080");

    MemcachedCache INSTANCE = MemcachedCache.create(mc);

    Assert.assertTrue(INSTANCE != null);

    MemcachedClientIF client = Mockito.mock(MemcachedClientIF.class);
    try {/*from  ww  w  .  ja  va 2  s  .  c o m*/
        ReflectFieldUtil.setField(INSTANCE, "client", client);
    } catch (Exception e) {
        e.printStackTrace();
    }

    //regular test
    final NamedKey nk = new NamedKey("space", "key".getBytes());

    when(client.set(computeKeyHash(mc.getMemcachedPrefix(), nk), 1000, serializeValue(nk, "result".getBytes())))
            .thenAnswer(new Answer<Future<Boolean>>() {
                public Future<Boolean> answer(InvocationOnMock invocation) throws Throwable {
                    //Future<Boolean> future = Mockito.mock(FutureTask.class);
                    when(future1.get()).thenReturn(true);
                    return future1;
                }
            });

    try {
        INSTANCE.put(nk, "result".getBytes(), 1000);
    } catch (Exception e) {
        e.printStackTrace();
    }

    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nk))).thenAnswer(new Answer<Future<Object>>() {
        public Future<Object> answer(InvocationOnMock invocation) throws Throwable {
            //Future<Object> future = Mockito.mock(FutureTask.class);
            when(future2.get(mc.getTimeout(), TimeUnit.MILLISECONDS))
                    .thenReturn(serializeValue(nk, "result".getBytes()));
            return future2;
        }
    });

    String re = new String(INSTANCE.get(nk));
    Assert.assertTrue(re.equals("result"));

    /////client exception
    final NamedKey nkIllegalStateException = new NamedKey("space", "IllegalStateException".getBytes());

    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nkIllegalStateException)))
            .thenThrow(new IllegalStateException("nkIllegalStateException"));

    Assert.assertTrue(INSTANCE.get(nkIllegalStateException) == null);

    //future exception
    final NamedKey nkTimeoutException = new NamedKey("space", "TimeoutException".getBytes());
    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nkTimeoutException)))
            .thenAnswer(new Answer<Future<Object>>() {
                public Future<Object> answer(InvocationOnMock invocation) throws Throwable {
                    //Future<Object> future = Mockito.mock(FutureTask.class);
                    when(future3.get(mc.getTimeout(), TimeUnit.MILLISECONDS))
                            .thenThrow(new TimeoutException("TimeoutException"));
                    return future3;
                }
            });
    Assert.assertTrue(INSTANCE.get(nkTimeoutException) == null);

    final NamedKey nkInterruptedException = new NamedKey("space", "InterruptedException".getBytes());
    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nkInterruptedException)))
            .thenAnswer(new Answer<Future<Object>>() {
                public Future<Object> answer(InvocationOnMock invocation) throws Throwable {
                    //Future<Object> future = Mockito.mock(FutureTask.class);
                    when(future4.get(mc.getTimeout(), TimeUnit.MILLISECONDS))
                            .thenThrow(new InterruptedException("InterruptedException"));
                    return future4;
                }
            });
    try {
        Assert.assertTrue(INSTANCE.get(nkInterruptedException) == null);
    } catch (Exception e) {

    }

    final NamedKey nkExecutionException = new NamedKey("space", "ExecutionException".getBytes());
    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nkExecutionException)))
            .thenAnswer(new Answer<Future<Object>>() {
                public Future<Object> answer(InvocationOnMock invocation) throws Throwable {
                    //Future<Object> future = Mockito.mock(FutureTask.class);
                    when(future5.get(mc.getTimeout(), TimeUnit.MILLISECONDS)).thenThrow(
                            new ExecutionException("ExecutionException", new Exception("ExecutionException")));
                    return future5;
                }
            });
    Assert.assertTrue(INSTANCE.get(nkExecutionException) == null);

    ////////test bulk

    //get bulk fail
    final NamedKey nkIllegalStateExceptionBulk = new NamedKey("space", "IllegalStateException".getBytes());
    ArrayList<NamedKey> a1 = new ArrayList<NamedKey>();
    a1.add(nkIllegalStateExceptionBulk);
    Map<String, NamedKey> keyLookup = Maps.uniqueIndex(a1, new Function<NamedKey, String>() {
        @Override
        public String apply(NamedKey input) {
            return computeKeyHash(mc.getMemcachedPrefix(), input);
        }
    });

    when(client.asyncGetBulk(keyLookup.keySet()))
            .thenThrow(new IllegalStateException("nkIllegalStateException"));

    Assert.assertTrue(INSTANCE.getBulk(a1).size() == 0);

    //test future
    final NamedKey some = new NamedKey("space", "resultsome".getBytes());
    ArrayList<NamedKey> a2 = new ArrayList<NamedKey>();
    a2.add(some);
    Map<String, NamedKey> keyLookup2 = Maps.uniqueIndex(a2, new Function<NamedKey, String>() {
        @Override
        public String apply(NamedKey input) {
            return computeKeyHash(mc.getMemcachedPrefix(), input);
        }
    });

    when(client.asyncGetBulk(keyLookup2.keySet())).thenAnswer(new Answer<BulkFuture<Map<String, Object>>>() {
        public BulkFuture<Map<String, Object>> answer(InvocationOnMock invocation) throws Throwable {
            //BulkFuture<Map<String, Object>> future = Mockito.mock(BulkFuture.class);
            Map<String, Object> mp = new HashMap<String, Object>();
            mp.put(computeKeyHash(mc.getMemcachedPrefix(), some), serializeValue(some, "result".getBytes()));
            when(future8.getSome(mc.getTimeout(), TimeUnit.MILLISECONDS)).thenReturn(mp);
            return future8;
        }
    });

    String somere = new String(INSTANCE.getBulk(a2).get(some));
    Assert.assertTrue(somere.equals("result"));

    //test bulk exception
    final NamedKey someInterruptedException = new NamedKey("space", "someInterruptedException".getBytes());
    ArrayList<NamedKey> a3 = new ArrayList<NamedKey>();
    a3.add(someInterruptedException);
    Map<String, NamedKey> keyLookup3 = Maps.uniqueIndex(a3, new Function<NamedKey, String>() {
        @Override
        public String apply(NamedKey input) {
            return computeKeyHash(mc.getMemcachedPrefix(), input);
        }
    });

    when(client.asyncGetBulk(keyLookup3.keySet())).thenAnswer(new Answer<BulkFuture<Map<String, Object>>>() {
        public BulkFuture<Map<String, Object>> answer(InvocationOnMock invocation) throws Throwable {
            //BulkFuture<Map<String, Object>> future = Mockito.mock(BulkFuture.class);
            when(future6.getSome(mc.getTimeout(), TimeUnit.MILLISECONDS))
                    .thenThrow(new InterruptedException("someInterruptedException"));
            return future6;
        }
    });
    try {
        INSTANCE.getBulk(a3).get(someInterruptedException);
    } catch (Exception e) {
        System.out.println("Catch InterruptedException success!");
    }

    final NamedKey someExecutionException = new NamedKey("space", "someExecutionException".getBytes());
    ArrayList<NamedKey> a4 = new ArrayList<NamedKey>();
    a4.add(someExecutionException);
    Map<String, NamedKey> keyLookup4 = Maps.uniqueIndex(a4, new Function<NamedKey, String>() {
        @Override
        public String apply(NamedKey input) {
            return computeKeyHash(mc.getMemcachedPrefix(), input);
        }
    });

    when(client.asyncGetBulk(keyLookup4.keySet())).thenAnswer(new Answer<BulkFuture<Map<String, Object>>>() {
        public BulkFuture<Map<String, Object>> answer(InvocationOnMock invocation) throws Throwable {
            //BulkFuture<Map<String, Object>> future = Mockito.mock(BulkFuture.class);
            when(future7.getSome(mc.getTimeout(), TimeUnit.MILLISECONDS)).thenThrow(
                    new ExecutionException("someExecutionException", new Exception("someExecutionException")));
            return future7;
        }
    });

    Assert.assertTrue(INSTANCE.getBulk(a4).get(someExecutionException) == null);

    CacheStats st = INSTANCE.getStats();
    Assert.assertTrue(st.getNumErrors() == 4);
    Assert.assertTrue(st.getNumHits() == 2);
    Assert.assertTrue(st.getNumMisses() == 0);
}

From source file:Sandbox.ZipExtractor.ProcessZip.java

private void callableWriteToFile() throws FileNotFoundException, InterruptedException, ExecutionException {
    //private void callableWriteToFile(List<ZipFileEntry> partition, int partNo, ExecutorService refreshExecutor) {
    //        int  corePoolSize  = 100;
    //        int  maxPoolSize   = 500;
    //        long keepAliveTime = 5000L;
    ////from w w w  . j  av  a 2 s. co m
    //        // Create thread pool for any Manual Refreshes.
    //        ThreadPoolExecutor refreshExecutor = new ThreadPoolExecutor(
    //                corePoolSize,
    //                maxPoolSize,
    //                keepAliveTime,
    //                TimeUnit.MILLISECONDS,
    //                new LinkedBlockingQueue<Runnable>());

    //ExecutorService executorServiceA = Executors.newFixedThreadPool(10);

    ExecutorService executorService = Executors.newCachedThreadPool();

    // List to keep track of all futures (results of Callable)
    List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();

    int counter = 0;

    for (ZipFileEntry zipFileEntry : practiceLicences) {
        //for (ZipFileEntry zipFileEntry : partition) {
        //System.out.println("\tPartition No: " + partNo + " Processing: " + ++counter);
        //Runnable worker = new WriteToFile("C:\\Temp\\App_Data\\TEST", zipFileEntry);
        //refreshExecutor.execute(worker);

        Callable<Boolean> worker = new WriteToFile("C:\\Temp\\App_Data\\TEST", zipFileEntry);
        Future<Boolean> submit = executorService.submit(worker);

        futures.add(submit);
    }

    // Process futures to create combined list
    for (Future<Boolean> future : futures) {
        try {
            if (future.get().equals(Boolean.FALSE)) {
                throw new FileNotFoundException("Failed to create file.");
            }
        } catch (InterruptedException e) {
            // Write error to log file then re-throw
            throw new InterruptedException(e.getMessage());
        } catch (ExecutionException e) {
            // Write error to log file then re-throw
            throw new ExecutionException(e.getMessage(), e.getCause());
        }
    }

    executorService.shutdown();

    //while(!refreshExecutor.isTerminated()) {
    //}

    //System.out.println("Finished all threads!");
}

From source file:de.fiz.ddb.aas.auxiliaryoperations.ThreadOrganisationCreate.java

/**
 * //w  w  w. j  a va2 s.  co  m
 * @return Organisation
 * @throws AASUnauthorizedException
 * @throws NamingException
 * @throws IOException
 * @throws CloneNotSupportedException
 * @throws IllegalAccessException
 * @throws Exception
 */
@PreAuthorize(privileges = { PrivilegeEnum.DEFAULT }, scope = Scope.ORGANIZATION)
public Organisation call() throws AASUnauthorizedException, ExecutionException, NameAlreadyBoundException {
    Organisation vResult = this._orgObj;
    // -- Fr eine Prfung, ob bereits existent:
    //    but only if that is not a copy in the export directory
    if (!this.isAddToLicensedOrgs() && organizationExists(this._orgObj.getOIDs().getOrgName())) {
        throw new NameAlreadyBoundException(
                "Error: A organization with ID: '" + this._orgObj.getOIDs().getOrgName() + "' already exists!");
    }

    try {
        // -- Ist ein Parent bekannt, muss auch die komplette RDN aufgebaut
        // werden:
        if (!this.isAddToLicensedOrgs()) {
            if ((this._orgObj.getOrgRDN() == null) && (this._orgObj.getOrgParent() != null)
                    && (!this._orgObj.getOrgParent().isEmpty())) {
                ThreadOIDsRDNComplement threadOIDsRDNComplement = new ThreadOIDsRDNComplement(
                        new OIDs(this._orgObj.getOrgParent(), false), getPerformer());
                this._orgParentOIDs = threadOIDsRDNComplement.call();

                if (this._orgParentOIDs != null) {
                    LOG.info("OrgParent = " + this._orgParentOIDs);
                    this._orgObj.setOrgRDN(new StringBuilder(this._orgObj.getId()).append(",")
                            .append(this._orgParentOIDs.getOrgRDN()).toString());
                } else {
                    throw new IllegalArgumentException("Error: A parent organization with ID: '"
                            + this._orgObj.getOrgParent() + "' not found!");
                }
            } else {
                this._orgObj.setOrgRDN(this._orgObj.getId());
            }
        }

        // -- Ask about Geo coordinates but only if that is not a copy in the export directory or Licensed directory
        if (!this.isAddToLicensedOrgs() && !this.isIngestingOperation()) {
            boolean vQueryRequestForGeocoding = ((Math.abs(this._orgObj.getAddress().getLatitude()) <= 1e-6)
                    || (Math.abs(this._orgObj.getAddress().getLongitude()) <= 1e-6));
            if (vQueryRequestForGeocoding) {
                try {
                    GeoRequest vGeoRequest = new GeoRequest(new GeoAdresse(this._orgObj.getAddress()),
                            LDAPConnector.getSingletonInstance().getHttpProxy());
                    vGeoRequest.setAskForLocation(true);
                    // -- should be set by Properties... change it!
                    vGeoRequest.addAcceptLocationType(GeoLocationType.ROOFTOP,
                            GeoLocationType.RANGE_INTERPOLATED, GeoLocationType.GEOMETRIC_CENTER,
                            GeoLocationType.APPROXIMATE);
                    _submit = LDAPConnector.getSingletonInstance().getExecutorServiceOne().submit(vGeoRequest);
                } catch (IllegalAccessException ex) {
                    LOG.log(Level.SEVERE, "Error bei Adresse: " + this._orgObj.getAddress(), ex);
                }
            }
        }

        this.createOrg();
        vResult = this._orgObj;

        // -- The performer gets automatically a member of this organization
        //  X  but only if that is not a copy in the export or licensed directory
        if ((!this.isAddToLicensedOrgs()) && (this._performer != null)) {
            //if ((this._performer != null)) {
            Map<OIDs, Set<PrivilegeEnum>> privileges = new HashMap<OIDs, Set<PrivilegeEnum>>();
            privileges.put(this._orgObj.getOIDs(), new HashSet<PrivilegeEnum>());
            privileges.get(this._orgObj.getOIDs()).add(PrivilegeEnum.ADMIN_ORG);
            ThreadUserOrgPrivilegsOperations threadUserOrgPrivilegsOperations = new ThreadUserOrgPrivilegsOperations(
                    _performer.getUid(), privileges, Action.ADD, this._performer);
            threadUserOrgPrivilegsOperations.call();
        }

    } catch (ExecutionException ex) {
        LOG.log(Level.WARNING, ex.getMessage(), ex.getCause());
        throw ex;
    } catch (NameNotFoundException ex) {
        LOG.log(Level.SEVERE, ex.getMessage());
        throw new ExecutionException(ex.getMessage(), ex);
    } catch (AssertionError ex) {
        LOG.log(Level.SEVERE, ex.getMessage());
        throw new ExecutionException(ex.getMessage(), ex);
    } finally {
        if (this._ready != null) {
            this._ready.countDown();
        }
        if ((_submit != null) && (!_submit.isDone()) && (!_submit.isCancelled())) {
            _submit.cancel(true);
        }
    }
    return vResult;
}

From source file:org.eclipse.tycho.nexus.internal.plugin.cache.UnzipCacheTest.java

@Test
public void testCacheForThreadSafty() throws InterruptedException, ExecutionException {
    final CountDownLatch startSignal = new CountDownLatch(1);
    final CountDownLatch doneSignal = new CountDownLatch(40);

    final ExecutorService executor = Executors.newCachedThreadPool();
    final List<Future<Void>> results = new LinkedList<Future<Void>>();

    for (int i = 0; i < 20; i++) {
        final Callable<Void> c = new CacheStressWorker(startSignal, doneSignal, PATH_TO_OLD_ZIP);
        results.add(executor.submit(c));
        final Callable<Void> c2 = new CacheStressWorker(startSignal, doneSignal, PATH_TO_LATEST_ZIP);
        results.add(executor.submit(c2));
    }/*from   ww w  .  j a va2 s  .c  o m*/

    //all threads: GO!
    startSignal.countDown();

    //Wait till all threads are done
    doneSignal.await();

    //Check all results: if an exception occured fail (probably an concurrency issue)
    for (final Future<Void> submitResult : results) {
        try {
            submitResult.get();
        } catch (final ExecutionException e) {
            throw new ExecutionException("At least one thread fail to execute", e);
        }
    }

    executor.shutdown();
}

From source file:org.jactr.core.model.six.DefaultCycleProcessor6.java

/**
 * using the current contents of the buffer, derive the conflict set and
 * select the best production. Request it to be fired, and eventually return
 * the result.//from  w  ww  .j  a v  a  2 s  .co  m
 * 
 * @return firing time (or NaN if we should quit) or -inf if no production was
 *         fired
 */
protected double evaluateAndFireProduction(BasicModel model, double currentTime)
        throws InterruptedException, ExecutionException {
    if (_nextPossibleProductionFiringTime > currentTime)
        return Double.NEGATIVE_INFINITY;

    /*
     * get the buffers and their contents
     */
    Collection<IActivationBuffer> buffers = model.getActivationBuffers();

    /*
     * and the procedural module since we'll be using him quite frequently
     */
    IProceduralModule procMod = model.getProceduralModule();

    /*
     * snag the conflict set, procMod should fire the notification events itself
     * this and selectInstantiation should not be separate methods, or better
     * yet, provide a third method
     */
    Future<Collection<IInstantiation>> conflictSet = procMod.getConflictSet(buffers);

    /*
     * figure out who is the best production..
     */
    IInstantiation instantiation = null;

    instantiation = procMod.selectInstantiation(conflictSet.get()).get();

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Conflict resolution selected " + instantiation);

    /*
     * and fire his arse.. and snag his return time -inf if no production was
     * fired, NaN if we should quit
     */
    double firingDuration = Double.NEGATIVE_INFINITY;
    if (instantiation != null)
        try {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Firing " + instantiation);
            firingDuration = procMod.fireProduction(instantiation, currentTime).get();

            _nextPossibleProductionFiringTime = currentTime + firingDuration;
        } catch (ExecutionException e) {
            throw new ExecutionException("Failed to execute " + instantiation, e.getCause());
        }
    else
        _nextPossibleProductionFiringTime = currentTime + procMod.getDefaultProductionFiringTime();

    return firingDuration;
}

From source file:org.openspaces.grid.gsm.machines.plugins.NonBlockingElasticMachineProvisioningAdapter.java

@Override
public FutureStoppedMachine stopMachineAsync(final GridServiceAgent agent, final long duration,
        final TimeUnit unit) {

    final AtomicReference<Throwable> atomicExceptionRef = new AtomicReference<Throwable>();
    final AtomicBoolean atomicDone = new AtomicBoolean(false);

    if (!isStartMachineSupported()) {
        throw new UnsupportedOperationException();
    }//from ww  w  . j a  va  2 s.  c  o  m

    final long start = System.currentTimeMillis();
    final long end = System.currentTimeMillis() + unit.toMillis(duration);
    final String hostAddress = agent.getMachine().getHostAddress();
    submit(new Runnable() {

        @Override
        public void run() {

            logger.info("Stopping machine " + hostAddress);
            try {
                NonBlockingElasticMachineProvisioningAdapter.this.machineProvisioning
                        .stopMachine(new StartedGridServiceAgent(agent, null), duration, unit);
                logger.info("machine " + hostAddress + " successfully stopped.");
                atomicDone.set(true);
            } catch (ElasticMachineProvisioningException e) {
                atomicExceptionRef.set(e);
            } catch (ElasticGridServiceAgentProvisioningException e) {
                atomicExceptionRef.set(e);
            } catch (InterruptedException e) {
                atomicExceptionRef.set(e);
            } catch (TimeoutException e) {
                atomicExceptionRef.set(e);
            } catch (NoClassDefFoundError e) {
                atomicExceptionRef.set((new NoClassDefFoundElasticMachineProvisioningException(e)));
            } catch (Throwable e) {
                atomicExceptionRef.set(e);
            }
        }

    });

    return new FutureStoppedMachine() {

        @Override
        public boolean isTimedOut() {
            Throwable exception = atomicExceptionRef.get();
            return (exception instanceof TimeoutException) || (!isDone() && System.currentTimeMillis() > end);
        }

        @Override
        public boolean isDone() {
            return atomicDone.get() || (atomicExceptionRef.get() != null);
        }

        @Override
        public Date getTimestamp() {
            return new Date(start);
        }

        @Override
        public ExecutionException getException() {
            ExecutionException executionException = null;
            Throwable throwable = atomicExceptionRef.get();
            if (throwable != null) {
                executionException = new ExecutionException(throwable.getMessage(), throwable);
            }
            return executionException;
        }

        @Override
        public Void get() throws ExecutionException, IllegalStateException, TimeoutException {

            if (!isDone()) {
                // dont allow calling get() before isDone returns true.
                throw new IllegalStateException("Async operation has not completed yet");
            }

            if (isDone() && getException() == null) {
                // all is ok
                return null;
            } else {
                throw getException();
            }
        }

        @Override
        public GridServiceAgent getGridServiceAgent() {
            return agent;
        }
    };

}

From source file:com.alibaba.openapi.client.rpc.AlibabaClientReactor.java

public <T> Future<T> send(Request request, Class<T> resultType, ClientPolicy clientPolicy,
        final RequestPolicy requestPolicy, FutureCallback<T> callback) {
    final InvokeContext context = new InvokeContext();
    context.setRequest(request);//from w w w  .j av a 2  s. c  o m
    context.setPolicy(requestPolicy);
    context.setCallback(callback);
    context.setResultType(resultType);
    int serverPort = requestPolicy.isUseHttps() ? clientPolicy.getHttpsPort() : clientPolicy.getHttpPort();
    LoggerHelper.getClientLogger().finer(
            "Use " + (clientPolicy.isUseHttps() ? "https" : "http") + " connect and create SessionRequest");
    //SessionRequestCallback??
    //SessionRequest??
    final SessionRequest req = ioReactor.connect(
            new InetSocketAddress(clientPolicy.getServerHost(), serverPort), null, context,
            new SessionRequestCallbackTrigger());

    return new Future<T>() {
        private boolean cancelled = false;

        public boolean cancel(boolean mayInterruptIfRunning) {
            if (req.isCompleted() || cancelled) {
                return false;
            }
            cancelled = true;
            req.cancel();
            context.completed();
            return true;
        }

        public boolean isCancelled() {
            return cancelled;
        }

        public boolean isDone() {
            return context.isCompleted() || cancelled;
        }

        public T get() throws InterruptedException, ExecutionException {
            context.waitForComplete();
            return _get();
        }

        public T get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            context.waitForComplete(timeout, unit);
            return _get();
        }

        @SuppressWarnings("unchecked")
        private T _get() throws ExecutionException {
            Response response = ((InvokeContext) req.getAttachment()).getResponse();
            Throwable targetException = response.getException();
            if (targetException != null) {
                if (requestPolicy.getErrorHandler() != null && targetException instanceof OceanException) {
                    requestPolicy.getErrorHandler().handle((OceanException) targetException);
                }
                throw new ExecutionException(targetException.getMessage(), targetException);
            }
            return (T) response.getResult();
        }
    };
}

From source file:org.eclipse.tycho.nexus.internal.plugin.cache.UnzipCacheTest.java

@Test
public void testMultiThreadedCleanUpAndCreation() throws InterruptedException, ExecutionException {
    final CountDownLatch startSignal = new CountDownLatch(1);
    final CountDownLatch doneSignal = new CountDownLatch(40);

    final ExecutorService executor = Executors.newCachedThreadPool();
    final List<Future<Void>> results = new LinkedList<Future<Void>>();

    for (int i = 0; i < 20; i++) {
        final Callable<Void> c = new RequestWorker(startSignal, doneSignal, true);
        results.add(executor.submit(c));
        final Callable<Void> c2 = new RequestWorker(startSignal, doneSignal, false);
        results.add(executor.submit(c2));
    }//w w w  .j av  a2s  .com
    //all threads: GO!
    startSignal.countDown();

    //Wait till all threads are done
    doneSignal.await();

    //Check all results: if an exception occured fail (probably an concurrency issue)
    for (final Future<Void> submitResult : results) {
        try {
            submitResult.get();
        } catch (final ExecutionException e) {
            throw new ExecutionException("At least one thread fail to execute", e);
        }
    }

    executor.shutdown();
}

From source file:org.apache.bookkeeper.meta.MetadataDrivers.java

/**
 * Process the provided <i>function</i> with metadata client driver resolved
 * from the metadata service uri returned by {@link ClientConfiguration#getMetadataServiceUri()}.
 *
 * @param conf client configuration//from   w w w.j  a va  2  s . c  om
 * @param function function to apply with metadata client driver.
 * @param executorService executor service used by the metadata client driver.
 * @throws MetadataException when failed to access metadata store
 * @throws ExecutionException exception thrown when processing <tt>function</tt>.
 */
public static <T> T runFunctionWithMetadataClientDriver(ClientConfiguration conf,
        Function<MetadataClientDriver, T> function, ScheduledExecutorService executorService)
        throws MetadataException, ExecutionException {
    try (MetadataClientDriver driver = MetadataDrivers
            .getClientDriver(URI.create(conf.getMetadataServiceUri()))) {
        driver.initialize(conf, executorService, NullStatsLogger.INSTANCE, Optional.empty());
        try {
            return function.apply(driver);
        } catch (Exception uee) {
            if (uee.getCause() instanceof MetadataException) {
                throw (MetadataException) uee.getCause();
            } else {
                throw new ExecutionException(uee.getMessage(), uee.getCause());
            }
        }
    } catch (ConfigurationException e) {
        throw new MetadataException(Code.INVALID_METADATA_SERVICE_URI, e);
    }
}

From source file:org.apache.hadoop.hive.druid.DruidStorageHandlerUtils.java

static FullResponseHolder getResponseFromCurrentLeader(HttpClient client, Request request,
        FullResponseHandler fullResponseHandler) throws ExecutionException, InterruptedException {
    FullResponseHolder responseHolder = client.go(request, fullResponseHandler).get();
    if (HttpResponseStatus.TEMPORARY_REDIRECT.equals(responseHolder.getStatus())) {
        String redirectUrlStr = responseHolder.getResponse().headers().get("Location");
        LOG.debug("Request[%s] received redirect response to location [%s].", request.getUrl(), redirectUrlStr);
        final URL redirectUrl;
        try {/*from  w w w . jav  a2s  . c  om*/
            redirectUrl = new URL(redirectUrlStr);
        } catch (MalformedURLException ex) {
            throw new ExecutionException(String.format(
                    "Malformed redirect location is found in response from url[%s], new location[%s].",
                    request.getUrl(), redirectUrlStr), ex);
        }
        responseHolder = client.go(withUrl(request, redirectUrl), fullResponseHandler).get();
    }
    return responseHolder;
}