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

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

Introduction

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

Prototype

public ImmutablePair(final L left, final R right) 

Source Link

Document

Create a new pair instance.

Usage

From source file:cgeo.geocaching.CacheDetailActivity.java

@Override
protected Pair<List<? extends Page>, Integer> getOrderedPages() {
    final ArrayList<Page> pages = new ArrayList<>();
    pages.add(Page.WAYPOINTS);/*from w ww .j  a v a2 s .  c om*/
    pages.add(Page.DETAILS);
    final int detailsIndex = pages.size() - 1;
    pages.add(Page.DESCRIPTION);
    // enforce showing the empty log book if new entries can be added
    if (cache.supportsLogging() || !cache.getLogs().isEmpty()) {
        pages.add(Page.LOGS);
    }
    if (CollectionUtils.isNotEmpty(cache.getFriendsLogs())) {
        pages.add(Page.LOGSFRIENDS);
    }
    if (CollectionUtils.isNotEmpty(cache.getInventory()) || CollectionUtils.isNotEmpty(genericTrackables)) {
        pages.add(Page.INVENTORY);
    }
    if (CollectionUtils.isNotEmpty(cache.getNonStaticImages())) {
        pages.add(Page.IMAGES);
    }
    return new ImmutablePair<List<? extends Page>, Integer>(pages, detailsIndex);
}

From source file:blusunrize.immersiveengineering.client.ClientProxy.java

private Pair<String, IManualPage[]> addVersionToManual(ComparableVersion currVer, ComparableVersion version,
        String changes, boolean ahead) {
    String title = version.toString();
    if (ahead)/*from  ww  w  .ja  v  a  2  s .c  o m*/
        title += I18n.format("ie.manual.newerVersion");
    else {
        int cmp = currVer.compareTo(version);
        if (cmp == 0)
            title += I18n.format("ie.manual.currentVersion");
        else if (cmp < 0)
            return null;
    }

    List<String> l = ManualHelper.getManual().fontRenderer
            .listFormattedStringToWidth(changes.replace("\t", "  "), 120);
    final int LINES_PER_PAGE = 16;
    int pageCount = l.size() / LINES_PER_PAGE + (l.size() % LINES_PER_PAGE == 0 ? 0 : 1);
    ManualPages.Text[] pages = new ManualPages.Text[pageCount];
    for (int i = 0; i < pageCount; i++) {
        StringBuilder nextPage = new StringBuilder();
        for (int j = LINES_PER_PAGE * i; j < l.size() && j < (i + 1) * LINES_PER_PAGE; j++)
            nextPage.append(l.get(j)).append("\n");
        pages[i] = new ManualPages.Text(ManualHelper.getManual(), nextPage.toString());
    }
    return new ImmutablePair<>(title, pages);
}

From source file:com.google.bitcoin.core.Wallet.java

public void sign(SendRequest sendRequest) throws CSExceptions.CannotEncode {
    // Now sign the inputs, thus proving that we are entitled to redeem the connected outputs.

    try {/*from   w w  w. j a v a 2 s. co  m*/
        sendRequest.tx.signInputs(Transaction.SigHash.ALL, this, sendRequest.aesKey);
    } catch (ScriptException e) {
        // If this happens it means an output script in a wallet tx could not be understood. That should never
        // happen, if it does it means the wallet has got into an inconsistent state.
        throw new RuntimeException(e);
    }
    /* CSPK-mike START */
    // After inputs are signed we can send messahe ot delivery server
    if (sendRequest.messageToCreate != null) {
        ImmutablePair<Integer, String> payload = new ImmutablePair<Integer, String>(sendRequest.hashCode(),
                sendRequest.messageToCreate.getServerURL());
        try {
            CSEventBus.INSTANCE.postAsyncEvent(CSEventType.MESSAGE_UPLOAD_STARTED, payload);
            if (sendRequest.messageParts != null) {
                CS.log.info("Sending message for tx " + sendRequest.tx.getHashAsString()
                        + " to delivery server " + sendRequest.messageToCreate.getServerURL());
                sendRequest.messageToCreate.setTxID(sendRequest.tx.getHashAsString());

                // Enable sending from wallets with password
                sendRequest.messageToCreate.setAesKey(sendRequest.aesKey);

                try {
                    if (!sendRequest.messageToCreate.create(this, sendRequest.messageParts,
                            sendRequest.createNonce)) {
                        throw new CSExceptions.CannotEncode("Cannot send message to delivery server");
                    }
                } catch (CSExceptions.CannotEncode e) {
                    // Catch error if create() throws an exception, or result was false
                    CS.log.info("Cannot create message for tx " + sendRequest.tx.getHashAsString()
                            + " on delivery server " + sendRequest.messageToCreate.getServerURL());
                    throw e;
                }
            }

            if (!CS.messageDB.insertSentMessage(sendRequest.tx.getHashAsString(),
                    sendRequest.tx.getOutputs().size(), sendRequest.messageToCreate.getPaymentRef(),
                    sendRequest.message, sendRequest.messageParts,
                    sendRequest.messageToCreate.getMessageParams())) {
                CS.log.info("Cannot store message for tx " + sendRequest.tx.getHashAsString());
                throw new CSExceptions.CannotEncode("Cannot store message in the database");
            }

            if (sendRequest.messageParts != null) {
                CS.log.info("Message for tx " + sendRequest.tx.getHashAsString()
                        + " was successfully sent via delivery server "
                        + sendRequest.messageToCreate.getServerURL());
            }

        } finally {
            CSEventBus.INSTANCE.postAsyncEvent(CSEventType.MESSAGE_UPLOAD_ENDED, payload);
        }
    }
    /* CSPK-mike END */
}

From source file:l2next.gameserver.model.Player.java

public void ask(ConfirmDlg dlg, OnAnswerListener listener) {
    if (_askDialog != null) {
        return;/*from  www  .j  a  v a2  s  . c  om*/
    }
    int rnd = Rnd.nextInt();
    _askDialog = new ImmutablePair<Integer, OnAnswerListener>(rnd, listener);
    dlg.setRequestId(rnd);
    sendPacket(dlg);
}

From source file:lineage2.gameserver.model.Player.java

/**
 * Method ask./*  w  w  w .j  a  va  2s.  co m*/
 * @param dlg ConfirmDlg
 * @param listener OnAnswerListener
 */
public void ask(ConfirmDlg dlg, OnAnswerListener listener) {
    if (_askDialog != null) {
        return;
    }
    int rnd = Rnd.nextInt();
    _askDialog = new ImmutablePair<Integer, OnAnswerListener>(rnd, listener);
    dlg.setRequestId(rnd);
    sendPacket(dlg);
}

From source file:nl.b3p.viewer.config.services.WMSService.java

/**
 * Update the tree structure of Layers by following the tree structure and
 * setting the parent and children accordingly. Reuses entities for layers
 * which are UNMODIFIED or UPDATED and inserts new entities for NEW layers.
 * <p>/*from w w  w  . ja va 2  s.c  o m*/
 * Because virtual layers with null name cannot be updated, those are always
 * recreated and user set properties are lost, except those set on the top
 * layer which are preserved.
 * <p>
 * Interface should disallow setting user properties (especially authorizations)
 * on virtual layers.
 */
private void updateLayerTree(final WMSService update, final UpdateResult result) {

    Layer newTopLayer;

    String topLayerName = update.getTopLayer().getName();
    if (topLayerName == null) {
        // Start with a new no name topLayer
        newTopLayer = update.getTopLayer().pluckCopy();
    } else {
        // Old persistent top layer or new plucked copy from updated service
        newTopLayer = result.getLayerStatus().get(topLayerName).getLeft();
    }

    // Copy user set stuff over from old toplayer, even if name was changed
    // or topLayer has no name
    newTopLayer.copyUserModifiedProperties(getTopLayer());

    newTopLayer.setParent(null);
    newTopLayer.setService(this);
    newTopLayer.getChildren().clear();
    setTopLayer(newTopLayer);

    // Do a breadth-first traversal to set the parent and fill the children
    // list of all layers.
    // For the breadth-first traversal save layers from updated service to
    // visit with their (possibly persistent) parent layers from this service

    // XXX why did we need BFS?

    Queue<Pair<Layer, Layer>> q = new LinkedList();

    // Start at children of topLayer from updated service, topLayer handled
    // above
    for (Layer child : update.getTopLayer().getChildren()) {
        q.add(new ImmutablePair(child, newTopLayer));
    }

    Set<String> visitedLayerNames = new HashSet();

    do {
        // Remove from head of queue
        Pair<Layer, Layer> p = q.remove();

        Layer updateLayer = p.getLeft(); // layer from updated service
        Layer parent = p.getRight(); // parent layer from this

        Layer thisLayer;
        String layerName = updateLayer.getName();
        if (layerName == null) {
            // 'New' no name layer - we can't possibly guess if it is
            // the same as an already existing no name layer so always
            // new entity
            thisLayer = updateLayer.pluckCopy();
        } else {

            if (visitedLayerNames.contains(layerName)) {
                // Duplicate layer in updated service -- ignore this one
                thisLayer = null;
            } else {
                // Find possibly already persistent updated layer
                // (depth first) - if new already a pluckCopy()
                thisLayer = result.getLayerStatus().get(layerName).getLeft();
                visitedLayerNames.add(layerName);
            }
        }

        if (thisLayer != null) {
            thisLayer.setService(this);
            thisLayer.setParent(parent);
            parent.getChildren().add(thisLayer);
        }

        for (Layer child : updateLayer.getChildren()) {
            // Add add end of queue
            q.add(new ImmutablePair(child, thisLayer));
        }
    } while (!q.isEmpty());
}

From source file:nl.basjes.parse.useragent.servlet.ParseService.java

private Response doHTML(String userAgentString) {
    long start = System.nanoTime();

    if (userAgentString == null) {
        return Response.status(Response.Status.PRECONDITION_FAILED)
                .entity("<b><u>The User-Agent header is missing</u></b>").build();
    }/*ww  w.j  a  v a  2 s .  c o m*/

    Response.ResponseBuilder responseBuilder = Response.status(200);

    StringBuilder sb = new StringBuilder(4096);
    try {
        sb.append("<!DOCTYPE html>");
        sb.append("<html><head profile=\"http://www.w3.org/2005/10/profile\">");
        sb.append("<link rel=\"icon\" type=\"image/ico\" href=\"/static/favicon.ico\" />\n");
        sb.append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
        sb.append("<title>Analyzing the useragent</title></head>");
        sb.append("<body>");

        sb.append("<h1>Analyzing your useragent string</h1>");

        sb.append(
                "Build using <a href=\"https://github.com/nielsbasjes/yauaa\">Yauaa (Yet another UserAgent analyzer)</a>.<br/>");
        sb.append(ANALYZER_VERSION).append("<br/>");
        sb.append("<hr/>");

        UserAgent userAgent = parse(userAgentString);

        sb.append("Received useragent: <B>").append(escapeHtml4(userAgent.getUserAgentString())).append("</B>");
        sb.append("<table border=1>");
        sb.append("<tr><th colspan=2>Field</th><th>Value</th></tr>");

        Map<String, Integer> fieldGroupCounts = new HashMap<>();
        List<Pair<String, Pair<String, String>>> fields = new ArrayList<>(32);
        for (String fieldname : userAgent.getAvailableFieldNamesSorted()) {
            Pair<String, String> split = prefixSplitter(fieldname);
            fields.add(new ImmutablePair<>(fieldname, split));
            Integer count = fieldGroupCounts.get(split.getLeft());
            if (count == null) {
                count = 1;
            } else {
                count++;
            }
            fieldGroupCounts.put(split.getLeft(), count);
        }

        String currentGroup = "";
        for (Pair<String, Pair<String, String>> field : fields) {
            String fieldname = field.getLeft();
            String groupName = field.getRight().getLeft();
            String fieldLabel = field.getRight().getRight();
            sb.append("<tr>");
            if (!currentGroup.equals(groupName)) {
                currentGroup = groupName;
                sb.append("<td rowspan=").append(fieldGroupCounts.get(currentGroup)).append("><b><u>")
                        .append(escapeHtml4(currentGroup)).append("</u></b></td>");
            }
            sb.append("<td>").append(camelStretcher(escapeHtml4(fieldLabel))).append("</td>").append("<td>")
                    .append(escapeHtml4(userAgent.getValue(fieldname))).append("</td>").append("</tr>");
        }
        sb.append("</table>");

        addBugReportButton(sb, userAgent);
        //            sb.append("<ul>");
        //            sb.append("<li><a href=\"/\">HTML (from header)</a></li>");
        //            sb.append("<li><a href=\"/json\">Json (from header)</a></li>");
        //
        //            String urlEncodedUserAgent = "";
        //            try {
        //                urlEncodedUserAgent = URLEncoder.encode(userAgentString, "utf-8");
        //                urlEncodedUserAgent = urlEncodedUserAgent.replace("+", "%20");
        //                sb.append("<li><a href=\"/").append(urlEncodedUserAgent).append("\">HTML (from url)</a></li>");
        //                sb.append("<li><a href=\"/json/").append(urlEncodedUserAgent).append("\">Json (from url)</a></li>");
        //            } catch (UnsupportedEncodingException e) {
        //                // Do nothing
        //            }
        //            sb.append("</ul>");

        sb.append("<br/>");
        sb.append("<hr/>");
        sb.append("<form action=\"/\" method=\"post\">");
        sb.append("Manual testing of a useragent:<br>");
        sb.append("<input type=\"text\" name=\"useragent\"  size=\"100\" value=\"")
                .append(escapeHtml4(userAgentString)).append("\">");
        sb.append("<input type=\"submit\" value=\"Analyze\">");
        sb.append("</form>");
        sb.append("<br/>");

        sb.append("<hr/>");
        userAgentString = "Mozilla/5.0 (Linux; Android 7.8.9; nl-nl ; Niels Ultimate 42 demo phone Build/42 ; nl-nl; "
                + "https://github.com/nielsbasjes/yauaa ) AppleWebKit/8.4.7.2 (KHTML, like Gecko) Yet another browser/3.1415926 Mobile Safari/6.6.6";
        sb.append("<form action=\"/\" method=\"post\">");
        sb.append("Try this demo: ");
        sb.append("<input type=\"hidden\" name=\"useragent\"  size=\"100\" value=\"")
                .append(escapeHtml4(userAgentString)).append("\">");
        sb.append("<input type=\"submit\" value=\"Analyze Demo\">");
        sb.append("</form>");

        sb.append("<hr/>");
    } finally {
        long stop = System.nanoTime();
        double milliseconds = (stop - start) / 1000000.0;

        sb.append("<br/>");
        sb.append("<u>Building this page took ").append(String.format(Locale.ENGLISH, "%3.3f", milliseconds))
                .append(" ms.</u><br/>");
        sb.append("</body>");
        sb.append("</html>");
    }
    return responseBuilder.entity(sb.toString()).build();
}

From source file:nssignalprocessing.mathematics.calculus.integraltransform.general.EmpiricalModeDecomposition.java

private static Pair<int[], double[]> getSplineMinMax(Pair<int[], double[]> values, int endValue) {
    int[] x = new int[values.getKey().length + 2];
    double[] y = new double[values.getValue().length + 2];
    //copy original elements
    System.arraycopy(values.getKey(), 0, x, 1, values.getKey().length);
    System.arraycopy(values.getValue(), 0, y, 1, values.getValue().length);
    x[x.length - 1] = endValue;/*  w  ww . j a v  a2s  .  c  om*/
    return new ImmutablePair<>(x, y);
}

From source file:nssignalprocessing.mathematics.calculus.minmax.Maxima.java

/**
 * Find all maxima in the array and return all indexes where local maxima occurs.
 * @param array array where all maxima should be checked
 * @param from start index (included, but maxima not checked for this)
 * @param to (excluded, maxima not checked also for to-1)
 * @return indexes of all local maxima in the given interval. 
 *//*  w  w w.  j  a v a  2 s  . c  o m*/
public static Pair<int[], double[]> getAllMaximaWithIndexes(double[] array, int from, int to) {
    //because just of adding and final conversion into array
    int incConstant = 8;
    int range = to - from;
    int incSize = Math.max(incConstant, range / incConstant);

    int[] rIdx = new int[incSize];
    double[] rVal = new double[incSize];
    int cId = 0;

    //were last two values increasing?
    boolean isInc = array[from] < array[from + 1];
    //even if at the beginning are two equal values, because we do not know 
    //whether it was decreasing or increasing
    int zeroIndex = -1;
    double am1, a, ap1;
    for (int i = from + 1; i < to - 1; i++) {
        am1 = array[i - 1];
        a = array[i];
        ap1 = array[i + 1];
        if (isInc && a == ap1 && am1 != a)
            zeroIndex = i; //only when it was increasing before
        if (isInc && am1 == a && ap1 < a) {
            rIdx[cId] = zeroIndex;
            rVal[cId] = array[zeroIndex];
            cId++;
        }
        if (am1 < a && a > ap1) {
            rIdx[cId] = i;
            rVal[cId] = array[i];
            cId++;
        }
        if (a != ap1)
            isInc = a < ap1;//update only when there is no stagnation
        if (cId == rIdx.length) {
            range = to - i;
            incSize = Math.max(incConstant, range / incConstant);
            rIdx = java.util.Arrays.copyOf(rIdx, rIdx.length + incSize);
            rVal = java.util.Arrays.copyOf(rVal, rIdx.length + incSize);
        }
    }
    return new ImmutablePair<>(java.util.Arrays.copyOf(rIdx, cId), java.util.Arrays.copyOf(rVal, cId));
}

From source file:nssignalprocessing.mathematics.calculus.minmax.Minima.java

/**
 * Find all minima in the array and return all indexes where local minima occurs.
 * @param array array where all minima should be checked
 * @param from start index (included, but minima not checked for this)
 * @param to (excluded, minima not checked also for to-1)
 * @return indexes of all local minima in the given interval. 
 *///  w w w.ja v a  2  s .  c  o m
public static Pair<int[], double[]> getAllMinimaWithIndexes(double[] array, int from, int to) {
    //because just of adding and final conversion into array
    int incConstant = 8;
    int range = to - from;
    int incSize = Math.max(incConstant, range / incConstant);

    int[] rIdx = new int[incSize];
    double[] rVal = new double[incSize];
    int cId = 0;

    //were last two values increasing?
    boolean isDec = array[from] > array[from + 1];
    //even if at the beginning are two equal values, because we do not know 
    //whether it was decreasing or increasing
    int zeroIndex = -1;
    double am1, a, ap1;
    for (int i = from + 1; i < to - 1; i++) {
        am1 = array[i - 1];
        a = array[i];
        ap1 = array[i + 1];
        if (isDec && a == ap1 && am1 != a)
            zeroIndex = i; //only when it was increasing before
        if (isDec && am1 == a && ap1 > a) {
            rIdx[cId] = zeroIndex;
            rVal[cId] = array[zeroIndex];
            cId++;
        }
        if (am1 > a && a < ap1) {
            rIdx[cId] = i;
            rVal[cId] = array[i];
            cId++;
        }
        if (a != ap1)
            isDec = a > ap1;//update only when there is no stagnation
        if (cId == rIdx.length) {
            range = to - i;
            incSize = Math.max(incConstant, range / incConstant);
            rIdx = java.util.Arrays.copyOf(rIdx, rIdx.length + incSize);
            rVal = java.util.Arrays.copyOf(rVal, rIdx.length + incSize);
        }
    }
    return new ImmutablePair<>(java.util.Arrays.copyOf(rIdx, cId), java.util.Arrays.copyOf(rVal, cId));
}