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);
}
}
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());
}
}
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);
}
}
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);
}
}
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);
}
Aggregations