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

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

Introduction

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

Prototype

@Nullable
public static <T> T find(Iterable<? extends T> iterable, Predicate<? super T> predicate,
        @Nullable T defaultValue) 

Source Link

Document

Returns the first element in iterable that satisfies the given predicate, or defaultValue if none found.

Usage

From source file:org.sonar.server.issue.IssueBulkChangeService.java

private Action getAction(final String actionKey) {
    Action action = Iterables.find(actions, new ActionMatchKey(actionKey), null);
    if (action == null) {
        throw new BadRequestException("The action : '" + actionKey + "' is unknown");
    }/*  w ww  .j a  v a2 s .c o m*/
    return action;
}

From source file:org.sonar.server.debt.DebtModelBackup.java

@CheckForNull
private static RulesDefinition.Rule ruleDef(String ruleRepo, String ruleKey, List<RulesDefinition.Rule> rules) {
    return Iterables.find(rules, new RuleDefMatchRuleRepoAndRuleKey(ruleRepo, ruleKey), null);
}

From source file:org.jfrog.build.api.builder.BuildInfoMavenBuilder.java

private Module findModule(final String moduleKey) {
    return Iterables.find(modules, new Predicate<Module>() {
        public boolean apply(Module input) {
            return input.getId().equals(moduleKey);
        }//from  ww w. ja  v a 2 s  .  c  o m
    }, null);
}

From source file:org.sonar.server.rule.DeprecatedRulesDefinition.java

@CheckForNull
private RuleDebt findRequirement(List<RuleDebt> requirements, final String repoKey, final String ruleKey) {
    return Iterables.find(requirements, new Predicate<RuleDebt>() {
        @Override/* www . j  a v  a 2  s  .  c  o m*/
        public boolean apply(RuleDebt input) {
            return input.ruleKey().equals(RuleKey.of(repoKey, ruleKey));
        }
    }, null);
}

From source file:com.microsoft.intellij.helpers.o365.Office365ManagerImpl.java

@Override
@NotNull//from   ww w .  j a va 2  s .  c om
public ListenableFuture<List<ServicePermissionEntry>> getO365PermissionsForApp(@NotNull final String objectId) {
    return requestFutureWithToken(new RequestCallback<ListenableFuture<List<ServicePermissionEntry>>>() {
        @Override
        public ListenableFuture<List<ServicePermissionEntry>> execute() throws Throwable {
            return Futures.transform(getApplicationByObjectId(objectId),
                    new AsyncFunction<Application, List<ServicePermissionEntry>>() {
                        @Override
                        public ListenableFuture<List<ServicePermissionEntry>> apply(Application application)
                                throws Exception {

                            final String[] filterAppIds = new String[] { ServiceAppIds.SHARE_POINT,
                                    ServiceAppIds.EXCHANGE, ServiceAppIds.AZURE_ACTIVE_DIRECTORY };

                            // build initial list of permission from the app's permissions
                            final List<ServicePermissionEntry> servicePermissions = getO365PermissionsFromResourceAccess(
                                    application.getrequiredResourceAccess(), filterAppIds);

                            // get permissions list from O365 service principals
                            return Futures.transform(getServicePrincipalsForO365(),
                                    new AsyncFunction<List<ServicePrincipal>, List<ServicePermissionEntry>>() {
                                        @Override
                                        public ListenableFuture<List<ServicePermissionEntry>> apply(
                                                List<ServicePrincipal> servicePrincipals) throws Exception {

                                            for (final ServicePrincipal servicePrincipal : servicePrincipals) {
                                                // lookup this service principal in app's list of resources; if it's not found add an entry
                                                ServicePermissionEntry servicePermissionEntry = Iterables.find(
                                                        servicePermissions,
                                                        new Predicate<ServicePermissionEntry>() {
                                                            @Override
                                                            public boolean apply(
                                                                    ServicePermissionEntry servicePermissionEntry) {
                                                                return servicePermissionEntry.getKey().getId()
                                                                        .equals(servicePrincipal.getappId());
                                                            }
                                                        }, null);

                                                if (servicePermissionEntry == null) {
                                                    servicePermissions.add(
                                                            servicePermissionEntry = new ServicePermissionEntry(
                                                                    new Office365Service(),
                                                                    new Office365PermissionList()));
                                                }

                                                Office365Service service = servicePermissionEntry.getKey();
                                                Office365PermissionList permissionList = servicePermissionEntry
                                                        .getValue();
                                                service.setId(servicePrincipal.getappId());
                                                service.setName(servicePrincipal.getdisplayName());

                                                List<OAuth2Permission> permissions = servicePrincipal
                                                        .getoauth2Permissions();
                                                for (final OAuth2Permission permission : permissions) {
                                                    // lookup permission in permissionList
                                                    Office365Permission office365Permission = Iterables.find(
                                                            permissionList,
                                                            new Predicate<Office365Permission>() {
                                                                @Override
                                                                public boolean apply(
                                                                        Office365Permission office365Permission) {
                                                                    return office365Permission.getId().equals(
                                                                            permission.getid().toString());
                                                                }
                                                            }, null);

                                                    if (office365Permission == null) {
                                                        permissionList.add(
                                                                office365Permission = new Office365Permission());
                                                        office365Permission.setEnabled(false);
                                                    }

                                                    office365Permission.setId(permission.getid().toString());
                                                    office365Permission.setName(
                                                            getPermissionDisplayName(permission.getvalue()));
                                                    office365Permission.setDescription(
                                                            permission.getuserConsentDisplayName());
                                                }
                                            }

                                            return Futures.immediateFuture(servicePermissions);
                                        }
                                    });
                        }
                    });
        }
    });
}

From source file:org.eclipse.incquery.patternlanguage.helper.CorePatternLanguageHelper.java

/**
 * Returns the first annotation of a given name from a pattern. This method ignores multiple defined annotations by
 * the same name. For getting a filtered collections of annotations, see
 * {@link #getAnnotationsByName(Pattern, String)}
 * //from ww w .  j  a v  a2s. co  m
 * @param pattern
 *            the pattern instance
 * @param name
 *            the name of the annotation to return
 * @returns the first annotation or null if no such annotation exists
 * @since 0.7.0
 */
public static Annotation getFirstAnnotationByName(Pattern pattern, String name) {
    return Iterables.find(pattern.getAnnotations(), new AnnotationNameFilter(name), null);
}

From source file:org.polarsys.reqcycle.repository.connector.document.DocParser.java

public void run(RequirementSource requirementSource) throws Exception {
    Scope scope = PropertyUtils.getScopeFromSource(requirementSource);
    requirementSource.clearContent();//from   w  ww .  ja va 2s .c o  m
    ArrayList<DocRequirementModele> listReqModele = new ArrayList<DocRequirementModele>();
    List<DocSectionModele> listSectionModele = new ArrayList<DocSectionModele>();

    //---------------------PART1 - per treatment ------------------------//
    //remove the excluded area in a document
    String finalDoc = getFinalDocument();

    //--------------------- PART1 - create sections ----------------------//
    listSectionModele = createSections(requirementSource);

    //sorting the list listSectionModele per end position of the Section
    if (listSectionModele != null) {
        Collections.sort(listSectionModele, new Comparator<DocSectionModele>() {

            @Override
            public int compare(DocSectionModele sec1, DocSectionModele sec2) {
                return (sec1.getPosition() < sec2.getPosition()) ? -1
                        : (sec1.getPosition() > sec2.getPosition()) ? 1 : 0;
            }
        });

        //--------------------- PART2 - sorting all requirements in document----------------------//
        if (requirementSource.getMappings() != null) {
            //transform a requirement input to model requirement. A model requirement is a requirement plus a position in document
            for (MappingElement reqIn : requirementSource.getMappings()) {

                Pattern pattern = Pattern.compile(reqIn.getSourceQualifier(),
                        Pattern.MULTILINE | Pattern.DOTALL);
                Matcher matcher = pattern.matcher(finalDoc);
                // check all occurrence of a requirement
                while (matcher.find()) {
                    if (matcher.groupCount() > 0) {
                        if (LogUtils.isDebug()) {
                            System.out.println("req " + matcher.group(1) + " --- position : " + matcher.end());
                        }
                        listReqModele.add(new DocRequirementModele(matcher.end(), reqIn, matcher.group(1)));
                    } else {
                        if (LogUtils.isDebug()) {
                            LogUtils.log("req " + matcher.group() + " --- position : " + matcher.end());
                        }
                        listReqModele.add(new DocRequirementModele(matcher.end(), reqIn, matcher.group()));
                    }

                }
            }

            //sorting the list ListReqModele per end position of the requirement
            if (listReqModele != null) {
                Collections.sort(listReqModele, new Comparator<DocRequirementModele>() {

                    @Override
                    public int compare(DocRequirementModele req1, DocRequirementModele req2) {
                        return (req1.getPosition() < req2.getPosition()) ? -1
                                : (req1.getPosition() > req2.getPosition()) ? 1 : 0;
                    }
                });
            }
        }

    }

    //-------------------PART3 -- parsing all requirements and attributes ------------------------// 

    for (int i = 0; i < listReqModele.size(); i++) {
        IRequirementType requirementType = (IRequirementType) PropertyUtils
                .getDataModelFromSource(requirementSource)
                .getType(listReqModele.get(i).getRequirement().getDescription());
        if (requirementType == null) {
            //error
            if (LogUtils.isDebug()) {
                System.out.println("the requirementType " + requirementType + " is nul");
            }
        }

        String startReq = listReqModele.get(i).getResult();
        String endReq = "\\Z";
        if (i + 1 < listReqModele.size()) {
            endReq = listReqModele.get(i + 1).getResult();
        }
        Pattern patternS = Pattern.compile("(" + startReq + ".*?)" + endReq,
                Pattern.MULTILINE | Pattern.DOTALL);
        Matcher matcherS = patternS.matcher(finalDoc);

        String documentSection = " ";
        while (matcherS.find()) {
            if (matcherS.groupCount() > 0) {
                if (LogUtils.isDebug()) {
                    System.out.println("req " + matcherS.group(1) + " ------- position : " + matcherS.end());
                }
                documentSection = matcherS.group(1);
            } else {
                if (LogUtils.isDebug()) {
                    System.out.println("req " + matcherS.group() + " ------- position : " + matcherS.end());
                }
                documentSection = matcherS.group();
            }

        }

        Pattern pattern = Pattern.compile(listReqModele.get(i).getRequirement().getSourceQualifier(),
                Pattern.MULTILINE | Pattern.DOTALL);
        Matcher matcher = pattern.matcher(documentSection);
        // check all occurrence of a requirement
        while (matcher.find()) {
            org.polarsys.reqcycle.repository.data.RequirementSourceData.Requirement requirement = requirementType
                    .createInstance();
            if (matcher.groupCount() > 0) {
                if (LogUtils.isDebug()) {
                    System.out.println(matcher.group(1));
                }
                requirement.setId(matcher.group(1));
            } else {
                if (LogUtils.isDebug()) {
                    System.out.println(matcher.group());
                }
                requirement.setId(matcher.group());
            }
            //add scope in requirement
            requirement.getScopes().add(scope);

            //check all attributes of a current requirement
            List<MappingAttribute> Attributes = listReqModele.get(i).getRequirement().getAttributes();

            for (final MappingAttribute att : Attributes) {
                Pattern patternAtt = Pattern.compile(att.getSourceId(), Pattern.MULTILINE | Pattern.DOTALL);
                Matcher matcherAtt = patternAtt.matcher(documentSection);
                while (matcherAtt.find()) {
                    IAttribute attFromType = Iterables.find(requirementType.getAttributes(),
                            new Predicate<IAttribute>() {
                                @Override
                                public boolean apply(IAttribute arg0) {
                                    return arg0.getName().equals(att.getDescription());
                                }
                            }, null);
                    Object value = null;
                    if (attFromType == null) {
                        // error
                        if (LogUtils.isDebug()) {
                            System.out.println("the attFromType " + attFromType + " is nul");
                        }
                    } else {
                        String stringFromDocument = null;
                        if (matcherAtt.groupCount() > 0) {
                            stringFromDocument = matcherAtt.group(1);
                        } else {
                            stringFromDocument = matcherAtt.group();
                        }
                        if (LogUtils.isDebug()) {
                            System.out.println("att : " + att.getDescription() + " :" + stringFromDocument);
                        }
                        value = getValueFromString(stringFromDocument, attFromType.getType());
                    }
                    manager.addAttributeValue(requirement, attFromType, value);
                }

            }
            org.polarsys.reqcycle.repository.data.RequirementSourceData.Section sect = findSectionForRequirement(
                    listReqModele.get(i).getPosition(), listSectionModele);
            manager.addElementsToSection(sect, requirement);

        }
    }
}

From source file:com.google.devtools.build.lib.skyframe.LocalRepositoryLookupFunction.java

/**
 * Checks whether the directory exists and is a workspace root. Returns {@link Optional#absent()}
 * if Skyframe needs to re-run, {@link Optional#of(LocalRepositoryLookupValue)} otherwise.
 *///from   w  w  w .ja  v a2s  .c  o  m
private Optional<LocalRepositoryLookupValue> maybeCheckWorkspaceForRepository(Environment env,
        final RootedPath directory) throws InterruptedException, LocalRepositoryLookupFunctionException {
    // Look up the main WORKSPACE file by the external package, to find all repositories.
    PackageLookupValue externalPackageLookupValue;
    try {
        externalPackageLookupValue = (PackageLookupValue) env.getValueOrThrow(
                PackageLookupValue.key(Label.EXTERNAL_PACKAGE_IDENTIFIER), BuildFileNotFoundException.class,
                InconsistentFilesystemException.class);
        if (externalPackageLookupValue == null) {
            return Optional.absent();
        }
    } catch (BuildFileNotFoundException e) {
        throw new LocalRepositoryLookupFunctionException(
                new ErrorDeterminingRepositoryException(
                        "BuildFileNotFoundException while loading the //external package", e),
                Transience.PERSISTENT);
    } catch (InconsistentFilesystemException e) {
        throw new LocalRepositoryLookupFunctionException(
                new ErrorDeterminingRepositoryException(
                        "InconsistentFilesystemException while loading the //external package", e),
                Transience.PERSISTENT);
    }

    RootedPath workspacePath = externalPackageLookupValue.getRootedPath(Label.EXTERNAL_PACKAGE_IDENTIFIER);

    SkyKey workspaceKey = WorkspaceFileValue.key(workspacePath);
    do {
        WorkspaceFileValue value;
        try {
            value = (WorkspaceFileValue) env.getValueOrThrow(workspaceKey, PackageFunctionException.class,
                    NameConflictException.class);
            if (value == null) {
                return Optional.absent();
            }
        } catch (PackageFunctionException e) {
            // TODO(jcater): When WFF is rewritten to not throw a PFE, update this.
            throw new LocalRepositoryLookupFunctionException(
                    new ErrorDeterminingRepositoryException(
                            "PackageFunctionException while loading the root WORKSPACE file", e),
                    Transience.PERSISTENT);
        } catch (NameConflictException e) {
            throw new LocalRepositoryLookupFunctionException(
                    new ErrorDeterminingRepositoryException(
                            "NameConflictException while loading the root WORKSPACE file", e),
                    Transience.PERSISTENT);
        }

        Package externalPackage = value.getPackage();
        if (externalPackage.containsErrors()) {
            Event.replayEventsOn(env.getListener(), externalPackage.getEvents());
        }

        // Find all local_repository rules in the WORKSPACE, and check if any have a "path" attribute
        // the same as the requested directory.
        Iterable<Rule> localRepositories = externalPackage.getRulesMatchingRuleClass(LocalRepositoryRule.NAME);
        Rule rule = Iterables.find(localRepositories, new Predicate<Rule>() {
            @Override
            public boolean apply(@Nullable Rule rule) {
                AggregatingAttributeMapper mapper = AggregatingAttributeMapper.of(rule);
                PathFragment pathAttr = new PathFragment(mapper.get("path", Type.STRING));
                return directory.getRelativePath().equals(pathAttr);
            }
        }, null);
        if (rule != null) {
            try {
                return Optional
                        .of(LocalRepositoryLookupValue.success(RepositoryName.create("@" + rule.getName())));
            } catch (LabelSyntaxException e) {
                // This shouldn't be possible if the rule name is valid, and it should already have been
                // validated.
                throw new LocalRepositoryLookupFunctionException(new ErrorDeterminingRepositoryException(
                        "LabelSyntaxException while creating the repository name from the rule "
                                + rule.getName(),
                        e), Transience.PERSISTENT);
            }
        }
        workspaceKey = value.next();

        // TODO(bazel-team): This loop can be quadratic in the number of load() statements, consider
        // rewriting or unrolling.
    } while (workspaceKey != null);

    return Optional.of(LocalRepositoryLookupValue.notFound());
}

From source file:io.soabase.zookeeper.discovery.ZooKeeperDiscovery.java

private FoundInstance findInstanceFromProvider(String serviceName, final SoaDiscoveryInstance instanceToFind) {
    ServiceInstance<Payload> foundInstance = null;
    ServiceProvider<Payload> provider = providers.getUnchecked(serviceName);
    if (provider != null) {
        try {//w  ww . j a  v a  2 s.c o m
            foundInstance = Iterables.find(provider.getAllInstances(),
                    new Predicate<ServiceInstance<Payload>>() {
                        @Override
                        public boolean apply(ServiceInstance<Payload> instance) {
                            return instanceToFind.getId().equals(instance.getId());
                        }
                    }, null);
        } catch (Exception e) {
            // TODO logging
            throw new RuntimeException(e);
        }
    }
    return (foundInstance != null) ? new FoundInstance(foundInstance, provider) : null;
}

From source file:com.groupon.jenkins.dynamic.build.DynamicProject.java

public Iterable<DynamicSubProject> getSubProjects(final Iterable<Combination> subBuildCombinations) {

    return Iterables.transform(subBuildCombinations, new Function<Combination, DynamicSubProject>() {

        @Override// w w w. j  a v a2s.  co  m
        public DynamicSubProject apply(final Combination requestedCombination) {
            final DynamicSubProject subProject = Iterables.find(getItems(), new Predicate<DynamicSubProject>() {

                @Override
                public boolean apply(final DynamicSubProject subProject) {
                    return requestedCombination.equals(subProject.getCombination());
                }
            }, null);
            return subProject == null ? DynamicProject.this.createNewSubProject(requestedCombination)
                    : subProject;
        }

    });
}