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.qq.tars.service.monitor.TARSStatMonitorService.java

private MultiKeyMap call(List<String> groupBy, List<String> conditions) throws IOException {
    String template = "{\"groupby\":%s,\"method\":\"query\",\"dataid\":\"tars_stat\","
            + "\"filter\":%s,\"indexs\":[\"succ_count\",\"timeout_count\",\"exce_count\",\"total_time\"]}";

    ObjectMapper mapper = new ObjectMapper();
    String request = String.format(template, mapper.writeValueAsString(groupBy),
            mapper.writeValueAsString(conditions));

    List<Pair<String, Integer>> addrs = adminService.getEndpoints("tars.tarsquerystat.NoTarsObj");
    if (addrs.isEmpty()) {
        throw new IOException("tars.tarsquerystat.NoTarsObj not found");
    }/* w w  w.j  a v a 2 s.co  m*/

    Pair<String, Integer> addr = addrs.get(0);
    log.info("tars.tarsquerystat.NoTarsObj, use {}:{}", addr.getLeft(), addr.getRight());

    TCPClient client = new TCPClient(addr.getLeft(), addr.getRight());
    List<String> response = client.sendAndReceive(request.getBytes(), 60000);

    log.debug("request={}", request);
    log.debug("reponse={}", StringUtils.join(response, "\n"));

    String line1 = response.get(0);
    if (!line1.startsWith("Ret:")) {
        throw new IOException(String.format("line #1, doesn't start with \"Ret:\", line=%s", line1));
    }
    int ret = Integer.parseInt(line1.substring(line1.lastIndexOf(':') + 1));
    if (ret == -1) {
        throw new IOException(String.format("line #1, Ret=%s", ret));
    }

    String line6 = response.get(5);
    if (!line6.startsWith("linecount:")) {
        throw new IOException(String.format("line #6, doesn't start with \"linecount:\", line=%s", line6));
    }
    int count = Integer.parseInt(line6.substring(line6.lastIndexOf(':') + 1));
    if (count + 7 != response.size()) {
        throw new IOException(String.format("line #6, size not match, %s vs %s", count + 7, response.size()));
    }

    String lastLine = response.get(response.size() - 1);
    if (!"endline".equals(lastLine)) {
        throw new IOException(
                String.format("line #%s, doesn't equal to \"endline\", line=%s", response.size(), lastLine));
    }

    MultiKeyMap result = new MultiKeyMap();
    for (int i = 6; i < response.size() - 1; i++) {
        String line = StringUtils.removeEnd(response.get(i), ",");
        String[] tokens = line.split(",");
        if (tokens.length != groupBy.size() + 4) {
            throw new IOException(String.format("line format error, line=%s", line));
        }

        String[] key = new String[groupBy.size()];
        int j = 0;
        for (; j < key.length; j++) {
            key[j] = tokens[j];
        }

        long[] value = new long[] { Long.parseLong(tokens[j++]), Long.parseLong(tokens[j++]),
                Long.parseLong(tokens[j++]), Long.parseLong(tokens[j]) };
        result.put(new MultiKey(key), value);
    }
    return result;
}

From source file:com.devicehive.websockets.handlers.CommandHandlers.java

@PreAuthorize("isAuthenticated() and hasPermission(null, 'GET_DEVICE_COMMAND')")
public WebSocketResponse processCommandSubscribe(JsonObject request, WebSocketSession session)
        throws InterruptedException {
    HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();//w  w  w .j  av  a  2s  .  co m
    final Date timestamp = gson.fromJson(request.get(TIMESTAMP), Date.class);
    final String deviceId = Optional.ofNullable(request.get(Constants.DEVICE_GUID))
            .map(JsonElement::getAsString).orElse(null);
    final Set<String> names = gson.fromJson(request.getAsJsonArray(NAMES), JsonTypes.STRING_SET_TYPE);
    Set<String> devices = gson.fromJson(request.getAsJsonArray(DEVICE_GUIDS), JsonTypes.STRING_SET_TYPE);

    logger.debug("command/subscribe requested for devices: {}, {}. Timestamp: {}. Names {} Session: {}",
            devices, deviceId, timestamp, names, session);

    devices = prepareActualList(devices, deviceId);

    List<DeviceVO> actualDevices;
    if (devices != null) {
        actualDevices = deviceService.findByGuidWithPermissionsCheck(devices, principal);
        if (actualDevices.size() != devices.size()) {
            throw new HiveException(String.format(Messages.DEVICES_NOT_FOUND, devices), SC_FORBIDDEN);
        }
    } else {
        actualDevices = deviceService
                .list(null, null, null, null, null, null, null, true, null, null, principal).join();
        devices = actualDevices.stream().map(DeviceVO::getGuid).collect(Collectors.toSet());
    }

    BiConsumer<DeviceCommand, String> callback = (command, subscriptionId) -> {
        JsonObject json = ServerResponsesFactory.createCommandInsertMessage(command, subscriptionId);
        sendMessage(json, session);
    };

    Pair<String, CompletableFuture<List<DeviceCommand>>> pair = commandService.sendSubscribeRequest(devices,
            names, timestamp, callback);

    pair.getRight().thenAccept(collection -> collection
            .forEach(cmd -> sendMessage(ServerResponsesFactory.createCommandInsertMessage(cmd, pair.getLeft()),
                    session)));

    logger.debug("command/subscribe done for devices: {}, {}. Timestamp: {}. Names {} Session: {}", devices,
            deviceId, timestamp, names, session.getId());

    ((CopyOnWriteArraySet) session.getAttributes().get(SUBSCSRIPTION_SET_NAME)).add(pair.getLeft());

    WebSocketResponse response = new WebSocketResponse();
    response.addValue(SUBSCRIPTION_ID, pair.getLeft(), null);
    return response;
}

From source file:com.formkiq.core.util.StringsTest.java

/**
 * testExtractLabelAndValue03()./* w  w  w . j  a  v a2s  . c o  m*/
 */
@Test
public void testExtractLabelAndValue03() {
    // given
    String s = null;

    // when
    Pair<String, String> results = Strings.extractLabelAndValue(s);

    // then
    assertEquals("", results.getLeft());
    assertEquals("", results.getRight());
}

From source file:com.act.lcms.plotter.WriteAndPlotMS1Results.java

private List<String> writeFeedMS1Values(List<Pair<Double, List<XZ>>> ms1s, Double maxIntensity, OutputStream os)
        throws IOException {
    // Write data output to outfile
    PrintStream out = new PrintStream(os);

    List<String> plotID = new ArrayList<>(ms1s.size());
    for (Pair<Double, List<XZ>> ms1ForFeed : ms1s) {
        Double feedingConcentration = ms1ForFeed.getLeft();
        List<XZ> ms1 = ms1ForFeed.getRight();

        plotID.add(String.format("concentration: %5e", feedingConcentration));
        // print out the spectra to outDATA
        for (XZ xz : ms1) {
            out.format("%.4f\t%.4f\n", xz.getTime(), xz.getIntensity());
            out.flush();//from w  w  w. ja  va  2s.  c  om
        }
        // delimit this dataset from the rest
        out.print("\n\n");
    }

    return plotID;
}

From source file:com.google.uzaygezen.core.hbase.HBaseQueryTest.java

public List<int[]> fullScanQuery(int[][] data, SpaceFillingCurve sfc, int[][] ranges) {
    MultiDimensionalSpec spec = sfc.getSpec();
    List<Integer> filtered = filter(data, ranges);
    List<Pair<BitVector, Integer>> pairs = new ArrayList<>(filtered.size());
    BitVector[] point = new BitVector[spec.getBitsPerDimension().size()];
    for (int j = 0; j < spec.getBitsPerDimension().size(); ++j) {
        point[j] = BitVectorFactories.OPTIMAL.apply(spec.getBitsPerDimension().get(j));
    }/*from ww w .java 2 s .com*/
    for (int i : filtered) {
        BitVector index = BitVectorFactories.OPTIMAL.apply(spec.sumBitsPerDimension());
        // int has 32 bits, which fits in each dimensions.
        for (int j = 0; j < spec.getBitsPerDimension().size(); ++j) {
            point[j].copyFrom(data[i][j]);
        }
        sfc.index(point, 0, index);
        pairs.add(Pair.of(index.clone(), i));
    }
    // Sort by Hilbert index.
    Collections.sort(pairs);
    List<int[]> expected = new ArrayList<>(pairs.size());
    for (Pair<BitVector, Integer> pair : pairs) {
        expected.add(data[pair.getRight()]);
    }
    return expected;
}

From source file:com.romeikat.datamessie.core.processing.service.stemming.text.TextStemmer.java

private String replaceNamedEntity(final SharedSessionContract ssc, final String textUnderStemming,
        final String namedEntityName) {
    // Determine replacement
    final Pair<String, String> replacingAndReplacement = getReplacingAndReplacement(ssc, namedEntityName);
    if (replacingAndReplacement == null) {
        return textUnderStemming;
    }//from   w  w w  . j  av a2s. c o  m

    final String replacing = replacingAndReplacement.getLeft();
    final String replacement = replacingAndReplacement.getRight();

    // Do the replacement (to whole words only)
    final String result = textUtil.replaceAllAsWholeWord(textUnderStemming, replacing, replacement);

    // Done
    return result;
}

From source file:com.twentyn.patentSearch.Searcher.java

private List<Triple<Float, String, String>> executeQuery(Pair<IndexReader, IndexSearcher> readerSearcher,
        BooleanQuery query) throws UncheckedIOException {
    TopDocs topDocs;//  ww w.  j a va 2s .c  o m
    try {
        topDocs = readerSearcher.getRight().search(query, MAX_RESULTS_PER_QUERY);
    } catch (IOException e) {
        LOGGER.error("Caught IO exception when trying to run search for %s: %s", query, e.getMessage());
        /* Wrap `e` in an unchecked exception to allow it to escape our call stack.  The top level function with catch
         * and rethrow it as a normal IOException. */
        throw new UncheckedIOException(e);
    }

    ScoreDoc[] scoreDocs = topDocs.scoreDocs;
    if (scoreDocs.length == 0) {
        LOGGER.debug("Search returned no results.");
        return Collections.emptyList();
    }
    // ScoreDoc just contains a score and an id.  We need to retrieve the documents' content using that id.

    /* Crux of the next bit:
     * Filter by score and convert from scoreDocs to document features.
     * No need to use `limit` here since we already had Lucene cap the result set size. */
    return Arrays.stream(scoreDocs).filter(scoreDoc -> scoreDoc.score >= scoreThreshold).map(scoreDoc -> { //
        try {
            Pair<String, String> features = this
                    .extractDocFeatures(readerSearcher.getLeft().document(scoreDoc.doc));
            // Put the score first so the natural sort order is based on score.
            return Triple.of(scoreDoc.score, features.getLeft(), features.getRight());
        } catch (IOException e) {
            // Yikes, this is v. bad.
            LOGGER.error("Caught IO exception when trying to read doc id %d: %s", scoreDoc.doc, e.getMessage());
            throw new UncheckedIOException(e); // Same as above.
        }
    }).collect(Collectors.toList());
}

From source file:com.yahoo.pulsar.common.naming.NamespaceBundlesTest.java

@Test
public void testSplitBundleInTwo() throws Exception {
    final int NO_BUNDLES = 2;
    NamespaceName nsname = new NamespaceName("pulsar/global/ns1");
    DestinationName dn = DestinationName.get("persistent://pulsar/global/ns1/topic-1");
    NamespaceBundles bundles = factory.getBundles(nsname);
    NamespaceBundle bundle = bundles.findBundle(dn);
    // (1) split : [0x00000000,0xffffffff] => [0x00000000_0x7fffffff,0x7fffffff_0xffffffff]
    Pair<NamespaceBundles, List<NamespaceBundle>> splitBundles = factory.splitBundles(bundle, NO_BUNDLES);
    assertNotNull(splitBundles);//from  w  w w.ja v a2s. c  om
    assertBundleDivideInTwo(bundle, splitBundles.getRight(), NO_BUNDLES);

    // (2) split: [0x00000000,0x7fffffff] => [0x00000000_0x3fffffff,0x3fffffff_0x7fffffff],
    // [0x7fffffff,0xffffffff] => [0x7fffffff_0xbfffffff,0xbfffffff_0xffffffff]
    NamespaceBundleFactory utilityFactory = NamespaceBundleFactory.createFactory(Hashing.crc32());
    assertBundles(utilityFactory, nsname, bundle, splitBundles, NO_BUNDLES);

    // (3) split: [0x00000000,0x3fffffff] => [0x00000000_0x1fffffff,0x1fffffff_0x3fffffff],
    // [0x3fffffff,0x7fffffff] => [0x3fffffff_0x5fffffff,0x5fffffff_0x7fffffff]
    Pair<NamespaceBundles, List<NamespaceBundle>> splitChildBundles = splitBundlesUtilFactory(utilityFactory,
            nsname, splitBundles.getLeft(), splitBundles.getRight().get(0), NO_BUNDLES);
    assertBundles(utilityFactory, nsname, splitBundles.getRight().get(0), splitChildBundles, NO_BUNDLES);

    // (4) split: [0x7fffffff,0xbfffffff] => [0x7fffffff_0x9fffffff,0x9fffffff_0xbfffffff],
    // [0xbfffffff,0xffffffff] => [0xbfffffff_0xdfffffff,0xdfffffff_0xffffffff]
    splitChildBundles = splitBundlesUtilFactory(utilityFactory, nsname, splitBundles.getLeft(),
            splitBundles.getRight().get(1), NO_BUNDLES);
    assertBundles(utilityFactory, nsname, splitBundles.getRight().get(1), splitChildBundles, NO_BUNDLES);

}

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

public HttpResponse process() {
    ClientID clientId;//  www  .  j av  a2  s .c  o  m
    URI postLogoutRedirectUri;
    LogoutErrorResponse parseErrorResponse;
    try {
        this.logoutRequest = LogoutRequest.parse(this.httpRequest);
        clientId = this.logoutRequest.getClientID();
        postLogoutRedirectUri = this.logoutRequest.getPostLogoutRedirectURI();
        parseErrorResponse = null;
    } catch (LogoutRequest.ParseException e) {
        if (e.getClientID() != null && e.getPostLogoutRedirectURI() != null
                && e.createLogoutErrorResponse() != null) {
            clientId = e.getClientID();
            postLogoutRedirectUri = e.getPostLogoutRedirectURI();
            parseErrorResponse = e.createLogoutErrorResponse();
        } else {
            LoggerUtils.logFailedRequest(logger, e.getErrorObject(), e);
            return HttpResponse.createErrorResponse(e.getErrorObject());
        }
    }

    try {
        if (this.tenant == null) {
            this.tenant = this.tenantInfoRetriever.getDefaultTenantName();
        }
        this.tenantInfo = this.tenantInfoRetriever.retrieveTenantInfo(this.tenant);
        this.clientInfo = this.clientInfoRetriever.retrieveClientInfo(this.tenant, clientId);
        if (!this.clientInfo.getPostLogoutRedirectURIs().contains(postLogoutRedirectUri)) {
            throw new ServerException(ErrorObject.invalidRequest("unregistered post_logout_redirect_uri"));
        }
    } catch (ServerException e) {
        LoggerUtils.logFailedRequest(logger, e);
        return HttpResponse.createErrorResponse(e.getErrorObject());
    }

    if (parseErrorResponse != null) {
        LoggerUtils.logFailedRequest(logger, parseErrorResponse.getErrorObject());
        return parseErrorResponse.toHttpResponse();
    }

    try {
        authenticateClient();

        Pair<LogoutSuccessResponse, Cookie> result = processInternal();
        LogoutSuccessResponse logoutSuccessResponse = result.getLeft();
        Cookie personUserCertificateLoggedOutCookie = result.getRight();

        HttpResponse httpResponse = logoutSuccessResponse.toHttpResponse();
        httpResponse.addCookie(loggedOutSessionCookie());
        if (personUserCertificateLoggedOutCookie != null) {
            httpResponse.addCookie(personUserCertificateLoggedOutCookie);
        }
        return httpResponse;
    } catch (ServerException e) {
        LoggerUtils.logFailedRequest(logger, e);
        LogoutErrorResponse logoutErrorResponse = new LogoutErrorResponse(
                this.logoutRequest.getPostLogoutRedirectURI(), this.logoutRequest.getState(),
                e.getErrorObject());
        return logoutErrorResponse.toHttpResponse();
    }
}

From source file:com.formkiq.core.util.StringsTest.java

/**
 * testExtractLabelAndValue01().//from   w  ww  .  jav  a2 s. co m
 */
@Test
public void testExtractLabelAndValue01() {
    // given
    String s = "name[1]";

    // when
    Pair<String, String> results = Strings.extractLabelAndValue(s);

    // then
    assertEquals("name", results.getLeft());
    assertEquals("1", results.getRight());
}