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:com.jfinal.ext.plugin.sqlinxml.SqlKit.java

@SuppressWarnings("unchecked")
private static void parseSql(File xmlfile, boolean override, Map<String, Object> sqlMap,
        Map<String, Pair<Class<?>, String>> modelMapping) {
    SqlGroup group = JaxbKit.unmarshal(xmlfile, SqlGroup.class);
    String name = group.name;/*w ww .  jav  a  2s  .  co  m*/
    if (name == null || name.trim().equals("")) {
        name = xmlfile.getName();
    }

    for (SqlValueItem sqlItem : group.sqlValues) {
        String sqlKey = name + "." + sqlItem.id;
        if (!override) {
            if (!sqlMap.containsKey(sqlKey)) {
                sqlMap.put(sqlKey, sqlItem);
                LOG.debug("load sql " + sqlKey);
            } else {
                LOG.error("already contain sql " + sqlKey);
            }
        } else {
            sqlMap.put(sqlKey, sqlItem);
            LOG.info("load sql " + sqlKey);
        }
    }

    for (SqlClauseItem sqlItem : group.sqlClauseItems) {
        String sqlKey = name + "." + sqlItem.id;
        if (!override) {
            if (!sqlMap.containsKey(sqlKey)) {
                sqlMap.put(sqlKey, sqlItem);
                LOG.debug("load sql " + sqlKey);
            } else {
                LOG.error("already contain sql " + sqlKey);
            }
        } else {
            sqlMap.put(sqlKey, sqlItem);
            LOG.info("load sql " + sqlKey);
        }
    }

    ModelMapping mMapping = group.modelMapping;
    if (mMapping != null) {
        for (ModelItem item : mMapping.modelItems) {
            Class<? extends Model<?>> modelClaz;
            try {
                modelClaz = (Class<Model<?>>) Class.forName(item.model, true,
                        Thread.currentThread().getContextClassLoader());
                String alias = item.alias;
                if (alias != null) {
                    for (String al : alias.split(",")) {
                        modelMapping.put(al, new ImmutablePair<Class<?>, String>(modelClaz, item.name));
                    }
                } else {
                    LOG.error("model " + item.model + "'s alias can't be null");
                }
            } catch (ClassNotFoundException e) {
                LOG.error("{}", e);
            }
        }
    }
}

From source file:hu.ppke.itk.nlpg.purepos.model.internal.NGramModel.java

/**
 * Finds the maximal frequency element in a nodelist.
 * /*from   ww w.ja  va  2  s.com*/
 * @param list
 * @param word
 * @return
 */
protected Pair<Integer, Double> findMax(ArrayList<TrieNode<Integer, Integer, W>> list, W word) {

    Integer maxPos;
    Double maxVal;
    if (!(list == null || list.size() == 0)) {
        maxPos = -1;
        maxVal = 0.0;
        for (int i = list.size() - 1; i >= 0; --i) {
            double val = calculateModifiedFreqVal(list, i, word);
            if (val > maxVal) {
                maxPos = i;
                maxVal = val;
            }

        }
    } else {
        maxPos = null;
        maxVal = null;
    }
    ImmutablePair<Integer, Double> ret = new ImmutablePair<Integer, Double>(maxPos, maxVal);
    return ret;
}

From source file:com.romeikat.datamessie.core.statistics.service.StatisticsService.java

public <T> SparseSingleTable<Long, LocalDate, T> getStatistics(final StatisticsSparseTable baseStatistics,
        final Collection<Long> sourceIds, final LocalDate from, final LocalDate to,
        final Function<LocalDate, LocalDate> transformDateFunction,
        final Function<DocumentsPerState, T> transformValueFunction) {
    final MergeNumberOfDocumentsFunction mergeNumberOfDocumentsFunction = new MergeNumberOfDocumentsFunction();
    final ITableExtractor<Long, LocalDate, DocumentsPerState, T> tableExtractor = new ITableExtractor<Long, LocalDate, DocumentsPerState, T>() {

        @Override//from  ww  w.  j  av  a 2  s .  c  o  m
        public Long getExtractedRowHeader(final Long sourceId) {
            if (sourceIds.contains(sourceId)) {
                return sourceId;
            }
            return null;
        }

        @Override
        public LocalDate getExtractedColumnHeader(final LocalDate publishedDate) {
            if (from != null && publishedDate.isBefore(from)) {
                return null;
            }
            if (to != null && publishedDate.isAfter(to)) {
                return null;
            }

            final LocalDate transformedPublishedDate = transformDateFunction.apply(publishedDate);
            return transformedPublishedDate;
        }

        @Override
        public DocumentsPerState mergeValues(final DocumentsPerState documentsPerState1,
                final DocumentsPerState documentsPerState2) {
            return mergeNumberOfDocumentsFunction.apply(new ImmutablePair<DocumentsPerState, DocumentsPerState>(
                    documentsPerState1, documentsPerState2));
        }

        @Override
        public T getExtractedValue(final DocumentsPerState documentsPerState) {
            return transformValueFunction.apply(documentsPerState);
        }

    };

    final SparseSingleTable<Long, LocalDate, T> extractedStatistics = baseStatistics.extract(tableExtractor);

    // extractedStatistics only contains row headers for source IDs that were reported within the
    // time period; in order to cover all source IDs, we add all (remaining) source IDs
    extractedStatistics.addRowHeaders(sourceIds);

    // extractedStatistics only contains column headers for dates that were reported within the time
    // period; in order to cover all dates, we add all (remaining) dates
    final List<LocalDate> publishedDates = DateUtil.getLocalDatesBetween(from, to);
    final List<LocalDate> transformedPublishedDates = Lists.transform(publishedDates, transformDateFunction);
    extractedStatistics.addColumnHeaders(transformedPublishedDates);

    return extractedStatistics;
}

From source file:eu.nerdz.api.impl.fastreverse.messages.FastReverseConversationHandler.java

/**
 * This is the only method that needs of being overloaded, because it does all message fetching.
 * {@inheritDoc}//w w w.  jav  a  2s.co  m
 */
@Override
protected Pair<List<Message>, Boolean> getMessagesAndCheck(Conversation conversation, int start, int howMany)
        throws IOException, HttpException, ContentException {

    if (howMany > 30) {
        howMany = 30;
    }

    if (start == 0 && howMany == 1 && conversation instanceof FastReverseConversation) { //FastReverseConversations contain the content of the last message - so we take this fast path.

        Pair<String, Boolean> lastInfo = ((FastReverseConversation) conversation).getLastMessageInfo();

        List<Message> lastMessage = new ArrayList<Message>(1);
        lastMessage.add(new FastReverseMessage(conversation, this.mUserInfo, conversation.getLastDate(),
                lastInfo.getLeft(), lastInfo.getRight(), false));

        return new ImmutablePair<List<Message>, Boolean>(lastMessage, false);
    }

    String response = this.mMessenger.get("/fastfetch.json.php?action=messages&otherid="
            + conversation.getOtherID() + "&start=" + start + "&limit=" + (howMany + 1));

    try {

        JSONObject errorObj = new JSONObject(response); //if this raises an exception, it's not an error response
        throw new ContentException(FastReverseErrCode.fromCode(errorObj.getInt("error")).toString());

    } catch (JSONException e) {

        try {

            JSONArray jsonResponse = new JSONArray(response);

            int length = jsonResponse.length();

            boolean hasMore = length > howMany; //if howMany is n, previously i've tried to fetch n + 1; if the number of elements fetched is really n + 1 this means that there are more messages.

            length = hasMore ? howMany : length;

            LinkedList<Message> conversationList = new LinkedList<Message>();

            for (int i = 0; i < length; ++i) {

                JSONObject conversationJson = jsonResponse.getJSONObject(i);

                boolean received = !conversationJson.getBoolean("sent");

                conversationList.addFirst(new FastReverseMessage(conversation, this.mUserInfo,
                        new Date(conversationJson.getLong("timestamp") * 1000L),
                        FastReverseConversationHandler.replaceBbcode(conversationJson.getString("message")),
                        received, conversationJson.getBoolean("read")));
            }

            return new ImmutablePair<List<Message>, Boolean>(conversationList, hasMore);
        } catch (JSONException e1) {

            e1.printStackTrace();

            throw new ContentException("Invalid json response from FastFetch");

        }
    }

}

From source file:com.romeikat.datamessie.core.base.util.sparsetable.SparseMultiTable.java

@Override
public Z mergeAllValues(final Function<Pair<Z, Z>, Z> mergeFunction) {
    final List<Z> allValues = new ArrayList<Z>();

    final List<List<Z>> innerValues = innerTable.getAllValues();
    for (final List<Z> innerValue : innerValues) {
        allValues.addAll(innerValue);/*from  w w w  .  j ava2  s.  c o m*/
    }

    if (allValues.isEmpty()) {
        return null;
    }

    Z mergedValue = allValues.get(0);
    for (int i = 1; i < allValues.size(); i++) {
        final Z previousValue = mergedValue;
        final Z currentValue = allValues.get(i);
        final Pair<Z, Z> previousAndCurrentValue = new ImmutablePair<Z, Z>(previousValue, currentValue);
        mergedValue = mergeFunction.apply(previousAndCurrentValue);
    }

    return mergedValue;
}

From source file:code.elix_x.excore.utils.net.packets.SmartNetworkWrapper.java

public <REQ extends IMessage> void registerMessage3(final Function<REQ, Runnable> onReceive,
        Class<REQ> requestMessageType, Side side) {
    registerMessage(new Function<Pair<REQ, MessageContext>, Pair<Runnable, IMessage>>() {

        @Override/*  www  .java2 s  .  co m*/
        public Pair<Runnable, IMessage> apply(Pair<REQ, MessageContext> t) {
            return new ImmutablePair<Runnable, IMessage>(onReceive.apply(t.getKey()), null);
        }

    }, requestMessageType, side);
}

From source file:com.pinterest.terrapin.storage.HFileReader.java

/**
 * Issues an HFile lookup on the underlying HFile.Reader. This is protected
 * for testing./* w  w w .  j  ava  2  s .  c  o  m*/
 */
protected Pair<ByteBuffer, Pair<ByteBuffer, Throwable>> getValueFromHFile(ByteBuffer key) {
    try {
        HFileScanner scanner = reader.getScanner(true, true, false);
        KeyValue kv = buildKeyValueForLookup(BytesUtil.readBytesFromByteBufferWithoutConsume(key));
        int code = scanner.seekTo(kv.getKey());
        ByteBuffer value = null;
        if (code == 0) {
            value = ByteBuffer.wrap(scanner.getKeyValue().getValue());
            if (this.sizeStatsKey != null) {
                Stats.addMetric(this.sizeStatsKey, value.remaining());
            }
            Stats.addMetric("value-size", value.remaining());
        } else {
            Stats.incr("not-found");
            if (this.notFoundStatsKey != null) {
                Stats.incr(this.notFoundStatsKey);
            }
        }
        return new ImmutablePair(key, new ImmutablePair(value, null));
    } catch (Throwable t) {
        return new ImmutablePair(key, new ImmutablePair(null, t));
    }
}

From source file:io.cloudslang.lang.compiler.validator.matcher.DescriptionPatternMatcher.java

public Pair<String, String> getDescriptionGeneralLineData(String input) {
    List<String> matches = getData(descriptionGeneralLinePattern, input,
            Regex.DESCRIPTION_GENERAL_LINE_DECLARATION_GROUP_NR,
            Regex.DESCRIPTION_GENERAL_LINE_CONTENT_GROUP_NR);
    return new ImmutablePair<>(matches.get(0), matches.get(1));
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.description.manifest.KubernetesManifest.java

public static Pair<KubernetesKind, String> fromFullResourceName(String fullResourceName) {
    String[] split = fullResourceName.split(" ");
    if (split.length != 2) {
        throw new IllegalArgumentException("Expected a full resource name of the form <kind> <name>");
    }/*w  w  w  .j a v a 2s. c  o  m*/

    KubernetesKind kind = KubernetesKind.fromString(split[0]);
    String name = split[1];

    return new ImmutablePair<>(kind, name);
}

From source file:com.galenframework.speclang2.pagespec.PageSectionProcessor.java

private Pair<PageRule, Map<String, String>> findAndProcessRule(String ruleText, StructNode ruleNode) {
    ListIterator<Pair<Rule, PageRule>> iterator = pageSpecHandler.getPageRules()
            .listIterator(pageSpecHandler.getPageRules().size());
    /*//from   ww  w .java  2s .  c  o m
    It is important to make a reversed iteration over all rules so that
    it is possible for the end user to override previously defined rules
     */

    while (iterator.hasPrevious()) {
        Pair<Rule, PageRule> rulePair = iterator.previous();
        Matcher matcher = rulePair.getKey().getPattern().matcher(ruleText);
        if (matcher.matches()) {
            int index = 1;

            Map<String, String> parameters = new HashMap<>();

            for (String parameterName : rulePair.getKey().getParameters()) {
                String value = matcher.group(index);
                pageSpecHandler.setGlobalVariable(parameterName, value, ruleNode);

                parameters.put(parameterName, value);
                index += 1;
            }

            return new ImmutablePair<>(rulePair.getValue(), parameters);
        }
    }
    throw new SyntaxException(ruleNode, "Couldn't find rule matching: " + ruleText);
}