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:forge.game.spellability.TargetChoices.java

public final SpellAbility getFirstTargetedSpell() {
    return Iterables.getFirst(targetSpells, null);
}

From source file:com.garyclayburg.persistence.repository.AccountMatcher.java

public User matchAccount(UserAccount scimAccount) {
    QUser qUser = new QUser("user");

    User matchedUser = null;/*from www  .  j  a v a 2s  .  c o  m*/
    //default policy matches accounts based on username
    String instanceName = scimAccount.getInstanceName();
    Iterable<User> userList;
    if (scimAccount.getInstanceName() == null) {
        // find users that already have a useraccount with specific instancename
        userList = autoUserRepo.findAll(qUser.userAccounts.any().username.eq(scimAccount.getUsername())
                .and(qUser.userAccounts.any().accountType.eq(scimAccount.getAccountType()))
                .and(qUser.userAccounts.any().instanceName.isNull()));
    } else {
        // find users that alredy have a useraccount without a specific instancename
        userList = autoUserRepo.findAll(qUser.userAccounts.any().username.eq(scimAccount.getUsername())
                .and(qUser.userAccounts.any().accountType.eq(scimAccount.getAccountType()))
                .and(qUser.userAccounts.any().instanceName.eq(instanceName)));
    }
    int matchListSize = Iterables.size(userList);
    if (matchListSize == 1) {
        matchedUser = Iterables.getFirst(userList, null);
        // this scimAccount was matched previously to the stored user
    } else if (matchListSize > 1) {
        log.error("ERR-102 more than one possible account match for username: " + scimAccount.getUsername());
    } else {
        // execute groovy identity policy on everyone to find match
        //todo use closure here to pass in groovy policy for creating username as part of user query?
        List<User> allUsers = autoUserRepo.findAll(); //todo find a more efficient method for this?
        int matches = 0;
        for (User oneUser : allUsers) {
            Map<String, String> generatedAttributes = attributeService.getGeneratedAttributes(oneUser);

            //convention: attributes named username are used for matching during a recon/sync
            String username = generatedAttributes.get("username");
            log.debug("checking username: {} {} {}", username, oneUser.getFirstname(), oneUser.getLastname());
            if (username != null && username.equals(scimAccount.getUsername())) {
                matches++;
                if (matchedUser == null) {
                    matchedUser = oneUser; //go with first match
                }
            }
        }
        log.info("found {} users matching username attribute policy for user {} ", matches,
                scimAccount.getUsername());
    }
    return matchedUser;
}

From source file:com.google.security.zynamics.reil.translators.ReilTranslator.java

/**
 * Returns the first instruction from a code container.
 * // w  w  w .j  a  va  2 s.  c  o  m
 * @param container The code container.
 * 
 * @return The first instruction from the code container.
 */
private static IInstruction getFirstInstruction(final ICodeContainer<?> container) {
    return Iterables.getFirst(container.getInstructions(), null);
}

From source file:com.android.tools.idea.databinding.LightGeneratedComponentClass.java

public LightGeneratedComponentClass(@NotNull PsiManager psiManager, final AndroidFacet facet) {
    super(psiManager);
    myFacet = facet;//from w  w  w .j  a v a2 s.  c o m
    myPsiModifierList = new LightModifierList(myManager, getLanguage(), PsiModifier.PUBLIC);
    myMethodCache = CachedValuesManager.getManager(facet.getModule().getProject()).createCachedValue(() -> {
        Project project = facet.getModule().getProject();

        Map<String, Set<String>> instanceAdapterClasses = Maps.newHashMap();
        JavaPsiFacade facade = JavaPsiFacade.getInstance(myFacet.getModule().getProject());
        PsiClass aClass = facade.findClass(SdkConstants.BINDING_ADAPTER_ANNOTATION,
                myFacet.getModule().getModuleWithDependenciesAndLibrariesScope(false));
        if (aClass == null) {
            return CachedValueProvider.Result.create(PsiMethod.EMPTY_ARRAY,
                    myManager.getModificationTracker().getJavaStructureModificationTracker());
        }

        @SuppressWarnings("unchecked")
        final Collection<? extends PsiModifierListOwner> psiElements = AnnotatedElementsSearch
                .searchElements(aClass, myFacet.getModule().getModuleScope(), PsiMethod.class).findAll();
        int methodCount = 0;

        for (PsiModifierListOwner owner : psiElements) {
            if (owner instanceof PsiMethod && !owner.hasModifierProperty(PsiModifier.STATIC)) {
                PsiClass containingClass = ((PsiMethod) owner).getContainingClass();
                if (containingClass == null) {
                    continue;
                }
                String className = containingClass.getName();
                Set<String> set = instanceAdapterClasses.get(className);
                if (set == null) {
                    set = new TreeSet<>();
                    instanceAdapterClasses.put(className, set);
                }
                if (set.add(containingClass.getQualifiedName())) {
                    methodCount++;
                }
            }
        }
        if (methodCount == 0) {
            return CachedValueProvider.Result.create(PsiMethod.EMPTY_ARRAY,
                    myManager.getModificationTracker().getJavaStructureModificationTracker());
        }
        PsiElementFactory elementFactory = PsiElementFactory.SERVICE.getInstance(project);
        PsiMethod[] result = new PsiMethod[methodCount];
        int methodIndex = 0;
        GlobalSearchScope scope = GlobalSearchScope.allScope(project);
        for (Map.Entry<String, Set<String>> methods : instanceAdapterClasses.entrySet()) {
            if (methods.getValue().size() == 1) {
                result[methodIndex] = createPsiMethod(elementFactory, "get" + methods.getKey(),
                        Iterables.getFirst(methods.getValue(), ""), project, scope);
                methodIndex++;
            } else {
                int suffix = 1;
                for (String item : methods.getValue()) {
                    final String name = "get" + methods.getKey() + suffix;
                    result[methodIndex] = createPsiMethod(elementFactory, name, item, project, scope);
                    suffix++;
                    methodIndex++;
                }
            }
        }
        return CachedValueProvider.Result.create(result,
                myManager.getModificationTracker().getJavaStructureModificationTracker());
    }, false);
}

From source file:net.nifheim.beelzebu.coins.bukkit.utils.bungee.PluginMessage.java

public void sendToBungeeCord(String channel, List<String> messages) {
    ByteArrayDataOutput out = ByteStreams.newDataOutput();
    out.writeUTF(channel);// ww w .j a  v a 2 s  .  c o m
    messages.forEach(message -> {
        out.writeUTF(message);
    });
    Player p = Iterables.getFirst(Bukkit.getOnlinePlayers(), null);
    if (p != null) {
        p.sendPluginMessage(Main.getInstance(), "Coins", out.toByteArray());
    }
}

From source file:com.addthis.hydra.job.store.JobStoreGit.java

/**
 * Returns the hash of the last commit before a job was deleted.
 * //  www .  j  a  v a  2 s.  c  om
 * This method uses the following git command equivalent:
 * <pre>
 * git log --all --skip=1 -n 1 -- jobs/[jobId]
 * </pre>
 * which only works as intended with deleted jobs. 
 * 
 * @param jobId     The id of a deleted job.
 * @throws GitAPIException
 * @throws IOException
 */
public String getCommitHashBeforeJobDeletion(String jobId) throws GitAPIException, IOException {
    // skip=1 skips the deletion, and -n 1 returns only the commit immediately before that
    Iterable<RevCommit> iter = git.log().all().addPath(getPathForJobId(jobId)).setSkip(1).setMaxCount(1).call();
    RevCommit commit = Iterables.getFirst(iter, null);
    return commit == null ? null : commit.getName();
}

From source file:org.icgc.dcc.release.job.fathmm.core.FathmmPredictor.java

public Map<String, String> predict(String translationId, String aaChange) {
    Map<String, String> result = null;
    Map<String, Object> cache = Iterables.getFirst(
            cacheQuery.bind("translationId", translationId).bind("aaMutation", aaChange).list(), null);

    if (cache != null) {
        result = newHashMap();//from   www.  j a v a2s  .c  om
        if (cache.get("score") != null) {
            result.put("Score", cache.get("score").toString());
            result.put("Prediction", cache.get("prediction").toString());
        }
    } else {
        result = calculateFATHMM(translationId, aaChange, "INHERITED");
        handle.execute(
                "insert into \"DCC_CACHE\" (translation_id,  aa_mutation, score, prediction) values (?,?,?,?)",
                translationId, aaChange, result.get("Score"), result.get("Prediction"));
    }

    return result;
}

From source file:com.google.template.soy.parsepasses.contextautoesc.CheckEscapingSanityVisitor.java

@Override
protected void visitCallDelegateNode(CallDelegateNode node) {
    if (autoescapeMode == AutoescapeMode.NONCONTEXTUAL) {
        TemplateNode callee;/*from   ww w .  ja  v  a 2  s.c  o m*/
        Set<DelegateTemplateDivision> divisions = templateRegistry
                .getDelTemplateDivisionsForAllVariants((node).getDelCalleeName());
        if (divisions != null && !divisions.isEmpty()) {
            // As the callee is required only to know the kind of the content and as all templates in
            // delPackage are of the same kind it is sufficient to choose only the first template.
            DelegateTemplateDivision division = Iterables.getFirst(divisions, null);
            callee = Iterables.get(division.delPackageNameToDelTemplateMap.values(), 0);
            if (callee.getContentKind() == SanitizedContent.ContentKind.TEXT) {
                throw SoyAutoescapeException
                        .createWithNode(
                                "Calls to strict templates with 'kind=\"text\"' attribute is not permitted in "
                                        + "non-contextually autoescaped templates: " + node.toSourceString(),
                                node);
            }
        }
    }
    visitChildren(node);
}

From source file:com.google.gitiles.GitwebRedirectFilter.java

private static String getFirst(ListMultimap<String, String> params, String name) {
    return Iterables.getFirst(params.get(checkNotNull(name)), null);
}

From source file:fr.mby.opa.picsimpl.dao.DbProposalDao.java

@Override
public ProposalBranch findBranchByName(final long albumId, final String name) {
    final EmCallback<ProposalBranch> emCallback = new EmCallback<ProposalBranch>(this.getEmf()) {

        @Override/*ww w  .  j av  a2  s  .c om*/
        @SuppressWarnings("unchecked")
        protected ProposalBranch executeWithEntityManager(final EntityManager em) throws PersistenceException {
            final Query findBranchByNameQuery = em.createNamedQuery(ProposalBranch.FIND_BRANCH_BY_NAME);
            findBranchByNameQuery.setParameter("albumId", albumId);
            findBranchByNameQuery.setParameter("name", name);

            final ProposalBranch bag = Iterables.getFirst(findBranchByNameQuery.getResultList(), null);
            return bag;
        }
    };

    return emCallback.getReturnedValue();
}