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.pinterest.terrapin.storage.HFileReader.java

@Override
public Future<Map<ByteBuffer, Pair<ByteBuffer, Throwable>>> getValues(List<ByteBuffer> keyList)
        throws Throwable {
    // Build a Future by executing a call against the future pool for every key.
    List<Future<Pair<ByteBuffer, Pair<ByteBuffer, Throwable>>>> futureList = Lists
            .newArrayListWithCapacity(keyList.size());
    for (final ByteBuffer key : keyList) {
        Future<Pair<ByteBuffer, Pair<ByteBuffer, Throwable>>> future = futurePool
                .apply(new Function0<Pair<ByteBuffer, Pair<ByteBuffer, Throwable>>>() {
                    @Override//from ww  w  . ja  v  a  2  s  .c o m
                    public Pair<ByteBuffer, Pair<ByteBuffer, Throwable>> apply() {
                        long startTimeMillis = System.currentTimeMillis();
                        Pair<ByteBuffer, Pair<ByteBuffer, Throwable>> keyExceptionPair = getValueFromHFile(key);
                        int timeMs = (int) (System.currentTimeMillis() - startTimeMillis);
                        if (metricsStatsKey != null) {
                            Stats.addMetric(metricsStatsKey, timeMs);
                        }
                        Stats.addMetric("lookup-latency-ms", timeMs);
                        if (keyExceptionPair.getRight().getRight() != null) {
                            if (errorStatsKey != null) {
                                Stats.incr(errorStatsKey);
                            }
                            Stats.incr("lookup-errors");
                        }
                        return keyExceptionPair;
                    }
                });
        futureList.add(future);
    }
    return Future.collect(futureList).map(
            new Function<List<Pair<ByteBuffer, Pair<ByteBuffer, Throwable>>>, Map<ByteBuffer, Pair<ByteBuffer, Throwable>>>() {
                @Override
                public Map<ByteBuffer, Pair<ByteBuffer, Throwable>> apply(
                        List<Pair<ByteBuffer, Pair<ByteBuffer, Throwable>>> keyValuePairList) {
                    Map<ByteBuffer, Pair<ByteBuffer, Throwable>> returnMap = Maps
                            .newHashMapWithExpectedSize(keyValuePairList.size());
                    for (Pair<ByteBuffer, Pair<ByteBuffer, Throwable>> pair : keyValuePairList) {
                        Pair<ByteBuffer, Throwable> value = pair.getRight();
                        if (value.getLeft() != null || value.getRight() != null) {
                            returnMap.put(pair.getLeft(), pair.getRight());
                        }
                    }
                    return returnMap;
                }
            });
}

From source file:cz.lidinsky.editor.Writer.java

public Factory<String> transform(Pair<Object, AccessibleObject> param) {

    final Object object = param.getLeft();
    final AccessibleObject member = param.getRight();

    Class dataType = ObjectMapUtils.getValueDataType(member);
    if (java.awt.Color.class.isAssignableFrom(dataType)) {
        return new Factory<String>() {
            public String create() {
                try {
                    Object rawValue = ObjectMapUtils.get(object, member, true);
                    if (rawValue == null) {
                        return "<null>";
                    } else {
                        return Integer.toString(((Color) rawValue).getRGB());
                    }//from w  ww  .j av a2 s.  c  o  m
                } catch (Exception e) {
                    throw new CommonException().setCause(e)
                            .set("message", "Exception while reading from a getter!").set("object", object)
                            .set("member", member).set("accessibility", true);
                }
            }
        };
    } else {
        return ObjectMapUtils.stringGetterFactory(true).transform(param);
    }
}

From source file:com.streamsets.pipeline.stage.executor.jdbc.TestJdbcQueryExecutor.java

/**
 * Validate structure of the result set (column names and types).
 *//*from  ww w .  jav  a  2s  .c  om*/
public void assertResultSetStructure(ResultSet rs, Pair<String, Integer>... columns) throws Exception {
    ResultSetMetaData metaData = rs.getMetaData();
    Assert.assertEquals(Utils.format("Unexpected number of columns"), columns.length,
            metaData.getColumnCount());
    int i = 1;
    for (Pair<String, Integer> column : columns) {
        Assert.assertEquals(Utils.format("Unexpected name for column {}", i), column.getLeft(),
                metaData.getColumnName(i));
        Assert.assertEquals(Utils.format("Unexpected type for column {}", i), (int) column.getRight(),
                metaData.getColumnType(i));
        i++;
    }
}

From source file:io.lavagna.service.ListValueMetadataRepositoryTest.java

@Test
public void findAll() {

    Pair<LabelListValue, LabelListValue> llvp = createLabelListValue();

    List<Integer> labelListValueIds = Arrays.asList(llvp.getLeft().getId(), llvp.getRight().getId());

    Assert.assertEquals(0, listValueMetadataQuery.findByLabelListValueIds(labelListValueIds).size());

    listValueMetadataQuery.insert(llvp.getLeft().getId(), "KEY", "VALUE");

    Assert.assertEquals(1, listValueMetadataQuery.findByLabelListValueIds(labelListValueIds).size());

    listValueMetadataQuery.insert(llvp.getRight().getId(), "KEY", "VALUE");

    Assert.assertEquals(2, listValueMetadataQuery.findByLabelListValueIds(labelListValueIds).size());
}

From source file:cherry.example.web.applied.ex90.AppliedEx90ControllerImpl.java

@Override
public ModelAndView confirm(AppliedEx90Form form, BindingResult binding, Authentication auth, Locale locale,
        SitePreference sitePref, NativeWebRequest request) {

    if (hasErrors(form, binding)) {
        return withViewname(viewnameOfStart).build();
    }//from   w w  w. ja  va2 s .c om

    Pair<String, List<String>> temp = createTempFile(asList(form.getFile()));
    form.setDirname(temp.getLeft());
    form.setNumOfFile(temp.getRight().size());
    form.setOriginalFilename(form.getFile().getOriginalFilename());

    return withoutView().build();
}

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 w w  w. j  a  v a2 s  .  c o m*/
            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:com.jaspersoft.jasperserver.jrsh.completion.completer.RepositoryNameCompleter.java

private List<String> reformatResources(List<Pair<String, Boolean>> resources) {
    List<String> list = new ArrayList<>();
    for (Pair<String, Boolean> pair : resources) {
        String resource = pair.getLeft();
        Boolean isFolder = pair.getRight();
        String last;//  ww  w.  j ava2s. c om
        if (isFolder) {
            last = lastName(resource) + "/";
        } else {
            last = lastName(resource);
        }
        list.add(last);
    }
    return list;
}

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

protected Pair<Double, Boolean> run(@NotNull Pair<List<File>, List<File>> pFiles, String remoteName)
        throws JSchException, IOException {
    List<File> exchangedFiles = pFiles.getLeft();
    boolean stillNotOk = true;
    for (int iteration = 0; stillNotOk && iteration < MAX_ITERATIONS; ++iteration) {
        File dataFile = exchangedFiles.get(0);
        String fullRemotePath = connSettings.getRemoteWorkDir();
        connector.sendFile(dataFile.getAbsolutePath(), fullRemotePath + "/data", getClass());
        logger.info(remoteName + "-> GLPK .data file sent");

        String remoteRelativeDataPath = "data/" + dataFile.getName();
        String remoteRelativeSolutionPath = ".." + RESULTS_SOLFILE;
        Matcher matcher = Pattern.compile("([\\w.-]*)(?:-\\d*)\\.dat").matcher(dataFile.getName());
        if (!matcher.matches()) {
            throw new RuntimeException(String.format("problem matching %s", dataFile.getName()));
        }/*from ww  w.j  ava 2  s.  co m*/
        logger.debug(remoteName + "-> Cleaning result directory");
        clearResultDir();

        logger.info(remoteName + "-> Processing execution...");
        String command = String.format("cd %s && %s %s", connSettings.getRemoteWorkDir(),
                ((GLPKSettings) connSettings).getExecutable(),
                "--math models/model_glpk.mod -d " + remoteRelativeDataPath);
        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.info("Remote exit status: " + remoteMsg);
            if (remoteMsg.get(0).contains("error processing param")) {
                iteration = MAX_ITERATIONS;
                logger.info(remoteName + "-> Wrong parameters. Aborting");
            } else {
                logger.info(remoteName + "-> Restarted. Iteration " + iteration);
            }
        }
    }

    if (stillNotOk) {
        logger.info(remoteName + "-> Error in remote optimization");
        throw new IOException("Error in the initial solution creation process");
    } else {
        File solutionFile = exchangedFiles.get(1);
        String fullRemotePath = connSettings.getRemoteWorkDir() + RESULTS_SOLFILE;
        connector.receiveFile(solutionFile.getAbsolutePath(), fullRemotePath, getClass());
        Double objFunctionValue = analyzeSolution(solutionFile, ((GLPKSettings) connSettings).isVerbose());
        logger.info(remoteName + "-> The value of the objective function is: " + objFunctionValue);
        // TODO: this always returns false, should check if every error just throws
        return Pair.of(objFunctionValue, false);
    }
}

From source file:com.foudroyantfactotum.mod.fousarchive.command.CommandPianoRollID.java

@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
    try {/*w w w  .  j  a  v  a 2s  .  c o m*/
        final List<Pair<SearchMatch, String>> pt = parse(getAsSingleString(args));
        if (pt.size() > 10)
            throw new CommandException("Too many matches");
        if (pt.size() == 0)
            pt.add(Pair.of(SearchMatch.Title, ""));

        final List<Predicate<MidiDetails>> func = new ArrayList<>(pt.size());
        final List<SearchMatch> outfString = new LinkedList<>();

        for (Pair<SearchMatch, String> p : pt) {
            func.add(p.getLeft().checkDetails(p.getRight()));
            outfString.add(p.getLeft());
        }

        final ResourceLocation[] songList = LiveMidiDetails.INSTANCE.songDetails();
        final List<Pair<ResourceLocation, MidiDetails>> validList = new LinkedList<>();

        sender.addChatMessage(new TextComponentString("==========Searching=========="));

        song: for (int i = 0; i < songList.length; ++i) {
            final MidiDetails song = LiveMidiDetails.INSTANCE.getDetailsOnSong(songList[i]);

            for (Predicate<MidiDetails> p : func)
                if (!p.test(song))
                    continue song;

            validList.add(Pair.of(songList[i], song));
        }
        int i = 0;

        for (Pair<ResourceLocation, MidiDetails> m : validList)
            sender.addChatMessage(new TextComponentString(
                    "\u00A7l" + (++i) + ". \u00A7r\u00A7o" + toStringer(m.getRight(), outfString) + "\u00A7r"));

        sender.addChatMessage(new TextComponentString("=========End  Search========="));

        if (validList.size() == 1) {
            final BlockPos sp = sender.getPosition();
            final ItemStack stack = new ItemStack(ModItems.pianoRoll, 1,
                    Math.abs(validList.get(0).getLeft().toString().hashCode()) % ItemPianoRoll.iconNo);
            final NBTTagCompound nbt = new NBTTagCompound();

            ItemPianoRoll.setPianoRollNBT(nbt, validList.get(0).getLeft().toString());
            stack.setTagCompound(nbt);

            sender.getEntityWorld().spawnEntityInWorld(
                    new EntityItem(sender.getEntityWorld(), sp.getX(), sp.getY(), sp.getZ(), stack));
        }
    } catch (Exception e) {
        if (e instanceof CommandException)
            throw e;
    }
}

From source file:fr.cvlaminck.merging.impl.strategy.ImmutableObjectMergingStrategy.java

/**
 * Create an immutable object merging strategy.
 *
 * @since 1.1//from  w w w.jav a2  s .com
 */
public ImmutableObjectMergingStrategy(Class<?> object, Pair... strategies) {
    final MutableObjectMergingStrategy objectMergingStrategy = new MutableObjectMergingStrategy(object);
    //All pairs that do not math the requirements will be simply ignored
    for (Pair strategy : strategies) {
        if (strategy.getRight() instanceof String) {
            //If we have a Pair<String, String> then the user has described a strategy specific to a field
            if (strategy.getLeft() instanceof String)
                objectMergingStrategy.setSpecificStrategyForField((String) strategy.getLeft(),
                        (String) strategy.getRight());
            //If we have a Pair<Object, String> then the user has described a default strategy
            if (strategy.getLeft() instanceof Class)
                objectMergingStrategy.setDefaultStrategyForType((Class<?>) strategy.getLeft(),
                        (String) strategy.getRight());
        }
    }
    this.wrappedObjectMergingStrategy = objectMergingStrategy;
}