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.streamsets.pipeline.stage.it.MultiplexingIT.java

@Test
public void testMultiplexing() throws Exception {
    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().table("${record:attribute('table')}")
            .partitions(new PartitionConfigBuilder()
                    .addPartition("country", HiveType.STRING, "${record:attribute('country')}")
                    .addPartition("year", HiveType.STRING, "${record:attribute('year')}").build())
            .build();/*from w w  w  . j  a v a  2  s. c o  m*/
    HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();

    // We build stream that have two tables
    List<Record> records = new LinkedList<>();

    Map<String, Field> map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 1));
    map.put("name", Field.create(Field.Type.STRING, "San Francisco"));
    Record record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    record.getHeader().setAttribute("table", "towns");
    record.getHeader().setAttribute("country", "US");
    record.getHeader().setAttribute("year", "2016");
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 1));
    map.put("customer", Field.create(Field.Type.STRING, "Santhosh"));
    map.put("value", Field.create(Field.Type.INTEGER, 200));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    record.getHeader().setAttribute("table", "invoice");
    record.getHeader().setAttribute("country", "India");
    record.getHeader().setAttribute("year", "2015");
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 2));
    map.put("name", Field.create(Field.Type.STRING, "Brno"));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    record.getHeader().setAttribute("table", "towns");
    record.getHeader().setAttribute("country", "CR");
    record.getHeader().setAttribute("year", "2016");
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 2));
    map.put("customer", Field.create(Field.Type.STRING, "Junko"));
    map.put("value", Field.create(Field.Type.INTEGER, 300));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    record.getHeader().setAttribute("table", "invoice");
    record.getHeader().setAttribute("country", "Japan");
    record.getHeader().setAttribute("year", "2015");
    records.add(record);

    processRecords(processor, hiveTarget, records);

    assertTableExists("default.towns");
    assertTableExists("default.invoice");
    assertQueryResult("select * from towns order by id", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            assertResultSetStructure(rs, new ImmutablePair("towns.id", Types.INTEGER),
                    new ImmutablePair("towns.name", Types.VARCHAR),
                    new ImmutablePair("towns.country", Types.VARCHAR),
                    new ImmutablePair("towns.year", Types.VARCHAR));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(1, rs.getLong(1));
            Assert.assertEquals("San Francisco", rs.getString(2));
            Assert.assertEquals("US", rs.getString(3));
            Assert.assertEquals("2016", rs.getString(4));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(2, rs.getLong(1));
            Assert.assertEquals("Brno", rs.getString(2));
            Assert.assertEquals("CR", rs.getString(3));
            Assert.assertEquals("2016", rs.getString(4));

            Assert.assertFalse("Unexpected number of rows", rs.next());
        }
    });
    assertQueryResult("select * from invoice order by id", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            assertResultSetStructure(rs, new ImmutablePair("invoice.id", Types.INTEGER),
                    new ImmutablePair("invoice.customer", Types.VARCHAR),
                    new ImmutablePair("invoice.value", Types.INTEGER),
                    new ImmutablePair("invoice.country", Types.VARCHAR),
                    new ImmutablePair("invoice.year", Types.VARCHAR));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(1, rs.getLong(1));
            Assert.assertEquals("Santhosh", rs.getString(2));
            Assert.assertEquals(200, rs.getLong(3));
            Assert.assertEquals("India", rs.getString(4));
            Assert.assertEquals("2015", rs.getString(5));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(2, rs.getLong(1));
            Assert.assertEquals("Junko", rs.getString(2));
            Assert.assertEquals(300, rs.getLong(3));
            Assert.assertEquals("Japan", rs.getString(4));
            Assert.assertEquals("2015", rs.getString(5));

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

From source file:com.ijuru.kwibuka.WordListWordifier.java

/**
 * Splits the input string all possible ways where the left hand side is a valid word or single digit
 * @param input the input string/*  w w w . j av  a 2 s . c o m*/
 * @return the splits
 */
protected List<Pair<Set<String>, String>> splitInput(String input) {
    List<Pair<Set<String>, String>> splits = new ArrayList<Pair<Set<String>, String>>();

    for (int s = 0; s < input.length(); s++) {
        String left = input.substring(0, s + 1);
        String right = input.substring(s + 1, input.length());

        Set<String> wordsForLeft = words.get(left);

        if (wordsForLeft != null) {
            splits.add(new ImmutablePair<Set<String>, String>(wordsForLeft, right));
        }
    }

    return splits;
}

From source file:com.romeikat.datamessie.core.base.util.CollectionUtil.java

public <T> Collection<Pair<T, T>> getPairsSymmetric(final Collection<T> elements, final boolean addSelfPairs) {
    final List<T> elementsList = new ArrayList<T>(elements);
    final List<Pair<T, T>> pairs = new LinkedList<Pair<T, T>>();
    final int numberOfElements = elementsList.size();
    if (elementsList == null || numberOfElements < 1) {
        return pairs;
    }/*from   w w  w .j  a v a2  s.  c  o m*/
    for (int i = 0; i < numberOfElements; i++) {
        final T element1 = elementsList.get(i);
        if (addSelfPairs) {
            pairs.add(new ImmutablePair<T, T>(element1, element1));
        }
        for (int j = 0; j < numberOfElements; j++) {
            if (i != j) {
                final T element2 = elementsList.get(j);
                pairs.add(new ImmutablePair<T, T>(element1, element2));
            }
        }
    }
    return pairs;
}

From source file:io.cloudslang.lang.compiler.validator.matcher.DescriptionPatternMatcher.java

public Pair<String, String> getDescriptionVariableLineDataDeclarationOnly(String input) {
    List<String> matches = getData(descriptionVariableLineDeclarationOnlyPattern, input,
            Regex.DESCRIPTION_VARIABLE_LINE_DECLARATION_ONLY_GROUP_NR);
    return new ImmutablePair<>(matches.get(0), "");
}

From source file:fr.lirmm.graphik.graal.forward_chaining.ChaseWithGRDAndUnfiers.java

@Override
public void next() throws ChaseException {
    Rule rule, unifiedRule;/*from w ww  .  jav a2  s .c o  m*/
    Substitution unificator;

    try {
        Pair<Rule, Substitution> pair = queue.poll();
        if (pair != null) {
            unificator = pair.getRight();
            rule = pair.getLeft();
            unifiedRule = Unifier.computeInitialAtomSetTermsSubstitution(rule.getBody()).createImageOf(rule);
            unifiedRule = unificator.createImageOf(unifiedRule);

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Execute rule: " + rule + " with unificator " + unificator);
            }

            if (this.getRuleApplier().apply(unifiedRule, this.atomSet)) {
                for (Integer e : this.grd.getOutgoingEdgesOf(rule)) {
                    Rule triggeredRule = this.grd.getEdgeTarget(e);
                    for (Substitution u : this.grd.getUnifiers(e)) {
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("-- -- Dependency: " + triggeredRule + " with " + u);
                            LOGGER.debug("-- -- Unificator: " + u);
                        }
                        if (u != null) {
                            this.queue.add(new ImmutablePair<Rule, Substitution>(triggeredRule, u));
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new ChaseException("An error occur pending saturation step.", e);
    }
}

From source file:main.java.metric.Metric.java

public static void initServerSet(Cluster cluster) {

    ICombinatoricsVector<Integer> initialVector = Factory.createVector(cluster.getServerSet());
    Generator<Integer> gen = Factory.createSimpleCombinationGenerator(initialVector, 2);

    for (ICombinatoricsVector<Integer> combination : gen) {

        int s_a_id = combination.getValue(0);
        int s_b_id = combination.getValue(1);

        Pair<Integer, Integer> pair1 = new ImmutablePair<Integer, Integer>(s_a_id, s_b_id);
        Pair<Integer, Integer> pair2 = new ImmutablePair<Integer, Integer>(s_b_id, s_a_id);

        mutually_exclusive_serverSets.put(pair1, 0);
        mutually_exclusive_serverSets.put(pair2, 0);
    }//from   w w w . j a v a  2 s. c  om

    // Testing
    //System.out.println(mutually_exclusive_serverSets);
}

From source file:com.pinterest.terrapin.client.TerrapinClientTest.java

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    hostNameClientMap = new ImmutableMap.Builder().put(HOST1, mockClient1).put(HOST2, mockClient2)
            .put(HOST3, mockClient3).build();
    terrapinClient = new TestTerrapinClient(mockFsViewManager).setHostNameClientMap(hostNameClientMap);

    ViewInfo viewInfo = createViewInfo((Map) ImmutableMap.of(HOST1, ImmutableList.of("0", "1", "3"), HOST2,
            ImmutableList.of("1", "2"), HOST3, ImmutableList.of("2", "3")));

    FileSetInfo fsInfo = new FileSetInfo();
    fsInfo.fileSetName = FILE_SET;/*  w w w  .jav  a2s .co m*/
    fsInfo.oldServingInfoList = Lists.newArrayList();
    fsInfo.deleted = false;
    fsInfo.numVersionsToKeep = 1;
    fsInfo.servingInfo = new FileSetInfo.ServingInfo("", RESOURCE, 4, PartitionerType.MODULUS);

    when(mockFsViewManager.getFileSetViewInfo(eq(FILE_SET))).thenReturn(new ImmutablePair(fsInfo, viewInfo));
    setUpResponseForHost("host1",
            (Map) ImmutableMap.of("0", ImmutableMap.of("a", "value_a"), "1", ImmutableMap.of("b", "value_b")),
            (Map) Maps.newHashMap());
    setUpResponseForHost("host2", (Map) ImmutableMap.of("2", ImmutableMap.of("c", "value_c")),
            (Map) ImmutableMap.of("1", ImmutableMap.of("b", TerrapinGetErrorCode.READ_ERROR)));
    setUpResponseForHost("host3",
            (Map) ImmutableMap.of("2", ImmutableMap.of("c", "value_c"), "3", ImmutableMap.of("d", "value_d")),
            (Map) ImmutableMap.of("3", ImmutableMap.of("h", TerrapinGetErrorCode.OTHER)));
}

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

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

    Map<String, Field> map = new LinkedHashMap<>();
    map.put("col", field);
    Record record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    try {//from  ww w .ja v a 2s  .co m
        processRecords(processor, hiveTarget, ImmutableList.of(record));
        if (!supported) {
            Assert.fail("Type is not supported, but yet no exception was thrown");
        }
    } catch (StageException se) {
        if (supported) {
            LOG.error("Processing exception", se);
            Assert.fail("Processing testing record unexpectedly failed: " + se.getMessage());
            throw se;
        } else {
            Assert.assertEquals(Errors.HIVE_19, se.getErrorCode());
            // No additional verification necessary
            return;
        }
    }

    assertTableExists("default.tbl");
    assertQueryResult("select * from tbl", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            assertResultSetStructure(rs, new ImmutablePair("tbl.col", hiveType),
                    new ImmutablePair("tbl.dt", Types.VARCHAR));

            Assert.assertTrue("Table tbl doesn't contain any rows", rs.next());
            Assert.assertEquals(null, rs.getObject(1));
            Assert.assertFalse("Table tbl contains more then one row", rs.next());
        }
    });
}

From source file:com.hortonworks.streamline.streams.metrics.topology.service.TopologyMetricsService.java

public List<Pair<String, Double>> getTopNAndOtherComponentsLatency(Topology topology, String asUser,
        int nOfTopN) throws IOException {
    TopologyMetrics topologyMetrics = getTopologyMetricsInstance(topology);
    Map<String, TopologyMetrics.ComponentMetric> metricsForTopology = topologyMetrics
            .getMetricsForTopology(CatalogToLayoutConverter.getTopologyLayout(topology), asUser);

    List<Pair<String, Double>> topNAndOther = new ArrayList<>();

    List<ImmutablePair<String, Double>> latencyOrderedComponents = metricsForTopology.entrySet().stream()
            .map((x) -> new ImmutablePair<>(x.getValue().getComponentName(), x.getValue().getProcessedTime()))
            // reversed sort
            .sorted((c1, c2) -> {//from  www .j a  v  a2s  . c  om
                if (c2.getValue() == null) {
                    // assuming c1 is bigger
                    return -1;
                } else {
                    return c2.getValue().compareTo(c1.getValue());
                }
            }).collect(toList());

    latencyOrderedComponents.stream().limit(nOfTopN).forEachOrdered(topNAndOther::add);
    double sumLatencyOthers = latencyOrderedComponents.stream().skip(nOfTopN)
            .filter((x) -> x.getValue() != null).mapToDouble(Pair::getValue).sum();

    topNAndOther.add(new ImmutablePair<>("Others", sumLatencyOthers));

    return topNAndOther;
}

From source file:io.pravega.controller.eventProcessor.impl.SerializedRequestHandler.java

@VisibleForTesting
List<Pair<T, CompletableFuture<Void>>> getEventQueueForKey(String key) {
    List<Pair<T, CompletableFuture<Void>>> retVal = null;

    synchronized (lock) {
        if (workers.containsKey(key)) {
            retVal = workers.get(key).stream().map(x -> new ImmutablePair<>(x.getEvent(), x.getResult()))
                    .collect(Collectors.toList());
        }// ww  w. j a v  a 2 s  .  c o  m
    }

    return retVal;
}