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

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

Introduction

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

Prototype

public static <L, R> Pair<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:io.lavagna.service.ListValueMetadataRepositoryTest.java

private Pair<LabelListValue, LabelListValue> createLabelListValue() {
    CardLabel label = cardLabelRepository.addLabel(project.getId(), false, CardLabel.LabelType.LIST,
            CardLabel.LabelDomain.USER, "listlabel", 0);
    Assert.assertEquals(0, cardLabelRepository.findListValuesByLabelId(label.getId()).size());
    LabelListValue llv = cardLabelRepository.addLabelListValue(label.getId(), "1");
    cardLabelRepository.addLabelValueToCard(label, card.getId(),
            new CardLabelValue.LabelValue(null, null, null, null, null, llv.getId()));

    LabelListValue llv2 = cardLabelRepository.addLabelListValue(label.getId(), "2");
    cardLabelRepository.addLabelValueToCard(label, card.getId(),
            new CardLabelValue.LabelValue(null, null, null, null, null, llv2.getId()));

    return Pair.of(llv, llv2);
}

From source file:eu.openanalytics.rsb.data.FileCatalogManager.java

@Override
@PreAuthorize("hasPermission(#applicationName, 'CATALOG_USER')")
public Map<Pair<CatalogSection, File>, List<File>> getCatalog(final String applicationName) {
    final Map<Pair<CatalogSection, File>, List<File>> catalog = new HashMap<Pair<CatalogSection, File>, List<File>>();

    for (final CatalogSection catalogSection : CatalogSection.values()) {
        final File catalogSectionDirectory = getCatalogSectionDirectory(catalogSection, applicationName);

        catalog.put(Pair.of(catalogSection, catalogSectionDirectory),
                Arrays.asList(catalogSectionDirectory.listFiles(Constants.FILE_ONLY_FILTER)));
    }//  w  ww .j ava2  s.c o m

    return catalog;
}

From source file:enumj.EnumeratorTest.java

@Test
public void testOf_Iterable() {
    System.out.println("of iterable");
    EnumeratorGenerator.generatorPairs().limit(100)
            .map(p -> Pair.of(p.getLeft().ofIterableEnumerator(), p.getRight().ofIterableEnumerator()))
            .forEach(p -> assertTrue(p.getLeft().elementsEqual(p.getRight())));
    EnumeratorGenerator.generatorPairs().limit(100)
            .map(p -> Pair.of(p.getLeft().ofIterableEnumerator(), p.getRight().ofIteratorEnumerator()))
            .forEach(p -> assertTrue(p.getLeft().elementsEqual(p.getRight())));
}

From source file:li.klass.fhem.appwidget.view.widget.base.otherWidgets.OtherWidgetsFragment.java

@Override
public void update(boolean doUpdate) {
    checkNotNull(widgetSize);/*from w ww .  j a  va  2  s .  com*/

    if (getView() == null)
        return;

    ListView listView = (ListView) getView().findViewById(R.id.list);
    OtherWidgetsAdapter adapter = (OtherWidgetsAdapter) listView.getAdapter();

    final List<WidgetType> widgets = WidgetType.getOtherWidgetsFor(widgetSize);
    List<Pair<WidgetType, String>> values = newArrayList(
            transform(widgets, new Function<WidgetType, Pair<WidgetType, String>>() {
                @Override
                public Pair<WidgetType, String> apply(WidgetType widgetType) {
                    return Pair.of(widgetType, getActivity().getString(widgetType.widgetView.getWidgetName()));
                }
            }));

    if (values.isEmpty()) {
        showEmptyView();
    } else {
        hideEmptyView();
    }

    adapter.updateData(values);
}

From source file:alfio.controller.form.ReservationForm.java

public Optional<Pair<List<TicketReservationWithOptionalCodeModification>, List<ASReservationWithOptionalCodeModification>>> validate(
        Errors bindingResult, TicketReservationManager tickReservationManager,
        AdditionalServiceRepository additionalServiceRepository, EventManager eventManager, Event event) {
    int selectionCount = ticketSelectionCount();

    if (selectionCount <= 0) {
        bindingResult.reject(ErrorsCode.STEP_1_SELECT_AT_LEAST_ONE);
        return Optional.empty();
    }/*from   w w  w .j  a v  a  2 s  . c o m*/

    List<Pair<TicketReservationModification, Integer>> maxTicketsByTicketReservation = selected().stream()
            .map(r -> Pair.of(r, tickReservationManager.maxAmountOfTicketsForCategory(event.getOrganizationId(),
                    event.getId(), r.getTicketCategoryId())))
            .collect(toList());
    Optional<Pair<TicketReservationModification, Integer>> error = maxTicketsByTicketReservation.stream()
            .filter(p -> p.getKey().getAmount() > p.getValue()).findAny();

    if (error.isPresent()) {
        bindingResult.reject(ErrorsCode.STEP_1_OVER_MAXIMUM, new Object[] { error.get().getValue() }, null);
        return Optional.empty();
    }

    final List<TicketReservationModification> categories = selected();
    final List<AdditionalServiceReservationModification> additionalServices = selectedAdditionalServices();

    final boolean validCategorySelection = categories.stream().allMatch(c -> {
        TicketCategory tc = eventManager.getTicketCategoryById(c.getTicketCategoryId(), event.getId());
        return OptionalWrapper.optionally(() -> eventManager.findEventByTicketCategory(tc)).isPresent();
    });

    final boolean validAdditionalServiceSelected = additionalServices.stream().allMatch(asm -> {
        AdditionalService as = eventManager.getAdditionalServiceById(asm.getAdditionalServiceId(),
                event.getId());
        ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
        return as.getInception(event.getZoneId()).isBefore(now)
                && as.getExpiration(event.getZoneId()).isAfter(now) && asm.getQuantity() >= 0
                && ((as.isFixPrice() && asm.isQuantityValid(as, selectionCount)) || (!as.isFixPrice()
                        && asm.getAmount() != null && asm.getAmount().compareTo(BigDecimal.ZERO) >= 0))
                && OptionalWrapper.optionally(() -> eventManager.findEventByAdditionalService(as)).isPresent();
    });

    if (!validCategorySelection || !validAdditionalServiceSelected) {
        bindingResult.reject(ErrorsCode.STEP_1_TICKET_CATEGORY_MUST_BE_SALEABLE);
        return Optional.empty();
    }

    List<TicketReservationWithOptionalCodeModification> res = new ArrayList<>();
    //
    Optional<SpecialPrice> specialCode = Optional.ofNullable(StringUtils.trimToNull(promoCode))
            .flatMap((trimmedCode) -> tickReservationManager.getSpecialPriceByCode(trimmedCode));
    //
    final ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
    maxTicketsByTicketReservation.forEach((pair) -> validateCategory(bindingResult, tickReservationManager,
            eventManager, event, pair.getRight(), res, specialCode, now, pair.getLeft()));
    return bindingResult.hasErrors() ? Optional.empty()
            : Optional.of(Pair.of(res,
                    additionalServices.stream()
                            .map(as -> new ASReservationWithOptionalCodeModification(as, specialCode))
                            .collect(Collectors.toList())));
}

From source file:com.act.lcms.CompareTwoNetCDFAroundMass.java

private List<Pair<Double, Double>> extractMZSlice(double mz, Iterator<LCMSSpectrum> spectraIt, int numOut,
        String tagfname) {//from   w  w w  . ja  v  a  2  s. c o m
    List<Pair<Double, Double>> mzSlice = new ArrayList<>();

    int pulled = 0;
    // iterate through first few, or all if -1 given
    while (spectraIt.hasNext() && (numOut == -1 || pulled < numOut)) {
        LCMSSpectrum timepoint = spectraIt.next();

        // get all (mz, intensity) at this timepoint
        List<Pair<Double, Double>> intensities = timepoint.getIntensities();

        // this time point is valid to look at if its max intensity is around
        // the mass we care about. So lets first get the max peak location
        double intensityForMz = extractMZ(mz, intensities, timepoint.getTimeVal());

        // the above is Pair(mz_extracted, intensity), where mz_extracted = mz
        // we now add the timepoint val and the intensity to the output
        mzSlice.add(Pair.of(timepoint.getTimeVal(), intensityForMz));

        pulled++;
    }
    System.out.format("Done: %s\n\n", tagfname);

    return mzSlice;
}

From source file:com.oembedler.moon.graphql.engine.execute.GraphQLDefaultRxExecutionStrategy.java

protected Observable<Pair<String, Object>> unwrapExecutionResult(String fieldName,
        ExecutionResult executionResult) {
    Observable<Pair<String, Object>> result;
    if (executionResult instanceof GraphQLRxExecutionResult) {
        GraphQLRxExecutionResult rxResult = (GraphQLRxExecutionResult) executionResult;
        Observable<?> unwrappedResult = rxResult.getDataObservable().flatMap(potentialResult -> {
            if (potentialResult instanceof GraphQLRxExecutionResult) {
                return ((GraphQLRxExecutionResult) potentialResult).getDataObservable();
            }/* w ww  . jav a2s  .co m*/
            return Observable.just(potentialResult);
        });

        result = Observable.zip(Observable.just(fieldName), unwrappedResult, Pair::of);
    } else {
        result = Observable
                .just(Pair.of(fieldName, executionResult != null ? executionResult.getData() : null));
    }
    return result;
}

From source file:edu.uci.ics.hyracks.api.client.impl.JobActivityGraphBuilder.java

@Override
public void addTargetEdge(int operatorOutputIndex, IActivity task, int taskOutputIndex) {
    if (LOGGER.isLoggable(Level.FINEST)) {
        LOGGER.finest("Adding target edge: " + task.getActivityId() + ":" + operatorOutputIndex + " -> "
                + task.getActivityId() + ":" + taskOutputIndex);
    }//from   w  w  w. j a v  a2s .c o m
    IOperatorDescriptor op = activityOperatorMap.get(task.getActivityId());
    IConnectorDescriptor conn = jobSpec.getOutputConnectorDescriptor(op, operatorOutputIndex);
    insertIntoIndexedMap(jag.getActivityOutputMap(), task.getActivityId(), taskOutputIndex, conn);
    connectorProducerMap.put(conn.getConnectorId(), Pair.of(task, taskOutputIndex));
}

From source file:com.yahoo.bard.webservice.web.filters.QueryParameterNormalizationFilter.java

/**
 * Extract a list of parameters and normalize all keys to be lowercase.
 *
 * NOTE: To preserve existing functionality, I won't change the value of any endpoint parameter name
 *       (i.e. the endpoint can remain case sensitive in absence of this filter). As a result, we have
 *       a naive solution here that applies a one-to-one mapping for changing the casing appropriately.
 *       Everything else is lowercased. A potentially "better" solution would be to make all endpoint
 *       parameters <em>lowercase</em> while simply converting all parameter names to lowercase values.
 *
 * @param uriInfo UriInfo containing parameters to be normalized
 * @return  List of key-value pairs with normalized keys
 *///from  w w w.  j a v a  2s. c o m
private Stream<Pair<String, String>> getNormalizedQueryParameters(UriInfo uriInfo) {
    return uriInfo.getQueryParameters().entrySet().stream().flatMap(entry -> {
        String key = entry.getKey().toLowerCase(Locale.ENGLISH);
        return entry.getValue().stream().map(value -> Pair.of(parameterMap.getOrDefault(key, key), value));
    });
}

From source file:cherry.goods.telno.SoumuExcelParserTest.java

@Test
public void testParse8() throws Exception {
    Map<String, Pair<String, String>> map;
    try (InputStream in = getClass().getResourceAsStream("soumu/000124077.xls")) {
        map = parser.parse(in);/*from  ww  w. ja v  a 2  s . c  o  m*/
    }
    assertEquals(4526, map.size());
    assertEquals(Pair.of("082", "200"), map.get("082200"));
    assertEquals(Pair.of("089", "999"), map.get("089999"));
}