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.github.steveash.guavate.ObjIntPair.java

/**
 * Obtains an instance from a {@code Pair}.
 *
 * @param <A> the first element type
 * @param pair  the pair to convert/*from  w w w . ja v a  2  s .  c o  m*/
 * @return a pair formed by extracting values from the pair
 */
public static <A> ObjIntPair<A> ofPair(Pair<A, Integer> pair) {
    Preconditions.checkNotNull(pair, "pair");
    return new ObjIntPair<A>(pair.getLeft(), pair.getRight());
}

From source file:cn.lambdalib.util.client.font.Fragmentor.java

public static List<String> toMultiline(String str, IFontSizeProvider font, double local_x, double limit) {
    Fragmentor frag = new Fragmentor(str);
    List<String> ret = new ArrayList<>();

    StringBuilder builder = new StringBuilder();
    while (frag.hasNext()) {
        Pair<TokenType, String> next = frag.next();
        TokenType type = next.getLeft();
        String content = next.getRight();
        double len = font.getTextWidth(content);
        if (local_x + len > limit) {
            if (!type.canSplit) { // Draws as whole in next line
                if (builder.length() > 0) {
                    ret.add(builder.toString());
                }/*from w  w  w  .ja v a  2  s  .  c  o  m*/
                builder.setLength(0);
                builder.append(content);
                local_x = len;
            } else { // Seperate to this line and next line
                while (!content.isEmpty()) {
                    double acc = 0.0;
                    int i = 0;
                    for (; i < content.length() && local_x + acc <= limit; ++i) {
                        acc += font.getCharWidth(content.charAt(i));
                    }

                    if (i < content.length() && isPunct(content.charAt(i))) {
                        ++i;
                    }

                    builder.append(content.substring(0, i));
                    String add = builder.toString();
                    ret.add(add);

                    builder.setLength(0);
                    local_x = 0;

                    content = content.substring(i);
                }
            }
        } else {
            builder.append(content);
            local_x += len;
        }
    }

    if (builder.length() > 0) {
        ret.add(builder.toString());
    }

    return ret;
}

From source file:com.pinterest.terrapin.base.FutureUtil.java

/**
 * Run speculative execution for a set of futures. This is especially useful for improving latency
 * and surviving failures. The provided BackupFutureRetryPolicy will decide whether the backup
 * future should be fired or not. The 1st future which returns successfully is returned.
 *
 * @param originalFuture The original future which has already been issued.
 * @param functionBackupFuture A function which can issue the backup future once @waitTimeMillis
 *                             has expired.
 * @param waitTimeMillis The time to wait in milliseconds before issuing the backup future.
 * @param statsPrefix The stats prefix to be prefixed with recorded stats such as "won", "lost"
 *                    and "backup-fired".
 * @param retryPolicy decides whether the backup future should be fired if the original future
 *                    fails//from  www.j a  v a2 s .  c om
 * @param <T>
 * @return Returns a future which encapsulates the speculative execution strategy.
 */
public static <T> Future<T> getSpeculativeFuture(final Future<T> originalFuture,
        final Function0<Future<T>> functionBackupFuture, long waitTimeMillis, final String statsPrefix,
        final BackupFutureRetryPolicy retryPolicy) {
    return originalFuture.within(Duration.fromMilliseconds(waitTimeMillis), timer)
            .rescue(new Function<Throwable, Future<T>>() {
                public Future<T> apply(Throwable t) {
                    if (retryPolicy.isRetriable(t)) {
                        final Future<T> backupFuture = functionBackupFuture.apply();
                        Stats.incr(statsPrefix + "-backup-fired");
                        // Build information into each future as to whether this is the original
                        // future or the backup future.
                        final Future<Pair<Boolean, T>> originalFutureWithInfo = originalFuture
                                .map(new Function<T, Pair<Boolean, T>>() {
                                    public Pair<Boolean, T> apply(T t) {
                                        return new ImmutablePair(true, t);
                                    }
                                });
                        final Future<Pair<Boolean, T>> backupFutureWithInfo = backupFuture
                                .map(new Function<T, Pair<Boolean, T>>() {
                                    public Pair<Boolean, T> apply(T t) {
                                        return new ImmutablePair(false, t);
                                    }
                                });
                        // If there is an exception, the first future throwing the exception will
                        // return. Instead we want the 1st future which is successful.
                        Future<Pair<Boolean, T>> origFutureSuccessful = originalFutureWithInfo
                                .rescue(new Function<Throwable, Future<Pair<Boolean, T>>>() {
                                    public Future<Pair<Boolean, T>> apply(Throwable t) {
                                        // Fall back to back up future which may also fail in which case we bubble
                                        // up the exception.
                                        return backupFutureWithInfo;
                                    }
                                });
                        Future<Pair<Boolean, T>> backupFutureSuccessful = backupFutureWithInfo
                                .rescue(new Function<Throwable, Future<Pair<Boolean, T>>>() {
                                    public Future<Pair<Boolean, T>> apply(Throwable t) {
                                        // Fall back to original Future which may also fail in which case we bubble
                                        // up the exception.
                                        return originalFutureWithInfo;
                                    }
                                });
                        return origFutureSuccessful.select(backupFutureSuccessful)
                                .map(new Function<Pair<Boolean, T>, T>() {
                                    public T apply(Pair<Boolean, T> tuple) {
                                        if (tuple.getLeft()) {
                                            Stats.incr(statsPrefix + "-won");
                                        } else {
                                            Stats.incr(statsPrefix + "-lost");
                                        }
                                        return tuple.getRight();
                                    }
                                });
                    } else {
                        return Future.exception(t);
                    }
                }
            });
}

From source file:com.epam.catgenome.util.HistogramUtils.java

/**
 * Creates a {@link Wig} histogram block and adds it to histogram portion, if blockValue > 0
 * @param histogram a List of {@link Wig} blocks, representing histogram
 * @param blockValue a value of histogram block, e.g. amount of features, fitting in interval
 * @param interval block's interval//  w w  w.ja  va2 s.c  om
 */
public static void addToHistogramPortion(final List<Wig> histogram, final int blockValue,
        final Pair<Integer, Integer> interval) {
    if (blockValue > 0) {
        Wig result = new Wig();
        result.setStartIndex(interval.getLeft());
        result.setEndIndex(interval.getRight());
        result.setValue((float) blockValue);

        histogram.add(result);
    }
}

From source file:com.twitter.distributedlog.TestDistributedLogBase.java

@BeforeClass
public static void setupCluster() throws Exception {
    File zkTmpDir = IOUtils.createTempDir("zookeeper", "distrlog");
    tmpDirs.add(zkTmpDir);//from  w  w  w . java 2 s. c  o m
    Pair<ZooKeeperServerShim, Integer> serverAndPort = LocalDLMEmulator.runZookeeperOnAnyPort(zkTmpDir);
    zks = serverAndPort.getLeft();
    zkPort = serverAndPort.getRight();
    bkutil = LocalDLMEmulator.newBuilder().numBookies(numBookies).zkHost("127.0.0.1").zkPort(zkPort)
            .serverConf(DLMTestUtil.loadTestBkConf()).shouldStartZK(false).build();
    bkutil.start();
    zkServers = "127.0.0.1:" + zkPort;
}

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

private static Map<String, Pair<ApprovalPolicyActionType, EvaluatedPolicyRule>> createActionsMap(
        Collection<List<Pair<ApprovalPolicyActionType, EvaluatedPolicyRule>>> allActionsWithRules) {
    Map<String, Pair<ApprovalPolicyActionType, EvaluatedPolicyRule>> rv = new HashMap<>();
    for (List<Pair<ApprovalPolicyActionType, EvaluatedPolicyRule>> actionsWithRules : allActionsWithRules) {
        for (Pair<ApprovalPolicyActionType, EvaluatedPolicyRule> actionWithRule : actionsWithRules) {
            if (actionWithRule.getLeft().getName() != null) {
                rv.put(actionWithRule.getLeft().getName(), actionWithRule);
            }/*from   w  ww .  j  a v  a2 s .  com*/
        }
    }
    return rv;
}

From source file:alfio.model.modification.support.LocationDescriptor.java

public static LocationDescriptor fromGeoData(Pair<String, String> coordinates, TimeZone timeZone,
        Map<ConfigurationKeys, Optional<String>> geoConf) {
    Map<String, String> params = new HashMap<>();
    String lat = coordinates.getLeft();
    String lng = coordinates.getRight();
    params.put("latitude", lat);
    params.put("longitude", lng);

    return new LocationDescriptor(timeZone.getID(), coordinates.getLeft(), coordinates.getRight(),
            getMapUrl(lat, lng, geoConf));
}

From source file:edu.wpi.checksims.testutil.AlgorithmUtils.java

/**
 * Ensure that every pair in a set of pairs is representing in algorithm results
 *
 * @param results Collection of algorithm results to check in
 * @param pairs Pairs of submissions to search for in the results
 */// w w w.j av  a 2 s  . c om
public static void checkResultsContainsPairs(Collection<AlgorithmResults> results,
        Set<Pair<Submission, Submission>> pairs) {
    assertNotNull(results);
    assertNotNull(pairs);

    assertEquals(results.size(), pairs.size());

    for (Pair<Submission, Submission> pair : pairs) {
        long numWithResult = results.stream().filter((result) -> {
            return (result.a.equals(pair.getLeft()) && result.b.equals(pair.getRight()))
                    || (result.a.equals(pair.getRight()) && result.b.equals(pair.getLeft()));
        }).count();

        assertEquals(1, numWithResult);
    }
}

From source file:com.nttec.everychan.ui.tabs.LocalHandler.java

public static TabModel getTabModel(String filename, Resources resources) {
    File file = new File(filename);
    if (file.exists() && !file.isDirectory()) {
        String lfilename = filename.toLowerCase(Locale.US);
        if (!lfilename.endsWith(".zip") && !lfilename.endsWith(".mht") && !lfilename.endsWith(".mhtml")) {
            file = file.getParentFile();
            filename = file.getAbsolutePath();
        }//from w ww  .  ja va  2s .  c  o m
    }

    ReadableContainer zip = null;
    UrlPageModel pageModel;
    String pageTitle;
    try {
        zip = ReadableContainer.obtain(file);
        Pair<String, UrlPageModel> p = MainApplication.getInstance().serializer
                .loadPageInfo(zip.openStream(DownloadingService.MAIN_OBJECT_FILE));
        pageTitle = p.getLeft();
        pageModel = p.getRight();
    } catch (Exception e) {
        Logger.e(TAG, e);
        MainApplication.getInstance().database.removeSavedThread(filename);
        return null;
    } finally {
        try {
            if (zip != null)
                zip.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    TabModel model = new TabModel();
    model.type = TabModel.TYPE_LOCAL;
    model.id = new Random().nextLong();
    model.title = pageTitle;
    model.pageModel = pageModel;
    model.hash = CryptoUtils.computeMD5(filename);
    try {
        model.webUrl = MainApplication.getInstance().getChanModule(pageModel.chanName).buildUrl(pageModel);
    } catch (IllegalArgumentException e) {
        model.webUrl = null;
    } catch (NullPointerException e) {
        return null;
    }
    model.localFilePath = filename;
    model.forceUpdate = true;
    return model;
}

From source file:com.formkiq.core.webflow.FlowManager.java

/**
 * Finds the current {@link WebFlow} if one exists.
 * @param req {@link HttpServletRequest}
 * @return {@link WebFlow}/* ww  w.  j a v  a 2s.c om*/
 */
private static WebFlow getCurrentWebFlow(final HttpServletRequest req) {

    Pair<String, Integer> webflowkey = getExecutionSessionKey(req.getParameter(PARAMETER_EXECUTION));
    String sessionKey = webflowkey.getLeft();

    if (StringUtils.hasText(sessionKey)) {
        Object obj = req.getSession().getAttribute(sessionKey);
        if (obj instanceof WebFlow) {
            WebFlow wf = (WebFlow) obj;
            return wf;
        }
    }

    throw new FlowNotFoundException();
}