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.eclipse.sirius.diagram.ui.internal.edit.commands.ChildrenAdjustmentCommand.java

/**
 * Add the needed commands, to move the children nodes, to the original
 * command.//w  w  w  . j av  a2s  . c  o m
 *
 * @param resizedPart
 *            The part that will be resized
 * @param cc
 *            The current command that resizes the parent part, command to
 *            complete with the moves of children
 * @param cbr
 *            The original request
 */
private void addChildrenAdjustmentCommands(IGraphicalEditPart resizedPart, CompositeTransactionalCommand cc,
        ChangeBoundsRequest cbr) {
    PrecisionPoint delta = new PrecisionPoint(cbr.getMoveDelta().getNegated());
    GraphicalHelper.applyInverseZoomOnPoint(resizedPart, delta);
    AbstractDNodeContainerCompartmentEditPart compartment = Iterables.getFirst(
            Iterables.filter(resizedPart.getChildren(), AbstractDNodeContainerCompartmentEditPart.class), null);
    if (compartment != null) {
        Iterable<EditPart> childrenExceptBorderItemPart = Iterables.filter(compartment.getChildren(),
                EditPart.class);
        for (EditPart editPart : childrenExceptBorderItemPart) {
            IAdaptable adapter = new EObjectAdapter((Node) editPart.getModel());
            // Shift this view by the delta
            cc.compose(CommandFactory.createICommand(cc.getEditingDomain(),
                    new MoveViewOperation(DiagramUIMessages.SetLocationCommand_Label_Resize, adapter, delta)));
        }
    }
}

From source file:com.linecorp.armeria.server.grpc.GrpcDocServicePlugin.java

@Override
public ServiceSpecification generateSpecification(Set<ServiceConfig> serviceConfigs) {
    final Map<String, ServiceEntryBuilder> map = new LinkedHashMap<>();
    for (ServiceConfig serviceConfig : serviceConfigs) {
        final GrpcService grpcService = serviceConfig.service().as(GrpcService.class).get();
        ImmutableSet.Builder<MediaType> supportedMediaTypesBuilder = ImmutableSet.builder();
        supportedMediaTypesBuilder.addAll(grpcService.supportedSerializationFormats().stream()
                .map(SerializationFormat::mediaType)::iterator);
        if (serviceConfig.service().as(UnframedGrpcService.class).isPresent()) {
            if (grpcService.supportedSerializationFormats().contains(GrpcSerializationFormats.PROTO)) {
                // Normal clients of a GrpcService are not required to set a protocol when using unframed
                // requests but we set it here for clarity in DocService, where there may be multiple
                // services with similar mime types but different protocols.
                supportedMediaTypesBuilder.add(MediaType.PROTOBUF.withParameter("protocol", "gRPC"));
            }//  w ww .  j  av a  2s. co m
            if (grpcService.supportedSerializationFormats().contains(GrpcSerializationFormats.JSON)) {
                supportedMediaTypesBuilder.add(MediaType.JSON_UTF_8.withParameter("protocol", "gRPC"));
            }
        }
        Set<MediaType> supportedMediaTypes = supportedMediaTypesBuilder.build();
        for (ServerServiceDefinition service : grpcService.services()) {
            map.computeIfAbsent(service.getServiceDescriptor().getName(), s -> {
                FileDescriptor fileDescriptor = ((ProtoFileDescriptorSupplier) service.getServiceDescriptor()
                        .getSchemaDescriptor()).getFileDescriptor();
                ServiceDescriptor serviceDescriptor = fileDescriptor.getServices().stream()
                        .filter(sd -> sd.getFullName().equals(service.getServiceDescriptor().getName()))
                        .findFirst().orElseThrow(IllegalStateException::new);
                return new ServiceEntryBuilder(serviceDescriptor);
            });
        }
        serviceConfig.pathMapping().prefix().ifPresent(path -> {
            for (ServerServiceDefinition service : grpcService.services()) {
                final String serviceName = service.getServiceDescriptor().getName();
                map.get(serviceName).endpoint(new EndpointInfo(serviceConfig.virtualHost().hostnamePattern(),
                        // Only the URL prefix, each method is served at a different path.
                        path + serviceName + '/', "",
                        // No default mime type for GRPC, so just pick arbitrarily for now.
                        // TODO(anuraag): Consider allowing default mime type to be null.
                        Iterables.getFirst(supportedMediaTypes, GrpcSerializationFormats.PROTO.mediaType()),
                        supportedMediaTypes));
            }
        });
    }
    return generate(map.values().stream().map(ServiceEntryBuilder::build).collect(toImmutableList()));
}

From source file:org.ldp4j.http.AlternativeEvaluation.java

private static <T extends Negotiable> Weighted<T> getPreferredValue(List<Weighted<T>> accepts,
        Comparator<T> comparator) {
    final SortedSet<Weighted<T>> sortedAccepts = Sets.newTreeSet(WeightedComparator.create(comparator));
    sortedAccepts.addAll(accepts);//from  ww w. j av  a  2 s .c  o  m
    Weighted<T> first = Iterables.getFirst(sortedAccepts, null);
    if (first != null && first.entity().isWildcard()) {
        first = null;
    }
    return first;
}

From source file:fr.letroll.ttorrentandroid.tracker.Tracker.java

/**
 * Start the tracker thread./*from  www. j ava2s  . co m*/
 */
public void start() throws IOException {
    LOG.info("Starting BitTorrent tracker on {}...", getAnnounceUrls());
    synchronized (lock) {

        if (this.metrics == null) {
            Object trackerId = Iterables.getFirst(getListenAddresses(), System.identityHashCode(this));
            this.metrics = new TrackerMetrics(getMetricsRegistry(), trackerId);

            metrics.addGauge("torrentCount", new Gauge<Integer>() {
                @Override
                public Integer value() {
                    return torrents.size();
                }
            });
        }

        for (Map.Entry<InetSocketAddress, Listener> e : listeners.entrySet()) {
            Listener listener = e.getValue();
            if (listener.connection == null) {
                // Creates a thread via: SocketConnection
                // -> ListenerManager -> Listener
                // -> DirectReactor -> ActionDistributor -> Daemon
                Container container = new TrackerService(version, torrents, metrics);
                Server server = new ContainerServer(container);
                listener.connection = new SocketConnection(server);
                listener.connectionAddress = listener.connection.connect(e.getKey());
            }
        }

        if (this.scheduler == null || this.scheduler.isShutdown()) {
            // TODO: Set a thread timeout, nothing is time critical.
            this.scheduler = new ScheduledThreadPoolExecutor(1);
            this.scheduler.scheduleWithFixedDelay(new PeerCollector(), PEER_COLLECTION_FREQUENCY_SECONDS,
                    PEER_COLLECTION_FREQUENCY_SECONDS, TimeUnit.SECONDS);
        }

    }
    LOG.info("Started BitTorrent tracker on {}...", getAnnounceUrls());
}

From source file:com.eucalyptus.tokens.TokensService.java

public GetAccessTokenResponseType getAccessToken(final GetAccessTokenType request)
        throws EucalyptusCloudException {
    final GetAccessTokenResponseType reply = request.getReply();
    reply.getResponseMetadata().setRequestId(reply.getCorrelationId());
    final Context ctx = Contexts.lookup();
    final Subject subject = ctx.getSubject();
    final User requestUser = ctx.getUser();

    final AccountUsername accountUsername = subject == null ? null
            : Iterables.getFirst(subject.getPublicCredentials(AccountUsername.class), null);
    if (accountUsername == null || !accountUsername.getAccount().equals(ctx.getAccount().getName())
            || !accountUsername.getUsername().equals(requestUser.getName())) {
        throw new EucalyptusCloudException("Invalid authentication");
    }/*  w w  w.  j a va2  s  .c om*/

    try {
        final SecurityToken token = SecurityTokenManager.issueSecurityToken(requestUser,
                Objects.firstNonNull(request.getDurationSeconds(), (int) TimeUnit.HOURS.toSeconds(12)));
        reply.setResult(GetAccessTokenResultType.forCredentials(token.getAccessKeyId(), token.getSecretKey(),
                token.getToken(), token.getExpires()));
    } catch (final SecurityTokenValidationException e) {
        throw new TokensException(TokensException.Code.ValidationError, e.getMessage());
    } catch (final AuthException e) {
        throw new EucalyptusCloudException(e.getMessage(), e);
    }

    return reply;
}

From source file:org.eclipse.elk.tree.p3place.NodePlacer.java

/**
 * This method cleans up the positioning of small sibling subtrees, thus fixing the
 * "left-to-right gluing" problem evident in earlier algorithms. When moving a new subtree
 * farther and farther to the right, gaps may open up among smaller subtrees that were
 * previously sandwiched between larger subtrees. Thus, when moving the new, larger subtree to
 * the right, the distance it is moved is also apportioned to smaller, interior subtrees,
 * creating a pleasing aesthetic placement.
 * //from   w ww . jav  a  2 s .  com
 * @param cN
 *            the root of the subtree
 * @param level
 *            the level of the root in the global tree
 */
private void apportion(final TNode cN, final int level) {
    /** Initialize the leftmost and neighbor corresponding to the root of the subtree */
    TNode leftmost = Iterables.getFirst(cN.getChildren(), null);
    TNode neighbor = leftmost != null ? leftmost.getProperty(Properties.LEFTNEIGHBOR) : null;
    int compareDepth = 1;
    /**
     * until this node and the neighbor to the left have nodes in the current level we have to
     * shift the current subtree
     */
    while (leftmost != null && neighbor != null) {
        /** Compute the location of Leftmost and where it should be with respect to Neighbor. */
        double leftModSum = 0;
        double rightModSum = 0;
        TNode ancestorLeftmost = leftmost;
        TNode ancestorNeighbor = neighbor;
        /** sum the modifiers of all ancestors according to the current level */
        for (int i = 0; i < compareDepth; i++) {
            ancestorLeftmost = ancestorLeftmost.getParent();
            ancestorNeighbor = ancestorNeighbor.getParent();
            rightModSum += ancestorLeftmost.getProperty(Properties.MODIFIER);
            leftModSum += ancestorNeighbor.getProperty(Properties.MODIFIER);
        }
        /**
         * Find the MoveDistance, and apply it to Node's subtree. Add appropriate portions to
         * smaller interior subtrees.
         */
        double prN = neighbor.getProperty(Properties.PRELIM);
        double prL = leftmost.getProperty(Properties.PRELIM);
        double mean = meanNodeWidth(leftmost, neighbor);
        double moveDistance = prN + leftModSum + spacing + mean - prL - rightModSum;

        if (0 < moveDistance) {
            /** Count interior sibling subtrees in LeftSiblings */
            TNode leftSibling = cN;
            int leftSiblings = 0;
            while (leftSibling != null && leftSibling != ancestorNeighbor) {
                leftSiblings++;
                leftSibling = leftSibling.getProperty(Properties.LEFTSIBLING);
            }
            /** Apply portions to appropriate left sibling subtrees. */
            if (leftSibling != null) {
                double portion = moveDistance / (double) leftSiblings;
                leftSibling = cN;
                while (leftSibling != ancestorNeighbor) {
                    double newPr = leftSibling.getProperty(Properties.PRELIM) + moveDistance;
                    leftSibling.setProperty(Properties.PRELIM, newPr);
                    double newMod = leftSibling.getProperty(Properties.MODIFIER) + moveDistance;
                    leftSibling.setProperty(Properties.MODIFIER, newMod);
                    moveDistance -= portion;
                    leftSibling = leftSibling.getProperty(Properties.LEFTSIBLING);
                }
            } else {
                /**
                 * Don't need to move anything--it needs to be done by an ancestor because
                 * AncestorNeighbor and AncestorLeftmost are not siblings of each other.
                 */
                return;
            }
        }
        /**
         * Determine the leftmost descendant of Node at the next lower level to compare its
         * positioning against that of its Neighbor.
         */
        compareDepth++;
        if (leftmost.isLeaf()) {
            leftmost = TreeUtil.getLeftMost(cN.getChildren(), compareDepth);
        } else {
            leftmost = Iterables.getFirst(leftmost.getChildren(), null);
        }
        neighbor = leftmost != null ? leftmost.getProperty(Properties.LEFTNEIGHBOR) : null;
    }
}

From source file:com.android.build.gradle.shrinker.IncrementalRunVisitor.java

@Override
public void visitEnd() {
    T field = Iterables.getFirst(mFields, null);
    if (field != null) {
        throw new IncrementalShrinker.IncrementalRunImpossibleException(String.format("Field %s.%s:%s removed.",
                mClassName, mGraph.getMemberName(field), mGraph.getMemberDescriptor(field)));
    }/*  www  .  j ava 2  s.c om*/

    for (T method : mMethods) {
        if (mGraph.getMemberName(method).endsWith(FullRunShrinker.SHRINKER_FAKE_MARKER)) {
            continue;
        }
        throw new IncrementalShrinker.IncrementalRunImpossibleException(
                String.format("Method %s.%s:%s removed.", mClassName, mGraph.getMemberName(method),
                        mGraph.getMemberDescriptor(method)));
    }

    checkForRemovedAnnotation(mAnnotations, mClassName);
}

From source file:org.openhab.binding.loxone.internal.LoxoneBinding.java

private Miniserver findMiniserver(final String instance) {
    return Iterables.find(miniservers, new Predicate<Miniserver>() {
        public boolean apply(Miniserver miniserver) {
            return instance.equalsIgnoreCase(miniserver.host().getName());
        }/*from ww  w .  j av a  2s  . c  o m*/
    }, Iterables.getFirst(miniservers, null));
}

From source file:org.elasticsearch.index.mapper.internal.IdFieldMapper.java

@Override
public Query prefixQuery(Object value, @Nullable MultiTermQuery.RewriteMethod method,
        @Nullable QueryParseContext context) {
    if (fieldType.indexed() || context == null) {
        return super.prefixQuery(value, method, context);
    }/*from ww  w .j a  va2  s  .c  om*/
    Collection<String> queryTypes = context.queryTypes();
    if (queryTypes.size() == 1) {
        PrefixQuery prefixQuery = new PrefixQuery(new Term(UidFieldMapper.NAME,
                Uid.createUidAsBytes(Iterables.getFirst(queryTypes, null), BytesRefs.toBytesRef(value))));
        if (method != null) {
            prefixQuery.setRewriteMethod(method);
        }
        return prefixQuery;
    }
    BooleanQuery query = new BooleanQuery();
    for (String queryType : queryTypes) {
        PrefixQuery prefixQuery = new PrefixQuery(
                new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(queryType, BytesRefs.toBytesRef(value))));
        if (method != null) {
            prefixQuery.setRewriteMethod(method);
        }
        query.add(prefixQuery, BooleanClause.Occur.SHOULD);
    }
    return query;
}