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

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

Introduction

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

Prototype

public abstract L getLeft();

Source Link

Document

Gets the left element from this pair.

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

Usage

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   www .  j a  va 2s  . c om

    // 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");
    }
}

From source file:com.evolveum.midpoint.wf.impl.processors.primary.policy.ObjectPolicyAspectPart.java

<T extends ObjectType> void extractObjectBasedInstructions(@NotNull ObjectTreeDeltas<T> objectTreeDeltas,
        @Nullable PrismObject<UserType> requester,
        @NotNull List<PcpChildWfTaskCreationInstruction<?>> instructions,
        @NotNull ModelInvocationContext<T> ctx, @NotNull OperationResult result)
        throws SchemaException, ObjectNotFoundException {

    ObjectDelta<T> focusDelta = objectTreeDeltas.getFocusChange();
    LensFocusContext<T> focusContext = (LensFocusContext<T>) ctx.modelContext.getFocusContext();
    PrismObject<T> object = focusContext.getObjectOld() != null ? focusContext.getObjectOld()
            : focusContext.getObjectNew();

    List<EvaluatedPolicyRule> triggeredApprovalActionRules = main
            .selectTriggeredApprovalActionRules(focusContext.getPolicyRules());
    LOGGER.trace("extractObjectBasedInstructions: triggeredApprovalActionRules:\n{}",
            debugDumpLazily(triggeredApprovalActionRules));

    if (!triggeredApprovalActionRules.isEmpty()) {
        generateObjectOidIfNeeded(focusDelta, ctx.modelContext);
        ProcessSpecifications processSpecifications = ProcessSpecifications
                .createFromRules(triggeredApprovalActionRules, prismContext);
        LOGGER.trace("Process specifications:\n{}", debugDumpLazily(processSpecifications));
        for (ProcessSpecification processSpecificationEntry : processSpecifications.getSpecifications()) {
            if (focusDelta.isEmpty()) {
                break; // we're done
            }//w w w .  ja v a2s  .co  m
            WfProcessSpecificationType processSpecification = processSpecificationEntry.basicSpec;
            List<ObjectDelta<T>> deltasToApprove = extractDeltasToApprove(focusDelta, processSpecification);
            LOGGER.trace("Deltas to approve:\n{}", debugDumpLazily(deltasToApprove));
            if (deltasToApprove.isEmpty()) {
                continue;
            }
            LOGGER.trace("Remaining delta:\n{}", debugDumpLazily(focusDelta));
            ApprovalSchemaBuilder builder = new ApprovalSchemaBuilder(main, approvalSchemaHelper);
            builder.setProcessSpecification(processSpecificationEntry);
            for (Pair<ApprovalPolicyActionType, EvaluatedPolicyRule> actionWithRule : processSpecificationEntry.actionsWithRules) {
                ApprovalPolicyActionType approvalAction = actionWithRule.getLeft();
                builder.add(main.getSchemaFromAction(approvalAction), approvalAction, object,
                        actionWithRule.getRight());
            }
            buildSchemaForObject(requester, instructions, ctx, result, deltasToApprove, builder);
        }
    } else if (baseConfigurationHelper.getUseDefaultApprovalPolicyRules(
            ctx.wfConfiguration) != DefaultApprovalPolicyRulesUsageType.NEVER) {
        // default rule
        ApprovalSchemaBuilder builder = new ApprovalSchemaBuilder(main, approvalSchemaHelper);
        if (builder.addPredefined(object, SchemaConstants.ORG_OWNER, result)) {
            LOGGER.trace("Added default approval action, as no explicit one was found");
            generateObjectOidIfNeeded(focusDelta, ctx.modelContext);
            List<ObjectDelta<T>> deltasToApprove = singletonList(focusDelta.clone());
            focusDelta.clear();
            buildSchemaForObject(requester, instructions, ctx, result, deltasToApprove, builder);
        }
    }
}

From source file:at.beris.virtualfile.shell.Shell.java

private void processCommand(Pair<Command, List<String>> cmd) throws IOException {
    switch (cmd.getLeft()) {
    case CD://from  www  . jav  a  2  s .c o  m
        change(cmd.getRight().get(0), false);
        break;
    case CON:
        connect(new URL(cmd.getRight().get(0)));
        break;
    case DIS:
        disconnect();
        break;
    case GET:
        get(cmd.getRight().get(0));
        break;
    case HELP:
        displayHelp();
        break;
    case LCD:
        change(cmd.getRight().get(0), true);
        break;
    case LPWD:
        System.out.println(localFile.getPath());
        break;
    case LLS:
        list(true);
        break;
    case LRM:
        remove(true, cmd.getRight().get(0));
        break;
    case LS:
        list(false);
        break;
    case PUT:
        put(cmd.getRight().get(0));
        break;
    case PWD:
        System.out.println(workingFile != null ? maskedUrlString(workingFile.getUrl()) : NOT_CONNECTED_MSG);
        break;
    case RM:
        remove(false, cmd.getRight().get(0));
        break;
    case STAT:
        displayStatistics();
        break;
    case QUIT:
        quit();
        break;
    default:
        System.out.println("Unknown command.");
    }
}

From source file:com.nttec.everychan.ui.ShareActivity.java

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    @SuppressWarnings("unchecked")
    Pair<TabModel, SerializablePage> item = (Pair<TabModel, SerializablePage>) getListAdapter()
            .getItem(position);//from   w w w  . java 2 s  .  com
    SendPostModel draft = MainApplication.getInstance().draftsCache.get(item.getLeft().hash);
    if (draft == null) {
        draft = new SendPostModel();
        draft.chanName = item.getLeft().pageModel.chanName;
        draft.boardName = item.getLeft().pageModel.boardName;
        draft.threadNumber = item.getLeft().pageModel.type == UrlPageModel.TYPE_THREADPAGE
                ? item.getLeft().pageModel.threadNumber
                : null;
        draft.comment = "";
        BoardModel boardModel = item.getRight().boardModel;
        if (boardModel.allowNames)
            draft.name = MainApplication.getInstance().settings.getDefaultName();
        if (boardModel.allowEmails)
            draft.email = MainApplication.getInstance().settings.getDefaultEmail();
        if (boardModel.allowDeletePosts || boardModel.allowDeleteFiles)
            draft.password = MainApplication.getInstance().getChanModule(item.getLeft().pageModel.chanName)
                    .getDefaultPassword();
        if (boardModel.allowRandomHash)
            draft.randomHash = MainApplication.getInstance().settings.isRandomHash();
    }

    BoardModel boardModel = item.getRight().boardModel;
    int attachmentsCount = draft.attachments == null ? 0 : draft.attachments.length;
    ++attachmentsCount;
    if (attachmentsCount > boardModel.attachmentsMaxCount) {
        Toast.makeText(this, R.string.postform_max_attachments, Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    File[] attachments = new File[attachmentsCount];
    for (int i = 0; i < (attachmentsCount - 1); ++i)
        attachments[i] = draft.attachments[i];
    attachments[attachmentsCount - 1] = selectedFile;
    draft.attachments = attachments;

    if (PostingService.isNowPosting()) {
        Toast.makeText(this, R.string.posting_now_posting, Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    Intent addPostIntent = new Intent(this.getApplicationContext(), PostFormActivity.class);
    addPostIntent.putExtra(PostingService.EXTRA_PAGE_HASH, item.getLeft().hash);
    addPostIntent.putExtra(PostingService.EXTRA_BOARD_MODEL, item.getRight().boardModel);
    addPostIntent.putExtra(PostingService.EXTRA_SEND_POST_MODEL, draft);
    finish();
    startActivity(addPostIntent);
}

From source file:com.epam.catgenome.manager.externaldb.ncbi.NCBIShortVarManager.java

/**
 * Retrieves variations from snp database in given region
 *
 * @param organism   -- organism name//from  w  w  w . j a  v a 2  s.  c om
 * @param start      -- start position
 * @param finish     -- end position
 * @param chromosome -- chromosome number
 * @return list of found variations
 * @throws ExternalDbUnavailableException
 */
public List<Variation> fetchVariationsOnRegion(String organism, String start, String finish, String chromosome)
        throws ExternalDbUnavailableException {

    String term = String.format("%s:%s[Base Position] AND \"%s\"[CHR] AND \"%s\"[ORGN]", start, finish,
            chromosome, organism);
    String searchResultXml = ncbiAuxiliaryManager.searchWithHistory(NCBIDatabase.SNP.name(), term, MAX_RESULT);

    Pair<String, String> stringStringPair = ncbiGeneInfoParser.parseHistoryResponse(searchResultXml,
            NCBIUtility.NCBI_SEARCH);

    String queryKey = stringStringPair.getLeft();
    String webEnv = stringStringPair.getRight();

    String dataXml = ncbiAuxiliaryManager.fetchWithHistory(queryKey, webEnv, NCBIDatabase.SNP);

    ExchangeSet snpResultJaxb = null;

    try {

        JAXBContext jaxbContext = JAXBContext
                .newInstance("com.epam.catgenome.manager.externaldb.bindings.dbsnp");
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        StringReader reader = new StringReader(dataXml);
        Object uniprotObject = unmarshaller.unmarshal(reader);

        if (uniprotObject instanceof ExchangeSet) {
            snpResultJaxb = (ExchangeSet) uniprotObject;
        }

    } catch (JAXBException e) {
        throw new ExternalDbUnavailableException("Error parsing ncbi snp response", e);
    }
    return getResultList(snpResultJaxb);
}

From source file:act.installer.pubchem.PubchemTTLMergerTest.java

public List<String> getValForKey(
        Pair<RocksDB, Map<PubchemTTLMerger.COLUMN_FAMILIES, ColumnFamilyHandle>> dbAndHandles,
        PubchemTTLMerger.COLUMN_FAMILIES columnFamily, String key) throws Exception {
    RocksDB db = dbAndHandles.getLeft();
    String columnFamilyName = columnFamily.getName();
    ColumnFamilyHandle cfh = dbAndHandles.getRight().get(columnFamily);
    byte[] keyBytes = key.getBytes();
    byte[] valBytes = db.get(cfh, keyBytes);
    try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(valBytes))) {
        return (List<String>) ois.readObject();
    }/*from   w w w.j av a2  s.  c om*/
}

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  w  w. j  a va2  s  . c o m
    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.twitter.distributedlog.service.balancer.ClusterBalancer.java

ClusterBalancer(DistributedLogClientBuilder clientBuilder,
        Pair<DistributedLogClient, MonitorServiceClient> clientPair) {
    this.clientBuilder = clientBuilder;
    this.client = clientPair.getLeft();
    this.monitor = clientPair.getRight();
}

From source file:at.beris.virtualfile.shell.Shell.java

private boolean commandArgumentsValid(Pair<Command, List<String>> cmd) {
    StringBuilder sb = new StringBuilder();
    Command cmdOp = cmd.getLeft();
    int[] expectedArgCounts = cmdOp.getArgumentCounts();
    List<String> actualArgs = cmd.getRight();

    sb.append("Wrong number of arguments for Command ").append(cmdOp.toString().toLowerCase())
            .append(". Expected ");

    boolean argCountMatches = false;
    for (int expectedArgCount : expectedArgCounts) {
        if (expectedArgCount == actualArgs.size())
            argCountMatches = true;/* w  ww .j a  va  2  s .  c o m*/
        sb.append(expectedArgCount).append(" or ");
    }
    sb.delete(sb.length() - 4, sb.length()).append(".");

    if (!argCountMatches)
        System.out.println(sb.toString());

    return argCountMatches;
}

From source file:com.astamuse.asta4d.web.form.field.impl.AbstractRadioAndCheckboxRenderer.java

protected Renderer retrieveAndCreateValueMap(final String editTargetSelector,
        final String displayTargetSelector) {
    Renderer render = Renderer.create();
    if (PrepareRenderingDataUtil.retrieveStoredDataFromContextBySelector(editTargetSelector) == null) {

        final List<Pair<String, String>> inputList = new LinkedList<>();

        final List<OptionValuePair> optionList = new LinkedList<>();

        render.add(editTargetSelector, new ElementSetter() {
            @Override/*from  w  w w. ja v  a2 s  . c o m*/
            public void set(Element elem) {
                inputList.add(Pair.of(elem.id(), elem.attr("value")));
            }
        });

        render.add(":root", new Renderable() {
            @Override
            public Renderer render() {
                Renderer render = Renderer.create();
                for (Pair<String, String> input : inputList) {
                    String id = input.getLeft();
                    final String value = input.getRight();
                    if (StringUtils.isEmpty(id)) {
                        if (allowNonIdItems()) {
                            optionList.add(new OptionValuePair(value, value));
                        } else {
                            String msg = "The target item[%s] must have id specified.";
                            throw new IllegalArgumentException(String.format(msg, editTargetSelector));
                        }
                    } else {
                        render.add(SelectorUtil.attr("for", id), Renderer.create("label", new ElementSetter() {
                            @Override
                            public void set(Element elem) {
                                optionList.add(new OptionValuePair(value, elem.text()));
                            }
                        }));
                        render.add(":root", new Renderable() {
                            @Override
                            public Renderer render() {
                                PrepareRenderingDataUtil.storeDataToContextBySelector(editTargetSelector,
                                        displayTargetSelector, new OptionValueMap(optionList));
                                return Renderer.create();
                            }
                        });
                    }
                } // end for loop
                return render;
            }
        });
    }
    return render;
}