Search in sources :

Example 21 with CompletableFuture

use of java8.util.concurrent.CompletableFuture in project streamsupport by stefan-zobel.

the class CompletableFutureTest method testAcceptEither_actionFailed.

/**
 * acceptEither result completes exceptionally if action does
 */
public void testAcceptEither_actionFailed() {
    for (ExecutionMode m : ExecutionMode.values()) for (Integer v1 : new Integer[] { 1, null }) for (Integer v2 : new Integer[] { 2, null }) {
        final CompletableFuture<Integer> f = new CompletableFuture<>();
        final CompletableFuture<Integer> g = new CompletableFuture<>();
        final FailingConsumer[] rs = new FailingConsumer[6];
        for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
        final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
        final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
        f.complete(v1);
        final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
        final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
        checkCompletedWithWrappedException(h0, rs[0].ex);
        checkCompletedWithWrappedException(h1, rs[1].ex);
        checkCompletedWithWrappedException(h2, rs[2].ex);
        checkCompletedWithWrappedException(h3, rs[3].ex);
        for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
        g.complete(v2);
        // unspecified behavior - both source completions available
        final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
        final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
        checkCompletedWithWrappedException(h4, rs[4].ex);
        assertTrue(Objects.equals(v1, rs[4].value) || Objects.equals(v2, rs[4].value));
        checkCompletedWithWrappedException(h5, rs[5].ex);
        assertTrue(Objects.equals(v1, rs[5].value) || Objects.equals(v2, rs[5].value));
        checkCompletedNormally(f, v1);
        checkCompletedNormally(g, v2);
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CompletableFuture(java8.util.concurrent.CompletableFuture)

Example 22 with CompletableFuture

use of java8.util.concurrent.CompletableFuture in project streamsupport by stefan-zobel.

the class CompletableFutureTest method testRejectingExecutor.

/**
 * Test submissions to an executor that rejects all tasks.
 */
public void testRejectingExecutor() {
    for (Integer v : new Integer[] { 1, null }) {
        final CountingRejectingExecutor e = new CountingRejectingExecutor();
        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
        List<CompletableFuture<?>> futures = new ArrayList<>();
        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
        srcs.add(complete);
        srcs.add(incomplete);
        for (CompletableFuture<Integer> src : srcs) {
            List<CompletableFuture<?>> fs = new ArrayList<>();
            fs.add(src.thenRunAsync(() -> {
            }, e));
            fs.add(src.thenAcceptAsync(z -> {
            }, e));
            fs.add(src.thenApplyAsync(z -> z, e));
            fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
            fs.add(src.thenAcceptBothAsync(src, (x, y) -> {
            }, e));
            fs.add(src.runAfterBothAsync(src, () -> {
            }, e));
            fs.add(src.applyToEitherAsync(src, z -> z, e));
            fs.add(src.acceptEitherAsync(src, z -> {
            }, e));
            fs.add(src.runAfterEitherAsync(src, () -> {
            }, e));
            fs.add(src.thenComposeAsync(z -> null, e));
            fs.add(src.whenCompleteAsync((z, t) -> {
            }, e));
            fs.add(src.handleAsync((z, t) -> null, e));
            for (CompletableFuture<?> future : fs) {
                if (src.isDone())
                    checkCompletedWithWrappedException(future, e.ex);
                else
                    checkIncomplete(future);
            }
            futures.addAll(fs);
        }
        {
            List<CompletableFuture<?>> fs = new ArrayList<>();
            fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
            fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
            fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {
            }, e));
            fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {
            }, e));
            fs.add(complete.runAfterBothAsync(incomplete, () -> {
            }, e));
            fs.add(incomplete.runAfterBothAsync(complete, () -> {
            }, e));
            for (CompletableFuture<?> future : fs) checkIncomplete(future);
            futures.addAll(fs);
        }
        {
            List<CompletableFuture<?>> fs = new ArrayList<>();
            fs.add(complete.applyToEitherAsync(incomplete, z -> z, e));
            fs.add(incomplete.applyToEitherAsync(complete, z -> z, e));
            fs.add(complete.acceptEitherAsync(incomplete, z -> {
            }, e));
            fs.add(incomplete.acceptEitherAsync(complete, z -> {
            }, e));
            fs.add(complete.runAfterEitherAsync(incomplete, () -> {
            }, e));
            fs.add(incomplete.runAfterEitherAsync(complete, () -> {
            }, e));
            for (CompletableFuture<?> future : fs) checkCompletedWithWrappedException(future, e.ex);
            futures.addAll(fs);
        }
        incomplete.complete(v);
        for (CompletableFuture<?> future : futures) checkCompletedWithWrappedException(future, e.ex);
        assertEquals(futures.size(), e.count.get());
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Arrays(java.util.Arrays) Test(junit.framework.Test) TimeoutException(java.util.concurrent.TimeoutException) Callable(java.util.concurrent.Callable) CompletableFuture.completedFuture(java8.util.concurrent.CompletableFuture.completedFuture) Predicate(java8.util.function.Predicate) AtomicReference(java.util.concurrent.atomic.AtomicReference) CompletableFuture.failedFuture(java8.util.concurrent.CompletableFuture.failedFuture) Function(java8.util.function.Function) ArrayList(java.util.ArrayList) TestSuite(junit.framework.TestSuite) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) BiFunction(java8.util.function.BiFunction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Consumer(java8.util.function.Consumer) ForkJoinPool(java8.util.concurrent.ForkJoinPool) Method(java.lang.reflect.Method) CompletionStage(java8.util.concurrent.CompletionStage) Objects(java8.util.Objects) CancellationException(java.util.concurrent.CancellationException) Executor(java.util.concurrent.Executor) ForkJoinTask(java8.util.concurrent.ForkJoinTask) Set(java.util.Set) Collectors(java8.util.stream.Collectors) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) StreamSupport(java8.util.stream.StreamSupport) Supplier(java8.util.function.Supplier) ExecutionException(java.util.concurrent.ExecutionException) List(java.util.List) CompletableFuture(java8.util.concurrent.CompletableFuture) BiConsumer(java8.util.function.BiConsumer) RefStreams(java8.util.stream.RefStreams) Modifier(java.lang.reflect.Modifier) CompletionException(java8.util.concurrent.CompletionException) SECONDS(java.util.concurrent.TimeUnit.SECONDS) CompletableFuture(java8.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 23 with CompletableFuture

use of java8.util.concurrent.CompletableFuture in project streamsupport by stefan-zobel.

the class CompletableFutureTest method testAcceptEither_exceptionalCompletion2.

public void testAcceptEither_exceptionalCompletion2() {
    for (ExecutionMode m : ExecutionMode.values()) for (boolean fFirst : new boolean[] { true, false }) for (Integer v1 : new Integer[] { 1, null }) {
        final CompletableFuture<Integer> f = new CompletableFuture<>();
        final CompletableFuture<Integer> g = new CompletableFuture<>();
        final CFException ex = new CFException();
        final NoopConsumer[] rs = new NoopConsumer[6];
        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
        final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
        final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
        assertTrue(fFirst ? f.complete(v1) : g.completeExceptionally(ex));
        assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
        final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
        final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
        // unspecified behavior - both source completions available
        try {
            assertNull(h0.join());
            rs[0].assertValue(v1);
        } catch (CompletionException ok) {
            checkCompletedWithWrappedException(h0, ex);
            rs[0].assertNotInvoked();
        }
        try {
            assertNull(h1.join());
            rs[1].assertValue(v1);
        } catch (CompletionException ok) {
            checkCompletedWithWrappedException(h1, ex);
            rs[1].assertNotInvoked();
        }
        try {
            assertNull(h2.join());
            rs[2].assertValue(v1);
        } catch (CompletionException ok) {
            checkCompletedWithWrappedException(h2, ex);
            rs[2].assertNotInvoked();
        }
        try {
            assertNull(h3.join());
            rs[3].assertValue(v1);
        } catch (CompletionException ok) {
            checkCompletedWithWrappedException(h3, ex);
            rs[3].assertNotInvoked();
        }
        checkCompletedNormally(f, v1);
        checkCompletedExceptionally(g, ex);
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CompletableFuture(java8.util.concurrent.CompletableFuture) CompletionException(java8.util.concurrent.CompletionException)

Example 24 with CompletableFuture

use of java8.util.concurrent.CompletableFuture in project streamsupport by stefan-zobel.

the class CompletableFutureTest method testCompleteAsync.

/**
 * completeAsync completes with value of given supplier
 */
public void testCompleteAsync() {
    for (Integer v1 : new Integer[] { 1, null }) {
        CompletableFuture<Integer> f = new CompletableFuture<>();
        f.completeAsync(() -> v1);
        f.join();
        checkCompletedNormally(f, v1);
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CompletableFuture(java8.util.concurrent.CompletableFuture)

Example 25 with CompletableFuture

use of java8.util.concurrent.CompletableFuture in project opacclient by opacapp.

the class Open method parse_search.

protected SearchRequestResult parse_search(Document doc, int page) throws OpacErrorException {
    searchResultDoc = doc;
    if (doc.select("#Label1, span[id$=LblInfoMessage]").size() > 0) {
        String message = doc.select("#Label1, span[id$=LblInfoMessage]").text();
        if (message.contains("keine Treffer")) {
            return new SearchRequestResult(new ArrayList<SearchResult>(), 0, 1, page);
        } else {
            throw new OpacErrorException(message);
        }
    }
    int totalCount;
    if (doc.select("span[id$=TotalItemsLabel]").size() > 0) {
        totalCount = Integer.parseInt(doc.select("span[id$=TotalItemsLabel]").first().text().split("[ \\t\\xA0\\u1680\\u180e\\u2000-\\u200a\\u202f\\u205f\\u3000]")[0]);
    } else {
        throw new OpacErrorException(stringProvider.getString(StringProvider.UNKNOWN_ERROR));
    }
    Pattern idPattern = Pattern.compile("\\$(mdv|civ|dcv)(\\d+)\\$");
    Pattern weakIdPattern = Pattern.compile("(mdv|civ|dcv)(\\d+)[^\\d]");
    Elements elements = doc.select("div[id$=divMedium], div[id$=divComprehensiveItem], div[id$=divDependentCatalogue]");
    List<SearchResult> results = new ArrayList<>();
    int i = 0;
    List<CompletableFuture<Void>> futures = new ArrayList<>();
    for (Element element : elements) {
        final SearchResult result = new SearchResult();
        // Cover
        if (element.select("input[id$=mediumImage]").size() > 0) {
            result.setCover(element.select("input[id$=mediumImage]").first().attr("src"));
        } else if (element.select("img[id$=CoverView_Image]").size() > 0) {
            assignBestCover(result, getCoverUrlList(element.select("img[id$=CoverView_Image]").first()));
        }
        Element catalogueContent = element.select(".catalogueContent, .oclc-searchmodule-mediumview-content, .oclc-searchmodule-comprehensiveitemview-content, .oclc-searchmodule-dependentitemview-content").first();
        // Media Type
        if (catalogueContent.select("#spanMediaGrpIcon, .spanMediaGrpIcon").size() > 0) {
            String mediatype = catalogueContent.select("#spanMediaGrpIcon, .spanMediaGrpIcon").attr("class");
            if (mediatype.startsWith("itemtype ")) {
                mediatype = mediatype.substring("itemtype ".length());
            }
            SearchResult.MediaType defaulttype = defaulttypes.get(mediatype);
            if (defaulttype == null)
                defaulttype = SearchResult.MediaType.UNKNOWN;
            if (data.has("mediatypes")) {
                try {
                    result.setType(SearchResult.MediaType.valueOf(data.getJSONObject("mediatypes").getString(mediatype)));
                } catch (JSONException e) {
                    result.setType(defaulttype);
                }
            } else {
                result.setType(defaulttype);
            }
        } else {
            result.setType(SearchResult.MediaType.UNKNOWN);
        }
        // Text
        String title = catalogueContent.select("a[id$=LbtnShortDescriptionValue], a[id$=LbtnTitleValue]").text();
        String subtitle = catalogueContent.select("span[id$=LblSubTitleValue]").text();
        String author = catalogueContent.select("span[id$=LblAuthorValue]").text();
        String year = catalogueContent.select("span[id$=LblProductionYearValue]").text();
        String series = catalogueContent.select("span[id$=LblSeriesValue]").text();
        // Some libraries, such as Bern, have labels but no <span id="..Value"> tags
        int j = 0;
        for (Element div : catalogueContent.children()) {
            if (subtitle.equals("") && div.select("span").size() == 0 && j > 0 && j < 3) {
                subtitle = div.text().trim();
            }
            if (author.equals("") && div.select("span[id$=LblAuthor]").size() == 1) {
                author = div.text().trim();
                if (author.contains(":")) {
                    author = author.split(":")[1];
                }
            }
            if (year.equals("") && div.select("span[id$=LblProductionYear]").size() == 1) {
                year = div.text().trim();
                if (year.contains(":")) {
                    year = year.split(":")[1];
                }
            }
            j++;
        }
        StringBuilder text = new StringBuilder();
        text.append("<b>").append(title).append("</b>");
        if (!subtitle.equals(""))
            text.append("<br/>").append(subtitle);
        if (!author.equals(""))
            text.append("<br/>").append(author);
        if (!year.equals(""))
            text.append("<br/>").append(year);
        if (!series.equals(""))
            text.append("<br/>").append(series);
        result.setInnerhtml(text.toString());
        // ID
        Matcher matcher = idPattern.matcher(element.html());
        if (matcher.find()) {
            result.setId(matcher.group(2));
        } else {
            matcher = weakIdPattern.matcher(element.html());
            if (matcher.find()) {
                result.setId(matcher.group(2));
            }
        }
        // Availability
        if (result.getId() != null) {
            String url = opac_url + "/DesktopModules/OCLC.OPEN.PL.DNN.SearchModule/SearchService" + ".asmx/GetAvailability";
            String culture = element.select("input[name$=culture]").val();
            JSONObject data = new JSONObject();
            try {
                // Determine portalID value
                int portalId = 1;
                for (Element scripttag : doc.select("script")) {
                    String scr = scripttag.html();
                    if (scr.contains("LoadSharedCatalogueViewAvailabilityAsync")) {
                        Pattern portalIdPattern = Pattern.compile(".*LoadSharedCatalogueViewAvailabilityAsync\\([^,]*,[^,]*," + "[^0-9,]*([0-9]+)[^0-9,]*,.*\\).*");
                        Matcher portalIdMatcher = portalIdPattern.matcher(scr);
                        if (portalIdMatcher.find()) {
                            portalId = Integer.parseInt(portalIdMatcher.group(1));
                        }
                    }
                }
                data.put("portalId", portalId).put("mednr", result.getId()).put("culture", culture).put("requestCopyData", false).put("branchFilter", "");
                RequestBody entity = RequestBody.create(MEDIA_TYPE_JSON, data.toString());
                futures.add(asyncPost(url, entity, false).handle((response, throwable) -> {
                    if (throwable != null)
                        return null;
                    try {
                        JSONObject availabilityData = new JSONObject(response.body().string());
                        String isAvail = availabilityData.getJSONObject("d").getString("IsAvail");
                        switch(isAvail) {
                            case "true":
                                result.setStatus(SearchResult.Status.GREEN);
                                break;
                            case "false":
                                result.setStatus(SearchResult.Status.RED);
                                break;
                            case "digital":
                                result.setStatus(SearchResult.Status.UNKNOWN);
                                break;
                        }
                    } catch (JSONException | IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        result.setNr(i);
        results.add(result);
    }
    CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).join();
    return new SearchRequestResult(results, totalCount, page);
}
Also used : URL(java.net.URL) Detail(de.geeksfactory.opacclient.objects.Detail) HashMap(java.util.HashMap) Volume(de.geeksfactory.opacclient.objects.Volume) CoverHolder(de.geeksfactory.opacclient.objects.CoverHolder) TextSearchField(de.geeksfactory.opacclient.searchfields.TextSearchField) Headers(okhttp3.Headers) Filter(de.geeksfactory.opacclient.objects.Filter) CheckboxSearchField(de.geeksfactory.opacclient.searchfields.CheckboxSearchField) Part.create(okhttp3.MultipartBody.Part.create) ArrayList(java.util.ArrayList) StringProvider(de.geeksfactory.opacclient.i18n.StringProvider) RequestBody(okhttp3.RequestBody) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) Matcher(java.util.regex.Matcher) Locale(java.util.Locale) Element(org.jsoup.nodes.Element) Map(java.util.Map) HttpClientFactory(de.geeksfactory.opacclient.networking.HttpClientFactory) Account(de.geeksfactory.opacclient.objects.Account) MediaType(okhttp3.MediaType) DateTimeFormat(org.joda.time.format.DateTimeFormat) SearchResult(de.geeksfactory.opacclient.objects.SearchResult) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) MalformedURLException(java.net.MalformedURLException) BarcodeSearchField(de.geeksfactory.opacclient.searchfields.BarcodeSearchField) Set(java.util.Set) SearchRequestResult(de.geeksfactory.opacclient.objects.SearchRequestResult) IOException(java.io.IOException) SearchQuery(de.geeksfactory.opacclient.searchfields.SearchQuery) DropdownSearchField(de.geeksfactory.opacclient.searchfields.DropdownSearchField) Library(de.geeksfactory.opacclient.objects.Library) List(java.util.List) CompletableFuture(java8.util.concurrent.CompletableFuture) DetailedItem(de.geeksfactory.opacclient.objects.DetailedItem) MultipartBody(okhttp3.MultipartBody) Document(org.jsoup.nodes.Document) NotReachableException(de.geeksfactory.opacclient.networking.NotReachableException) SearchField(de.geeksfactory.opacclient.searchfields.SearchField) Jsoup(org.jsoup.Jsoup) Elements(org.jsoup.select.Elements) Pattern(java.util.regex.Pattern) AccountData(de.geeksfactory.opacclient.objects.AccountData) JSONArray(org.json.JSONArray) Copy(de.geeksfactory.opacclient.objects.Copy) FormElement(org.jsoup.nodes.FormElement) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Element(org.jsoup.nodes.Element) FormElement(org.jsoup.nodes.FormElement) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) SearchResult(de.geeksfactory.opacclient.objects.SearchResult) Elements(org.jsoup.select.Elements) CompletableFuture(java8.util.concurrent.CompletableFuture) SearchRequestResult(de.geeksfactory.opacclient.objects.SearchRequestResult) JSONObject(org.json.JSONObject) RequestBody(okhttp3.RequestBody)

Aggregations

CompletableFuture (java8.util.concurrent.CompletableFuture)44 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)41 CompletionException (java8.util.concurrent.CompletionException)11 CancellationException (java.util.concurrent.CancellationException)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Set (java.util.Set)4 ExecutionException (java.util.concurrent.ExecutionException)4 Executor (java.util.concurrent.Executor)4 MILLISECONDS (java.util.concurrent.TimeUnit.MILLISECONDS)4 SECONDS (java.util.concurrent.TimeUnit.SECONDS)4 CompletionStage (java8.util.concurrent.CompletionStage)4 Supplier (java8.util.function.Supplier)4 Method (java.lang.reflect.Method)3 Modifier (java.lang.reflect.Modifier)3 Arrays (java.util.Arrays)3 Callable (java.util.concurrent.Callable)3 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)3 TimeoutException (java.util.concurrent.TimeoutException)3