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

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

Introduction

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

Prototype

public static <L, R> Pair<L, R> of(final L left, final R right) 

Source Link

Document

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.

Usage

From source file:com.qq.tars.service.admin.AdminService.java

public List<CommandResult> doCommand(List<CommandTarget> targets, String command) {
    return targets.stream().map(target -> {
        Pair<Integer, String> pair;
        try {//w  w w  .  j a  va  2  s.  com
            pair = doCommand(target.getApplication(), target.getServerName(), target.getNodeName(), command);

            log.info("application={}, server name={}, node name={}", target.getApplication(),
                    target.getServerName(), target.getNodeName());
        } catch (TARSRequestException e) {
            log.error("application={}, server name={}, node name={}, command={}", target.getApplication(),
                    target.getServerName(), target.getNodeName(), e);
            pair = Pair.of(-1, e.getMessage());
        }

        CommandResult result = new CommandResult();
        BeanUtils.copyProperties(target, result);
        result.setRet(pair.getLeft());
        result.setErrMsg(pair.getRight());
        return result;
    }).collect(Collectors.toList());
}

From source file:io.cloudslang.lang.runtime.steps.ActionExecutionData.java

public void doAction(@Param(EXECUTION_RUNTIME_SERVICES) ExecutionRuntimeServices executionRuntimeServices,
        @Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv,
        @Param(ExecutionParametersConsts.NON_SERIALIZABLE_EXECUTION_DATA) Map<String, Map<String, Object>> nonSerializableExecutionData,
        @Param(ScoreLangConstants.NEXT_STEP_ID_KEY) Long nextStepId,
        @Param(ScoreLangConstants.ACTION_TYPE) ActionType actionType,
        @Param(ScoreLangConstants.JAVA_ACTION_CLASS_KEY) String className,
        @Param(ScoreLangConstants.JAVA_ACTION_METHOD_KEY) String methodName,
        @Param(ScoreLangConstants.JAVA_ACTION_GAV_KEY) String gav,
        @Param(ScoreLangConstants.PYTHON_ACTION_SCRIPT_KEY) String script,
        @Param(ScoreLangConstants.PYTHON_ACTION_DEPENDENCIES_KEY) Collection<String> dependencies,
        @Param(ScoreLangConstants.SEQ_STEPS_KEY) List<SeqStep> steps,
        @Param(ExecutionParametersConsts.EXECUTION) Serializable execution) {

    Map<String, Value> returnValue = new HashMap<>();
    Map<String, Value> callArguments = runEnv.removeCallArguments();
    Map<String, Value> callArgumentsDeepCopy = new HashMap<>();

    for (Map.Entry<String, Value> entry : callArguments.entrySet()) {
        callArgumentsDeepCopy.put(entry.getKey(), ValueFactory.create(entry.getValue()));
    }/*  www.j  av  a 2 s . c  o m*/

    Map<String, SerializableSessionObject> serializableSessionData = runEnv.getSerializableDataMap();
    fireEvent(executionRuntimeServices, ScoreLangConstants.EVENT_ACTION_START,
            "Preparing to run action " + actionType, runEnv.getExecutionPath().getParentPath(),
            LanguageEventData.StepType.ACTION, null, callArgumentsDeepCopy,
            Pair.of(LanguageEventData.CALL_ARGUMENTS, (Serializable) callArgumentsDeepCopy));
    try {
        switch (actionType) {
        case JAVA:
            returnValue = runJavaAction(serializableSessionData, callArguments, nonSerializableExecutionData,
                    gav, className, methodName, executionRuntimeServices.getNodeNameWithDepth(),
                    runEnv.getParentFlowStack().size());
            break;
        case PYTHON:
            returnValue = prepareAndRunPythonAction(dependencies, script, callArguments);
            break;
        case SEQUENTIAL:
            returnValue = runSequentialAction(callArguments, gav, steps, execution, runEnv, nextStepId);
            break;
        default:
            break;
        }
        if (stepDataConsumer != null) {
            stepDataConsumer.consumeStepData(callArguments, returnValue);
        }
    } catch (RuntimeException ex) {
        fireEvent(executionRuntimeServices, ScoreLangConstants.EVENT_ACTION_ERROR, ex.getMessage(),
                runEnv.getExecutionPath().getParentPath(), LanguageEventData.StepType.ACTION, null,
                callArgumentsDeepCopy, Pair.of(LanguageEventData.EXCEPTION, ex.getMessage()));
        logger.error(ex);
        throw (ex);
    }

    ReturnValues returnValues = new ReturnValues(returnValue, null);
    runEnv.putReturnValues(returnValues);
    fireEvent(executionRuntimeServices, ScoreLangConstants.EVENT_ACTION_END, "Action performed",
            runEnv.getExecutionPath().getParentPath(), LanguageEventData.StepType.ACTION, null,
            callArgumentsDeepCopy);

    if (!SEQUENTIAL.equals(actionType.getValue())) {
        /*
        Due to the way Sequential Actions work, we have to pause the execution BEFORE the actual run.
        Thus, we have to populate the run environment with the required data before pausing and persisting.
        We let the sequential action handler do it, since here it would be too late.
         */
        runEnv.putNextStepPosition(nextStepId);
    }
}

From source file:com.act.lcms.db.analysis.HitOrMissReplicateFilterAndTransformer.java

/**
 * This function takes in a list of molecules from multiple replicates over the same time and alignes the peaks across
 * these replicates. If the peaks can be aligned, the function reports the min statistic across those peaks, else it
 * defaults to a low statistic./* www .  j  a  v  a 2  s  .  c  om*/
 * @param oneOrMoreReplicates
 * @return A pair of transformed HitOrMiss molecule and whether to save the result in the final model.
 */
public Pair<IonAnalysisInterchangeModel.HitOrMiss, Boolean> apply(
        List<IonAnalysisInterchangeModel.HitOrMiss> oneOrMoreReplicates) {

    List<Double> intensityValues = oneOrMoreReplicates.stream().map(molecule -> molecule.getIntensity())
            .collect(Collectors.toList());
    List<Double> snrValues = oneOrMoreReplicates.stream().map(molecule -> molecule.getSnr())
            .collect(Collectors.toList());
    List<Double> timeValues = oneOrMoreReplicates.stream().map(molecule -> molecule.getTime())
            .collect(Collectors.toList());

    IonAnalysisInterchangeModel.HitOrMiss result = new IonAnalysisInterchangeModel.HitOrMiss();
    result.setInchi(oneOrMoreReplicates.get(REPRESENTATIVE_INDEX).getInchi());
    result.setIon(oneOrMoreReplicates.get(REPRESENTATIVE_INDEX).getIon());
    result.setPlot(NIL_PLOT);

    // We get the min and max time to calculate how much do the replicates deviate in time for the same signal. If
    // the deviation in the time axis is greater than our tolerance, we know the signal is bad.
    Double minTime = timeValues.stream().reduce(Double.MAX_VALUE, (accum, newVal) -> Math.min(accum, newVal));
    Double maxTime = timeValues.stream().reduce(Double.MIN_VALUE, (accum, newVal) -> Math.max(accum, newVal));

    if (maxTime - minTime < TIME_TOLERANCE_IN_SECONDS) {
        Double minIntensity = intensityValues.stream().reduce(Double.MAX_VALUE,
                (accum, newVal) -> Math.min(accum, newVal));

        Integer indexOfMinIntensityReplicate = intensityValues.indexOf(minIntensity);

        // The SNR and Time values will be the copy of the replicate with the lowest intensity value.
        result.setSnr(snrValues.get(indexOfMinIntensityReplicate));
        result.setIntensity(minIntensity);
        result.setTime(timeValues.get(indexOfMinIntensityReplicate));

        return Pair.of(result, DO_NOT_THROW_OUT_MOLECULE);
    } else {
        // TODO: We can just throw out such molecules.
        result.setSnr(LOWEST_POSSIBLE_VALUE_FOR_PEAK_STATISTIC);
        result.setIntensity(LOWEST_POSSIBLE_VALUE_FOR_PEAK_STATISTIC);
        result.setTime(LOWEST_POSSIBLE_VALUE_FOR_PEAK_STATISTIC);

        return Pair.of(result, DO_NOT_THROW_OUT_MOLECULE);
    }
}

From source file:forge.properties.ForgeProfileProperties.java

private static Pair<String, String> getDefaultDirs() {
    if (!GuiBase.getInterface().isRunningOnDesktop()) { //special case for mobile devices
        final String assetsDir = ForgeConstants.ASSETS_DIR;
        return Pair.of(assetsDir + "data" + File.separator, assetsDir + "cache" + File.separator);
    }//from ww w .  j a  v a 2s . c  o m

    final String osName = System.getProperty("os.name");
    final String homeDir = System.getProperty("user.home");

    if (StringUtils.isEmpty(osName) || StringUtils.isEmpty(homeDir)) {
        throw new RuntimeException("cannot determine OS and user home directory");
    }

    final String fallbackDataDir = String.format("%s/.forge", homeDir);

    if (StringUtils.containsIgnoreCase(osName, "windows")) {
        // the split between appdata and localappdata on windows is relatively recent.  If
        // localappdata is not defined, use appdata for both.  and if appdata is not defined,
        // fall back to a linux-style dot dir in the home directory
        String appRoot = System.getenv().get("APPDATA");
        if (StringUtils.isEmpty(appRoot)) {
            appRoot = fallbackDataDir;
        }
        String cacheRoot = System.getenv().get("LOCALAPPDATA");
        if (StringUtils.isEmpty(cacheRoot)) {
            cacheRoot = appRoot;
        }
        // the cache dir is Forge/Cache instead of just Forge since appRoot and cacheRoot might be the
        // same directory on windows and we need to distinguish them.
        return Pair.of(appRoot + File.separator + "Forge",
                cacheRoot + File.separator + "Forge" + File.separator + "Cache");
    } else if (StringUtils.containsIgnoreCase(osName, "mac os x")) {
        return Pair.of(String.format("%s/Library/Application Support/Forge", homeDir),
                String.format("%s/Library/Caches/Forge", homeDir));
    }

    // Linux and everything else
    return Pair.of(fallbackDataDir, String.format("%s/.cache/forge", homeDir));
}

From source file:cherry.goods.telno.SoumuExcelParserTest.java

@Test
public void testParse9() throws Exception {
    Map<String, Pair<String, String>> map;
    try (InputStream in = getClass().getResourceAsStream("soumu/000124078.xls")) {
        map = parser.parse(in);//  w ww .j av  a 2 s  .c o  m
    }
    assertEquals(5330, map.size());
    assertEquals(Pair.of("092", "320"), map.get("092320"));
    assertEquals(Pair.of("0997", "79"), map.get("099779"));
}

From source file:de.tntinteractive.portalsammler.sources.HanVBSourceV1.java

@Override
public Pair<Integer, Integer> poll(final SourceSettings settings, final UserInteraction gui,
        final SecureStore store) throws Exception {
    final WebDriver driver = this
            .createDriver("https://www.hannoversche-volksbank.de/ptlweb/WebPortal?bankid=0744");

    final WebElement userField = driver.findElement(By.id("vrkennungalias"));
    userField.sendKeys(settings.get(USER, gui));

    final WebElement passwordField = driver.findElement(By.id("pin"));
    passwordField.sendKeys(settings.get(PASSWORD, gui));

    passwordField.submit();//from w  ww  .  j ava 2  s  .c  o  m

    waitForPresence(driver, By.linkText("Postkorb"));

    int newDocs = 0;
    int knownDocs = 0;
    try {
        clickLink(driver, "Postkorb");
        waitForPresence(driver, By.name("confirmDeleteMultiMessage"));

        final WebElement form = driver.findElement(By.name("confirmDeleteMultiMessage"));
        final WebElement tbody = form.findElement(By.tagName("tbody"));

        final List<String> links = new ArrayList<String>();
        for (final WebElement tr : tbody.findElements(By.tagName("tr"))) {
            final List<WebElement> tds = tr.findElements(By.tagName("td"));
            final WebElement link = tds.get(2).findElement(By.tagName("a"));
            links.add(link.getAttribute("href"));
        }

        for (final String link : links) {
            driver.get(link);

            final DocumentInfo info = DocumentInfo.create(this.getId(), DocumentFormat.TEXT);
            final StringBuilder content = new StringBuilder();

            driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
            final WebElement fieldset = driver.findElement(By.tagName("fieldset"));
            for (final WebElement div : fieldset.findElements(By.tagName("div"))) {
                if (this.isLabeled(div, "Eingang")) {
                    info.setDate(this.parseTimestamp(div.findElement(By.className("gad-field-box")).getText()));
                } else if (this.isLabeled(div, "Betreff")) {
                    final WebElement data = div.findElement(By.className("gad-field-box"));
                    info.addKeywords(data.findElement(By.tagName("span")).getAttribute("title"));
                } else if (this.isNotLabeled(div)) {
                    content.append(div.getText());
                }
            }
            driver.manage().timeouts().implicitlyWait(WAIT_TIME, TimeUnit.SECONDS);

            if (!store.containsDocument(info)) {
                store.storeDocument(info, content.toString().getBytes("UTF-8"));
                newDocs++;
            } else {
                knownDocs++;
            }
        }

    } finally {
        clickLink(driver, "Logout");
    }
    return Pair.of(newDocs, knownDocs);
}

From source file:additionalpipes.pipes.PipeFluidsTeleport.java

private List<Pair<ForgeDirection, IFluidHandler>> getPossibleFluidsMovements() {
    List<Pair<ForgeDirection, IFluidHandler>> result = Lists.newArrayListWithCapacity(6);

    for (ForgeDirection o : ForgeDirection.VALID_DIRECTIONS) {
        TileEntity tile = container.getTile(o);

        if (Utils.checkPipesConnections(tile, container) && tile instanceof IFluidHandler) {
            result.add(Pair.of(o.getOpposite(), (IFluidHandler) tile));
        }/*w w w  .ja  v a2 s  .  c om*/
    }

    return result;
}

From source file:enumj.StreamComparator.java

private Pair<Function<Stream<T>, Stream<T>>, Function<E, E>> getLimitFuns() {
    final int seed = rnd.nextInt();
    final long limit = limitOfSeed.apply(seed);
    final Function<Stream<T>, Stream<T>> lhs = s -> s.limit(limit);
    final Function<E, E> rhs = e -> limit(e, limit);
    if (statistics != null) {
        statistics.limit();/*w  w w .j a va  2  s .c om*/
    }
    return Pair.of(lhs, rhs);
}

From source file:com.act.biointerpretation.desalting.DesalterTest.java

@Test
public void testDesaltingDetectsAndCountsRepeatedFragments() throws Exception {
    List<Pair<String, Map<String, Integer>>> testCases = new ArrayList<Pair<String, Map<String, Integer>>>() {
        {/*from ww w .ja  va2  s.  c  om*/
            add(Pair.of( // Phenanthroline!
                    "InChI=1S/2C12H8N2.2ClH.Ru/c2*1-3-9-5-6-10-4-2-8-14-12(10)11(9)13-7-1;;;/h2*1-8H;2*1H;/q2*-2;;;+9",
                    new HashMap<String, Integer>() {
                        {
                            put("InChI=1S/C12H8N2/c1-3-9-5-6-10-4-2-8-14-12(10)11(9)13-7-1/h1-8H/q-2", 2);
                        }
                    }));
            add(Pair.of( // Cyanide!
                    "InChI=1S/12CN.2Fe.2H/c12*1-2;;;;/q12*-1;+2;+3;;", new HashMap<String, Integer>() {
                        {
                            put("InChI=1S/CN/c1-2/q-1", 12);
                        }
                    }));
            add(Pair.of( // Bypyradine!
                    "InChI=1S/2C10H10N2.2ClH.Ru/c2*1-3-7-11-9(5-1)10-6-2-4-8-12-10;;;/h2*1-10H;2*1H;/q2*-2;;;+8/p-2",
                    new HashMap<String, Integer>() {
                        {
                            put("InChI=1S/C10H10N2/c1-3-7-11-9(5-1)10-6-2-4-8-12-10/h1-10H/q-2", 2);
                        }
                    }));
            add(Pair.of( // Cyclopentadien!
                    "InChI=1S/2C5H5.F6P.Fe/c2*1-2-4-5-3-1;1-7(2,3,4,5)6;/h2*1-5H;;/q3*-1;+3",
                    new HashMap<String, Integer>() {
                        {
                            put("InChI=1S/C5H5/c1-2-4-5-3-1/h1-5H/q-1", 2);
                        }
                    }));
            add(Pair.of( // Citrate!  (Bonus: multiple copper ions.)
                    "InChI=1S/2C6H8O7.3Cu/c2*7-3(8)1-6(13,5(11)12)2-4(9)10;;;/h2*13H,1-2H2,(H,7,8)(H,9,10)(H,11,12);;;/q;;3*+2/p-6",
                    new HashMap<String, Integer>() {
                        {
                            put("InChI=1S/C6H8O7/c7-3(8)1-6(13,5(11)12)2-4(9)10/h13H,1-2H2,(H,7,8)(H,9,10)(H,11,12)",
                                    2);
                        }
                    }));
        }
    };

    Desalter desalter = new Desalter(new ReactionProjector());
    desalter.initReactors();

    for (Pair<String, Map<String, Integer>> testCase : testCases) {
        String inchi = testCase.getLeft();
        Map<String, Integer> expectedFragmentCounts = testCase.getRight();
        Map<String, Integer> actual = desalter.desaltInchi(inchi);
        assertEquals(String.format("Fragments and counts match for %s", inchi), expectedFragmentCounts, actual);
    }
}

From source file:io.mandrel.metrics.impl.MongoMetricsRepository.java

@Override
public void sync(Map<String, Long> accumulators) {

    LocalDateTime now = LocalDateTime.now();
    LocalDateTime keytime = now.withMinute(0).withSecond(0).withNano(0);

    // {global.XXX=0, global.YYY=0, ...} to {global{XXX=O, YYY=0}, ...}
    Stream<Pair<String, Pair<String, Long>>> map = accumulators.entrySet().stream().map(e -> {
        Iterable<String> results = splitter.split(e.getKey());
        List<String> elts = Lists.newArrayList(results);
        return Pair.of(elts.get(0), Pair.of(elts.get(1), e.getValue()));
    });// w  w  w  .j  av a 2s .  c o  m
    Map<String, List<Pair<String, Long>>> byKey = map.collect(Collectors.groupingBy(e -> e.getLeft(),
            Collectors.mapping(e -> e.getRight(), Collectors.toList())));

    List<? extends WriteModel<Document>> requests = byKey.entrySet().stream().map(e -> {
        Document updates = new Document();

        e.getValue().stream().forEach(i -> {
            Iterable<String> results = splitter.split(i.getKey());
            List<String> elts = Lists.newArrayList(results);
            if (elts.size() > 1) {
                updates.put(elts.get(0) + "." + JsonBsonCodec.toBson(elts.get(1)), i.getValue());
            } else {
                updates.put(i.getKey(), i.getValue());
            }
        });

        return new UpdateOneModel<Document>(Filters.eq("_id", e.getKey()), new Document("$inc", updates),
                new UpdateOptions().upsert(true));
    }).collect(Collectors.toList());

    counters.bulkWrite(requests);

    requests = byKey.entrySet().stream().map(e -> {
        List<UpdateOneModel<Document>> tsUpdates = Lists.newArrayList();

        e.getValue().stream().forEach(i -> {
            Iterable<String> results = splitter.split(i.getKey());
            List<String> elts = Lists.newArrayList(results);

            if (elts.size() == 1 && e.getKey().equalsIgnoreCase(MetricKeys.global())) {
                tsUpdates.add(new UpdateOneModel<Document>(
                        Filters.and(Filters.eq("type", e.getKey() + MetricKeys.METRIC_DELIM + i.getKey()),
                                Filters.eq("timestamp_hour", keytime)),
                        new Document("$inc",
                                new Document("values." + Integer.toString(now.getMinute()), i.getValue())),
                        new UpdateOptions().upsert(true)));
            }
        });

        return tsUpdates;
    }).flatMap(list -> list.stream()).collect(Collectors.toList());

    timeseries.bulkWrite(requests);

}