Example usage for java.lang Iterable iterator

List of usage examples for java.lang Iterable iterator

Introduction

In this page you can find the example usage for java.lang Iterable iterator.

Prototype

Iterator<T> iterator();

Source Link

Document

Returns an iterator over elements of type T .

Usage

From source file:com.infinities.skyport.openstack.SkyportNovaOpenStack.java

@Override
public synchronized @Nonnull AuthenticationContext getAuthenticationContext()
        throws CloudException, InternalException {
    APITrace.begin(this, "Cloud.getAuthenticationContext");
    try {//w w w.ja  v  a2s .  c om
        Cache<AuthenticationContext> cache = Cache.getInstance(this, "authenticationContext",
                AuthenticationContext.class, CacheLevel.REGION_ACCOUNT, new TimePeriod<Day>(1, TimePeriod.DAY));
        ProviderContext ctx = getContext();

        if (ctx == null) {
            throw new CloudException("No context was set for this request");
        }
        Iterable<AuthenticationContext> current = cache.get(ctx);
        AuthenticationContext authenticationContext = null;

        NovaMethod method = new SkyportNovaMethod(this);

        if (current != null) {
            authenticationContext = current.iterator().next();
        } else {
            try {
                authenticationContext = method.authenticate();
            } finally {
                if (authenticationContext == null) {
                    NovaException.ExceptionItems items = new NovaException.ExceptionItems();

                    items.code = HttpStatus.SC_UNAUTHORIZED;
                    items.type = CloudErrorType.AUTHENTICATION;
                    items.message = "unauthorized";
                    items.details = "The API keys failed to authenticate with the specified endpoint.";
                    throw new NovaException(items);
                }
                cache.put(ctx, Collections.singletonList(authenticationContext));
            }
        }
        return authenticationContext;
    } finally {
        APITrace.end();
    }
}

From source file:com.auditbucket.test.functional.TestCallerRef.java

@Test
@Transactional/*  www .j a va2s  . c o  m*/
public void findByCallerRefAcrossDocumentTypes() throws Exception {
    registrationEP.registerSystemUser(new RegistrationBean(monowai, mike, "bah"));
    Fortress fortress = fortressEP.registerFortress(new FortressInputBean("auditTest", true), null).getBody();

    MetaInputBean inputBean = new MetaInputBean(fortress.getName(), "wally", "DocTypeA", new DateTime(),
            "ABC123");

    // Ok we now have a metakey, let's find it by callerRef ignoring the document and make sure we find the same thing
    String metaKey = trackEP.trackHeader(inputBean, null, null).getBody().getMetaKey();
    Iterable<MetaHeader> results = trackEP.getByCallerRef(fortress.getName(), "ABC123", null, null);
    assertEquals(true, results.iterator().hasNext());
    assertEquals(metaKey, results.iterator().next().getMetaKey());

    // Same caller ref but different document - this scenario is the callers to resolve
    inputBean = new MetaInputBean(fortress.getName(), "wally", "DocTypeZ", new DateTime(), "ABC123");
    trackEP.trackHeader(inputBean, null, null).getBody();

    results = trackEP.getByCallerRef(fortress.getName(), "ABC123", null, null);
    int count = 0;
    // Should be a total of 2, both for the same fortress but different document types
    for (MetaHeader result : results) {
        assertEquals("ABC123", result.getCallerRef());
        count++;
    }
    assertEquals(2, count);

}

From source file:com.simphony.managedbeans.PopulationBean.java

/**
 * Llenamos lista de agremiados//from   w  w w.j a v  a2  s . co  m
 */
private void fillPopulation() {
    list.clear();
    Iterable<Population> c = this.populationService.getPopulationRepository().findAll(sortByDescription());
    Iterator<Population> cu = c.iterator();
    while (cu.hasNext()) {
        list.add(cu.next());
    }
}

From source file:haven.Utils.java

public static <T> T el(Iterable<T> c) {
    Iterator<T> i = c.iterator();
    if (!i.hasNext())
        return (null);
    return (i.next());
}

From source file:io.crate.integrationtests.BlobHttpIntegrationTest.java

@Before
public void setup() throws ExecutionException, InterruptedException {
    Iterable<HttpServerTransport> transports = internalCluster().getInstances(HttpServerTransport.class);
    Iterator<HttpServerTransport> httpTransports = transports.iterator();
    address = ((InetSocketTransportAddress) httpTransports.next().boundAddress().publishAddress()).address();
    address2 = ((InetSocketTransportAddress) httpTransports.next().boundAddress().publishAddress()).address();
    BlobAdminClient blobAdminClient = internalCluster().getInstance(BlobAdminClient.class);

    Settings indexSettings = Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)
            .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 2).build();
    blobAdminClient.createBlobTable("test", indexSettings).get();
    blobAdminClient.createBlobTable("test_blobs2", indexSettings).get();

    client().admin().indices().prepareCreate("test_no_blobs")
            .setSettings(Settings.builder().put("number_of_shards", 2).put("number_of_replicas", 0).build())
            .execute().actionGet();//from  w w w .ja v  a2 s  .  c  om
    ensureGreen();
}

From source file:com.citic.zxyjs.zwlscx.mapreduce.join.api.DataJoinReducerBase.java

@SuppressWarnings("unchecked")
protected void reduce(Text key, Iterable<TaggedMapOutput> values, Context context)
        throws IOException, InterruptedException {
    SortedMap<Text, ResetableIterator<TaggedMapOutput>> groups = regroup(key, values.iterator(), context);
    Text[] tags = groups.keySet().toArray(new Text[0]);
    ResetableIterator<TaggedMapOutput>[] groupValues = new ResetableIterator[tags.length];
    for (int i = 0; i < tags.length; i++) {
        groupValues[i] = groups.get(tags[i]);
    }/*from  w  w  w.j  a v  a  2s .  c  o m*/
    joinAndCollect(tags, groupValues, key, context);
    for (int i = 0; i < tags.length; i++) {
        groupValues[i].close();
    }
}

From source file:com.github.jknack.handlebars.helper.EachHelper.java

/**
 * Iterate over an iterable object./*from w w w .java 2 s  .c  o m*/
 *
 * @param context The context object.
 * @param options The helper options.
 * @return The string output.
 * @throws IOException If something goes wrong.
 */
private CharSequence iterableContext(final Iterable<Object> context, final Options options) throws IOException {
    StringBuilder buffer = new StringBuilder();
    if (options.isFalsy(context)) {
        buffer.append(options.inverse());
    } else {
        Iterator<Object> iterator = context.iterator();
        int index = -1;
        Context parent = options.context;
        while (iterator.hasNext()) {
            index += 1;
            Object element = iterator.next();
            boolean first = index == 0;
            boolean even = index % 2 == 0;
            boolean last = !iterator.hasNext();
            Context current = Context.newBuilder(parent, element).combine("@index", index)
                    .combine("@first", first ? "first" : "").combine("@last", last ? "last" : "")
                    .combine("@odd", even ? "" : "odd").combine("@even", even ? "even" : "").build();
            buffer.append(options.fn(current));
            current.destroy();
        }
    }
    return buffer.toString();
}

From source file:fr.landel.utils.commons.StringUtils.java

/**
 * <p>//from   w w w  .  jav  a2s. co m
 * Joins the elements of the provided iterable into a single String
 * containing the provided list of elements.
 * </p>
 *
 * <p>
 * No delimiter is added before or after the list. A {@code null} separator
 * is the same as an empty String (""). The formatter if provided should
 * support {@code null} value. By default the formatter used the function
 * {@link String#valueOf}.
 * </p>
 *
 * <pre>
 * StringUtils.join(null, *, *)                = null
 * StringUtils.join([], *, *)                  = ""
 * StringUtils.join([null], *, null)           = "null"
 * StringUtils.join(["a", "b", "c"], "--", null)  = "a--b--c"
 * StringUtils.join(["a", "b", "c"], null, StringUtils::upperCase)  = "ABC"
 * StringUtils.join(["a", "b", "c"], "", StringUtils::upperCase)    = "ABC"
 * StringUtils.join([null, "", "a"], ",", StringUtils::upperCase)   = ",,A"
 * </pre>
 * 
 * @param iterable
 *            the {@link Iterable} providing the values to join together,
 *            may be null
 * @param separator
 *            the separator character to use, null treated as ""
 * @param formatter
 *            the formatter to stringify each element, null treated as
 *            {@link String#valueOf}
 * @param <T>
 *            the type of iterable element
 * @return the joined String, {@code null} if null array input.
 */
public static <T> String join(final Iterable<T> iterable, final String separator,
        final Function<T, String> formatter) {
    if (iterable == null) {
        return null;
    }

    return join(iterable.iterator(), separator, formatter);
}

From source file:se.inera.axel.shs.broker.messagestore.internal.MongoMessageLogAdminServiceIT.java

@Test
public void findMessagesByCorrId() throws Exception {

    MessageLogAdminService.Filter filter = new MessageLogAdminService.Filter();
    filter.setCorrId("testing-corrid");

    Iterable<ShsMessageEntry> results = messageLogAdminService.findMessages(filter);
    Assert.assertNotNull(results);/*from   w  ww . j a  v a 2s  .  c om*/
    Assert.assertTrue(results.iterator().hasNext(), "Result has no entries");

    for (ShsMessageEntry result : results) {
        if (!"testing-corrid".equals(result.getLabel().getCorrId())) {
            Assert.fail("Result contains messages that don't match criteria");
        }
    }
}

From source file:se.inera.axel.shs.broker.messagestore.internal.MongoMessageLogAdminServiceIT.java

@Test
public void findMessageByTxid() throws Exception {
    ShsMessage message = make(a(ShsMessageMaker.ShsMessage));
    ShsMessageEntry entry = messageLogService.saveMessage(message);
    Assert.assertNotNull(entry);/*from w  ww  .  jav a  2  s.  co  m*/

    MessageLogAdminService.Filter filter = new MessageLogAdminService.Filter();
    filter.setTxId(message.getLabel().getTxId());

    Iterable<ShsMessageEntry> results = messageLogAdminService.findMessages(filter);
    Assert.assertNotNull(results);
    Assert.assertTrue(results.iterator().hasNext(), "Result has no entries");

    ShsMessageEntry result = results.iterator().next();
    Assert.assertEquals(result.getId(), entry.getId());

}