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.android.tools.idea.npw.AddAndroidActivityPath.java

/**
 * Finds and returns the main src directory for the given project or null if one cannot be found.
 *//*from   ww  w .  ja  v a2  s  .c o  m*/
@Nullable
private static File findSrcDirectory(@NotNull SourceProvider sourceProvider) {
    return Iterables.getFirst(sourceProvider.getJavaDirectories(), null);
}

From source file:org.opennms.features.topology.plugins.topo.graphml.GraphMLMetaTopologyProvider.java

@Override
public GraphProvider getDefaultGraphProvider() {
    return Iterables.getFirst(graphsByNamespace.values(), null);
}

From source file:com.android.tools.idea.gradle.AndroidGradleJavaProjectModelModifier.java

@Nullable
private static Promise<Void> addExternalLibraryDependency(@NotNull Collection<Module> modules,
        @NotNull ArtifactDependencySpec dependencySpec, @NotNull DependencyScope scope) {
    Module firstModule = Iterables.getFirst(modules, null);
    if (firstModule == null) {
        return null;
    }/*www .j  av  a2s  .c  o  m*/
    Project project = firstModule.getProject();

    VirtualFile openedFile = FileEditorManagerEx.getInstanceEx(firstModule.getProject()).getCurrentFile();

    List<GradleBuildModel> buildModelsToUpdate = Lists.newArrayList();
    for (Module module : modules) {
        GradleBuildModel buildModel = GradleBuildModel.get(module);
        if (buildModel == null) {
            return null;
        }
        String configurationName = getConfigurationName(module, scope, openedFile);
        DependenciesModel dependencies = buildModel.dependencies();
        dependencies.addArtifact(configurationName, dependencySpec);
        buildModelsToUpdate.add(buildModel);
    }

    new WriteCommandAction(project, "Add Gradle Library Dependency") {
        @Override
        protected void run(@NotNull Result result) throws Throwable {
            for (GradleBuildModel buildModel : buildModelsToUpdate) {
                buildModel.applyChanges();
            }
            registerUndoAction(project);
        }
    }.execute();

    return requestProjectSync(project);
}

From source file:io.helixservice.feature.restservice.controller.Response.java

/**
 * Get the first value for a header//from ww w. ja  v  a2  s  . c  om
 *
 * @param headerName Header name
 * @return
 */
public String getHeader(String headerName) {
    return Iterables.getFirst(headers.get(headerName), null);
}

From source file:org.obm.provisioning.processing.impl.BatchProcessorImpl.java

private void postProcess(Batch batch) {
    try {//from   w  ww . ja  va  2  s .  c om
        ObmDomain domain = batch.getDomain();

        if (Iterables.getFirst(domain.getHosts().get(ServiceProperty.SMTP_IN), null) != null) {
            satelliteService.create(getSatelliteConfiguration(), domain).updateMTA();
        } else {
            logger.info(String.format("Not updating obm-satellite, the domain %s has no linked %s host.",
                    domain.getName(), ServiceProperty.SMTP_IN));
        }
    } catch (Exception e) {
        throw new ProcessingException("Cannot update obm-satellite.", e);
    }
}

From source file:org.apache.calcite.plan.volcano.RelSubset.java

@Override
public void explain(RelWriter pw) {
    // Not a typical implementation of "explain". We don't gather terms &
    // values to be printed later. We actually do the work.
    String s = getDescription();/*  w  w w  .  j  a  va2s.  co  m*/
    pw.item("subset", s);
    final AbstractRelNode input = (AbstractRelNode) Iterables.getFirst(getRels(), null);
    if (input == null) {
        return;
    }
    input.explainTerms(pw);
    pw.done(input);
}

From source file:io.brooklyn.ambari.server.AmbariServerSshDriver.java

private AmbariCluster getParentAmbariCluster() {
    Iterable<AmbariCluster> ancestors = Iterables.filter(Entities.ancestors(entity), AmbariCluster.class);
    return Iterables.getFirst(ancestors, null);
}

From source file:com.facebook.buck.cli.FineGrainedJavaDependencySuggester.java

/**
 * Suggests a refactoring by printing it to stdout (with warnings printed to stderr).
 * @throws IllegalArgumentException/*w ww .  j  a v  a  2 s.c  om*/
 */
void suggestRefactoring() {
    final TargetNode<?, ?> suggestedNode = graph.get(suggestedTarget);
    if (!(suggestedNode.getConstructorArg() instanceof JavaLibraryDescription.Arg)) {
        console.printErrorText(String.format("'%s' does not correspond to a Java rule", suggestedTarget));
        throw new IllegalArgumentException();
    }

    JavaLibraryDescription.Arg arg = (JavaLibraryDescription.Arg) suggestedNode.getConstructorArg();
    JavaFileParser javaFileParser = javaDepsFinder.getJavaFileParser();
    Multimap<String, String> providedSymbolToRequiredSymbols = HashMultimap.create();
    Map<String, PathSourcePath> providedSymbolToSrc = new HashMap<>();
    for (SourcePath src : arg.srcs) {
        extractProvidedSymbolInfoFromSourceFile(src, javaFileParser, providedSymbolToRequiredSymbols,
                providedSymbolToSrc);
    }

    // Create a MutableDirectedGraph from the providedSymbolToRequiredSymbols.
    MutableDirectedGraph<String> symbolsDependencies = new MutableDirectedGraph<>();
    // Iterate the keys of providedSymbolToSrc rather than providedSymbolToRequiredSymbols because
    // providedSymbolToRequiredSymbols will not have any entries for providedSymbols with no
    // dependencies.
    for (String providedSymbol : providedSymbolToSrc.keySet()) {
        // Add a node for the providedSymbol in case it has no edges.
        symbolsDependencies.addNode(providedSymbol);
        for (String requiredSymbol : providedSymbolToRequiredSymbols.get(providedSymbol)) {
            if (providedSymbolToRequiredSymbols.containsKey(requiredSymbol)
                    && !providedSymbol.equals(requiredSymbol)) {
                symbolsDependencies.addEdge(providedSymbol, requiredSymbol);
            }
        }
    }

    // Determine the strongly connected components.
    Set<Set<String>> stronglyConnectedComponents = symbolsDependencies.findStronglyConnectedComponents();
    // Maps a providedSymbol to the component that contains it.
    Map<String, NamedStronglyConnectedComponent> namedComponentsIndex = new TreeMap<>();
    Set<NamedStronglyConnectedComponent> namedComponents = new TreeSet<>();
    for (Set<String> stronglyConnectedComponent : stronglyConnectedComponents) {
        // We just use the first provided symbol in the strongly connected component as the canonical
        // name for the component. Maybe not the best name, but certainly not the worst.
        String name = Iterables.getFirst(stronglyConnectedComponent, /* defaultValue */ null);
        if (name == null) {
            throw new IllegalStateException("A strongly connected component was created with zero nodes.");
        }

        NamedStronglyConnectedComponent namedComponent = new NamedStronglyConnectedComponent(name,
                stronglyConnectedComponent);
        namedComponents.add(namedComponent);
        for (String providedSymbol : stronglyConnectedComponent) {
            namedComponentsIndex.put(providedSymbol, namedComponent);
        }
    }

    // Visibility argument.
    StringBuilder visibilityBuilder = new StringBuilder("  visibility = [\n");
    SortedSet<String> visibilities = FluentIterable.from(suggestedNode.getVisibilityPatterns())
            .transform(VisibilityPattern::getRepresentation).toSortedSet(Ordering.natural());
    for (String visibility : visibilities) {
        visibilityBuilder.append("    '" + visibility + "',\n");
    }
    visibilityBuilder.append("  ],\n");
    String visibilityArg = visibilityBuilder.toString();

    // Print out the new version of the original rule.
    console.getStdOut().printf("java_library(\n" + "  name = '%s',\n" + "  exported_deps = [\n",
            suggestedTarget.getShortName());
    for (NamedStronglyConnectedComponent namedComponent : namedComponents) {
        console.getStdOut().printf("    ':%s',\n", namedComponent.name);
    }
    console.getStdOut().print("  ],\n" + visibilityArg + ")\n");

    // Print out a rule for each of the strongly connected components.
    JavaDepsFinder.DependencyInfo dependencyInfo = javaDepsFinder.findDependencyInfoForGraph(graph);
    for (NamedStronglyConnectedComponent namedComponent : namedComponents) {
        String buildRuleDefinition = createBuildRuleDefinition(namedComponent, providedSymbolToSrc,
                providedSymbolToRequiredSymbols, namedComponentsIndex, dependencyInfo, symbolsDependencies,
                visibilityArg);
        console.getStdOut().print(buildRuleDefinition);
    }
}

From source file:com.google.gerrit.server.change.Submit.java

/**
 * If the merge was attempted and it failed the system usually writes a
 * comment as a ChangeMessage and sets status to NEW. Find the relevant
 * message and return it./*  w  w w. jav  a 2s. co  m*/
 */
public ChangeMessage getConflictMessage(RevisionResource rsrc) throws OrmException {
    final Timestamp before = rsrc.getChange().getLastUpdatedOn();
    ChangeMessage msg = Iterables.getFirst(Iterables.filter(
            Lists.reverse(dbProvider.get().changeMessages().byChange(rsrc.getChange().getId()).toList()),
            new Predicate<ChangeMessage>() {
                @Override
                public boolean apply(ChangeMessage input) {
                    return input.getAuthor() == null && input.getWrittenOn().getTime() >= before.getTime();
                }
            }), null);
    return msg;
}

From source file:controllers.modules.AspectLexBuilder.java

public static Result update(UUID corpus, UUID lexicon) {
    DocumentCorpus corpusObj = null;/*  w w w . j a  va 2  s  .co m*/
    if (corpus != null) {
        corpusObj = fetchResource(corpus, DocumentCorpus.class);
    }
    AspectLexicon lexiconObj = null;
    if (lexicon != null) {
        lexiconObj = fetchResource(lexicon, AspectLexicon.class);
    }

    AspectLexiconFactory factory = null;

    MultipartFormData formData = request().body().asMultipartFormData();
    if (formData != null) {
        // if we have a multi-part form with a file.
        if (formData.getFiles() != null) {
            // get either the file named "file" or the first one.
            FilePart filePart = ObjectUtils.defaultIfNull(formData.getFile("file"),
                    Iterables.getFirst(formData.getFiles(), null));
            if (filePart != null) {
                factory = (AspectLexiconFactory) new AspectLexiconFactory().setFile(filePart.getFile())
                        .setFormat(FilenameUtils.getExtension(filePart.getFilename()));
            }
        }
    } else {
        JsonNode json = request().body().asJson();
        if (json != null) {
            AspectLexiconFactoryModel viewModel = Json.fromJson(json, AspectLexiconFactoryModel.class);
            if (viewModel != null) {
                factory = viewModel.toFactory();

                if (lexiconObj != null) {
                    if (corpusObj != null && (lexiconObj.getBaseCorpus() == null
                            || !ObjectUtils.equals(lexiconObj.getBaseCorpus(), corpusObj))) {
                        throw new IllegalArgumentException();
                    }
                }
            } else {
                throw new IllegalArgumentException();
            }
        } else {
            // if not json, then just create empty options.
            factory = new AspectLexiconFactory();
        }
    }

    if (factory == null) {
        throw new IllegalArgumentException();
    }

    if (lexicon == null && StringUtils.isEmpty(factory.getTitle())) {
        factory.setTitle("Untitled aspect lexicon");
    }

    factory.setBaseStore(corpusObj);
    factory.setOwnerId(SessionedAction.getUsername(ctx()));
    factory.setExistingId(lexicon);
    factory.setEm(em());

    AspectLexiconModel lexiconVM = null;
    lexiconObj = factory.create();
    if (!em().contains(lexiconObj)) {
        em().persist(lexiconObj);

        lexiconVM = (AspectLexiconModel) createViewModel(lexiconObj);
        lexiconVM.populateSize(em(), lexiconObj);
        return created(lexiconVM.asJson());
    }

    em().merge(lexiconObj);

    lexiconVM = (AspectLexiconModel) createViewModel(lexiconObj);
    lexiconVM.populateSize(em(), lexiconObj);
    return ok(lexiconVM.asJson());
}