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

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

Introduction

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

Prototype

@Nullable
public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue) 

Source Link

Document

Returns the first element in iterable or defaultValue if the iterable is empty.

Usage

From source file:com.arpnetworking.tsdaggregator.perf.FilePerfTestBase.java

/**
 * Runs a test./*from w  ww  .  jav a 2  s  .c  o m*/
 *
 * @param pipelineConfigurationFile Pipeline configuration file.
 * @param duration Timeout period.
 */
protected void benchmark(final File pipelineConfigurationFile, final Duration duration) {
    LOGGER.debug(String.format("Launching pipeline; configuration=%s", pipelineConfigurationFile));

    // Create custom "canary" sink
    final CountDownLatch latch = new CountDownLatch(1);
    final Stopwatch timer = Stopwatch.createUnstarted();
    final ListeningSink sink = new ListeningSink(new Function<Collection<AggregatedData>, Void>() {
        @Nullable
        @Override
        public Void apply(@Nullable final Collection<AggregatedData> input) {
            if (input != null) {
                final AggregatedData datum = Iterables.getFirst(input, null);
                if (datum != null && TestFileGenerator.CANARY.equals(datum.getFQDSN().getMetric())
                        && timer.isRunning()) {
                    timer.stop();
                    latch.countDown();
                }
            }
            return null;
        }
    });

    // Load the specified stock configuration
    final PipelineConfiguration stockPipelineConfiguration = new StaticConfiguration.Builder()
            .addSource(new JsonNodeFileSource.Builder().setFile(pipelineConfigurationFile).build())
            .setObjectMapper(PipelineConfiguration.createObjectMapper(_injector)).build()
            .getRequiredAs(PipelineConfiguration.class);

    // Add the custom "canary" sink
    final List<Sink> benchmarkSinks = Lists.newArrayList(stockPipelineConfiguration.getSinks());
    benchmarkSinks.add(sink);

    // Create the custom configuration
    final PipelineConfiguration benchmarkPipelineConfiguration = OvalBuilder.<PipelineConfiguration, PipelineConfiguration.Builder>clone(
            stockPipelineConfiguration).setSinks(benchmarkSinks).build();

    // Instantiate the pipeline
    final Pipeline pipeline = new Pipeline(benchmarkPipelineConfiguration);

    // Execute the pipeline until the canary flies the coop
    try {
        timer.start();
        pipeline.launch();

        if (!latch.await(duration.getMillis(), TimeUnit.MILLISECONDS)) {
            LOGGER.error("Test timed out");
            throw new RuntimeException("Test timed out");
        }
    } catch (final InterruptedException e) {
        Thread.interrupted();
        throw new RuntimeException("Test interrupted");
    } finally {
        pipeline.shutdown();
    }
}

From source file:org.dishevelled.bio.range.tree.CenteredRangeTree.java

/**
 * Create and return a new node for the specified ranges.
 *
 * @param ranges ranges//from   w  w  w  .j  a  va2s.  c  o  m
 * @return a new node for the specified ranges
 */
private Node createNode(final Iterable<Range<C>> ranges) {
    Range<C> span = Iterables.getFirst(ranges, null);
    if (span == null) {
        return null;
    }
    for (Range<C> range : ranges) {
        checkNotNull(range, "ranges must not contain null ranges");
        span = range.span(span);
    }
    if (span.isEmpty()) {
        return null;
    }
    C center = Ranges.center(span);
    List<Range<C>> left = Lists.newArrayList();
    List<Range<C>> right = Lists.newArrayList();
    List<Range<C>> overlap = Lists.newArrayList();
    for (Range<C> range : ranges) {
        if (Ranges.isLessThan(range, center)) {
            left.add(range);
        } else if (Ranges.isGreaterThan(range, center)) {
            right.add(range);
        } else {
            overlap.add(range);
        }
    }
    return new Node(center, createNode(left), createNode(right), overlap);
}

From source file:org.apache.metron.elasticsearch.dao.ElasticsearchRetrieveLatestDao.java

@Override
public Iterable<Document> getAllLatest(List<GetRequest> getRequests) {
    Collection<String> guids = new HashSet<>();
    Collection<String> sensorTypes = new HashSet<>();
    for (GetRequest getRequest : getRequests) {
        guids.add(getRequest.getGuid());
        sensorTypes.add(getRequest.getSensorType());
    }/*from   w  ww.j a va  2s.com*/
    List<Document> documents = searchByGuids(guids, sensorTypes, hit -> {
        Long ts = 0L;
        String doc = hit.getSourceAsString();
        String sourceType = Iterables.getFirst(Splitter.on("_doc").split(hit.getType()), null);
        try {
            return Optional.of(new Document(doc, hit.getId(), sourceType, ts));
        } catch (IOException e) {
            throw new IllegalStateException("Unable to retrieve latest: " + e.getMessage(), e);
        }
    }

    );
    return documents;
}

From source file:com.google.security.zynamics.binnavi.debug.helpers.BreakpointableNodeCounter.java

@Override
public IterationMode next(final NaviNode node) {
    final INaviViewNode viewNode = node.getRawNode();

    if (viewNode instanceof INaviCodeNode) {
        final INaviCodeNode codeNode = (INaviCodeNode) viewNode;
        final INaviInstruction instruction = Iterables.getFirst(codeNode.getInstructions(), null);
        final INaviModule module = instruction.getModule();
        final BreakpointAddress address = new BreakpointAddress(module,
                new UnrelocatedAddress(instruction.getAddress()));
        if (EchoBreakpointCollector.isBlocked(breakpointManager, address)) {
            return IterationMode.CONTINUE;
        }/*from   www .j  ava2 s .  co  m*/
        ++breakpointAbleNodeCount;
    } else if (viewNode instanceof INaviFunctionNode) {
        final INaviFunctionNode functionNode = (INaviFunctionNode) viewNode;
        final INaviModule module = functionNode.getFunction().getModule();
        final BreakpointAddress address = new BreakpointAddress(module,
                new UnrelocatedAddress(functionNode.getFunction().getAddress()));
        if (EchoBreakpointCollector.isBlocked(breakpointManager, address)) {
            return IterationMode.CONTINUE;
        }
        ++breakpointAbleNodeCount;
    }
    return IterationMode.CONTINUE;
}

From source file:org.jetbrains.jet.lang.resolve.lazy.descriptors.LazyPackageDescriptor.java

public LazyPackageDescriptor(@NotNull NamespaceDescriptorParent containingDeclaration, @NotNull Name name,
        @NotNull ResolveSession resolveSession, @NotNull PackageMemberDeclarationProvider declarationProvider) {
    super(containingDeclaration, Collections.<AnnotationDescriptor>emptyList(), name);

    WritableScopeImpl scope = new WritableScopeImpl(JetScope.EMPTY, this, RedeclarationHandler.DO_NOTHING,
            "Package scope");
    resolveSession.getRootModuleDescriptor().getModuleConfiguration()
            .extendNamespaceScope(resolveSession.getTrace(), this, scope);
    scope.changeLockLevel(WritableScope.LockLevel.READING);

    this.lazyScope = new LazyPackageMemberScope(resolveSession, declarationProvider, this);

    this.memberScope = new ChainedScope(this, "Lazy package members scope: " + name, lazyScope, scope);

    NavigatablePsiElement declaration = Iterables
            .getFirst(declarationProvider.getPackageDeclarations(getFqName()), null);
    if (declaration != null) {
        resolveSession.getTrace().record(BindingContext.NAMESPACE, declaration, this);
    }//  w w w  .ja  v  a 2s . c  o  m
}

From source file:com.facebook.buck.rules.coercer.FrameworkPathTypeCoercer.java

@Override
public FrameworkPath coerce(CellPathResolver cellRoots, ProjectFilesystem filesystem,
        Path pathRelativeToProjectRoot, Object object) throws CoerceFailedException {
    if (object instanceof String) {
        Path path = Paths.get((String) object);

        String firstElement = Preconditions.checkNotNull(Iterables.getFirst(path, Paths.get(""))).toString();

        if (firstElement.startsWith("$")) { // NOPMD - length() > 0 && charAt(0) == '$' is ridiculous
            Optional<PBXReference.SourceTree> sourceTree = PBXReference.SourceTree
                    .fromBuildSetting(firstElement);
            if (sourceTree.isPresent()) {
                int nameCount = path.getNameCount();
                if (nameCount < 2) {
                    throw new HumanReadableException(
                            "Invalid source tree path: '%s'. Should have at least one path component after"
                                    + "'%s'.",
                            path, firstElement);
                }/*from  ww  w.  j a  v  a  2s .com*/
                return FrameworkPath.ofSourceTreePath(new SourceTreePath(sourceTree.get(),
                        path.subpath(1, path.getNameCount()), Optional.empty()));
            } else {
                throw new HumanReadableException("Unknown SourceTree: '%s'. Should be one of: %s", firstElement,
                        Joiner.on(", ")
                                .join(Iterables.transform(
                                        ImmutableList.copyOf(PBXReference.SourceTree.values()),
                                        input -> "$" + input.toString())));
            }
        } else {
            return FrameworkPath.ofSourcePath(
                    sourcePathTypeCoercer.coerce(cellRoots, filesystem, pathRelativeToProjectRoot, object));
        }
    }

    throw CoerceFailedException.simple(object, getOutputClass(),
            "input should be either a source tree path or a source path");
}

From source file:com.google.template.soy.soytree.TemplateSubject.java

public TemplateSubject causesError(SoyError error) {
    ErrorReporterImpl errorReporter = new ErrorReporterImpl();
    try {/*w ww  . j ava  2  s.c  o  m*/
        new TemplateParser(new FixedIdGenerator(), getSubject(), "example.soy", 1, errorReporter)
                .parseTemplateContent();
    } finally {
        Truth.assertThat(errorReporter.locationsForError.keySet()).contains(error);
        actualSourceLocation = Iterables.getFirst(errorReporter.locationsForError.get(error), null);
        return this;
    }
}

From source file:brooklyn.util.mutex.SemaphoreForTasks.java

@Override
protected synchronized void onRequesting() {
    if (!owningTasks.isEmpty() || !requestingTasks.isEmpty()) {
        Tasks.setBlockingTask(!requestingTasks.isEmpty() ? Iterables.getLast(requestingTasks)
                : Iterables.getFirst(owningTasks, null));
        Tasks.setBlockingDetails(// w w  w.  j  ava2  s  . c o m
                "Waiting on semaphore " + getName() + " (" + getDescription() + "); " + "queued at "
                        + Time.makeDateString() + " when " + getRequestingThreads().size() + " ahead in queue");
    }
    requestingTasks.addIfNotNull(Tasks.current());
    super.onRequesting();
}

From source file:org.trancecode.xproc.step.XsltStepProcessor.java

@Override
protected void execute(final StepInput input, final StepOutput output) {
    final Iterable<XdmNode> sourceDocuments = input.readNodes(XProcPorts.SOURCE);
    final XdmNode sourceDocument = Iterables.getFirst(sourceDocuments, null);

    final String providedOutputBaseUri = input.getOptionValue(XProcOptions.OUTPUT_BASE_URI);
    final URI outputBaseUri;
    if (providedOutputBaseUri != null && providedOutputBaseUri.length() > 0) {
        outputBaseUri = URI.create(providedOutputBaseUri);
    } else if (sourceDocument != null && sourceDocument.getBaseURI() != null
            && sourceDocument.getBaseURI().toString().length() > 0) {
        outputBaseUri = sourceDocument.getBaseURI();
    } else {/*w  ww  .  j a v  a 2 s .c  o  m*/
        outputBaseUri = input.getBaseUri();
    }
    assert outputBaseUri != null;
    LOG.trace("outputBaseUri = {}", outputBaseUri);

    final String version = input.getOptionValue(XProcOptions.VERSION, DEFAULT_VERSION);
    LOG.trace("version = {}", version);

    if (!SUPPORTED_VERSIONS.contains(version)) {
        throw XProcExceptions.xc0038(input.getStep().getLocation(), version);
    }

    if (version.equals("1.0") && Iterables.size(sourceDocuments) != 1) {
        throw XProcExceptions.xc0039(input.getLocation(), Iterables.size(sourceDocuments));
    }

    final XdmNode stylesheet = input.readNode(XProcPorts.STYLESHEET);
    assert stylesheet != null;

    final Processor processor = input.getPipelineContext().getProcessor();

    // TODO pipeline logging
    final XsltTransformer transformer;
    try {
        transformer = processor.newXsltCompiler().compile(stylesheet.asSource()).load();
        if (sourceDocument != null) {
            transformer.setInitialContextNode(sourceDocument);
        }
    } catch (final SaxonApiException e) {
        throw new PipelineException(e);
    }

    // TODO transformer.setMessageListener();
    final XdmDestination result = new XdmDestination();
    if (!outputBaseUri.toString().isEmpty()) {
        result.setBaseURI(outputBaseUri);
    }
    transformer.setDestination(result);
    transformer.getUnderlyingController().setBaseOutputURI(outputBaseUri.toString());

    final List<XdmNode> secondaryPortNodes = Lists.newArrayList();
    transformer.getUnderlyingController().setOutputURIResolver(new OutputURIResolver() {
        final Map<URI, XdmDestination> destinations = Maps.newHashMap();

        @Override
        public void close(final Result result) throws TransformerException {
            final URI uri = URI.create(result.getSystemId());
            assert destinations.containsKey(uri);
            final XdmDestination xdmResult = destinations.get(uri);
            LOG.trace("result base URI = {}", xdmResult.getXdmNode().getBaseURI());
            secondaryPortNodes.add(xdmResult.getXdmNode());
        }

        @Override
        public OutputURIResolver newInstance() {
            return this;
        }

        @Override
        public Result resolve(final String href, final String base) throws TransformerException {
            final URI uri = Uris.resolve(href, base);
            assert uri != null;
            LOG.debug("new result document: {}", uri);

            try {
                final XdmDestination xdmResult = new XdmDestination();
                xdmResult.setBaseURI(uri);
                destinations.put(uri, xdmResult);
                final Receiver receiver = xdmResult.getReceiver(processor.getUnderlyingConfiguration());
                receiver.setSystemId(uri.toString());

                return receiver;
            } catch (final SaxonApiException e) {
                throw new TransformerException(e);
            }
        }
    });

    final String initialMode = input.getOptionValue(XProcOptions.INITIAL_MODE, null);
    if (initialMode != null) {
        // FIXME does not handle namespaces
        try {
            transformer.setInitialMode(new QName(initialMode));
        } catch (IllegalArgumentException e) {
            throw XProcExceptions.xc0056(input.getLocation());
        }
    }

    final Map<QName, String> parameters = input.getParameters(XProcPorts.PARAMETERS);
    LOG.debug("parameters = {}", parameters);
    for (final Map.Entry<QName, String> parameter : parameters.entrySet()) {
        transformer.setParameter(parameter.getKey(), new XdmAtomicValue(parameter.getValue()));
    }

    final StringBuilder terminateMessage = new StringBuilder();
    transformer.setMessageListener((content, terminate, locator) -> {
        if (terminate) {
            LOG.trace("terminateMessage = {}", content);
            terminateMessage.append(content.toString());
        }

        // TODO use a message log
        System.err.println(content);
    });

    try {
        transformer.transform();
    } catch (final SaxonApiException e) {
        if (terminateMessage.length() > 0) {
            throw new PipelineException(terminateMessage.toString());
        }

        // TODO XProcException?
        throw new PipelineException(e);
    }

    output.writeNodes(XProcPorts.SECONDARY, secondaryPortNodes);
    output.writeNodes(XProcPorts.RESULT, result.getXdmNode());
}

From source file:org.apache.jackrabbit.oak.plugins.memory.PropertyStates.java

/**
 * Create a multi valued {@code PropertyState} based on a list of
 * {@link Value} instances. The {@link Type} of the property is determined
 * by the type of the first value in the list or {@link Type#STRING} if the
 * list is empty.//  w  w w  . ja va 2 s . com
 *
 * @param name  The name of the property state
 * @param values  The values of the property state
 * @return  The new property state
 * @throws RepositoryException forwarded from {@code value}
 */
@Nonnull
public static PropertyState createProperty(String name, Iterable<Value> values) throws RepositoryException {
    int type = PropertyType.STRING;
    Value first = Iterables.getFirst(values, null);
    if (first != null) {
        type = first.getType();
    }
    return createProperty(name, values, type);
}