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

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

Introduction

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

Prototype

public static <T> boolean addAll(Collection<T> addTo, Iterator<? extends T> iterator) 

Source Link

Document

Adds all elements in iterator to collection .

Usage

From source file:org.obeonetwork.dsl.uml2.design.services.ActivityServices.java

/**
 * Get all the behaviors available in the semantic resources.
 * /*  www  . ja v  a2 s .co m*/
 * @param eObj
 *            Semantic element
 * @return All the behaviors
 */
public List<EObject> getAllBehaviors(Element element) {
    List<EObject> behaviors = Lists.newArrayList();
    UMLServices umlServices = new UMLServices();
    List<org.eclipse.uml2.uml.Package> rootPkgs = umlServices.getAllAvailableRootPackages(element);
    for (org.eclipse.uml2.uml.Package pkg : rootPkgs) {
        Iterators.addAll(behaviors,
                Iterators.filter(pkg.eAllContents(), Predicates.instanceOf(Behavior.class)));
    }

    return behaviors;
}

From source file:com.google.devtools.common.options.OptionsParserImpl.java

/**
 * Parses the args, and returns what it doesn't parse. May be called multiple
 * times, and may be called recursively. Calls may contain intersecting sets
 * of options; in that case, the arg seen last takes precedence.
 *
 * <p>The method uses the invariant that if an option has neither an implicit
 * dependent nor an expanded from value, then it must have been explicitly
 * set.//from   w w w  . j  a va  2s  . c  o  m
 */
private List<String> parse(OptionPriority priority, Function<? super String, String> sourceFunction,
        String implicitDependent, String expandedFrom, List<String> args) throws OptionsParsingException {

    List<String> unparsedArgs = Lists.newArrayList();
    LinkedHashMap<String, List<String>> implicitRequirements = Maps.newLinkedHashMap();

    Iterator<String> argsIterator = args.iterator();
    while (argsIterator.hasNext()) {
        String arg = argsIterator.next();

        if (!arg.startsWith("-")) {
            unparsedArgs.add(arg);
            continue; // not an option arg
        }

        if (arg.equals("--")) { // "--" means all remaining args aren't options
            Iterators.addAll(unparsedArgs, argsIterator);
            break;
        }

        ParseOptionResult optionParseResult = parseOption(arg, argsIterator);
        Field field = optionParseResult.field;
        Option option = optionParseResult.option;
        String value = optionParseResult.value;

        final String originalName = option.name();

        if (option.wrapperOption()) {
            if (value.startsWith("-")) {

                List<String> unparsed = parse(priority,
                        Functions.constant("Unwrapped from wrapper option --" + originalName), null, // implicitDependent
                        null, // expandedFrom
                        ImmutableList.of(value));

                if (!unparsed.isEmpty()) {
                    throw new OptionsParsingException("Unparsed options remain after unwrapping " + arg + ": "
                            + Joiner.on(' ').join(unparsed));
                }

                // Don't process implicitRequirements or expansions for wrapper options. In particular,
                // don't record this option in unparsedValues, so that only the wrapped option shows
                // up in canonicalized options.
                continue;

            } else {
                throw new OptionsParsingException("Invalid --" + originalName + " value format. "
                        + "You may have meant --" + originalName + "=--" + value);
            }
        }

        if (implicitDependent == null) {
            // Log explicit options and expanded options in the order they are parsed (can be sorted
            // later). Also remember whether they were expanded or not. This information is needed to
            // correctly canonicalize flags.
            UnparsedOptionValueDescription unparsedOptionValueDescription = new UnparsedOptionValueDescription(
                    originalName, field, value, priority, sourceFunction.apply(originalName),
                    expandedFrom == null);
            unparsedValues.add(unparsedOptionValueDescription);
            if (option.allowMultiple()) {
                canonicalizeValues.put(field, unparsedOptionValueDescription);
            } else {
                canonicalizeValues.replaceValues(field, ImmutableList.of(unparsedOptionValueDescription));
            }
        }

        // Handle expansion options.
        if (option.expansion().length > 0) {
            Function<Object, String> expansionSourceFunction = Functions.<String>constant(
                    "expanded from option --" + originalName + " from " + sourceFunction.apply(originalName));
            maybeAddDeprecationWarning(field);
            List<String> unparsed = parse(priority, expansionSourceFunction, null, originalName,
                    ImmutableList.copyOf(option.expansion()));
            if (!unparsed.isEmpty()) {
                // Throw an assertion, because this indicates an error in the code that specified the
                // expansion for the current option.
                throw new AssertionError("Unparsed options remain after parsing expansion of " + arg + ": "
                        + Joiner.on(' ').join(unparsed));
            }
        } else {
            Converter<?> converter = optionsData.getConverter(field);
            Object convertedValue;
            try {
                convertedValue = converter.convert(value);
            } catch (OptionsParsingException e) {
                // The converter doesn't know the option name, so we supply it here by
                // re-throwing:
                throw new OptionsParsingException("While parsing option " + arg + ": " + e.getMessage(), e);
            }

            // ...but allow duplicates of single-use options across separate calls to
            // parse(); latest wins:
            if (!option.allowMultiple()) {
                setValue(field, originalName, convertedValue, priority, sourceFunction.apply(originalName),
                        implicitDependent, expandedFrom);
            } else {
                // But if it's a multiple-use option, then just accumulate the
                // values, in the order in which they were seen.
                // Note: The type of the list member is not known; Java introspection
                // only makes it available in String form via the signature string
                // for the field declaration.
                addListValue(field, convertedValue, priority, sourceFunction.apply(originalName),
                        implicitDependent, expandedFrom);
            }
        }

        // Collect any implicit requirements.
        if (option.implicitRequirements().length > 0) {
            implicitRequirements.put(option.name(), Arrays.asList(option.implicitRequirements()));
        }
    }

    // Now parse any implicit requirements that were collected.
    // TODO(bazel-team): this should happen when the option is encountered.
    if (!implicitRequirements.isEmpty()) {
        for (Map.Entry<String, List<String>> entry : implicitRequirements.entrySet()) {
            Function<Object, String> requirementSourceFunction = Functions
                    .<String>constant("implicit requirement of option --" + entry.getKey() + " from "
                            + sourceFunction.apply(entry.getKey()));

            List<String> unparsed = parse(priority, requirementSourceFunction, entry.getKey(), null,
                    entry.getValue());
            if (!unparsed.isEmpty()) {
                // Throw an assertion, because this indicates an error in the code that specified in the
                // implicit requirements for the option(s).
                throw new AssertionError("Unparsed options remain after parsing implicit options: "
                        + Joiner.on(' ').join(unparsed));
            }
        }
    }

    return unparsedArgs;
}

From source file:org.movsim.simulator.roadnetwork.RoadSegment.java

/**
 * Returns the instantaneous travel time estimated on small sections within a {@code RoadSegment} with assuming the allowed freeflow
 * speed in case of no vehicle./*from  w w  w.jav a  2 s.c o  m*/
 * 
 * @return grid-based instantaneous travel time with adhoc assumed travel time if road is empty
 */
public double instantaneousTravelTimeOnGrid(double gridLength) {
    Preconditions.checkArgument(gridLength > 0, "gridLength must be > 0");
    double totalTravelTime = 0;
    double startPos = 0;
    // TODO hack here, depends on order of vehicles
    LinkedList<Vehicle> vehicles = Lists.newLinkedList();
    Iterators.addAll(vehicles, iterator());
    while (startPos < roadLength) {
        double endPos = Math.min(startPos + gridLength, roadLength);
        double maxRoadSpeed = freeFlowSpeed; // FIXME consider speedlimits
        totalTravelTime += travelTimeInRange(startPos, endPos, maxRoadSpeed, vehicles);
        startPos += gridLength;
    }
    return totalTravelTime;
}

From source file:org.apache.cassandra.db.LegacyLayout.java

public static UnfilteredRowIterator onWireCellstoUnfilteredRowIterator(CFMetaData metadata, DecoratedKey key,
        LegacyDeletionInfo delInfo, Iterator<LegacyCell> cells, boolean reversed, SerializationHelper helper) {

    // If the table is a static compact, the "column_metadata" are now internally encoded as
    // static. This has already been recognized by decodeCellName, but it means the cells
    // provided are not in the expected order (the "static" cells are not necessarily at the front).
    // So sort them to make sure toUnfilteredRowIterator works as expected.
    // Further, if the query is reversed, then the on-wire format still has cells in non-reversed
    // order, but we need to have them reverse in the final UnfilteredRowIterator. So reverse them.
    if (metadata.isStaticCompactTable() || reversed) {
        List<LegacyCell> l = new ArrayList<>();
        Iterators.addAll(l, cells);
        Collections.sort(l, legacyCellComparator(metadata, reversed));
        cells = l.iterator();//from   w  w  w . java 2 s .  c  o m
    }

    return toUnfilteredRowIterator(metadata, key, delInfo, cells, reversed, helper);
}

From source file:org.obeonetwork.dsl.uml2.design.services.ActivityServices.java

/**
 * Get all the signals available in the semantic resources.
 * //www .  ja  v a  2 s  .  c  o m
 * @param eObj
 *            Semantic element
 * @return All the signals
 */
public List<EObject> getAllSignals(Element element) {
    List<EObject> signals = Lists.newArrayList();
    UMLServices umlServices = new UMLServices();
    List<org.eclipse.uml2.uml.Package> rootPkgs = umlServices.getAllAvailableRootPackages(element);
    for (org.eclipse.uml2.uml.Package pkg : rootPkgs) {
        Iterators.addAll(signals, Iterators.filter(pkg.eAllContents(), Predicates.instanceOf(Signal.class)));
    }

    return signals;
}

From source file:org.obeonetwork.dsl.sysml.design.services.SysMLServices.java

/**
 * Get all valid elements in session.//from w  w  w .jav  a2  s.  c  o m
 * 
 * @param cur
 *            Current element
 * @param validForDiagram
 *            Predicate
 * @return List of valid elements
 */
private List<EObject> allValidSessionElements(EObject cur, Predicate<EObject> validForDiagram) {
    Session found = SessionManager.INSTANCE.getSession(cur);
    List<EObject> result = Lists.newArrayList();
    if (found != null) {
        for (Resource res : found.getSemanticResources()) {
            Iterators.addAll(result, Iterators.filter(res.getAllContents(), validForDiagram));
        }
    }
    return result;
}

From source file:org.obeonetwork.dsl.sysml.design.services.SysMLServices.java

/**
 * Get all valid attributes of a class.//w  w  w .  j a  v a  2  s .c om
 * 
 * @param cur
 *            Current element
 * @param validForDiagram
 *            Predicate
 * @return List of valid elements
 */
private List<EObject> allValidAttributes(Class cur, Predicate<EObject> validForDiagram) {
    List<EObject> result = Lists.newArrayList();
    Iterators.addAll(result, Iterators.filter(cur.getAttributes().iterator(), validForDiagram));
    return result;
}

From source file:de.tum.in.bluetooth.discovery.BluetoothDeviceDiscovery.java

/** Used to get all the configurations for the remote bluetooth devices */
private void loadAutoPairingConfiguration(final String deviceList) {
    if (deviceList == null) {
        this.m_fleet = null;
        LOGGER.warn("No device configuration found, ignoring auto-pairing and device filter");
    } else {/*from ww  w .  j a  va 2s. co  m*/
        final List<String> devices = Lists.newArrayList();
        Device device = null;
        this.m_fleet = new DeviceList();

        final String DEVICE_SPLITTER = "#";
        Iterators.addAll(devices, Splitter.on(DEVICE_SPLITTER).split(deviceList).iterator());
        for (final String deviceStr : devices) {
            final String SEPARATOR = ";";
            final String NEW_LINE = "\n";

            final Splitter splitter = Splitter.on(SEPARATOR).omitEmptyStrings().trimResults();
            final Joiner stringDevicesJoiner = Joiner.on(NEW_LINE).skipNulls();

            final Properties properties = new Properties();

            final String deviceAsPropertiesFormat = stringDevicesJoiner.join(splitter.splitToList(deviceStr));

            if (isNullOrEmpty(deviceAsPropertiesFormat.toString())) {
                LOGGER.error("No Bluetooth Enabled Device Addess Found");
            }

            try {
                properties.load(new StringReader(deviceAsPropertiesFormat));
            } catch (final IOException e) {
                LOGGER.error("Error while parsing list of input bluetooth devices");
            }

            device = new Device();
            device.setId(properties.getProperty("id"));
            device.setUsername(properties.getProperty("username"));
            device.setPassword(properties.getProperty("password"));
            device.setPin(properties.getProperty("pin"));
            device.setRetry(Boolean.valueOf(properties.getProperty("retry")));
            device.setMaxRetry(new BigInteger(properties.getProperty("max-retry")));
            this.m_fleet.getDevices().add(device);
        }
    }
}

From source file:eu.numberfour.n4js.validation.validators.N4JSMemberRedefinitionValidator.java

/**
 * Constraints 41 (Abstract Class)//  w  w w.j a va 2  s. c  o m
 */
private boolean constraints_41_AbstractClass(TClassifier classifier, MemberCube memberCube) {
    List<TMember> abstractMembers = null;
    if (!classifier.isAbstract() && classifier instanceof TClass) {
        for (Entry<NameStaticPair, MemberMatrix> entry : memberCube.entrySet()) {
            MemberMatrix mm = entry.getValue();
            MemberList<TMember> l = new MemberList<>();
            Iterators.addAll(l, mm.actuallyInheritedAndMixedMembers());
            for (SourceAwareIterator iter = mm.actuallyInheritedAndMixedMembers(); iter.hasNext();) {
                TMember m = iter.next();
                if (m.isAbstract()) {
                    if (abstractMembers == null) {
                        abstractMembers = new ArrayList<>();
                    }
                    abstractMembers.add(m);
                }
            }
        }
    }
    if (abstractMembers != null) {
        messageMissingImplementations(abstractMembers);
        return false;
    }
    return true;
}

From source file:org.obeonetwork.dsl.uml2.design.services.UMLServices.java

/**
 * Get all the packageable elements available in the semantic resources.
 * /*from  www  .ja  v  a  2 s.  c om*/
 * @param eObj
 *            Semantic element
 * @return All the packageable elements
 */
public List<EObject> getAllPackageableElements(Element element) {
    List<EObject> result = Lists.newArrayList();
    UMLServices umlServices = new UMLServices();
    List<org.eclipse.uml2.uml.Package> rootPkgs = umlServices.getAllAvailableRootPackages(element);
    result.addAll(rootPkgs);
    for (org.eclipse.uml2.uml.Package pkg : rootPkgs) {
        Iterators.addAll(result,
                Iterators.filter(pkg.eAllContents(), Predicates.instanceOf(PackageableElement.class)));
    }
    if (element instanceof Package) {
        result.removeAll(((Package) element).getPackagedElements());
    }

    return result;
}