Example usage for com.google.common.collect Iterables isEmpty

List of usage examples for com.google.common.collect Iterables isEmpty

Introduction

In this page you can find the example usage for com.google.common.collect Iterables isEmpty.

Prototype

public static boolean isEmpty(Iterable<?> iterable) 

Source Link

Document

Determines if the given iterable contains no elements.

Usage

From source file:co.cask.cdap.template.etl.common.RecordPutTransformer.java

@Nullable
private Schema.Field getKeyField(Schema recordSchema) {
    Schema.Field field = recordSchema.getField(rowField);
    if (field == null && !rowFieldCaseSensitive) {
        Iterable<Schema.Field> filtered = Iterables.filter(recordSchema.getFields(),
                new Predicate<Schema.Field>() {
                    @Override/*  w w  w.  j  a  va  2s.  com*/
                    public boolean apply(Schema.Field input) {
                        return input.getName().equalsIgnoreCase(rowField);
                    }
                });
        if (!Iterables.isEmpty(filtered)) {
            Preconditions.checkArgument(Iterables.size(filtered) == 1,
                    "Cannot have multiple fields in the schema that match %s in a case-insensitive "
                            + "manner when the property %s is false. Found %s.",
                    rowField, Properties.Table.CASE_SENSITIVE_ROW_FIELD, Iterables.toString(filtered));
            field = filtered.iterator().next();
            rowField = field.getName();
        }
    }
    return field;
}

From source file:org.sonar.plugins.cpd.JavaCpdEngine.java

static void save(org.sonar.api.batch.sensor.SensorContext context, InputFile inputFile,
        @Nullable Iterable<CloneGroup> duplications) {
    if (duplications == null || Iterables.isEmpty(duplications)) {
        return;//from   w ww .  j  av a2 s .  com
    }
    Set<Integer> duplicatedLines = new HashSet<Integer>();
    int duplicatedBlocks = computeBlockAndLineCount(duplications, duplicatedLines);
    Map<Integer, Integer> duplicationByLine = new HashMap<Integer, Integer>();
    for (int i = 1; i <= inputFile.lines(); i++) {
        duplicationByLine.put(i, duplicatedLines.contains(i) ? 1 : 0);
    }
    ((DefaultMeasure<String>) context.<String>newMeasure().forMetric(CoreMetrics.DUPLICATION_LINES_DATA)
            .onFile(inputFile).withValue(KeyValueFormat.format(duplicationByLine))).setFromCore().save();
    // Save
    ((DefaultMeasure<Integer>) context.<Integer>newMeasure().forMetric(CoreMetrics.DUPLICATED_FILES)
            .onFile(inputFile).withValue(1)).setFromCore().save();
    ((DefaultMeasure<Integer>) context.<Integer>newMeasure().forMetric(CoreMetrics.DUPLICATED_LINES)
            .onFile(inputFile).withValue(duplicatedLines.size())).setFromCore().save();
    ((DefaultMeasure<Integer>) context.<Integer>newMeasure().forMetric(CoreMetrics.DUPLICATED_BLOCKS)
            .onFile(inputFile).withValue(duplicatedBlocks)).setFromCore().save();

    DuplicationBuilder builder = context.duplicationBuilder(inputFile);
    for (CloneGroup duplication : duplications) {
        builder.originBlock(duplication.getOriginPart().getStartLine(),
                duplication.getOriginPart().getEndLine());
        for (ClonePart part : duplication.getCloneParts()) {
            if (!part.equals(duplication.getOriginPart())) {
                ((DefaultDuplicationBuilder) builder).isDuplicatedBy(part.getResourceId(), part.getStartLine(),
                        part.getEndLine());
            }
        }
    }
    context.saveDuplications(inputFile, builder.build());
}

From source file:co.cask.cdap.data2.transaction.stream.AbstractStreamFileConsumerFactory.java

private MultiLiveStreamFileReader createReader(final StreamConfig streamConfig,
        StreamConsumerState consumerState) throws IOException {
    Location streamLocation = streamConfig.getLocation();
    Preconditions.checkNotNull(streamLocation, "Stream location is null for %s", streamConfig.getStreamId());

    // Look for the latest stream generation
    final int generation = StreamUtils.getGeneration(streamConfig);
    streamLocation = StreamUtils.createGenerationLocation(streamLocation, generation);

    final long currentTime = System.currentTimeMillis();

    if (!Iterables.isEmpty(consumerState.getState())) {
        // See if any offset has a different generation or is expired. If so, don't use the old states.
        boolean useStoredStates = Iterables.all(consumerState.getState(), new Predicate<StreamFileOffset>() {
            @Override//from  w  w  w  . j av  a2  s  .  com
            public boolean apply(StreamFileOffset input) {
                boolean isExpired = input.getPartitionEnd() < currentTime - streamConfig.getTTL();
                boolean sameGeneration = generation == input.getGeneration();
                return !isExpired && sameGeneration;
            }
        });

        if (useStoredStates) {
            LOG.info("Create file reader with consumer state: {}", consumerState);
            // Has existing offsets, just resume from there.
            MultiLiveStreamFileReader reader = new MultiLiveStreamFileReader(streamConfig,
                    consumerState.getState());
            reader.initialize();
            return reader;
        }
    }

    // TODO: Support starting from some time rather then from beginning.
    // Otherwise, search for files with the smallest partition start time
    // If no partition exists for the stream, start with one partition earlier than current time to make sure
    // no event will be lost if events start flowing in about the same time.
    long startTime = StreamUtils.getPartitionStartTime(currentTime - streamConfig.getPartitionDuration(),
            streamConfig.getPartitionDuration());
    long earliestNonExpiredTime = StreamUtils.getPartitionStartTime(currentTime - streamConfig.getTTL(),
            streamConfig.getPartitionDuration());

    for (Location partitionLocation : streamLocation.list()) {
        if (!partitionLocation.isDirectory() || !StreamUtils.isPartition(partitionLocation.getName())) {
            // Partition should be a directory
            continue;
        }

        long partitionStartTime = StreamUtils.getPartitionStartTime(partitionLocation.getName());
        boolean isPartitionExpired = partitionStartTime < earliestNonExpiredTime;
        if (!isPartitionExpired && partitionStartTime < startTime) {
            startTime = partitionStartTime;
        }
    }

    // Create file offsets
    // TODO: Be able to support dynamic name of stream writer instances.
    // Maybe it's done through MultiLiveStreamHandler to alter list of file offsets dynamically
    Location partitionLocation = StreamUtils.createPartitionLocation(streamLocation, startTime,
            streamConfig.getPartitionDuration());
    List<StreamFileOffset> fileOffsets = Lists.newArrayList();
    getFileOffsets(partitionLocation, fileOffsets, generation);

    LOG.info("Empty consumer state. Create file reader with file offsets: groupId={}, instanceId={} states={}",
            consumerState.getGroupId(), consumerState.getInstanceId(), fileOffsets);

    MultiLiveStreamFileReader reader = new MultiLiveStreamFileReader(streamConfig, fileOffsets);
    reader.initialize();
    return reader;
}

From source file:org.apache.beam.runners.direct.portable.EvaluationContext.java

/**
 * Handle the provided {@link TransformResult}, produced after evaluating the provided {@link
 * CommittedBundle} (potentially null, if the result of a root {@link PTransform}).
 *
 * <p>The result is the output of running the transform contained in the {@link TransformResult}
 * on the contents of the provided bundle.
 *
 * @param completedBundle the bundle that was processed to produce the result. Potentially {@code
 *     null} if the transform that produced the result is a root transform
 * @param completedTimers the timers that were delivered to produce the {@code completedBundle},
 *     or an empty iterable if no timers were delivered
 * @param result the result of evaluating the input bundle
 * @return the committed bundles contained within the handled {@code result}
 *//*from  ww  w. j ava  2s.  co m*/
public CommittedResult<PTransformNode> handleResult(CommittedBundle<?> completedBundle,
        Iterable<TimerData> completedTimers, TransformResult<?> result) {
    Iterable<? extends CommittedBundle<?>> committedBundles = commitBundles(result.getOutputBundles());
    metrics.commitLogical(completedBundle, result.getLogicalMetricUpdates());

    // Update watermarks and timers
    EnumSet<OutputType> outputTypes = EnumSet.copyOf(result.getOutputTypes());
    if (Iterables.isEmpty(committedBundles)) {
        outputTypes.remove(OutputType.BUNDLE);
    } else {
        outputTypes.add(OutputType.BUNDLE);
    }
    CommittedResult<PTransformNode> committedResult = CommittedResult.create(result,
            getUnprocessedInput(completedBundle, result), committedBundles, outputTypes);
    // Update state internals
    CopyOnAccessInMemoryStateInternals theirState = result.getState();
    if (theirState != null) {
        CopyOnAccessInMemoryStateInternals committedState = theirState.commit();
        StepAndKey stepAndKey = StepAndKey.of(result.getTransform(), completedBundle.getKey());
        if (!committedState.isEmpty()) {
            applicationStateInternals.put(stepAndKey, committedState);
        } else {
            applicationStateInternals.remove(stepAndKey);
        }
    }
    // Watermarks are updated last to ensure visibility of any global state before progress is
    // permitted
    watermarkManager.updateWatermarks(completedBundle,
            result.getTimerUpdate().withCompletedTimers(completedTimers), committedResult.getExecutable(),
            committedResult.getUnprocessedInputs().orNull(), committedResult.getOutputs(),
            result.getWatermarkHold());
    return committedResult;
}

From source file:org.apache.beam.runners.direct.SideInputContainer.java

/**
 * Set the value of the {@link PCollectionView} in the {@link BoundedWindow} to be based on the
 * specified values, if the values are part of a later pane than currently exist within the
 * {@link PCollectionViewWindow}./*w w  w . ja v a  2s  .  c  o m*/
 */
private void updatePCollectionViewWindowValues(PCollectionView<?> view, BoundedWindow window,
        Collection<WindowedValue<?>> windowValues) {
    PCollectionViewWindow<?> windowedView = PCollectionViewWindow.of(view, window);
    AtomicReference<Iterable<? extends WindowedValue<?>>> contents = viewByWindows.getUnchecked(windowedView);
    if (contents.compareAndSet(null, windowValues)) {
        // the value had never been set, so we set it and are done.
        return;
    }
    PaneInfo newPane = windowValues.iterator().next().getPane();

    Iterable<? extends WindowedValue<?>> existingValues;
    long existingPane;
    do {
        existingValues = contents.get();
        existingPane = Iterables.isEmpty(existingValues) ? -1L
                : existingValues.iterator().next().getPane().getIndex();
    } while (newPane.getIndex() > existingPane && !contents.compareAndSet(existingValues, windowValues));
}

From source file:net.freifunk.autodeploy.printing.LabelPrintingServiceImpl.java

private void printPng(final File png) {
    final PrintRequestAttributeSet printRequestAttributes = new HashPrintRequestAttributeSet();
    final DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
    final PrintService[] printServices = PrintServiceLookup.lookupPrintServices(flavor, printRequestAttributes);

    final Iterable<PrintService> filteredPrintServices = Iterables.filter(ImmutableList.copyOf(printServices),
            new Predicate<PrintService>() {

                @Override//from  ww  w  .j av  a 2 s. c om
                public boolean apply(final PrintService input) {
                    return LABLE_PRINTER.equals(input.getName());
                }
            });

    if (Iterables.isEmpty(filteredPrintServices)) {
        LOG.warn("No printer found. Aborting.");
        return;
    }

    final PrintService printService = Iterables.getOnlyElement(filteredPrintServices);

    final DocPrintJob job = printService.createPrintJob();
    final DocAttributeSet docAttributes = new HashDocAttributeSet();
    try {
        final Doc document = new SimpleDoc(new FileInputStream(png), flavor, docAttributes);
        job.print(document, printRequestAttributes);
    } catch (final PrintException | IOException e) {
        throw new IllegalStateException("Could not print label.", e);
    }
}

From source file:com.vmware.appfactory.feed.controller.FeedApiController.java

/**
 * Deletes a feed and all the other stuff that points back to it.
 *
 * This will delete related jobs and job batches.
 *///from www.j  a  va 2 s  . c  om
private void deleteFeedAndRelated(Feed feed) {
    // Abort the currently scanning task if any.
    Iterable<? extends TaskState> activeTasks = _scanningQueue.findActiveTasksForFeed(feed.getId());

    if (!Iterables.isEmpty(activeTasks)) {
        Iterator i = activeTasks.iterator();
        while (i.hasNext()) {
            TaskState s = (TaskState) i.next();
            _log.info("Aborting active feed task({}) with status: {}", s.getId(), s.getStatus());
            // Abort running feed scan task.
            _scanningQueue.abortTask(s.getId());
        }
    }

    // Abort any running conversions pertaining to this feed.
    deleteAppSourceRelated(feed);

    // Now we can safely delete the feed.
    _daoFactory.getFeedDao().delete(feed);
}

From source file:ezbake.data.graph.blueprints.visibility.VisibilityFilterQuery.java

/**
 * Create a Guava predicate from a Blueprints predicate.
 *
 * @param key element property key to check
 * @param predicate predicate to check element property value
 * @param value value as other argument to predicate
 * @return Guava predicate wrapping Blueprints predicate
 *///from   w  ww.  j a  v  a 2s  . c  o m
private <T extends Element> Predicate<T> blueprintsPredicate(final String key,
        final com.tinkerpop.blueprints.Predicate predicate, final Object value) {
    return new Predicate<T>() {
        @Override
        public boolean apply(T element) {
            List<Map<String, Object>> values = element.getProperty(key);
            if (values == null) {
                return false;
            }

            Iterable<Map<String, Object>> it = Iterables
                    .filter(values,
                            Predicates.and(
                                    permissionContext.getPropertyFilter()
                                            .hasAnyPermissionPredicate(Permission.DISCOVER, Permission.READ),
                                    blueprintsValuePredicate(predicate, value)));

            return !Iterables.isEmpty(it);
        }
    };
}

From source file:com.scurrilous.uritemplate.URITemplate.java

private static boolean isUndefined(Object value) {
    return value == null || (value instanceof Map && isUndefinedMap((Map<?, ?>) value))
            || (value instanceof Iterable && Iterables.isEmpty((Iterable<?>) value));
}

From source file:org.eclipse.xtext.ui.util.PluginProjectFactory.java

/**
 * @since 2.8/*from w  w  w  . j a  v a2s  .  com*/
 */
protected void addToBuildProperties(StringBuilder content, Iterable<String> entries, String entryName) {
    if (entries != null && !Iterables.isEmpty(entries)) {
        String assigment = entryName + " = ";
        String indent = Strings.repeat(" ", assigment.length());
        content.append(assigment);
        for (final Iterator<String> iterator = entries.iterator(); iterator.hasNext();) {
            content.append(iterator.next());
            if (iterator.hasNext()) {
                content.append(",\\\n");
                content.append(indent);
            }
        }
    }
}