Example usage for org.apache.commons.lang3.tuple Pair getRight

List of usage examples for org.apache.commons.lang3.tuple Pair getRight

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getRight.

Prototype

public abstract R getRight();

Source Link

Document

Gets the right element from this pair.

When treated as a key-value pair, this is the value.

Usage

From source file:edu.uci.ics.hyracks.api.rewriter.runtime.SuperActivityOperatorNodePushable.java

public void init() throws HyracksDataException {
    Map<ActivityId, IOperatorNodePushable> startOperatorNodePushables = new HashMap<ActivityId, IOperatorNodePushable>();
    Queue<Pair<Pair<IActivity, Integer>, Pair<IActivity, Integer>>> childQueue = new LinkedList<Pair<Pair<IActivity, Integer>, Pair<IActivity, Integer>>>();
    List<IConnectorDescriptor> outputConnectors = null;

    /**//from w ww  . j ava  2  s. c  o m
     * Set up the source operators
     */
    for (Entry<ActivityId, IActivity> entry : startActivities.entrySet()) {
        IOperatorNodePushable opPushable = entry.getValue().createPushRuntime(ctx, recordDescProvider,
                partition, nPartitions);
        startOperatorNodePushables.put(entry.getKey(), opPushable);
        operatprNodePushablesBFSOrder.add(opPushable);
        operatorNodePushables.put(entry.getKey(), opPushable);
        inputArity += opPushable.getInputArity();
        outputConnectors = parent.getActivityOutputMap().get(entry.getKey());
        if (outputConnectors != null) {
            for (IConnectorDescriptor conn : outputConnectors) {
                childQueue.add(parent.getConnectorActivityMap().get(conn.getConnectorId()));
            }
        }
    }

    /**
     * Using BFS (breadth-first search) to construct to runtime execution
     * DAG;
     */
    while (childQueue.size() > 0) {
        /**
         * expend the executing activities further to the downstream
         */
        if (outputConnectors != null && outputConnectors.size() > 0) {
            for (IConnectorDescriptor conn : outputConnectors) {
                if (conn != null) {
                    childQueue.add(parent.getConnectorActivityMap().get(conn.getConnectorId()));
                }
            }
        }

        /**
         * construct the source to destination information
         */
        Pair<Pair<IActivity, Integer>, Pair<IActivity, Integer>> channel = childQueue.poll();
        ActivityId sourceId = channel.getLeft().getLeft().getActivityId();
        int outputChannel = channel.getLeft().getRight();
        ActivityId destId = channel.getRight().getLeft().getActivityId();
        int inputChannel = channel.getRight().getRight();
        IOperatorNodePushable sourceOp = operatorNodePushables.get(sourceId);
        IOperatorNodePushable destOp = operatorNodePushables.get(destId);
        if (destOp == null) {
            destOp = channel.getRight().getLeft().createPushRuntime(ctx, recordDescProvider, partition,
                    nPartitions);
            operatprNodePushablesBFSOrder.add(destOp);
            operatorNodePushables.put(destId, destOp);
        }

        /**
         * construct the dataflow connection from a producer to a consumer
         */
        sourceOp.setOutputFrameWriter(outputChannel, destOp.getInputFrameWriter(inputChannel),
                recordDescProvider.getInputRecordDescriptor(destId, inputChannel));

        /**
         * traverse to the child of the current activity
         */
        outputConnectors = parent.getActivityOutputMap().get(destId);
    }
}

From source file:com.mtbs3d.minecrift.control.GuiScreenNaviator.java

public void down() {
    if (onSlot && slot != null && slotIndex != slot.publicGetSize() - 1) {
        slotIndex++;// www . ja  v  a 2 s. com
        int slotY = slot.select(slotIndex, false);
        curPoint = Pair.of(screen.width / 2, slotY);
        mouseto();
        return;
    }
    onSlot = false;
    parsePoints();
    if (curPoint != null) {
        Pair<Integer, Integer> nextBest = null;
        for (Pair<Integer, Integer> point : points) {
            if (point.getRight() > curPoint.getRight()) {
                if (nextBest == null || dist(nextBest, curPoint, AXIS_PREFERENCE, 1) > dist(point, curPoint,
                        AXIS_PREFERENCE, 1))
                    nextBest = point;
            }
        }
        if (nextBest != null) {
            mc.currentScreen.mouseGuiDrag(curPoint.getLeft(), curPoint.getRight());
            curPoint = nextBest;
            mouseto();
        }
    }
}

From source file:at.gridtec.lambda4j.consumer.bi.ThrowableBiConsumer.java

/**
 * Applies this consumer to the given tuple.
 *
 * @param tuple The tuple to be applied to the consumer
 * @throws NullPointerException If given argument is {@code null}
 * @throws X Any throwable from this consumers action
 * @see org.apache.commons.lang3.tuple.Pair
 *//*from ww  w.  j a  v a  2  s .co m*/
default void acceptThrows(@Nonnull Pair<T, U> tuple) throws X {
    Objects.requireNonNull(tuple);
    acceptThrows(tuple.getLeft(), tuple.getRight());
}

From source file:com.mtbs3d.minecrift.control.GuiScreenNaviator.java

public void up() {
    parsePoints();/* ww w  .  j a  v  a  2s  .c om*/
    if (curPoint != null) {
        Pair<Integer, Integer> nextBest = null;
        for (Pair<Integer, Integer> point : points) {
            if (point.getRight() < curPoint.getRight()) {
                if (nextBest == null || dist(nextBest, curPoint, AXIS_PREFERENCE, 1) > dist(point, curPoint,
                        AXIS_PREFERENCE, 1))
                    nextBest = point;
            }
        }
        if (nextBest != null) {

            mc.currentScreen.mouseGuiDrag(curPoint.getLeft(), curPoint.getRight());
            curPoint = nextBest;
            mouseto();
            onSlot = false;
        } else if (slot != null) {
            if (onSlot && slotIndex != 0)
                slotIndex--;
            int slotY = slot.select(slotIndex, false);
            curPoint = Pair.of(screen.width / 2, slotY);
            mouseto();
            onSlot = true;
        }
    }

}

From source file:com.javiermoreno.springboot.mvc.users.UserCtrl.java

/**
 * Retrieves the users registered in the application.
 * @param page page of the results// ww w  .  j a  va  2  s .co  m
 * @param amount how many results
 * @param direction ASC or DESC
 * @param sortingProperty name of the property used for sorting
 * @return 
 */
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "GET /users", notes = "Paginable.")
public HttpEntity<DailyUserPageResource> showAll(@RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "25") int amount, @RequestParam(required = false) Sort.Direction direction,
        @RequestParam(required = false) String sortingProperty) {

    Pair<List<DailyUser>, Long> data = userService.retrieveAllUsers(page, amount, direction, sortingProperty);

    DailyUserPageResource resource = new DailyUserPageResource();
    resource.users = data.getLeft();
    resource.page = page;
    resource.amount = amount;
    resource.total = data.getRight();
    resource.lastPageNumber = (int) (resource.total / resource.amount);

    resource.add(
            linkTo(methodOn(UserCtrl.class).showAll(page, amount, direction, sortingProperty)).withSelfRel());
    resource.add(linkTo(methodOn(UserCtrl.class).showAll(0, amount, direction, sortingProperty))
            .withRel("firstPage"));
    resource.add(linkTo(
            methodOn(UserCtrl.class).showAll(resource.lastPageNumber, amount, direction, sortingProperty))
                    .withRel("lastPage"));
    if (page > 0) {
        resource.add(linkTo(methodOn(UserCtrl.class).showAll(page - 1, amount, direction, sortingProperty))
                .withRel("prevPage"));
    }
    if (page + amount < resource.total) {
        resource.add(linkTo(methodOn(UserCtrl.class).showAll(page + 1, amount, direction, sortingProperty))
                .withRel("nextPage"));
    }
    for (int i = max(0, page - 5); i < min(page + 5, resource.lastPageNumber); i++) {
        resource.add(linkTo(methodOn(UserCtrl.class).showAll(i, amount, direction, sortingProperty))
                .withRel("page" + i));
    }

    return new ResponseEntity<>(resource, HttpStatus.OK);
}

From source file:alfio.manager.AdminReservationManagerIntegrationTest.java

@Test
public void testReserveMixed() throws Exception {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 1, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> eventWithUsername = initEvent(categories, organizationRepository, userManager,
            eventManager, eventRepository);
    Event event = eventWithUsername.getKey();
    String username = eventWithUsername.getValue();
    DateTimeModification expiration = DateTimeModification.fromZonedDateTime(ZonedDateTime.now().plusDays(1));
    CustomerData customerData = new CustomerData("Integration", "Test", "integration-test@test.ch",
            "Billing Address", "en");

    TicketCategory existingCategory = ticketCategoryRepository.findByEventId(event.getId()).get(0);

    Category resExistingCategory = new Category(existingCategory.getId(), "", existingCategory.getPrice());
    Category resNewCategory = new Category(null, "name", new BigDecimal("100.00"));
    int attendees = 1;
    List<TicketsInfo> ticketsInfoList = Arrays.asList(
            new TicketsInfo(resExistingCategory, generateAttendees(attendees), false, false),
            new TicketsInfo(resNewCategory, generateAttendees(attendees), false, false),
            new TicketsInfo(resExistingCategory, generateAttendees(attendees), false, false));
    AdminReservationModification modification = new AdminReservationModification(expiration, customerData,
            ticketsInfoList, "en", false, null);
    Result<Pair<TicketReservation, List<Ticket>>> result = adminReservationManager
            .createReservation(modification, event.getShortName(), username);
    assertTrue(result.isSuccess());/*from  ww w  . j  ava 2s .c o m*/
    Pair<TicketReservation, List<Ticket>> data = result.getData();
    List<Ticket> tickets = data.getRight();
    assertTrue(tickets.size() == 3);
    assertNotNull(data.getLeft());
    assertTrue(tickets.stream().allMatch(t -> t.getTicketsReservationId().equals(data.getKey().getId())));
    int resExistingCategoryId = tickets.get(0).getCategoryId();
    int resNewCategoryId = tickets.get(2).getCategoryId();

    Event modified = eventManager.getSingleEvent(event.getShortName(), username);
    assertEquals(AVAILABLE_SEATS, eventRepository.countExistingTickets(event.getId()).intValue());
    assertEquals(3, ticketRepository
            .findPendingTicketsInCategories(Arrays.asList(resExistingCategoryId, resNewCategoryId)).size());
    assertEquals(3, ticketRepository.findTicketsInReservation(data.getLeft().getId()).size());

    String reservationId = data.getLeft().getId();
    assertEquals(ticketRepository.findTicketsInReservation(reservationId).stream().findFirst().get().getId(),
            ticketRepository.findFirstTicketInReservation(reservationId).get().getId());

    ticketCategoryRepository.findByEventId(event.getId())
            .forEach(tc -> assertTrue(specialPriceRepository.findAllByCategoryId(tc.getId()).stream()
                    .allMatch(sp -> sp.getStatus() == SpecialPrice.Status.PENDING)));
    adminReservationManager.confirmReservation(event.getShortName(), data.getLeft().getId(), username);
    ticketCategoryRepository.findByEventId(event.getId())
            .forEach(tc -> assertTrue(specialPriceRepository.findAllByCategoryId(tc.getId()).stream()
                    .allMatch(sp -> sp.getStatus() == SpecialPrice.Status.TAKEN)));
    assertFalse(ticketRepository.findAllReservationsConfirmedButNotAssigned(event.getId())
            .contains(data.getLeft().getId()));
}

From source file:com.formkiq.core.util.StringsTest.java

/**
 * Test Base64 Image to Bytes and back./*from   w  w  w.  j a v  a2  s .  c  o m*/
 * @throws IOException IOException
 */
@Test
public void testBase64StringToImg01() throws IOException {
    // given
    String sig = getResourceAsString("/signature.txt");

    // when
    Pair<byte[], String> result = Strings.base64StringToImg(sig);

    // then
    final int len = 4541;
    assertEquals(len, result.getLeft().length);
    assertEquals("png", result.getRight());

    // when
    String imgsrc = Strings.bytesToImg(result.getLeft(), result.getRight());

    // then
    String expect = "data:image/png;base64," + "iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAA";
    assertTrue(sig.startsWith(expect));
    assertTrue(imgsrc.startsWith(expect));
}

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()));
    }// ww w .  j a va 2 s .  c o  m

}

From source file:com.github.helenusdriver.driver.tools.Tool.java

/**
 * Finds object creators with their dependencies based on the provided set of
 * class names. For each class found; the corresponding array element will be
 * nulled. All others are simply skipped.
 *
 * @author paouelle/*from w  w  w . j a v a  2s. c  om*/
 *
 * @param  classes the graph where to record creator classes
 * @param  cnames the set of class names for object creators
 * @param  no_dependents if dependents creators should not be considered
 * @throws LinkageError if the linkage fails for one entity class
 * @throws ExceptionInInitializerError if the initialization provoked by one
 *         of one the entity class fails
 */
private static void findCreatorsFromClasses(DirectedGraph<Class<?>> classes, String[] cnames,
        boolean no_dependents) {
    for (int i = 0; i < cnames.length; i++) {
        try {
            final Class<?> clazz = Class.forName(cnames[i]);

            cnames[i] = null; // clear since we found a class
            final Pair<Method, Class<?>[]> initial = Tool.findInitial(clazz);

            if (initial == null) {
                System.out.println(Tool.class.getSimpleName() + ": no objects found using " + clazz.getName());
                continue;
            }
            classes.add(clazz);
            final DirectedGraph.Node<Class<?>> node = classes.get(clazz);

            if (!no_dependents) {
                for (final Class<?> c : initial.getRight()) {
                    node.add(c);
                }
            }
        } catch (ClassNotFoundException e) { // ignore and continue
        }
    }
}

From source file:ca.on.oicr.pde.workflows.GATKGenotypeGVCFsWorkflow.java

@Override
public void buildWorkflow() {

    final String binDir = this.getWorkflowBaseDir() + "/bin/";
    final Boolean manualOutput = BooleanUtils.toBoolean(getProperty("manual_output"), "true", "false");
    final String queue = getOptionalProperty("queue", "");
    final String java = getProperty("java");
    final String gatk = getOptionalProperty("gatk_jar", binDir);
    final String gatkKey = getProperty("gatk_key");
    final String identifier = getProperty("identifier");
    final String refFasta = getProperty("ref_fasta");
    final Double standCallConf = Double.valueOf(getProperty("stand_call_conf"));
    final Double standEmitConf = Double.valueOf(getProperty("stand_emit_conf"));
    final String dbsnpVcf = getOptionalProperty("gatk_dbsnp_vcf", null);
    final Integer gatkGenotypeGvcfsXmx = Integer.parseInt(getProperty("gatk_genotype_gvcfs_xmx"));
    final String gatkGenotypeGvcfsParams = getOptionalProperty("gatk_genotype_gvcfs_params", null);
    final Integer gatkCombineGVCFsXmx = Integer.parseInt(getProperty("gatk_combine_gvcfs_xmx"));
    final Integer gatkOverhead = Integer.parseInt(getProperty("gatk_sched_overhead_mem"));
    final Integer maxGenotypeGVCFsInputFiles = Integer
            .parseInt(getProperty("gatk_genotype_gvcfs_max_input_files"));
    final Integer maxCombineGVCFsInputFiles = Integer
            .parseInt(getProperty("gatk_combine_gvcfs_max_input_files"));
    final List<String> chrSizesList = Arrays.asList(StringUtils.split(getProperty("chr_sizes"), ","));
    final Set<String> chrSizes = new LinkedHashSet<>(chrSizesList);

    if (chrSizes.size() != chrSizesList.size()) {
        throw new RuntimeException("Duplicate chr_sizes detected.");
    }/*from w  w  w . j  a  va 2s.co m*/

    // one chrSize record is required, null will result in no parallelization
    if (chrSizes.isEmpty()) {
        chrSizes.add(null);
    }

    List<Pair<String, Job>> combineGvcfs = batchGVCFs(inputFiles, maxGenotypeGVCFsInputFiles,
            maxCombineGVCFsInputFiles, java, gatkCombineGVCFsXmx, gatkOverhead, tmpDir, gatk, gatkKey,
            tmpGVCFsDir, refFasta, queue);

    //use linked hashmap to keep "pairs" in sort order determined by chr_sizes
    LinkedHashMap<String, Pair<GenotypeGVCFs, Job>> vcfs = new LinkedHashMap<>();
    for (String chrSize : chrSizes) {

        //GATK Genotype VCFs( https://www.broadinstitute.org/gatk/gatkdocs/org_broadinstitute_gatk_tools_walkers_variantutils_GenotypeGVCFs.php )
        GenotypeGVCFs.Builder genotypeGvcfsBuilder = new GenotypeGVCFs.Builder(java, gatkGenotypeGvcfsXmx + "g",
                tmpDir, gatk, gatkKey, dataDir)
                        .setReferenceSequence(refFasta)
                        .setOutputFileName(
                                identifier + (chrSize != null ? "." + chrSize.replace(":", "-") : "") + ".raw")
                        .addInterval(chrSize).setStandardCallConfidence(standCallConf)
                        .setStandardEmitConfidence(standEmitConf).setDbsnpFilePath(dbsnpVcf)
                        .setExtraParameters(gatkGenotypeGvcfsParams);
        for (String f : getLeftCollection(combineGvcfs)) {
            genotypeGvcfsBuilder.addInputFile(f);
        }
        GenotypeGVCFs genotypeGvcfsCommand = genotypeGvcfsBuilder.build();

        Job genotypeGvcfsJob = getWorkflow().createBashJob("GATKGenotypeGVCFs")
                .setMaxMemory(Integer.toString((gatkGenotypeGvcfsXmx + gatkOverhead) * 1024)).setQueue(queue);
        genotypeGvcfsJob.getCommand().setArguments(genotypeGvcfsCommand.getCommand());

        // add parents, null if provision file in, not null if parent is a combine gvcf job
        for (Job j : getRightCollection(combineGvcfs)) {
            if (j != null) {
                genotypeGvcfsJob.addParent(j);
            }
        }

        if (vcfs.put(chrSize, Pair.of(genotypeGvcfsCommand, genotypeGvcfsJob)) != null) {
            throw new RuntimeException("Unexpected state: duplicate vcf.");
        }
    }

    if (vcfs.size() > 1) {
        //GATK CatVariants ( https://www.broadinstitute.org/gatk/guide/tooldocs/org_broadinstitute_gatk_tools_CatVariants.php )
        CatVariants.Builder catVariantsBuilder = new CatVariants.Builder(java, gatkCombineGVCFsXmx + "g",
                tmpDir, gatk, gatkKey, dataDir).setReferenceSequence(refFasta)
                        //individual vcf files sorted by genotype gvcfs; order of input vcf concatenation is determined by chr_sizes order (assumed to be sorted)
                        .disableSorting().setOutputFileName(identifier + ".raw");
        for (GenotypeGVCFs cmd : getLeftCollection(vcfs.values())) {
            catVariantsBuilder.addInputFile(cmd.getOutputFile());
        }
        CatVariants catVariantsCommand = catVariantsBuilder.build();

        Job combineGVCFsJob = getWorkflow().createBashJob("GATKCombineGVCFs")
                .setMaxMemory(Integer.toString((gatkCombineGVCFsXmx + gatkOverhead) * 1024)).setQueue(queue);
        combineGVCFsJob.getParents().addAll(getRightCollection(vcfs.values()));
        combineGVCFsJob.getCommand().setArguments(catVariantsCommand.getCommand());
        combineGVCFsJob.addFile(
                createOutputFile(catVariantsCommand.getOutputFile(), "application/vcf-gz", manualOutput));
        combineGVCFsJob.addFile(
                createOutputFile(catVariantsCommand.getOutputIndex(), "application/tbi", manualOutput));
    } else if (vcfs.size() == 1) {
        Pair<GenotypeGVCFs, Job> p = Iterables.getOnlyElement(vcfs.values());
        GenotypeGVCFs cmd = p.getLeft();
        Job genotypeGvcfsJob = p.getRight();
        genotypeGvcfsJob.addFile(createOutputFile(cmd.getOutputFile(), "application/vcf-gz", manualOutput));
        genotypeGvcfsJob.addFile(createOutputFile(cmd.getOutputIndex(), "application/tbi", manualOutput));
    } else {
        throw new RuntimeException("Unexpected state: No VCFs");
    }
}