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

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

Introduction

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

Prototype

public static <F, T> Iterator<T> transform(final Iterator<F> fromIterator,
        final Function<? super F, ? extends T> function) 

Source Link

Document

Returns an iterator that applies function to each element of fromIterator .

Usage

From source file:org.ow2.sirocco.cloudmanager.api.openstack.server.resources.nova.functions.ServerCreateToMachineCreate.java

@Override
public MachineCreate apply(ServerForCreate server) {
    MachineCreate machine = new MachineCreate();
    machine.setName(server.getName());//from  www .j  a v  a  2s.  c  o m
    machine.setDescription("Machine created with the Openstack/Sirocco API");

    String image = server.getImageRef();
    String flavor = server.getFlavorRef();

    MachineTemplate template = new MachineTemplate();

    if (image != null) {
        if (image.startsWith("http") && image.contains("/")) {
            image = image.substring(image.lastIndexOf('/') + 1);
        }
        try {
            template.setMachineImage(machineImageManager.getMachineImageByUuid(image));
        } catch (CloudProviderException e) {
            LOG.error("Can not find machine image");
        }
    } else {
        LOG.warn("Can not get imageRef from input create server bean");
    }

    if (flavor != null) {
        if (flavor.startsWith("http") && flavor.contains("/")) {
            flavor = flavor.substring(flavor.lastIndexOf('/') + 1);
        }

        MachineConfiguration machineConfig = null;
        try {
            template.setMachineConfig(machineManager.getMachineConfigurationByUuid(flavor));
        } catch (CloudProviderException e) {
            LOG.error("Can not find machine configuration");
        }
    } else {
        // ?
        LOG.warn("Can not get flavorRef from the input create server bean");
    }

    // openstack use the security group names where sirocco uses the UUIDs
    List groups = Lists.newArrayList(Collections2.filter(
            Lists.transform(server.getSecurityGroups(), new Function<ServerForCreate.SecurityGroup, String>() {
                @Override
                public String apply(ServerForCreate.SecurityGroup input) {
                    return new SecurityGroupNameToUUID(networkManager).apply(input.getName());
                }
            }), new Predicate<String>() {
                @Override
                public boolean apply(String input) {
                    return input != null;
                }
            }));
    template.setSecurityGroupUuids(groups);

    if (server.getKeyName() != null) {
        Credentials credentials = new GetCredentialsByName(credentialsManager).apply(server.getKeyName());
        if (credentials != null) {
            template.setCredential(credentials);
        } else {
            // should throw an exception
            LOG.warn("No credentials found for key name " + server.getKeyName());
        }
    }

    if (server.getNetworks() != null) {
        // Keep only the networks with UUID and the ones which are available in sirocco.
        // Other operations are not supported in sirocco.
        Iterator<ServerForCreate.Network> keep = Iterators.filter(server.getNetworks().iterator(),
                new Predicate<ServerForCreate.Network>() {
                    @Override
                    public boolean apply(ServerForCreate.Network input) {
                        if (input.getUuid() != null) {
                            try {
                                networkManager.getNetworkByUuid(input.getUuid());
                                return true;
                            } catch (ResourceNotFoundException e) {
                                // TODO : Throw exception since the user specified a network which is not available
                                return false;
                            }
                        } else {
                            return false;
                        }
                    }
                });

        Iterator<MachineTemplateNetworkInterface> out = Iterators.transform(keep,
                new Function<ServerForCreate.Network, MachineTemplateNetworkInterface>() {
                    @Override
                    public MachineTemplateNetworkInterface apply(ServerForCreate.Network network) {
                        MachineTemplateNetworkInterface result = new MachineTemplateNetworkInterface();
                        if (network.getUuid() != null) {
                            try {
                                result.setNetwork(networkManager.getNetworkByUuid(network.getUuid()));
                            } catch (ResourceNotFoundException e) {
                            }
                        }
                        return result;
                    }
                });
        template.setNetworkInterfaces(Lists.newArrayList(out));
    }

    if (server.getUserData() != null) {
        template.setUserData(server.getUserData());
    }

    //        template.setCredential(credentials);
    //        template.setEventLogTemplate(eventLogTemplate);
    //        template.setInitialState(state);
    //        template.setMachineConfig(config);
    //        template.setMachineImage(image);
    //        template.setNetworkInterfaces(interfaces);
    //        template.setSystemCredentialName(credentialName);
    //        template.setUserData(userData);
    //        template.setUser(user);
    //        template.setVolumes(volumes);
    //        template.setVolumeTemplates(volumeTemplates);
    //        template.setCreated(created);
    //        template.setDeleted(deleted);
    //        template.setDescription(desccription);
    //        template.setId(id);
    //        template.setIsEmbeddedInSystemTemplate(Boolean.TRUE);
    //        template.setName(name);
    //        template.setName(props);
    //        template.setProviderAssignedId(id);
    //        template.setUpdated(updated);

    machine.setMachineTemplate(template);

    if (server.getMetadata() != null && server.getMetadata().size() > 0) {
        machine.setProperties(server.getMetadata());
    }

    return machine;
}

From source file:org.apache.hadoop.hive.metastore.messaging.json.JSONMessageFactory.java

static List<Map<String, String>> getPartitionKeyValues(final Table table, Iterator<Partition> iterator) {
    return Lists.newArrayList(Iterators.transform(iterator,
            new com.google.common.base.Function<Partition, Map<String, String>>() {
                @Override//from   www . j  av  a 2  s. c o m
                public Map<String, String> apply(@Nullable Partition partition) {
                    return getPartitionKeyValues(table, partition);
                }
            }));
}

From source file:com.netxforge.netxstudio.data.ReferenceHelper.java

public static Iterator<CDOObject> transEObjectToCDOObjects(Iterator<? extends EObject> eObjects) {
    final Function<EObject, CDOObject> cdoObjectFromEObject = new Function<EObject, CDOObject>() {
        public CDOObject apply(EObject from) {
            return (CDOObject) from;
        }// w w  w.  j  a  va 2 s  .  c  o m
    };
    return Iterators.transform(eObjects, cdoObjectFromEObject);
}

From source file:org.geogit.api.plumbing.DeepMove.java

private void moveTree(final ObjectId treeId, final ObjectDatabase from, final ObjectDatabase to,
        final Set<ObjectId> metadataIds) {

    Supplier<Iterator<NodeRef>> refs = command(LsTreeOp.class).setReference(treeId.toString())
            .setStrategy(Strategy.DEPTHFIRST_ONLY_FEATURES);

    Supplier<Iterator<Node>> nodes = Suppliers.compose(new Function<Iterator<NodeRef>, Iterator<Node>>() {

        @Override//w  w  w . ja v a 2  s. co m
        public Iterator<Node> apply(Iterator<NodeRef> input) {
            return Iterators.transform(input, new Function<NodeRef, Node>() {
                @Override
                public Node apply(NodeRef input) {
                    return input.getNode();
                }
            });
        }
    }, refs);

    // move all features, recursively as given by the LsTreeOp strategy
    moveObjects(from, to, nodes, metadataIds);

    // collect all subtree and bucket ids here to delete them from the origin db
    final Set<ObjectId> alltreeIds = Sets.newTreeSet();
    Predicate<RevTree> collectIds = new Predicate<RevTree>() {
        @Override
        public boolean apply(RevTree input) {
            alltreeIds.add(input.getId());
            return true;
        }
    };

    // iterator that traverses the tree,all its subtrees, an bucket trees
    Iterator<RevTree> allSubtreesAndBuckets = new AllTrees(treeId, from);
    allSubtreesAndBuckets = Iterators.filter(allSubtreesAndBuckets, collectIds);

    to.putAll(allSubtreesAndBuckets);
    from.deleteAll(alltreeIds.iterator());
}

From source file:qdg.StaticMixedSubIdGraph.java

@Override
public Iterator<Edge> getIncidentArcIterator(Node node) {
    return Iterators.transform(new ConcatIterator<Integer>(arcLace.getOutArcIterator(((HasId) node).getId()),
            arcLace.getInArcIterator(((HasId) node).getId())), constructArc);
}

From source file:org.fcrepo.kernel.FedoraResourceImpl.java

@Override
public Collection<String> getModels() throws RepositoryException {
    if (isFrozen.apply(node)) {
        return newArrayList(
                Iterators.transform(property2values.apply(node.getProperty(FROZEN_MIXIN_TYPES)), value2string));
    }/* w  w  w  .  j  a v a 2s  .  c o  m*/
    return map(node.getMixinNodeTypes(), nodetype2name);
}

From source file:org.fcrepo.kernel.modeshape.rdf.impl.LdpContainerRdfContext.java

/**
 * Get the member relations assert on the subject by the given node
 * @param container/*  www . j  a  va  2 s.  co m*/
 * @return
 * @throws RepositoryException
 */
private Iterator<Triple> memberRelations(final FedoraResource container) throws RepositoryException {
    final com.hp.hpl.jena.graph.Node memberRelation;

    if (container.hasProperty(LDP_HAS_MEMBER_RELATION)) {
        final Property property = container.getProperty(LDP_HAS_MEMBER_RELATION);
        memberRelation = createURI(property.getString());
    } else if (container.hasType(LDP_BASIC_CONTAINER)) {
        memberRelation = LDP_MEMBER.asNode();
    } else {
        return emptyIterator();
    }

    final String insertedContainerProperty;

    if (container.hasType(LDP_INDIRECT_CONTAINER)) {
        if (container.hasProperty(LDP_INSERTED_CONTENT_RELATION)) {
            insertedContainerProperty = container.getProperty(LDP_INSERTED_CONTENT_RELATION).getString();
        } else {
            return emptyIterator();
        }
    } else {
        insertedContainerProperty = MEMBER_SUBJECT.getURI();
    }

    return flatMap(container.getChildren(),
            UncheckedFunction.<FedoraResource, Iterator<Triple>>uncheck(child -> {
                final com.hp.hpl.jena.graph.Node childSubject = child instanceof NonRdfSourceDescription
                        ? uriFor(((NonRdfSourceDescription) child).getDescribedResource())
                        : uriFor(child);

                if (insertedContainerProperty.equals(MEMBER_SUBJECT.getURI())) {
                    return singletonIterator(create(subject(), memberRelation, childSubject));
                }
                String insertedContentProperty = getPropertyNameFromPredicate(resource().getNode(),
                        createResource(insertedContainerProperty), null);

                if (child.hasProperty(insertedContentProperty)) {
                    // do nothing, insertedContentProperty is good

                } else if (child.hasProperty(getReferencePropertyName(insertedContentProperty))) {
                    // The insertedContentProperty is a pseudo reference property
                    insertedContentProperty = getReferencePropertyName(insertedContentProperty);

                } else {
                    // No property found!
                    return emptyIterator();
                }

                final PropertyValueIterator values = new PropertyValueIterator(
                        child.getProperty(insertedContentProperty));

                return Iterators.transform(values, v -> create(subject(), memberRelation,
                        new ValueConverter(session(), translator()).convert(v).asNode()));

            }));
}

From source file:qdg.view.MixedGraphAsBiDiGraph.java

@Override
public Iterator<Edge> getIncidentArcIterator(Node node) {
    Iterator<Edge> forwardArcs = Iterators.transform(g.getIncidentArcIterator(node), forwardEdge);
    Iterator<Edge> backwardArcs = Iterators.transform(g.getIncidentArcIterator(node), backwardEdge);
    Iterator<Edge> forwardUEdges = Iterators.transform(g.getIncidentEdgeIterator(node), forwardEdge);
    Iterator<Edge> backwardUEdges = Iterators.transform(g.getIncidentUEdgeIterator(node), backwardEdge);
    return Iterators.concat(forwardArcs, backwardArcs, forwardUEdges, backwardUEdges);
}

From source file:org.polymap.core.model2.store.feature.FeatureStoreUnitOfWork.java

@Override
public <T extends Entity> Collection find(Class<T> entityClass) {
    try {/*  ww w  .  j  av a 2s.  co  m*/
        // schema
        FeatureStore fs = featureSource(entityClass);
        FeatureType schema = fs.getSchema();

        // features (just IDs) 
        final FeatureCollection features = fs.getFeatures(
                new DefaultQuery(schema.getName().getLocalPart(), Filter.INCLUDE, new String[] {}));
        final Iterator<Feature> it = features.iterator();

        return new AbstractCollection<String>() {

            private LazyInit<Integer> size = new PlainLazyInit();

            public Iterator<String> iterator() {
                return Iterators.transform(it, new Function<Feature, String>() {
                    public String apply(Feature input) {
                        return input.getIdentifier().getID();
                    }
                });
            }

            public int size() {
                return size.get(new Supplier<Integer>() {
                    public Integer get() {
                        return features.size();
                    }
                });
            }

            public boolean isEmpty() {
                return size() == 0; //features.isEmpty();
            }

            protected void finalize() throws Throwable {
                if (it != null) {
                    features.close(it);
                }
            }
        };
    } catch (IOException e) {
        throw new ModelRuntimeException(e);
    }
}

From source file:org.geogit.geotools.plumbing.ImportOp.java

/**
 * Executes the import operation using the parameters that have been specified. Features will be
 * added to the working tree, and a new working tree will be constructed. Either {@code all} or
 * {@code table}, but not both, must be set prior to the import process.
 * /*from w  ww  .j  a  v  a 2s  .c o  m*/
 * @return RevTree the new working tree
 */
@SuppressWarnings("deprecation")
@Override
public RevTree call() {
    if (dataStore == null) {
        throw new GeoToolsOpException(StatusCode.DATASTORE_NOT_DEFINED);
    }

    if ((table == null || table.isEmpty()) && !(all)) {
        throw new GeoToolsOpException(StatusCode.TABLE_NOT_DEFINED);
    }

    if (table != null && !table.isEmpty() && all) {
        throw new GeoToolsOpException(StatusCode.ALL_AND_TABLE_DEFINED);
    }

    boolean foundTable = false;

    List<Name> typeNames;
    try {
        typeNames = dataStore.getNames();
    } catch (Exception e) {
        throw new GeoToolsOpException(StatusCode.UNABLE_TO_GET_NAMES);
    }

    if (typeNames.size() > 1 && alter && all) {
        throw new GeoToolsOpException(StatusCode.ALTER_AND_ALL_DEFINED);
    }

    if (alter) {
        overwrite = false;
    }

    getProgressListener().started();
    int tableCount = 0;
    if (destPath != null && !destPath.isEmpty()) {
        if (typeNames.size() > 1 && all) {
            if (overwrite) {
                // we delete the previous tree to honor the overwrite setting, but then turn it
                // to false. Otherwise, each table imported will overwrite the previous ones and
                // only the last one will be imported.
                try {
                    this.getWorkTree().delete(new NameImpl(destPath));
                } catch (Exception e) {
                    throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_INSERT);
                }
                overwrite = false;
            }

        }
    }

    for (Name typeName : typeNames) {
        tableCount++;
        if (!all && !table.equals(typeName.toString()))
            continue;

        foundTable = true;

        String tableName = String.format("%-16s", typeName.getLocalPart());
        if (typeName.getLocalPart().length() > 16) {
            tableName = tableName.substring(0, 13) + "...";
        }
        getProgressListener().setDescription("Importing " + tableName + " (" + (all ? tableCount : 1) + "/"
                + (all ? typeNames.size() : 1) + ")... ");

        SimpleFeatureSource featureSource;
        SimpleFeatureCollection features;
        try {
            featureSource = dataStore.getFeatureSource(typeName);
            features = featureSource.getFeatures();
        } catch (Exception e) {
            throw new GeoToolsOpException(StatusCode.UNABLE_TO_GET_FEATURES);
        }

        final RevFeatureType featureType = RevFeatureType.build(featureSource.getSchema());

        String path;
        if (destPath == null || destPath.isEmpty()) {
            path = featureType.getName().getLocalPart();
        } else {
            path = destPath;
        }

        NodeRef.checkValidPath(path);

        ProgressListener taskProgress = subProgress(100.f / (all ? typeNames.size() : 1f));

        String refspec = Ref.WORK_HEAD + ":" + path;

        if (overwrite) {
            try {
                this.getWorkTree().delete(new NameImpl(path));
            } catch (Exception e) {
                throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_INSERT);
            }
        }

        final SimpleFeatureIterator featureIterator = features.features();
        Iterator<Feature> iterator = new AbstractIterator<Feature>() {
            @Override
            protected Feature computeNext() {
                if (!featureIterator.hasNext()) {
                    return super.endOfData();
                }
                return featureIterator.next();
            }
        };
        final String fidPrefix = featureType.getName().getLocalPart() + ".";
        iterator = Iterators.transform(iterator, new FidReplacer(fidPrefix));

        Integer collectionSize = features.size();
        if (!alter) {
            try {
                if (iterator.hasNext()) {
                    getWorkTree().insert(path, iterator, taskProgress, null, collectionSize);
                } else {
                    // No features
                    if (overwrite) {
                        getWorkTree().createTypeTree(path, featureType.type());
                    }
                }
            } catch (Exception e) {
                throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_INSERT);
            } finally {
                featureIterator.close();
            }
        } else {
            // first we modify the feature type and the existing features, if needed
            this.getWorkTree().updateTypeTree(path, featureType.type());

            Iterator<NodeRef> oldFeatures = command(LsTreeOp.class).setReference(refspec)
                    .setStrategy(Strategy.FEATURES_ONLY).call();
            Iterator<Feature> transformedIterator = transformIterator(oldFeatures, featureType);
            try {
                Integer size = features.size();
                getWorkTree().insert(path, transformedIterator, taskProgress, null, size);
            } catch (Exception e) {
                throw new GeoToolsOpException(StatusCode.UNABLE_TO_INSERT);
            }
            // then we add the new ones
            getWorkTree().insert(path, iterator, taskProgress, null, collectionSize);
        }

    }
    if (!foundTable) {
        if (all) {
            throw new GeoToolsOpException(StatusCode.NO_FEATURES_FOUND);
        } else {
            throw new GeoToolsOpException(StatusCode.TABLE_NOT_FOUND);
        }
    }
    getProgressListener().progress(100.f);
    getProgressListener().complete();
    return getWorkTree().getTree();
}