Example usage for java.util Collection toArray

List of usage examples for java.util Collection toArray

Introduction

In this page you can find the example usage for java.util Collection toArray.

Prototype

default <T> T[] toArray(IntFunction<T[]> generator) 

Source Link

Document

Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

Usage

From source file:com.android.google.demo.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException {

    CharSequence contents = HttpHelper.downloadViaHttp(
            "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;//from   w w  w .j a  v a 2 s .c  o  m
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>(authorsArray.length());
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e.toString());
    }

    Collection<String> newTexts = new ArrayList<String>();
    maybeAddText(title, newTexts);
    maybeAddTextSeries(authors, newTexts);
    maybeAddText(pages == null || pages.length() == 0 ? null : pages + "pp.", newTexts);

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}

From source file:com.ebay.pulsar.replay.processor.ReplayInboundKafkaProcessor.java

@Override
public BatchResponse onNextBatch(BatchSource source, Collection<JetstreamEvent> events) throws EventException {

    // check if it's time to send the batch, check the delay time of the
    // lastEvent, if it's no time to send the batch, tell the IKC to wait
    // and resend this batch
    long start = System.currentTimeMillis();
    if (getReplayConfig().getTimestampKey() != null && getReplayConfig().getDelayInMs() > 0) {
        JetstreamEvent[] eventArr = events.toArray(new JetstreamEvent[events.size()]);
        JetstreamEvent lastEvent = eventArr[eventArr.length - 1];
        Long ts = (Long) lastEvent.get(getReplayConfig().getTimestampKey());
        if (ts != null) {
            long v = ts + getReplayConfig().getDelayInMs() - start;
            if (v > 0) {
                incrementEventRecievedCounter(events.size());
                incrementEventDelayedCounter(events.size());
                return BatchResponse.getNextBatch().setOffset(source.getHeadOffset()).setWaitTimeInMs(v);
            }// www  . j  av a 2 s  .  c om
        }
    }

    return super.onNextBatch(source, events);

}

From source file:com.netflix.curator.framework.recipes.leader.TestLeaderSelectorCluster.java

@Test
public void testLostRestart() throws Exception {
    final Timing timing = new Timing();

    CuratorFramework client = null;//from   w w w  .ja va  2  s.  c o m
    TestingCluster cluster = new TestingCluster(3);
    cluster.start();
    try {
        client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(),
                timing.connection(), new RetryOneTime(1));
        client.start();
        client.sync("/", null);

        final AtomicReference<Exception> error = new AtomicReference<Exception>(null);
        final AtomicReference<String> lockNode = new AtomicReference<String>(null);
        final Semaphore semaphore = new Semaphore(0);
        final CountDownLatch lostLatch = new CountDownLatch(1);
        final CountDownLatch internalLostLatch = new CountDownLatch(1);
        LeaderSelectorListener listener = new LeaderSelectorListener() {
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                try {
                    List<String> names = client.getChildren().forPath("/leader");
                    if (names.size() != 1) {
                        semaphore.release();
                        Exception exception = new Exception("Names size isn't 1: " + names.size());
                        error.set(exception);
                        return;
                    }
                    lockNode.set(names.get(0));

                    semaphore.release();
                    if (!timing.multiple(4).awaitLatch(internalLostLatch)) {
                        error.set(new Exception("internalLostLatch await failed"));
                    }
                } finally {
                    lostLatch.countDown();
                }
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.LOST) {
                    internalLostLatch.countDown();
                }
            }
        };
        LeaderSelector selector = new LeaderSelector(client, "/leader", listener);
        selector.start();
        Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore));
        if (error.get() != null) {
            throw new AssertionError(error.get());
        }

        Collection<InstanceSpec> instances = cluster.getInstances();
        cluster.stop();

        Assert.assertTrue(timing.multiple(4).awaitLatch(lostLatch));
        timing.sleepABit();
        Assert.assertFalse(selector.hasLeadership());

        Assert.assertNotNull(lockNode.get());

        cluster = new TestingCluster(instances.toArray(new InstanceSpec[instances.size()]));
        cluster.start();

        try {
            client.delete().forPath(ZKPaths.makePath("/leader", lockNode.get())); // simulate the lock deleting due to session expiration
        } catch (Exception ignore) {
            // ignore
        }

        Assert.assertTrue(semaphore.availablePermits() == 0);
        Assert.assertFalse(selector.hasLeadership());

        selector.requeue();
        Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore));
    } finally {
        IOUtils.closeQuietly(client);
        IOUtils.closeQuietly(cluster);
    }
}

From source file:com.marklogic.entityservices.tests.TestSetup.java

public void teardownClass() {
    JSONDocumentManager docMgr = _client.newJSONDocumentManager();
    Collection<String> cleanupDocuments = new ArrayList<String>();
    cleanupDocuments.addAll(getTestResourceNames("/source-documents"));
    cleanupDocuments.addAll(getTestResourceNames("/test-instances"));
    cleanupDocuments.addAll(getTestResourceNames("/json-models"));
    cleanupDocuments.addAll(getTestResourceNames("/xml-models"));

    docMgr.delete(cleanupDocuments.toArray(new String[] {}));

}

From source file:io.github.moosbusch.lumpi.application.spi.AbstractLumpiApplicationContext.java

private void loadAnnotationConfig(
        LumpiApplication<? extends LumpiApplicationContext, ? extends BindableWindow> application) {
    Collection<String> beanPackages = application.getBeanConfigurationPackages();
    Collection<Class<?>> annotatedClasses = application.getBeanConfigurationClasses();

    if (isValidBeanConfigurationClasses(annotatedClasses)) {

        if (!annotatedClasses.isEmpty()) {
            register(annotatedClasses.toArray(new Class[0]));
        }//from  w w  w .  j ava2  s.  c  o  m

        if (beanPackages != null) {
            if (!beanPackages.isEmpty()) {
                scan(beanPackages.toArray(new String[0]));
            }
        }

        return;
    }

    throw new IllegalStateException("No configuration-class of type 'PivotBeanConfiguration' is defined!");

}

From source file:com.actian.services.knime.core.operators.DeriveGroupNodeDialogPane.java

public DeriveGroupNodeDialogPane() {
    initComponents();//from   w ww . j a  v a2 s.c  om
    // Find out which aggregation functions are loaded.
    Collection<String> list = new ArrayList<>();
    Iterator<FunctionDescription> it = AggregationRegistry.getInstance().getFunctionDescriptions().iterator();
    while (it.hasNext()) {
        FunctionDescription fd = it.next();
        String desc = StringUtils.rightPad(fd.getName(), 20) + fd.getDescription();
        list.add(desc);
    }
    fcomboBox.setModel(new DefaultComboBoxModel<String>(list.toArray(new String[] {})));

}

From source file:greenapi.core.model.resources.Machine.java

/**
 * Filter and returns the {@link Memory} of the given type.
 * /*from  w w w.  j  av a2 s.c o m*/
 * @param type
 *            The type of the memory to be returned.
 * @return A not-null array with the memory found or empty if there isn't any memory of the given type.
 */
private Memory[] filterMemoryBy(final MemoryType type) {
    Collection<Memory> filtered = Collections2.filter(Lists.newArrayList(this.memories),
            new Predicate<Memory>() {
                @Override
                public boolean apply(Memory input) {
                    return type.equals(input.getType());
                }
            });

    return filtered.toArray(new Memory[filtered.size()]);
}

From source file:com.koda.integ.hbase.test.BlockCacheStorageSimpleRegionTests.java

/**
 * _test random direct scanners./*www . j  a v a  2 s .c  om*/
 * 
 * FAIL after compaction
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void _testRandomDirectScanners() throws IOException {
    LOG.info("Random StoreFile scanners . Running " + (N / 10) + " of size " + M + " scanners");
    Random r = new Random();
    long totalScanned = 0;
    long start = System.currentTimeMillis();
    Map<byte[], Store> storeMap = region.getStores();
    Collection<Store> stores = storeMap.values();
    Store store = stores.iterator().next();
    Collection<StoreFile> files = store.getStorefiles();
    StoreFile[] array = new StoreFile[files.size()];
    files.toArray(array);
    for (int i = 0; i < N / 10; i++) {

        StoreFile file = array[r.nextInt(files.size())];
        byte[] row = (ROW_PREFIX + r.nextInt(N)).getBytes();
        StoreFile.Reader reader = file.createReader();
        StoreFileScanner scanner = reader.getStoreFileScanner(false, false);
        KeyValue kv = new KeyValue(row, CF, CQQ[0]);
        //LOG.info(i+" Seek "+kv);
        scanner.seek(kv);
        int total = 0;
        while (total++ < M && scanner.next() != null) {
            totalScanned++;
        }
        if (i % 100000 == 0 && i > 0) {
            LOG.info("Scanner " + i + " scanned=" + totalScanned + " avg per scanner=" + (totalScanned / i));
        }
        scanner.close();
        reader.close(false);

    }
    LOG.info("Random StoreFile scanners done. " + (N / 10) + " in " + (System.currentTimeMillis() - start)
            + "ms. Total scanned=" + totalScanned + " Avg. =" + ((totalScanned * 10) / N));
}

From source file:com.khs.sherpa.processor.RestfulRequestProcessor.java

public String getEndpoint(HttpServletRequest request) {
    Map<String, Object> map = applicationContext.getEndpointTypes();
    Collection<Method> methods = new HashSet<Method>();

    for (Entry<String, Object> entry : map.entrySet()) {
        Collection<Method> m = Reflections.getAllMethods(entry.getValue().getClass(),
                Predicates.and(ReflectionUtils.withAnnotation(Action.class),
                        SherpaPredicates.withActionMappingPattern(UrlUtil.getPath(request))));
        methods.addAll(m);//from w ww . j  a  va  2s .com
    }

    method = MethodUtil.validateHttpMethods(methods.toArray(new Method[] {}), request.getMethod());
    if (method != null) {
        Class<?> type = method.getDeclaringClass();
        if (type.isAnnotationPresent(Endpoint.class)) {
            if (StringUtils.isNotEmpty(type.getAnnotation(Endpoint.class).value())) {
                return type.getAnnotation(Endpoint.class).value();
            }
        }
        return type.getSimpleName();
    }
    throw new SherpaEndpointNotFoundException("no endpoint for url [" + UrlUtil.getPath(request) + "]");
}

From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java

/**
 * Retrieves the certificate from the specified URL and confirms that the certificate is valid.
 *
 * @param signingCertificateChainUrl/*from w  w  w .j  ava 2 s .c om*/
 *            the URL to retrieve the certificate chain from
 * @return the certificate at the specified URL, if the certificate is valid
 * @throws CertificateException
 *             if the certificate cannot be retrieve or is invalid
 */
public static X509Certificate retrieveAndVerifyCertificateChain(final String signingCertificateChainUrl)
        throws CertificateException {
    try (InputStream in = getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openStream()) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance(Sdk.SIGNATURE_CERTIFICATE_TYPE);
        @SuppressWarnings("unchecked")
        Collection<X509Certificate> certificateChain = (Collection<X509Certificate>) certificateFactory
                .generateCertificates(in);
        /*
         * check the before/after dates on the certificate date to confirm that it is valid on
         * the current date
         */
        X509Certificate signingCertificate = certificateChain.iterator().next();
        signingCertificate.checkValidity();

        // check the certificate chain
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);

        X509TrustManager x509TrustManager = null;
        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                x509TrustManager = (X509TrustManager) trustManager;
            }
        }

        if (x509TrustManager == null) {
            throw new IllegalStateException(
                    "No X509 TrustManager available. Unable to check certificate chain");
        } else {
            x509TrustManager.checkServerTrusted(
                    certificateChain.toArray(new X509Certificate[certificateChain.size()]),
                    Sdk.SIGNATURE_KEY_TYPE);
        }

        /*
         * verify Echo API's hostname is specified as one of subject alternative names on the
         * signing certificate
         */
        if (!subjectAlernativeNameListContainsEchoSdkDomainName(
                signingCertificate.getSubjectAlternativeNames())) {
            throw new CertificateException("The provided certificate is not valid for the Echo SDK");
        }

        return signingCertificate;
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException ex) {
        throw new CertificateException("Unable to verify certificate at URL: " + signingCertificateChainUrl,
                ex);
    }
}