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

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

Introduction

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

Prototype

public static <T> int indexOf(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns the index in iterable of the first element that satisfies the provided predicate , or -1 if the Iterable has no such elements.

Usage

From source file:org.sonar.cxx.checks.SwitchLastCaseIsDefaultCheck.java

@Override
public void visitNode(AstNode node) {
    List<AstNode> switchCases = getSwitchCases(node);
    int defaultCaseIndex = Iterables.indexOf(switchCases, DEFAULT_CASE_NODE_FILTER);

    if (defaultCaseIndex == -1) {
        getContext().createLineViolation(this, MISSING_DEFAULT_CASE_MESSAGE, node);
    } else {/*from w w w .j av a 2 s  . c o m*/
        AstNode defaultCase = Iterables.get(switchCases, defaultCaseIndex);

        if (!defaultCase.equals(Iterables.getLast(switchCases))) {
            getContext().createLineViolation(this, DEFAULT_CASE_IS_NOT_LAST_MESSAGE, defaultCase);
        }
    }
}

From source file:org.apache.druid.server.http.security.DatasourceResourceFilter.java

private String getRequestDatasourceName(ContainerRequest request) {
    final String dataSourceName = request.getPathSegments()
            .get(Iterables.indexOf(request.getPathSegments(), new Predicate<PathSegment>() {
                @Override/*  w w  w .  j av a2  s . com*/
                public boolean apply(PathSegment input) {
                    return "datasources".equals(input.getPath());
                }
            }) + 1).getPath();
    Preconditions.checkNotNull(dataSourceName);
    return dataSourceName;
}

From source file:org.apache.druid.indexing.overlord.http.security.TaskResourceFilter.java

@Override
public ContainerRequest filter(ContainerRequest request) {
    final String taskId = Preconditions.checkNotNull(request.getPathSegments()
            .get(Iterables.indexOf(request.getPathSegments(), new Predicate<PathSegment>() {
                @Override/*from w ww  . ja v a2  s .c om*/
                public boolean apply(PathSegment input) {
                    return "task".equals(input.getPath());
                }
            }) + 1).getPath());

    Optional<Task> taskOptional = taskStorageQueryAdapter.getTask(taskId);
    if (!taskOptional.isPresent()) {
        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
                .entity(StringUtils.format("Cannot find any task with id: [%s]", taskId)).build());
    }
    final String dataSourceName = Preconditions.checkNotNull(taskOptional.get().getDataSource());

    final ResourceAction resourceAction = new ResourceAction(
            new Resource(dataSourceName, ResourceType.DATASOURCE), getAction(request));

    final Access authResult = AuthorizationUtils.authorizeResourceAction(getReq(), resourceAction,
            getAuthorizerMapper());

    if (!authResult.isAllowed()) {
        throw new ForbiddenException(authResult.toString());
    }

    return request;
}

From source file:com.btmatthews.atlas.core.common.PagingBuilder.java

/**
 * Promote a sort ordering moving it up one position.
 *
 * @param name The sort field name.//from   ww w  . j a v a2 s . co m
 * @return Always returns the {@link PagingBuilder} object.
 */
public PagingBuilder promoteOrdering(final String name) {
    final int index = Iterables.indexOf(sortOrderings, findOrdering(name));
    if (index > 0) {
        final Ordering temp = sortOrderings.get(index - 1);
        sortOrderings.set(index - 1, sortOrderings.get(index));
        sortOrderings.set(index, temp);
    }
    return this;
}

From source file:org.xpect.util.IssueVisualizer.java

public String visualize(String documentString, Collection<Issue> issues) {
    Text document = new Text(documentString);
    @SuppressWarnings("unchecked")
    List<Issue>[] mapped = new List[document.length()];
    List<Issue> unmapped = Lists.newArrayList();
    for (Issue issue : issues) {
        if (issue.getOffset() != null && issue.getLength() != null && issue.getOffset() >= 0
                && issue.getOffset() < document.length() && issue.getLength() > 0) {
            int max = Math.min(issue.getOffset() + issue.getLength(), document.length());
            for (int i = issue.getOffset(); i < max; i++) {
                if (mapped[i] == null)
                    mapped[i] = Lists.newArrayList(issue);
                else
                    mapped[i].add(issue);
            }/*from ww w.  j a  v a2  s  . co  m*/
        } else
            unmapped.add(issue);
    }
    StringBuffer result = new StringBuffer();
    for (Issue issue : unmapped) {
        if (result.length() > 0)
            result.append(document.getNL());
        result.append(issueToString(issue));
    }
    boolean first = true;
    int offset = 0;
    for (String line : document.splitIntoLines()) {
        if (first)
            first = false;
        else
            result.append(document.getNL());
        result.append(line);
        boolean lineHasIssue = false;
        for (int i = offset; i < offset + line.length(); i++)
            if (mapped[i] != null)
                lineHasIssue = true;
        if (lineHasIssue) {
            result.append(document.getNL());
            Set<Issue> lineIssues = Sets.newLinkedHashSet();
            for (int i = offset; i < offset + line.length(); i++)
                if (mapped[i] != null) {
                    int mark = 0;
                    lineIssues.addAll(mapped[i]);
                    for (Issue issue : mapped[i])
                        mark += 1 << Iterables.indexOf(lineIssues, Predicates.equalTo(issue));
                    result.append(Integer.toHexString(mark));
                } else
                    result.append(document.charAt(i) == '\t' ? "\t" : " ");
            for (Issue issue : lineIssues) {
                int id = 1 << Iterables.indexOf(lineIssues, Predicates.equalTo(issue));
                result.append(document.getNL());
                result.append(id);
                result.append(": ");
                result.append(issueToString(issue));
            }
        }
        offset += line.length() + document.currentLineEndLenght(offset);
    }
    return result.toString();
}

From source file:com.btmatthews.atlas.core.common.PagingBuilder.java

/**
 * Demote a sort ordering moving it down one position.
 *
 * @param name The sort field name.//w ww . j av  a2  s .  c  o  m
 * @return Always returns the {@link PagingBuilder} object.
 */
public PagingBuilder demoteOrdering(final String name) {
    final int index = Iterables.indexOf(sortOrderings, findOrdering(name));
    if (index >= 0 && index < sortOrderings.size() - 1) {
        final Ordering temp = sortOrderings.get(index + 1);
        sortOrderings.set(index + 1, sortOrderings.get(index));
        sortOrderings.set(index, temp);
    }
    return this;
}

From source file:org.openehr.designer.user.UserConfigurationServiceImpl.java

@Override
public void saveRepository(String username, UserRepositoryConfiguration configuration) {
    UserRepositoriesConfiguration conf = getRepositoriesConfiguration(username);
    int existingIndex = Iterables.indexOf(conf.getRepositories(),
            r -> r.getName().equals(configuration.getName()));
    if (existingIndex >= 0) {
        conf.getRepositories().set(existingIndex, configuration);
    } else {//  ww w  . ja  va2  s.c o m
        conf.getRepositories().add(configuration);
    }
    writeConfiguration(getRepositoriesConfigurationPath(username), conf);
}

From source file:com.sahlbach.maven.delivery.Delivery.java

/**
 * orders the (merged) jobs according to their before and after attributes.
 * @throws MojoExecutionException in case the order attributes contain errors (non existing job references)
 *//*from w  w w . j  a va2s  .  c  o  m*/
public void orderJobs() throws MojoExecutionException {
    List<Job> result = Lists.newArrayList(Iterables.filter(jobs, new Predicate<Job>() {
        @Override
        public boolean apply(Job input) {
            return (StringUtils.isEmpty(input.getAfter()) && StringUtils.isEmpty(input.getBefore()));
        }
    }));
    List<Job> toSort = Lists.newArrayList(Iterables.filter(jobs, new Predicate<Job>() {
        @Override
        public boolean apply(Job input) {
            return (!StringUtils.isEmpty(input.getAfter()) || !StringUtils.isEmpty(input.getBefore()));
        }
    }));
    boolean sortedAtLeaseOne;
    do {
        sortedAtLeaseOne = false;
        for (Job job : toSort) {
            if (!StringUtils.isEmpty(job.getAfter())) {
                int foundIndex = Iterables.indexOf(result, new FindJobViaJobId(job.getAfter()));
                if (foundIndex > -1) {
                    result.add(foundIndex + 1, job);
                    sortedAtLeaseOne = true;
                }
            } else {
                int foundIndex = Iterables.indexOf(result, new FindJobViaJobId(job.getBefore()));
                if (foundIndex > -1) {
                    result.add(foundIndex, job);
                    sortedAtLeaseOne = true;
                }
            }
            toSort.remove(job);
        }
    } while (sortedAtLeaseOne);
    if (!toSort.isEmpty()) {
        throw new MojoExecutionException("Could not resolve the before or after references of job: "
                + Joiner.on(",").join(Lists.transform(toSort, new Function<Job, String>() {
                    @Override
                    public String apply(Job input) {
                        return input.getId();
                    }
                })));
    }
    jobs = result;
}

From source file:org.openehr.designer.user.UserConfigurationServiceImpl.java

@Override
public boolean deleteRepositoryByName(String username, String name) {
    UserRepositoriesConfiguration conf = getRepositoriesConfiguration(username);
    int existingIndex = Iterables.indexOf(conf.getRepositories(), r -> r.getName().equals(name));
    if (existingIndex < 0)
        return false;

    conf.getRepositories().remove(existingIndex);
    writeConfiguration(getRepositoriesConfigurationPath(username), conf);
    return true;/*from   www.j av a  2 s. c o m*/
}

From source file:gobblin.data.management.version.finder.DatePartitionHiveVersionFinder.java

/**
 * Create a {@link TimestampedHiveDatasetVersion} from a {@link Partition}. The hive table is expected
 * to be date partitioned by {@link #partitionKeyName}. The partition value format must be {@link #pattern}
 *
 * @throws IllegalArgumentException when {@link #partitionKeyName} is not found in the <code></code>
 * @throws IllegalArgumentException when a value can not be found for {@link #partitionKeyName} in the <code>partition</code>
 * @throws IllegalArgumentException if the partition value can not be parsed with {@link #pattern}
 * {@inheritDoc}//from   ww  w . j  ava 2 s.c  om
 */
@Override
protected TimestampedHiveDatasetVersion getDatasetVersion(Partition partition) {

    int index = Iterables.indexOf(partition.getTable().getPartitionKeys(), this.partitionKeyNamePredicate);

    if (index == -1) {
        throw new IllegalArgumentException(String.format("Failed to find partition key %s in the table %s",
                this.partitionKeyName, partition.getTable().getCompleteName()));
    }

    if (index >= partition.getValues().size()) {
        throw new IllegalArgumentException(
                String.format("Failed to find partition value for key %s in the partition %s",
                        this.partitionKeyName, partition.getName()));
    }
    return new TimestampedHiveDatasetVersion(this.formatter.parseDateTime(
            partition.getValues().get(index).trim().substring(0, this.pattern.length())), partition);
}