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:alluxio.web.WebInterfaceWorkerBlockInfoServlet.java

/**
 * Populates attributes before redirecting to a jsp.
 *
 * @param request the {@link HttpServletRequest} object
 * @param response the {@link HttpServletResponse} object
 * @throws ServletException if the target resource throws this exception
 * @throws IOException if the target resource throws this exception
 *//*from  w w w  .  j  a  va  2 s .c o m*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("fatalError", "");
    String filePath = request.getParameter("path");
    if (!(filePath == null || filePath.isEmpty())) {
        // Display file block info
        try {
            UIFileInfo uiFileInfo = getUiFileInfo(new AlluxioURI(filePath));
            List<ImmutablePair<String, List<UIFileBlockInfo>>> fileBlocksOnTier = new ArrayList<>();
            for (Entry<String, List<UIFileBlockInfo>> e : uiFileInfo.getBlocksOnTier().entrySet()) {
                fileBlocksOnTier.add(new ImmutablePair<>(e.getKey(), e.getValue()));
            }
            request.setAttribute("fileBlocksOnTier", fileBlocksOnTier);
            request.setAttribute("blockSizeBytes", uiFileInfo.getBlockSizeBytes());
            request.setAttribute("path", filePath);
            getServletContext().getRequestDispatcher("/worker/viewFileBlocks.jsp").forward(request, response);
            return;
        } catch (FileDoesNotExistException e) {
            request.setAttribute("fatalError", "Error: Invalid Path " + e.getMessage());
            getServletContext().getRequestDispatcher("/worker/blockInfo.jsp").forward(request, response);
            return;
        } catch (IOException e) {
            request.setAttribute("invalidPathError",
                    "Error: File " + filePath + " is not available " + e.getMessage());
            getServletContext().getRequestDispatcher("/worker/blockInfo.jsp").forward(request, response);
            return;
        } catch (BlockDoesNotExistException e) {
            request.setAttribute("fatalError", "Error: block not found. " + e.getMessage());
            getServletContext().getRequestDispatcher("/worker/blockInfo.jsp").forward(request, response);
            return;
        } catch (AlluxioException e) {
            request.setAttribute("fatalError", "Error: alluxio exception. " + e.getMessage());
            getServletContext().getRequestDispatcher("/worker/blockInfo.jsp").forward(request, response);
            return;
        }
    }

    List<Long> fileIds = getSortedFileIds();
    request.setAttribute("nTotalFile", fileIds.size());

    request.setAttribute("orderedTierAliases", new WorkerStorageTierAssoc().getOrderedStorageAliases());

    // URL can not determine offset and limit, let javascript in jsp determine and redirect
    if (request.getParameter("offset") == null && request.getParameter("limit") == null) {
        getServletContext().getRequestDispatcher("/worker/blockInfo.jsp").forward(request, response);
        return;
    }

    try {
        int offset = Integer.parseInt(request.getParameter("offset"));
        int limit = Integer.parseInt(request.getParameter("limit"));
        List<Long> subFileIds = fileIds.subList(offset, offset + limit);
        List<UIFileInfo> uiFileInfos = new ArrayList<>(subFileIds.size());
        for (long fileId : subFileIds) {
            try {
                uiFileInfos.add(getUiFileInfo(fileId));
            } catch (IOException e) {
                // The file might have been deleted, log a warning and ignore this file.
                LOG.warn("Unable to get file info for fileId {}. {}", fileId, e.getMessage());
            }
        }
        request.setAttribute("fileInfos", uiFileInfos);
    } catch (FileDoesNotExistException e) {
        request.setAttribute("fatalError", "Error: Invalid FileId " + e.getMessage());
        getServletContext().getRequestDispatcher("/worker/blockInfo.jsp").forward(request, response);
        return;
    } catch (NumberFormatException e) {
        request.setAttribute("fatalError", "Error: offset or limit parse error, " + e.getLocalizedMessage());
        getServletContext().getRequestDispatcher("/worker/blockInfo.jsp").forward(request, response);
        return;
    } catch (IndexOutOfBoundsException e) {
        request.setAttribute("fatalError",
                "Error: offset or offset + limit is out of bound, " + e.getLocalizedMessage());
        getServletContext().getRequestDispatcher("/worker/blockInfo.jsp").forward(request, response);
        return;
    } catch (IllegalArgumentException | AlluxioException e) {
        request.setAttribute("fatalError", e.getLocalizedMessage());
        getServletContext().getRequestDispatcher("/worker/blockInfo.jsp").forward(request, response);
        return;
    }

    getServletContext().getRequestDispatcher("/worker/blockInfo.jsp").forward(request, response);
}

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

public ChaseWithGRDAndUnfiers(GraphOfRuleDependencies grd, AtomSet atomSet) {
    super(new DefaultRuleApplier());
    this.grd = grd;
    this.atomSet = atomSet;
    for (Rule r : grd.getRules()) {
        this.queue.add(new ImmutablePair<Rule, Substitution>(r, new HashMapSubstitution()));
    }//from   ww w  . j  a  va2  s.c o m
}

From source file:fr.cvlaminck.merging.impl.DefaultValueMergers.java

@Override
public void unregisterValueMerger(Class<?> mergerType, String mergingStrategy) {
    Pair<Class<?>, String> key = new ImmutablePair<Class<?>, String>(mergerType, mergingStrategy);
    mergers.remove(key);/*from  ww  w  .j  a  v a 2 s  . co  m*/
}

From source file:au.gov.ga.earthsci.bookmark.properties.layer.LayersProperty.java

/**
 * Add additional layer state to this property.
 * /*  w w w .  j  a v a2s  .  c om*/
 * @param id
 *            The id of the layer
 * @param opacity
 *            The opacity of the layer
 */
public void addLayer(String id, Double opacity, String name) {
    //      layerState.put(id, opacity);
    //      layerName.put(id, name);
    List<Pair<String, String>> pairs = new ArrayList<Pair<String, String>>();
    pairs.add(new ImmutablePair<String, String>("opacity", opacity.toString()));
    pairs.add(new ImmutablePair<String, String>("name", name));
    addLayer(id, pairs.toArray(new Pair[0]));

}

From source file:com.mobilecashout.osprey.plugin.PluginManager.java

private ImmutablePair<String, PluginInterface> resolve(String command, String localRemote)
        throws IncompatibleEnvironmentError {
    String incompatibleFound = null;

    for (PluginInterface plugin : plugins) {
        String hashName = "@" + plugin.getName();
        if (command.startsWith(hashName)) {

            if (!Arrays.asList(plugin.getEnvironments()).contains(localRemote)) {
                incompatibleFound = hashName;
                continue;
            }/*ww  w.j a  va2s .  c  o  m*/

            String commandPart = "";
            if (command.length() > hashName.length()) {
                commandPart = command.substring(hashName.length());
            }

            if (!commandPart.startsWith(":")) {
                commandPart = commandPart.trim();
            }

            return new ImmutablePair<>(commandPart, plugin);
        }
    }

    if (null != incompatibleFound) {
        throw new IncompatibleEnvironmentError(incompatibleFound, localRemote);
    }

    return null;
}

From source file:com.evolveum.midpoint.wf.impl.processors.primary.policy.ProcessSpecifications.java

static ProcessSpecifications createFromRules(List<EvaluatedPolicyRule> rules, PrismContext prismContext)
        throws ObjectNotFoundException {
    // Step 1: plain list of approval actions -> map: process-spec -> list of related actions/rules ("collected")
    LinkedHashMap<WfProcessSpecificationType, List<Pair<ApprovalPolicyActionType, EvaluatedPolicyRule>>> collectedSpecifications = new LinkedHashMap<>();
    for (EvaluatedPolicyRule rule : rules) {
        for (ApprovalPolicyActionType approvalAction : rule.getEnabledActions(ApprovalPolicyActionType.class)) {
            WfProcessSpecificationType spec = approvalAction.getProcessSpecification();
            collectedSpecifications.computeIfAbsent(spec, s -> new ArrayList<>())
                    .add(new ImmutablePair<>(approvalAction, rule));
        }//from   ww w  .j  ava  2  s  .c  o  m
    }
    // Step 2: resolve references
    for (WfProcessSpecificationType spec : new HashSet<>(collectedSpecifications.keySet())) { // cloned to avoid concurrent modification exception
        if (spec != null && spec.getRef() != null) {
            List<Map.Entry<WfProcessSpecificationType, List<Pair<ApprovalPolicyActionType, EvaluatedPolicyRule>>>> matching = collectedSpecifications
                    .entrySet().stream()
                    .filter(e -> e.getKey() != null && spec.getRef().equals(e.getKey().getName()))
                    .collect(Collectors.toList());
            if (matching.isEmpty()) {
                throw new IllegalStateException("Process specification named '" + spec.getRef()
                        + "' referenced from an approval action couldn't be found");
            } else if (matching.size() > 1) {
                throw new IllegalStateException("More than one process specification named '" + spec.getRef()
                        + "' referenced from an approval action: " + matching);
            } else {
                // move all actions/rules to the referenced process specification
                List<Pair<ApprovalPolicyActionType, EvaluatedPolicyRule>> referencedSpecActions = matching
                        .get(0).getValue();
                referencedSpecActions.addAll(collectedSpecifications.get(spec));
                collectedSpecifications.remove(spec);
            }
        }
    }

    Map<String, Pair<ApprovalPolicyActionType, EvaluatedPolicyRule>> actionsMap = null;

    // Step 3: include other actions
    for (Map.Entry<WfProcessSpecificationType, List<Pair<ApprovalPolicyActionType, EvaluatedPolicyRule>>> processSpecificationEntry : collectedSpecifications
            .entrySet()) {
        WfProcessSpecificationType spec = processSpecificationEntry.getKey();
        if (spec == null || spec.getIncludeAction().isEmpty() && spec.getIncludeActionIfPresent().isEmpty()) {
            continue;
        }
        if (actionsMap == null) {
            actionsMap = createActionsMap(collectedSpecifications.values());
        }
        for (String actionToInclude : spec.getIncludeAction()) {
            processActionToInclude(actionToInclude, actionsMap, processSpecificationEntry, true);
        }
        for (String actionToInclude : spec.getIncludeActionIfPresent()) {
            processActionToInclude(actionToInclude, actionsMap, processSpecificationEntry, false);
        }
    }

    // Step 4: sorts process specifications and wraps into ProcessSpecification objects
    ProcessSpecifications rv = new ProcessSpecifications(prismContext);
    collectedSpecifications.entrySet().stream().sorted((ps1, ps2) -> {
        WfProcessSpecificationType key1 = ps1.getKey();
        WfProcessSpecificationType key2 = ps2.getKey();
        if (key1 == null) {
            return key2 == null ? 0 : 1; // non-empty (key2) records first
        } else if (key2 == null) {
            return -1; // non-empty (key1) record first
        }
        int order1 = defaultIfNull(key1.getOrder(), Integer.MAX_VALUE);
        int order2 = defaultIfNull(key2.getOrder(), Integer.MAX_VALUE);
        return Integer.compare(order1, order2);
    }).forEach(e -> rv.specifications.add(rv.new ProcessSpecification(e)));
    return rv;
}

From source file:io.confluent.kafka.connect.source.io.processing.csv.SchemaConfig.java

public Pair<ParserConfig, ParserConfig> parserConfigs(SpoolDirectoryConfig config) {
    Preconditions.checkNotNull(fields, "fields cannot be null.");
    Preconditions.checkNotNull(name, "SchemaConfig.name cannot be null");
    Preconditions.checkState(!name.isEmpty(), "SchemaConfig.name cannot be null");
    Preconditions.checkState(!name.equalsIgnoreCase(keyName),
            "SchemaConfig.name and SchemaConfig.keyName cannot be the same.");

    SchemaBuilder valueBuilder = SchemaBuilder.struct();
    valueBuilder.name(this.name);

    Preconditions.checkNotNull(keys, "keys cannot be null.");
    SchemaBuilder keyBuilder = SchemaBuilder.struct();

    if (null == this.keyName || this.keyName.isEmpty()) {
        String keySchemaName = (this.name == null ? "" : this.name) + "Key";
        keyBuilder.name(keySchemaName);/*from w  w w.  jav a  2s . c om*/
    } else {
        keyBuilder.name(this.keyName);
    }

    Set<String> keyLookup = new HashSet<>(this.keys);

    List<FieldMapping> valueMaps = new ArrayList<>();
    List<FieldMapping> keyMaps = new ArrayList<>();

    for (FieldConfig fieldConfig : this.fields) {
        valueBuilder.field(fieldConfig.name, fieldConfig.schema());

        FieldMapping mapping = new FieldMapping(fieldConfig.index, fieldConfig.name, fieldConfig.schema());
        valueMaps.add(mapping);

        if (keyLookup.contains(fieldConfig.name)) {
            keyMaps.add(mapping);
            keyBuilder.field(fieldConfig.name, fieldConfig.schema());
            keyLookup.remove(fieldConfig.name);
        }
    }

    Preconditions.checkState(keyLookup.isEmpty(),
            "Keys specified were not found in the schema. The following key field(s) " + "were not found: %s",
            Joiner.on(",").join(keyLookup));

    if (config.includeFileMetadata()) {
        FileMetadata.addFieldSchema(valueBuilder);
    }

    ParserConfig keyParserConfig = new ParserConfig(this.keys.isEmpty() ? null : keyBuilder.build(), keyMaps);
    ParserConfig valueParserConfig = new ParserConfig(valueBuilder.build(), valueMaps);

    return new ImmutablePair<>(keyParserConfig, valueParserConfig);
}

From source file:com.flowpowered.commons.store.SimpleStoredMap.java

@Override
public List<Pair<T, String>> getItems() {
    List<Pair<T, String>> items = new ArrayList<>();
    for (Map.Entry<String, T> entry : store.getEntrySet()) {
        items.add(new ImmutablePair<>(entry.getValue(), entry.getKey()));
    }//  w  ww.j  a  v  a2s . com
    return items;
}

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

@Test
public void testPartialInput() throws Exception {
    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder()
            .partitions(Collections.<PartitionConfig>emptyList()).build();
    HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();

    List<Record> records = new LinkedList<>();
    Record record;/*from w w  w .j a va2 s  . c o  m*/

    record = RecordCreator.create("s", "s:1");
    record.set(
            Field.create(Field.Type.MAP, ImmutableSortedMap.of("id", Field.create(Field.Type.STRING, "text"))));
    records.add(record);

    record = RecordCreator.create("s", "s:2");
    record.set(Field.create(Field.Type.MAP,
            ImmutableSortedMap.of("name", Field.create(Field.Type.STRING, "text"))));
    records.add(record);

    record = RecordCreator.create("s", "s:3");
    record.set(Field.create(Field.Type.MAP,
            ImmutableSortedMap.of("value", Field.create(Field.Type.STRING, "text"))));
    records.add(record);

    record = RecordCreator.create("s", "s:4");
    record.set(Field.create(Field.Type.MAP, ImmutableSortedMap.of("value",
            Field.create(Field.Type.STRING, "text"), "id", Field.create(Field.Type.STRING, "text"))));
    records.add(record);

    record = RecordCreator.create("s", "s:5");
    record.set(Field.create(Field.Type.MAP, ImmutableSortedMap.of("name",
            Field.create(Field.Type.STRING, "text"), "id", Field.create(Field.Type.STRING, "text"))));
    records.add(record);

    processRecords(processor, hiveTarget, records);

    // End state should be with three columns
    assertTableStructure("default.tbl", new ImmutablePair("tbl.id", Types.VARCHAR),
            new ImmutablePair("tbl.name", Types.VARCHAR), new ImmutablePair("tbl.value", Types.VARCHAR));

    // 5 rows
    assertQueryResult("select count(*) from tbl", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            Assert.assertTrue(rs.next());
            Assert.assertEquals(5, rs.getInt(1));
            Assert.assertFalse(rs.next());
        }
    });

    // And 4 files
    Assert.assertEquals(3, getDefaultFileSystem().listStatus(new Path("/user/hive/warehouse/tbl/")).length);
}

From source file:edu.sabanciuniv.sentilab.sare.models.setcover.DocumentSetCover.java

private Pair<List<SetCoverDocument>, List<SetCoverDocument>> splitByCoverage(double weightCoverage) {
    List<SetCoverDocument> covered = Lists.newArrayList();
    List<SetCoverDocument> uncovered = Lists.newArrayList();
    List<SetCoverDocument> setCoverDocuments = Collections
            .synchronizedList(Lists.newArrayList(this.getAllDocuments()));

    double totalWeight = this.getTotalWeight();
    double accumulatedWeight = 0;

    // sort set cover.
    Iterator<SetCoverDocument> iterator = Ordering.from(new Comparator<SetCoverDocument>() {
        @Override//w w w. ja v a2 s.c  o m
        public int compare(SetCoverDocument o1, SetCoverDocument o2) {
            return (int) ((o2.getWeight() - o1.getWeight()) * 100);
        }
    }).immutableSortedCopy(setCoverDocuments).iterator();

    // get all the useful ones.
    while (iterator.hasNext()) {
        if (accumulatedWeight >= weightCoverage * totalWeight) {
            break;
        }

        SetCoverDocument document = iterator.next();
        accumulatedWeight += document.getWeight();
        covered.add(document);
    }

    while (iterator.hasNext()) {
        uncovered.add(iterator.next());
    }

    return new ImmutablePair<List<SetCoverDocument>, List<SetCoverDocument>>(covered, uncovered);
}