Example usage for org.apache.commons.lang3.tuple ImmutablePair ImmutablePair

List of usage examples for org.apache.commons.lang3.tuple ImmutablePair ImmutablePair

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple ImmutablePair ImmutablePair.

Prototype

public ImmutablePair(final L left, final R right) 

Source Link

Document

Create a new pair instance.

Usage

From source file:com.joyent.manta.http.ApacheHttpHeaderUtils.java

/**
 * In order to be sure we're continuing to download the same object we need to extract the {@code ETag} and {@code
 * Content-Range} headers from the response. Either header missing is an error. Additionally, when the {@code
 * Content-Range} header is present the specified range should be equal to the response's {@code Content-Length}.
 * If the {@code Content-Range} header is missing and {@code allowContentRangeInference} is true, we may infer the
 * response code was 200 and construct a representative {@code Content-Range} from byte offset 0 to
 * {@code Content-Length - 1}.//from  w ww.j  a va 2s  . c om
 *
 * @param response the response to check for headers
 * @param allowContentRangeInference whether or not we can derive a {@link HttpRange.Response} from the
 * {@code Content-Length} header instead of only using it for verification.
 * @return the request headers we're concerned with validating
 * @throws ProtocolException when the headers are malformed, unparseable, or the {@code
 * Content-Range} and {@code Content-Length} are mismatched
 */
static Pair<String, HttpRange.Response> extractDownloadResponseFingerprint(final HttpResponse response,
        final boolean allowContentRangeInference) throws ProtocolException {

    final String etag = extractSingleHeaderValue(response, ETAG, true);

    final long contentLength;
    try {
        final String rawContentLength = extractSingleHeaderValue(response, CONTENT_LENGTH, true);
        // since we're passing required=true an ProtocolException would be thrown and
        // @SuppressWarnings("ConstantConditions") is too blunt a hammer and would apply to the whole method, so...
        // noinspection ConstantConditions
        contentLength = Long.parseUnsignedLong(rawContentLength);
    } catch (final NumberFormatException e) {
        throw new ProtocolException(
                String.format("Failed to parse Content-Length response, matching headers: %s",
                        Arrays.deepToString(response.getHeaders(CONTENT_LENGTH))));
    }

    final String rawContentRange = extractSingleHeaderValue(response, CONTENT_RANGE, false);

    if (StringUtils.isBlank(rawContentRange)) {
        if (!allowContentRangeInference) {
            throw new ProtocolException("Content-Range header required but missing.");
        }

        // the entire object is being requested
        return new ImmutablePair<>(etag, new HttpRange.Response(0, contentLength - 1, contentLength));
    }

    final HttpRange.Response contentRange = parseContentRange(rawContentRange);

    // Manta follows the spec and sends the Content-Length of the range, which we should ensure matches
    if (contentRange.contentLength() != contentLength) {
        throw new ProtocolException(String.format(
                "Content-Range start-to-end size and Content-Length mismatch: expected [%d], got [%d]",
                contentRange.contentLength(), contentLength));
    }

    return new ImmutablePair<>(etag, contentRange);
}

From source file:com.kantenkugel.discordbot.modules.AutoRespond.java

private String intConfig(String cfgString, ServerConfig cfg, MessageEvent event) {
    if (cfgString == null) {
        return getUsage();
    }/* w  w w  .  j a  v a 2 s.  com*/
    String[] split = cfgString.split("\\s+", 2);
    if (split.length < 2) {
        return getUsage();
    }
    switch (split[0].toLowerCase()) {
    case "add":
        Matcher matcher = addPattern.matcher(split[1]);
        if (matcher.matches() && matcher.group(2).trim().length() > 0) {
            Set<String> keys = new HashSet<>();
            Collections.addAll(keys, matcher.group(2).toLowerCase().split("\\s+"));
            responses.put(matcher.group(1).toLowerCase(), new ImmutablePair<>(keys, matcher.group(3)));
            cfg.save();
            return "Response " + matcher.group(1).toLowerCase() + " added.";
        }
        break;
    case "remove":
    case "del":
        if (responses.containsKey(split[1].toLowerCase())) {
            responses.remove(split[1].toLowerCase());
            cfg.save();
            return "Response " + split[1].toLowerCase() + " removed.";
        } else {
            return "Response " + split[1].toLowerCase() + " not found!";
        }
    case "channels":
        String[] split2 = split[1].split("\\s+", 2);
        if (split2.length == 2) {
            switch (split2[0].toLowerCase()) {
            case "add":
                if (event.getMessage().getMentionedChannels().size() > 0) {
                    event.getMessage().getMentionedChannels().forEach(c -> channels.add(c.getId()));
                    cfg.save();
                    return "Channel(s) added.";
                }
                Optional<TextChannel> any = event.getGuild().getTextChannels().parallelStream()
                        .filter(tc -> tc.getName().equals(split2[1])).findAny();
                if (any.isPresent()) {
                    channels.add(any.get().getId());
                    cfg.save();
                    return "Channel " + split2[1] + " added.";
                } else {
                    return "Channel " + split2[1] + " not found!";
                }
            case "del":
            case "remove":
                if (event.getMessage().getMentionedChannels().size() > 0) {
                    event.getMessage().getMentionedChannels().forEach(c -> channels.remove(c.getId()));
                    cfg.save();
                    return "Channel(s) removed.";
                }
                Optional<TextChannel> any2 = event.getGuild().getTextChannels().parallelStream()
                        .filter(tc -> tc.getName().equals(split2[1])).findAny();
                if (any2.isPresent()) {
                    if (channels.contains(any2.get().getId())) {
                        channels.remove(any2.get().getId());
                        cfg.save();
                        return "Channel " + split2[1] + " removed.";
                    } else {
                        return "Channel " + split2[1] + " was not added!";
                    }
                } else {
                    return "Channel " + split2[1] + " not found!";
                }
            }
        }
        break;
    }
    return getUsage();
}

From source file:com.nextdoor.bender.operation.substitution.regex.RegexSubstitution.java

/**
 * Matches a regex against a field and extracts matching groups.
 * //from  www.java  2 s.  c o  m
 * @param devent
 * @param config
 * @return
 * @throws FieldNotFoundException
 */
private Pair<String, Map<String, Object>> getRegexMatches(DeserializedEvent devent)
        throws FieldNotFoundException {
    String foundSourceField = null;
    Matcher matcher = null;

    for (String sourceField : this.srcFields) {
        String sourceValue;
        try {
            sourceValue = devent.getFieldAsString(sourceField);
        } catch (FieldNotFoundException e) {
            continue;
        }

        matcher = pattern.matcher(sourceValue);

        if (matcher.find()) {
            /*
             * Keep track of the field name that we use so it can be removed later.
             */
            foundSourceField = sourceField;
            break;
        }
    }

    if (foundSourceField == null) {
        throw new FieldNotFoundException("unable to find field in: " + this.srcFields);
    }

    /*
     * Go through each match group in the field config and attempt to add that match group from the
     * regex match. If field type coercion does not succeed then field is skipped.
     */
    Map<String, Object> matchedGroups = new HashMap<String, Object>(matcher.groupCount());
    try {
        for (RegexSubField field : this.fields) {
            String matchStrVal = matcher.group(field.getRegexGroupName());

            if (matchStrVal == null) {
                continue;
            }

            switch (field.getType()) {
            case BOOLEAN:
                matchedGroups.put(field.getKey(), Boolean.parseBoolean(matchStrVal));
                break;
            case NUMBER:
                matchedGroups.put(field.getKey(), NumberUtils.createNumber(matchStrVal));
                break;
            case STRING:
                matchedGroups.put(field.getKey(), matchStrVal);
                break;
            default:
                matchedGroups.put(field.getKey(), matchStrVal);
                break;
            }
        }
    } catch (NumberFormatException e) {
        throw new FieldNotFoundException("matched field is not a number");
    }

    return new ImmutablePair<String, Map<String, Object>>(foundSourceField, matchedGroups);
}

From source file:com.streamsets.pipeline.stage.it.DriftIT.java

@Test
public void testRenameColumn() throws Exception {
    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().build();
    HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();

    List<Record> records = new LinkedList<>();

    Map<String, Field> map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 1));
    map.put("old_column", Field.create(Field.Type.STRING, "old_value"));
    Record record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);/*from w  w  w. j av  a 2 s .  c o m*/

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 2));
    map.put("new_column", Field.create(Field.Type.STRING, "new_value"));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    processRecords(processor, hiveTarget, records);

    assertQueryResult("select * from tbl order by id", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            assertResultSetStructure(rs, new ImmutablePair("tbl.id", Types.INTEGER),
                    new ImmutablePair("tbl.old_column", Types.VARCHAR),
                    new ImmutablePair("tbl.new_column", Types.VARCHAR),
                    new ImmutablePair("tbl.dt", Types.VARCHAR));

            Assert.assertTrue("Table tbl doesn't contain any rows", rs.next());
            Assert.assertEquals(1, rs.getLong(1));
            Assert.assertEquals("old_value", rs.getString(2));
            Assert.assertEquals(null, rs.getString(3));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(2, rs.getLong(1));
            Assert.assertEquals(null, rs.getString(2));
            Assert.assertEquals("new_value", rs.getString(3));

            Assert.assertFalse("Unexpected number of rows", rs.next());
        }
    });
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.KubernetesV2SearchProvider.java

private Map<String, List<String>> getKeysRelatedToLogicalMatches(String matchQuery) {
    return logicalTypes.stream().map(type -> cacheUtils.getAllDataMatchingPattern(type, matchQuery).stream()
            .map(e -> e.getRelationships().values().stream().flatMap(Collection::stream)
                    .filter(Objects::nonNull).map(k -> new ImmutablePair<>(k, e.getId())))
            .flatMap(x -> x)).flatMap(x -> x)
            .collect(Collectors.groupingBy(Pair::getLeft, Collectors.reducing(Collections.emptyList(),
                    i -> Collections.singletonList(i.getRight()), (a, b) -> {
                        List<String> res = new ArrayList<>();
                        res.addAll(a);//from   ww w  .j ava  2  s  .  c  o  m
                        res.addAll(b);
                        return res;
                    })));
}

From source file:it.unibo.alchemist.model.implementations.environments.AbstractEnvironment.java

private ListSet<Node<T>> getAllNodesInRange(final Position center, final double range) {
    if (range <= 0) {
        throw new IllegalArgumentException("Range query must be positive (provided: " + range + ")");
    }//from   w  ww  .  j  av  a 2s.c  o m
    if (cache == null) {
        cache = Caffeine.newBuilder().maximumSize(1000).build(pair -> runQuery(pair.left, pair.right));
    }
    return cache.get(new ImmutablePair<>(center, range));
}

From source file:com.hurence.logisland.processor.MatchIP.java

@Override
protected void updateMatchingRules(ProcessContext context) {
    // loop over dynamic properties to add rules
    for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        if (!entry.getKey().isDynamic()) {
            continue;
        }//from   ww  w  .  j  a  v  a 2s  .  c o m

        final String name = entry.getKey().getName();
        final String query = entry.getValue();
        String[] params = query.split(":", 2);
        if (params.length == 2) {
            String queryField = params[0];
            String luceneQuery;
            String luceneValue;
            String ipValue = params[1];
            Matcher ipMatcher = ipPattern.matcher(ipValue);
            Matcher cidrMatcher = cidrPattern.matcher(ipValue);
            if (ipMatcher.lookingAt()) {
                // This is a static ip address
                // convert it to a long
                long addr = ipToLong(ipValue);
                luceneValue = String.valueOf(addr);
                luceneQuery = queryField + ":" + luceneValue;
                matchingRules.put(name, new MatchingRule(name, luceneQuery, query));
                luceneAttrsToQuery.add(queryField);
            } else if (cidrMatcher.lookingAt()) {
                // This is a cidr
                // Convert it to a range
                SubnetUtils su = new SubnetUtils(ipValue);
                String lowIp = su.getInfo().getLowAddress();
                String highIp = su.getInfo().getHighAddress();
                long lowIpLong = ipToLong(lowIp);
                long highIpLong = ipToLong(highIp);
                luceneValue = "[ " + String.valueOf(lowIpLong) + " TO " + String.valueOf(highIpLong) + " ]";
                luceneQuery = queryField + ":" + luceneValue;
                matchingRules.put(name, new MatchingRule(name, luceneQuery, query));
                luceneAttrsToQuery.add(queryField);
            } else {
                regexpMatchingRules.put(name, new MatchingRule(name, query));
                // Consider the value to be a regexp
                // To Be Done
                Pattern ipRegexp = Pattern.compile(ipValue);
                if (ipRegexps == null) {
                    ipRegexps = new HashMap<>();
                }
                if (ipRegexps.containsKey(queryField)) {
                    HashSet<Pair<String, Pattern>> regexpVals = ipRegexps.get(queryField);
                    regexpVals.add(new ImmutablePair<>(name, ipRegexp));
                    ipRegexps.put(queryField, regexpVals);
                } else {
                    HashSet<Pair<String, Pattern>> regexpVals = new HashSet<>();
                    regexpVals.add(new org.apache.commons.lang3.tuple.ImmutablePair<>(name, ipRegexp));
                    ipRegexps.put(queryField, regexpVals);
                }
            }
        }
    }
}

From source file:com.ottogroup.bi.streaming.operator.json.insert.JsonStaticContentInsertionTest.java

/**
 * Test case for {@link JsonStaticContentInsertion#map(JSONObject)} with valid configuration provided during instantiation
 *///  w ww  . j  av  a 2s  .com
@Test
public void testMap_withValidInsertionConfiguration() throws Exception {
    Assert.assertTrue(MatchJSONContent.create().assertString("test", Matchers.is("value"))
            .assertString("valid", Matchers.is("test"))
            .matchOnSingle(new JsonStaticContentInsertion(
                    Arrays.asList(new ImmutablePair<JsonContentReference, Serializable>(
                            new JsonContentReference(new String[] { "valid" }, JsonContentType.STRING),
                            "test"))).map(new JSONObject("{\"test\":\"value\"}"))));
}

From source file:com.hortonworks.streamline.streams.runtime.rule.sql.SqlBasicExprScriptTest.java

@Test
public void testBasicAggregation() throws Exception {
    // SELECT STREAM DEPTID, EMPID, MIN(SALARY) FROM FOO where ID > 0 GROUP BY DEPTID, EMPID

    Expression min_salary = new AggregateFunctionExpression("MIN",
            ImmutableList.of(new FieldExpression(Schema.Field.of("salary", Schema.Type.INTEGER))));

    Expression deptid = new FieldExpression(Schema.Field.of("deptid", Schema.Type.INTEGER));
    Expression empid = new FieldExpression(Schema.Field.of("empid", Schema.Type.INTEGER));
    GroupBy groupBy = new GroupBy(ImmutableList.of(deptid, empid));
    Expression id = new FieldExpression(Schema.Field.of("id", Schema.Type.INTEGER));
    Expression id_gt_0 = new BinaryExpression(Operator.GREATER_THAN, id, new Literal("0"));
    Condition condition = new Condition();
    condition.setExpression(id_gt_0);//from   ww  w  .  j  a  va2 s. co  m

    Projection projection = new Projection();
    projection.setExpressions(ImmutableList.<Expression>of(deptid, empid, min_salary));

    sqlScript = new SqlScript(new StormSqlExpression(condition, projection, groupBy, null), new SqlEngine(),
            new SqlScript.CorrelatedValuesToStreamlineEventConverter(
                    Lists.newArrayList("deptid", "empid", "MIN")));

    // (100, 100), 10
    Map<String, Object> kv1 = new HashMap<>();
    kv1.put("id", 1);
    kv1.put("deptid", 100);
    kv1.put("empid", 100);
    kv1.put("salary", 10);

    // (100, 100), 5
    Map<String, Object> kv2 = new HashMap<>();
    kv2.put("id", 2);
    kv2.put("deptid", 100);
    kv2.put("empid", 100);
    kv2.put("salary", 5);

    // (101, 101), 10
    Map<String, Object> kv3 = new HashMap<>();
    kv3.put("id", 3);
    kv3.put("deptid", 101);
    kv3.put("empid", 101);
    kv3.put("salary", 10);

    // (102, 102), 5
    Map<String, Object> kv4 = new HashMap<>();
    kv4.put("id", 4);
    kv4.put("deptid", 102);
    kv4.put("empid", 102);
    kv4.put("salary", 5);

    StreamlineEvent group1Event1 = StreamlineEventImpl.builder().fieldsAndValues(kv1).dataSourceId("1").build();
    StreamlineEvent group1Event2 = StreamlineEventImpl.builder().fieldsAndValues(kv2).dataSourceId("1").build();
    StreamlineEvent group2Event1 = StreamlineEventImpl.builder().fieldsAndValues(kv3).dataSourceId("1").build();
    StreamlineEvent group3Event1 = StreamlineEventImpl.builder().fieldsAndValues(kv4).dataSourceId("1").build();

    sqlScript.evaluate(group1Event1);
    sqlScript.evaluate(group1Event2);
    sqlScript.evaluate(group2Event1);
    sqlScript.evaluate(group3Event1);
    Collection<StreamlineEvent> result = sqlScript.evaluate(StreamlineEventImpl.GROUP_BY_TRIGGER_EVENT);

    Assert.assertEquals(3, result.size());

    Map<List<Integer>, Pair<Integer, Set<String>>> expectedGroupValueToMinAndParentIds;
    expectedGroupValueToMinAndParentIds = new HashMap<>();
    expectedGroupValueToMinAndParentIds.put(Lists.newArrayList(100, 100),
            new ImmutablePair<>(5, Sets.newHashSet(group1Event1.getId(), group1Event2.getId())));
    expectedGroupValueToMinAndParentIds.put(Lists.newArrayList(101, 101),
            new ImmutablePair<>(10, Sets.newHashSet(group2Event1.getId())));
    expectedGroupValueToMinAndParentIds.put(Lists.newArrayList(102, 102),
            new ImmutablePair<>(5, Sets.newHashSet(group3Event1.getId())));

    result.iterator().forEachRemaining(res -> {
        List<Integer> groupValue = Lists.newArrayList((Integer) res.get("deptid"), (Integer) res.get("empid"));
        Assert.assertTrue(expectedGroupValueToMinAndParentIds.containsKey(groupValue));
        Pair<Integer, Set<String>> minAndPairIds = expectedGroupValueToMinAndParentIds.get(groupValue);
        Integer minValue = (Integer) res.get("MIN");
        Assert.assertEquals(minValue, minAndPairIds.getLeft());

        Assert.assertTrue(EventCorrelationInjector.containsParentIds(res));
        Assert.assertEquals(minAndPairIds.getRight(), EventCorrelationInjector.getParentIds(res));

        // avoid matching multiple times
        expectedGroupValueToMinAndParentIds.remove(groupValue);
    });
}

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

@Override
protected Pair<List<File>, List<File>> createWorkingFiles(@NonNull SolutionPerJob solutionPerJob)
        throws IOException {
    Pair<List<File>, List<File>> returnValue;

    List<File> jsimgFileList = retrieveInputFiles(solutionPerJob, ".jsimg");

    final String experiment = String.format("%s, class %s, provider %s, VM %s, # %d",
            solutionPerJob.getParentID(), solutionPerJob.getId(), dataProcessor.getProviderName(),
            solutionPerJob.getTypeVMselected().getId(), solutionPerJob.getNumberVM());

    if (jsimgFileList.isEmpty()) {
        logger.debug(String.format("Generating QN model for %s", experiment));
        usingInputModel = false;// w  ww  .  ja  v  a2 s  . com
        returnValue = generateQNModel(solutionPerJob);
    } else {
        logger.debug(String.format("Using input QN model for %s", experiment));
        usingInputModel = true;

        // TODO now it just takes the first file, I would expect a single file per list
        File inputJsimgFile = jsimgFileList.get(0);

        final String prefix = buildPrefix(solutionPerJob);

        Map<String, String> jsimgFilePlaceholders = new TreeMap<>();
        jsimgFilePlaceholders.put("@@CORES@@",
                Long.toUnsignedString(solutionPerJob.getNumberContainers().longValue()));
        jsimgFilePlaceholders.put("@@CONCURRENCY@@",
                Long.toUnsignedString(solutionPerJob.getNumberUsers().longValue()));
        List<String> outcomes = processPlaceholders(inputJsimgFile, jsimgFilePlaceholders);

        File jsimgFile = fileUtility.provideTemporaryFile(prefix, ".jsimg");
        writeLinesToFile(outcomes, jsimgFile);

        List<File> model = new ArrayList<>(1);
        model.add(jsimgFile);
        returnValue = new ImmutablePair<>(model, new ArrayList<>());
    }

    return returnValue;
}