Example usage for java.util.concurrent FutureTask FutureTask

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

Introduction

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

Prototype

public FutureTask(Callable<V> callable) 

Source Link

Document

Creates a FutureTask that will, upon running, execute the given Callable .

Usage

From source file:be.agiv.security.demo.Main.java

private void invokeClaimsAwareService() {
    GridBagLayout gridBagLayout = new GridBagLayout();
    GridBagConstraints gridBagConstraints = new GridBagConstraints();
    JPanel contentPanel = new JPanel(gridBagLayout);

    final JLabel ipStsLabel = new JLabel("IP-STS:");
    gridBagConstraints.gridx = 0;/*from  w  w  w. ja v a2 s  . c o  m*/
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = GridBagConstraints.WEST;
    gridBagConstraints.ipadx = 5;
    gridBagLayout.setConstraints(ipStsLabel, gridBagConstraints);
    contentPanel.add(ipStsLabel);

    final JTextField ipStsTextField = new JTextField(
            "https://auth.beta.agiv.be/ipsts/Services/DaliSecurityTokenServiceConfiguration.svc/IWSTrust13",
            60);
    gridBagConstraints.gridx++;
    gridBagLayout.setConstraints(ipStsTextField, gridBagConstraints);
    contentPanel.add(ipStsTextField);

    JLabel realmLabel = new JLabel("Realm:");
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagLayout.setConstraints(realmLabel, gridBagConstraints);
    contentPanel.add(realmLabel);

    JTextField realmTextField = new JTextField(AGIVSecurity.BETA_REALM, 30);
    gridBagConstraints.gridx++;
    gridBagLayout.setConstraints(realmTextField, gridBagConstraints);
    contentPanel.add(realmTextField);

    final CredentialPanel credentialPanel = new CredentialPanel();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
    gridBagLayout.setConstraints(credentialPanel, gridBagConstraints);
    contentPanel.add(credentialPanel);

    final JLabel rStsLabel = new JLabel("R-STS:");
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagConstraints.gridwidth = 1;
    gridBagLayout.setConstraints(rStsLabel, gridBagConstraints);
    contentPanel.add(rStsLabel);

    final JTextField rStsTextField = new JTextField(
            "https://auth.beta.agiv.be/sts/Services/SalvadorSecurityTokenServiceConfiguration.svc/IWSTrust13",
            60);
    gridBagConstraints.gridx++;
    gridBagLayout.setConstraints(rStsTextField, gridBagConstraints);
    contentPanel.add(rStsTextField);

    JLabel serviceRealmLabel = new JLabel("Service realm:");
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagLayout.setConstraints(serviceRealmLabel, gridBagConstraints);
    contentPanel.add(serviceRealmLabel);

    JTextField serviceRealmTextField = new JTextField(ClaimsAwareServiceFactory.SERVICE_REALM, 60);
    gridBagConstraints.gridx++;
    gridBagLayout.setConstraints(serviceRealmTextField, gridBagConstraints);
    contentPanel.add(serviceRealmTextField);

    JLabel urlLabel = new JLabel("Service URL:");
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagLayout.setConstraints(urlLabel, gridBagConstraints);
    contentPanel.add(urlLabel);

    JTextField urlTextField = new JTextField(ClaimsAwareServiceFactory.SERVICE_LOCATION, 60);
    gridBagConstraints.gridx++;
    gridBagLayout.setConstraints(urlTextField, gridBagConstraints);
    contentPanel.add(urlTextField);

    final JCheckBox noWsPolicyCheckBox = new JCheckBox("WSDL without WS-Policy");
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
    gridBagLayout.setConstraints(noWsPolicyCheckBox, gridBagConstraints);
    contentPanel.add(noWsPolicyCheckBox);

    final JCheckBox useWsSecureConversationCheckBox = new JCheckBox("Use WS-SecureConversation");
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
    gridBagLayout.setConstraints(useWsSecureConversationCheckBox, gridBagConstraints);
    contentPanel.add(useWsSecureConversationCheckBox);

    final JCheckBox usePreviousSecurityCheckBox = new JCheckBox("Use previous AGIV Security");
    final JCheckBox cancelPreviousSecureConversationToken = new JCheckBox("Cancel previous conversation token");
    usePreviousSecurityCheckBox.setEnabled(null != this.agivSecurity);
    cancelPreviousSecureConversationToken.setEnabled(false);
    usePreviousSecurityCheckBox.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            LOG.debug("use previous security: " + usePreviousSecurityCheckBox.isSelected());
            boolean newSecurity = !usePreviousSecurityCheckBox.isSelected();
            ipStsLabel.setEnabled(newSecurity);
            ipStsTextField.setEditable(newSecurity);
            credentialPanel.setEnabled(newSecurity);
            rStsLabel.setEnabled(newSecurity);
            rStsTextField.setEnabled(newSecurity);
            cancelPreviousSecureConversationToken.setEnabled(!newSecurity);
        }
    });
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
    gridBagLayout.setConstraints(usePreviousSecurityCheckBox, gridBagConstraints);
    contentPanel.add(usePreviousSecurityCheckBox);

    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
    gridBagLayout.setConstraints(cancelPreviousSecureConversationToken, gridBagConstraints);
    contentPanel.add(cancelPreviousSecureConversationToken);

    JPanel expiresPanel = new JPanel();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagConstraints.gridwidth = 2;
    gridBagLayout.setConstraints(expiresPanel, gridBagConstraints);
    contentPanel.add(expiresPanel);

    JLabel expiresLabelLabel = new JLabel("Secure conversation token expires:");
    expiresLabelLabel.setEnabled(null != this.agivSecurity);
    expiresPanel.add(expiresLabelLabel);

    JLabel expiresLabel = new JLabel();
    expiresLabel.setEnabled(null != this.agivSecurity);
    expiresPanel.add(expiresLabel);
    if (null != this.agivSecurity) {
        if (false == this.agivSecurity.getSecureConversationTokens().isEmpty()) {
            SecurityToken secureConversationToken = this.agivSecurity.getSecureConversationTokens().values()
                    .iterator().next();
            expiresLabel.setText(secureConversationToken.getExpires().toString());
        }
    }

    int dialogResult = JOptionPane.showConfirmDialog(this, contentPanel, "Claims Aware Service",
            JOptionPane.OK_CANCEL_OPTION);
    if (dialogResult == JOptionPane.CANCEL_OPTION) {
        return;
    }

    final String location = urlTextField.getText();
    final String serviceRealm = serviceRealmTextField.getText();
    final String ipStsLocation = ipStsTextField.getText();
    final String rStsLocation = rStsTextField.getText();
    final String username = credentialPanel.getUsername();
    final String password = credentialPanel.getPassword();
    final File pkcs12File = credentialPanel.getPKCS12File();
    final String realm = realmTextField.getText();

    ExecutorService executor = Executors.newFixedThreadPool(1);
    FutureTask<ArrayOfClaimInfo> futureTask = new FutureTask<ArrayOfClaimInfo>(
            new Callable<ArrayOfClaimInfo>() {

                public ArrayOfClaimInfo call() throws Exception {
                    Service service;
                    if (noWsPolicyCheckBox.isSelected()) {
                        service = ClaimsAwareServiceFactory.getInstanceNoWSPolicy();
                    } else {
                        service = ClaimsAwareServiceFactory.getInstance();
                    }
                    IService iservice = service.getWS2007FederationHttpBindingIService(new AddressingFeature());
                    BindingProvider bindingProvider = (BindingProvider) iservice;

                    if (false == usePreviousSecurityCheckBox.isSelected()) {
                        if (null != username) {
                            Main.this.agivSecurity = new AGIVSecurity(ipStsLocation, rStsLocation, realm,
                                    username, password);
                        } else {
                            Main.this.agivSecurity = new AGIVSecurity(ipStsLocation, rStsLocation, realm,
                                    pkcs12File, password);
                        }
                        Main.this.agivSecurity.addSTSListener(Main.this);
                        if (Main.this.proxyEnable) {
                            agivSecurity.setProxy(Main.this.proxyHost, Main.this.proxyPort,
                                    Main.this.proxyType);
                        }
                    }
                    if (cancelPreviousSecureConversationToken.isSelected()) {
                        Main.this.agivSecurity.cancelSecureConversationTokens();
                    }
                    Main.this.agivSecurity.enable(bindingProvider, location,
                            useWsSecureConversationCheckBox.isSelected(), serviceRealm);

                    ArrayOfClaimInfo result = iservice.getData(0);
                    return result;
                }
            }) {

        @Override
        protected void done() {
            try {
                ArrayOfClaimInfo result = get();
                List<ClaimInfo> claims = result.getClaimInfo();
                StringBuffer message = new StringBuffer();
                for (ClaimInfo claim : claims) {
                    message.append(claim.getName());
                    message.append(" = ");
                    message.append(claim.getValue());
                    message.append("\n");
                }

                JOptionPane.showMessageDialog(Main.this, message.toString(), "Claims Aware Service Result",
                        JOptionPane.INFORMATION_MESSAGE);
            } catch (final Exception e) {
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {

                        public void run() {
                            Main.this.statusBar.setErrorStatus(e.getMessage());
                        }
                    });
                } catch (Exception e1) {
                }
                showException(e);
            }
        }
    };
    executor.execute(futureTask);
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java

protected long runWithTimeout(MutationTestRunnable r) {
    long[] preIds = threadMxBean.getAllThreadIds();
    FutureTask<Object> future = new FutureTask<Object>(Executors.callable(r));
    Thread thread = new Thread(future);
    thread.setDaemon(true);//from w  w  w  .ja va 2  s.c om
    logger.debug("Start  test: ");
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    thread.start();
    String exceptionMessage = null;
    Throwable capturedThrowable = null;
    try {
        future.get(timeout, TimeUnit.SECONDS);
        logger.debug("Second timeout");
    } catch (InterruptedException e) {
        capturedThrowable = e;
    } catch (ExecutionException e) {
        capturedThrowable = e;
    } catch (TimeoutException e) {
        exceptionMessage = JavalancheMessages.MUTATION_TIME_LIMIT_MESSAGE + "Mutation causes test timeout";
        capturedThrowable = e;
    } catch (Throwable t) {
        capturedThrowable = t;
    } finally {
        if (capturedThrowable != null) {
            if (exceptionMessage == null) {
                exceptionMessage = "Exception caught during test execution.";
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            capturedThrowable.printStackTrace(new PrintStream(out));
            logger.debug(
                    "Setting test failed. Message: " + exceptionMessage + " Exception " + capturedThrowable);
            r.setFailed(exceptionMessage, capturedThrowable);
        }
    }
    if (!future.isDone()) {
        r.setFailed(JavalancheMessages.MUTATION_TIME_LIMIT_MESSAGE
                + "Mutated Thread is still running after timeout.", null);
        switchOfMutation(future);
    }
    stopWatch.stop();
    if (!checkAllFinished(preIds)) {
        if (configuration.useThreadStop()) {
            stopThreads(preIds);
        } else {
            shutDown(r, stopWatch);
        }
    }
    logger.debug("End timed test, it took " + stopWatch.getTime() + " ms");
    return stopWatch.getTime();
}

From source file:org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.java

int stopProcessWithTimeout(final Process proc, long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
    FutureTask<Integer> future = new FutureTask<>(() -> {
        proc.destroy();/*from   www .j ava  2 s.  c o  m*/
        return proc.waitFor();
    });

    executor.execute(future);

    return future.get(timeout, unit);
}

From source file:com.impetus.ankush2.hadoop.utils.HadoopUtils.java

/**
 * Gets the jmx bean using callable.//  w  w w .j  a  v  a  2 s  .  c  om
 * 
 * @param host
 *            the host
 * @param clientPort
 *            the client port
 * @param beanName
 *            the bean name
 * @return the jmx bean using callable
 * @throws AnkushException
 *             the ankush exception
 */
public static Map<String, Object> getJmxBeanUsingCallable(String host, String clientPort, String beanName)
        throws AnkushException {
    String errMsg = "Could not get JMX bean data for host-" + host + ", port-" + clientPort + ".";
    try {
        long waitTime = AppStoreWrapper.getAnkushConfReader().getLongValue("hadoop.jmxmonitoring.wait.time");
        CallableJmxBeanData callableJmxBeanData = new CallableJmxBeanData(host, clientPort, beanName);
        FutureTask<Map<String, Object>> futureTaskJmxBeanData = new FutureTask<Map<String, Object>>(
                callableJmxBeanData);

        AppStoreWrapper.getExecutor().execute(futureTaskJmxBeanData);

        Map<String, Object> beanObject = futureTaskJmxBeanData.get(waitTime, TimeUnit.MILLISECONDS);
        if (beanObject == null) {
            throw new AnkushException(errMsg);
        }
        return beanObject;
    } catch (AnkushException e) {
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error(errMsg, Constant.Component.Name.HADOOP, host, e);
        throw new AnkushException(errMsg);
    }
}

From source file:org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl.java

int stopProcessWithTimeout(final Process proc, long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
    FutureTask<Integer> future = new FutureTask<Integer>(new Callable<Integer>() {
        @Override/*from  w w  w  . j a  v  a  2 s  . co  m*/
        public Integer call() throws InterruptedException {
            proc.destroy();
            return proc.waitFor();
        }
    });

    executor.execute(future);

    return future.get(timeout, unit);
}

From source file:com.impetus.ankush2.hadoop.utils.HadoopUtils.java

/**
 * Gets the json object using callable./*  www .j a v  a  2s .c  o  m*/
 * 
 * @param url
 *            the url
 * @return the json object using callable
 * @throws AnkushException
 *             the ankush exception
 */
public static JSONObject getJsonObjectUsingCallable(String url) throws AnkushException {
    String errMsg = "Could not get JSON object for URL-" + url + ".";
    try {
        long waitTime = AppStoreWrapper.getAnkushConfReader().getLongValue("hadoop.jmxmonitoring.wait.time");
        CallableRestJsonData callableRestJsonData = new CallableRestJsonData(url);

        FutureTask<JSONObject> futureTaskJmxBeanData = new FutureTask<JSONObject>(callableRestJsonData);

        AppStoreWrapper.getExecutor().execute(futureTaskJmxBeanData);

        JSONObject beanObject = futureTaskJmxBeanData.get(waitTime, TimeUnit.MILLISECONDS);
        if (beanObject == null) {
            throw new AnkushException(errMsg);
        }
        return beanObject;
    } catch (AnkushException e) {
        throw e;
    } catch (Exception e) {
        LOG.error(errMsg, Constant.Component.Name.HADOOP, e);
        throw new AnkushException(errMsg);
    }
}

From source file:org.apache.stratos.load.balancer.endpoint.TenantAwareLoadBalanceEndpoint.java

private void incrementInFlightRequestCount(MessageContext messageContext) {
    try {/*from w w w. j a  v  a  2  s. co m*/
        String clusterId = (String) messageContext.getProperty(Constants.CLUSTER_ID);
        if (StringUtils.isBlank(clusterId)) {
            throw new RuntimeException("Cluster id not found in message context");
        }
        FutureTask<Object> task = new FutureTask<Object>(new InFlightRequestIncrementCallable(clusterId));
        LoadBalancerStatisticsExecutor.getInstance().getService().submit(task);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Could not increment in-flight request count", e);
        }
    }
}

From source file:org.apache.solr.request.SimpleFacets.java

License:asdf

/**
 * Returns a list of value constraints and the associated facet counts 
 * for each facet field specified in the params.
 *
 * @see FacetParams#FACET_FIELD/*ww  w  . j a v a2s.c o  m*/
 * @see #getFieldMissingCount
 * @see #getFacetTermEnumCounts
 */
@SuppressWarnings("unchecked")
public NamedList<Object> getFacetFieldCounts() throws IOException, SyntaxError {

    NamedList<Object> res = new SimpleOrderedMap<>();
    String[] facetFs = global.getParams(FacetParams.FACET_FIELD);
    if (null == facetFs) {
        return res;
    }

    // Passing a negative number for FACET_THREADS implies an unlimited number of threads is acceptable.
    // Also, a subtlety of directExecutor is that no matter how many times you "submit" a job, it's really
    // just a method call in that it's run by the calling thread.
    int maxThreads = req.getParams().getInt(FacetParams.FACET_THREADS, 0);
    Executor executor = maxThreads == 0 ? directExecutor : facetExecutor;
    final Semaphore semaphore = new Semaphore((maxThreads <= 0) ? Integer.MAX_VALUE : maxThreads);
    List<Future<NamedList>> futures = new ArrayList<>(facetFs.length);

    if (fdebugParent != null) {
        fdebugParent.putInfoItem("maxThreads", maxThreads);
    }

    try {
        //Loop over fields; submit to executor, keeping the future
        for (String f : facetFs) {
            if (fdebugParent != null) {
                fdebug = new FacetDebugInfo();
                fdebugParent.addChild(fdebug);
            }
            final ParsedParams parsed = parseParams(FacetParams.FACET_FIELD, f);
            final SolrParams localParams = parsed.localParams;
            final String termList = localParams == null ? null : localParams.get(CommonParams.TERMS);
            final String key = parsed.key;
            final String facetValue = parsed.facetValue;
            Callable<NamedList> callable = () -> {
                try {
                    NamedList<Object> result = new SimpleOrderedMap<>();
                    if (termList != null) {
                        List<String> terms = StrUtils.splitSmart(termList, ",", true);
                        result.add(key, getListedTermCounts(facetValue, parsed, terms));
                    } else {
                        result.add(key, getTermCounts(facetValue, parsed));
                    }
                    return result;
                } catch (SolrException se) {
                    throw se;
                } catch (Exception e) {
                    throw new SolrException(ErrorCode.SERVER_ERROR,
                            "Exception during facet.field: " + facetValue, e);
                } finally {
                    semaphore.release();
                }
            };

            RunnableFuture<NamedList> runnableFuture = new FutureTask<>(callable);
            semaphore.acquire();//may block and/or interrupt
            executor.execute(runnableFuture);//releases semaphore when done
            futures.add(runnableFuture);
        } //facetFs loop

        //Loop over futures to get the values. The order is the same as facetFs but shouldn't matter.
        for (Future<NamedList> future : futures) {
            res.addAll(future.get());
        }
        assert semaphore.availablePermits() >= maxThreads;
    } catch (InterruptedException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                "Error while processing facet fields: InterruptedException", e);
    } catch (ExecutionException ee) {
        Throwable e = ee.getCause();//unwrap
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                "Error while processing facet fields: " + e.toString(), e);
    }

    return res;
}

From source file:org.apache.stratos.load.balancer.endpoint.TenantAwareLoadBalanceEndpoint.java

private void decrementInFlightRequestCount(MessageContext messageContext) {
    try {/*  w w w .  j a v a2  s.  c  o  m*/
        String clusterId = (String) messageContext.getProperty(Constants.CLUSTER_ID);
        if (StringUtils.isBlank(clusterId)) {
            throw new RuntimeException("Cluster id not found in message context");
        }
        FutureTask<Object> task = new FutureTask<Object>(new InFlightRequestDecrementCallable(clusterId));
        LoadBalancerStatisticsExecutor.getInstance().getService().submit(task);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Could not decrement in-flight request count", e);
        }
    }
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

private void execute(final HttpUriRequest httpUriRequest, final boolean concurrent) throws IOException {
    final HttpClientContext context = HttpClientContext.create();
    context.setRequestConfig(reqConfBuilder.build());
    if (this.host != null)
        context.setTargetHost(new HttpHost(this.host));

    setHeaders(httpUriRequest);//from www . j  ava 2s.c  om
    // statistics
    storeConnectionInfo(httpUriRequest);
    // execute the method; some asserts confirm that that the request can be send with Content-Length and is therefore not terminated by EOF
    if (httpUriRequest instanceof HttpEntityEnclosingRequest) {
        final HttpEntityEnclosingRequest hrequest = (HttpEntityEnclosingRequest) httpUriRequest;
        final HttpEntity entity = hrequest.getEntity();
        assert entity != null;
        //assert !entity.isChunked();
        //assert entity.getContentLength() >= 0;
        assert !hrequest.expectContinue();
    }

    final String initialThreadName = Thread.currentThread().getName();
    Thread.currentThread().setName("HTTPClient-" + httpUriRequest.getURI());
    final long time = System.currentTimeMillis();
    try {

        if (concurrent) {
            FutureTask<CloseableHttpResponse> t = new FutureTask<CloseableHttpResponse>(
                    new Callable<CloseableHttpResponse>() {
                        @Override
                        public CloseableHttpResponse call() throws ClientProtocolException, IOException {
                            final CloseableHttpClient client = clientBuilder.build();
                            CloseableHttpResponse response = client.execute(httpUriRequest, context);
                            return response;
                        }
                    });
            executor.execute(t);
            try {
                this.httpResponse = t.get(this.timeout, TimeUnit.MILLISECONDS);
            } catch (ExecutionException e) {
                throw e.getCause();
            } catch (Throwable e) {
            }
            try {
                t.cancel(true);
            } catch (Throwable e) {
            }
            if (this.httpResponse == null)
                throw new IOException("timout to client after " + this.timeout + "ms" + " for url "
                        + httpUriRequest.getURI().toString());
        } else {
            final CloseableHttpClient client = clientBuilder.build();
            this.httpResponse = client.execute(httpUriRequest, context);
        }
        this.httpResponse.setHeader(HeaderFramework.RESPONSE_TIME_MILLIS,
                Long.toString(System.currentTimeMillis() - time));
    } catch (final Throwable e) {
        ConnectionInfo.removeConnection(httpUriRequest.hashCode());
        httpUriRequest.abort();
        if (this.httpResponse != null)
            this.httpResponse.close();
        //e.printStackTrace();
        throw new IOException(
                "Client can't execute: " + (e.getCause() == null ? e.getMessage() : e.getCause().getMessage())
                        + " duration=" + Long.toString(System.currentTimeMillis() - time) + " for url "
                        + httpUriRequest.getURI().toString());
    } finally {
        /* Restore the thread initial name */
        Thread.currentThread().setName(initialThreadName);
    }
}