Example usage for com.google.common.collect Iterators toArray

List of usage examples for com.google.common.collect Iterators toArray

Introduction

In this page you can find the example usage for com.google.common.collect Iterators toArray.

Prototype

@GwtIncompatible("Array.newInstance(Class, int)")
public static <T> T[] toArray(Iterator<? extends T> iterator, Class<T> type) 

Source Link

Document

Copies an iterator's elements into an array.

Usage

From source file:org.apache.asterix.test.aql.ResultExtractor.java

public static InputStream extract(InputStream resultStream) throws Exception {
    ObjectMapper om = new ObjectMapper();
    StringWriter sw = new StringWriter();
    String resultStr = IOUtils.toString(resultStream, Charset.defaultCharset());
    PrettyPrinter singleLine = new SingleLinePrettyPrinter();
    ObjectNode result = om.readValue(resultStr, ObjectNode.class);

    LOGGER.fine("+++++++\n" + result + "\n+++++++\n");

    String type = "";
    String status = "";
    String results = "";
    String field = "";
    for (Iterator<String> sIter = result.fieldNames(); sIter.hasNext();) {
        field = sIter.next();/*w w  w .  j  ava 2s .c  o  m*/
        switch (field) {
        case "requestID":
            break;
        case "signature":
            break;
        case "status":
            status = om.writeValueAsString(result.get(field));
            break;
        case "type":
            type = om.writeValueAsString(result.get(field));
            break;
        case "metrics":
            LOGGER.fine(om.writeValueAsString(result.get(field)));
            break;
        case "errors":
            JsonNode errors = result.get(field).get(0).get("msg");
            throw new AsterixException(errors.asText());
        case "results":
            if (result.get(field).size() <= 1) {
                if (result.get(field).size() == 0) {
                    results = "";
                } else if (result.get(field).isArray()) {
                    if (result.get(field).get(0).isTextual()) {
                        results = result.get(field).get(0).asText();
                    } else {
                        ObjectMapper omm = new ObjectMapper();
                        omm.setDefaultPrettyPrinter(singleLine);
                        omm.enable(SerializationFeature.INDENT_OUTPUT);
                        results = omm.writer(singleLine).writeValueAsString(result.get(field));
                    }
                } else {
                    results = om.writeValueAsString(result.get(field));
                }
            } else {
                StringBuilder sb = new StringBuilder();
                JsonNode[] fields = Iterators.toArray(result.get(field).elements(), JsonNode.class);
                if (fields.length > 1) {
                    for (JsonNode f : fields) {
                        if (f.isObject()) {
                            sb.append(om.writeValueAsString(f));
                        } else {
                            sb.append(f.asText());
                        }
                    }
                }
                results = sb.toString();
            }
            break;
        default:
            throw new AsterixException(field + "unanticipated field");
        }
    }

    return IOUtils.toInputStream(results);
}

From source file:io.wcm.config.editor.impl.EditorParameterProvider.java

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    Configuration[] allConfigurations = Iterators.toArray(getConfigurations(request), Configuration.class);
    Map<String, Application> applicationsMap = getApplicationsMap();
    JSONArray parameters = new JSONArray();

    for (int i = allConfigurations.length - 1; i >= 0; i--) {
        Configuration configuration = allConfigurations[i];
        try {//from  ww  w .j  av  a  2s.  c om
            addParameters(parameters, configuration, request, applicationsMap);
        } catch (JSONException ex) {
            log.error("Could not parse parameters for the configuration {}", configuration.getConfigurationId(),
                    ex);
            response.sendError(500);
        }
    }

    writeResponse(response, parameters);
}

From source file:io.wcm.config.core.management.util.TypeConversion.java

/**
 * Converts a typed value to it's string representation.
 * @param value Typed value/* w  w w.j  av  a  2s .  c o m*/
 * @return String value
 */
public static String objectToString(Object value) {
    if (value == null) {
        return null;
    }
    if (value instanceof String) {
        return (String) value;
    }
    if (value instanceof String[]) {
        return StringUtils.join((String[]) value, ARRAY_DELIMITER);
    } else if (value instanceof Integer) {
        return Integer.toString((Integer) value);
    } else if (value instanceof Long) {
        return Long.toString((Long) value);
    } else if (value instanceof Double) {
        return Double.toString((Double) value);
    } else if (value instanceof Boolean) {
        return Boolean.toString((Boolean) value);
    } else if (value instanceof Map) {
        Map<?, ?> map = (Map<?, ?>) value;
        StringBuilder stringValue = new StringBuilder();
        Map.Entry<?, ?>[] entries = Iterators.toArray(map.entrySet().iterator(), Map.Entry.class);
        for (int i = 0; i < entries.length; i++) {
            Map.Entry<?, ?> entry = entries[i];
            String entryKey = Objects.toString(entry.getKey(), "");
            String entryValue = Objects.toString(entry.getValue(), "");
            stringValue.append(entryKey).append(KEY_VALUE_DELIMITER).append(entryValue);
            if (i < entries.length - 1) {
                stringValue.append(ARRAY_DELIMITER);
            }
        }
        return stringValue.toString();
    }
    throw new IllegalArgumentException("Unsupported type: " + value.getClass().getName());
}

From source file:eu.trentorise.opendata.semtext.TermsView.java

@Override
public Object[] toArray() {
    return Iterators.toArray(iterator(), Term.class);
}

From source file:org.richfaces.ui.misc.focus.AbstractFocusRenderStrategy.java

/**
 * Returns clientIds of component for which validation has failed and adds form's clientId at the end (as a fallback if
 * there is no invalid component or none of invalid components won't be focusable on the client).
 *//* w  ww  .j ava2 s  .  com*/
private String[] getClientIdsWithMessages(FacesContext context, UIForm form) {
    Iterator<String> clientIdsWithMessages = Iterators.filter(context.getClientIdsWithMessages(),
            new Predicate<String>() {
                @Override
                public boolean apply(String input) {
                    return input != null;
                }
            });
    return Iterators.toArray(clientIdsWithMessages, String.class);
}

From source file:io.wcm.config.core.management.impl.ParameterResolverImpl.java

@Override
public Map<String, Object> getEffectiveValues(ResourceResolver resolver, Collection<String> configurationIds) {
    Map<String, Object> parameterValues = new HashMap<>();

    // apply default values
    applyDefaultValues(parameterValues);
    applyOverrideSystemDefault(parameterValues);

    // apply configured values following inheritance hierarchy
    String[] configurationIdArray = Iterators.toArray(configurationIds.iterator(), String.class);
    SortedSet<String> lockedParameterNames = ImmutableSortedSet.<String>of();
    for (int i = configurationIdArray.length - 1; i >= 0; i--) {
        String configurationId = configurationIdArray[i];
        lockedParameterNames = applyConfiguredValues(resolver, configurationId, parameterValues,
                lockedParameterNames);//w w w  . ja va2  s  .  com

        // apply forced override values
        applyOverrideForce(configurationId, parameterValues);
    }

    return parameterValues;
}

From source file:ch.njol.skript.expressions.ExprFilter.java

@Override
protected Object[] get(Event e) {
    try {//ww w.j a  v  a2s.  c om
        return Converters.convertStrictly(Iterators.toArray(iterator(e), Object.class), getReturnType());
    } catch (ClassCastException e1) {
        return null;
    }
}

From source file:org.polarsys.reqcycle.styling.ui.providers.StylingContentProvider.java

@Override
public Object[] getElements(Object inputElement) {
    if (inputElement instanceof NavigatorRoot) {
        predicates = ((NavigatorRoot) inputElement).getPredicates();
        scopes = ((NavigatorRoot) inputElement).getScopes();
        reqFilter = ((NavigatorRoot) inputElement).getFilter();
        displayType = ((NavigatorRoot) inputElement).getDisplay();

        switch (displayType) {
        case FILTERBYNAME:
            if ((reqFilter != null) && (!reqFilter.equals(""))) {
                final Pattern p = Pattern.compile(".*" + reqFilter + ".*", Pattern.DOTALL);
                final Predicate<Object> attPredicate = new Predicate<Object>() {
                    @Override//  w  w w  .j  a va2  s . c  o  m
                    public boolean apply(Object arg0) {
                        if (arg0 instanceof Requirement) {
                            Requirement req = (Requirement) arg0;
                            return req.getId() != null && p.matcher(req.getId()).matches();
                        }
                        return true;
                    }
                };
                return Iterators.toArray(
                        Iterators.filter(((NavigatorRoot) inputElement).getSources().iterator(), attPredicate),
                        Object.class);
            } else {
                List<RequirementSource> sources = ((NavigatorRoot) inputElement).getSources();
                return sources.toArray();
            }
        case FILTERBYPREDICATE:
            if (predicates.size() == 1) {
                IPredicate predicate = predicates.get(0);

                return Iterators
                        .toArray(Iterators.filter(((NavigatorRoot) inputElement).getSources().iterator(),
                                new PPredicate(predicate)), Object.class);
            } else {
                List<RequirementSource> sources = ((NavigatorRoot) inputElement).getSources();
                return sources.toArray();
            }
        case ORDERBYPREDICATE:
            if (predicates.size() != 0) {
                return predicates.toArray();
            } else {
                List<RequirementSource> sources = ((NavigatorRoot) inputElement).getSources();
                return sources.toArray();
            }
        case ORDERBYSCOPE:
            if (scopes.size() != 0) {
                return scopes.toArray();
            } else {
                List<RequirementSource> sources = ((NavigatorRoot) inputElement).getSources();
                return sources.toArray();
            }
        case REQONLY:
        case NONE:
        default:
            List<RequirementSource> sources = ((NavigatorRoot) inputElement).getSources();
            return sources.toArray();
        }
    }
    return null;
}

From source file:com.datastax.driver.core.ClusterAssert.java

/**
 * Asserts that given Set of {@link TokenRange}s are valid.
 * <p/>/*w w  w . j  a v a  2s.  c om*/
 * Ensures that no ranges intersect and that they cover the entire ring.
 */
private ClusterAssert hasValidTokenRanges(Set<TokenRange> ranges) {
    // Ensure no ranges intersect.
    Iterator<TokenRange> it = ranges.iterator();
    while (it.hasNext()) {
        TokenRange range = it.next();
        Assertions.assertThat(range).doesNotIntersect(Iterators.toArray(it, TokenRange.class));
    }

    // Ensure the defined ranges cover the entire ring.
    it = ranges.iterator();
    TokenRange mergedRange = it.next();
    while (it.hasNext()) {
        TokenRange next = it.next();
        mergedRange = mergedRange.mergeWith(next);
    }
    boolean isFullRing = mergedRange.getStart().equals(mergedRange.getEnd()) && !mergedRange.isEmpty();
    assertThat(isFullRing).as("Ring is not fully defined for Cluster.").isTrue();

    return this;
}

From source file:org.polarsys.reqcycle.styling.ui.providers.StylingContentProvider.java

@Override
public Object[] getChildren(final Object object) {
    Collection<AbstractElement> elements = Collections.emptyList();

    if (object instanceof RequirementSource) {
        RequirementSource requirementSource = (RequirementSource) object;
        if ((displayType.equals(RequirementViewDisplayType.FILTERBYPREDICATE)) && (predicates.size() == 1)) {
            IPredicate predicate = predicates.get(0);

            return Iterators.toArray(
                    Iterators.filter(requirementSource.getRequirements().iterator(), new PPredicate(predicate)),
                    Object.class);
        } else if (displayType.equals(RequirementViewDisplayType.FILTERBYNAME)) {
            final Pattern p = Pattern.compile(".*" + reqFilter + ".*", Pattern.DOTALL);
            final Predicate<Object> attPredicate = new Predicate<Object>() {
                @Override/*from   ww  w  .  j  a  v  a2s  . co m*/
                public boolean apply(Object arg0) {
                    if (arg0 instanceof Requirement) {
                        Requirement req = (Requirement) arg0;
                        return req.getId() != null && p.matcher(req.getId()).matches();
                    }
                    return false;
                }
            };
            return Iterators.toArray(Iterators.filter(new Source2Reqs().apply(requirementSource), attPredicate),
                    Object.class);
        } else {
            if (displayType.equals(RequirementViewDisplayType.REQONLY)) {
                return Iterators.toArray(
                        Iterators.concat(Iterators.transform(
                                Collections.singletonList(requirementSource).iterator(), new Source2Reqs())),
                        Object.class);
            } else {
                elements = requirementSource.getRequirements();
            }
        }
    } else if (object instanceof IPredicate) {
        return Iterators.toArray(Iterators.filter(
                Iterators.concat(Iterators.transform(navigatorRoot.getSources().iterator(), new Source2Reqs())),
                new PPredicate((IPredicate) object)), Object.class);
    } else if (object instanceof Section) {
        if ((displayType.equals(RequirementViewDisplayType.FILTERBYPREDICATE)) && (predicates.size() == 1)) {
            IPredicate predicate = predicates.get(0);
            return Iterators.toArray(
                    Iterators.filter(((Section) object).getChildren().iterator(), new PPredicate(predicate)),
                    Object.class);
        } else {
            elements = ((Section) object).getChildren();
        }
    } else if (object instanceof Scope) {
        return ((Scope) object).getRequirements().toArray();
    }

    if (elements.size() != 0) {
        return Iterables.toArray(elements, Object.class);
    } else {
        return null;
    }
}