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:com.netflix.genie.agent.execution.statemachine.StateMachineAutoConfiguration.java

/**
 * Provide a lazy bean which is a collection of all the states the state machine should contain which have an
 * associated action. All should implement {@link StateAction}.
 *
 * @param initializeAction              The initialization action
 * @param configureAgentAction          The configure agent action
 * @param resolveJobSpecificationAction The resolve job specification action
 * @param setUpJobAction                The setup job action
 * @param launchJobAction               The launch job action
 * @param monitorJobAction              The monitor job action
 * @param cleanupJobAction              The cleanup job action
 * @param shutdownAction                The shut down action
 * @param handleErrorAction             The handle error action
 * @return A collection of all the actions
 *///from  w  w  w . ja v a  2s .  c o  m
@Bean
@Lazy
public Collection<Pair<States, StateAction>> statesWithActions(final StateAction.Initialize initializeAction,
        final StateAction.ConfigureAgent configureAgentAction,
        final StateAction.ResolveJobSpecification resolveJobSpecificationAction,
        final StateAction.SetUpJob setUpJobAction, final StateAction.LaunchJob launchJobAction,
        final StateAction.MonitorJob monitorJobAction, final StateAction.CleanupJob cleanupJobAction,
        final StateAction.Shutdown shutdownAction, final StateAction.HandleError handleErrorAction) {
    return Arrays.asList(Pair.of(States.INITIALIZE, initializeAction),
            Pair.of(States.CONFIGURE_AGENT, configureAgentAction),
            Pair.of(States.RESOLVE_JOB_SPECIFICATION, resolveJobSpecificationAction),
            Pair.of(States.SETUP_JOB, setUpJobAction), Pair.of(States.LAUNCH_JOB, launchJobAction),
            Pair.of(States.MONITOR_JOB, monitorJobAction), Pair.of(States.CLEANUP_JOB, cleanupJobAction),
            Pair.of(States.SHUTDOWN, shutdownAction), Pair.of(States.HANDLE_ERROR, handleErrorAction));
}

From source file:io.pravega.segmentstore.server.host.handler.AppendProcessor.java

/**
 * Setup an append so that subsequent append calls can occur.
 * This requires validating that the segment exists.
 * The reply: AppendSetup indicates that appends may proceed and contains the eventNumber which they should proceed
 * from (in the event that this is a reconnect from a producer we have seen before)
 *//* w w  w.  j  a v a2s  . c  o m*/
@Override
public void setupAppend(SetupAppend setupAppend) {
    String newSegment = setupAppend.getSegment();
    UUID writer = setupAppend.getWriterId();
    store.getStreamSegmentInfo(newSegment, true, TIMEOUT).whenComplete((info, u) -> {
        try {
            if (u != null) {
                handleException(writer, setupAppend.getRequestId(), newSegment, "setting up append", u);
            } else {
                long eventNumber = info.getAttributes().getOrDefault(writer,
                        SegmentMetadata.NULL_ATTRIBUTE_VALUE);
                synchronized (lock) {
                    latestEventNumbers.putIfAbsent(Pair.of(newSegment, writer), eventNumber);
                }
                connection.send(new AppendSetup(setupAppend.getRequestId(), newSegment, writer, eventNumber));
            }
        } catch (Throwable e) {
            handleException(writer, setupAppend.getRequestId(), newSegment, "handling setupAppend result", e);
        }
    });
}

From source file:com.qq.tars.service.admin.AdminService.java

public List<Pair<String, Integer>> getEndpoints(String objectName) {
    List<EndpointF> endpoints = communicator.getEndpoint4All(objectName);
    log.info("object name={}, endpoints size={}", objectName, endpoints.size());
    return endpoints.stream().map(endpoint -> Pair.of(endpoint.getHost(), endpoint.getPort()))
            .collect(Collectors.toList());
}

From source file:enumj.EnumerableTest.java

@Test
public void testOfLazyIterator() {
    System.out.println("ofLazyIterator");
    EnumerableGenerator.generatorPairs().limit(100)
            .map(p -> Pair.of(p.getLeft().ofLazyIteratorEnumerable(), p.getRight().ofLazyIteratorEnumerable()))
            .forEach(p -> assertTrue(p.getLeft().elementsEqual(p.getRight())));
}

From source file:de.vandermeer.skb.interfaces.transformers.textformat.Text_To_WrappedFormat.java

@Override
default Pair<ArrayList<String>, ArrayList<String>> transform(String input) {
    Validate.notBlank(input);/*from w  w w  .java  2 s  .c o m*/
    Validate.isTrue(this.getWidth() > 0);

    ArrayList<String> topList = new ArrayList<>();
    ArrayList<String> bottomList = new ArrayList<>();

    //an emergency break, counting loops to avoid endless loops
    int count;

    String text = StringUtils.replacePattern(input, "\\r\\n|\\r|\\n", LINEBREAK);
    text = StringUtils.replace(text, "<br>", LINEBREAK);
    text = StringUtils.replace(text, "<br/>", LINEBREAK);

    StrBuilder sb = new StrBuilder(text);
    if (this.getTopSettings() != null) {
        //we have a top request, do that one first
        Validate.notNull(this.getTopSettings().getLeft());
        Validate.notNull(this.getTopSettings().getRight());
        Validate.isTrue(this.getTopSettings().getLeft() > 0);
        Validate.isTrue(this.getTopSettings().getRight() > 0);

        int topLines = this.getTopSettings().getLeft();
        int topWidth = this.getTopSettings().getRight();
        count = 0;

        while (sb.size() > 0 && topLines > 0 && count++ < 200) {
            if (sb.startsWith(LINEBREAK)) {
                sb.replaceFirst(LINEBREAK, "");
            }
            String s = null;
            boolean wln = false;
            if (sb.indexOf(LINEBREAK) > 0) {
                s = sb.substring(0, sb.indexOf(LINEBREAK));
                wln = true;
                //sb.replace(0, sb.indexOf(LINEBREAK) + LINEBREAK.length(), "");
            } else {
                s = sb.toString();
                //sb.clear();
            }
            String wrap = WordUtils.wrap(s, topWidth, LINEBREAK, true);
            StrTokenizer tok = new StrTokenizer(wrap, LINEBREAK).setIgnoreEmptyTokens(false);
            String[] ar = tok.getTokenArray();
            if (ar.length <= topLines) {
                //all lines done, cleanup
                for (String str : ar) {
                    topList.add(str.trim());
                }
                if (wln == true) {
                    //if we had a conditional linebreak there might be more text, remove the line we processed
                    sb.replace(0, sb.indexOf(LINEBREAK) + LINEBREAK.length(), "");
                } else {
                    //no conditional line break, clean builder
                    sb.clear();
                }
                topLines = 0;
            } else {
                //we have more lines than we need, so remove the text we have from the builder and copy processed lines
                StrBuilder replace = new StrBuilder();
                for (int i = 0; i < topLines; i++) {
                    topList.add(ar[i].trim());
                    replace.appendSeparator(' ').append(ar[i]);
                }
                if (wln == true) {
                    replace.append(LINEBREAK);
                }
                sb.replaceFirst(replace.toString(), "");
                topLines = 0;
            }
        }
    }

    //no top, simple wrapping with recognition of conditional line breaks
    count = 0;
    while (sb.size() > 0 && count++ < 200) {
        if (sb.startsWith(LINEBREAK)) {
            sb.replaceFirst(LINEBREAK, "");
        }
        String s = null;
        if (sb.indexOf(LINEBREAK) > 0) {
            s = sb.substring(0, sb.indexOf(LINEBREAK));
            sb.replace(0, sb.indexOf(LINEBREAK) + LINEBREAK.length(), "");
        } else {
            s = sb.toString();
            sb.clear();
        }
        s = WordUtils.wrap(s, this.getWidth(), LINEBREAK, true);
        StrTokenizer tok = new StrTokenizer(s, LINEBREAK).setIgnoreEmptyTokens(false);
        for (String str : tok.getTokenArray()) {
            bottomList.add(str.trim());
        }
    }

    return Pair.of(topList, bottomList);
}

From source file:it.anyplace.sync.discovery.DiscoveryHandler.java

private void processDeviceAddressBg(final Iterable<DeviceAddress> deviceAddresses) {
    if (isClosed) {
        logger.debug("discarding device addresses, discovery handler already closed");
    } else {/*from  ww w . j  a  va 2  s . c o  m*/
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    logger.info("processing device address list");
                    List<DeviceAddress> list = Lists.newArrayList(deviceAddresses);
                    final Set<String> peers = Sets.newHashSet(configuration.getPeerIds());
                    Iterables.removeIf(list, new Predicate<DeviceAddress>() { //do not process address already processed
                        @Override
                        public boolean apply(DeviceAddress deviceAddress) {
                            return !peers.contains(deviceAddress.getDeviceId()) || deviceAddressMap.containsKey(
                                    Pair.of(deviceAddress.getDeviceId(), deviceAddress.getAddress()));
                        }
                    });
                    list = AddressRanker.testAndRank(list);
                    for (DeviceAddress deviceAddress : list) {
                        putDeviceAddress(deviceAddress);
                    }
                } catch (Exception ex) {
                    logger.error("error processing device addresses", ex);
                }
            }
        });
    }
}

From source file:alfio.controller.api.ReservationApiController.java

@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/vat-validation", method = RequestMethod.POST)
@Transactional//from w w  w  . java 2 s  .c o m
public ResponseEntity<VatDetail> validateEUVat(@PathVariable("eventName") String eventName,
        @PathVariable("reservationId") String reservationId, PaymentForm paymentForm, Locale locale,
        HttpServletRequest request) {

    String country = paymentForm.getVatCountryCode();
    Optional<Triple<Event, TicketReservation, VatDetail>> vatDetail = eventRepository
            .findOptionalByShortName(eventName)
            .flatMap(e -> ticketReservationRepository.findOptionalReservationById(reservationId)
                    .map(r -> Pair.of(e, r)))
            .filter(e -> EnumSet.of(INCLUDED, NOT_INCLUDED).contains(e.getKey().getVatStatus()))
            .filter(e -> vatChecker.isVatCheckingEnabledFor(e.getKey().getOrganizationId()))
            .flatMap(e -> vatChecker.checkVat(paymentForm.getVatNr(), country, e.getKey().getOrganizationId())
                    .map(vd -> Triple.of(e.getLeft(), e.getRight(), vd)));

    vatDetail.filter(t -> t.getRight().isValid()).ifPresent(t -> {
        VatDetail vd = t.getRight();
        String billingAddress = vd.getName() + "\n" + vd.getAddress();
        PriceContainer.VatStatus vatStatus = determineVatStatus(t.getLeft().getVatStatus(),
                t.getRight().isVatExempt());
        ticketReservationRepository.updateBillingData(vatStatus, vd.getVatNr(), country,
                paymentForm.isInvoiceRequested(), reservationId);
        OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId,
                t.getLeft(), Locale.forLanguageTag(t.getMiddle().getUserLanguage()));
        ticketReservationRepository.addReservationInvoiceOrReceiptModel(reservationId,
                Json.toJson(orderSummary));
        ticketReservationRepository.updateTicketReservation(reservationId, t.getMiddle().getStatus().name(),
                paymentForm.getEmail(), paymentForm.getFullName(), paymentForm.getFirstName(),
                paymentForm.getLastName(), locale.getLanguage(), billingAddress, null,
                Optional.ofNullable(paymentForm.getPaymentMethod()).map(PaymentProxy::name).orElse(null));
        paymentForm.getTickets().forEach((ticketId, owner) -> {
            if (isNotEmpty(owner.getEmail())
                    && ((isNotEmpty(owner.getFirstName()) && isNotEmpty(owner.getLastName()))
                            || isNotEmpty(owner.getFullName()))) {
                ticketHelper.preAssignTicket(eventName, reservationId, ticketId, owner, Optional.empty(),
                        request, (tr) -> {
                        }, Optional.empty());
            }
        });
    });

    return vatDetail.map(Triple::getRight).map(vd -> {
        if (vd.isValid()) {
            return ResponseEntity.ok(vd);
        } else {
            return new ResponseEntity<VatDetail>(HttpStatus.BAD_REQUEST);
        }
    }).orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}

From source file:com.yahoo.bullet.drpc.FilterBoltTest.java

@Test
public void testProjection() {
    Tuple rule = makeIDTuple(TupleType.Type.RULE_TUPLE, 42L,
            makeProjectionRule(Pair.of("field", "id"), Pair.of("map_field.id", "mid")));
    bolt.execute(rule);//  w ww.j  a  v a 2s  . com

    BulletRecord record = RecordBox.get().add("field", "b235gf23b").add("timestamp", 92L)
            .addMap("map_field", Pair.of("id", "123"), Pair.of("bar", "foo")).getRecord();

    Tuple matching = makeTuple(TupleType.Type.RECORD_TUPLE, record);
    bolt.execute(matching);

    BulletRecord expectedRecord = RecordBox.get().add("id", "b235gf23b").add("mid", "123").getRecord();
    Tuple expected = makeRecordTuple(TupleType.Type.FILTER_TUPLE, 42L, expectedRecord);
    Assert.assertTrue(wasRawRecordEmittedTo(FilterBolt.FILTER_STREAM, 1, expected));
}

From source file:de.tuberlin.uebb.jbop.optimizer.utils.LoopMatcher.java

/**
 * Gets the body bounds.//ww  w  . j  a v a 2s  . co  m
 * 
 * @param gotoNode
 *          the goto node
 * @return the body bounds
 */
public static Pair<AbstractInsnNode, AbstractInsnNode> getBodyBounds(final AbstractInsnNode gotoNode) {
    final Loop loop = getLoop(getStoreOfLoopForGoto(gotoNode));
    if (loop == null) {
        return null;
    }
    final List<AbstractInsnNode> body = loop.getBody();
    if (body == null || body.isEmpty()) {
        return null;
    }
    return Pair.of(body.get(0), body.get(body.size() - 1));
}

From source file:edu.wpi.checksims.algorithm.smithwaterman.SmithWatermanAlgorithm.java

/**
 * Compute a Smith-Waterman alignment through exhaustive (but more reliable) process.
 *
 * TODO tests for this (already tested through SmithWaterman)
 *
 * @return Pair of TokenList representing optimal alignments
 * @throws InternalAlgorithmError Thrown if internal error causes violation of preconditions
 *///from w  w  w .  j a va 2 s .  com
public Pair<TokenList, TokenList> computeSmithWatermanAlignmentExhaustive() throws InternalAlgorithmError {
    Map<Integer, Set<Coordinate>> localCandidates;

    // Keep computing while we have results over threshold
    do {
        // Recompute whole array
        localCandidates = computeArraySubset(wholeArray);

        if (localCandidates.isEmpty()) {
            break;
        }

        // Get the largest key
        int largestKey = Ordering.natural().max(localCandidates.keySet());

        // Get matching coordinates
        Set<Coordinate> largestCoords = localCandidates.get(largestKey);

        if (largestCoords == null || largestCoords.isEmpty()) {
            throw new InternalAlgorithmError(
                    "Error: largest key " + largestKey + " maps to null or empty candidate set!");
        }

        // Arbitrarily break ties
        Coordinate chosenCoord = Iterables.get(largestCoords, 0);

        // Get match coordinates
        Set<Coordinate> matchCoords = getMatchCoordinates(chosenCoord);

        // Set match invalid
        setMatchesInvalid(matchCoords);
    } while (!localCandidates.isEmpty());

    // IntelliJ has an aversion to passing anything with a 'y' in it as the right side of a pair
    // This alleviates the warning
    //noinspection SuspiciousNameCombination
    return Pair.of(xList, yList);
}