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

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

Introduction

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

Prototype

public abstract L getLeft();

Source Link

Document

Gets the left element from this pair.

When treated as a key-value pair, this is the key.

Usage

From source file:com.vmware.identity.openidconnect.server.LoginTest.java

@Test
public void testLoginStringWithSessionCookieMatching() throws Exception {
    // if request has both a loginString and session cookie, then if the session cookie matches, use it and ignore the loginString
    String loginString = passwordLoginString();
    Cookie sessionCookie = new Cookie(SESSION_COOKIE_NAME, SESSION_ID);
    Pair<ModelAndView, MockHttpServletResponse> result = doRequest(loginString, sessionCookie);
    ModelAndView modelView = result.getLeft();
    MockHttpServletResponse response = result.getRight();
    Assert.assertNull("modelView", modelView);
    boolean ajaxRequest = false; // it is actually an ajax request but then TestContext would expect a session cookie to be returned
    validateAuthnSuccessResponse(response, Flow.AUTHZ_CODE, Scope.OPENID, false, ajaxRequest, STATE, NONCE);
}

From source file:models.Search.java

private void initResults() {
    Pair<List<Document>, Long> result = doSearch();
    this.documents = result.getLeft();
    this.hitCount = result.getRight();
}

From source file:fredboat.audio.queue.AudioLoader.java

private void loadSplit(AudioTrack at, IdentifierContext ic) {
    if (!(at instanceof YoutubeAudioTrack)) {
        ic.textChannel.sendMessage(I18n.get(ic.textChannel.getGuild()).getString("loadSplitNotYouTube"))
                .queue();//from w w w.jav a 2 s. c  o  m
        return;
    }
    YoutubeAudioTrack yat = (YoutubeAudioTrack) at;

    YoutubeVideo yv = YoutubeAPI.getVideoFromID(yat.getIdentifier(), true);
    String desc = yv.getDescription();
    Matcher m = SPLIT_DESCRIPTION_PATTERN.matcher(desc);

    ArrayList<Pair<Long, String>> pairs = new ArrayList<>();

    while (m.find()) {
        long timestamp;
        try {
            timestamp = TextUtils.parseTimeString(m.group(2));
        } catch (NumberFormatException e) {
            continue;
        }

        String title1 = m.group(1);
        String title2 = m.group(3);

        if (title1.length() > title2.length()) {
            pairs.add(new ImmutablePair<>(timestamp, title1));
        } else {
            pairs.add(new ImmutablePair<>(timestamp, title2));
        }

    }

    if (pairs.size() < 2) {
        ic.textChannel.sendMessage(I18n.get(ic.textChannel.getGuild()).getString("loadSplitNotResolves"))
                .queue();
        return;
    }

    ArrayList<SplitAudioTrackContext> list = new ArrayList<>();

    int i = 0;
    for (Pair<Long, String> pair : pairs) {
        long startPos;
        long endPos;

        if (i != pairs.size() - 1) {
            // Not last
            startPos = pair.getLeft();
            endPos = pairs.get(i + 1).getLeft();
        } else {
            // Last
            startPos = pair.getLeft();
            endPos = at.getDuration();
        }

        AudioTrack newAt = at.makeClone();
        newAt.setPosition(startPos);

        SplitAudioTrackContext atc = new SplitAudioTrackContext(newAt, ic.member, startPos, endPos,
                pair.getRight());

        list.add(atc);
        gplayer.queue(atc);

        i++;
    }

    MessageBuilder mb = new MessageBuilder()
            .append(I18n.get(ic.textChannel.getGuild()).getString("loadFollowingTracksAdded") + "\n");
    for (SplitAudioTrackContext atc : list) {
        mb.append("`[").append(TextUtils.formatTime(atc.getEffectiveDuration())).append("]` ")
                .append(atc.getEffectiveTitle()).append("\n");
    }

    //This is pretty spammy .. let's use a shorter one
    if (mb.length() > 800) {
        mb = new MessageBuilder().append(MessageFormat
                .format(I18n.get(ic.textChannel.getGuild()).getString("loadPlaylistTooMany"), list.size()));
    }

    context.textChannel.sendMessage(mb.build()).queue();

}

From source file:com.minlia.cloud.framework.test.common.client.template.AbstractTestRestTemplate.java

@Override
public final RequestSpecification givenReadAuthenticated() {
    final Pair<String, String> credentials = getReadCredentials();
    return auth.givenBasicAuthenticated(credentials.getLeft(), credentials.getRight());
}

From source file:com.minlia.cloud.framework.test.common.client.template.AbstractTestRestTemplate.java

final RequestSpecification givenWriteAuthenticated() {
    final Pair<String, String> credentials = getWriteCredentials();
    return auth.givenBasicAuthenticated(credentials.getLeft(), credentials.getRight());
}

From source file:com.minlia.cloud.framework.test.common.client.template.AbstractTestRestTemplate.java

final RequestSpecification givenDeleteAuthenticated() {
    final Pair<String, String> credentials = getWriteCredentials();
    return auth.givenBasicAuthenticated(credentials.getLeft(), credentials.getRight());
}

From source file:com.twitter.distributedlog.logsegment.TestLogSegmentCache.java

@Test(timeout = 60000)
public void testDiff() {
    LogSegmentCache cache = new LogSegmentCache("test-diff");
    // add 5 completed log segments
    for (int i = 1; i <= 5; i++) {
        LogSegmentMetadata metadata = DLMTestUtil.completedLogSegment("/segment" + i, i, i, i * 100L, 100, i,
                99L, 0L);//from   www  .  j a v a  2s  .c o m
        String name = DLMTestUtil.completedLedgerZNodeNameWithLogSegmentSequenceNumber(i);
        cache.add(name, metadata);
    }
    // add one inprogress log segment
    LogSegmentMetadata inprogress = DLMTestUtil.inprogressLogSegment("/inprogress-6", 6, 600L, 6);
    String name = DLMTestUtil.inprogressZNodeName(6);
    cache.add(name, inprogress);

    // deleted first 2 completed log segments and completed the last one
    Set<String> segmentRemoved = Sets.newHashSet();
    for (int i = 1; i <= 2; i++) {
        segmentRemoved.add(DLMTestUtil.completedLedgerZNodeNameWithLogSegmentSequenceNumber(i));
    }
    segmentRemoved.add((DLMTestUtil.inprogressZNodeName(6)));
    Set<String> segmentReceived = Sets.newHashSet();
    Set<String> segmentAdded = Sets.newHashSet();
    for (int i = 3; i <= 6; i++) {
        segmentReceived.add(DLMTestUtil.completedLedgerZNodeNameWithLogSegmentSequenceNumber(i));
        if (i == 6) {
            segmentAdded.add(DLMTestUtil.completedLedgerZNodeNameWithLogSegmentSequenceNumber(i));
        }
    }

    Pair<Set<String>, Set<String>> segmentChanges = cache.diff(segmentReceived);
    assertTrue("Should remove " + segmentRemoved + ", but removed " + segmentChanges.getRight(),
            Sets.difference(segmentRemoved, segmentChanges.getRight()).isEmpty());
    assertTrue("Should add " + segmentAdded + ", but added " + segmentChanges.getLeft(),
            Sets.difference(segmentAdded, segmentChanges.getLeft()).isEmpty());
}

From source file:de.ks.activity.context.ActivityContext.java

@SuppressWarnings("unchecked")
@Override//from  ww w .j a  v  a 2s . c om
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
    if (contextual instanceof Bean) {
        Bean bean = (Bean) contextual;
        Pair<String, Class<?>> key = getKey(bean);

        lock.writeLock().lock();
        try {
            Object o = bean.create(creationalContext);
            StoredBean storedBean = new StoredBean(bean, creationalContext, o);
            activities.get(key.getLeft()).put(key.getRight(), storedBean);
            return (T) o;
        } finally {
            lock.writeLock().unlock();
        }
    }
    return null;
}

From source file:io.prestosql.plugin.accumulo.index.ColumnCardinalityCache.java

/**
 * Gets the cardinality for each {@link AccumuloColumnConstraint}.
 * Given constraints are expected to be indexed! Who knows what would happen if they weren't!
 *
 * @param schema Schema name/*w ww. j  a  v a2 s  .  com*/
 * @param table Table name
 * @param auths Scan authorizations
 * @param idxConstraintRangePairs Mapping of all ranges for a given constraint
 * @param earlyReturnThreshold Smallest acceptable cardinality to return early while other tasks complete
 * @param pollingDuration Duration for polling the cardinality completion service
 * @return An immutable multimap of cardinality to column constraint, sorted by cardinality from smallest to largest
 * @throws TableNotFoundException If the metrics table does not exist
 * @throws ExecutionException If another error occurs; I really don't even know anymore.
 */
public Multimap<Long, AccumuloColumnConstraint> getCardinalities(String schema, String table,
        Authorizations auths, Multimap<AccumuloColumnConstraint, Range> idxConstraintRangePairs,
        long earlyReturnThreshold, Duration pollingDuration) {
    // Submit tasks to the executor to fetch column cardinality, adding it to the Guava cache if necessary
    CompletionService<Pair<Long, AccumuloColumnConstraint>> executor = new ExecutorCompletionService<>(
            executorService);
    idxConstraintRangePairs.asMap().forEach((key, value) -> executor.submit(() -> {
        long cardinality = getColumnCardinality(schema, table, auths, key.getFamily(), key.getQualifier(),
                value);
        LOG.debug("Cardinality for column %s is %s", key.getName(), cardinality);
        return Pair.of(cardinality, key);
    }));

    // Create a multi map sorted by cardinality
    ListMultimap<Long, AccumuloColumnConstraint> cardinalityToConstraints = MultimapBuilder.treeKeys()
            .arrayListValues().build();
    try {
        boolean earlyReturn = false;
        int numTasks = idxConstraintRangePairs.asMap().entrySet().size();
        do {
            // Sleep for the polling duration to allow concurrent tasks to run for this time
            Thread.sleep(pollingDuration.toMillis());

            // Poll each task, retrieving the result if it is done
            for (int i = 0; i < numTasks; ++i) {
                Future<Pair<Long, AccumuloColumnConstraint>> futureCardinality = executor.poll();
                if (futureCardinality != null && futureCardinality.isDone()) {
                    Pair<Long, AccumuloColumnConstraint> columnCardinality = futureCardinality.get();
                    cardinalityToConstraints.put(columnCardinality.getLeft(), columnCardinality.getRight());
                }
            }

            // If the smallest cardinality is present and below the threshold, set the earlyReturn flag
            Optional<Entry<Long, AccumuloColumnConstraint>> smallestCardinality = cardinalityToConstraints
                    .entries().stream().findFirst();
            if (smallestCardinality.isPresent()) {
                if (smallestCardinality.get().getKey() <= earlyReturnThreshold) {
                    LOG.info("Cardinality %s, is below threshold. Returning early while other tasks finish",
                            smallestCardinality);
                    earlyReturn = true;
                }
            }
        } while (!earlyReturn && cardinalityToConstraints.entries().size() < numTasks);
    } catch (ExecutionException | InterruptedException e) {
        if (e instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        }
        throw new PrestoException(UNEXPECTED_ACCUMULO_ERROR, "Exception when getting cardinality", e);
    }

    // Create a copy of the cardinalities
    return ImmutableMultimap.copyOf(cardinalityToConstraints);
}

From source file:net.malisis.doors.gui.VanishingDiamondGui.java

@Subscribe
public void onConfigChanged(ComponentEvent.ValueChange event) {
    Pair<ForgeDirection, DataType> data = (Pair<ForgeDirection, DataType>) event.getComponent().getData();
    int time = event.getComponent() instanceof UITextField ? NumberUtils.toInt((String) event.getNewValue())
            : 0;//from  w  w  w.ja  v  a  2s .  c o m
    boolean checked = event.getComponent() instanceof UICheckBox ? (boolean) event.getNewValue() : false;
    VanishingDiamondFrameMessage.sendConfiguration(tileEntity, data.getLeft(), data.getRight(), time, checked);
}