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

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

Introduction

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

Prototype

public static <T> T get(Iterable<T> iterable, int position) 

Source Link

Document

Returns the element at the specified position in an iterable.

Usage

From source file:com.arpnetworking.utility.ParallelLeastShardAllocationStrategy.java

/**
 * {@inheritDoc}/*from   w  w  w  .  ja  va  2s  . c  om*/
 */
@Override
public Future<Set<String>> rebalance(final Map<ActorRef, IndexedSeq<String>> currentShardAllocations,
        final Set<String> rebalanceInProgress) {
    // Only keep the rebalances that are in progress
    _pendingRebalances.keySet().retainAll(rebalanceInProgress);

    // Build a friendly set of current allocations
    // Sort the set by "effective shards after rebalance"
    final TreeSet<RegionShardAllocations> allocations = new TreeSet<>(
            Comparator.comparingInt(RegionShardAllocations::getEffectiveShardCount));

    for (final Map.Entry<ActorRef, IndexedSeq<String>> entry : currentShardAllocations.entrySet()) {
        allocations.add(new RegionShardAllocations(entry.getKey(),
                // Only count the shards that are not currently rebalancing
                JavaConversions.setAsJavaSet(entry.getValue().<String>toSet()).stream()
                        .filter(e -> !rebalanceInProgress.contains(e)).collect(Collectors.toSet())));
    }

    final Set<String> toRebalance = Sets.newHashSet();

    for (int x = 0; x < _maxParallel - rebalanceInProgress.size(); x++) {
        // Note: the poll* functions remove the item from the set
        final RegionShardAllocations leastShards = allocations.pollFirst();
        final RegionShardAllocations mostShards = allocations.pollLast();

        // Make sure that we have more than 1 region
        if (mostShards == null) {
            LOGGER.debug().setMessage("Cannot rebalance shards, less than 2 shard regions found.").log();
            break;
        }

        // Make sure that the difference is enough to warrant a rebalance
        if (mostShards.getEffectiveShardCount() - leastShards.getEffectiveShardCount() < _rebalanceThreshold) {
            LOGGER.debug().setMessage(
                    "Not rebalancing any (more) shards, shard region with most shards already balanced with least")
                    .addData("most", mostShards.getEffectiveShardCount())
                    .addData("least", leastShards.getEffectiveShardCount())
                    .addData("rebalanceThreshold", _rebalanceThreshold).log();
            break;
        }

        final String rebalanceShard = Iterables.get(mostShards.getShards(), 0);

        // Now we take a shard from mostShards and give it to leastShards
        mostShards.removeShard(rebalanceShard);
        leastShards.incrementIncoming();
        toRebalance.add(rebalanceShard);
        _pendingRebalances.put(rebalanceShard, leastShards.getRegion());

        // Put them back in the list with their new counts
        allocations.add(mostShards);
        allocations.add(leastShards);
    }

    // Transform the currentShardAllocations to a Map<ActorRef, Set<String>> from the
    // Scala representation
    final Map<ActorRef, Set<String>> currentAllocations = Maps.transformValues(currentShardAllocations,
            e -> Sets.newHashSet(JavaConversions.seqAsJavaList(e)));

    final RebalanceNotification notification = new RebalanceNotification(currentAllocations,
            rebalanceInProgress, _pendingRebalances);
    LOGGER.debug().setMessage("Broadcasting rebalance info").addData("target", _notify)
            .addData("shardAllocations", notification).log();
    if (_notify.isPresent()) {
        _notify.get().tell(notification, ActorRef.noSender());
    }
    return Futures.successful(toRebalance);
}

From source file:org.polarsys.reqcycle.traceability.table.model.TableController.java

public void deleteTraceabilityLinks(Iterator<TransverseLink> links) {
    ITraceabilityStorage storage = null;
    IProject project = null;//w  ww.j  a  va  2s.  c om
    try {
        Collection<Reachable> notification = Sets.newHashSet();
        while (links.hasNext()) {
            TransverseLink link = links.next();
            if (storage == null) {
                project = link.getProject();
                storage = provider.getProjectStorage(project);
                storage.startTransaction();
            }
            Reachable source = Iterables.get(link.getSources(), 0);
            Reachable target = Iterables.get(link.getTargets(), 0);
            if (storage != null) {
                storage.removeTraceabilityLink(link.getId());
                notification.add(link.getId());
                notification.add(source);
                notification.add(target);
                notification.add(link.getId().trimFragment());
            }
        }
        if (storage != null) {
            storage.commit();
            listenerManager.notifyChanged(notification.toArray(new Reachable[] {}));
        }
    } catch (Exception e) {
        e.printStackTrace();
        storage.rollback();
    } finally {
        storage.save();
        //         storage.dispose();
        refreshViewerData();
    }
}

From source file:utils.teamcity.wallt.view.wall.WallView.java

private GridPane buildScreenPane(final Iterable<Object> buildsInScreen, final int nbColums,
        final int byColums) {
    final GridPane screenPane = new GridPane();
    screenPane.setHgap(GAP_SPACE);//from w  w w . j  a va 2 s . c o m
    screenPane.setVgap(GAP_SPACE);
    screenPane.setPadding(new Insets(GAP_SPACE));
    screenPane.setStyle("-fx-background-color:black;");
    screenPane.setAlignment(Pos.CENTER);

    final Iterable<List<Object>> partition = Iterables.paddedPartition(buildsInScreen, byColums);
    for (int x = 0; x < nbColums; x++) {
        final List<Object> buildList = x < size(partition) ? Iterables.get(partition, x)
                : Collections.emptyList();
        for (int y = 0; y < byColums; y++) {
            if (buildList.isEmpty()) {
                createEmptyTile(screenPane, x, y, nbColums, byColums);
                continue;
            }

            final Object build = Iterables.get(buildList, y);
            if (build == null)
                createEmptyTile(screenPane, x, y, nbColums, byColums);
            else
                createTileFromModel(screenPane, build, x, y, nbColums, byColums);
        }
    }

    return screenPane;
}

From source file:org.obm.push.bean.MSEmailHeader.java

public MSAddress getDisplayTo() {
    if (to != null && !to.isEmpty()) {
        return Iterables.get(to, 0);
    } else {/*ww  w .  j a v  a 2s. com*/
        return null;
    }
}

From source file:edu.udo.scaffoldhunter.model.util.Subsets.java

/**
 * Creates the intersection of an arbitrary number of {@link Subsets}. The
 * {@link Session} is the same as the parents {@link Session}.
 * /* w  w  w. j  a va 2 s  . c om*/
 * @param parent
 *            the parent {@link Subset}, or null to use the first input
 *            {@link Subset}
 * @param subsets
 *            the input {@link Subset}s
 * 
 * @return the intersection {@link Subset}
 */
public static Subset intersection(Subset parent, Iterable<Subset> subsets) {
    Preconditions.checkNotNull(subsets);

    Set<Molecule> molecules = Sets.newHashSet(Iterables.get(subsets, 0));
    for (Subset s : Iterables.skip(subsets, 1)) {
        Set<Molecule> set = Sets.newHashSet(s);
        molecules.retainAll(set);
    }

    if (parent == null) {
        parent = Iterables.get(subsets, 0);
    }

    return new Subset(parent, "intersection subset", null, parent.getSession(), molecules, null);
}

From source file:org.jclouds.googlecomputeengine.config.GoogleComputeEngineRestClientModule.java

@Provides
@Singleton//  ww w.  j  a va2 s. c o  m
@UserProject
public Supplier<String> supplyProject(@org.jclouds.location.Provider final Supplier<Credentials> creds) {
    return compose(new Function<Credentials, String>() {
        public String apply(Credentials in) {
            checkState(in.identity.indexOf("@") != 1,
                    "identity should be in project_id@developer.gserviceaccount.com" + " format");
            return Iterables.get(Splitter.on("@").split(in.identity), 0);
        }
    }, creds);
}

From source file:org.jclouds.tools.ant.taskdefs.compute.ComputeTaskUtils.java

static String ipOrEmptyString(Set<String> set) {
    if (set.size() > 0) {
        return Iterables.get(set, 0);
    } else {/*from ww  w.j  a va 2  s  .c o  m*/
        return "";
    }
}

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

public AssumeRoleResponseType assumeRole(final AssumeRoleType request) throws EucalyptusCloudException {
    final AssumeRoleResponseType reply = request.getReply();
    reply.getResponseMetadata().setRequestId(reply.getCorrelationId());

    // Verify that access is not via a role or password credentials.
    ////  w  ww .  ja v  a2 s . com
    // It is not currently safe to allow access via a role (see EUCA-8416).
    // Other forms of temporary credential are not forbidden by the pipeline at
    // the time of authentication.
    final Context ctx = Contexts.lookup();
    final Subject subject = ctx.getSubject();
    final Set<QueryIdCredential> queryIdCreds = subject == null ? Collections.<QueryIdCredential>emptySet()
            : subject.getPublicCredentials(QueryIdCredential.class);
    if (queryIdCreds.size() == 1 && Iterables.get(queryIdCreds, 0).getType().isPresent()) {
        throw new TokensException(TokensException.Code.MissingAuthenticationToken,
                "Temporary credential not permitted.");
    }
    rejectPasswordCredentials();

    final Role role = lookupRole(request.getRoleArn());

    //TODO Should we fail if a policy is supplied? (since we ignore it)
    try {
        ExternalIdContext.doWithExternalId(request.getExternalId(), EucalyptusCloudException.class,
                new Callable<Role>() {
                    @Override
                    public Role call() throws EucalyptusCloudException {
                        try {
                            return RestrictedTypes.doPrivilegedWithoutOwner(Accounts.getRoleFullName(role),
                                    new RoleResolver(role));
                        } catch (final AuthException e) {
                            throw new EucalyptusCloudException(e.getMessage(), e);
                        }
                    }
                });

        final SecurityToken token = SecurityTokenManager.issueSecurityToken(role,
                Objects.firstNonNull(request.getDurationSeconds(), (int) TimeUnit.HOURS.toSeconds(1)));
        reply.getAssumeRoleResult().setCredentials(new CredentialsType(token.getAccessKeyId(),
                token.getSecretKey(), token.getToken(), token.getExpires()));
        reply.getAssumeRoleResult().setAssumedRoleUser(
                new AssumedRoleUserType(role.getRoleId() + ":" + request.getRoleSessionName(),
                        assumedRoleArn(role, request.getRoleSessionName())));
    } 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.reqcycle.traceability.table.model.TableController.java

public void deleteTraceabilityLinks(Iterator<TransverseLink> links) {
    ITraceabilityStorage storage = null;
    IProject project = null;/*w  w w. ja v  a2  s.  co m*/
    try {
        while (links.hasNext()) {
            TransverseLink link = links.next();
            if (storage == null) {
                project = link.getProject();
                storage = getStorage(project, provider);
                storage.startTransaction();
            }
            Reachable source = Iterables.get(link.getSources(), 0);
            Reachable target = Iterables.get(link.getTargets(), 0);
            if (storage != null)
                storage.removeUpwardRelationShip(link.getKind(), null, target, source);
        }
        if (storage != null) {
            storage.commit();
        }
    } catch (Exception e) {
        e.printStackTrace();
        storage.rollback();
    } finally {
        storage.save();
        refreshViewerData();
        IFile file = project.getFile(new Path(RDF_FILE));
        try {
            file.refreshLocal(0, new NullProgressMonitor());
        } catch (CoreException e) {
            //DO NOTHING
        }
    }
}

From source file:org.apache.whirr.actions.ScriptBasedClusterAction.java

public Cluster execute(ClusterSpec clusterSpec, Cluster cluster) throws IOException, InterruptedException {

    Map<InstanceTemplate, ClusterActionEvent> eventMap = Maps.newHashMap();
    Cluster newCluster = cluster;//from w  w  w  . ja  v  a  2  s  .  c  o  m
    for (InstanceTemplate instanceTemplate : clusterSpec.getInstanceTemplates()) {
        if (shouldIgnoreInstanceTemplate(instanceTemplate)) {
            continue; // skip execution if this group of instances is not in target
        }
        StatementBuilder statementBuilder = new StatementBuilder();

        ComputeServiceContext computeServiceContext = getCompute().apply(clusterSpec);
        FirewallManager firewallManager = new FirewallManager(computeServiceContext, clusterSpec, newCluster);

        VelocityEngine velocityEngine = TemplateUtils.newVelocityEngine();

        ClusterActionEvent event = new ClusterActionEvent(getAction(), clusterSpec, instanceTemplate,
                newCluster, statementBuilder, getCompute(), firewallManager, velocityEngine);

        eventMap.put(instanceTemplate, event);
        for (String role : instanceTemplate.getRoles()) {
            if (roleIsInTarget(role)) {
                safeGetActionHandler(role).beforeAction(event);
            }
        }

        // cluster may have been updated by handler
        newCluster = event.getCluster();
    }

    doAction(eventMap);

    // cluster may have been updated by action
    newCluster = Iterables.get(eventMap.values(), 0).getCluster();

    for (InstanceTemplate instanceTemplate : clusterSpec.getInstanceTemplates()) {
        if (shouldIgnoreInstanceTemplate(instanceTemplate)) {
            continue;
        }
        ClusterActionEvent event = eventMap.get(instanceTemplate);
        for (String role : instanceTemplate.getRoles()) {
            if (roleIsInTarget(role)) {
                event.setCluster(newCluster);
                safeGetActionHandler(role).afterAction(event);

                // cluster may have been updated by handler
                newCluster = event.getCluster();
            }
        }
    }

    return newCluster;
}