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:at.beris.virtualfile.shell.Shell.java

private boolean commandArgumentsValid(Pair<Command, List<String>> cmd) {
    StringBuilder sb = new StringBuilder();
    Command cmdOp = cmd.getLeft();//from  w  w  w . ja  va 2s.  c  o m
    int[] expectedArgCounts = cmdOp.getArgumentCounts();
    List<String> actualArgs = cmd.getRight();

    sb.append("Wrong number of arguments for Command ").append(cmdOp.toString().toLowerCase())
            .append(". Expected ");

    boolean argCountMatches = false;
    for (int expectedArgCount : expectedArgCounts) {
        if (expectedArgCount == actualArgs.size())
            argCountMatches = true;
        sb.append(expectedArgCount).append(" or ");
    }
    sb.delete(sb.length() - 4, sb.length()).append(".");

    if (!argCountMatches)
        System.out.println(sb.toString());

    return argCountMatches;
}

From source file:com.norconex.importer.handler.transformer.impl.StripBetweenTransformer.java

@Override
protected void transformStringContent(String reference, StringBuilder content, ImporterMetadata metadata,
        boolean parsed, boolean partialContent) {
    int flags = Pattern.DOTALL | Pattern.UNICODE_CASE;
    if (!caseSensitive) {
        flags = flags | Pattern.CASE_INSENSITIVE;
    }/* w w w  .j  a  v a  2s.c  o m*/
    for (Pair<String, String> pair : stripPairs) {
        List<Pair<Integer, Integer>> matches = new ArrayList<Pair<Integer, Integer>>();
        Pattern leftPattern = Pattern.compile(pair.getLeft(), flags);
        Matcher leftMatch = leftPattern.matcher(content);
        while (leftMatch.find()) {
            Pattern rightPattern = Pattern.compile(pair.getRight(), flags);
            Matcher rightMatch = rightPattern.matcher(content);
            if (rightMatch.find(leftMatch.end())) {
                if (inclusive) {
                    matches.add(new ImmutablePair<Integer, Integer>(leftMatch.start(), rightMatch.end()));
                } else {
                    matches.add(new ImmutablePair<Integer, Integer>(leftMatch.end(), rightMatch.start()));
                }
            } else {
                break;
            }
        }
        for (int i = matches.size() - 1; i >= 0; i--) {
            Pair<Integer, Integer> matchPair = matches.get(i);
            content.delete(matchPair.getLeft(), matchPair.getRight());
        }
    }
}

From source file:com.streamsets.pipeline.stage.origin.mongodb.oplog.MongoDBOplogSourceIT.java

@Test
public void testReadFromOffset() throws Exception {
    MongoDBOplogSource source = new MongoDBOplogSourceBuilder()
            .connectionString("mongodb://" + mongoContainerIp + ":" + mongoContainerMappedPort)
            .collection(OPLOG_COLLECTION).initialTs(initialTs).initialOrdinal(0).build();
    SourceRunner runner = new SourceRunner.Builder(MongoDBSource.class, source).addOutputLane(LANE).build();
    MongoCursor<Document> cursor = mongoCursorFindIterable
            .filter(Filters.and(Filters.gt(MongoDBOplogSource.TIMESTAMP_FIELD, new BsonTimestamp(initialTs, 0)),
                    Filters.or(Filters.eq(MongoDBOplogSource.OP_TYPE_FIELD, OplogOpType.INSERT.getOp()),
                            Filters.eq(MongoDBOplogSource.OP_TYPE_FIELD, OplogOpType.UPDATE.getOp()),
                            Filters.eq(MongoDBOplogSource.OP_TYPE_FIELD, OplogOpType.DELETE.getOp()),
                            Filters.eq(MongoDBOplogSource.OP_TYPE_FIELD, OplogOpType.CMD.getOp()),
                            Filters.eq(MongoDBOplogSource.OP_TYPE_FIELD, OplogOpType.NOOP.getOp()),
                            Filters.eq(MongoDBOplogSource.OP_TYPE_FIELD, OplogOpType.DB.getOp()))))
            .iterator();//from w w  w .  j  a v a  2s . c  o  m
    //Insert 3 testDocuments
    Document document1 = new Document("d", 1);
    Document document2 = new Document("d", 2);
    Document document3 = new Document("d", 3);
    testDocuments.insertMany(Arrays.asList(document1, document2, document3));

    runner.runInit();
    String offset = "";
    List<Record> records;
    try {
        Pair<String, List<Record>> runOp = runSourceAndGetOp(runner, offset);
        records = runOp.getRight();
        //Persist offset from this run and use it.
        offset = runOp.getLeft();
        Assert.assertEquals(3, records.size());
        for (Record record : records) {
            checkRecord(record, cursor.tryNext());
            checkRecordForFields(record, OplogOpType.INSERT.getOp(), DATABASE + "." + testCollectionName);
        }
    } finally {
        runner.runDestroy();
    }

    //Now update the testDocuments by incrementing the field value of d by 1 for first 2 testDocuments
    UpdateResult updateResult = testDocuments.updateMany(Filters.lt("d", 3),
            new Document("$inc", new Document("c", 1)));
    Assert.assertEquals(2, updateResult.getModifiedCount());

    //Recreate runner and source but use the previous offset
    source = new MongoDBOplogSourceBuilder()
            .connectionString("mongodb://" + mongoContainerIp + ":" + mongoContainerMappedPort)
            //No initial offset (ts/ordinal)
            .collection(OPLOG_COLLECTION).filterOlogOpTypeFilter(Collections.singletonList(OplogOpType.UPDATE))
            .build();
    runner = new SourceRunner.Builder(MongoDBSource.class, source).addOutputLane(LANE).build();
    runner.runInit();
    try {
        Pair<String, List<Record>> runOp = runSourceAndGetOp(runner, offset);
        records = runOp.getRight();
        Assert.assertEquals(2, records.size());
        for (Record record : records) {
            checkRecord(record, cursor.tryNext());
            checkRecordForFields(record, OplogOpType.UPDATE.getOp(), DATABASE + "." + testCollectionName);
        }
    } finally {
        runner.runDestroy();
        cursor.close();
    }
}

From source file:com.wolvereness.overmapped.OverMapped.java

private void writeToFile(final MultiProcessor executor, final Map<String, ByteClass> byteClasses,
        final List<Pair<ZipEntry, byte[]>> fileEntries, final BiMap<String, String> nameMaps,
        final BiMap<Signature, Signature> signatureMaps, final Map<Signature, Integer> flags)
        throws IOException, FileNotFoundException, InterruptedException, ExecutionException {
    final Collection<Future<Pair<ZipEntry, byte[]>>> classWrites = newArrayList();
    for (final ByteClass clazz : byteClasses.values()) {
        classWrites.add(//from  w  w w.  j  a  v  a 2 s .  c o m
                executor.submit(clazz.callable(signatureMaps, nameMaps, byteClasses, flags, correctEnums)));
    }

    FileOutputStream fileOut = null;
    JarOutputStream jar = null;
    try {
        jar = new JarOutputStream(fileOut = new FileOutputStream(output));
        for (final Pair<ZipEntry, byte[]> fileEntry : fileEntries) {
            jar.putNextEntry(fileEntry.getLeft());
            jar.write(fileEntry.getRight());
        }
        for (final Future<Pair<ZipEntry, byte[]>> fileEntryFuture : classWrites) {
            final Pair<ZipEntry, byte[]> fileEntry = fileEntryFuture.get();
            jar.putNextEntry(fileEntry.getLeft());
            jar.write(fileEntry.getRight());
        }
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (final IOException ex) {
            }
        }
        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (final IOException ex) {
            }
        }
    }
}

From source file:com.mtbs3d.minecrift.control.GuiScreenNaviator.java

private float dist(Pair<Integer, Integer> a, Pair<Integer, Integer> b, float xScale, float yScale) {
    float x = xScale * (a.getLeft() - b.getLeft());
    float y = yScale * (a.getRight() - b.getRight());
    return (float) Math.sqrt(x * x + y * y);
}

From source file:models.Search.java

private void initResults() {
    Pair<List<Document>, Long> result = doSearch();
    this.documents = result.getLeft();
    this.hitCount = result.getRight();
}

From source file:ee.ria.xroad.proxy.testsuite.MessageTestCase.java

/**
 * Performs the request and validates the response.
 * @throws Exception in case of any unexpected errors
 *//*  w ww  .  j  av a 2  s  .  co  m*/
public void execute() throws Exception {
    startUp();
    generateQueryId();

    CloseableHttpAsyncClient client = getClient();
    client.start();

    // Request input stream is read twice, once for recording,
    // second time for HTTP request.
    Pair<String, InputStream> requestInput = getRequestInput(false);

    try (InputStream is = requestInput.getRight()) {
        sentRequest = new Message(is, requestInput.getLeft()).parse();
    }

    AsyncHttpSender sender = new AsyncHttpSender(client);
    // Needed by some test cases
    sender.addHeader(HEADER_HASH_ALGO_ID, DEFAULT_DIGEST_ALGORITHM_ID);

    // Get the input again.
    requestInput = getRequestInput(addUtf8BomToRequestFile);

    try (InputStream is = requestInput.getRight()) {
        for (Entry<String, String> e : requestHeaders.entrySet()) {
            sender.addHeader(e.getKey(), e.getValue());
        }

        if ("post".equalsIgnoreCase(httpMethod)) {
            sender.doPost(getClientUri(), is, CHUNKED_LENGTH, requestInput.getLeft());
        } else {
            sender.doGet(getClientUri());
        }

        sender.waitForResponse(DEFAULT_CLIENT_TIMEOUT);
    }

    try {
        receivedResponse = extractResponse(sender);

        if (sentRequest != null && sentRequest.getSoap() != null
                && sentRequest.getSoap() instanceof SoapMessageImpl) {
            sentResponse = receivedResponse;
        }
    } finally {
        sender.close();
        client.close();
        closeDown();
    }

    if (failed) {
        throw new Exception("Test failed in previous stage");
    }

    if (receivedResponse.getSoap() != null) {
        log.debug("Validating SOAP message\n{}", receivedResponse.getSoap().getXml());
    }

    if (receivedResponse.isFault()) {
        log.debug("Validating fault: {}, {}", ((SoapFault) receivedResponse.getSoap()).getCode(),
                ((SoapFault) receivedResponse.getSoap()).getString());
        validateFaultResponse(receivedResponse);
        return;
    }

    if (!receivedResponse.isResponse()) {
        throw new Exception("Received SOAP message is not a response");
    }

    if (sentResponse != null && !checkConsistency(sentResponse, receivedResponse)) {
        throw new Exception("Received response is not the same as sent response");
    }

    log.debug("Validating normal response");
    validateNormalResponse(receivedResponse);
}

From source file:com.mirth.connect.server.migration.ServerMigrator.java

private void runConfigurationMigrator(ConfigurationMigrator configurationMigrator,
        PropertiesConfiguration mirthConfig, Version version) {
    configurationMigrator.updateConfiguration(mirthConfig);

    HashMap<String, Object> addedProperties = new LinkedHashMap<String, Object>();
    Map<String, Object> propertiesToAdd = configurationMigrator.getConfigurationPropertiesToAdd();

    if (propertiesToAdd != null) {
        for (Entry<String, Object> propertyToAdd : propertiesToAdd.entrySet()) {
            if (!mirthConfig.containsKey(propertyToAdd.getKey())) {
                PropertiesConfigurationLayout layout = mirthConfig.getLayout();
                String key = propertyToAdd.getKey();
                Object value;//from  w ww .j a v  a 2 s  .co  m
                String comment = "";

                if (propertyToAdd.getValue() instanceof Pair) {
                    // If a pair is used, get both the value and comment
                    Pair<Object, String> pair = (Pair<Object, String>) propertyToAdd.getValue();
                    value = pair.getLeft();
                    comment = pair.getRight();
                } else {
                    // Only the value was specified
                    value = propertyToAdd.getValue();
                }

                mirthConfig.setProperty(key, value);

                // If this is the first added property, add a general comment about the added properties before it
                if (addedProperties.isEmpty()) {
                    if (StringUtils.isNotEmpty(comment)) {
                        comment = "\n\n" + comment;
                    }
                    comment = "The following properties were automatically added on startup for version "
                            + version + comment;
                }

                if (StringUtils.isNotEmpty(comment)) {
                    // When a comment is specified, always put a blank line before it
                    layout.setBlancLinesBefore(key, 1);
                    layout.setComment(key, comment);
                }

                addedProperties.put(key, value);
            }
        }
    }

    List<String> removedProperties = new ArrayList<String>();
    String[] propertiesToRemove = configurationMigrator.getConfigurationPropertiesToRemove();

    if (propertiesToRemove != null) {
        for (String propertyToRemove : propertiesToRemove) {
            if (mirthConfig.containsKey(propertyToRemove)) {
                mirthConfig.clearProperty(propertyToRemove);
                removedProperties.add(propertyToRemove);
            }
        }
    }

    if (!addedProperties.isEmpty() || !removedProperties.isEmpty()) {
        if (!addedProperties.isEmpty()) {
            logger.info("Adding properties in mirth.properties: " + addedProperties);
        }

        if (!removedProperties.isEmpty()) {
            logger.info("Removing properties in mirth.properties: " + removedProperties);
        }

        try {
            mirthConfig.save();
        } catch (ConfigurationException e) {
            logger.error("There was an error updating mirth.properties.", e);

            if (!addedProperties.isEmpty()) {
                logger.error("The following properties should be added to mirth.properties manually: "
                        + addedProperties.toString());
            }

            if (!removedProperties.isEmpty()) {
                logger.error("The following properties should be removed from mirth.properties manually: "
                        + removedProperties.toString());
            }
        }
    }
}

From source file:de.hasait.clap.impl.CLAPClassNode.java

@Override
public void printUsage(final Map<CLAPUsageCategoryImpl, StringBuilder> pCategories,
        final CLAPUsageCategoryImpl pCurrentCategory, final StringBuilder pResult) {
    final Pair<CLAPUsageCategoryImpl, StringBuilder> pair = handleUsageCategory(pCategories, pCurrentCategory,
            pResult);//from   w w  w  .j  a v  a2 s  .com
    if (pair != null) {
        final CLAPUsageCategoryImpl currentCategory = pair.getLeft();
        final StringBuilder result = pair.getRight();
        internalPrintUsage(pCategories, currentCategory, result, " "); //$NON-NLS-1$
    }
}

From source file:com.devicehive.resource.impl.DeviceCommandResourceImpl.java

private void poll(final long timeout, final String deviceGuidsCsv, final String namesCsv,
        final String timestamp, final AsyncResponse asyncResponse) throws InterruptedException {
    final HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();/* w w w .  j a va2s . c o m*/

    final Date ts = TimestampQueryParamParser
            .parse(timestamp == null ? timestampService.getDateAsString() : timestamp);

    final Response response = ResponseFactory.response(Response.Status.OK, Collections.emptyList(),
            JsonPolicyDef.Policy.COMMAND_LISTED);

    asyncResponse.setTimeoutHandler(asyncRes -> asyncRes.resume(response));

    Set<String> availableDevices;
    if (deviceGuidsCsv == null) {
        availableDevices = deviceService.findByGuidWithPermissionsCheck(Collections.emptyList(), principal)
                .stream().map(DeviceVO::getGuid).collect(Collectors.toSet());

    } else {
        availableDevices = Optional.ofNullable(StringUtils.split(deviceGuidsCsv, ',')).map(Arrays::asList)
                .map(list -> deviceService.findByGuidWithPermissionsCheck(list, principal))
                .map(list -> list.stream().map(DeviceVO::getGuid).collect(Collectors.toSet()))
                .orElse(Collections.emptySet());
    }

    Set<String> names = Optional.ofNullable(StringUtils.split(namesCsv, ',')).map(Arrays::asList)
            .map(list -> list.stream().collect(Collectors.toSet())).orElse(Collections.emptySet());

    BiConsumer<DeviceCommand, String> callback = (command, subscriptionId) -> {
        if (!asyncResponse.isDone()) {
            asyncResponse.resume(ResponseFactory.response(Response.Status.OK, Collections.singleton(command),
                    Policy.COMMAND_LISTED));
        }
    };

    if (!availableDevices.isEmpty()) {
        Pair<String, CompletableFuture<List<DeviceCommand>>> pair = commandService
                .sendSubscribeRequest(availableDevices, names, ts, callback);
        pair.getRight().thenAccept(collection -> {
            if (!collection.isEmpty() && !asyncResponse.isDone()) {
                asyncResponse.resume(
                        ResponseFactory.response(Response.Status.OK, collection, Policy.COMMAND_LISTED));
            }

            if (timeout == 0) {
                asyncResponse.setTimeout(1, TimeUnit.MILLISECONDS); // setting timeout to 0 would cause
                // the thread to suspend indefinitely, see AsyncResponse docs
            } else {
                asyncResponse.setTimeout(timeout, TimeUnit.SECONDS);
            }
        });

        asyncResponse.register(new CompletionCallback() {
            @Override
            public void onComplete(Throwable throwable) {
                commandService.sendUnsubscribeRequest(pair.getLeft(), null);
            }
        });
    } else {
        if (!asyncResponse.isDone()) {
            asyncResponse.resume(response);
        }
    }

}