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

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

Introduction

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

Prototype

public ImmutableTriple(final L left, final M middle, final R right) 

Source Link

Document

Create a new triple instance.

Usage

From source file:com.boozallen.cognition.ingest.storm.bolt.starter.LineRegexReplaceInRegionBolt.java

void configureRegexRegions(Configuration conf) throws ConfigurationException {
    List<String> regexRegionGroupList = conf.getList(REGEX_REGION_GROUP).stream().map(o -> o.toString())
            .collect(Collectors.toList());
    List<String> regexRegionSearchList = conf.getList(REGEX_REGION_SEARCH).stream().map(o -> o.toString())
            .collect(Collectors.toList());
    List<String> regexRegionReplaceList = conf.getList(REGEX_REGION_REPLACE).stream().map(o -> o.toString())
            .collect(Collectors.toList());

    int groupListSize = regexRegionGroupList.size();
    int searchListSize = regexRegionSearchList.size();
    int replaceListSize = regexRegionReplaceList.size();
    if (!(groupListSize == searchListSize && searchListSize == replaceListSize)) {
        // all lists must be the same size
        throw new ConfigurationException(
                "Error initializing class. All regexRegion lists must be the same size");
    }//w w  w . j a  v a2s  .  com

    groupSearchReplaceList = new ArrayList<>(groupListSize);
    for (int index = 0; index < regexRegionGroupList.size(); index++) {
        Pattern pattern = Pattern.compile(regexRegionGroupList.get(index));
        String regex = regexRegionSearchList.get(index);
        String replacement = regexRegionReplaceList.get(index);

        ImmutableTriple<Pattern, String, String> triple = new ImmutableTriple<>(pattern, regex, replacement);
        groupSearchReplaceList.add(triple);
    }
}

From source file:com.minlia.cloud.framework.test.common.util.SearchIntegrationTestUtil.java

public static <T extends Serializable> void givenResourceExists_whenSearchByStartsWithPartOfLowerCaseNameIsPerformed_thenResourceIsFound(
        final IOperations<T> api, final T newEntity, final SearchField key, final ClientOperation op,
        final String value) {
    final T existingResource = api.create(newEntity);
    final String partOfValue = value.substring(2);

    // When//from  w ww  . j  av a 2 s . c om
    final ImmutableTriple<String, ClientOperation, String> containsConstraint = new ImmutableTriple<String, ClientOperation, String>(
            key.toString(), op, partOfValue);
    final List<T> searchResults = api.searchAll(containsConstraint);

    // Then
    assertThat(searchResults, hasItem(existingResource));
}

From source file:com.mirth.connect.client.ui.codetemplate.CodeTemplateLibrariesPanel.java

public void initialize() {
    PlatformUI.MIRTH_FRAME.codeTemplatePanel.doRefreshCodeTemplates(new ActionListener() {
        @Override//from  w  w  w .  j  a va 2s.co  m
        public void actionPerformed(ActionEvent evt) {
            for (CodeTemplateLibrary library : PlatformUI.MIRTH_FRAME.codeTemplatePanel
                    .getCachedCodeTemplateLibraries().values()) {
                libraryMap.put(library.getId(), new CodeTemplateLibrary(library));
            }
            Map<String, CodeTemplate> codeTemplateMap = PlatformUI.MIRTH_FRAME.codeTemplatePanel
                    .getCachedCodeTemplates();

            DefaultMutableTreeTableNode rootNode = new DefaultMutableTreeTableNode();

            for (CodeTemplateLibrary library : libraryMap.values()) {
                boolean enabled = library.getEnabledChannelIds().contains(channelId)
                        || (library.isIncludeNewChannels()
                                && !library.getDisabledChannelIds().contains(channelId));
                DefaultMutableTreeTableNode libraryNode = new DefaultMutableTreeTableNode(
                        new ImmutableTriple<String, String, Boolean>(library.getId(), library.getName(),
                                enabled));

                for (CodeTemplate codeTemplate : library.getCodeTemplates()) {
                    codeTemplate = codeTemplateMap.get(codeTemplate.getId());
                    if (codeTemplate != null) {
                        libraryNode.add(
                                new DefaultMutableTreeTableNode(new ImmutableTriple<String, String, Boolean>(
                                        codeTemplate.getId(), codeTemplate.getName(), enabled)));
                    }
                }

                rootNode.add(libraryNode);
            }

            ((DefaultTreeTableModel) libraryTreeTable.getTreeTableModel()).setRoot(rootNode);
            libraryTreeTable.expandAll();

            libraryTreeTable.getModel().addTableModelListener(new TableModelListener() {
                @Override
                public void tableChanged(TableModelEvent evt) {
                    for (Enumeration<? extends MutableTreeTableNode> libraryNodes = ((DefaultMutableTreeTableNode) libraryTreeTable
                            .getTreeTableModel().getRoot()).children(); libraryNodes.hasMoreElements();) {
                        Triple<String, String, Boolean> triple = (Triple<String, String, Boolean>) libraryNodes
                                .nextElement().getUserObject();

                        CodeTemplateLibrary library = libraryMap.get(triple.getLeft());
                        if (triple.getRight()) {
                            library.getDisabledChannelIds().remove(channelId);
                            library.getEnabledChannelIds().add(channelId);
                        } else {
                            library.getDisabledChannelIds().add(channelId);
                            library.getEnabledChannelIds().remove(channelId);
                        }
                    }
                }
            });

            parent.codeTemplateLibrariesReady();
        }
    });
}

From source file:com.kakao.hbase.manager.command.ExportKeysTest.java

@Test
public void testRunOptimize() throws Exception {
    String outputFile = "exportkeys_test.keys";

    try {//ww  w. j a  v  a  2  s  . c  o m
        String splitPoint = "splitpoint";

        splitTable(splitPoint.getBytes());

        String[] argsParam = { "zookeeper", tableName, outputFile, "--optimize=1g" };
        Args args = new ManagerArgs(argsParam);
        assertEquals("zookeeper", args.getZookeeperQuorum());
        ExportKeys command = new ExportKeys(admin, args);

        waitForSplitting(2);
        command.run();

        List<Triple<String, String, String>> results = new ArrayList<>();
        for (String keys : Files.readAllLines(Paths.get(outputFile), Constant.CHARSET)) {

            String[] split = keys.split(ExportKeys.DELIMITER);
            results.add(new ImmutableTriple<>(split[0], split[1], split[2]));
        }
        assertEquals(0, results.size());
    } finally {
        Files.delete(Paths.get(outputFile));
    }
}

From source file:com.kakao.hbase.manager.command.ExportKeysTest.java

@Test
public void testRegex() throws Exception {
    String outputFile = "exportkeys_test.keys";

    try {/*from w  ww.jav  a  2s. c o  m*/
        String splitPoint = "splitpoint";
        splitTable(splitPoint.getBytes());
        String tableName2 = createAdditionalTable(tableName + "2");
        splitTable(tableName2, splitPoint.getBytes());

        String tableNameRegex = tableName + ".*";
        String[] argsParam = { "zookeeper", tableNameRegex, outputFile };
        Args args = new ManagerArgs(argsParam);
        assertEquals("zookeeper", args.getZookeeperQuorum());
        ExportKeys command = new ExportKeys(admin, args);

        waitForSplitting(2);
        waitForSplitting(tableName2, 2);
        command.run();

        List<Triple<String, String, String>> results = new ArrayList<>();
        for (String keys : Files.readAllLines(Paths.get(outputFile), Constant.CHARSET)) {

            String[] split = keys.split(ExportKeys.DELIMITER);
            results.add(new ImmutableTriple<>(split[0], split[1], split[2]));
        }
        assertEquals(4, results.size());
    } finally {
        Files.delete(Paths.get(outputFile));
    }
}

From source file:com.minlia.cloud.framework.test.common.service.search.AbstractSearchIntegrationTest.java

@Override
@Test//from  www .j a v a 2 s.co m
public final void givenResourceWithNameDoesNotExist_whenResourceIsSearchedByName_thenResourceIsNotFound() {
    final T existingResource = persistNewEntity();

    // When
    final ImmutableTriple<String, ClientOperation, String> nameConstraint = new ImmutableTriple<String, ClientOperation, String>(
            SearchField.name.toString(), EQ, randomAlphabetic(8));
    final List<T> searchResults = getApi().searchAll(nameConstraint);

    // Then
    assertThat(searchResults, not(hasItem(existingResource)));
}

From source file:blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler.java

public void addBlockData(World world, Connection con) {
    int dimId = world.provider.getDimension();
    if (!blockWireMap.containsItem(dimId))
        blockWireMap.addKey(dimId, new ConcurrentHashMap<>());
    Map<BlockPos, BlockWireInfo> mapForDim = blockWireMap.lookup(dimId);
    if (mapForDim == null || !world.isBlockLoaded(con.end))
        return;/*from   w  w w  .  j av a2 s . c  om*/
    raytraceAlongCatenary(con, world, (p) -> {
        if (!mapForDim.containsKey(p.getLeft()))
            mapForDim.put(p.getLeft(), new BlockWireInfo());
        if (mapForDim.get(p.getLeft()).in.stream().noneMatch((c) -> c.getLeft().hasSameConnectors(con)))
            mapForDim.get(p.getLeft()).in.add(new ImmutableTriple<>(con, p.getMiddle(), p.getRight()));
        return false;
    }, (p) -> {
        if (!mapForDim.containsKey(p.getLeft()))
            mapForDim.put(p.getLeft(), new BlockWireInfo());
        if (mapForDim.get(p.getLeft()).near.stream().noneMatch((c) -> c.getLeft().hasSameConnectors(con)))
            mapForDim.get(p.getLeft()).near.add(new ImmutableTriple<>(con, p.getMiddle(), p.getRight()));
    });
}

From source file:com.hurence.logisland.processor.elasticsearch.EnrichRecordsElasticsearch.java

/**
 * process events//from   w  w  w.j av a  2  s.co  m
 *
 * @param context
 * @param records
 * @return
 */
@Override
public Collection<Record> process(final ProcessContext context, final Collection<Record> records) {
    if (records.size() == 0) {
        return Collections.emptyList();
    }

    List<Triple<Record, String, IncludeFields>> recordsToEnrich = new ArrayList<>();
    MultiGetQueryRecordBuilder mgqrBuilder = new MultiGetQueryRecordBuilder();

    mgqrBuilder.excludeFields(excludesArray);

    for (Record record : records) {

        String recordKeyName = evaluatePropAsString(record, context, RECORD_KEY_FIELD);
        String indexName = evaluatePropAsString(record, context, ES_INDEX_FIELD);
        String typeName = evaluatePropAsString(record, context, ES_TYPE_FIELD);
        String includesFieldName = evaluatePropAsString(record, context, ES_INCLUDES_FIELD);

        if (recordKeyName != null && indexName != null && typeName != null) {
            try {
                // Includes :
                String[] includesArray = null;
                if ((includesFieldName != null) && (!includesFieldName.isEmpty())) {
                    includesArray = includesFieldName.split("\\s*,\\s*");
                }
                IncludeFields includeFields = new IncludeFields(includesArray);
                mgqrBuilder.add(indexName, typeName, includeFields.getAttrsToIncludeArray(), recordKeyName);
                recordsToEnrich.add(new ImmutableTriple(record, asUniqueKey(indexName, typeName, recordKeyName),
                        includeFields));
            } catch (Throwable t) {
                record.setStringField(FieldDictionary.RECORD_ERRORS, "Can not request ElasticSearch with "
                        + indexName + " " + typeName + " " + recordKeyName);
                getLogger().error(
                        "Can not request ElasticSearch with index: {}, type: {}, recordKey: {}, record id is :\n{}",
                        new Object[] { indexName, typeName, recordKeyName, record.getId() }, t);
            }
        } else {
            getLogger().warn(
                    "Can not request ElasticSearch with "
                            + "index: {}, type: {}, recordKey: {}, record id is :\n{}",
                    new Object[] { indexName, typeName, recordKeyName, record.getId() });
        }
    }

    List<MultiGetResponseRecord> multiGetResponseRecords = null;
    try {
        List<MultiGetQueryRecord> mgqrs = mgqrBuilder.build();
        if (mgqrs.isEmpty())
            return records;
        multiGetResponseRecords = elasticsearchClientService.multiGet(mgqrs);
    } catch (InvalidMultiGetQueryRecordException e) {
        getLogger().error("error while multiGet elasticsearch", e);
    }

    if (multiGetResponseRecords == null || multiGetResponseRecords.isEmpty()) {
        return records;
    }

    // Transform the returned documents from ES in a Map
    Map<String, MultiGetResponseRecord> responses = multiGetResponseRecords.stream()
            .collect(Collectors.toMap(EnrichRecordsElasticsearch::asUniqueKey, Function.identity()));

    recordsToEnrich.forEach(recordToEnrich -> {

        Triple<Record, String, IncludeFields> triple = recordToEnrich;
        Record outputRecord = triple.getLeft();
        String key = triple.getMiddle();
        IncludeFields includeFields = triple.getRight();

        MultiGetResponseRecord responseRecord = responses.get(key);
        if ((responseRecord != null) && (responseRecord.getRetrievedFields() != null)) {
            // Retrieve the fields from responseRecord that matches the ones in the recordToEnrich.
            responseRecord.getRetrievedFields().forEach((fieldName, v) -> {
                if (includeFields.includes(fieldName)) {
                    // Now check if there is an attribute mapping rule to apply
                    if (includeFields.hasMappingFor(fieldName)) {
                        String mappedAttributeName = includeFields.getAttributeToMap(fieldName);
                        // Replace the attribute name
                        outputRecord.setStringField(mappedAttributeName, v);
                    } else {
                        outputRecord.setStringField(fieldName, v);
                    }
                }
            });
        }
    });

    return records;
}

From source file:alluxio.master.file.replication.ReplicationChecker.java

private void check(Set<Long> inodes, ReplicationHandler handler, Mode mode) {
    Set<Long> lostBlocks = mBlockMaster.getLostBlocks();
    Set<Triple<AlluxioURI, Long, Integer>> requests = new HashSet<>();
    for (long inodeId : inodes) {
        // TODO(binfan): calling lockFullInodePath locks the entire path from root to the target
        // file and may increase lock contention in this tree. Investigate if we could avoid
        // locking the entire path but just the inode file since this access is read-only.
        try (LockedInodePath inodePath = mInodeTree.lockFullInodePath(inodeId, LockPattern.READ)) {
            InodeFileView file = inodePath.getInodeFile();
            for (long blockId : file.getBlockIds()) {
                BlockInfo blockInfo = null;
                try {
                    blockInfo = mBlockMaster.getBlockInfo(blockId);
                } catch (BlockInfoException e) {
                    // Cannot find this block in Alluxio from BlockMaster, possibly persisted in UFS
                } catch (UnavailableException e) {
                    // The block master is not available, wait for the next heartbeat
                    LOG.warn("The block master is not available: {}", e.getMessage());
                    return;
                }//from   ww w  .  j a  v a 2s  .c o  m
                int currentReplicas = (blockInfo == null) ? 0 : blockInfo.getLocations().size();
                switch (mode) {
                case EVICT:
                    int maxReplicas = file.getReplicationMax();
                    if (file.getPersistenceState() == PersistenceState.TO_BE_PERSISTED
                            && file.getReplicationDurable() > maxReplicas) {
                        maxReplicas = file.getReplicationDurable();
                    }
                    if (currentReplicas > maxReplicas) {
                        requests.add(new ImmutableTriple<>(inodePath.getUri(), blockId,
                                currentReplicas - maxReplicas));
                    }
                    break;
                case REPLICATE:
                    int minReplicas = file.getReplicationMin();
                    if (file.getPersistenceState() == PersistenceState.TO_BE_PERSISTED
                            && file.getReplicationDurable() > minReplicas) {
                        minReplicas = file.getReplicationDurable();
                    }
                    if (currentReplicas < minReplicas) {
                        // if this file is not persisted and block master thinks it is lost, no effort made
                        if (!file.isPersisted() && lostBlocks.contains(blockId)) {
                            continue;
                        }
                        requests.add(new ImmutableTriple<>(inodePath.getUri(), blockId,
                                minReplicas - currentReplicas));
                    }
                    break;
                default:
                    LOG.warn("Unexpected replication mode {}.", mode);
                }
            }
        } catch (FileDoesNotExistException e) {
            LOG.warn("Failed to check replication level for inode id {} : {}", inodeId, e.getMessage());
        }
    }
    for (Triple<AlluxioURI, Long, Integer> entry : requests) {
        AlluxioURI uri = entry.getLeft();
        long blockId = entry.getMiddle();
        int numReplicas = entry.getRight();
        try {
            switch (mode) {
            case EVICT:
                handler.evict(uri, blockId, numReplicas);
                mQuietPeriodSeconds /= 2;
                break;
            case REPLICATE:
                handler.replicate(uri, blockId, numReplicas);
                mQuietPeriodSeconds /= 2;
                break;
            default:
                LOG.warn("Unexpected replication mode {}.", mode);
            }
        } catch (JobDoesNotExistException | ResourceExhaustedException e) {
            LOG.warn("The job service is busy, will retry later. {}", e.toString());
            mQuietPeriodSeconds = (mQuietPeriodSeconds == 0) ? 1
                    : Math.min(MAX_QUIET_PERIOD_SECONDS, mQuietPeriodSeconds * 2);
            return;
        } catch (UnavailableException e) {
            LOG.warn("Unable to complete the replication check: {}, will retry later.", e.getMessage());
            return;
        } catch (Exception e) {
            LOG.warn("Unexpected exception encountered when starting a replication / eviction job (uri={},"
                    + " block ID={}, num replicas={}) : {}", uri, blockId, numReplicas, e.getMessage());
            LOG.debug("Exception: ", e);
        }
    }
}

From source file:com.kakao.hbase.manager.command.ExportKeysTest.java

@Test
public void testRegexAll() throws Exception {
    if (miniCluster) {
        String outputFile = "exportkeys_test.keys";

        try {//from  w w  w  . java2  s. c  o m
            String splitPoint = "splitpoint";
            splitTable(splitPoint.getBytes());
            String tableName2 = createAdditionalTable(tableName + "2");
            splitTable(tableName2, splitPoint.getBytes());

            String[] argsParam = { "zookeeper", ".*", outputFile };
            Args args = new ManagerArgs(argsParam);
            assertEquals("zookeeper", args.getZookeeperQuorum());
            ExportKeys command = new ExportKeys(admin, args);

            waitForSplitting(2);
            waitForSplitting(tableName2, 2);
            command.run();

            List<Triple<String, String, String>> results = new ArrayList<>();
            for (String keys : Files.readAllLines(Paths.get(outputFile), Constant.CHARSET)) {

                String[] split = keys.split(ExportKeys.DELIMITER);
                results.add(new ImmutableTriple<>(split[0], split[1], split[2]));
            }
            assertEquals(4, results.size());
        } finally {
            Files.delete(Paths.get(outputFile));
        }
    }
}