List of usage examples for org.apache.commons.lang3.tuple Pair getLeft
public abstract L getLeft();
Gets the left element from this pair.
When treated as a key-value pair, this is the key.
From source file:edu.uci.ics.pregelix.runtime.simpleagg.AccumulatingAggregatorFactory.java
@SuppressWarnings("unchecked") @Override//w w w .j av a 2 s . co m public IAggregatorDescriptor createAggregator(IHyracksTaskContext ctx, RecordDescriptor inRecordDesc, RecordDescriptor outRecordDescriptor, int[] aggKeys, int[] partialKeys) throws HyracksDataException { return new IAggregatorDescriptor() { private FrameTupleReference ftr = new FrameTupleReference(); @Override public void init(ArrayTupleBuilder tupleBuilder, IFrameTupleAccessor accessor, int tIndex, AggregateState state) throws HyracksDataException { Pair<ArrayBackedValueStorage[], IAggregateFunction[]> aggState = (Pair<ArrayBackedValueStorage[], IAggregateFunction[]>) state.state; ArrayBackedValueStorage[] aggOutput = aggState.getLeft(); IAggregateFunction[] agg = aggState.getRight(); // initialize aggregate functions for (int i = 0; i < agg.length; i++) { aggOutput[i].reset(); try { agg[i].init(); } catch (Exception e) { throw new HyracksDataException(e); } } ftr.reset(accessor, tIndex); for (int i = 0; i < agg.length; i++) { try { agg[i].step(ftr); } catch (Exception e) { throw new HyracksDataException(e); } } } @Override public void aggregate(IFrameTupleAccessor accessor, int tIndex, IFrameTupleAccessor stateAccessor, int stateTupleIndex, AggregateState state) throws HyracksDataException { Pair<ArrayBackedValueStorage[], IAggregateFunction[]> aggState = (Pair<ArrayBackedValueStorage[], IAggregateFunction[]>) state.state; IAggregateFunction[] agg = aggState.getRight(); ftr.reset(accessor, tIndex); for (int i = 0; i < agg.length; i++) { try { agg[i].step(ftr); } catch (Exception e) { throw new HyracksDataException(e); } } } @Override public void outputFinalResult(ArrayTupleBuilder tupleBuilder, IFrameTupleAccessor accessor, int tIndex, AggregateState state) throws HyracksDataException { Pair<ArrayBackedValueStorage[], IAggregateFunction[]> aggState = (Pair<ArrayBackedValueStorage[], IAggregateFunction[]>) state.state; ArrayBackedValueStorage[] aggOutput = aggState.getLeft(); IAggregateFunction[] agg = aggState.getRight(); for (int i = 0; i < agg.length; i++) { try { agg[i].finish(); tupleBuilder.addField(aggOutput[i].getByteArray(), aggOutput[i].getStartOffset(), aggOutput[i].getLength()); } catch (Exception e) { throw new HyracksDataException(e); } } } @Override public AggregateState createAggregateStates() { IAggregateFunction[] agg = new IAggregateFunction[aggFactories.length]; ArrayBackedValueStorage[] aggOutput = new ArrayBackedValueStorage[aggFactories.length]; for (int i = 0; i < agg.length; i++) { aggOutput[i] = new ArrayBackedValueStorage(); try { agg[i] = aggFactories[i].createAggregateFunction(aggOutput[i]); } catch (Exception e) { throw new IllegalStateException(e); } } return new AggregateState(Pair.of(aggOutput, agg)); } @Override public void reset() { } @Override public void outputPartialResult(ArrayTupleBuilder tupleBuilder, IFrameTupleAccessor accessor, int tIndex, AggregateState state) throws HyracksDataException { throw new IllegalStateException("this method should not be called"); } @Override public void close() { } }; }
From source file:alfio.controller.api.admin.EmailMessageApiController.java
@RequestMapping("/") public PageAndContent<List<LightweightEmailMessage>> loadEmailMessages( @PathVariable("eventName") String eventName, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "search", required = false) String search, Principal principal) { Event event = eventManager.getSingleEvent(eventName, principal.getName()); ZoneId zoneId = event.getZoneId(); Pair<Integer, List<LightweightMailMessage>> found = notificationManager .loadAllMessagesForEvent(event.getId(), page, search); return new PageAndContent<>(found.getRight().stream().map(m -> new LightweightEmailMessage(m, zoneId, true)) .collect(Collectors.toList()), found.getLeft()); }
From source file:com.linkedin.pinot.integration.tests.BaseClusterIntegrationTest.java
public static Future<Map<File, File>> buildSegmentsFromAvro(final List<File> avroFiles, Executor executor, int baseSegmentIndex, final File baseDirectory, final File segmentTarDir, final String tableName, final boolean createStarTreeIndex, final com.linkedin.pinot.common.data.Schema inputPinotSchema) { int segmentCount = avroFiles.size(); LOGGER.info("Building " + segmentCount + " segments in parallel"); List<ListenableFutureTask<Pair<File, File>>> futureTasks = new ArrayList<ListenableFutureTask<Pair<File, File>>>(); for (int i = 1; i <= segmentCount; ++i) { final int segmentIndex = i - 1; final int segmentNumber = i + baseSegmentIndex; final ListenableFutureTask<Pair<File, File>> buildSegmentFutureTask = ListenableFutureTask .<Pair<File, File>>create(new Callable<Pair<File, File>>() { @Override//from w ww .j a v a 2 s .c o m public Pair<File, File> call() throws Exception { try { // Build segment LOGGER.info("Starting to build segment " + segmentNumber); File outputDir = new File(baseDirectory, "segment-" + segmentNumber); final File inputAvroFile = avroFiles.get(segmentIndex); final SegmentGeneratorConfig genConfig = SegmentTestUtils .getSegmentGenSpecWithSchemAndProjectedColumns(inputAvroFile, outputDir, TimeUnit.DAYS, tableName, inputPinotSchema); if (inputPinotSchema != null) { genConfig.setSchema(inputPinotSchema); } // jfim: We add a space and a special character to do a regression test for PINOT-3296 Segments with spaces // in their filename don't work properly genConfig.setSegmentNamePostfix(Integer.toString(segmentNumber) + " %"); genConfig.setEnableStarTreeIndex(createStarTreeIndex); // Enable off heap star tree format in the integration test. StarTreeIndexSpec starTreeIndexSpec = null; if (createStarTreeIndex) { starTreeIndexSpec = new StarTreeIndexSpec(); starTreeIndexSpec.setEnableOffHeapFormat(true); } genConfig.setStarTreeIndexSpec(starTreeIndexSpec); final SegmentIndexCreationDriver driver = SegmentCreationDriverFactory.get(null); driver.init(genConfig); driver.build(); // Tar segment String segmentName = outputDir.list()[0]; final String tarGzPath = TarGzCompressionUtils.createTarGzOfDirectory( outputDir.getAbsolutePath() + "/" + segmentName, new File(segmentTarDir, segmentName).getAbsolutePath()); LOGGER.info("Completed segment " + segmentNumber + " : " + segmentName + " from file " + inputAvroFile.getName()); return new ImmutablePair<File, File>(inputAvroFile, new File(tarGzPath)); } catch (Exception e) { LOGGER.error("Exception while building segment input: {} output {} ", avroFiles.get(segmentIndex), "segment-" + segmentNumber); throw new RuntimeException(e); } } }); futureTasks.add(buildSegmentFutureTask); executor.execute(buildSegmentFutureTask); } ListenableFuture<List<Pair<File, File>>> pairListFuture = Futures.allAsList(futureTasks); return Futures.transform(pairListFuture, new AsyncFunction<List<Pair<File, File>>, Map<File, File>>() { @Override public ListenableFuture<Map<File, File>> apply(List<Pair<File, File>> input) throws Exception { Map<File, File> avroToSegmentMap = new HashMap<File, File>(); for (Pair<File, File> avroToSegmentPair : input) { avroToSegmentMap.put(avroToSegmentPair.getLeft(), avroToSegmentPair.getRight()); } return Futures.immediateFuture(avroToSegmentMap); } }); }
From source file:alfio.manager.PaymentManager.java
PaymentResult processPayPalPayment(String reservationId, String token, String payerId, int price, Event event) { try {/*from www . ja v a2 s .c om*/ Pair<String, String> captureAndPaymentId = paypalManager.commitPayment(reservationId, token, payerId, event); String captureId = captureAndPaymentId.getLeft(); String paymentId = captureAndPaymentId.getRight(); Supplier<String> feeSupplier = () -> FeeCalculator.getCalculator(event, configurationManager) .apply(ticketRepository.countTicketsInReservation(reservationId), (long) price) .map(String::valueOf).orElse("0"); Pair<Long, Long> fees = paypalManager.getInfo(paymentId, captureId, event, feeSupplier).map(i -> { Long platformFee = Optional.ofNullable(i.getPlatformFee()).map(Long::parseLong).orElse(0L); Long gatewayFee = Optional.ofNullable(i.getFee()).map(Long::parseLong).orElse(0L); return Pair.of(platformFee, gatewayFee); }).orElseGet(() -> Pair.of(0L, 0L)); transactionRepository.insert(captureId, paymentId, reservationId, ZonedDateTime.now(), price, event.getCurrency(), "Paypal confirmation", PaymentProxy.PAYPAL.name(), fees.getLeft(), fees.getRight()); return PaymentResult.successful(captureId); } catch (Exception e) { log.warn("errow while processing paypal payment: " + e.getMessage(), e); if (e instanceof PayPalRESTException) { return PaymentResult.unsuccessful(ErrorsCode.STEP_2_PAYPAL_UNEXPECTED); } else if (e instanceof PaypalManager.HandledPaypalErrorException) { return PaymentResult.unsuccessful(e.getMessage()); } throw new IllegalStateException(e); } }
From source file:com.act.lcms.plotter.WriteAndPlotMS1Results.java
private List<String> writeFeedMS1Values(List<Pair<Double, List<XZ>>> ms1s, Double maxIntensity, OutputStream os) throws IOException { // Write data output to outfile PrintStream out = new PrintStream(os); List<String> plotID = new ArrayList<>(ms1s.size()); for (Pair<Double, List<XZ>> ms1ForFeed : ms1s) { Double feedingConcentration = ms1ForFeed.getLeft(); List<XZ> ms1 = ms1ForFeed.getRight(); plotID.add(String.format("concentration: %5e", feedingConcentration)); // print out the spectra to outDATA for (XZ xz : ms1) { out.format("%.4f\t%.4f\n", xz.getTime(), xz.getIntensity()); out.flush();/*w w w. java2 s . c o m*/ } // delimit this dataset from the rest out.print("\n\n"); } return plotID; }
From source file:com.spartasystems.holdmail.integration.MessageControllerIntegrationTest.java
@Test public void shouldAcceptAndListMailsForRandomRecipients() throws Exception { int countBeforeStart = get(ENDPOINT_MESSAGES).then().extract().path("messages.size()"); final int numMailsToSend = 5; List<Pair<String, String>> expectedMessages = sendMailToRandomRecipients(numMailsToSend); ValidatableMockMvcResponse resp = get(ENDPOINT_MESSAGES).then().statusCode(200).body("messages.size()", equalTo(countBeforeStart + numMailsToSend)); for (int i = 0; i < numMailsToSend; i++) { // mails are listed most recently accepted first Pair<String, String> recipAndSubject = expectedMessages.get(numMailsToSend - i - 1); resp.body("messages.get(" + i + ").senderEmail", equalTo(FROM_EMAIL)) .body("messages.get(" + i + ").recipients", equalTo(recipAndSubject.getLeft())) .body("messages.get(" + i + ").subject", equalTo(recipAndSubject.getRight())); }//from w w w . jav a 2 s . co m }
From source file:it.polimi.diceH2020.SPACE4CloudWS.solvers.PerformanceSolver.java
public Optional<Double> evaluate(@NonNull SolutionPerJob solPerJob) { Optional<Double> returnValue = Optional.of(solPerJob.getThroughput()); if (solPerJob.getChanged()) { try {//from ww w. java 2 s.c om putRemoteSubDirectory(solPerJob); Pair<List<File>, List<File>> pFiles = createWorkingFiles(solPerJob); String jobID = solPerJob.getId(); String directory = retrieveRemoteSubDirectory(solPerJob); Pair<Double, Boolean> result = run(pFiles, "class" + jobID, directory); delete(pFiles.getLeft()); if (connSettings.isCleanRemote()) cleanRemoteSubDirectory(directory); solPerJob.setError(result.getRight()); returnValue = Optional.of(result.getLeft()); removeRemoteSubDirectory(solPerJob); } catch (Exception e) { logger.error("Error in SPJ evaluation", e); solPerJob.setError(Boolean.TRUE); returnValue = Optional.empty(); } } return returnValue; }
From source file:com.sk89q.craftbook.sponge.mechanics.variable.Variables.java
public String parseVariables(String line, @Nullable Player player) { for (Pair<String, String> possibleVariable : getPossibleVariables(line)) { String namespace = possibleVariable.getLeft(); String name = possibleVariable.getRight(); boolean explicit = true; if (namespace == null) { if (defaultToGlobal.getValue()) { namespace = GLOBAL_NAMESPACE; if (player != null && getVariable(player.getUniqueId().toString(), name) != null) { namespace = player.getUniqueId().toString(); }/* ww w.java 2 s . c o m*/ } else { if (player != null) { namespace = player.getUniqueId().toString(); } else { continue; } } explicit = false; } String variable = getVariable(namespace, name); if (variable != null) { String variableText = (explicit ? (namespace + '|') : "") + name; line = line.replace('%' + variableText + '%', getVariable(namespace, name)); } } return line; }
From source file:com.intuit.wasabi.repository.cassandra.impl.CassandraPagesRepository.java
@Override public Map<Pair<Application.Name, Page.Name>, List<PageExperiment>> getExperimentsWithoutLabels( Collection<Pair<Application.Name, Page.Name>> appAndPagePairs) { logger.debug("getExperimentsWithoutLabels {}", appAndPagePairs); Map<Pair<Application.Name, Page.Name>, List<PageExperiment>> resultMap = new HashMap<>(); try {/*from ww w . j a v a 2 s .com*/ Map<Pair<Application.Name, Page.Name>, ListenableFuture<Result<PageExperimentByAppNamePage>>> expFutureMap = new HashMap<>(); appAndPagePairs.forEach(pair -> { expFutureMap.put(pair, pageExperimentIndexAccessor.asyncSelectBy(pair.getLeft().toString(), pair.getRight().toString())); }); for (Pair<Application.Name, Page.Name> pair : expFutureMap.keySet()) { ListenableFuture<Result<PageExperimentByAppNamePage>> expFuture = expFutureMap.get(pair); Stream<PageExperimentByAppNamePage> resultList = StreamSupport.stream( Spliterators.spliteratorUnknownSize( UninterruptibleUtil.getUninterruptibly(expFuture).iterator(), Spliterator.ORDERED), false); List<PageExperiment> pageExperimentsList = resultList.map(t -> { PageExperiment.Builder builder = new PageExperiment.Builder( Experiment.ID.valueOf(t.getExperimentId()), null, t.isAssign()); return builder.build(); }).collect(Collectors.toList()); resultMap.put(pair, pageExperimentsList); } } catch (Exception e) { logger.error("getExperimentsWithoutLabels for {} failed", appAndPagePairs, e); throw new RepositoryException("Could not getExperimentsWithoutLabels", e); } logger.debug("Returning PageExperimentList map {}", resultMap); return resultMap; }
From source file:com.formkiq.core.util.StringsTest.java
/** * testExtractLabelAndValue03().//from www. ja v a2 s .c om */ @Test public void testExtractLabelAndValue03() { // given String s = null; // when Pair<String, String> results = Strings.extractLabelAndValue(s); // then assertEquals("", results.getLeft()); assertEquals("", results.getRight()); }