List of usage examples for org.apache.commons.lang3.tuple Pair of
public static <L, R> Pair<L, R> of(final L left, final R right)
Obtains an immutable pair of from two objects inferring the generic types.
This factory allows the pair to be created using inference to obtain the generic types.
From source file:net.malisis.doors.gui.VanishingDiamondGui.java
@Override public void construct() { UIWindow window = new UIWindow(this, "tile.vanishing_block_diamond.name", 200, 220); window.add(new UILabel(this, "Direction").setPosition(0, 20)); window.add(new UILabel(this, "Delay").setPosition(55, 20)); window.add(new UILabel(this, "Inversed").setPosition(90, 20)); int i = 0;/* ww w. j a v a2 s . c om*/ for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { DirectionState state = tileEntity.getDirectionState(dir); int y = i * 14 + 30; UICheckBox cb = new UICheckBox(this, dir.name()); cb.setPosition(2, y).setChecked(state.shouldPropagate).register(this); cb.attachData(Pair.of(dir, DataType.PROPAGATION)); UITextField textField = new UITextField(this, "" + state.delay).setSize(27, 0).setPosition(55, y) .setDisabled(!state.shouldPropagate).register(this); textField.attachData(Pair.of(dir, DataType.DELAY)); UICheckBox invCb = new UICheckBox(this).setPosition(105, y).setDisabled(!state.shouldPropagate) .setChecked(state.inversed).register(this); invCb.attachData(Pair.of(dir, DataType.INVERSED)); window.add(cb); window.add(textField); window.add(invCb); configs.put(dir, new UIComponent[] { cb, textField, invCb }); i++; } UIContainer cont = new UIContainer<UIContainer>(this, 50, 60).setPosition(0, 40, Anchor.RIGHT); duration = new UITextField(this, null).setSize(30, 0).setPosition(0, 10, Anchor.CENTER).register(this); duration.attachData(Pair.of(null, DataType.DURATION)); cont.add(new UILabel(this, "Duration").setPosition(0, 0, Anchor.CENTER)); cont.add(duration); UIInventory inv = new UIInventory(this, inventoryContainer.getInventory(1)); inv.setPosition(0, 40, Anchor.CENTER); cont.add(new UILabel(this, "Block").setPosition(0, 30, Anchor.CENTER)); cont.add(inv); window.add(cont); UIPlayerInventory playerInv = new UIPlayerInventory(this, inventoryContainer.getPlayerInventory()); window.add(playerInv); addToScreen(window); TileEntityUtils.linkTileEntityToGui(tileEntity, this); }
From source file:net.lldp.checksims.algorithm.smithwaterman.SmithWatermanTest.java
private AlgorithmResults runSmithWaterman(Submission a, Submission b, TokenType at, TokenType bt) throws TokenTypeMismatchException, InternalAlgorithmError { if (bt != at) { throw new TokenTypeMismatchException("Tokenization of " + a + " and " + b + " do not match"); }// w ww . j a v a2 s .com return instance.detectSimilarity(Pair.of(a, b), new SubmissionTokenizer(Tokenizer.getTokenizer(at)).fromSubmission(a), new SubmissionTokenizer(Tokenizer.getTokenizer(bt)).fromSubmission(b)); }
From source file:mtsar.processors.task.InverseCountAllocatorTest.java
@Test public void testEqualAllocation() { when(countDAO.getCountsSQL(anyString())).thenReturn(Arrays.asList(Pair.of(1, 0), Pair.of(2, 0))); final TaskAllocator allocator = new InverseCountAllocator(stage, dbi, taskDAO, answerDAO); final Optional<TaskAllocation> optional = allocator.allocate(worker); assertThat(optional.isPresent()).isTrue(); final TaskAllocation allocation = optional.get(); assertThat(allocation.getTask().get().getId()).isBetween(1, 2); assertThat(allocation.getTaskRemaining()).isEqualTo(2); assertThat(allocation.getTaskCount()).isEqualTo(2); }
From source file:com.coveo.spillway.storage.AsyncLimitUsageStorage.java
public void sendAndCacheRequests(Collection<AddAndGetRequest> requests) { try {//from w w w .j a va 2 s. c o m Map<LimitKey, Integer> responses = wrappedLimitUsageStorage.addAndGet(requests); // Flatten all requests into a single list of overrides. Map<Pair<LimitKey, Instant>, Integer> rawOverrides = new HashMap<>(); for (AddAndGetRequest request : requests) { LimitKey limitEntry = LimitKey.fromRequest(request); Instant expirationDate = request.getBucket().plus(request.getExpiration()); rawOverrides.merge(Pair.of(limitEntry, expirationDate), responses.get(limitEntry), Integer::sum); } List<OverrideKeyRequest> overrides = rawOverrides.entrySet().stream().map( kvp -> new OverrideKeyRequest(kvp.getKey().getLeft(), kvp.getKey().getRight(), kvp.getValue())) .collect(Collectors.toList()); cache.overrideKeys(overrides); } catch (RuntimeException ex) { logger.warn("Failed to send and cache requests.", ex); } }
From source file:com.blacklocus.qs.QueueReader.java
@Override public void go() throws Exception { for (Collection<Q> queueItems : queueItemProvider) { try {/*from w w w. jav a2 s . com*/ if (queueItems.size() > 0) { for (final Q queueItem : queueItems) { handler.withFuture(queueItem, executor.submit(new Callable<Pair<Q, R>>() { public Pair<Q, R> call() throws Exception { T converted = null; R result = null; try { converted = handler.convert(queueItem); result = handler.process(converted); handler.onSuccess(queueItem, converted, result); return Pair.of(queueItem, result); } catch (Throwable t) { LOG.error("An error occurred while processing item {}", queueItem, t); handler.onError(queueItem, converted, t); throw new RuntimeException(t); } finally { handler.onComplete(queueItem, converted, result); } } })); } } else { LOG.debug("No items available... sleeping for {} ms", sleepMs); Thread.sleep(sleepMs); } } catch (InterruptedException e) { LOG.error("Reader thread interrupted", e); Thread.currentThread().interrupt(); } catch (Throwable t) { LOG.error("Runtime error in reader thread", t); } } }
From source file:com.baifendian.swordfish.common.hadoop.YarnRestClient.java
/** * ??// w w w . j av a 2s . c o m * * @param appId * @return ? null, ?? * @throws JSONException * @throws IOException */ public FlowStatus getApplicationStatus(String appId) throws JSONException, IOException { if (StringUtils.isEmpty(appId)) { return null; } String url = ConfigurationUtil.getApplicationStatusAddress(appId); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(url); ResponseHandler<Pair<Integer, String>> rh = response -> { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { if (statusLine.getStatusCode() == 404 || statusLine.getStatusCode() == 330) { return null; } throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException("Response contains no content"); } String content = EntityUtils.toString(entity); JSONObject o = null; try { o = new JSONObject(content); } catch (JSONException e) { throw new HttpResponseException(statusLine.getStatusCode(), content); } if (!o.has("app") || o.isNull("app")) { throw new RuntimeException("Response content not valid " + content); } try { return Pair.of(statusLine.getStatusCode(), o.getJSONObject("app").getString("finalStatus")); } catch (JSONException e) { throw new HttpResponseException(statusLine.getStatusCode(), content); } }; Pair<Integer, String> pair = httpclient.execute(httpget, rh); if (pair == null) { return null; } switch (pair.getRight()) { case "FAILED": return FlowStatus.FAILED; case "KILLED": return FlowStatus.KILL; case "SUCCEEDED": return FlowStatus.SUCCESS; case "NEW": case "NEW_SAVING": case "SUBMITTED": case "ACCEPTED": return FlowStatus.INIT; case "RUNNING": default: return FlowStatus.RUNNING; } }
From source file:com.github.steveash.guavate.GuavateTest.java
@Test public void test_zip_secondLonger() { Stream<String> base1 = Stream.of("a", "b"); Stream<Integer> base2 = Stream.of(1, 2, 3); List<Pair<String, Integer>> test = Guavate.zip(base1, base2).collect(Collectors.toList()); assertEquals(test, ImmutableList.of(Pair.of("a", 1), Pair.of("b", 2))); }
From source file:com.teambr.modularsystems.core.client.models.BakedCoreExpansion.java
@Override public Pair<? extends IBakedModel, Matrix4f> handlePerspective( ItemCameraTransforms.TransformType cameraTransformType) { return Pair.of(this, transforms.get(cameraTransformType).getMatrix()); }
From source file:alfio.manager.PaymentManager.java
/** * This method processes the pending payment using the configured payment gateway (at the time of writing, only STRIPE) * and returns a PaymentResult.//from w w w . j a v a2 s.com * In order to preserve the consistency of the payment, when a non-gateway Exception is thrown, it rethrows an IllegalStateException * * @param reservationId * @param gatewayToken * @param price * @param event * @param email * @param customerName * @param billingAddress * @return PaymentResult * @throws java.lang.IllegalStateException if there is an error after charging the credit card */ PaymentResult processStripePayment(String reservationId, String gatewayToken, int price, Event event, String email, CustomerName customerName, String billingAddress) { try { final Optional<Charge> optionalCharge = stripeManager.chargeCreditCard(gatewayToken, price, event, reservationId, email, customerName.getFullName(), billingAddress); return optionalCharge.map(charge -> { log.info("transaction {} paid: {}", reservationId, charge.getPaid()); Pair<Long, Long> fees = Optional.ofNullable(charge.getBalanceTransactionObject()).map(bt -> { List<Fee> feeDetails = bt.getFeeDetails(); return Pair.of( Optional.ofNullable(StripeManager.getFeeAmount(feeDetails, "application_fee")) .map(Long::parseLong).orElse(0L), Optional.ofNullable(StripeManager.getFeeAmount(feeDetails, "stripe_fee")) .map(Long::parseLong).orElse(0L)); }).orElse(null); transactionRepository.insert(charge.getId(), null, reservationId, ZonedDateTime.now(), price, event.getCurrency(), charge.getDescription(), PaymentProxy.STRIPE.name(), fees != null ? fees.getLeft() : 0L, fees != null ? fees.getRight() : 0L); return PaymentResult.successful(charge.getId()); }).orElseGet(() -> PaymentResult.unsuccessful("error.STEP2_UNABLE_TO_TRANSITION")); } catch (Exception e) { if (e instanceof StripeException) { return PaymentResult.unsuccessful(stripeManager.handleException((StripeException) e)); } throw new IllegalStateException(e); } }
From source file:io.knotx.mocks.adapter.MockActionAdapterHandler.java
private Pair<Optional<String>, JsonObject> getErrorResponse() { return Pair.of(Optional.empty(), new JsonObject().put("clientResponse", errorResponse().getResponse().toMetadataJson())); }