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

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

Introduction

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

Prototype

@Override
public R getValue() 

Source Link

Document

Gets the value from this pair.

This method implements the Map.Entry interface returning the right element as the value.

Usage

From source file:org.codice.ddf.rest.impl.CatalogServiceImplTest.java

@Test
public void testParseAttachmentsWithAttributeOverrides() throws IngestException, SourceUnavailableException {
    CatalogFramework framework = givenCatalogFramework();
    CatalogServiceImpl catalogServiceImpl = new CatalogServiceImpl(framework, attachmentParser,
            attributeRegistry);//from  www  .java  2s .c o  m

    when(attributeRegistry.lookup(Topic.KEYWORD))
            .thenReturn(Optional.of(new TopicAttributes().getAttributeDescriptor(Topic.KEYWORD)));
    when(attributeRegistry.lookup(Core.LOCATION))
            .thenReturn(Optional.of(new CoreAttributes().getAttributeDescriptor(Core.LOCATION)));

    List<Attachment> attachments = new ArrayList<>();
    ContentDisposition contentDisposition = new ContentDisposition(
            "form-data; name=parse.resource; filename=/path/to/metacard.txt");
    Attachment attachment = new Attachment("parse.resource", new ByteArrayInputStream("Some Text".getBytes()),
            contentDisposition);
    ContentDisposition contentDisposition1 = new ContentDisposition("form-data; name=parse.location");
    Attachment attachment1 = new Attachment("parse.location", new ByteArrayInputStream("POINT(0 0)".getBytes()),
            contentDisposition1);
    ContentDisposition contentDisposition2 = new ContentDisposition("form-data; name=parse.topic.keyword");
    Attachment attachment2 = new Attachment("parse.topic.keyword",
            new ByteArrayInputStream("keyword1".getBytes()), contentDisposition2);
    ContentDisposition contentDisposition3 = new ContentDisposition("form-data; name=parse.topic.keyword");
    Attachment attachment3 = new Attachment("parse.topic.keyword",
            new ByteArrayInputStream("keyword2".getBytes()), contentDisposition3);
    attachments.add(attachment);
    attachments.add(attachment1);
    attachments.add(attachment2);
    attachments.add(attachment3);

    Pair<AttachmentInfo, Metacard> attachmentInfoAndMetacard = catalogServiceImpl.parseAttachments(attachments,
            null);
    Metacard metacard = attachmentInfoAndMetacard.getValue();

    assertThat(metacard.getAttribute(Core.LOCATION).getValues(), hasItem("POINT(0 0)"));
    assertThat(metacard.getAttribute(Topic.KEYWORD).getValues(), hasItems("keyword1", "keyword2"));
}

From source file:org.codice.ddf.rest.impl.CatalogServiceImplTest.java

@Test
@SuppressWarnings({ "unchecked" })
public void testParseAttachmentsTooLarge() throws IOException, CatalogTransformerException,
        SourceUnavailableException, IngestException, InvalidSyntaxException {
    CatalogFramework framework = givenCatalogFramework();
    BundleContext bundleContext = mock(BundleContext.class);
    Collection<ServiceReference<InputTransformer>> serviceReferences = new ArrayList<>();
    ServiceReference serviceReference = mock(ServiceReference.class);
    InputTransformer inputTransformer = mock(InputTransformer.class);
    MetacardImpl metacard = new MetacardImpl();
    metacard.setMetadata("Some Text Again");
    when(inputTransformer.transform(any())).thenReturn(metacard);
    when(bundleContext.getService(serviceReference)).thenReturn(inputTransformer);
    serviceReferences.add(serviceReference);
    when(bundleContext.getServiceReferences(InputTransformer.class, "(id=xml)")).thenReturn(serviceReferences);

    CatalogServiceImpl catalogServiceImpl = new CatalogServiceImpl(framework, attachmentParser,
            attributeRegistry) {//w ww  . j a v a 2  s .c o  m
        @Override
        BundleContext getBundleContext() {
            return bundleContext;
        }
    };
    when(attributeRegistry.lookup(Core.METADATA))
            .thenReturn(Optional.of(new CoreAttributes().getAttributeDescriptor(Core.METADATA)));
    when(attributeRegistry.lookup("foo")).thenReturn(Optional.empty());

    addMatchingService(catalogServiceImpl, Collections.singletonList(getSimpleTransformer()));

    List<Attachment> attachments = new ArrayList<>();
    ContentDisposition contentDisposition = new ContentDisposition(
            "form-data; name=parse.resource; filename=C:\\DDF\\metacard.txt");
    Attachment attachment = new Attachment("parse.resource", new ByteArrayInputStream("Some Text".getBytes()),
            contentDisposition);
    attachments.add(attachment);
    ContentDisposition contentDisposition1 = new ContentDisposition(
            "form-data; name=parse.metadata; filename=C:\\DDF\\metacard.xml");
    Attachment attachment1 = new Attachment("parse.metadata",
            new ByteArrayInputStream("Some Text Again".getBytes()), contentDisposition1);
    attachments.add(attachment1);

    Pair<AttachmentInfo, Metacard> attachmentInfoAndMetacard = catalogServiceImpl.parseAttachments(attachments,
            "xml");
    assertThat(attachmentInfoAndMetacard.getValue().getMetadata(), equalTo("Some Text Again"));

    ContentDisposition contentDisposition2 = new ContentDisposition(
            "form-data; name=metadata; filename=C:\\DDF\\metacard.xml");
    Attachment attachment2 = new Attachment("metadata",
            new ByteArrayInputStream(Strings.repeat("hi", 100_000).getBytes()), contentDisposition2);
    attachments.add(attachment2);

    ContentDisposition contentDisposition3 = new ContentDisposition(
            "form-data; name=foo; filename=C:\\DDF\\metacard.xml");
    Attachment attachment3 = new Attachment("foo", new ByteArrayInputStream("bar".getBytes()),
            contentDisposition3);
    attachments.add(attachment3);

    attachmentInfoAndMetacard = catalogServiceImpl.parseAttachments(attachments, "xml");

    // Ensure that the metadata was not overriden because it was too large to be parsed
    assertThat(attachmentInfoAndMetacard.getValue().getMetadata(), equalTo("Some Text Again"));
    assertThat(attachmentInfoAndMetacard.getValue().getAttribute("foo"), equalTo(null));
}

From source file:org.corpus_tools.graphannis.SaltExport.java

private static void mapLabels(SAnnotationContainer n, API.StringMap labels) {
    for (API.StringMap.Iterator it = labels.begin(); !it.equals(labels.end()); it = it.increment()) {
        Pair<String, String> qname = SaltUtil.splitQName(it.first().getString());
        String value = it.second() == null ? null : it.second().getString();

        if ("annis".equals(qname.getKey())) {
            n.createFeature(qname.getKey(), qname.getValue(), value);
        } else {/*w w w. j  av a  2s .co m*/
            n.createAnnotation(qname.getKey(), qname.getValue(), value);
        }
    }
}

From source file:org.deeplearning4j.clustering.cluster.ClusterSet.java

/**
 *
 * @param point/*from ww w .  j  a va2  s  . com*/
 * @param moveClusterCenter
 * @return
 */
public PointClassification classifyPoint(Point point, boolean moveClusterCenter) {
    Pair<Cluster, Double> nearestCluster = nearestCluster(point);
    Cluster newCluster = nearestCluster.getKey();
    boolean locationChange = isPointLocationChange(point, newCluster);
    addPointToCluster(point, newCluster, moveClusterCenter);
    return new PointClassification(nearestCluster.getKey(), nearestCluster.getValue(), locationChange);
}

From source file:org.deeplearning4j.clustering.kdtree.KDTreeTest.java

@Test
public void testTree() {
    KDTree tree = new KDTree(2);
    INDArray half = Nd4j.create(Nd4j.createBuffer(new double[] { 0.5, 0.5 }));
    INDArray one = Nd4j.create(Nd4j.createBuffer(new double[] { 1, 1 }));
    tree.insert(half);//from  w ww  . ja v a  2s.  c o m
    tree.insert(one);
    Pair<Double, INDArray> pair = tree.nn(Nd4j.create(Nd4j.createBuffer(new double[] { 0.5, 0.5 })));
    assertEquals(half, pair.getValue());
}

From source file:org.echocat.jomon.net.cluster.channel.ClusterChannelTestSupport.java

@Nonnull
protected Map<String, AtomicInteger> getMessageToCount() {
    final Map<String, AtomicInteger> messageToCount = new HashMap<>();
    for (final Pair<C, ReceivedMessage<N>> pair : getMessageHandler().getReceivedMessages()) {
        final String message = pair.getValue().getDataAsString(CHARSET);
        AtomicInteger count = messageToCount.get(message);
        if (count == null) {
            count = new AtomicInteger();
            messageToCount.put(message, count);
        }//from   ww  w .  j av  a2 s  .  c o  m
        count.incrementAndGet();
    }
    return messageToCount;
}

From source file:org.esigate.Driver.java

/**
 * Perform rendering on a single url content, and append result to "writer". Automatically follows redirects
 * //from w w  w.  j a va  2  s.  com
 * @param pageUrl
 *            Address of the page containing the template
 * @param incomingRequest
 *            originating request object
 * @param renderers
 *            the renderers to use in order to transform the output
 * @return The resulting response
 * @throws IOException
 *             If an IOException occurs while writing to the writer
 * @throws HttpErrorPage
 *             If an Exception occurs while retrieving the template
 */
public CloseableHttpResponse render(String pageUrl, IncomingRequest incomingRequest, Renderer... renderers)
        throws IOException, HttpErrorPage {
    DriverRequest driverRequest = new DriverRequest(incomingRequest, this, pageUrl);

    // Replace ESI variables in URL
    // TODO: should be performed in the ESI extension
    String resultingPageUrl = VariablesResolver.replaceAllVariables(pageUrl, driverRequest);

    String targetUrl = ResourceUtils.getHttpUrlWithQueryString(resultingPageUrl, driverRequest, false);

    String currentValue;
    CloseableHttpResponse response;

    // Retrieve URL
    // Get from cache to prevent multiple request to the same url if
    // multiple fragments are used.

    String cacheKey = CACHE_RESPONSE_PREFIX + targetUrl;
    Pair<String, CloseableHttpResponse> cachedValue = incomingRequest.getAttribute(cacheKey);
    // content and response were not in cache
    if (cachedValue == null) {
        OutgoingRequest outgoingRequest = requestExecutor.createOutgoingRequest(driverRequest, targetUrl,
                false);
        headerManager.copyHeaders(driverRequest, outgoingRequest);
        response = requestExecutor.execute(outgoingRequest);
        int redirects = MAX_REDIRECTS;
        try {
            while (redirects > 0
                    && redirectStrategy.isRedirected(outgoingRequest, response, outgoingRequest.getContext())) {
                redirects--;
                outgoingRequest = requestExecutor.createOutgoingRequest(driverRequest, redirectStrategy
                        .getLocationURI(outgoingRequest, response, outgoingRequest.getContext()).toString(),
                        false);
                headerManager.copyHeaders(driverRequest, outgoingRequest);
                response = requestExecutor.execute(outgoingRequest);
            }
        } catch (ProtocolException e) {
            throw new HttpErrorPage(HttpStatus.SC_BAD_GATEWAY, "Invalid response from server", e);
        }
        response = headerManager.copyHeaders(outgoingRequest, incomingRequest, response);
        currentValue = HttpResponseUtils.toString(response, this.eventManager);
        // Cache
        cachedValue = new ImmutablePair<String, CloseableHttpResponse>(currentValue, response);
        incomingRequest.setAttribute(cacheKey, cachedValue);
    }
    currentValue = cachedValue.getKey();
    response = cachedValue.getValue();

    logAction("render", pageUrl, renderers);

    // Apply renderers
    currentValue = performRendering(pageUrl, driverRequest, response, currentValue, renderers);

    response.setEntity(new StringEntity(currentValue, HttpResponseUtils.getContentType(response)));

    return response;
}

From source file:org.flinkspector.datastream.input.EventTimeInputBuilder.java

/**
 * Print the input list./*from   w  w w . j  av a  2s.c om*/
 *
 * @return
 */
public String toString() {
    StringBuilder builder = new StringBuilder();
    for (Pair<StreamRecord<T>, Long> r : input) {
        builder.append("value: " + r.getValue() + " timestamp: " + r.getLeft().getTimestamp() + "\n");
    }
    return builder.toString();
}

From source file:org.forgerock.openidm.security.impl.KeystoreResourceProvider.java

@Override
public Promise<ActionResponse, ResourceException> actionInstance(Context context, ActionRequest request) {
    try {/* w  w w .j a va 2 s .  c  o  m*/
        String alias = request.getContent().get("alias").asString();
        if (ACTION_GENERATE_CERT.equalsIgnoreCase(request.getAction())
                || ACTION_GENERATE_CSR.equalsIgnoreCase(request.getAction())) {
            if (alias == null) {
                return new BadRequestException("A valid resource ID must be specified in the request")
                        .asPromise();
            }
            String algorithm = request.getContent().get("algorithm").defaultTo(DEFAULT_ALGORITHM).asString();
            String signatureAlgorithm = request.getContent().get("signatureAlgorithm")
                    .defaultTo(DEFAULT_SIGNATURE_ALGORITHM).asString();
            int keySize = request.getContent().get("keySize").defaultTo(DEFAULT_KEY_SIZE).asInteger();
            JsonValue result = null;
            if (ACTION_GENERATE_CERT.equalsIgnoreCase(request.getAction())) {
                // Generate self-signed certificate
                if (store.getStore().containsAlias(alias)) {
                    return new ConflictException("The resource with ID '" + alias
                            + "' could not be created because there is already another resource with the same ID")
                                    .asPromise();
                } else {
                    logger.info("Generating a new self-signed certificate with the alias {}", alias);
                    String domainName = request.getContent().get("domainName").required().asString();
                    String validFrom = request.getContent().get("validFrom").asString();
                    String validTo = request.getContent().get("validTo").asString();

                    // Generate the cert
                    Pair<X509Certificate, PrivateKey> pair = generateCertificate(domainName, algorithm, keySize,
                            signatureAlgorithm, validFrom, validTo);
                    Certificate cert = pair.getKey();
                    PrivateKey key = pair.getValue();

                    // Add it to the store and reload
                    logger.debug("Adding certificate entry under the alias {}", alias);
                    store.getStore().setEntry(alias,
                            new KeyStore.PrivateKeyEntry(key, new Certificate[] { cert }),
                            new KeyStore.PasswordProtection(store.getPassword().toCharArray()));
                    store.store();
                    manager.reload();
                    // Save the store to the repo (if clustered)
                    saveStore();

                    result = returnCertificate(alias, cert);
                    if (request.getContent().get("returnPrivateKey").defaultTo(false).asBoolean()) {
                        result.put("privateKey", getKeyMap(key));
                    }
                }
            } else {
                // Generate CSR
                Pair<PKCS10CertificationRequest, PrivateKey> csr = generateCSR(alias, algorithm,
                        signatureAlgorithm, keySize, request.getContent());
                result = returnCertificateRequest(alias, csr.getKey());
                if (request.getContent().get("returnPrivateKey").defaultTo(false).asBoolean()) {
                    result.put("privateKey", getKeyMap(csr.getRight()));
                }
            }
            return Responses.newActionResponse(result).asPromise();
        } else {
            return new BadRequestException("Unsupported action " + request.getAction()).asPromise();
        }
    } catch (JsonValueException e) {
        return new BadRequestException(e.getMessage(), e).asPromise();
    } catch (Exception e) {
        return new InternalServerErrorException(e).asPromise();
    }
}

From source file:org.forgerock.openidm.security.impl.PrivateKeyResourceProvider.java

@Override
public void createDefaultEntry(String alias) throws Exception {
    Pair<X509Certificate, PrivateKey> pair = generateCertificate("localhost", "OpenIDM Self-Signed Certificate",
            "None", "None", "None", "None", DEFAULT_ALGORITHM, DEFAULT_KEY_SIZE, DEFAULT_SIGNATURE_ALGORITHM,
            null, null);//from   w w w  . j av a2  s  .c o m
    Certificate cert = pair.getKey();
    PrivateKey key = pair.getValue();
    store.getStore().setEntry(alias, new PrivateKeyEntry(key, new Certificate[] { cert }),
            new KeyStore.PasswordProtection(store.getPassword().toCharArray()));
    store.store();
}