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:org.xpect.model.XpectFileImplCustom.java

@Override
public XpectTest getTest() {
    return Iterables.getFirst(Iterables.filter(getMembers(), XpectTest.class), null);
}

From source file:org.eclipse.sirius.diagram.sequence.ui.business.internal.diagramtype.SequenceCollapseUpdater.java

/**
 * {@inheritDoc}//www . j  ava  2s  .c  o  m
 * 
 * @see org.eclipse.sirius.diagram.business.api.helper.graphicalfilters.CollapseUpdater#getExpandedBounds(Node,
 *      DDiagramElement)
 */
@Override
public Option<Bounds> getExpandedBounds(Node node, DDiagramElement element) {
    Option<Bounds> optionalBounds;
    if (!specificCollapsePredicate.apply(element)) {
        optionalBounds = super.getExpandedBounds(node, element);
    } else {
        CollapseFilter filter = Iterables
                .getFirst(Iterables.filter(element.getGraphicalFilters(), CollapseFilter.class), null);
        if (filter != null) {
            optionalBounds = getExpandedBounds(node, new Dimension(filter.getWidth(), filter.getHeight()));
        } else {
            optionalBounds = Options.newNone();
        }
    }
    return optionalBounds;
}

From source file:io.druid.server.router.TieredBrokerHostSelector.java

public Pair<String, ServerDiscoverySelector> select(final Query<T> query) {
    synchronized (lock) {
        if (!ruleManager.isStarted() || !started) {
            return getDefaultLookup();
        }/* ww  w. jav  a 2  s .c  o m*/
    }

    String brokerServiceName = null;

    for (TieredBrokerSelectorStrategy strategy : strategies) {
        final Optional<String> optionalName = strategy.getBrokerServiceName(tierConfig, query);
        if (optionalName.isPresent()) {
            brokerServiceName = optionalName.get();
            break;
        }
    }

    if (brokerServiceName == null) {
        // For Union Queries tier will be selected on the rules for first dataSource.
        List<Rule> rules = ruleManager
                .getRulesWithDefault(Iterables.getFirst(query.getDataSource().getNames(), null));

        // find the rule that can apply to the entire set of intervals
        DateTime now = new DateTime();
        int lastRulePosition = -1;
        LoadRule baseRule = null;

        for (Interval interval : query.getIntervals()) {
            int currRulePosition = 0;
            for (Rule rule : rules) {
                if (rule instanceof LoadRule && currRulePosition > lastRulePosition
                        && rule.appliesTo(interval, now)) {
                    lastRulePosition = currRulePosition;
                    baseRule = (LoadRule) rule;
                    break;
                }
                currRulePosition++;
            }
        }

        if (baseRule == null) {
            return getDefaultLookup();
        }

        // in the baseRule, find the broker of highest priority
        for (Map.Entry<String, String> entry : tierConfig.getTierToBrokerMap().entrySet()) {
            if (baseRule.getTieredReplicants().containsKey(entry.getKey())) {
                brokerServiceName = entry.getValue();
                break;
            }
        }
    }

    if (brokerServiceName == null) {
        log.error("WTF?! No brokerServiceName found for datasource[%s], intervals[%s]. Using default[%s].",
                query.getDataSource(), query.getIntervals(), tierConfig.getDefaultBrokerServiceName());
        brokerServiceName = tierConfig.getDefaultBrokerServiceName();
    }

    ServerDiscoverySelector retVal = selectorMap.get(brokerServiceName);

    if (retVal == null) {
        log.error("WTF?! No selector found for brokerServiceName[%s]. Using default selector for[%s]",
                brokerServiceName, tierConfig.getDefaultBrokerServiceName());
        retVal = selectorMap.get(tierConfig.getDefaultBrokerServiceName());
    }

    return new Pair<>(brokerServiceName, retVal);
}

From source file:co.cask.cdap.templates.DefaultAdapterConfigurer.java

/**
 * Gets the program Id of the app template for this adapter.
 *///from ww w  .  ja v a  2s .c  o m
private Id.Program getProgramId(Id.Namespace namespaceId, ApplicationSpecification templateSpec) {
    // Get the program spec. Either one should be non-null, but not both. Also, both cannot be null.
    // It was verified during the template deployment time.
    ProgramSpecification programSpec = Objects.firstNonNull(
            Iterables.getFirst(templateSpec.getWorkers().values(), null),
            Iterables.getFirst(templateSpec.getWorkflows().values(), null));

    ProgramType programType = (programSpec instanceof WorkerSpecification) ? ProgramType.WORKER
            : ProgramType.WORKFLOW;
    return Id.Program.from(namespaceId, templateSpec.getName(), programType, programSpec.getName());
}

From source file:com.google.gerrit.server.project.ConfigInfo.java

public ConfigInfo(boolean serverEnableSignedPush, ProjectControl control, TransferConfig config,
        DynamicMap<ProjectConfigEntry> pluginConfigEntries, PluginConfigFactory cfgFactory,
        AllProjectsNameProvider allProjects, DynamicMap<RestView<ProjectResource>> views) {
    ProjectState projectState = control.getProjectState();
    Project p = control.getProject();/*from   ww w  . j a v a 2 s  .com*/
    this.description = Strings.emptyToNull(p.getDescription());

    InheritedBooleanInfo useContributorAgreements = new InheritedBooleanInfo();
    InheritedBooleanInfo useSignedOffBy = new InheritedBooleanInfo();
    InheritedBooleanInfo useContentMerge = new InheritedBooleanInfo();
    InheritedBooleanInfo requireChangeId = new InheritedBooleanInfo();
    InheritedBooleanInfo createNewChangeForAllNotInTarget = new InheritedBooleanInfo();
    InheritedBooleanInfo enableSignedPush = new InheritedBooleanInfo();
    InheritedBooleanInfo requireSignedPush = new InheritedBooleanInfo();

    useContributorAgreements.value = projectState.isUseContributorAgreements();
    useSignedOffBy.value = projectState.isUseSignedOffBy();
    useContentMerge.value = projectState.isUseContentMerge();
    requireChangeId.value = projectState.isRequireChangeID();
    createNewChangeForAllNotInTarget.value = projectState.isCreateNewChangeForAllNotInTarget();

    useContributorAgreements.configuredValue = p.getUseContributorAgreements();
    useSignedOffBy.configuredValue = p.getUseSignedOffBy();
    useContentMerge.configuredValue = p.getUseContentMerge();
    requireChangeId.configuredValue = p.getRequireChangeID();
    createNewChangeForAllNotInTarget.configuredValue = p.getCreateNewChangeForAllNotInTarget();
    enableSignedPush.configuredValue = p.getEnableSignedPush();
    requireSignedPush.configuredValue = p.getRequireSignedPush();

    ProjectState parentState = Iterables.getFirst(projectState.parents(), null);
    if (parentState != null) {
        useContributorAgreements.inheritedValue = parentState.isUseContributorAgreements();
        useSignedOffBy.inheritedValue = parentState.isUseSignedOffBy();
        useContentMerge.inheritedValue = parentState.isUseContentMerge();
        requireChangeId.inheritedValue = parentState.isRequireChangeID();
        createNewChangeForAllNotInTarget.inheritedValue = parentState.isCreateNewChangeForAllNotInTarget();
        enableSignedPush.inheritedValue = projectState.isEnableSignedPush();
        requireSignedPush.inheritedValue = projectState.isRequireSignedPush();
    }

    this.useContributorAgreements = useContributorAgreements;
    this.useSignedOffBy = useSignedOffBy;
    this.useContentMerge = useContentMerge;
    this.requireChangeId = requireChangeId;
    this.createNewChangeForAllNotInTarget = createNewChangeForAllNotInTarget;
    if (serverEnableSignedPush) {
        this.enableSignedPush = enableSignedPush;
        this.requireSignedPush = requireSignedPush;
    }

    MaxObjectSizeLimitInfo maxObjectSizeLimit = new MaxObjectSizeLimitInfo();
    maxObjectSizeLimit.value = config.getEffectiveMaxObjectSizeLimit(projectState) == config
            .getMaxObjectSizeLimit() ? config.getFormattedMaxObjectSizeLimit() : p.getMaxObjectSizeLimit();
    maxObjectSizeLimit.configuredValue = p.getMaxObjectSizeLimit();
    maxObjectSizeLimit.inheritedValue = config.getFormattedMaxObjectSizeLimit();
    this.maxObjectSizeLimit = maxObjectSizeLimit;

    this.submitType = p.getSubmitType();
    this.state = p.getState() != com.google.gerrit.extensions.client.ProjectState.ACTIVE ? p.getState() : null;

    this.commentlinks = Maps.newLinkedHashMap();
    for (CommentLinkInfo cl : projectState.getCommentLinks()) {
        this.commentlinks.put(cl.name, cl);
    }

    pluginConfig = getPluginConfig(control.getProjectState(), pluginConfigEntries, cfgFactory, allProjects);

    actions = Maps.newTreeMap();
    for (UiAction.Description d : UiActions.from(views, new ProjectResource(control),
            Providers.of(control.getUser()))) {
        actions.put(d.getId(), new ActionInfo(d));
    }
    this.theme = projectState.getTheme();
}

From source file:org.apache.metron.elasticsearch.writer.ElasticsearchWriter.java

List<HostnamePort> getIps(Map<String, Object> globalConfiguration) {
    Object ipObj = globalConfiguration.get("es.ip");
    Object portObj = globalConfiguration.get("es.port");
    if (ipObj == null) {
        return Collections.emptyList();
    }//from   w ww  . j ava 2s . co  m
    if (ipObj instanceof String && ipObj.toString().contains(",") && ipObj.toString().contains(":")) {
        List<String> ips = Arrays.asList(((String) ipObj).split(","));
        List<HostnamePort> ret = new ArrayList<>();
        for (String ip : ips) {
            Iterable<String> tokens = Splitter.on(":").split(ip);
            String host = Iterables.getFirst(tokens, null);
            String portStr = Iterables.getLast(tokens, null);
            ret.add(new HostnamePort(host, Integer.parseInt(portStr)));
        }
        return ret;
    } else if (ipObj instanceof String && ipObj.toString().contains(",")) {
        List<String> ips = Arrays.asList(((String) ipObj).split(","));
        List<HostnamePort> ret = new ArrayList<>();
        for (String ip : ips) {
            ret.add(new HostnamePort(ip, Integer.parseInt(portObj + "")));
        }
        return ret;
    } else if (ipObj instanceof String && !ipObj.toString().contains(":")) {
        return ImmutableList.of(new HostnamePort(ipObj.toString(), Integer.parseInt(portObj + "")));
    } else if (ipObj instanceof String && ipObj.toString().contains(":")) {
        Iterable<String> tokens = Splitter.on(":").split(ipObj.toString());
        String host = Iterables.getFirst(tokens, null);
        String portStr = Iterables.getLast(tokens, null);
        return ImmutableList.of(new HostnamePort(host, Integer.parseInt(portStr)));
    } else if (ipObj instanceof List) {
        List<String> ips = (List) ipObj;
        List<HostnamePort> ret = new ArrayList<>();
        for (String ip : ips) {
            Iterable<String> tokens = Splitter.on(":").split(ip);
            String host = Iterables.getFirst(tokens, null);
            String portStr = Iterables.getLast(tokens, null);
            ret.add(new HostnamePort(host, Integer.parseInt(portStr)));
        }
        return ret;
    }
    throw new IllegalStateException(
            "Unable to read the elasticsearch ips, expected es.ip to be either a list of strings, a string hostname or a host:port string");
}

From source file:net.minecraftforge.fml.common.asm.transformers.AccessTransformer.java

protected void processATFile(CharSource rulesResource) throws IOException {
    rulesResource.readLines(new LineProcessor<Void>() {
        @Override//from   w w  w.j  av a2s  .com
        public Void getResult() {
            return null;
        }

        @Override
        public boolean processLine(String input) throws IOException {
            String line = Iterables.getFirst(Splitter.on('#').limit(2).split(input), "").trim();
            if (line.length() == 0) {
                return true;
            }
            List<String> parts = Lists.newArrayList(Splitter.on(" ").trimResults().split(line));
            if (parts.size() > 3) {
                throw new RuntimeException("Invalid config file line " + input);
            }
            Modifier m = new Modifier();
            m.setTargetAccess(parts.get(0));

            if (parts.size() == 2) {
                m.modifyClassVisibility = true;
            } else {
                String nameReference = parts.get(2);
                int parenIdx = nameReference.indexOf('(');
                if (parenIdx > 0) {
                    m.desc = nameReference.substring(parenIdx);
                    m.name = nameReference.substring(0, parenIdx);
                } else {
                    m.name = nameReference;
                }
            }
            String className = parts.get(1).replace('/', '.');
            modifiers.put(className, m);
            if (DEBUG)
                System.out.printf("AT RULE: %s %s %s (type %s)\n", toBinary(m.targetAccess), m.name, m.desc,
                        className);
            return true;
        }
    });
}

From source file:org.elasticsearch.index.query.IdsFilterParser.java

@Override
public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
    XContentParser parser = parseContext.parser();

    List<BytesRef> ids = new ArrayList<>();
    Collection<String> types = null;
    String filterName = null;/*from   ww w .j  ava2 s  . c o m*/
    String currentFieldName = null;
    XContentParser.Token token;
    boolean idsProvided = false;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.START_ARRAY) {
            if ("values".equals(currentFieldName)) {
                idsProvided = true;
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    BytesRef value = parser.bytesOrNull();
                    if (value == null) {
                        throw new QueryParsingException(parseContext.index(),
                                "No value specified for term filter");
                    }
                    ids.add(value);
                }
            } else if ("types".equals(currentFieldName) || "type".equals(currentFieldName)) {
                types = new ArrayList<>();
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    String value = parser.textOrNull();
                    if (value == null) {
                        throw new QueryParsingException(parseContext.index(),
                                "No type specified for term filter");
                    }
                    types.add(value);
                }
            } else {
                throw new QueryParsingException(parseContext.index(),
                        "[ids] filter does not support [" + currentFieldName + "]");
            }
        } else if (token.isValue()) {
            if ("type".equals(currentFieldName) || "_type".equals(currentFieldName)) {
                types = ImmutableList.of(parser.text());
            } else if ("_name".equals(currentFieldName)) {
                filterName = parser.text();
            } else {
                throw new QueryParsingException(parseContext.index(),
                        "[ids] filter does not support [" + currentFieldName + "]");
            }
        }
    }

    if (!idsProvided) {
        throw new QueryParsingException(parseContext.index(),
                "[ids] filter requires providing a values element");
    }

    if (ids.isEmpty()) {
        return Queries.MATCH_NO_FILTER;
    }

    if (types == null || types.isEmpty()) {
        types = parseContext.queryTypes();
    } else if (types.size() == 1 && Iterables.getFirst(types, null).equals("_all")) {
        types = parseContext.mapperService().types();
    }

    TermsFilter filter = new TermsFilter(UidFieldMapper.NAME, Uid.createTypeUids(types, ids));
    if (filterName != null) {
        parseContext.addNamedFilter(filterName, filter);
    }
    return filter;
}

From source file:org.jclouds.aws.ec2.compute.extensions.AWSEC2SecurityGroupExtension.java

@Override
public boolean removeSecurityGroup(String id) {
    checkNotNull(id, "id");
    String[] parts = AWSUtils.parseHandle(id);
    String region = parts[0];//from   ww  w  .java2  s.  c om
    String groupId = parts[1];

    org.jclouds.ec2.domain.SecurityGroup group = Iterables.getFirst(
            client.getSecurityGroupApi().get().describeSecurityGroupsInRegionById(region, groupId), null);

    if (group != null) {
        client.getSecurityGroupApi().get().deleteSecurityGroupInRegionById(region, groupId);
        // TODO: test this clear happens
        groupCreator.invalidate(new RegionNameAndIngressRules(region, group.getName(), null, false));
        return true;
    }

    return false;
}

From source file:com.google.api.server.spi.discovery.ProxyingDiscoveryProvider.java

private String getApiConfigStringWithRoot(ImmutableList<ApiConfig> configs, final String root)
        throws InternalServerErrorException, ApiConfigException {
    Map<ApiKey, String> configMap = configWriter.writeConfig(rewriteConfigsWithRoot(configs, root));
    if (configMap.size() != 1) {
        logger.severe("config generation yielded more than one API");
        throw new InternalServerErrorException("Internal Server Error");
    }/* ww w  .  j av a2 s .  c om*/
    return Iterables.getFirst(configMap.values(), null);
}