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:com.sludev.commons.vfs2.provider.s3.SS3FileObject.java

/**
 * Upload a local file to Amazon S3.//from   www.ja v a 2 s. c o  m
 * 
 * @param f File object from the local file-system to be uploaded to Amazon S3
 */
public void putObject(File f) {
    Pair<String, String> path = getContainerAndPath();

    fileSystem.getClient().putObject(new PutObjectRequest(path.getLeft(), path.getRight(), f));
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.view.provider.KubernetesV2LiveManifestProvider.java

@Override
public KubernetesV2Manifest getManifest(String account, String location, String name) {
    if (!isAccountRelevant(account)) {
        return null;
    }//from   w  w w  .  ja  v a 2s. com

    if (!makesLiveCalls(account)) {
        return null;
    }

    Pair<KubernetesKind, String> parsedName;
    try {
        parsedName = KubernetesManifest.fromFullResourceName(name);
    } catch (Exception e) {
        return null;
    }

    // TODO(lwander): move to debug once early users have validated this
    log.info("Live call to lookup manifest '{}:{}' in namespace '{}' under account '{}'", parsedName.getRight(),
            parsedName.getLeft(), location, account);
    KubernetesV2Credentials credentials = getCredentials(account)
            .orElseThrow(() -> new IllegalStateException("Already verified that credentials are relevant"));
    KubernetesManifest manifest = credentials.get(parsedName.getLeft(), location, parsedName.getRight());
    if (manifest == null) {
        return null;
    }

    String namespace = manifest.getNamespace();
    KubernetesKind kind = manifest.getKind();

    List<KubernetesManifest> events = credentials.eventsFor(kind, namespace, parsedName.getRight());

    // TODO kubectl top pod <name> -n <namespace>
    // low-priority, pipeline-only mode doesn't need to see resource usage.
    List<Map> metrics = Collections.emptyList();

    return buildManifest(account, manifest, events, metrics);
}

From source file:com.nextdoor.bender.operation.conditional.ConditionalOperation.java

public Stream<InternalEvent> getOutputStream(Stream<InternalEvent> input) {
    /*//from  ww w  .  j  av a  2s.c  om
     * outputStreams keeps track of the output Stream of each Condition.
     */
    List<Stream<InternalEvent>> outputStreams = new ArrayList<Stream<InternalEvent>>(
            this.conditionsAndProcs.size());

    /*
     * From a list of operation configurations in each condition construct queues and streams.
     */
    this.filtersAndQueues = new ArrayList<Pair<FilterOperation, Queue<InternalEvent>>>(
            this.conditionsAndProcs.size());
    for (Pair<FilterOperation, List<OperationProcessor>> filterAndProcs : this.conditionsAndProcs) {

        FilterOperation filter = filterAndProcs.getLeft();
        List<OperationProcessor> procs = filterAndProcs.getRight();

        /*
         * Construct a Queue for each conditional. This is the input to each Condition.
         */
        Queue<InternalEvent> queue = new Queue<InternalEvent>(
                new LinkedBlockingQueue<InternalEvent>(procs.size()));

        this.filtersAndQueues.add(new ImmutablePair<FilterOperation, Queue<InternalEvent>>(filter, queue));

        /*
         * Connect the condition's input Queue with operations. Each operation returns a stream with its
         * operation concatenated on.
         */
        Stream<InternalEvent> conditionInput = queue.jdkStream();
        for (OperationProcessor proc : procs) {
            conditionInput = proc.perform(conditionInput);
        }

        /*
         * Last input is the output.
         */
        outputStreams.add(conditionInput);
    }

    /*
     * Condition Consumer Threads
     * 
     * Combine each condition's output stream and write to the output Queue. When all data is consumed
     * the last condition closes the output Queue.
     */
    Queue<InternalEvent> outputQueue = new Queue<InternalEvent>(
            new LinkedBlockingQueue<InternalEvent>(this.conditionsAndProcs.size()));
    AtomicInteger lock = new AtomicInteger(outputStreams.size());

    outputStreams.forEach(stream -> {
        this.es.execute(new StreamToQueue(stream, outputQueue, lock));
    });

    /*
     * Consume input Stream in a thread and publish to each condition's Queue.
     */
    new Thread(new Runnable() {
        @Override
        public void run() {
            input.forEach(ievent -> {
                boolean matches = false;

                for (Pair<FilterOperation, Queue<InternalEvent>> filterAndQueue : filtersAndQueues) {
                    FilterOperation filter = filterAndQueue.getLeft();

                    /*
                     * If event passes the filter offer event to queue.
                     */
                    if (filter.test(ievent)) {
                        filterAndQueue.getRight().offer(ievent);
                        matches = true;
                        break;
                    }
                }

                /*
                 * Send to output queue if no case matches
                 */
                if (!matches && !filterNonMatch) {
                    outputQueue.offer(ievent);
                }
            });

            /*
             * Close queues when source queue is consumed.
             */
            for (Pair<FilterOperation, Queue<InternalEvent>> filterAndQueue : filtersAndQueues) {
                filterAndQueue.getRight().close();
            }
        }
    }).start();

    return outputQueue.jdkStream();
}

From source file:alfio.manager.AdminReservationManagerIntegrationTest.java

private void validateSuccess(boolean bounded, List<Integer> attendeesNr, Event event, String username,
        List<TicketCategory> existingCategories, Result<Pair<TicketReservation, List<Ticket>>> result,
        List<Attendee> allAttendees, int expectedEventSeats, int reservedTickets) {

    assertTrue(result.isSuccess());//from www.  j  ava  2s  . c om
    Pair<TicketReservation, List<Ticket>> data = result.getData();
    assertTrue(data.getRight().size() == attendeesNr.stream().mapToInt(i -> i).sum());
    assertNotNull(data.getLeft());
    Event modified = eventManager.getSingleEvent(event.getShortName(), username);
    assertEquals(expectedEventSeats, eventRepository.countExistingTickets(event.getId()).intValue());
    List<Ticket> tickets = ticketRepository.findPendingTicketsInCategories(
            existingCategories.stream().map(TicketCategory::getId).collect(toList()));
    assertEquals(attendeesNr.stream().mapToInt(i -> i).sum(), tickets.size() - reservedTickets);
    if (bounded) {
        final Iterator<Integer> iterator = attendeesNr.iterator();
        existingCategories.forEach(existingCategory -> {
            TicketCategory categoryModified = ticketCategoryRepository
                    .getByIdAndActive(existingCategory.getId(), event.getId());
            assertEquals(categoryModified.getMaxTickets(), iterator.next().intValue());
        });
    }
    for (int i = 0; i < tickets.size() - reservedTickets; i++) {
        Attendee attendee = allAttendees.get(i);
        if (!attendee.isEmpty()) {
            Ticket ticket = data.getRight().get(i);
            assertTrue(ticket.getAssigned());
            assertNotNull(ticket.getFullName());
            assertEquals(attendee.getFullName(), ticket.getFullName());
            assertEquals(attendee.getEmailAddress(), ticket.getEmail());
            assertEquals(Ticket.TicketStatus.PENDING, ticket.getStatus());
            assertEquals(data.getLeft().getId(), ticket.getTicketsReservationId());
        }
    }
    ticketCategoryRepository.findByEventId(modified.getId())
            .forEach(tc -> assertTrue(specialPriceRepository.findAllByCategoryId(tc.getId()).stream()
                    .allMatch(sp -> sp.getStatus() == SpecialPrice.Status.PENDING)));
    assertFalse(ticketRepository.findAllReservationsConfirmedButNotAssigned(event.getId())
            .contains(data.getLeft().getId()));
}

From source file:edu.upenn.cis.stormlite.LocalCluster.java

/**
 * For each bolt in the topology, create multiple objects (according to the parallelism)
 * //from   w w w.j a v a  2 s.c o m
 * @param topo Topology
 */
private void createBoltInstances(Topology topo, Config config) {
    for (String key : topo.getBolts().keySet()) {
        Pair<Class<? extends IRichBolt>, Integer> bolt = topo.getBolt(key);

        OutputCollector collector = new OutputCollector(context);

        boltStreams.put(key, new ArrayList<IRichBolt>());
        for (int i = 0; i < bolt.getRight(); i++)
            try {
                IRichBolt newBolt = bolt.getLeft().newInstance();
                newBolt.prepare(config, context, collector);
                boltStreams.get(key).add(newBolt);
                log.debug("Created a bolt executor " + key + "/" + newBolt.getExecutorId() + " of type "
                        + bolt.getLeft().getName());
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
}

From source file:com.act.lcms.db.model.LCMSWell.java

public List<LCMSWell> insertFromPlateComposition(DB db, PlateCompositionParser parser, Plate p)
        throws SQLException, IOException {
    Map<Pair<String, String>, String> msids = parser.getCompositionTables().get("msid");
    List<Pair<String, String>> sortedCoordinates = new ArrayList<>(msids.keySet());
    Collections.sort(sortedCoordinates, new Comparator<Pair<String, String>>() {
        // TODO: parse the values of these pairs as we read them so we don't need this silly comparator.
        @Override//w  ww  .  ja  v  a2s  .  c  o  m
        public int compare(Pair<String, String> o1, Pair<String, String> o2) {
            if (o1.getKey().equals(o2.getKey())) {
                return Integer.valueOf(Integer.parseInt(o1.getValue()))
                        .compareTo(Integer.parseInt(o2.getValue()));
            }
            return o1.getKey().compareTo(o2.getKey());
        }
    });

    List<LCMSWell> results = new ArrayList<>();
    for (Pair<String, String> coords : sortedCoordinates) {
        String msid = msids.get(coords);
        if (msid == null || msid.isEmpty()) {
            continue;
        }
        String composition = parser.getCompositionTables().get("composition").get(coords);
        String chemical = parser.getCompositionTables().get("chemical").get(coords);
        String note = null;
        if (parser.getCompositionTables().get("note") != null) {
            note = parser.getCompositionTables().get("note").get(coords);
        }
        Pair<Integer, Integer> index = parser.getCoordinatesToIndices().get(coords);
        LCMSWell s = INSTANCE.insert(db, p.getId(), index.getLeft(), index.getRight(), msid, composition,
                chemical, note);

        results.add(s);
    }

    return results;
}

From source file:ca.on.oicr.pde.workflows.GATKHaplotypeCallerWorkflow.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 String dbsnpVcf = getProperty("gatk_dbsnp_vcf");
    final Integer intervalPadding = hasPropertyAndNotNull("interval_padding")
            ? Integer.parseInt(getProperty("interval_padding"))
            : null;//from  w  ww .  java 2s  .c  o m
    final Integer downsamplingCoverage = hasPropertyAndNotNull("downsampling_coverage")
            ? Integer.parseInt(getProperty("downsampling_coverage"))
            : null;
    final String downsamplingType = getOptionalProperty("downsampling_type", null);
    final Integer gatkHaplotypeCallerThreads = Integer.parseInt(getProperty("gatk_haplotype_caller_threads"));
    final Integer gatkHaplotypeCallerXmx = Integer.parseInt(getProperty("gatk_haplotype_caller_xmx"));
    final Integer gatkCombineGVCFsXmx = Integer.parseInt(getProperty("gatk_combine_gvcfs_xmx"));
    final Integer gatkOverhead = Integer.parseInt(getProperty("gatk_sched_overhead_mem"));
    final String haplotypeCallerParams = getOptionalProperty("gatk_haplotype_caller_params", null);

    final List<String> intervalFilesList = Arrays
            .asList(StringUtils.split(getOptionalProperty("interval_files", ""), ","));
    final Set<String> intervalFiles = new HashSet<>(intervalFilesList);
    if (intervalFiles.size() != intervalFilesList.size()) {
        throw new RuntimeException("Duplicate interval_files detected");
    }

    final Set<String> chrSizes;
    if (hasProperty("chr_sizes")) {
        //chr_sizes has been set
        List<String> chrSizesList = Arrays.asList(StringUtils.split(getProperty("chr_sizes"), ","));
        chrSizes = new HashSet<>(chrSizesList);
        if (chrSizes.size() != chrSizesList.size()) {
            throw new RuntimeException("Duplicate chr_sizes detected.");
        }
    } else if (!intervalFiles.isEmpty()) {
        //chr_sizes not set, interval_files has been set - use interval files to calculate chrSizes
        try {
            chrSizes = BEDFileUtils.getChromosomes(intervalFiles);
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    } else {
        //chr_sizes and interval_files not set - can not calculate chrSizes
        chrSizes = new HashSet<>();
    }

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

    Map<String, Pair<HaplotypeCaller, Job>> gvcfs = new HashMap<>();
    for (String chrSize : chrSizes) {
        //GATK Haplotype Caller ( https://www.broadinstitute.org/gatk/gatkdocs/org_broadinstitute_gatk_tools_walkers_haplotypecaller_HaplotypeCaller.php )
        HaplotypeCaller haplotypeCallerCommand = new HaplotypeCaller.Builder(java,
                Integer.toString(gatkHaplotypeCallerXmx) + "g", tmpDir, gatk, gatkKey, dataDir)
                        .setInputBamFiles(inputBamFiles).setReferenceSequence(refFasta)
                        .setDbsnpFilePath(dbsnpVcf).addInterval(chrSize).addIntervalFiles(intervalFiles)
                        .setIntervalPadding(intervalPadding)
                        .setDownsamplingCoverageThreshold(downsamplingCoverage)
                        .setDownsamplingType(downsamplingType)
                        .setOutputFileName(
                                identifier + (chrSize != null ? "." + chrSize.replace(":", "-") : ""))
                        .setNumCpuThreadsPerDataThread(gatkHaplotypeCallerThreads)
                        .setExtraParameters(haplotypeCallerParams).build();
        Job haplotypeCallerJob = this.getWorkflow().createBashJob("GATKHaplotypeCaller")
                .setMaxMemory(Integer.toString((gatkHaplotypeCallerXmx + gatkOverhead) * 1024)).setQueue(queue);
        haplotypeCallerJob.getCommand().setArguments(haplotypeCallerCommand.getCommand());

        if (gvcfs.put(chrSize, Pair.of(haplotypeCallerCommand, haplotypeCallerJob)) != null) {
            throw new RuntimeException("Unexpected state: Duplicate key.");
        }
    }

    if (gvcfs.size() > 1) {
        //GATK CatVariants ( https://www.broadinstitute.org/gatk/guide/tooldocs/org_broadinstitute_gatk_tools_CatVariants.php )
        CatVariants.Builder catVariantsBuilder = new CatVariants.Builder(java,
                Integer.toString(gatkCombineGVCFsXmx) + "g", tmpDir, gatk, gatkKey, dataDir)
                        .setReferenceSequence(refFasta).setOutputFileName(identifier);
        for (HaplotypeCaller hc : getLeftCollection(gvcfs.values())) {
            catVariantsBuilder.addInputFile(hc.getOutputFile());
        }
        CatVariants catvariantsCommand = catVariantsBuilder.build();
        Job combineGVCFsJob = getWorkflow().createBashJob("GATKCombineGVCFs")
                .setMaxMemory(Integer.toString((gatkCombineGVCFsXmx + gatkOverhead) * 1024)).setQueue(queue);
        combineGVCFsJob.getParents().addAll(getRightCollection(gvcfs.values()));
        combineGVCFsJob.getCommand().setArguments(catvariantsCommand.getCommand());
        combineGVCFsJob.addFile(
                createOutputFile(catvariantsCommand.getOutputFile(), "application/g-vcf-gz", manualOutput));
        combineGVCFsJob.addFile(
                createOutputFile(catvariantsCommand.getOutputIndex(), "application/tbi", manualOutput));
    } else if (gvcfs.size() == 1) {
        Pair<HaplotypeCaller, Job> p = Iterables.getOnlyElement(gvcfs.values());
        HaplotypeCaller hcCmd = p.getLeft();
        Job hcJob = p.getRight();
        hcJob.addFile(createOutputFile(hcCmd.getOutputFile(), "application/g-vcf-gz", manualOutput));
        hcJob.addFile(createOutputFile(hcCmd.getOutputIndex(), "application/tbi", manualOutput));
    } else {
        throw new RuntimeException("Unexpected state: No GVCFs");
    }
}

From source file:de.johni0702.minecraft.gui.layout.GridLayout.java

@Override
public ReadableDimension calcMinSize(GuiContainer<?> container) {
    Preconditions.checkState(columns != 0, "Columns may not be 0.");
    int maxWidth = 0, maxHeight = 0;

    int elements = 0;
    for (Map.Entry<GuiElement, LayoutData> entry : container.getElements().entrySet()) {
        GuiElement element = entry.getKey();
        ReadableDimension minSize = element.getMinSize();

        int width = minSize.getWidth();
        if (width > maxWidth) {
            maxWidth = width;/* ww  w  . j  av  a2s.  c  om*/
        }

        int height = minSize.getHeight();
        if (height > maxHeight) {
            maxHeight = height;
        }
        elements++;
    }
    int rows = (elements - 1 + columns) / columns;

    int totalWidth = maxWidth * columns;
    int totalHeight = maxHeight * rows;

    if (!cellsEqualSize) {
        Pair<int[], int[]> maxCellSize = calcNeededCellSize(container);

        totalWidth = 0;
        for (int w : maxCellSize.getLeft()) {
            totalWidth += w;
        }

        totalHeight = 0;
        for (int h : maxCellSize.getRight()) {
            totalHeight += h;
        }
    }

    if (elements > 0) {
        totalWidth += spacingX * (columns - 1);
    }
    if (elements > columns) {
        totalHeight += spacingY * (rows - 1);
    }
    return new Dimension(totalWidth, totalHeight);
}

From source file:alfio.controller.api.admin.ExtensionApiController.java

@RequestMapping(value = "/log")
public PageAndContent<List<ExtensionLog>> getLog(@RequestParam(required = false, name = "path") String path,
        @RequestParam(required = false, name = "name") String name,
        @RequestParam(required = false, name = "type") ExtensionLog.Type type,
        @RequestParam(required = false, name = "page", defaultValue = "0") Integer page, Principal principal) {
    ensureAdmin(principal);/* w ww.  j  a va  2 s .com*/
    final int pageSize = 50;
    Pair<List<ExtensionLog>, Integer> res = extensionService.getLog(StringUtils.trimToNull(path),
            StringUtils.trimToNull(name), type, pageSize, (page == null ? 0 : page) * pageSize);
    return new PageAndContent<>(res.getLeft(), res.getRight());
}

From source file:com.sludev.commons.vfs2.provider.azure.AzFileObject.java

/**
 * Lists the children of this file.  Is only called if {@link #doGetType}
 * returns {@link FileType#FOLDER}.  The return value of this method
 * is cached, so the implementation can be expensive.<br />
 * @return a possible empty String array if the file is a directory or null or an exception if the
 * file is not a directory or can't be read.
 * @throws Exception if an error occurs.
 *//*from   w  w  w .j a v  a2  s.co  m*/
@Override
protected String[] doListChildren() throws Exception {
    String[] res = null;

    Pair<String, String> path = getContainerAndPath();

    String prefix = path.getRight();
    if (prefix.endsWith("/") == false) {
        // We need folders ( prefixes ) to end with a slash
        prefix += "/";
    }

    Iterable<ListBlobItem> blobs = null;
    if (prefix.equals("/")) {
        // Special root path case. List the root blobs with no prefix
        blobs = currContainer.listBlobs();
    } else {
        blobs = currContainer.listBlobs(prefix);
    }

    List<ListBlobItem> blobList = new ArrayList<>();

    // Pull it all in memory and work from there
    CollectionUtils.addAll(blobList, blobs);
    ArrayList<String> resList = new ArrayList<>();
    for (ListBlobItem currBlob : blobList) {
        String currBlobStr = currBlob.getUri().getPath();
        resList.add(currBlobStr);
    }

    res = resList.toArray(new String[resList.size()]);

    return res;
}