Search in sources :

Example 36 with AbstractIterator

use of com.google.common.collect.AbstractIterator in project Wurst-MC-1.12 by Wurst-Imperium.

the class BlockUtils method getValidBlocksByDistance.

public static Iterable<BlockPos> getValidBlocksByDistance(double range, boolean ignoreVisibility, BlockValidator validator) {
    // prepare range check
    Vec3d eyesPos = RotationUtils.getEyesPos().subtract(0.5, 0.5, 0.5);
    double rangeSq = Math.pow(range + 0.5, 2);
    // set start pos
    BlockPos startPos = new BlockPos(RotationUtils.getEyesPos());
    return () -> new AbstractIterator<BlockPos>() {

        // initialize queue
        private ArrayDeque<BlockPos> queue = new ArrayDeque<>(Arrays.asList(startPos));

        private HashSet<BlockPos> visited = new HashSet<>();

        @Override
        protected BlockPos computeNext() {
            // find block using breadth first search
            while (!queue.isEmpty()) {
                BlockPos current = queue.pop();
                // check range
                if (eyesPos.squareDistanceTo(new Vec3d(current)) > rangeSq)
                    continue;
                boolean canBeClicked = WBlock.canBeClicked(current);
                if (ignoreVisibility || !canBeClicked)
                    // add neighbors
                    for (EnumFacing facing : EnumFacing.values()) {
                        BlockPos next = current.offset(facing);
                        if (visited.contains(next))
                            continue;
                        queue.add(next);
                        visited.add(next);
                    }
                // check if block is valid
                if (canBeClicked && validator.isValid(current))
                    return current;
            }
            return endOfData();
        }
    };
}
Also used : EnumFacing(net.minecraft.util.EnumFacing) BlockPos(net.minecraft.util.math.BlockPos) AbstractIterator(com.google.common.collect.AbstractIterator) Vec3d(net.minecraft.util.math.Vec3d) ArrayDeque(java.util.ArrayDeque) HashSet(java.util.HashSet)

Example 37 with AbstractIterator

use of com.google.common.collect.AbstractIterator in project cdap by caskdata.

the class FactScanner method createIterator.

private Iterator<FactScanResult> createIterator() {
    return new AbstractIterator<FactScanResult>() {

        @Override
        protected FactScanResult computeNext() {
            Row rowResult;
            while ((rowResult = scanner.next()) != null) {
                rowScanned++;
                byte[] rowKey = rowResult.getRow();
                // Decode context and metric from key
                String measureName = codec.getMeasureName(rowKey);
                // if measureNames is empty we include all metrics
                if (!measureNames.isEmpty() && !measureNames.contains(measureName)) {
                    continue;
                }
                // todo: codec.getDimensionValues(rowKey) needs to un-encode dimension names which may result in read in
                // entity table (depending on the cache and its state). To avoid that, we can pass to scanner the
                // list of dimension names as we *always* know it (it is given) at the time of scanning
                List<DimensionValue> dimensionValues = codec.getDimensionValues(rowKey);
                boolean exhausted = false;
                List<TimeValue> timeValues = Lists.newLinkedList();
                // todo: entry set is ordered by ts?
                for (Map.Entry<byte[], byte[]> columnValue : rowResult.getColumns().entrySet()) {
                    long ts = codec.getTimestamp(rowKey, columnValue.getKey());
                    if (ts < startTs) {
                        continue;
                    }
                    if (ts > endTs) {
                        exhausted = true;
                        break;
                    }
                    // todo: move Bytes.toLong into codec?
                    TimeValue timeValue = new TimeValue(ts, Bytes.toLong(columnValue.getValue()));
                    timeValues.add(timeValue);
                }
                if (timeValues.isEmpty() && exhausted) {
                    break;
                }
                // todo: can return empty list, if all data is < startTs or > endTs
                return new FactScanResult(measureName, dimensionValues, timeValues);
            }
            scanner.close();
            return endOfData();
        }
    };
}
Also used : DimensionValue(co.cask.cdap.api.dataset.lib.cube.DimensionValue) AbstractIterator(com.google.common.collect.AbstractIterator) Row(co.cask.cdap.api.dataset.table.Row) Map(java.util.Map) TimeValue(co.cask.cdap.api.dataset.lib.cube.TimeValue)

Example 38 with AbstractIterator

use of com.google.common.collect.AbstractIterator in project cdap by caskdata.

the class ArtifactInspector method getPluginClasses.

/**
 * Returns an {@link Iterable} of class name that are under the given list of package names that are loadable
 * through the plugin ClassLoader.
 */
private Iterable<Class<?>> getPluginClasses(final Iterable<String> packages, final ClassLoader pluginClassLoader) {
    return new Iterable<Class<?>>() {

        @Override
        public Iterator<Class<?>> iterator() {
            final Iterator<String> packageIterator = packages.iterator();
            return new AbstractIterator<Class<?>>() {

                Iterator<String> classIterator = ImmutableList.<String>of().iterator();

                String currentPackage;

                @Override
                protected Class<?> computeNext() {
                    while (!classIterator.hasNext()) {
                        if (!packageIterator.hasNext()) {
                            return endOfData();
                        }
                        currentPackage = packageIterator.next();
                        try {
                            // Gets all package resource URL for the given package
                            String resourceName = currentPackage.replace('.', File.separatorChar);
                            Enumeration<URL> resources = pluginClassLoader.getResources(resourceName);
                            List<Iterator<String>> iterators = new ArrayList<>();
                            // Go though all available resources and collect all class names that are plugin classes.
                            while (resources.hasMoreElements()) {
                                URL packageResource = resources.nextElement();
                                // There should be exactly one of resource that match, because it maps to a directory on the FS.
                                if (packageResource.getProtocol().equals("file")) {
                                    Iterator<String> classFiles = DirUtils.list(new File(packageResource.toURI()), "class").iterator();
                                    // Transform class file into class name and filter by @Plugin class only
                                    iterators.add(Iterators.filter(Iterators.transform(classFiles, new Function<String, String>() {

                                        @Override
                                        public String apply(String input) {
                                            return getClassName(currentPackage, input);
                                        }
                                    }), new Predicate<String>() {

                                        @Override
                                        public boolean apply(String className) {
                                            return isPlugin(className, pluginClassLoader);
                                        }
                                    }));
                                }
                            }
                            if (!iterators.isEmpty()) {
                                classIterator = Iterators.concat(iterators.iterator());
                            }
                        } catch (Exception e) {
                            // Cannot happen
                            throw Throwables.propagate(e);
                        }
                    }
                    try {
                        return pluginClassLoader.loadClass(classIterator.next());
                    } catch (ClassNotFoundException | NoClassDefFoundError e) {
                        // Cannot happen, since the class name is from the list of the class files under the classloader.
                        throw Throwables.propagate(e);
                    }
                }
            };
        }
    };
}
Also used : ArrayList(java.util.ArrayList) URL(java.net.URL) ZipException(java.util.zip.ZipException) EOFException(java.io.EOFException) UnsupportedTypeException(co.cask.cdap.api.data.schema.UnsupportedTypeException) IOException(java.io.IOException) InvalidArtifactException(co.cask.cdap.common.InvalidArtifactException) Predicate(com.google.common.base.Predicate) Iterator(java.util.Iterator) AbstractIterator(com.google.common.collect.AbstractIterator) PluginClass(co.cask.cdap.api.plugin.PluginClass) ApplicationClass(co.cask.cdap.api.artifact.ApplicationClass) AbstractIterator(com.google.common.collect.AbstractIterator) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 39 with AbstractIterator

use of com.google.common.collect.AbstractIterator in project n4js by eclipse.

the class InternalN4JSWorkspace method getArchiveIterator.

/**
 * Iterates all entries in the given archive data that are nested under the relative location.
 *
 * @param archive
 *            the input stream with the zip entries. Will not be closed by this method, but has to be closed by the
 *            caller.
 */
protected Iterator<ZipEntry> getArchiveIterator(final ZipInputStream archive, String archiveRelativeLocation) {
    final String relativeLocation = archiveRelativeLocation + '/';
    final Iterator<ZipEntry> iterator = new AbstractIterator<ZipEntry>() {

        @Override
        protected ZipEntry computeNext() {
            try {
                ZipEntry candidate = archive.getNextEntry();
                while (candidate != null) {
                    if (!candidate.isDirectory()) {
                        String name = candidate.getName();
                        if (name.startsWith(relativeLocation)) {
                            return candidate;
                        }
                    }
                    candidate = archive.getNextEntry();
                }
            } catch (IOException e) {
            // ignore
            }
            return endOfData();
        }
    };
    return ImmutableList.copyOf(iterator).iterator();
}
Also used : ZipEntry(java.util.zip.ZipEntry) AbstractIterator(com.google.common.collect.AbstractIterator) IOException(java.io.IOException)

Example 40 with AbstractIterator

use of com.google.common.collect.AbstractIterator in project n4js by eclipse.

the class N4JSUnloader method getAllProperContents.

/**
 * Traverse the contents of the object that is contained in the {@link ObjectToFragment}. The string builder is used
 * as an accumulating parameter. That is, during the traversal it will be used and trimmed again. This allows to
 * reuse the underlying char array which is already copied when the fragment is turned into a string.
 *
 * The fragments use the very same notation as described in
 * {@link InternalEObject#eURIFragmentSegment(EStructuralFeature, EObject)}.
 *
 * The implementation from {@link ResourceImpl} uses a {@link SegmentSequence} rather than a {@link StringBuilder}.
 * Since we have to concatenate the string in the end anyway.
 */
private static Iterator<ObjectToFragment> getAllProperContents(ObjectToFragment eObject, final StringBuilder result) {
    // we inherit from the AbstractTreeIterator which will help us getting a proper pre-order traversal
    return new AbstractTreeIterator<ObjectToFragment>(eObject, false) {

        /* don't resolve containment proxies */
        @Override
        public Iterator<ObjectToFragment> getChildren(Object parent) {
            final EObject current = ((ObjectToFragment) parent).object;
            final EStructuralFeature[] containments = containmentFeatures(current);
            if (containments == null || containments.length == 0) {
                // no containment features found, exit
                return Iterators.emptyIterator();
            }
            // we have at least one containment feature - append the fragment delimiter '/'
            result.append('/');
            // and concatenate all the iterators for the children
            return Iterators.concat(getFeatureIterators(current, containments));
        }

        /**
         * Returns an iterator of iterators. Each nested iterator covers a single containment feature. If the
         * feature is multi valued, the nested iterator has as many values as are set on the feature.
         */
        private Iterator<Iterator<ObjectToFragment>> getFeatureIterators(EObject current, EStructuralFeature[] containments) {
            return new AbstractIterator<Iterator<ObjectToFragment>>() {

                /**
                 * The length of the string builder before something was added by this traversing iterator.
                 */
                private final int prevLength = result.length();

                private int featureIdx = 0;

                @Override
                protected Iterator<ObjectToFragment> computeNext() {
                    while (featureIdx < containments.length) {
                        EStructuralFeature containment = containments[featureIdx];
                        featureIdx++;
                        // only consider features that have values
                        if (current.eIsSet(containment)) {
                            // reset the string builder
                            result.setLength(prevLength);
                            // append the @ sign and the feature name
                            // '@<feature-name>'
                            result.append('@').append(containment.getName());
                            // compute the contained values
                            return newValueIterator(containment);
                        }
                    }
                    return endOfData();
                }

                /**
                 * Returns an iterator for the values that are assigned to the given containment feature.
                 */
                private Iterator<ObjectToFragment> newValueIterator(EStructuralFeature feature) {
                    if (feature.isMany()) {
                        // add the dot as the delimiter between feature name and index in the list
                        result.append('.');
                        // compute the value indexes
                        return newManyValueIterator((List<?>) current.eGet(feature));
                    } else {
                        // no dot is added for single valued features
                        return newSingleValueIterator((EObject) current.eGet(feature));
                    }
                }

                /**
                 * Finalize the fragment for the given instance and return a singleton iterator for it.
                 */
                private Iterator<ObjectToFragment> newSingleValueIterator(EObject value) {
                    ObjectToFragment objectToFragment = new ObjectToFragment(value, result.toString());
                    return Iterators.singletonIterator(objectToFragment);
                }

                /**
                 * Traverse the list of values and return the feature indexes along with the values.
                 */
                private AbstractIterator<ObjectToFragment> newManyValueIterator(final List<?> values) {
                    return new AbstractIterator<ObjectToFragment>() {

                        /**
                         * The length of the string builder before something was added by this traversing iterator.
                         */
                        private final int prevLengthBeforeIdx = result.length();

                        /**
                         * The index in the value list.
                         */
                        private int valueIdx = 0;

                        @Override
                        protected ObjectToFragment computeNext() {
                            if (valueIdx < values.size()) {
                                EObject value = (EObject) values.get(valueIdx);
                                result.setLength(prevLengthBeforeIdx);
                                result.append(valueIdx);
                                valueIdx++;
                                return new ObjectToFragment(value, result.toString());
                            }
                            return endOfData();
                        }
                    };
                }
            };
        }

        private EStructuralFeature[] containmentFeatures(final EObject current) {
            return ((EClassImpl.FeatureSubsetSupplier) current.eClass().getEAllStructuralFeatures()).containments();
        }
    };
}
Also used : AbstractTreeIterator(org.eclipse.emf.common.util.AbstractTreeIterator) EObject(org.eclipse.emf.ecore.EObject) InternalEObject(org.eclipse.emf.ecore.InternalEObject) EStructuralFeature(org.eclipse.emf.ecore.EStructuralFeature) Iterator(java.util.Iterator) AbstractTreeIterator(org.eclipse.emf.common.util.AbstractTreeIterator) AbstractIterator(com.google.common.collect.AbstractIterator) EObject(org.eclipse.emf.ecore.EObject) InternalEObject(org.eclipse.emf.ecore.InternalEObject) List(java.util.List) AbstractIterator(com.google.common.collect.AbstractIterator)

Aggregations

AbstractIterator (com.google.common.collect.AbstractIterator)55 IOException (java.io.IOException)15 Iterator (java.util.Iterator)14 Map (java.util.Map)8 ArrayList (java.util.ArrayList)7 List (java.util.List)6 File (java.io.File)5 EOFException (java.io.EOFException)4 Collection (java.util.Collection)4 HashSet (java.util.HashSet)4 BIGINT (com.facebook.presto.common.type.BigintType.BIGINT)3 SMALLINT (com.facebook.presto.common.type.SmallintType.SMALLINT)3 ImmutableMap (com.google.common.collect.ImmutableMap)3 Deque (java.util.Deque)3 Set (java.util.Set)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 CyclicBarrier (java.util.concurrent.CyclicBarrier)3 Test (org.junit.Test)3 TopicMetadata (co.cask.cdap.messaging.TopicMetadata)2 TopicId (co.cask.cdap.proto.id.TopicId)2