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:com.silverpeas.notation.model.RatingDAOTest.java

@Test
public void moveRating() throws Exception {
    IDataSet actualDataSet = getActualDataSet();
    ITable table = actualDataSet.getTable("sb_notation_notation");
    int[] aimedIds = new int[] { 1, 2, 3, 7 };
    Map<Integer, Pair<String, Integer>> raterRatings = new HashMap<Integer, Pair<String, Integer>>();
    for (int id : aimedIds) {
        int index = getTableIndexForId(table, id);
        assertThat((Integer) table.getValue(index, "id"), is(id));
        assertThat((String) table.getValue(index, "instanceId"), is(INSTANCE_ID));
        assertThat((String) table.getValue(index, "externalId"), is(CONTRIBUTION_ID));
        assertThat((String) table.getValue(index, "externalType"), is(CONTRIBUTION_TYPE));
        raterRatings.put(id,//from   w w w  .  ja v a  2 s .  c o m
                Pair.of((String) table.getValue(index, "author"), (Integer) table.getValue(index, "note")));
    }

    long nbMoved = RatingDAO.moveRatings(getConnection(),
            new ContributionRatingPK(CONTRIBUTION_ID, INSTANCE_ID, CONTRIBUTION_TYPE), "otherInstanceId");

    actualDataSet = getActualDataSet();
    table = actualDataSet.getTable("sb_notation_notation");
    assertThat(table.getRowCount(), is(RATING_ROW_COUNT));

    assertThat(nbMoved, is((long) aimedIds.length));
    for (int id : aimedIds) {
        int index = getTableIndexForId(table, id);
        assertThat((Integer) table.getValue(index, "id"), is(id));
        assertThat((String) table.getValue(index, "instanceId"), is("otherInstanceId"));
        assertThat((String) table.getValue(index, "externalId"), is(CONTRIBUTION_ID));
        assertThat((String) table.getValue(index, "externalType"), is(CONTRIBUTION_TYPE));
        Pair<String, Integer> raterRating = raterRatings.get(id);
        assertThat((String) table.getValue(index, "author"), is(raterRating.getLeft()));
        assertThat((Integer) table.getValue(index, "note"), is(raterRating.getRight()));
    }
}

From source file:de.pixida.logtest.buildserver.RunIntegrationTests.java

private List<Job> createJobs(final Map<File, List<Pair<File, Map<String, String>>>> pairsWithParams) {
    final List<Job> result = new ArrayList<>();
    for (final Entry<File, List<Pair<File, Map<String, String>>>> pair : pairsWithParams.entrySet()) {
        final List<LogSink> sinks = new ArrayList<>();
        for (final Pair<File, Map<String, String>> sinkDef : pair.getValue()) {
            final LogSink newSink = new LogSink();
            newSink.setAutomaton(new JsonAutomatonDefinition(sinkDef.getLeft()));
            newSink.setParameters(sinkDef.getRight());
            sinks.add(newSink);/*from w ww  .j ava 2  s.c  o  m*/
        }

        final Job newJob = new Job();
        newJob.setLogReader(this.createAndConfigureLogReader(pair.getKey()));
        newJob.setSinks(sinks);
        result.add(newJob);
    }
    return result;
}

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

@Override
public KubernetesV2ServerGroup getServerGroup(String account, String namespace, String name) {
    Pair<KubernetesKind, String> parsedName;
    try {//from   w w  w  .  j  a  v a  2  s . com
        parsedName = KubernetesManifest.fromFullResourceName(name);
    } catch (IllegalArgumentException e) {
        return null;
    }

    KubernetesKind kind = parsedName.getLeft();
    String shortName = parsedName.getRight();
    String key = Keys.infrastructure(kind, account, namespace, shortName);
    List<String> relatedTypes = kindMap.translateSpinnakerKind(INSTANCES).stream().map(KubernetesKind::toString)
            .collect(Collectors.toList());

    relatedTypes.addAll(kindMap.translateSpinnakerKind(LOAD_BALANCERS).stream().map(KubernetesKind::toString)
            .collect(Collectors.toList()));

    Optional<CacheData> serverGroupData = cacheUtils.getSingleEntryWithRelationships(kind.toString(), key,
            relatedTypes.toArray(new String[relatedTypes.size()]));

    return serverGroupData.map(cd -> {
        List<CacheData> instanceData = kindMap.translateSpinnakerKind(INSTANCES).stream()
                .map(k -> cacheUtils.loadRelationshipsFromCache(Collections.singletonList(cd), k.toString()))
                .flatMap(Collection::stream).collect(Collectors.toList());

        List<CacheData> loadBalancerData = kindMap.translateSpinnakerKind(LOAD_BALANCERS).stream()
                .map(k -> cacheUtils.loadRelationshipsFromCache(Collections.singletonList(cd), k.toString()))
                .flatMap(Collection::stream).collect(Collectors.toList());

        return cacheUtils.<KubernetesV2ServerGroup>resourceModelFromCacheData(
                KubernetesV2ServerGroupCacheData.builder().serverGroupData(cd).instanceData(instanceData)
                        .loadBalancerData(loadBalancerData).build());
    }).orElse(null);
}

From source file:io.cloudslang.lang.compiler.parser.utils.MetadataValidatorImpl.java

private List<RuntimeException> processCommonRules(List<String> lines,
        ParsedDescriptionSection parsedDescriptionSection, boolean isStep) {
    List<RuntimeException> errors = new ArrayList<>();
    int startLineNumberZeroBased = parsedDescriptionSection.getStartLineNumber() - 1;

    // validate begin wrapper line
    validateBeginWrapperLine(lines, isStep, errors, startLineNumberZeroBased);

    boolean finished = false;
    String previousTag = null;//from   ww w  . j a v a 2 s.c  o m
    int previousItemEndLineNumber = -1;
    for (int lineNrZeroBased = startLineNumberZeroBased + 1; !finished
            && lineNrZeroBased < lines.size(); lineNrZeroBased++) {
        String currentLine = lines.get(lineNrZeroBased);

        // #! @tag var: content
        // #! @tag: content
        boolean variableLine = isVariableLine(currentLine);
        boolean isGeneralLine = isGeneralLine(currentLine);
        if (variableLine || isGeneralLine || isVariableLineDeclarationOnly(currentLine)) {
            // extract tag
            String currentTag;
            if (variableLine) {
                Pair<String, String> declaration = descriptionPatternMatcher
                        .getDescriptionVariableLineData(currentLine);
                String[] declarationElements = descriptionPatternMatcher
                        .splitDeclaration(declaration.getLeft());
                currentTag = declarationElements[0];
            } else if (isGeneralLine) {
                Pair<String, String> declaration = descriptionPatternMatcher
                        .getDescriptionGeneralLineData(currentLine);
                String[] declarationElements = descriptionPatternMatcher
                        .splitDeclaration(declaration.getLeft());
                currentTag = declarationElements[0];
            } else {
                Pair<String, String> declaration = descriptionPatternMatcher
                        .getDescriptionVariableLineDataDeclarationOnly(currentLine);
                String[] declarationElements = descriptionPatternMatcher
                        .splitDeclaration(declaration.getLeft());
                currentTag = declarationElements[0];
            }

            // validate empty line
            validateEmptyLine(lines, errors, previousTag, previousItemEndLineNumber, currentTag);

            previousTag = currentTag;
            previousItemEndLineNumber = lineNrZeroBased;
        } else {
            // #! continued from previous line
            if (isNonEmptyComplementaryLine(currentLine)) {
                previousItemEndLineNumber = lineNrZeroBased;
            } else {
                // #!!#
                if (descriptionPatternMatcher.matchesDescriptionEnd(currentLine)) {
                    // validate ending wrapper line
                    validateEndingWrapperLine(lines, isStep, errors, lineNrZeroBased);

                    finished = true;
                }
                // otherwise ignore
            }
        }
    }
    return errors;
}

From source file:it.polimi.diceH2020.SPACE4CloudWS.solvers.solversImpl.SPNSolver.SPNSolver.java

@Override
protected Pair<Double, Boolean> run(Pair<List<File>, List<File>> pFiles, String remoteName,
        String remoteDirectory) throws Exception {
    List<File> files = pFiles.getLeft();
    if (!pFiles.getRight().isEmpty() || files.size() != 3) {
        throw new IllegalArgumentException("wrong number of input files");
    }//w ww.  j a  v a 2  s  .c o m

    File netFile = files.get(0);
    File defFile = files.get(1);
    File statFile = files.get(2);
    Matcher matcher = prefixRegex.matcher(netFile.getName());
    if (!matcher.matches()) {
        throw new RuntimeException(String.format("problem matching %s", netFile.getName()));
    }
    String prefix = matcher.group(1);

    String remotePath = remoteDirectory + File.separator + remoteName;

    boolean stillNotOk = true;
    for (int i = 0; stillNotOk && i < MAX_ITERATIONS; ++i) {
        logger.info(remoteName + "-> Starting Stochastic Petri Net simulation on the server");

        cleanRemoteSubDirectory(remoteDirectory);
        connector.exec(String.format("mkdir -p %s", remoteDirectory), getClass());
        logger.trace("Scenario is " + dataService.getScenario().getStringRepresentation());
        connector.sendFile(netFile.getAbsolutePath(), remotePath + ".net", getClass());
        logger.debug(remoteName + "-> GreatSPN .net file sent");
        connector.sendFile(defFile.getAbsolutePath(), remotePath + ".def", getClass());
        logger.debug(remoteName + "-> GreatSPN .def file sent");
        if (dataService.getScenario().getTechnology() != Technology.STORM) {
            connector.sendFile(statFile.getAbsolutePath(), remotePath + ".stat", getClass());
            logger.debug(remoteName + "-> GreatSPN .stat file sent");
        }

        String command = String.format("%s %s -a %f -c %d", connSettings.getSolverPath(), remotePath,
                connSettings.getAccuracy(), ((SPNSettings) connSettings).getConfidence().getFlag());
        logger.debug(remoteName + "-> Starting GreatSPN model...");
        List<String> remoteMsg = connector.exec(command, getClass());
        if (remoteMsg.contains("exit-status: 0")) {
            stillNotOk = false;
            logger.info(remoteName + "-> The remote optimization process completed correctly");
        } else {
            logger.debug(remoteName + "-> Remote exit status: " + remoteMsg);
        }
    }

    if (stillNotOk) {
        logger.info(remoteName + "-> Error in remote optimization");
        throw new Exception("Error in the SPN server");
    } else {
        List<String> remoteOutput = connector.exec(String.format("ls %s", remoteDirectory), getClass());
        String remoteResultFile = remoteDirectory + File.separator;
        try (BufferedReader reader = new BufferedReader(new StringReader(remoteOutput.get(0)))) {
            remoteResultFile += reader.lines().filter(line -> line.contains("simres")).findAny()
                    .orElse(remoteName + ".simres");
        }
        File solFile = fileUtility.provideTemporaryFile(prefix, ".simres");
        connector.receiveFile(solFile.getAbsolutePath(), remoteResultFile, getClass());
        Map<String, Double> results = new PNSimResFileParser(solFile).parse();
        if (fileUtility.delete(solFile))
            logger.debug(solFile + " deleted");

        double result = results.get(label);
        /* This is a workaround for the crazy behavior of the PNML transformation
         * that converts milliseconds to seconds.
         * Here we turn hertz into kilohertz to obtain results consistent
         * with our input.
         */
        if (usingInputModel && dataService.getScenario().getTechnology() != Technology.STORM)
            result /= 1000;
        logger.info(remoteName + "-> GreatSPN model run.");

        // TODO: this always returns false, should check if every error just throws
        return Pair.of(result, false);
    }
}

From source file:candr.yoclip.DefaultParserHelpFactoryTest.java

@Test
public void testGetOptionDescription() {

    final ParserHelpFactory<TestCase> testCase = new DefaultParserHelpFactory<TestCase>();
    final ParserOptions<TestCase> parserOptions = new ParserOptionsFactory<TestCase>(TestCase.class).create();

    final String prefix = parserOptions.getPrefix();
    final String separator = parserOptions.getSeparator();

    ParserOption<TestCase> optionParameter = parserOptions.get("s");
    Pair<String, String> description = testCase.getOptionDescription(prefix, separator, optionParameter);
    assertThat("option usage", description.getLeft(), is("/s|/string=STRING"));
    assertThat("option description", description.getRight(), is("Sets the 'option' field option."));

    optionParameter = parserOptions.get("D");
    description = testCase.getOptionDescription(prefix, separator, optionParameter);
    assertThat("properties usage", description.getLeft(), is("/DKEY=VALUE"));
    assertThat("option description", description.getRight(),
            is("Sets a property and value into the 'properties' Map field."));

    optionParameter = parserOptions.get(ParserOptions.ARGUMENTS_KEY);
    description = testCase.getOptionDescription(prefix, separator, optionParameter);
    assertThat("arguments usage", description.getLeft(), is("ARG"));
    assertThat("option description", description.getRight(),
            is("Sets an argument into the 'arguments' List field."));
}

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 ww w.j ava 2s  .  c  o m*/

    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.quancheng.saluki.boot.runner.GrpcReferenceRunner.java

private String getGroup(SalukiReference reference, String serviceName, Class<?> referenceClass) {
    Pair<String, String> groupVersion = findGroupAndVersionByServiceName(serviceName);
    if (StringUtils.isNoneBlank(reference.group())) {
        return reference.group();
    } else if (StringUtils.isNoneBlank(groupVersion.getLeft())) {
        String replaceGroup = groupVersion.getLeft();
        Matcher matcher = REPLACE_PATTERN.matcher(replaceGroup);
        if (matcher.find()) {
            String replace = matcher.group().substring(2, matcher.group().length() - 1).trim();
            String[] replaces = StringUtils.split(replace, ":");
            if (replaces.length == 2) {
                String realGroup = env.getProperty(replaces[0], replaces[1]);
                return realGroup;
            } else {
                throw new IllegalArgumentException("replaces formater is #{XXXgroup:groupName}");
            }// w w w .j a v a  2  s .  co  m
        } else {
            return replaceGroup;
        }
    } else if (this.isGenericClient(referenceClass)) {
        return StringUtils.EMPTY;
    }
    throw new java.lang.IllegalArgumentException(
            String.format("reference group can not be null or empty,the servicName is %s", serviceName));

}

From source file:net.fabricmc.loader.FabricLoader.java

public void load(Collection<File> modFiles) {
    if (modsLoaded) {
        throw new RuntimeException("FabricLoader has already had mods loaded!");
    }//from w w w .  j  a  va  2 s  .  c o  m

    List<Pair<ModInfo, File>> existingMods = new ArrayList<>();

    int classpathModsCount = 0;
    if (Boolean.parseBoolean(System.getProperty("fabric.development", "false"))) {
        List<Pair<ModInfo, File>> classpathMods = getClasspathMods();
        existingMods.addAll(classpathMods);
        classpathModsCount = classpathMods.size();
        LOGGER.debug("Found %d classpath mods", classpathModsCount);
    }

    for (File f : modFiles) {
        if (f.isDirectory()) {
            continue;
        }
        if (!f.getPath().endsWith(".jar")) {
            continue;
        }

        ModInfo[] fileMods = getJarMods(f);

        if (Launch.classLoader != null && fileMods.length != 0) {
            try {
                Launch.classLoader.addURL(f.toURI().toURL());
            } catch (MalformedURLException e) {
                LOGGER.error("Unable to load mod from %s", f.getName());
                e.printStackTrace();
                continue;
            }
        }

        for (ModInfo info : fileMods) {
            existingMods.add(Pair.of(info, f));
        }
    }

    LOGGER.debug("Found %d JAR mods", existingMods.size() - classpathModsCount);

    mods: for (Pair<ModInfo, File> pair : existingMods) {
        ModInfo mod = pair.getLeft();
        /* if (mod.isLazilyLoaded()) {
           innerMods:
           for (Pair<ModInfo, File> pair2 : existingMods) {
              ModInfo mod2 = pair2.getLeft();
              if (mod == mod2) {
          continue innerMods;
              }
              for (Map.Entry<String, ModInfo.Dependency> entry : mod2.getRequires().entrySet()) {
          String depId = entry.getKey();
          ModInfo.Dependency dep = entry.getValue();
          if (depId.equalsIgnoreCase(mod.getId()) && dep.satisfiedBy(mod)) {
             addMod(mod, pair.getRight(), loaderInitializesMods());
          }
              }
           }
           continue mods;
        } */
        addMod(mod, pair.getRight(), loaderInitializesMods());
    }

    String modText;
    switch (mods.size()) {
    case 0:
        modText = "Loading %d mods";
        break;
    case 1:
        modText = "Loading %d mod: %s";
        break;
    default:
        modText = "Loading %d mods: %s";
        break;
    }

    LOGGER.info(modText, mods.size(), String.join(", ",
            mods.stream().map(ModContainer::getInfo).map(ModInfo::getId).collect(Collectors.toList())));

    modsLoaded = true;
    onModsPopulated();
}

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

private static Map<Integer, String> extractPathwayStepIonsFromStandardIonAnalysis(
        List<ChemicalAssociatedWithPathway> pathwayChems, File lcmsDir, DB db, List<StandardWell> standardWells,
        String plottingDir, Map<Integer, Pair<Boolean, Boolean>> ionModesAvailable) throws Exception {

    Map<Integer, String> result = new HashMap<>();

    for (ChemicalAssociatedWithPathway pathwayChem : pathwayChems) {

        Map<StandardWell, StandardIonResult> wellToIonRanking = StandardIonAnalysis
                .getBestMetlinIonsForChemical(pathwayChem.getChemical(), lcmsDir, db, standardWells,
                        plottingDir);/*from   w w w  .j av  a  2 s .  c  o  m*/

        Pair<Boolean, Boolean> modes = ionModesAvailable.get(pathwayChem.getId());

        Map<StandardIonResult, String> chemicalToCuratedMetlinIon = new HashMap<>();
        List<StandardIonResult> standardIonResults = new ArrayList<>(wellToIonRanking.values());

        for (StandardIonResult standardIonResult : standardIonResults) {
            Integer manualOverrideId = standardIonResult.getManualOverrideId();
            if (manualOverrideId != null) {
                chemicalToCuratedMetlinIon.put(standardIonResult,
                        CuratedStandardMetlinIon.getBestMetlinIon(db, manualOverrideId).getBestMetlinIon());
            }
        }

        String bestMetlinIon = AnalysisHelper.scoreAndReturnBestMetlinIonFromStandardIonResults(
                standardIonResults, chemicalToCuratedMetlinIon, modes.getLeft(), modes.getRight());

        if (bestMetlinIon != null) {
            result.put(pathwayChem.getId(), bestMetlinIon);
        } else {
            result.put(pathwayChem.getId(), DEFAULT_SEARCH_ION);
        }
    }
    return result;
}