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

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

Introduction

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

Prototype

public ImmutableTriple(final L left, final M middle, final R right) 

Source Link

Document

Create a new triple instance.

Usage

From source file:edu.nyu.tandon.tool.BinnedRawHits.java

/**
 * Scores the given document iterator and produces score outputDH.
 *
 * @param results            an iterator returning instances of {@link DocumentScoreInfo}.
 * @param documentCollection an optional document collection, or <code>null</code>.
 * @param titleList          an optional list of titles, or <code>null</code>.
 * @param marker             an optional text marker to mark snippets, or <code>null</code>.
 * @return the number of documents scanned.
 *///from   w ww.ja v  a2s. c o m
@SuppressWarnings("boxing")
public int output(final ObjectArrayList<DocumentScoreInfo<ObjectArrayList<Byte>>> results,
        final DocumentCollection documentCollection, final BigList<? extends CharSequence> titleList,
        final Marker marker) throws IOException {

    int i, j;
    int doc = 0;

    DocumentScoreInfo<ObjectArrayList<Byte>> dsi;

    for (i = 0; i < results.size(); i++) {

        dsi = results.get(i);

        // docHits
        doc = (int) dsi.document;
        int index = (doc * limits.length) + bins[i];
        docHits[index]++;

        // postHits
        for (j = 0; j < dsi.info.size(); j++)
            postHits.add(new ImmutableTriple<Integer, Integer, Integer>(doc,
                    (int) ((BM25Scorer) queryEngine.scorer).flatIndexIterator[dsi.info.get(j)].termNumber(),
                    i));
    }

    if (doc > 0 && (queryCount % 2000 == 0))
        LOGGER.info("Processed " + queryCount + " queries");
    //            outputDH.printf("%d %d %d\n", queryCount, doc, i+1 );

    return i;
}

From source file:it.acubelab.smaph.SmaphAnnotator.java

/**
 * Issue a query to Bing and extract the result.
 * /*  ww w . ja v a  2s.  c o m*/
 * @param query
 *            the query to be issued to Bing
 * @param boldsAndRanks
 *            storage for the bolds (a pair &lt;bold, rank&gt; means bold
 *            appeared in the snippets of the result in position rank)
 * @param urls
 *            storage for the urls found by Bing.
 * @param relatedSearch
 *            storage for the "related search" suggestions.
 * @param snippetsToBolds
 *            storage for the list of pairs &lt;snippets, the bolds found in
 *            that snippet&gt;
 * @return a triple &lt;results, webTotal, bingReply&gt; where results is
 *         the number of results returned by Bing, webTotal is the number of
 *         pages found by Bing, and bingReply is the raw Bing reply.
 * @param topk
 *            limit to top-k results.
 * @param wikisearch
 *            whether to append the word "wikipedia" to the query or not.
 * @throws Exception
 *             if something went wrong while querying Bing.
 */

private Triple<Integer, Double, JSONObject> takeBingData(String query,
        List<Pair<String, Integer>> boldsAndRanks, List<String> urls, List<String> relatedSearch,
        List<Pair<String, Vector<Pair<Integer, Integer>>>> snippetsToBolds, int topk, boolean wikisearch)
        throws Exception {
    if (!boldsAndRanks.isEmpty())
        throw new RuntimeException("boldsAndRanks must be empty");
    if (!urls.isEmpty())
        throw new RuntimeException("urls must be empty");
    if (wikisearch)
        query += " wikipedia";
    JSONObject bingReply = queryBing(query, BING_RETRY);
    JSONObject data = (JSONObject) bingReply.get("d");
    JSONObject results = (JSONObject) ((JSONArray) data.get("results")).get(0);
    JSONArray webResults = (JSONArray) results.get("Web");
    double webTotal = new Double((String) results.get("WebTotal"));

    getBoldsAndUrls(webResults, topk, boldsAndRanks, urls, snippetsToBolds);

    if (relatedSearch != null) {
        JSONArray relatedSearchResults = (JSONArray) results.get("RelatedSearch");
        for (int i = 0; i < relatedSearchResults.length(); i++) {
            JSONObject resI = (JSONObject) relatedSearchResults.get(i);
            String rsI = (String) resI.get("Title");
            relatedSearch.add(rsI);
        }
    }

    return new ImmutableTriple<Integer, Double, JSONObject>(webResults.length(), webTotal, bingReply);
}

From source file:com.clust4j.algo.NearestNeighborHeapSearch.java

public Triple<Integer, Integer, Integer> getTreeStats() {
    return new ImmutableTriple<>(n_trims, n_leaves, n_splits);
}

From source file:org.apache.olingo.ext.pojogen.AbstractPOJOGenMojo.java

private Triple<XMLMetadata, String, Edm> getMetadata() throws FileNotFoundException {
    if (StringUtils.isEmpty(serviceRootURL) && StringUtils.isEmpty(localEdm)) {
        throw new IllegalArgumentException("Must provide either serviceRootURL or localEdm");
    }//w w w  .ja va 2 s . co  m
    if (StringUtils.isNotEmpty(serviceRootURL) && StringUtils.isNotEmpty(localEdm)) {
        throw new IllegalArgumentException("Must provide either serviceRootURL or localEdm, not both");
    }

    XMLMetadata metadata = null;
    String metadataETag = null;
    Edm edm = null;
    if (StringUtils.isNotEmpty(serviceRootURL)) {
        final EdmMetadataRequest req = getClient().getRetrieveRequestFactory()
                .getMetadataRequest(serviceRootURL);
        metadata = req.getXMLMetadata();
        final ODataRetrieveResponse<Edm> res = req.execute();
        metadataETag = res.getETag();
        edm = res.getBody();
    } else if (StringUtils.isNotEmpty(localEdm)) {
        final FileInputStream fis = new FileInputStream(FileUtils.getFile(localEdm));
        try {
            metadata = getClient().getDeserializer(ContentType.APPLICATION_XML).toMetadata(fis);
            edm = getClient().getReader().readMetadata(metadata.getSchemaByNsOrAlias());
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    if (metadata == null || edm == null) {
        throw new IllegalStateException("Metadata not found");
    }
    return new ImmutableTriple<XMLMetadata, String, Edm>(metadata, metadataETag, edm);
}

From source file:org.apache.olingo.ext.proxy.commons.AbstractEntityCollectionInvocationHandler.java

@SuppressWarnings("unchecked")
@Override/*from  w w  w  . j a  v  a 2  s  .com*/
public Triple<List<T>, URI, List<ClientAnnotation>> fetchPartial(final URI uri, final Class<T> typeRef) {

    final List<ClientEntity> entities = new ArrayList<ClientEntity>();
    final URI next;
    final List<ClientAnnotation> anns = new ArrayList<ClientAnnotation>();

    if (isSingleton) {
        final ODataRetrieveResponse<ClientSingleton> res = ((ODataClient) getClient())
                .getRetrieveRequestFactory().getSingletonRequest(uri).execute();

        entities.add(res.getBody());
        next = null;
    } else {
        final ODataEntitySetRequest<ClientEntitySet> req = getClient().getRetrieveRequestFactory()
                .getEntitySetRequest(uri);
        req.setPrefer(getClient().newPreferences().includeAnnotations("*"));

        final ODataRetrieveResponse<ClientEntitySet> res = req.execute();

        final ClientEntitySet entitySet = res.getBody();
        entities.addAll(entitySet.getEntities());
        next = entitySet.getNext();
        anns.addAll(entitySet.getAnnotations());
    }

    final List<T> res = new ArrayList<T>(entities.size());

    for (ClientEntity entity : entities) {
        Class<?> actualRef = null;
        if (entity.getTypeName() != null) {
            actualRef = service.getEntityTypeClass(entity.getTypeName().toString());
        }
        if (actualRef == null) {
            actualRef = typeRef;
        }

        final EntityInvocationHandler handler = this instanceof EntitySetInvocationHandler
                ? EntityInvocationHandler.getInstance(entity, EntitySetInvocationHandler.class.cast(this),
                        actualRef)
                : EntityInvocationHandler.getInstance(entity, targetEntitySetURI, actualRef, service);

        final EntityInvocationHandler handlerInTheContext = getContext().entityContext()
                .getEntity(handler.getUUID());

        res.add((T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[] { actualRef }, handlerInTheContext == null ? handler : handlerInTheContext));
    }

    return new ImmutableTriple<List<T>, URI, List<ClientAnnotation>>(res, next, anns);
}

From source file:org.apache.olingo.ext.proxy.commons.ComplexCollectionInvocationHandler.java

@SuppressWarnings("unchecked")
@Override/*from  ww  w . j  av a 2 s. c o m*/
public Triple<List<T>, URI, List<ClientAnnotation>> fetchPartial(final URI uri, final Class<T> typeRef) {
    final ODataPropertyRequest<ClientProperty> req = getClient().getRetrieveRequestFactory()
            .getPropertyRequest(uri);
    req.setPrefer(getClient().newPreferences().includeAnnotations("*"));

    final ODataRetrieveResponse<ClientProperty> res = req.execute();

    final List<T> resItems = new ArrayList<T>();

    final ClientProperty property = res.getBody();
    if (property != null && property.hasCollectionValue()) {
        for (ClientValue item : (ClientCollectionValue<ClientValue>) property.getValue()) {
            Class<?> actualRef = null;
            if (StringUtils.isNotBlank(item.getTypeName())) {
                actualRef = service.getComplexTypeClass(item.getTypeName());
            }
            if (actualRef == null) {
                actualRef = typeRef;
            }

            resItems.add((T) getComplex(property.getName(), item, actualRef, null, null, true));
        }
    }

    return new ImmutableTriple<List<T>, URI, List<ClientAnnotation>>(resItems, null,
            Collections.<ClientAnnotation>emptyList());
}

From source file:org.apache.olingo.ext.proxy.commons.PrimitiveCollectionInvocationHandler.java

@Override
@SuppressWarnings("unchecked")
public Triple<List<T>, URI, List<ClientAnnotation>> fetchPartial(final URI uri, final Class<T> typeRef) {
    final ODataPropertyRequest<ClientProperty> req = getClient().getRetrieveRequestFactory()
            .getPropertyRequest(uri);/*from  ww w. j  a  va2  s.co m*/
    req.setPrefer(getClient().newPreferences().includeAnnotations("*"));

    final ODataRetrieveResponse<ClientProperty> res = req.execute();

    final List<T> resItems = new ArrayList<T>();

    final ClientProperty property = res.getBody();
    if (property != null && !property.hasNullValue()) {
        for (ClientValue item : property.getCollectionValue()) {
            resItems.add((T) item.asPrimitive().toValue());
        }
    }

    return new ImmutableTriple<List<T>, URI, List<ClientAnnotation>>(resItems, null,
            Collections.<ClientAnnotation>emptyList());
}

From source file:org.apache.reef.vortex.common.AggregateFunctionRepository.java

/**
 * Associates an aggregate function ID with a {@link VortexAggregateFunction} and a {@link VortexFunction}.
 *///w ww.  j av a 2  s.  c  o m
public Triple<VortexAggregateFunction, VortexFunction, VortexAggregatePolicy> put(final int aggregateFunctionId,
        final VortexAggregateFunction aggregateFunction, final VortexFunction function,
        final VortexAggregatePolicy policy) {
    return aggregateFunctionMap.put(aggregateFunctionId,
            new ImmutableTriple<>(aggregateFunction, function, policy));
}

From source file:org.coinspark.wallet.CSMessage.java

/**
 * Try to retrieve message//  w ww. j av  a  2 s .c  om
 * @param wallet
 * @param acceptedAddress
 * @param Nonce
 * @return Tuple of (boolean update, error code, error msg)
 */
private ImmutableTriple<Boolean, CSUtils.CSServerError, String> retrieve(Wallet wallet, String acceptedAddress,
        CSNonce Nonce) {
    if (Nonce.error != CSUtils.CSServerError.NOERROR) {
        return new ImmutableTriple<Boolean, CSUtils.CSServerError, String>(false, Nonce.error,
                "Error retrieving message");
    }

    JRequestRetrieveParams params = new JRequestRetrieveParams();

    params.txid = txID;
    params.recipient = acceptedAddress;
    params.nonce = Nonce.nonce;
    params.signature = getSignature(wallet, acceptedAddress, Nonce);
    params.pubkey = getPubKey(wallet, acceptedAddress, Nonce);

    if (Nonce.error != CSUtils.CSServerError.NOERROR) {
        return new ImmutableTriple<Boolean, CSUtils.CSServerError, String>(false, Nonce.error,
                "Error retrieving message");
    }

    JResponse response = jsonQuery(new JRequest(params));

    Nonce.error = response.error;
    if (Nonce.error != CSUtils.CSServerError.NOERROR) {
        return new ImmutableTriple<Boolean, CSUtils.CSServerError, String>(false, Nonce.error,
                "Error retrieving message");
    }

    if (Nonce.error == CSUtils.CSServerError.NOERROR) {
        if ((response.result.get("salt") == null)) {
            Nonce.errorMessage = "salt not found in retrieve query";
            Nonce.error = CSUtils.CSServerError.RESPONSE_INVALID;
        } else {
            meta.setSalt(response.result.get("salt").getAsString());
            //                messageParams.salt=response.result.get("salt").getAsString();
        }
    }

    CoinSparkMessagePart[] receivedParts = null;
    if (Nonce.error == CSUtils.CSServerError.NOERROR) {
        if ((response.result.get("message") == null)) {
            Nonce.errorMessage = "message not found in retrieve query";
            Nonce.error = CSUtils.CSServerError.RESPONSE_INVALID;
        } else {
            if (!response.result.get("message").isJsonArray()) {
                Nonce.errorMessage = "message is not json array";
                Nonce.error = CSUtils.CSServerError.RESPONSE_INVALID;
            } else {
                JsonArray jarray = response.result.getAsJsonArray("message");
                numParts = jarray.size();
                receivedParts = new CoinSparkMessagePart[numParts];
                for (int j = 0; j < jarray.size(); j++) {
                    JsonObject jentry = jarray.get(j).getAsJsonObject();
                    CoinSparkMessagePart onePart = new CoinSparkMessagePart();
                    if (jentry.get("mimetype") != null) {
                        onePart.mimeType = jentry.get("mimetype").getAsString();
                    } else {
                        Nonce.errorMessage = "mimetype not found in one of message parts";
                        Nonce.error = CSUtils.CSServerError.RESPONSE_INVALID;
                    }
                    onePart.fileName = null;
                    if (jentry.get("filename") != null) {
                        if (!jentry.get("filename").isJsonNull()) {
                            onePart.fileName = jentry.get("filename").getAsString();
                        }
                    }
                    if (jentry.get("content") != null) {
                        String jsonData = jentry.get("content").getAsString();
                        if (jsonData != null) {
                            onePart.content = Base64.decodeBase64(jsonData);
                        }
                    } else {
                        Nonce.errorMessage = "content not found in one of message parts";
                        Nonce.error = CSUtils.CSServerError.RESPONSE_INVALID;
                    }
                    if (Nonce.error == CSUtils.CSServerError.NOERROR) {
                        receivedParts[j] = onePart;
                    }
                }
            }
        }
    }

    if (Nonce.error == CSUtils.CSServerError.NOERROR) {
        byte[] receivedHash = CoinSparkMessage.calcMessageHash(Base64.decodeBase64(meta.getSalt()),
                receivedParts);
        if (receivedHash == null || !Arrays.equals(Arrays.copyOf(this.getHashBytes(), meta.getHashLen()),
                Arrays.copyOf(receivedHash, meta.getHashLen()))) {
            Nonce.errorMessage = "message hash doesn't match encoded in metadata";
            Nonce.error = CSUtils.CSServerError.RESPONSE_HASH_MISMATCH;
        }
    }

    // Message received, so save message parts, and save the metadata
    if (Nonce.error == CSUtils.CSServerError.NOERROR) {
        if (!saveMessageParts(receivedParts)) {
            return new ImmutableTriple<Boolean, CSUtils.CSServerError, String>(true,
                    CSUtils.CSServerError.NOERROR, null);
            // Internal error - no change in state
        }

        if (!saveMetadata(txID, 0, null)) // Internal error - no change in state
        {
            return new ImmutableTriple<Boolean, CSUtils.CSServerError, String>(true,
                    CSUtils.CSServerError.NOERROR, null);
        }
    }

    if (Nonce.error != CSUtils.CSServerError.NOERROR) {
        log.error("Delivery: Code: " + Nonce.error + ": " + Nonce.errorMessage);
    }

    switch (Nonce.error) {
    case NOERROR:
        messageRetrievalState = CSMessageState.VALID;
        break;
    //       case RECIPIENT_IP_IS_SUSPENDED:
    case RECIPIENT_IS_SUSPENDED:
        messageRetrievalState = CSMessageState.ADDRESSES_SUSPENDED;
        break;
    //       case RECIPIENT_IP_NOT_ACCEPTED:
    case RECIPIENT_NOT_ACCEPTED:
        messageRetrievalState = CSMessageState.ADDRESSES_NOT_ACCEPTED;
        break;
    case TX_MESSAGE_UNKNOWN:
        messageRetrievalState = CSMessageState.NOT_FOUND;
        break; //return true;
    case TX_MESSAGE_PENDING:
        messageRetrievalState = CSMessageState.PENDING;
        break; //return true;
    case TX_MESSAGE_EXPIRED:
        messageRetrievalState = CSMessageState.EXPIRED;
        break; //return true;
    case NONCE_NOT_FOUND: // Internal error - no change in state
    case SIGNATURE_INCORRECT:
        break; //return true;
    default:
        messageRetrievalState = CSMessageState.SERVER_ERROR;
        //return true;
    }

    if (Nonce.error != CSUtils.CSServerError.NOERROR) {
        return new ImmutableTriple<Boolean, CSUtils.CSServerError, String>(true, Nonce.error,
                "Error retrieving message");
    }

    return new ImmutableTriple<Boolean, CSUtils.CSServerError, String>(true, CSUtils.CSServerError.NOERROR,
            null);
}

From source file:org.coinspark.wallet.CSMessage.java

private ImmutableTriple<Boolean, CSUtils.CSServerError, String> retrieve(Wallet wallet) {
    String acceptedAddress = null;
    CSNonce nonce = null;/*from w  w w  . java 2 s.  c o m*/
    boolean suspended = false;

    // Null exception check.
    if (meta.addresses != null) {
        for (String address : meta.addresses) {
            if (acceptedAddress == null) {
                nonce = getRetrieveNonce(address);
                suspended |= nonce.suspended;
                if (!nonce.mayBeOtherAddressIsBetter) {
                    acceptedAddress = address;
                }
            }
        }
    }

    if (acceptedAddress == null) {
        for (ECKey key : wallet.getKeys()) {
            if (acceptedAddress == null) {
                Address pubKeyHash = new Address(wallet.getNetworkParameters(), key.getPubKeyHash());
                String address = pubKeyHash.toString();
                boolean found = false;

                if (meta.addresses != null) {
                    for (String addressToCheck : meta.addresses) {
                        if (!found) {
                            if (addressToCheck.equals(address)) {
                                found = true;
                            }
                        }
                    }
                }

                if (!found) {
                    nonce = getRetrieveNonce(address);
                    suspended |= nonce.suspended;
                    if (!nonce.mayBeOtherAddressIsBetter) {
                        acceptedAddress = address;
                    }
                }
            }
        }
    }

    if (acceptedAddress == null) {
        if (suspended) {
            messageRetrievalState = CSMessageState.ADDRESSES_SUSPENDED;
            return new ImmutableTriple<Boolean, CSUtils.CSServerError, String>(true,
                    CSUtils.CSServerError.RECIPIENT_IS_SUSPENDED, "Error retrieving message");
        } else {
            messageRetrievalState = CSMessageState.ADDRESSES_NOT_ACCEPTED;
            return new ImmutableTriple<Boolean, CSUtils.CSServerError, String>(true,
                    CSUtils.CSServerError.RECIPIENT_NOT_ACCEPTED, "Error retrieving message");
        }
    }

    if (nonce == null) {
        messageRetrievalState = CSMessageState.ADDRESSES_NOT_ACCEPTED;
        return new ImmutableTriple<Boolean, CSUtils.CSServerError, String>(true,
                CSUtils.CSServerError.NONCE_NOT_FOUND, "Error retrieving message");
    }

    switch (nonce.error) {
    case NOERROR:
        break;
    case TX_MESSAGE_UNKNOWN:
        messageRetrievalState = CSMessageState.NOT_FOUND;
        break; //return true;
    case TX_MESSAGE_PENDING:
        messageRetrievalState = CSMessageState.PENDING;
        break; //return true;
    case TX_MESSAGE_EXPIRED:
        messageRetrievalState = CSMessageState.EXPIRED;
        break; //return true;
    default:
        messageRetrievalState = CSMessageState.SERVER_ERROR;
        break; //return true;
    }

    if (nonce.error != CSUtils.CSServerError.NOERROR) {
        return new ImmutableTriple<Boolean, CSUtils.CSServerError, String>(true, nonce.error,
                "Error retrieving message");
    }

    return retrieve(wallet, acceptedAddress, nonce);
}