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:arena.dao.DAOSupport.java

public int update(Iterable<T> valueobjects) {
    Iterable<T> actuallyUpdate = valueobjects;
    if (this.updateListeners != null) {
        for (DAOUpdateListener<T> pre : this.updateListeners) {
            actuallyUpdate = pre.preUpdate(actuallyUpdate);
        }//  www. ja  v a  2s .c om
    }
    int retVal = doUpdate(actuallyUpdate.iterator());

    // We only have post insert VOs if we sent at least one
    if (this.updateListeners != null) {
        for (DAOUpdateListener<T> post : this.updateListeners) {
            post.postUpdate(actuallyUpdate);
        }
    }
    return retVal;
}

From source file:arena.dao.DAOSupport.java

public int delete(Iterable<T> valueobjects) {
    Iterable<T> actuallyDelete = valueobjects;
    if (this.deleteListeners != null) {
        for (DAODeleteListener<T> pre : this.deleteListeners) {
            actuallyDelete = pre.preDelete(actuallyDelete);
        }//w w w . j a  v a 2  s . co m
    }
    int retVal = doDelete(actuallyDelete.iterator());

    // We only have post delete VOs if we sent at least one
    if (this.deleteListeners != null) {
        for (DAODeleteListener<T> post : this.deleteListeners) {
            post.postDelete(actuallyDelete);
        }
    }
    return retVal;
}

From source file:de.fhg.igd.mapviewer.server.wms.WMSTileProvider.java

/**
 * Tile provider using WMS services//  w w w  .  ja  va 2  s  .c  om
 * 
 * @param baseUrl the base URL for the GetCapabilities request
 * @param preferredEpsg the EPSG code of preferred SRS
 * @param zoomLevels the number of zoom levels
 * @param minTileSize the minimum tile size
 * @param minMapSize the minimum map size
 * @param layers the layers to display
 * 
 * @throws WMSCapabilitiesException if reading the capabilities fails
 */
public WMSTileProvider(final String baseUrl, final int preferredEpsg, final int zoomLevels,
        final int minTileSize, final int minMapSize, final String layers) throws WMSCapabilitiesException {

    this.capabilities = WMSUtil.getCapabilities(baseUrl);

    // get server URL
    String mapUrl = capabilities.getMapURL();

    if (mapUrl.endsWith("?") || mapUrl.endsWith("&")) //$NON-NLS-1$ //$NON-NLS-2$
        serverUrl = mapUrl;
    else if (mapUrl.indexOf('?') >= 0)
        serverUrl = mapUrl + '&';
    else
        serverUrl = mapUrl + '?';

    log.info("GetMap URL: " + serverUrl); //$NON-NLS-1$

    // get bounding box
    WMSBounds bb = WMSUtil.getBoundingBox(capabilities, preferredEpsg);

    if (bb != null) {
        // determine parameters from bounding box
        try {
            epsg = Integer.parseInt(bb.getSRS().substring(5));
            minX = bb.getMinX();
            xRange = bb.getMaxX() - minX;
            minY = bb.getMinY();
            yRange = bb.getMaxY() - minY;
        } catch (Exception e) {
            // invalid bb
            log.error("Invalid bounding box", e); //$NON-NLS-1$
            bb = null;
        }
    }
    if (bb == null) {
        // no bounding boxes -> world wms
        log.warn("No valid bounding box found, creating world wms"); //$NON-NLS-1$
        // default tiles
        epsg = EPSG_WGS84;
        minX = -180;
        xRange = 360;
        minY = -90;
        yRange = 180;
    }

    log.info("Map bounds - epsg: " + epsg + ", minX: " + minX + ", xRange: " + xRange //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            + ", minY: " + minY + ", yRange: " + yRange); //$NON-NLS-1$ //$NON-NLS-2$

    // determine tile sizes
    double tileRatio = xRange / yRange;
    if (tileRatio >= 1.0) {
        // xRange is bigger
        yTileSize = minTileSize;
        xTileSize = (int) (tileRatio * yTileSize);
    } else {
        // yRange is bigger
        xTileSize = minTileSize;
        yTileSize = (int) (xTileSize / tileRatio);
    }
    log.info("Tile size: " + xTileSize + "x" + yTileSize); //$NON-NLS-1$ //$NON-NLS-2$

    // determine format
    Iterable<String> formats = capabilities.getFormats();
    Iterator<String> itFormat = formats.iterator();
    while (format == null && itFormat.hasNext()) {
        String f = itFormat.next();
        if (SUPPORTED_FORMATS.contains(f))
            format = f;
    }
    if (format == null) {
        throw new WMSCapabilitiesException("No supported format found: " + formats); //$NON-NLS-1$
    }

    // zoom levels
    maxZoom = zoomLevels - 1;
    totalMapZoom = (int) (maxZoom
            + (Math.log((double) minMapSize / (double) Math.max(xTileSize, yTileSize)) / Math.log(2)));

    // version
    version = capabilities.getVersion();

    // layers
    List<Layer> layerList = WMSUtil.getLayers(layers, capabilities);
    this.layerString = WMSUtil.getLayerString(layerList, true);
}

From source file:de.fau.amos4.web.EmployeeFormController.java

@RequestMapping("/employee/token/submit")
public ModelAndView EmployeeTokenSubmit(HttpServletResponse response,
        @RequestParam(value = "token", required = true) String token, Model model) throws IOException {
    long employeeId = 0;
    Iterable<Employee> allEmployees = employeeRepository.findAll();
    for (Iterator<Employee> i = allEmployees.iterator(); i.hasNext();) {
        Employee currEmployee = i.next();
        if (currEmployee.getToken().equals(token)) {
            employeeId = currEmployee.getId();
        }//from  w ww . j av a  2s  .  co  m
    }

    ModelAndView mav = new ModelAndView();
    if (employeeId != 0) {
        mav.setViewName("employee/edit");
        Employee employee = employeeRepository.findOne(employeeId);
        FormGenerator generator = new FormGenerator();
        mav.addObject("formInfo", generator.Generate(Employee.class, employee));
        mav.addObject("id", employeeId);
        mav.addObject("employee", employee);
        mav.addObject("allDisabled", YesNo.values());
        mav.addObject("allMarital", MaritalStatus.values());
        mav.addObject("allSex", Sex.values());
        mav.addObject("allDenomination", Denomination.values());
        mav.addObject("allTypeOfContract", TypeOfFixedTermContract.values());
        mav.addObject("allHealthInsurance", HealthInsurance.values());
        mav.addObject("allNursingCareInsurance", NursingCareInsurance.values());
        mav.addObject("allPensionInsurance", PensionInsurance.values());
        mav.addObject("addUnemploymentInsurance", UnemploymentInsurance.values());
        mav.addObject("allParenthood", Parenthood.values());
    } else {
        mav.addObject("m", "invalid");
        mav.setViewName("employee/token");
    }
    return mav;
}

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

/**
 * Iterate over an iterable object./*  ww  w. j a v  a 2s .com*/
 *
 * @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" : "")
                    // 1-based index
                    .combine("@index_1", index + 1).build();
            buffer.append(options.fn(current));
            current.destroy();
        }
    }
    return buffer.toString();
}

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

@Test
public void findRelatedMessages() throws Exception {
    ShsMessage message = make(a(ShsMessageMaker.ShsMessage));
    ShsMessageEntry entry = messageLogService.saveMessage(message);
    Assert.assertNotNull(entry);//from  w w w. ja va  2  s  . c  om

    final int maxRelatedEntries = 5;
    // Inject more messages than MAX_RELATED_ENTRIES
    for (int i = 0; i < maxRelatedEntries + 10; i++) {
        messageLogService.messageReceived(messageLogService.saveMessage(make(a(ShsMessage,
                with(ShsMessage.label,
                        a(ShsLabel, with(to, a(To, with(To.value, ShsLabelMaker.DEFAULT_TEST_FROM))),
                                with(corrId, entry.getLabel().getTxId()),
                                with(transferType, TransferType.ASYNCH)))))));
    }

    Iterable<? extends ShsMessageEntry> relatedEntries = messageLogAdminService.findRelatedEntries(entry,
            maxRelatedEntries);
    Iterator<? extends ShsMessageEntry> iter = relatedEntries.iterator();

    int countRelatedEntries = 0;
    for (; iter.hasNext(); ++countRelatedEntries)
        iter.next();

    Assert.assertTrue(countRelatedEntries <= maxRelatedEntries,
            "Exceeded max number of related entries that should get fetched");
}

From source file:com.splout.db.hadoop.TestTablespaceGeneratorTestInsertionSortOrder.java

@Test
public void test() throws Exception {
    generateInput();/*from  w ww .j a v a  2 s . co m*/

    // 1 - define tablespace
    TablespaceBuilder tablespaceBuilder = new TablespaceBuilder();

    TableBuilder paymentsBuilder = new TableBuilder(PAYMENTS_SCHEMA).addCSVTextFile(PAYMENTS_FILE + "");
    paymentsBuilder.partitionBy("name");
    // Insert sort order:
    paymentsBuilder.insertionSortOrder(OrderBy.parse("name:desc"));

    TableBuilder logsBuilder = new TableBuilder(LOGS_SCHEMA).addCSVTextFile(LOGS_FILE + "");
    logsBuilder.partitionBy("name");
    // Insert sort order:
    logsBuilder.insertionSortOrder(OrderBy.parse("action:asc, loc:asc"));

    TableBuilder geoData = new TableBuilder(GEODATA_SCHEMA).addCSVTextFile(GEODATA_FILE + "");
    geoData.replicateToAll();
    // Insert sort order:
    geoData.insertionSortOrder(OrderBy.parse("loc:desc"));

    tablespaceBuilder.add(paymentsBuilder.build());
    tablespaceBuilder.add(logsBuilder.build());
    tablespaceBuilder.add(geoData.build());

    tablespaceBuilder.setNPartitions(1); // only one partition so we can check the order

    TablespaceSpec tablespace = tablespaceBuilder.build();

    // 2 - generate view
    Path outputPath = new Path(TEST_OUTPUT);
    TablespaceGenerator viewGenerator = new TablespaceGenerator(tablespace, outputPath, this.getClass());
    viewGenerator.setCustomReducer(new TupleReducer<ITuple, NullWritable>() {

        public void reduce(ITuple group, Iterable<ITuple> tuples, TupleMRContext context, Collector collector)
                throws IOException, InterruptedException, TupleMRException {

            Iterator<ITuple> it = tuples.iterator();

            // First table in schema order is payments, sorted by name desc

            Assert.assertEquals("Tanos", it.next().get("name").toString());
            Assert.assertEquals("Pere", it.next().get("name").toString());
            Assert.assertEquals("Ivn", it.next().get("name").toString());

            // Second table in schema order is logs, sorted by (action asc, loc asc)

            ITuple next = it.next();
            Assert.assertEquals("DOWN", next.get("action").toString());
            Assert.assertEquals("Germany", next.get("loc").toString());
            next = it.next();
            Assert.assertEquals("DOWN", next.get("action").toString());
            Assert.assertEquals("Spain", next.get("loc").toString());
            next = it.next();
            Assert.assertEquals("DOWN", next.get("action").toString());
            Assert.assertEquals("Spain", next.get("loc").toString());
            next = it.next();
            Assert.assertEquals("UP", next.get("action").toString());
            Assert.assertEquals("Germany", next.get("loc").toString());
            next = it.next();
            Assert.assertEquals("UP", next.get("action").toString());
            Assert.assertEquals("Greece", next.get("loc").toString());
            next = it.next();
            Assert.assertEquals("UP", next.get("action").toString());
            Assert.assertEquals("Greece", next.get("loc").toString());

            // Thrid table in schema order is geodata, sorted by loc desc

            Assert.assertEquals("Spain", it.next().get("loc").toString());
            Assert.assertEquals("Greece", it.next().get("loc").toString());
            Assert.assertEquals("Germany", it.next().get("loc").toString());
        }

        ;
    });

    viewGenerator.generateView(new Configuration(), SamplingType.RANDOM,
            new TupleSampler.RandomSamplingOptions());
}

From source file:name.martingeisse.webide.features.java.compiler.memfile.MemoryFileManager.java

@Override
public Iterable<JavaFileObject> list(final Location location, final String packageName, final Set<Kind> kinds,
        final boolean recurse) throws IOException {
    logger.trace("listing memory files for location [" + location + "], package [" + packageName + "], kinds ["
            + StringUtils.join(kinds, ", ") + "], recurse [" + recurse + "]");
    final Iterable<JavaFileObject> superIterable = super.list(location, packageName, kinds, recurse);
    final Iterable<JavaFileObject> thisIterable = listThis(location, packageName, kinds, recurse);
    logger.trace("contributed memory files: " + StringUtils.join(thisIterable.iterator(), ", "));
    return new Iterable<JavaFileObject>() {
        @Override//from  w ww. j  a v a 2s .  c  om
        public Iterator<JavaFileObject> iterator() {
            return GenericTypeUtil
                    .unsafeCast(new IteratorChain(superIterable.iterator(), thisIterable.iterator()));
        }
    };
}

From source file:org.terasoluna.gfw.web.el.ObjectToMapConverter.java

/**
 * Convert the given Iterable to the flatten map
 * @param prefix prefix of the key/*from   w w  w .j  a v a 2 s.com*/
 * @param value iterable instance to convert
 * @return converted map. all keys are prefixed with the given key. If given Iterable is empty, the pair of the given
 *         name(prefix) and an empty string is added into map of return value.
 */
private Map<String, String> convert(String prefix, Iterable value) {
    Map<String, String> map = new LinkedHashMap<String, String>();
    Iterator iterator = value.iterator();
    if (!iterator.hasNext()) {
        map.put(prefix, "");
        return map;
    }
    int i = 0;
    while (iterator.hasNext()) {
        map.putAll(this.convert(prefix + "[" + i + "]", iterator.next()));
        i++;
    }
    return map;
}

From source file:com.github.rvesse.airline.SingleCommand.java

private SingleCommand(Class<C> command, Iterable<GlobalRestriction> restrictions,
        ParserMetadata<C> parserConfig) {
    if (command == null)
        throw new NullPointerException("command is null");
    this.parserConfig = parserConfig != null ? parserConfig : MetadataLoader.<C>loadParser(command);
    this.restrictions = restrictions != null ? IteratorUtils.toList(restrictions.iterator())
            : AirlineUtils.arrayToList(GlobalRestriction.DEFAULTS);
    if (this.restrictions.size() == 0)
        this.restrictions.addAll(AirlineUtils.arrayToList(GlobalRestriction.DEFAULTS));

    commandMetadata = MetadataLoader.loadCommand(command);
}