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

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

Introduction

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

Prototype

public static <L, R> ImmutablePair<L, R> of(final L left, final R right) 

Source Link

Document

Obtains an immutable pair of from two objects inferring the generic types.

This factory allows the pair to be created using inference to obtain the generic types.

Usage

From source file:org.gvnix.addon.jpa.addon.entitylistener.JpaOrmEntityListenerOperationsImpl.java

/**
 * Gets the <code>entity-listener</code> xml element for
 * <code>listenerClass</code>. Creates it if not found.
 * //from   ww w.  j a  va 2 s .c  o m
 * @param document XML document instance
 * @param entityListenerElement parent XML Element
 * @param listenerClass listener class to search/create
 * @param sourceMetadataProvider metadaProviderId of listener class
 * @return Element found/created, true if element has been created
 */
private Pair<Element, Boolean> getOrCreateListenerElement(Document document, Element entityListenerElement,
        JavaType listenerClass, String sourceMetadataProvider) {

    Pair<Element, Boolean> result = getOrCreateElement(document, entityListenerElement, ENTITY_LISTENER_TAG,
            ImmutablePair.of(CLASS_ATTRIBUTE, listenerClass.getFullyQualifiedTypeName()));

    // If has not been changed
    if (!result.getRight()) {
        return result;
    }

    // Add source MetadataProviderId on description child tag
    Element element = result.getLeft();
    Element description = document.createElement("description");
    description.setTextContent(sourceMetadataProvider);
    element.appendChild(description);

    return ImmutablePair.of(element, true);
}

From source file:org.gvnix.addon.jpa.addon.entitylistener.JpaOrmEntityListenerOperationsImpl.java

/**
 * Gets or creates a xml element (with tag-name <code>elementName</code>) on
 * <code>parent</code>./*from w  w w.j  a va2  s  .  c o  m*/
 * <p/>
 * If <code>attributeValue</code> is provided will be used to search and
 * applied to the creation.
 * 
 * @param document xml document instance
 * @param parent node to add the new xml element
 * @param elementName new xml tag name
 * @param attributeValue (optional) attribute name + attribute value
 * @return Element found; true if element is new
 */
private Pair<Element, Boolean> getOrCreateElement(Document document, Element parent, String elementName,
        Pair<String, String> attributeValue) {
    boolean changed = false;

    // prepare xpath expression to search for element
    StringBuilder sbXpath = new StringBuilder();
    sbXpath.append(elementName);
    if (attributeValue != null) {
        sbXpath.append("[@");
        sbXpath.append(attributeValue.getKey());
        sbXpath.append("='");
        sbXpath.append(attributeValue.getValue());
        sbXpath.append("']");
    }
    String xpath = sbXpath.toString();

    // Search for element
    Element targetElement = XmlUtils.findFirstElement(xpath, parent);

    if (targetElement == null) {
        // Not found: create it
        targetElement = document.createElement(elementName);
        if (attributeValue != null) {
            targetElement.setAttribute(attributeValue.getKey(), attributeValue.getValue());
        }
        parent.appendChild(targetElement);

        // search again
        targetElement = XmlUtils.findFirstElement(xpath, parent);
        if (targetElement == null) {
            // something went worng
            throw new IllegalStateException("Can't create ".concat(xpath).concat(" element"));
        }
        changed = true;
    }

    return ImmutablePair.of(targetElement, changed);
}

From source file:org.gvnix.addon.jpa.addon.entitylistener.JpaOrmEntityListenerOperationsImpl.java

/**
 * Gets or creates the <code>entity</code> xml element
 * //from w  w  w . ja v a 2 s .  c o  m
 * @param document XML document
 * @param root element
 * @param entityClass
 * @return the new xml element, changes made
 */
private Pair<Element, Boolean> getOrCreateEntityElement(Document document, Element root, JavaType entityClass) {

    return getOrCreateElement(document, root, "entity",
            ImmutablePair.of(CLASS_ATTRIBUTE, entityClass.getFullyQualifiedTypeName()));
}

From source file:org.killbill.billing.plugin.simpletax.internal.VATINValidator.java

private static Pair<Pattern, Predicate<String>> pair(Pattern pattern, Predicate<String> validator) {
    return ImmutablePair.of(pattern, validator);
}

From source file:org.lenskit.eval.temporal.TemporalEvaluatorTest.java

@Before
public void initialize() throws IOException {
    predictOutputFile = folder.newFile("predictions.csv");
    List<Rating> ratings = new ArrayList<>();
    Generator<Rating> rgen = LenskitGenerators.ratings();
    Set<Pair<Long, Long>> used = new HashSet<>();

    while (ratings.size() < RATING_COUNT) {
        Rating r = rgen.next();// w w  w.  j  av a  2s . c om
        long uid = r.getUserId() % 5;
        Pair<Long, Long> ui = ImmutablePair.of(uid, r.getItemId());
        if (used.contains(ui)) {
            continue;
        }

        used.add(ui);
        Rating r2 = r.copyBuilder().setUserId(r.getUserId() % 5).build();
        ratings.add(r2);
    }

    assumeThat(ratings, hasSize(RATING_COUNT));

    dao = StaticDataSource.fromList(ratings).get();

    LenskitConfiguration config = new LenskitConfiguration();
    config.bind(ItemScorer.class).to(UserMeanItemScorer.class);
    config.bind(UserMeanBaseline.class, ItemScorer.class).to(ItemMeanRatingItemScorer.class);

    tempEval.setRebuildPeriod(1L);
    tempEval.setDataSource(dao);
    tempEval.setAlgorithm("UserMeanBaseline", config);
    tempEval.setOutputFile(predictOutputFile);
}

From source file:org.obiba.mica.dataset.search.VariableIndexer.java

private void deleteDatasetVariables(String indexName, Dataset dataset) {
    // remove variables that have this dataset as parent
    Map.Entry<String, String> termQuery = ImmutablePair.of("datasetId", dataset.getId());
    indexer.delete(indexName, Indexer.HARMONIZED_VARIABLE_TYPE, termQuery);
    indexer.delete(indexName, Indexer.VARIABLE_TYPE, termQuery);
}

From source file:org.obiba.mica.taxonomy.TaxonomyIndexer.java

@Async
@Subscribe/*from  w ww  . ja v a2s. c o  m*/
public void taxonomiesUpdated(TaxonomiesUpdatedEvent event) {
    // reindex all taxonomies if target is TAXONOMY or there is no target
    if ((event.getTaxonomyTarget() == null && event.getTaxonomyName() == null)
            || event.getTaxonomyTarget() == TaxonomyTarget.TAXONOMY) {
        log.info("All taxonomies were updated");
        if (indexer.hasIndex(Indexer.TAXONOMY_INDEX))
            indexer.dropIndex(Indexer.TAXONOMY_INDEX);
        index(TaxonomyTarget.VARIABLE,
                ImmutableList.<Taxonomy>builder().addAll(taxonomyService.getOpalTaxonomies().stream() //
                        .filter(t -> taxonomyService.metaTaxonomyContains(t.getName()))
                        .collect(Collectors.toList())) //
                        .add(taxonomyService.getVariableTaxonomy()) //
                        .build());
        index(TaxonomyTarget.STUDY, Lists.newArrayList(taxonomyService.getStudyTaxonomy()));
        index(TaxonomyTarget.DATASET, Lists.newArrayList(taxonomyService.getDatasetTaxonomy()));
        index(TaxonomyTarget.NETWORK, Lists.newArrayList(taxonomyService.getNetworkTaxonomy()));
    } else {
        Map.Entry<String, String> termQuery = ImmutablePair.of("taxonomyName", event.getTaxonomyName());
        indexer.delete(Indexer.TAXONOMY_INDEX, new String[] { Indexer.TAXONOMY_TYPE,
                Indexer.TAXONOMY_VOCABULARY_TYPE, Indexer.TAXONOMY_TERM_TYPE }, termQuery);

        switch (event.getTaxonomyTarget()) {
        case STUDY:
            log.info("Study taxonomies were updated");
            index(TaxonomyTarget.STUDY, Lists.newArrayList(taxonomyService.getStudyTaxonomy()));
            break;
        case NETWORK:
            log.info("Network taxonomies were updated");
            index(TaxonomyTarget.NETWORK, Lists.newArrayList(taxonomyService.getNetworkTaxonomy()));
            break;
        case DATASET:
            log.info("Dataset taxonomies were updated");
            index(TaxonomyTarget.DATASET, Lists.newArrayList(taxonomyService.getDatasetTaxonomy()));
            break;
        case VARIABLE:
            log.info("Variable taxonomies were updated");
            index(TaxonomyTarget.VARIABLE, Lists.newArrayList(taxonomyService.getVariableTaxonomy()));
            break;
        }
    }
}

From source file:org.onosproject.bmv2.ctl.Bmv2ThriftClient.java

/**
 * Parse device ID into host and port.//from  w  ww  .  j  a  va 2  s. c o m
 *
 * @param did device ID
 * @return a pair of host and port
 */
private static Pair<String, Integer> parseDeviceId(DeviceId did) {
    String[] info = did.toString().split(":");
    if (info.length == 3) {
        String host = info[1];
        int port = Integer.parseInt(info[2]);
        return ImmutablePair.of(host, port);
    } else {
        throw new IllegalArgumentException(
                "Unable to parse BMv2 device ID " + did.toString() + ", expected format is scheme:host:port");
    }
}

From source file:org.onosproject.p4runtime.ctl.P4RuntimeClientImpl.java

private <E extends PiEntity> void logWriteErrors(Collection<E> writeEntities, StatusRuntimeException ex,
        WriteOperationType opType, String entryType) {
    List<P4RuntimeOuterClass.Error> errors = null;
    String description = null;/* ww w.j  av  a  2 s  .com*/
    try {
        errors = extractWriteErrorDetails(ex);
    } catch (InvalidProtocolBufferException e) {
        description = ex.getStatus().getDescription();
    }

    log.warn("Unable to {} {} {}(s) on {}: {}{} (detailed errors might be logged below)", opType.name(),
            writeEntities.size(), entryType, deviceId, ex.getStatus().getCode().name(),
            description == null ? "" : " - " + description);

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

    // FIXME: we are assuming entities is an ordered collection, e.g. a list,
    // and that errors are reported in the same order as the corresponding
    // written entity. Write RPC methods should be refactored to accept an
    // order list of entities, instead of a collection.
    if (errors.size() == writeEntities.size()) {
        Iterator<E> entityIterator = writeEntities.iterator();
        errors.stream().map(e -> ImmutablePair.of(e, entityIterator.next()))
                .filter(p -> p.left.getCanonicalCode() != Status.OK.getCode().value())
                .forEach(p -> log.warn("Unable to {} {}: {} [{}]", opType.name(), entryType,
                        parseP4Error(p.getLeft()), p.getRight().toString()));
    } else {
        log.error(
                "Unable to reconcile error details to updates "
                        + "(sent {} updates, but device returned {} errors)",
                entryType, writeEntities.size(), errors.size());
        errors.stream().filter(err -> err.getCanonicalCode() != Status.OK.getCode().value()).forEach(
                err -> log.warn("Unable to {} {} (unknown): {}", opType.name(), entryType, parseP4Error(err)));
    }
}

From source file:org.onosproject.pi.demo.app.ecmp.EcmpFabricApp.java

/**
 * Provisions an ECMP group for the given device and set of ports, returns
 * the group ID.//w  w w  . ja  v a2s.co m
 */
private int provisionGroup(DeviceId deviceId, Set<PortNumber> ports) throws FlowRuleGeneratorException {

    int groupId = groupIdOf(deviceId, ports);

    // Group buckets
    List<GroupBucket> bucketList = ports.stream()
            .map(port -> DefaultTrafficTreatment.builder().setOutput(port).build())
            .map(DefaultGroupBucket::createSelectGroupBucket).collect(Collectors.toList());

    // Group cookie (with action profile ID)
    PiGroupKey groupKey = new PiGroupKey(TBL_WCMP_TABLE_ID, ACT_PRF_WCMP_SELECTOR_ID, groupId);

    log.info("Adding group {} to {}...", groupId, deviceId);
    groupService.addGroup(new DefaultGroupDescription(deviceId, GroupDescription.Type.SELECT,
            new GroupBuckets(bucketList), groupKey, groupId, appId));

    groupKeys.add(ImmutablePair.of(deviceId, groupKey));

    return groupId;
}