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:io.wcm.caconfig.extensions.persistence.impl.ToolsConfigPagePersistenceStrategy.java

@SuppressWarnings("unchecked")
@Override//from w  w w . j a  va2  s. com
public Collection<Iterator<Resource>> getResourceCollectionInheritanceChain(
        @NotNull final Resource contentResource, @NotNull final Collection<String> bucketNames,
        @NotNull final String configName) {
    if (!isEnabledAndParamsValid(contentResource, bucketNames, configName)) {
        return null;
    }
    final ResourceResolver resourceResolver = contentResource.getResourceResolver();
    final List<String> paths = IteratorUtils.toList(findConfigRefs(contentResource, bucketNames));

    // get resource collection with respect to collection inheritance
    Collection<Resource> resourceCollection = getResourceCollectionInternal(bucketNames, configName,
            paths.iterator(), resourceResolver);

    // get inheritance chain for each item found
    // yes, this resolves the closest item twice, but is the easiest solution to combine both logic aspects
    Iterator<Iterator<Resource>> result = IteratorUtils.transformedIterator(resourceCollection.iterator(),
            new Transformer() {

                @Override
                public Object transform(Object input) {
                    Resource item = (Resource) input;
                    return getResourceInheritanceChainInternal(bucketNames, configName + "/" + item.getName(),
                            paths.iterator(), resourceResolver);
                }
            });
    if (result.hasNext()) {
        return IteratorUtils.toList(result);
    } else {
        return null;
    }
}

From source file:com.evolveum.midpoint.web.component.assignment.MultipleAssignmentSelector.java

private List<AssignmentEditorDto> applyQueryToListProvider(ObjectQuery query,
        List<AssignmentEditorDto> providerList) {
    ObjectDataProvider temporaryProvider = new ObjectDataProvider(MultipleAssignmentSelector.this, type);
    List<AssignmentEditorDto> displayAssignmentsList = new ArrayList<>();
    temporaryProvider.setQuery(query);/*from  w  ww  .j av  a2s .  c  o m*/
    Iterator it = temporaryProvider.internalIterator(0, temporaryProvider.size());
    List<SelectableBean<F>> providerDataList = IteratorUtils.toList(it);
    for (AssignmentEditorDto dto : providerList) {
        for (SelectableBean<F> providerDataDto : providerDataList) {
            F object = providerDataDto.getValue();
            if (object != null && object.getOid().equals(dto.getTargetRef().getOid())) {
                displayAssignmentsList.add(dto);
                break;
            }
        }
    }
    return displayAssignmentsList;
}

From source file:com.feilong.commons.core.tools.json.JsonUtil.java

/**
 * Bean?Map?????Json./*from w  w w  . j  a va2  s  . com*/
 *
 * @param obj
 *            the obj
 * @param jsonConfig
 *            the json config
 * @return the jSON
 * @throws JSONException
 *             the JSON exception
 * @see net.sf.json.JSONArray#fromObject(Object, JsonConfig)
 * @see net.sf.json.JSONObject#fromObject(Object, JsonConfig)
 * @see net.sf.json.util.JSONUtils#isArray(Object)
 * @see java.lang.Class#isEnum()
 * @see net.sf.json.JsonConfig#registerJsonValueProcessor(Class, JsonValueProcessor)
 * @see org.apache.commons.collections.IteratorUtils#toList(Iterator)
 * @see org.apache.commons.collections.IteratorUtils#toList(Iterator, int)
 */
public static JSON toJSON(Object obj, JsonConfig jsonConfig) throws JSONException {
    if (null == jsonConfig) {
        jsonConfig = getDefaultJsonConfig();
        // ?
        DateJsonValueProcessor jsonValueProcessor = new DateJsonValueProcessor(
                DatePattern.COMMON_DATE_AND_TIME);
        jsonConfig.registerJsonValueProcessor(Date.class, jsonValueProcessor);
    }

    // obj instanceof Collection || obj instanceof Object[]
    if (JSONUtils.isArray(obj) || //
            obj instanceof Enum || // obj.getClass().isEnum() null// object'isanEnum.UseJSONArrayinstead
            obj instanceof Iterator) {

        if (obj instanceof Iterator) {
            Collection<?> list = IteratorUtils.toList((Iterator<?>) obj);
            obj = list;
        }
        //Accepts JSON formatted strings, arrays, Collections and Enums.
        return JSONArray.fromObject(obj, jsonConfig);
    }
    //Accepts JSON formatted strings, Maps, DynaBeans and JavaBeans.
    return JSONObject.fromObject(obj, jsonConfig);
}

From source file:com.dasein.cloud.azurepack.tests.platform.AzurePackRelationalDatabaseSupportTest.java

@Test
public void testGetSupportedVersionsReturnsCorrectValues() throws CloudException, InternalException {
    //for now getSupportedVersions should return an empty list
    final Iterable<String> supportedVersions = support.getSupportedVersions(null);
    assertNotNull(supportedVersions);/*from w  ww .  j  ava  2  s.c o m*/
    assertEquals(0, IteratorUtils.toList(supportedVersions.iterator()).size());
}

From source file:gov.gtas.services.CaseDispositionServiceImpl.java

@Override
public List<HitDispositionStatus> getHitDispositionStatuses() {
    Iterable<HitDispositionStatus> i = hitDispRepo.findAll();
    if (i != null) {
        return IteratorUtils.toList(i.iterator());
    }/*  w w w .j  av  a 2  s  . c  o  m*/
    return new ArrayList<>();
}

From source file:com.delphix.delphix.DelphixEngine.java

/**
 * Provision a VDB either a semantic point or a snapshot with the name of the new VDB being optional
 *///from  w  w w  .  j av  a2s .co  m
@SuppressWarnings("unchecked")
public String provisionVDB(String containerRef, String snapshotRef, String containerName, String repositoryRef,
        String mountBase) throws IOException, DelphixEngineException {
    String defaultParams = "";
    if (snapshotRef.equals(CONTENT_LATEST_POINT) || snapshotRef.equals(CONTENT_LATEST_SNAPSHOT)) {
        defaultParams = getProvisionDefaultsContainer(containerRef, snapshotRef);
    } else {
        defaultParams = getProvisionDefaultsSnapshot(snapshotRef);
    }
    // Strip out null values from provision parameters
    defaultParams = defaultParams.replaceAll("(\"[^\"]+\":null,?|,?\"[^\"]+\":null)", "");
    JsonNode params = MAPPER.readTree(defaultParams);

    // Set new VDB name if it is passed
    if (!containerName.isEmpty()) {
        ObjectNode containerNode = (ObjectNode) params.get("container");
        containerNode.put("name", containerName);
        ObjectNode sourceConfigNode = (ObjectNode) params.get("sourceConfig");
        sourceConfigNode.put("databaseName", containerName);
        sourceConfigNode.put("uniqueName", containerName);
        ObjectNode instanceNode = (ObjectNode) sourceConfigNode.get("instance");
        instanceNode.put("instanceName", containerName);
    }

    // Set target repository
    if (!repositoryRef.isEmpty() && !repositoryRef.equals("default")) {
        ObjectNode sourceConfig = (ObjectNode) params.get("sourceConfig");
        sourceConfig.put("repository", repositoryRef);
        DelphixRepository repository = getRepository(repositoryRef);
        // Handle provisioning to RAC
        if (repository.getRAC()) {
            sourceConfig.put("type", "OracleRACConfig");
            if (sourceConfig.has("instance")) {
                sourceConfig.remove("instance");
            }
            ArrayNode instances = sourceConfig.putArray("instances");
            ArrayList<DelphixClusterNode> clusterNodes = listClusterNodes();
            int i = 1;
            for (DelphixClusterNode node : clusterNodes) {
                ObjectNode instance = MAPPER.createObjectNode();
                instance.put("type", "OracleRACInstance");
                instance.put("instanceNumber", i);
                ObjectNode containerNode = (ObjectNode) params.get("container");
                instance.put("instanceName", containerNode.get("name").asText() + i);
                instance.put("node", node.getReference());
                instances.add(instance);
                i++;
            }
        }
    }

    // Set the base mount point
    if (!mountBase.isEmpty()) {
        ObjectNode sourceConfig = (ObjectNode) params.get("source");
        sourceConfig.put("mountBase", mountBase);

    }
    JsonNode result;
    ObjectNode sourceNode = (ObjectNode) params.get("source");

    // Hack for RAC support
    if (sourceNode.has("redoLogSizeInMB")) {
        sourceNode.remove("redoLogSizeInMB");
    }
    try {
        result = enginePOST(PATH_PROVISION, params.toString());
    } catch (DelphixEngineException e) {
        // Handle the case where some of the fields in the defaults are read
        // only by removing those fields
        if (e.getMessage().contains("This field is read-only")) {
            JsonNode errors = MAPPER.readTree(e.getMessage());
            List<String> list1 = IteratorUtils.toList(errors.fieldNames());
            for (String field1 : list1) {
                List<String> list2 = IteratorUtils.toList(errors.get(field1).fieldNames());
                for (String field2 : list2) {
                    // Field1 is the outer field and field2 is the inner
                    // field
                    ObjectNode node = (ObjectNode) params.get(field1);
                    // Remove the inner field
                    node.remove(field2);
                }
            }
            result = enginePOST(PATH_PROVISION, params.toString());
        } else {
            throw e;
        }
    }
    return result.get(FIELD_JOB).asText();

}

From source file:com.stratio.qa.specs.CommonG.java

/**
 * Parse jsonpath expression from a given string.
 * <p>/*  w ww. j a  v a 2 s  .c  o m*/
 * If the string is json we can obtain its keys using ~ symbol.
 * <p>
 * If position is not null and the result of jsonpath expression is an array,
 * then this function will return the element at the given position at the array.
 * <p>
 * If position is null, it will return the result of the jsonpath evaluation as string.
 *
 * @param jsonString string to be parsed
 * @param expr       jsonpath expression
 * @param position   position from a search result
 */
public String getJSONPathString(String jsonString, String expr, String position) {

    String value;

    if (expr.contains(".~")) {
        this.getLogger().debug("Expression referred to json keys");
        Pattern pattern = Pattern.compile("^(.*?).~(.*?)$");
        Matcher matcher = pattern.matcher(expr);
        String aux = null;
        String op = null;
        if (matcher.find()) {
            aux = matcher.group(1);
            op = matcher.group(2);
        }
        LinkedHashMap auxData = JsonPath.parse(jsonString).read(aux);
        JSONObject json = new JSONObject(auxData);
        List<String> keys = IteratorUtils.toList(json.keys());
        List<String> stringKeys = new ArrayList<String>();
        if (op.equals("")) {
            for (String key : keys) {
                stringKeys.add("\"" + key + "\"");
            }
            value = stringKeys.toString();
        } else {
            Pattern patternOp = Pattern.compile("^\\[(-?\\d+)\\]$");
            Matcher matcherOp = patternOp.matcher(op);
            Integer index = null;
            Boolean isNegative = false;
            if (matcherOp.find()) {
                if (matcherOp.group(1).contains("-")) {
                    isNegative = true;
                }
                index = Integer.parseInt(matcherOp.group(1).replace("-", ""));
            }
            if (isNegative) {
                value = keys.get(keys.size() - index).toString();
            } else {
                value = keys.get(index).toString();
            }

        }
    } else {
        String result = JsonValue.readHjson(jsonString).toString();
        Object data = JsonPath.parse(result).read(expr);
        if (position != null) {
            JSONArray jsonArray = new JSONArray(data.toString());
            value = jsonArray.get(Integer.parseInt(position)).toString();
        } else {
            if (data instanceof LinkedHashMap) {
                value = (new JSONObject((LinkedHashMap) data)).toString();
            } else {
                value = data.toString();
            }
        }
    }
    return value;
}

From source file:com.atlassian.jira.bc.group.TestDefaultGroupService.java

@Test
public void testValidateRemoveUserFromGroupsHappyPath() {
    final DefaultGroupService defaultGroupService = new DefaultGroupService(null, null, null, null, null, null,
            null, null, null, null, null, null, null, null) {
        @Override//from www .  j a  va 2 s.  co m
        public boolean validateRemoveUsersFromGroups(final JiraServiceContext jiraServiceContext,
                final GroupRemoveChildMapper mapper) {
            assertNotNull(mapper);
            final List groupsForUser = IteratorUtils.toList(mapper.getGroupsIterator("admin"));
            assertNotNull(groupsForUser);
            assertEquals(1, groupsForUser.size());
            assertEquals("Group1", groupsForUser.iterator().next());
            assertFalse(mapper.isRemoveFromAllSelected("admin"));
            return true;
        }
    };

    final SimpleErrorCollection errors = new SimpleErrorCollection();
    final JiraServiceContext jiraServiceContext = getContext(errors);

    assertTrue(defaultGroupService.validateRemoveUserFromGroups(jiraServiceContext, EasyList.build("Group1"),
            "admin"));

}

From source file:nl.tricode.magnolia.blogs.templates.BlogRenderableDefinition.java

/**
 * Get total number of blog posts for current state.
 * (Performs additional JCR-SQL2 query to obtain count!)
 *
 * @param path       Start node path in hierarchy
 * @param useFilters <code>true</code> to use filters
 * @return long Number of blog posts/*from   ww  w. j a v  a  2s .  c om*/
 */
public int getBlogCount(String path, boolean useFilters) throws RepositoryException {
    String customFilters = getAuthorPredicate() + getTagPredicate(filter) + getCategoryPredicate(filter)
            + getDateCreatedPredicate();
    final String sqlBlogItems = buildQuery(path, useFilters, customFilters, BLOG_NODE_TYPE);
    return IteratorUtils.toList(QueryUtil.search(BlogWorkspaceUtil.COLLABORATION, sqlBlogItems, Query.JCR_SQL2,
            BlogsNodeTypes.Blog.NAME)).size();
}

From source file:nl.tricode.magnolia.blogs.templates.BlogRenderableDefinition.java

public int getRelatedBlogCount(String filterProperty, String filterIdentifier) throws RepositoryException {
    final String sqlBlogItems = "SELECT p.* from [mgnl:blog] AS p WHERE ISDESCENDANTNODE(p,'/') AND contains(p."
            + filterProperty + ", '" + filterIdentifier + "')";
    return IteratorUtils.toList(QueryUtil.search(BlogWorkspaceUtil.COLLABORATION, sqlBlogItems, Query.JCR_SQL2,
            BlogsNodeTypes.Blog.NAME)).size();
}