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:gov.nih.nci.firebird.test.data.SuperUserBuilder.java

protected SuperUserBuilder(TargetGridResources gridResources, TestDataLoader dataLoader,
        Iterator<? extends LoginAccount> loginIterator) {
    super(gridResources, dataLoader, loginIterator);
    profile.setPerson(getUser().getPerson());
    profile.setPrimaryOrganization(/*from   ww  w  . ja  v a  2 s  .  c om*/
            new PrimaryOrganization(getNesOrganization(), PrimaryOrganizationType.HEALTH_CARE_FACILITY));
    getUser().createInvestigatorRole(profile);

    Set<Organization> sponsors = getSponsorsWithProtocolRegistrationsOrganization();
    getUser().addSponsorRepresentativeRole(Iterables.getFirst(sponsors, null));
    getUser().addSponsorDelegateRole(Iterables.getLast(sponsors));
}

From source file:org.openmrs.module.webservices.rest.resource.ItemResource.java

private void setNewDefaultPrice(Item instance, final String price, final String name) {
    Collection<ItemPrice> results = Collections2.filter(instance.getPrices(), new Predicate<ItemPrice>() {
        @Override//from   w  w w  .ja va2  s  .co m
        public boolean apply(@Nullable ItemPrice itemPrice) {
            if (itemPrice != null) {
                String itemPriceName = itemPrice.getName();
                if (itemPrice.getPrice().toPlainString().equals(price)
                        && namesEqualOrBlank(itemPriceName, name)) {
                    return true;
                }
            }

            return false;
        }

    });

    if (results != null && results.size() > 0) {
        instance.setDefaultPrice(Iterables.getFirst(results, null));
    } else {
        // If there are no matches in the current price set, save the price in a new ItemPrice to hopefully be
        // updated later, in case we haven't set new prices yet.
        instance.setDefaultPrice(new ItemPrice(new BigDecimal(price), ""));
    }
}

From source file:org.eclipse.elk.alg.mrtree.p3place.NodePlacer.java

/**
 * In this first postorder walk, every node of the tree is assigned a preliminary x-coordinate
 * (held in property PRELIM). In addition, internal nodes are given modifiers, which will be
 * used to move their offspring to the right (held in property MODIFIER).
 * //from   ww  w  . j  a va  2s  .  co m
 * @param cN
 *            the root level of the tree
 * @param level
 *            the index of the passed level
 */
private void firstWalk(final TNode cN, final int level) {
    cN.setProperty(InternalProperties.MODIFIER, 0d);
    TNode lS = cN.getProperty(InternalProperties.LEFTSIBLING);

    if (cN.isLeaf()) {
        if (lS != null) {
            /**
             * Determine the preliminary x-coordinate based on: the preliminary x-coordinate of
             * the left sibling, the separation between sibling nodes, and tHe mean size of left
             * sibling and current node.
             */
            double p = lS.getProperty(InternalProperties.PRELIM) + spacing + meanNodeWidth(lS, cN);
            cN.setProperty(InternalProperties.PRELIM, p);
        } else {
            /** No sibling on the left to worry about. */
            cN.setProperty(InternalProperties.PRELIM, 0d);
        }
    } else {
        /**
         * This Node is not a leaf, so call this procedure recursively for each of its
         * offspring.
         */
        for (TNode child : cN.getChildren()) {
            firstWalk(child, level + 1);
        }

        /**
         * Set the prelim and modifer for this node by determine the midpoint of its offsprings
         * and the middle node size of the node and its left sibling
         */
        TNode lM = Iterables.getFirst(cN.getChildren(), null);
        TNode rM = Iterables.getLast(cN.getChildren(), null);
        double midPoint = (rM.getProperty(InternalProperties.PRELIM)
                + lM.getProperty(InternalProperties.PRELIM)) / 2f;

        if (lS != null) {
            /** This Node has a left sibling so its offsprings must be shifted to the right */
            double p = lS.getProperty(InternalProperties.PRELIM) + spacing + meanNodeWidth(lS, cN);
            cN.setProperty(InternalProperties.PRELIM, p);
            cN.setProperty(InternalProperties.MODIFIER, cN.getProperty(InternalProperties.PRELIM) - midPoint);
            /** shift the offsprings of this node to the right */
            apportion(cN, level);
        } else {
            /** No sibling on the left to worry about. */
            cN.setProperty(InternalProperties.PRELIM, midPoint);
        }
    }
}

From source file:com.eucalyptus.ws.handlers.HmacHandler.java

@Override
@SuppressWarnings("deprecation")
public void incomingMessage(MessageEvent event) throws Exception {
    if (event.getMessage() instanceof MappingHttpRequest) {
        final MappingHttpRequest httpRequest = (MappingHttpRequest) event.getMessage();
        final Map<String, String> parameters = httpRequest.getParameters();
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        httpRequest.getContent().readBytes(bos, httpRequest.getContent().readableBytes());
        final String body = bos.toString();
        bos.close();// w w  w  .  j a  v  a  2 s. c o m
        final Function<String, List<String>> headerLookup = SignatureHandlerUtils.headerLookup(httpRequest);
        final Function<String, List<String>> parameterLookup = SignatureHandlerUtils
                .parameterLookup(httpRequest);
        final HmacUtils.SignatureVariant variant = HmacUtils.detectSignatureVariant(headerLookup,
                parameterLookup);
        final Map<String, List<String>> headers = Maps.newHashMap();
        for (final String header : httpRequest.getHeaderNames()) {
            headers.put(header.toLowerCase(), httpRequest.getHeaders(header));
        }
        if (variant.getVersion().value() <= 2) {
            if (!parameters.containsKey(SecurityParameter.AWSAccessKeyId.parameter())) {
                throw new AuthenticationException(
                        "Missing required parameter: " + SecurityParameter.AWSAccessKeyId);
            }
        }

        final HmacCredentials credentials = new HmacCredentials(httpRequest.getCorrelationId(), variant,
                processParametersForVariant(httpRequest, variant), headers, httpRequest.getMethod().getName(),
                httpRequest.getServicePath(), body);

        SecurityContext.getLoginContext(credentials).login();

        final Subject subject = Contexts.lookup(httpRequest.getCorrelationId()).getSubject();
        final QueryIdCredential credential = Iterables
                .getFirst(subject.getPublicCredentials(QueryIdCredential.class), null);
        if (credential == null || (credential.getType().isPresent()
                && !allowedTemporaryKeyTypes.contains(credential.getType().get()))) {
            throw new AuthenticationException("Temporary credentials forbidden for service");
        }

        parameters.keySet().removeAll(variant.getParametersToRemove());
        parameters.remove(SecurityParameter.SecurityToken.parameter());
    }
}

From source file:org.obm.icalendar.ical4jwrapper.ICalendarEvent.java

private VAlarm firstVAlarm(VEvent vEvent) {
    Collection<VAlarm> alarms = vEvent.getAlarms();
    if (alarms != null) {
        return Iterables.getFirst(alarms, null);
    }//from  w  ww.  ja va 2  s  .c om
    return null;
}

From source file:com.yahoo.yqlplus.engine.internal.source.ExportModuleAdapter.java

@Override
public StreamValue pipe(Location location, ContextPlanner context, String name, StreamValue input,
        List<OperatorNode<ExpressionOperator>> arguments) {
    Collection<ObjectBuilder.MethodBuilder> targets = methods.get(name);
    if (targets.isEmpty()) {
        throw new ProgramCompileException(location, "Method '%s' not found on module %s", name, moduleName);
    }//from   ww w .  j a v a  2s  . co  m
    @SuppressWarnings("ConstantConditions")
    GambitCreator.Invocable firstInvocable = Iterables.getFirst(targets, null).invoker();
    TypeWidget outputType = firstInvocable.getReturnType();
    DynamicExpressionEvaluator eval = new DynamicExpressionEvaluator(context);
    List<OperatorNode<PhysicalExprOperator>> callArgs = Lists.newArrayList();
    callArgs.add(getModule(location, context));
    callArgs.add(context.getContextExpr());
    if (targets.size() > 1) {
        callArgs.add(input.materializeValue());
        callArgs.addAll(eval.applyAll(arguments));
        for (ObjectBuilder.MethodBuilder candidate : targets) {
            outputType = context.getValueTypeAdapter().unifyTypes(outputType,
                    candidate.invoker().getReturnType());
        }
        return StreamValue.iterate(context,
                OperatorNode.create(location, PhysicalExprOperator.CALL, outputType, name, callArgs));
    } else {
        Iterator<TypeWidget> args = firstInvocable.getArgumentTypes().iterator();
        args.next();
        args.next();
        // consume the module & context
        callArgs.add(input.materializeValue());
        // consume the stream argument
        args.next();
        Iterator<OperatorNode<ExpressionOperator>> e = arguments.iterator();
        while (args.hasNext()) {
            if (!e.hasNext()) {
                throw new ProgramCompileException(location,
                        "Argument length mismatch in call to %s (expects %d arguments)", name,
                        firstInvocable.getArgumentTypes().size());
            }
            callArgs.add(OperatorNode.create(location, PhysicalExprOperator.CAST, args.next(),
                    eval.apply(e.next())));
        }
        if (e.hasNext()) {
            throw new ProgramCompileException(location,
                    "Argument length mismatch in call to %s (expects %d arguments)", name,
                    firstInvocable.getArgumentTypes().size());
        }
        return StreamValue.iterate(context,
                OperatorNode.create(location, PhysicalExprOperator.INVOKE, firstInvocable, callArgs));
    }
}

From source file:org.summer.dsl.xbase.typesystem.references.OwnedConverter.java

@Override
public LightweightTypeReference doVisitParameterizedTypeReference(JvmParameterizedTypeReference reference) {
    JvmType type = getType(reference);/*w w w. jav a 2s .  c om*/
    if (type == null || type.eIsProxy()) {
        List<INode> nodes = NodeModelUtils.findNodesForFeature(reference,
                TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE);
        if (nodes.isEmpty()) {
            Set<EObject> sourceElements = owner.getServices().getJvmModelAssociations()
                    .getSourceElements(reference);
            EObject firstSource = Iterables.getFirst(sourceElements, null);
            if (firstSource instanceof JvmParameterizedTypeReference) {
                nodes = NodeModelUtils.findNodesForFeature(firstSource,
                        TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE);
            }
        }
        if (nodes.size() == 1) {
            String name = nodes.get(0).getText().trim();
            if (name != null && name.length() != 0) {
                int lastDot = name.lastIndexOf('.');
                int lastDollar = name.lastIndexOf('$');
                int lastDotOrDollar = Math.max(lastDot, lastDollar);
                if (lastDotOrDollar != -1 && lastDotOrDollar != name.length() - 1) {
                    String shortName = name.substring(lastDotOrDollar + 1);
                    if (shortName.length() != 0) {
                        name = shortName;
                    }
                }
                return new UnknownTypeReference(owner, name);
            }
        }
        return new UnknownTypeReference(owner);
    }
    ParameterizedTypeReference result = new ParameterizedTypeReference(owner, type);
    for (JvmTypeReference argument : reference.getArguments()) {
        result.addTypeArgument(visit(argument).getWrapperTypeIfPrimitive());
    }
    return result;
}

From source file:com.google.javascript.jscomp.deps.Es6SortedDependencies.java

private void processInputs() {
    // Index./* ww  w  .  jav  a2  s.c  o  m*/
    for (INPUT userOrderedInput : userOrderedInputs) {
        Collection<String> provides = userOrderedInput.getProvides();
        String firstProvide = Iterables.getFirst(provides, null);
        if (firstProvide == null
                // "module$" indicates the provide is generated from the path. If this is the only thing
                // the module provides and it is not an ES6 module then it is just a script and doesn't
                // export anything.
                || (provides.size() == 1 && firstProvide.startsWith("module$")
                // ES6 modules should always be considered as exporting something.
                        && !"es6".equals(userOrderedInput.getLoadFlags().get("module")))) {
            nonExportingInputs.put(ModuleNames.fileToModuleName(userOrderedInput.getName()), userOrderedInput);
        }
        for (String providedSymbolName : userOrderedInput.getProvides()) {
            exportingInputBySymbolName.put(providedSymbolName, userOrderedInput);
        }
    }
    for (INPUT userOrderedInput : userOrderedInputs) {
        for (String symbolName : userOrderedInput.getRequiredSymbols()) {
            INPUT importedInput = exportingInputBySymbolName.get(symbolName);
            if (importedInput != null) {
                importedInputByImportingInput.put(userOrderedInput, importedInput);
            }
        }
    }

    // Order.
    // For each input, traverse in user-provided order.
    for (INPUT userOrderedInput : userOrderedInputs) {
        // Traverse the graph starting from this input and record any
        // newly-reached inputs.
        orderInput(userOrderedInput);
    }

    // Free temporary indexes.
    completedInputs.clear();
    importedInputByImportingInput.clear();
}

From source file:com.facebook.presto.hive.HiveSplitManager.java

@Override
public ConnectorSplitSource getSplits(ConnectorSession session, ConnectorTableLayoutHandle layoutHandle) {
    HiveTableLayoutHandle layout = checkType(layoutHandle, HiveTableLayoutHandle.class, "layoutHandle");

    List<HivePartition> partitions = Lists.transform(layout.getPartitions().get(),
            partition -> checkType(partition, HivePartition.class, "partition"));

    HivePartition partition = Iterables.getFirst(partitions, null);
    if (partition == null) {
        return new FixedSplitSource(connectorId, ImmutableList.<ConnectorSplit>of());
    }/*from   w  w  w. j  av  a2  s.  c  o m*/
    SchemaTableName tableName = partition.getTableName();
    Optional<HiveBucketing.HiveBucket> bucket = partition.getBucket();

    // sort partitions
    partitions = Ordering.natural().onResultOf(HivePartition::getPartitionId).reverse().sortedCopy(partitions);

    Optional<Table> table = metastore.getTable(tableName.getSchemaName(), tableName.getTableName());
    if (!table.isPresent()) {
        throw new TableNotFoundException(tableName);
    }
    Iterable<HivePartitionMetadata> hivePartitions = getPartitionMetadata(table.get(), tableName, partitions);

    HiveSplitLoader hiveSplitLoader = new BackgroundHiveSplitLoader(connectorId, table.get(), hivePartitions,
            bucket, maxSplitSize, session, hdfsEnvironment, namenodeStats, directoryLister, executor,
            maxPartitionBatchSize, maxInitialSplitSize, maxInitialSplits, recursiveDfsWalkerEnabled);

    HiveSplitSource splitSource = new HiveSplitSource(connectorId, maxOutstandingSplits, hiveSplitLoader,
            executor);
    hiveSplitLoader.start(splitSource);

    return splitSource;
}

From source file:org.apache.druid.server.router.TieredBrokerHostSelector.java

public Pair<String, Server> select(final Query<T> query) {
    synchronized (lock) {
        if (!ruleManager.isStarted() || !started) {
            return getDefaultLookup();
        }//from w  w 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 = DateTimes.nowUtc();
        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();
    }

    NodesHolder nodesHolder = servers.get(brokerServiceName);

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

    return new Pair<>(brokerServiceName, nodesHolder.pick());
}