Example usage for java.util.concurrent Callable Callable

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

Introduction

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

Prototype

Callable

Source Link

Usage

From source file:disko.flow.analyzers.hgdb.RelationCounterAnalyzer.java

public void process(AnalysisContext<TextDocument> context, Ports ports) throws InterruptedException {
    final HyperGraph graph = this.graph != null ? this.graph : context.getGraph();

    RelationCountFactory.createCountingIndices(graph);

    InputPort<EntityMaintainer> entityInput = ports.getInput(EntityAnalyzer.ENTITY_CHANNEL);
    InputPort<RelexTaskResult> parseInput = ports.getInput(FullRelexAnalyzer.PARSE_CHANNEL);

    for (RelexTaskResult parses = parseInput.take(); !parseInput.isEOS(parses); parses = parseInput.take()) {

        EntityMaintainer em = entityInput.take();
        if (entityInput.isEOS(em))
            break;

        final HashMap<String, String> entityTypes = RelationCountFactory.getEntityTypes(em);

        log.debug("Counting relations for all parses for: " + em.getOriginalSentence());

        final RelexTaskResult currentParses = parses;
        ////from w ww.j  a  v a 2 s.c  om
        // We encapsulate the processing of a single in a HGDB transaction.
        // This gives a considerable
        // performance boost because when there is no current transaction in
        // effect, HGDB will create
        // a transaction for every single query. For a sentence with, say,
        // 20 parses of about 20 relations
        // each this yields 2800 transactions (opening and committing a
        // transaction is a costly operation).
        //
        try {
            log.info("Saving parses for " + em.getOriginalSentence());
            long startTime = System.currentTimeMillis();
            graph.getTransactionManager().transact(new Callable<Object>() {
                public Object call() {
                    for (ParsedSentence parsedSentence : currentParses.result.getParses()) {
                        log.debug(parsedSentence);

                        ArrayList<RelationCount> relationCounts = RelationCountFactory
                                .getRelationCounts(entityTypes, parsedSentence);
                        HashMap<HGHandle, RelationCount> counts = new HashMap<HGHandle, RelationCount>();
                        for (RelationCount r : relationCounts)
                            incrementCounts(graph, counts, r, currentParses.result.getParses().size());
                        for (RelationCount r : counts.values())
                            graph.update(r);
                    }
                    return null;
                }
            });
            log.info("Parses saved, total time elapsed=" + (System.currentTimeMillis() - startTime) / 1000.0);
        } catch (Throwable t) {
            log.error("While storing counts for " + em.getOriginalSentence(), t);
        }
        log.debug("Relation count completed.");
    }
    log.debug("RelationCounterProcessor ended");
}

From source file:com.andrada.sitracker.reader.Samlib.java

@Override
public int addAuthorForUrl(@NotNull String url) {
    Author author = null;/*  ww  w . j av a2s . co m*/
    int message = -1;
    try {
        if (url.equals("") || !url.matches(Constants.SIMPLE_URL_REGEX)) {
            throw new MalformedURLException();
        }
        url = url.replace("zhurnal.lib.ru", "samlib.ru");

        if (!url.endsWith(Constants.AUTHOR_PAGE_URL_ENDING_WO_SLASH)
                && !url.endsWith(Constants.AUTHOR_PAGE_ALT_URL_ENDING_WO_SLASH)) {
            url = (url.endsWith("/")) ? url + Constants.AUTHOR_PAGE_URL_ENDING_WO_SLASH
                    : url + Constants.AUTHOR_PAGE_URL_ENDING_WI_SLASH;
        }

        if (!url.startsWith(Constants.HTTP_PROTOCOL) && !url.startsWith(Constants.HTTPS_PROTOCOL)) {
            url = Constants.HTTP_PROTOCOL + url;
        }
        String urlId = SamlibPageHelper.getUrlIdFromCompleteUrl(url);
        if (helper.getAuthorDao().queryBuilder().where().eq("urlId", urlId).query().size() != 0) {
            throw new AddAuthorException(AddAuthorException.AuthorAddErrors.AUTHOR_ALREADY_EXISTS);
        }

        HttpRequest request = HttpRequest.get(new URL(url));
        if (request.code() == 404) {
            throw new MalformedURLException();
        }
        AuthorPageReader reader = new SamlibAuthorPageReader(request.body());
        author = reader.getAuthor(url);
        helper.getAuthorDao().create(author);
        final List<Publication> items = reader.getPublications(author);
        if (items.size() == 0) {
            helper.getAuthorDao().delete(author);
            throw new AddAuthorException(AddAuthorException.AuthorAddErrors.AUTHOR_NO_PUBLICATIONS);
        }

        helper.getPublicationDao().callBatchTasks(new Callable<Object>() {
            @Nullable
            @Override
            public Object call() throws Exception {
                for (Publication publication : items) {
                    helper.getPublicationDao().create(publication);
                }
                return null;
            }
        });

    } catch (HttpRequest.HttpRequestException e) {
        message = R.string.cannot_add_author_network;
    } catch (MalformedURLException e) {
        message = R.string.cannot_add_author_malformed;
    } catch (SQLException e) {
        if (author != null) {
            try {
                helper.getAuthorDao().delete(author);
            } catch (SQLException e1) {
                //Swallow the exception as the author just wasn't saved
            }
        }
        message = R.string.cannot_add_author_internal;
    } catch (AddAuthorException e) {
        switch (e.getError()) {
        case AUTHOR_ALREADY_EXISTS:
            message = R.string.cannot_add_author_already_exits;
            break;
        case AUTHOR_DATE_NOT_FOUND:
            message = R.string.cannot_add_author_no_update_date;
            break;
        case AUTHOR_NAME_NOT_FOUND:
            message = R.string.cannot_add_author_no_name;
            break;
        case AUTHOR_NO_PUBLICATIONS:
            message = R.string.cannot_add_author_no_publications;
            break;
        default:
            message = R.string.cannot_add_author_unknown;
            break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return message;
}

From source file:org.apache.lucene.replicator.http.HttpReplicator.java

@Override
public void release(String sessionID) throws IOException {
    String[] params = new String[] { ReplicationService.REPLICATE_SESSION_ID_PARAM, sessionID };
    final HttpResponse response = executeGET(ReplicationAction.RELEASE.name(), params);
    doAction(response, new Callable<Object>() {
        @Override/*  www  . ja v a2 s  .  c  o m*/
        public Object call() throws Exception {
            return null; // do not remove this call: as it is still validating for us!
        }
    });
}

From source file:co.cask.cdap.client.rest.RestStreamWriter.java

private ListenableFuture<Void> write(HttpEntity entity, Map<String, String> headers) {
    final HttpPost postRequest = new HttpPost(restClient.getBaseURL()
            .resolve(String.format("/%s/streams/%s", restClient.getVersion(), streamName)));

    for (Map.Entry<String, String> entry : headers.entrySet()) {
        postRequest.setHeader(streamName + "." + entry.getKey(), entry.getValue());
    }//from www  . j  ava 2s  .  co m

    postRequest.setEntity(entity);

    return pool.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            CloseableHttpResponse response = restClient.execute(postRequest);
            try {
                LOG.info("Write stream execute with response: " + response);
                RestClient.responseCodeAnalysis(response);
            } finally {
                response.close();
            }
            return null;
        }
    });
}

From source file:org.jboss.aerogear.test.api.extension.SenderStatisticsRequest.java

public void await(final int expectedTokenCount, Duration timeout) {

    final AtomicInteger found = new AtomicInteger();

    try {/*from w w w  . j  a v a2s  .  com*/
        Awaitility.await().atMost(timeout).until(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                SenderStatistics statistics = get();
                found.set(statistics.deviceTokens != null ? statistics.deviceTokens.size() : 0);
                return found.get() == expectedTokenCount;
            }
        });
    } catch (ConditionTimeoutException e) {
        System.err.println("SenderStats: Was expecting " + expectedTokenCount + " tokens but " + found.get()
                + " " + "were found.");
    }
}

From source file:com.microsoft.windowsazure.management.compute.ComputeManagementIntegrationTestBase.java

protected static void createManagementClient() throws Exception {
    Configuration config = createConfiguration();
    config.setProperty(ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER,
            new DefaultHttpRequestRetryHandler());

    managementClient = ManagementService.create(config);
    addClient((ServiceClient<?>) managementClient, new Callable<Void>() {
        @Override/*from  w w w . j a  va  2  s. c o  m*/
        public Void call() throws Exception {
            createManagementClient();
            return null;
        }
    });
}

From source file:de.blizzy.documentr.search.PageFinder.java

public SearchResult findPages(final String searchText, final int page, final Authentication authentication)
        throws ParseException, IOException, TimeoutException {

    Assert.hasLength(searchText);/*from w w w. j  a  va 2s .  c  o  m*/
    Assert.isTrue(page >= 1);
    Assert.notNull(authentication);

    IndexSearcher searcher = null;
    Future<SearchResult> findFuture = null;
    try {
        searcher = searcherManager.acquire();
        final IndexSearcher indexSearcher = searcher;

        Callable<SearchResult> findCallable = new Callable<SearchResult>() {
            @Override
            public SearchResult call() throws ParseException, IOException, TimeoutException {
                return findPages(searchText, page, authentication, indexSearcher);
            }
        };
        findFuture = taskExecutor.submit(findCallable);

        SearchTextSuggestion suggestion = getSearchTextSuggestion(searchText, authentication, indexSearcher);
        SearchResult result = findFuture.get(DocumentrConstants.INTERACTIVE_TIMEOUT, TimeUnit.SECONDS);
        result.setSuggestion(suggestion);
        return result;
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof ParseException) {
            throw (ParseException) cause;
        } else if (cause instanceof IOException) {
            throw (IOException) cause;
        } else if (cause instanceof TimeoutException) {
            throw (TimeoutException) cause;
        } else {
            throw Util.toRuntimeException(cause);
        }
    } finally {
        if (findFuture != null) {
            findFuture.cancel(false);
        }
        if (searcher != null) {
            searcherManager.release(searcher);
        }
    }
}

From source file:edu.mit.oidc.web.StatusEndpoint.java

@RequestMapping(value = "/" + URL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getStatus(Model m) {

    Map<String, Map<String, Object>> e = new HashMap<>();

    ExecutorService executor = Executors.newFixedThreadPool(3);

    try {//w  ww. j a  va2 s.co  m
        List<Future<Map<String, Map<String, Object>>>> results = executor
                .invokeAll(Arrays.asList(new Callable<Map<String, Map<String, Object>>>() {
                    // get database status
                    @Override
                    public Map<String, Map<String, Object>> call() throws Exception {
                        return getDbStatus();
                    }
                }, new Callable<Map<String, Map<String, Object>>>() {
                    // get kerberos status
                    @Override
                    public Map<String, Map<String, Object>> call() throws Exception {
                        return getKerbStatus();
                    }
                }, new Callable<Map<String, Map<String, Object>>>() {
                    // get LDAP status
                    @Override
                    public Map<String, Map<String, Object>> call() throws Exception {
                        return getLdapStatus();
                    }
                }), getTimeoutSeconds(), TimeUnit.SECONDS);

        // collect all the results and return them
        for (Future<Map<String, Map<String, Object>>> result : results) {
            e.putAll(result.get());
        }

        m.addAttribute(JsonEntityView.ENTITY, e);
        return JsonEntityView.VIEWNAME;
    } catch (InterruptedException | ExecutionException ex) {

        m.addAttribute(HttpCodeView.CODE, HttpStatus.INTERNAL_SERVER_ERROR);
        m.addAttribute(JsonErrorView.ERROR_MESSAGE, ex.getMessage());

        return JsonErrorView.VIEWNAME;
    }

}

From source file:com.microsoft.windowsazure.management.sql.RecoverDatabaseOperationsImpl.java

/**
* Issues a recovery request for an Azure SQL Database.
*
* @param sourceServerName Required. The name of the Azure SQL Database
* Server on which the database was hosted.
* @param parameters Required. Additional parameters for the Create Recover
* Database Operation request.//from  w w  w.  java 2 s  .  c o m
* @return Contains the response to the Create Recover Database Operation
* request.
*/
@Override
public Future<RecoverDatabaseOperationCreateResponse> createAsync(final String sourceServerName,
        final RecoverDatabaseOperationCreateParameters parameters) {
    return this.getClient().getExecutorService().submit(new Callable<RecoverDatabaseOperationCreateResponse>() {
        @Override
        public RecoverDatabaseOperationCreateResponse call() throws Exception {
            return create(sourceServerName, parameters);
        }
    });
}

From source file:com.amazonaws.devicefarm.DeviceFarmUploader.java

public Collection<Upload> batchUpload(final List<File> artifacts, final Project project,
        final UploadType uploadType) {

    List<Future<Upload>> futures = Lists.newArrayList();

    // Upload each artifact and create a future for it.
    for (final File file : artifacts) {
        futures.add(uploadExecutor.submit(new Callable<Upload>() {
            @Override/*from ww w  . j  av  a2s .  com*/
            public Upload call() throws Exception {
                return upload(file, project, uploadType);
            }
        }));
    }

    List<Upload> uploads = Lists.newArrayList();

    // Check future results and append the upload results to a list.
    for (Future<Upload> f : futures) {
        try {
            uploads.add(f.get());
        } catch (Exception e) {
            throw new DeviceFarmException(e);
        }
    }

    return uploads;
}