Example usage for org.apache.commons.collections IteratorUtils toList

List of usage examples for org.apache.commons.collections IteratorUtils toList

Introduction

In this page you can find the example usage for org.apache.commons.collections IteratorUtils toList.

Prototype

public static List toList(Iterator iterator) 

Source Link

Document

Gets a list based on an iterator.

Usage

From source file:com.activecq.samples.clientcontext.impl.ClientContextBuilderImpl.java

@Override
public JSONObject xssProtect(JSONObject json, String... whitelist) throws JSONException {
    final List<String> keys = IteratorUtils.toList(json.keys());
    final boolean useWhiteList = !ArrayUtils.isEmpty(whitelist);
    log.debug("Use Whitelist: " + !ArrayUtils.isEmpty(whitelist));

    for (final String key : keys) {
        log.debug("XSS Key: " + key);
        if (!useWhiteList || (useWhiteList && !ArrayUtils.contains(whitelist, key))) {
            log.debug("XSS -> " + key + XSS_SUFFIX + ": "
                    + xss.filter(ProtectionContext.PLAIN_HTML_CONTENT, json.optString(key)));
            json.put(key + XSS_SUFFIX, xss.filter(ProtectionContext.PLAIN_HTML_CONTENT, json.optString(key)));
        }/* w w w.  j  a va2 s  .c  o m*/
    }

    log.debug("XSS JSON: " + json.toString(4));

    return json;
}

From source file:net.cpollet.jixture.fixtures.TestGeneratedFixture.java

@Test
public void getClassesToDeleteReturnsClassesToDeleteOfAllGeneratorsInReverseOrder() {
    // GIVEN//from   w w w.  ja  v  a  2s . co  m
    generatedFixture //
            .addGenerators( //
                    new SimpleGenerator(Integer.class, 2), //
                    new SimpleGenerator(String.class, 3));

    // WHEN
    Iterator<Class> classesToDeleteIterator = generatedFixture.getClassesToDeleteIterator();

    // THEN
    List classesToDelete = IteratorUtils.toList(classesToDeleteIterator);
    assertThat(classesToDelete) //
            .hasSize(2) //
            .containsExactly(String.class, Integer.class);
}

From source file:it.inserpio.neo4art.controller.MuseumController.java

/**
 * Retrieve all museums//from w  w  w  .  j  a  v  a  2 s . c  om
 * 
 * @return
 */
@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.GET, produces = { "application/xml", "application/json" })
public @ResponseBody List<Museum> getAllMuseums() {
    return IteratorUtils.toList(this.museumRepository.findAll().iterator());
}

From source file:co.cask.hydrator.plugin.batch.aggreagtor.aggregator.Sampling.java

@Override
public void aggregate(String groupKey, Iterator<StructuredRecord> iterator, Emitter<StructuredRecord> emitter)
        throws Exception {
    int finalSampleSize = 0;
    if (config.sampleSize != null) {
        finalSampleSize = config.sampleSize;
    }/*from   w w w.j av  a  2  s .  c o m*/
    if (config.samplePercentage != null) {
        finalSampleSize = Math.round((config.samplePercentage / 100) * config.totalRecords);
    }

    switch (TYPE.valueOf(config.samplingType.toUpperCase())) {
    case SYSTEMATIC:
        if (config.overSamplingPercentage != null) {
            finalSampleSize = Math
                    .round(finalSampleSize + (finalSampleSize * (config.overSamplingPercentage / 100)));
        }

        int sampleIndex = Math.round(config.totalRecords / finalSampleSize);
        Float random = new Float(0);
        if (config.random != null) {
            random = config.random;
        } else {
            random = new Random().nextFloat();
        }
        int firstSampleIndex = Math.round(sampleIndex * random);
        List<StructuredRecord> records = IteratorUtils.toList(iterator);
        int counter = 0;
        emitter.emit(records.get(firstSampleIndex));
        counter++;

        while (counter < finalSampleSize) {
            int index = firstSampleIndex + (counter * sampleIndex);
            emitter.emit(records.get(index - 1));
            counter++;
        }
        break;

    case RESERVOIR:
        PriorityBuffer sampleData = new PriorityBuffer(true, new Comparator<StructuredRecord>() {
            @Override
            public int compare(StructuredRecord o1, StructuredRecord o2) {
                if ((float) o1.get("random") < (float) o2.get("random")) {
                    return 1;
                } else if ((float) o1.get("random") > (float) o2.get("random")) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });

        int count = 0;
        Random randomValue = new Random();
        List<StructuredRecord> recordArray = IteratorUtils.toList(iterator);
        Schema inputSchema = recordArray.get(0).getSchema();
        Schema schemaWithRandomField = createSchemaWithRandomField(inputSchema);
        while (count < finalSampleSize) {
            StructuredRecord record = recordArray.get(0);
            sampleData.add(getSampledRecord(record, randomValue.nextFloat(), schemaWithRandomField));
            count++;
        }

        while (count < recordArray.size()) {
            StructuredRecord structuredRecord = (StructuredRecord) sampleData.get();
            Float randomFloat = randomValue.nextFloat();
            if ((float) structuredRecord.get("random") < randomFloat) {
                sampleData.remove();
                StructuredRecord record = recordArray.get(count);
                sampleData.add(getSampledRecord(record, randomFloat, structuredRecord.getSchema()));
            }
            count++;
        }

        Iterator<StructuredRecord> sampleDataIterator = sampleData.iterator();
        while (sampleDataIterator.hasNext()) {
            StructuredRecord sampledRecord = sampleDataIterator.next();
            StructuredRecord.Builder builder = StructuredRecord.builder(inputSchema);
            for (Schema.Field field : sampledRecord.getSchema().getFields()) {
                if (!field.getName().equalsIgnoreCase("random")) {
                    builder.set(field.getName(), sampledRecord.get(field.getName()));
                }
            }
            emitter.emit(builder.build());
        }
        break;
    }
}

From source file:com.adobe.cq.wcm.core.components.extension.contentfragment.internal.servlets.ElementsDataSourceServlet.java

@Nonnull
@Override/* w ww  .jav a2  s .com*/
protected List<ContentElement> getItems(@Nonnull ContentFragment fragment,
        @Nonnull SlingHttpServletRequest request) {
    Config config = getConfig(request);
    ValueMap map = getComponentValueMap(config, request);
    String textOnlyParam = request.getParameter(PARAM_AND_PN_DISPLAY_MODE);
    boolean textOnly = map != null && map.containsKey(PARAM_AND_PN_DISPLAY_MODE)
            && map.get(PARAM_AND_PN_DISPLAY_MODE, "multi").equals(SINGLE_TEXT);
    if (textOnlyParam != null) {
        textOnly = textOnlyParam.equals(SINGLE_TEXT);
    }
    if (textOnly) {
        Iterator<ContentElement> elementIterator = fragment.getElements();
        List<ContentElement> elementList = new ArrayList<ContentElement>();
        while (elementIterator.hasNext()) {
            ContentElement element = elementIterator.next();
            String contentType = element.getValue().getContentType();
            if (contentType != null && contentType.startsWith("text/")
                    && !element.getValue().getDataType().isMultiValue()) {
                elementList.add(element);
            }
        }
        return elementList;
    }
    return IteratorUtils.toList(fragment.getElements());
}

From source file:edu.isi.karma.controller.command.worksheet.RenameColumnCommand.java

private void replaceColumnName(JSONObject object) {

    for (Object key : IteratorUtils.toList(object.keys())) {
        String strKey = (String) key;

        Object value = object.get(strKey);
        if (value instanceof String) {
            String strValue = (String) value;
            if (strValue.equals(oldColumnName)) {
                object.put(strKey, newColumnName);
                logger.info("Change column name in " + strKey + " of " + object.toString());
            }//from ww  w  .j ava  2  s .c  om
        } else if (value instanceof JSONObject) {
            replaceColumnName((JSONObject) value);
        } else if (value instanceof JSONArray) {
            JSONArray valueArr = (JSONArray) value;
            for (int i = 0; i < valueArr.length(); i++) {
                JSONObject input = valueArr.getJSONObject(i);
                replaceColumnName(input);
            }
        }
    }

}

From source file:com.gs.obevo.db.impl.core.changetypes.CsvReaderDataSource.java

@Override
protected CatoDataObject nextDataObject() throws Exception {
    if (csvVersion == CsvStaticDataReader.CSV_V2) {
        if (!this.iteratorV2.hasNext()) {
            return null;
        }/*ww  w.j av  a2  s  .  c  o m*/
        List<String> data = IteratorUtils.toList(iteratorV2.next().iterator());

        if (data == null || data.size() == 0 || (data.size() == 1 && data.get(0).isEmpty())) {
            return null;
        } else if (data.size() != this.fields.size()) {
            throw new IllegalArgumentException("This row does not have the right # of columns: expecting "
                    + this.fields.size() + " columns, but the row was: " + Lists.mutable.with(data));
        }

        CatoDataObject dataObject = this.createDataObject();
        for (int i = 0; i < data.size(); i++) {
            dataObject.setValue(this.fields.get(i), data.get(i));
        }

        return dataObject;
    } else {

        String[] data = this.csvreaderV1.readNext();

        if (data == null || data.length == 0 || (data.length == 1 && data[0].isEmpty())) {
            return null;
        } else if (data.length != this.fields.size()) {
            throw new IllegalArgumentException("This row does not have the right # of columns: expecting "
                    + this.fields.size() + " columns, but the row was: " + Lists.mutable.with(data));
        }

        CatoDataObject dataObject = this.createDataObject();
        for (int i = 0; i < data.length; i++) {
            dataObject.setValue(this.fields.get(i), data[i]);
        }

        return dataObject;
    }
}

From source file:com.adobe.acs.commons.synth.children.ChildrenAsPropertyResourceTest.java

@Test
public void testSerialization() throws Exception {
    childrenAsPropertyResource = new ChildrenAsPropertyResource(resource, "animals");

    childrenAsPropertyResource.create("entry-100", "nt:unstructured", entry100);

    List<Resource> actuals = IteratorUtils.toList(childrenAsPropertyResource.listChildren());

    ValueMap actual = actuals.get(0).getValueMap();
    ValueMap expected = new ValueMapDecorator(entry100);

    Assert.assertEquals(expected.get("name", String.class), actual.get("name", String.class));
    Assert.assertEquals(expected.get("double", String.class), actual.get("double", String.class));
    Assert.assertEquals(expected.get("long", Double.class), actual.get("long", Double.class));
    Assert.assertEquals(expected.get("integer", Integer.class), actual.get("integer", Integer.class));
    Assert.assertEquals(expected.get("integerAsLong", Integer.class),
            actual.get("integerAsLong", Integer.class));
    Assert.assertEquals(expected.get("boolean", Boolean.class), actual.get("boolean", Boolean.class));
    Assert.assertEquals(expected.get("booleanAsString", Boolean.class),
            actual.get("booleanAsString", Boolean.class));
    Assert.assertEquals(expected.get("date", Date.class), actual.get("date", Date.class));
    Assert.assertEquals(expected.get("calendar", Calendar.class), actual.get("calendar", Calendar.class));

    // Special expectation setting as ValueMaps do not handle these types are expected by the implementation
    Assert.assertEquals((Integer) expected.get("integerAsDouble", Double.class).intValue(),
            actual.get("integerAsDouble", Integer.class));
    Assert.assertEquals(new BigDecimal(expected.get("bigdecimal", String.class)),
            actual.get("bigdecimal", BigDecimal.class));
    Assert.assertEquals(new BigDecimal(expected.get("bigdecimal2", String.class)),
            actual.get("bigdecimal2", BigDecimal.class));

    Assert.assertNotNull(actual.get("date", Calendar.class));
    Assert.assertEquals(expected.get("calendar", Calendar.class), actual.get("date", Calendar.class));

    Assert.assertNotNull(actual.get("calendar", Date.class));
    Assert.assertEquals(expected.get("date", Date.class), actual.get("calendar", Date.class));
}

From source file:com.gs.obevo.impl.graph.GraphSorter.java

/**
 * Sorts the graph to provide a consistent topological ordering.
 *
 * @param graph      The input graph - all vertices in the graph will be returned in the output list
 * @param comparator The comparator on which to order the vertices to guarantee a consistent topological ordering
 *//*from w  w  w.  ja va2  s  .co m*/
public <T> ImmutableList<T> sortChanges(final DirectedGraph<T, DefaultEdge> graph,
        Comparator<? super T> comparator) {
    if (graph.vertexSet().isEmpty()) {
        return Lists.immutable.empty();
    }

    GraphUtil.validateNoCycles(graph);

    TopologicalOrderIterator<T, DefaultEdge> iterator = getTopologicalOrderIterator(graph, comparator);

    return Lists.immutable.withAll(IteratorUtils.toList(iterator));
}

From source file:edu.uci.ics.jung.utils.DefaultUserData.java

/**
 * Uses the CopyAction to determine how each of the user datum elements in
 * udc should be carried over to the this UserDataContiner
 * //from w  w  w. j a v a 2  s. c om
 * @param udc
 *            The UserDataContainer whose user data is being imported
 */
public void importUserData(UserDataContainer udc) {
    for (Iterator keyIt = udc.getUserDatumKeyIterator(); keyIt.hasNext();) {
        Object key = keyIt.next();
        Object value = udc.getUserDatum(key);
        CopyAction action = udc.getUserDatumCopyAction(key);
        Object newValue = action.onCopy(value, udc, this);
        try {
            if (newValue != null)
                addUserDatum(key, newValue, action);

        } catch (IllegalArgumentException iae) {
            List userDataKeys = IteratorUtils.toList(udc.getUserDatumKeyIterator());
            throw new FatalException("Copying <" + key + "> of " + userDataKeys
                    + " into a container that started with some keys ", iae);
        }
    }

}