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.act.lcms.db.analysis.ChemicalToMapOfMetlinIonsToIntensityTimeValues.java

/**
 * This function plots a combination of positive and negative control intensity-time values.
 * @param searchMzs A list of mass charge values
 * @param plottingPath The wells used for the analysis. This variable is mainly used for
 * @param peakDataPos The postive intensity-time value
 * @param peakDataNegs The negative controls intensity-time values
 * @param plottingDirectory The directory where the plots are going to be placed in
 * @return// ww  w . j  av  a2s .c  om
 * @throws IOException
 */
public static Map<String, String> plotPositiveAndNegativeControlsForEachMZ(Set<Pair<String, Double>> searchMzs,
        String plottingPath, ChemicalToMapOfMetlinIonsToIntensityTimeValues peakDataPos,
        List<ChemicalToMapOfMetlinIonsToIntensityTimeValues> peakDataNegs, String plottingDirectory)
        throws IOException {

    Map<String, String> result = new HashMap<>();
    Map<String, Double> individualMaxIntensities = new HashMap<>();
    WriteAndPlotMS1Results plottingUtil = new WriteAndPlotMS1Results();

    for (Pair<String, Double> mz : searchMzs) {
        LinkedHashMap<String, List<XZ>> ms1s = new LinkedHashMap<>();
        Map<String, Double> metlinMasses = new HashMap<>();
        Double maxIntensity = 0.0d;

        String chemicalAndIonName = mz.getLeft();
        Double massChargeValue = mz.getRight();

        // Get positive ion results
        String positiveChemicalName = AnalysisHelper.constructChemicalAndScanTypeName(chemicalAndIonName,
                ScanData.KIND.POS_SAMPLE);
        List<XZ> ionValuesPos = peakDataPos.peakData.get(positiveChemicalName).get(chemicalAndIonName);
        ms1s.put(positiveChemicalName, ionValuesPos);
        Double localMaxIntensityPos = findPeakMaxIntensity(ionValuesPos);
        maxIntensity = Math.max(maxIntensity, localMaxIntensityPos);
        individualMaxIntensities.put(positiveChemicalName, localMaxIntensityPos);
        metlinMasses.put(positiveChemicalName, massChargeValue);

        // Get negative control results
        Integer negNameCounter = 0;
        for (ChemicalToMapOfMetlinIonsToIntensityTimeValues peakDataNeg : peakDataNegs) {
            String negativeChemicalName = AnalysisHelper.constructChemicalAndScanTypeName(chemicalAndIonName,
                    ScanData.KIND.NEG_CONTROL);
            String negativeChemicalNameId = negativeChemicalName + "_" + negNameCounter.toString();
            List<XZ> ionValuesNeg = peakDataNeg.peakData.get(negativeChemicalName).get(chemicalAndIonName);
            ms1s.put(negativeChemicalNameId, ionValuesNeg);
            Double localMaxIntensityNeg = findPeakMaxIntensity(ionValuesNeg);
            maxIntensity = Math.max(maxIntensity, localMaxIntensityNeg);
            individualMaxIntensities.put(negativeChemicalNameId, localMaxIntensityNeg);
            metlinMasses.put(negativeChemicalNameId, massChargeValue);
            negNameCounter++;
        }

        String relativePath = massChargeValue.toString() + "_" + plottingPath + "_" + chemicalAndIonName;
        File absolutePathFileWithoutExtension = new File(plottingDirectory, relativePath);
        String absolutePathWithoutExtension = absolutePathFileWithoutExtension.getAbsolutePath();
        String absolutePathWithExtension = absolutePathWithoutExtension + "." + FMT;

        // Check if the plotting file already exists. If it does, we should not overwrite it. Instead, we just change
        // the path name by appending a counter till the collision no longer exists.
        // TODO: Implement an elegant solution to this problem.
        File duplicateFile = new File(absolutePathWithExtension);
        Integer fileDuplicateCounter = 0;
        while (duplicateFile.exists() && !duplicateFile.isDirectory()) {
            LOGGER.warn("Duplicate file exists for %s, writing to another file",
                    duplicateFile.getAbsolutePath());
            fileDuplicateCounter++;
            relativePath = relativePath + "_" + fileDuplicateCounter.toString();
            absolutePathFileWithoutExtension = new File(plottingDirectory, relativePath);
            absolutePathWithoutExtension = absolutePathFileWithoutExtension.getAbsolutePath();
            absolutePathWithExtension = absolutePathWithoutExtension + "." + FMT;
            duplicateFile = new File(absolutePathWithExtension);
        }

        LOGGER.info("Wrote plot to %s", absolutePathWithoutExtension);

        plottingUtil.plotSpectra(ms1s, maxIntensity, individualMaxIntensities, metlinMasses,
                absolutePathWithoutExtension, FMT, false, false);

        result.put(mz.getLeft(), relativePath + "." + FMT);
    }

    return result;
}

From source file:com.twitter.graphjet.bipartite.GraphConcurrentTestHelper.java

/**
 * This helper method sets up a concurrent read-write situation with a single writer and multiple
 * readers that access the same underlying bipartiteGraph, and tests for correct edge access during
 * simultaneous edge writes. This helps test read consistency during arbitrary points of
 * inserting edges. Note that the exact read-write sequence here is non-deterministic and would
 * vary depending on the machine, but the hope is that given the large number of readers the reads
 * would be done at many different points of edge insertion. The test itself checks only for
 * partial correctness (it could have false positives) so this should only be used as a supplement
 * to other testing./*from ww  w . j a v  a 2 s .c  o  m*/
 *
 * @param graph              is the underlying
 *                           {@link BipartiteGraph}
 * @param numReadersPerNode  is the number of reader threads to use per node
 * @param leftSize           is the number of left nodes
 * @param rightSize          is the number of right nodes
 * @param edgeProbability    is the probability of an edge between a left-right node pair
 * @param random             is the random number generator to use for generating a random graph
 */
public static <T extends BipartiteGraph & DynamicBipartiteGraph> void testRandomConcurrentReadWriteThreads(
        T graph, int numReadersPerNode, int leftSize, int rightSize, double edgeProbability, Random random) {
    int maxWaitingTimeForThreads = 20; // in milliseconds
    int numLeftReaders = leftSize * numReadersPerNode;
    int numRightReaders = rightSize * numReadersPerNode;
    int totalNumReaders = numLeftReaders + numRightReaders;
    CountDownLatch readersDoneLatch = new CountDownLatch(totalNumReaders);
    // First, construct a random set of edges to insert in the graph
    Set<Pair<Long, Long>> edges = Sets
            .newHashSetWithExpectedSize((int) (leftSize * rightSize * edgeProbability));
    List<BipartiteGraphReader> leftReaders = Lists.newArrayListWithCapacity(numLeftReaders);
    List<BipartiteGraphReader> rightReaders = Lists.newArrayListWithCapacity(numRightReaders);
    Long2ObjectMap<LongSet> leftSideGraph = new Long2ObjectOpenHashMap<LongSet>(leftSize);
    Long2ObjectMap<LongSet> rightSideGraph = new Long2ObjectOpenHashMap<LongSet>(leftSize);
    int averageLeftDegree = (int) (rightSize * edgeProbability);
    for (int i = 0; i < leftSize; i++) {
        LongSet nodeEdges = new LongOpenHashSet(averageLeftDegree);
        for (int j = 0; j < rightSize; j++) {
            if (random.nextDouble() < edgeProbability) {
                nodeEdges.add(j);
                if (!rightSideGraph.containsKey(j)) {
                    rightSideGraph.put(j, new LongOpenHashSet(new long[] { i }));
                } else {
                    rightSideGraph.get(j).add(i);
                }
                edges.add(Pair.of((long) i, (long) j));
            }
        }
        leftSideGraph.put(i, nodeEdges);
    }

    // Create a bunch of leftReaders per node that'll read from the graph at random
    for (int i = 0; i < leftSize; i++) {
        for (int j = 0; j < numReadersPerNode; j++) {
            leftReaders.add(new BipartiteGraphReader(graph, new CountDownLatch(0), readersDoneLatch, i, true,
                    random.nextInt(maxWaitingTimeForThreads)));
        }
    }

    // Create a bunch of rightReaders per node that'll read from the graph at random
    for (int i = 0; i < rightSize; i++) {
        for (int j = 0; j < numReadersPerNode; j++) {
            rightReaders.add(new BipartiteGraphReader(graph, new CountDownLatch(0), readersDoneLatch, i, false,
                    random.nextInt(maxWaitingTimeForThreads)));
        }
    }

    // Create a single writer that will insert these edges in random order
    List<WriterInfo> writerInfo = Lists.newArrayListWithCapacity(edges.size());
    List<Pair<Long, Long>> edgesList = Lists.newArrayList(edges);
    Collections.shuffle(edgesList);
    CountDownLatch writerDoneLatch = new CountDownLatch(edgesList.size());
    for (Pair<Long, Long> edge : edgesList) {
        writerInfo.add(new WriterInfo(edge.getLeft(), edge.getRight(), new CountDownLatch(0), writerDoneLatch));
    }

    ExecutorService executor = Executors.newFixedThreadPool(totalNumReaders + 1); // single writer
    List<Callable<Integer>> allThreads = Lists.newArrayListWithCapacity(totalNumReaders + 1);
    // First, we add the writer
    allThreads.add(Executors.callable(new BipartiteGraphWriter(graph, writerInfo), 1));
    // then the readers
    for (int i = 0; i < numLeftReaders; i++) {
        allThreads.add(Executors.callable(leftReaders.get(i), 1));
    }
    for (int i = 0; i < numRightReaders; i++) {
        allThreads.add(Executors.callable(rightReaders.get(i), 1));
    }
    // these will execute in some non-deterministic order
    Collections.shuffle(allThreads, random);

    // Wait for all the processes to finish
    try {
        List<Future<Integer>> results = executor.invokeAll(allThreads, 10, TimeUnit.SECONDS);
        for (Future<Integer> result : results) {
            assertTrue(result.isDone());
            assertEquals(1, result.get().intValue());
        }
    } catch (InterruptedException e) {
        throw new RuntimeException("Execution for a thread was interrupted: ", e);
    } catch (ExecutionException e) {
        throw new RuntimeException("Execution issue in an executor thread: ", e);
    }

    // confirm that these worked as expected
    try {
        readersDoneLatch.await();
        writerDoneLatch.await();
    } catch (InterruptedException e) {
        throw new RuntimeException("Execution for a latch was interrupted: ", e);
    }

    // Check that all readers' read info is consistent with the graph
    // first check the left side
    for (int i = 0; i < numLeftReaders; i++) {
        LongSet expectedLeftEdges = leftSideGraph.get(leftReaders.get(i).queryNode);
        assertTrue(leftReaders.get(i).getQueryNodeDegree() <= expectedLeftEdges.size());
        if (leftReaders.get(i).getQueryNodeDegree() == 0) {
            assertNull(leftReaders.get(i).getQueryNodeEdges());
        } else {
            for (long edge : leftReaders.get(i).getQueryNodeEdges()) {
                assertTrue(expectedLeftEdges.contains(edge));
            }
        }
    }

    // then the right side
    for (int i = 0; i < numRightReaders; i++) {
        LongSet expectedRightEdges = rightSideGraph.get(rightReaders.get(i).queryNode);
        assertTrue(rightReaders.get(i).getQueryNodeDegree() <= expectedRightEdges.size());
        if (rightReaders.get(i).getQueryNodeDegree() == 0) {
            assertNull(rightReaders.get(i).getQueryNodeEdges());
        } else {
            for (long edge : rightReaders.get(i).getQueryNodeEdges()) {
                assertTrue(expectedRightEdges.contains(edge));
            }
        }
    }
}

From source file:com.pinterest.terrapin.base.FutureUtil.java

/**
 * Run speculative execution for a set of futures. This is especially useful for improving latency
 * and surviving failures. The provided BackupFutureRetryPolicy will decide whether the backup
 * future should be fired or not. The 1st future which returns successfully is returned.
 *
 * @param originalFuture The original future which has already been issued.
 * @param functionBackupFuture A function which can issue the backup future once @waitTimeMillis
 *                             has expired.
 * @param waitTimeMillis The time to wait in milliseconds before issuing the backup future.
 * @param statsPrefix The stats prefix to be prefixed with recorded stats such as "won", "lost"
 *                    and "backup-fired".
 * @param retryPolicy decides whether the backup future should be fired if the original future
 *                    fails/*from w ww. j av a2s .c o  m*/
 * @param <T>
 * @return Returns a future which encapsulates the speculative execution strategy.
 */
public static <T> Future<T> getSpeculativeFuture(final Future<T> originalFuture,
        final Function0<Future<T>> functionBackupFuture, long waitTimeMillis, final String statsPrefix,
        final BackupFutureRetryPolicy retryPolicy) {
    return originalFuture.within(Duration.fromMilliseconds(waitTimeMillis), timer)
            .rescue(new Function<Throwable, Future<T>>() {
                public Future<T> apply(Throwable t) {
                    if (retryPolicy.isRetriable(t)) {
                        final Future<T> backupFuture = functionBackupFuture.apply();
                        Stats.incr(statsPrefix + "-backup-fired");
                        // Build information into each future as to whether this is the original
                        // future or the backup future.
                        final Future<Pair<Boolean, T>> originalFutureWithInfo = originalFuture
                                .map(new Function<T, Pair<Boolean, T>>() {
                                    public Pair<Boolean, T> apply(T t) {
                                        return new ImmutablePair(true, t);
                                    }
                                });
                        final Future<Pair<Boolean, T>> backupFutureWithInfo = backupFuture
                                .map(new Function<T, Pair<Boolean, T>>() {
                                    public Pair<Boolean, T> apply(T t) {
                                        return new ImmutablePair(false, t);
                                    }
                                });
                        // If there is an exception, the first future throwing the exception will
                        // return. Instead we want the 1st future which is successful.
                        Future<Pair<Boolean, T>> origFutureSuccessful = originalFutureWithInfo
                                .rescue(new Function<Throwable, Future<Pair<Boolean, T>>>() {
                                    public Future<Pair<Boolean, T>> apply(Throwable t) {
                                        // Fall back to back up future which may also fail in which case we bubble
                                        // up the exception.
                                        return backupFutureWithInfo;
                                    }
                                });
                        Future<Pair<Boolean, T>> backupFutureSuccessful = backupFutureWithInfo
                                .rescue(new Function<Throwable, Future<Pair<Boolean, T>>>() {
                                    public Future<Pair<Boolean, T>> apply(Throwable t) {
                                        // Fall back to original Future which may also fail in which case we bubble
                                        // up the exception.
                                        return originalFutureWithInfo;
                                    }
                                });
                        return origFutureSuccessful.select(backupFutureSuccessful)
                                .map(new Function<Pair<Boolean, T>, T>() {
                                    public T apply(Pair<Boolean, T> tuple) {
                                        if (tuple.getLeft()) {
                                            Stats.incr(statsPrefix + "-won");
                                        } else {
                                            Stats.incr(statsPrefix + "-lost");
                                        }
                                        return tuple.getRight();
                                    }
                                });
                    } else {
                        return Future.exception(t);
                    }
                }
            });
}

From source file:com.streamsets.pipeline.stage.BaseHiveIT.java

/**
 * Validate structure of the result set (column names and types).
 */// w  w w  .  j a  v  a 2s  . c  o  m
public static 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:com.vmware.identity.openidconnect.server.LoginTest.java

private static void assertErrorResponseUsingPersonUserCert(String certHeader, Object certAttribute,
        Cookie cookie, String expectedError) throws Exception {
    Pair<ModelAndView, MockHttpServletResponse> result = doRequestUsingPersonUserCert(certHeader, certAttribute,
            cookie);//  ww w .j  a v  a  2  s .  c om
    ModelAndView modelView = result.getLeft();
    MockHttpServletResponse response = result.getRight();

    Assert.assertNull("modelView", modelView);
    Assert.assertNull("sessionCookie", response.getCookie(SESSION_COOKIE_NAME));
    Assert.assertEquals("status", 401, response.getStatus());
    Assert.assertNotNull("errorResponseHeader", response.getHeader("CastleError"));
    Assert.assertEquals("errorMessage", expectedError, response.getErrorMessage());
}

From source file:com.vmware.identity.openidconnect.server.LoginTest.java

private static void assertSuccessResponseUsingPersonUserCert(String certHeader, Object certAttribute)
        throws Exception {
    Pair<ModelAndView, MockHttpServletResponse> result = doRequestUsingPersonUserCert(certHeader, certAttribute,
            (Cookie) null);//from w w w.j a  v a2  s.c o m
    ModelAndView modelView = result.getLeft();
    MockHttpServletResponse response = result.getRight();

    Assert.assertNull("modelView", modelView);
    validateAuthnSuccessResponse(response, Flow.AUTHZ_CODE, Scope.OPENID, false /* redirectResponseMode */,
            true /* ajaxRequest */, STATE, NONCE);
}

From source file:com.vmware.identity.openidconnect.server.LoginTest.java

private static void assertSuccessResponse(String loginString, String authzHeader) throws Exception {
    Pair<ModelAndView, MockHttpServletResponse> result = doRequest(loginString, authzHeader,
            null /* sessionCookie */, idmClient());
    ModelAndView modelView = result.getLeft();
    MockHttpServletResponse response = result.getRight();
    Assert.assertNull("modelView", modelView);
    validateAuthnSuccessResponse(response, Flow.AUTHZ_CODE, Scope.OPENID, false, true, STATE, NONCE);
}

From source file:com.vmware.identity.openidconnect.server.LoginTest.java

private static void assertErrorResponse(String loginString, String authzHeader, String expectedError,
        String expectedAuthzResponseHeader, String expectedAuthenticateHeader, CasIdmClient idmClient)
        throws Exception {
    Pair<ModelAndView, MockHttpServletResponse> result = doRequest(loginString, authzHeader,
            null /* sessionCookie */, idmClient);
    ModelAndView modelView = result.getLeft();
    MockHttpServletResponse response = result.getRight();
    Assert.assertNull("modelView", modelView);
    Assert.assertNull("sessionCookie", response.getCookie(SESSION_COOKIE_NAME));
    Assert.assertEquals("status", 401, response.getStatus());
    Object errorResponseHeader = response.getHeader("CastleError");
    Assert.assertNotNull("errorResponseHeader", errorResponseHeader);
    Assert.assertEquals("errorMessage", expectedError, response.getErrorMessage());

    if (expectedAuthzResponseHeader != null) {
        Object authzResponseHeader = response.getHeader("CastleAuthorization");
        Assert.assertNotNull("authzResponseHeader", authzResponseHeader);
        Assert.assertEquals("expectedAuthzResponseHeader", expectedAuthzResponseHeader,
                authzResponseHeader.toString());
    }/* w  w w.j a  v  a  2s.c  o  m*/

    if (expectedAuthenticateHeader != null) {
        Object wwwAuthenticateHeader = response.getHeader("WWW-Authenticate");
        Assert.assertNotNull("wwwAuthenticateHeader", wwwAuthenticateHeader);
        Assert.assertEquals("expectedAuthenticateHeader", expectedAuthenticateHeader,
                wwwAuthenticateHeader.toString());
    }
}

From source file:controllers.oer.Application.java

private static Status response(JsonNode json) {
    /* JSONP callback support for remote server calls with JavaScript: */
    final String[] callback = request() == null || request().queryString() == null ? null
            : request().queryString().get("callback");
    Pair<String, Lang> negotiatedContent = negotiateContent(json);
    final Status notAcceptable = status(406, "Not acceptable: unsupported content type requested\n");
    if (invalidAcceptHeader() || negotiatedContent == null)
        return notAcceptable;
    if (callback != null)
        return ok(String.format("%s(%s)", callback[0], negotiatedContent.getLeft()));
    if (negotiatedContent.getRight().equals(Lang.JSONLD))
        return ok(Json.parse(negotiatedContent.getLeft()));
    return ok(negotiatedContent.getLeft());
}

From source file:alfio.manager.CheckInManager.java

public static String decrypt(String key, String payload) {
    try {/*from   w ww . ja va2s . co m*/
        Pair<Cipher, SecretKeySpec> cipherAndSecret = getCypher(key);
        Cipher cipher = cipherAndSecret.getKey();
        String[] splitted = payload.split(Pattern.quote("|"));
        byte[] iv = Base64.decodeBase64(splitted[0]);
        byte[] body = Base64.decodeBase64(splitted[1]);
        cipher.init(Cipher.DECRYPT_MODE, cipherAndSecret.getRight(), new IvParameterSpec(iv));
        byte[] decrypted = cipher.doFinal(body);
        return new String(decrypted, StandardCharsets.UTF_8);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}