Example usage for com.google.common.collect Multimap keySet

List of usage examples for com.google.common.collect Multimap keySet

Introduction

In this page you can find the example usage for com.google.common.collect Multimap keySet.

Prototype

Set<K> keySet();

Source Link

Document

Returns a view collection of all distinct keys contained in this multimap.

Usage

From source file:com.cinchapi.concourse.importer.JsonImporter.java

/**
 * Given a string of JSON data, upsert it into Concourse.
 * //w w w  . j  av a 2s . c o  m
 * @param json
 * @return the records that were affected by the import
 */
protected Set<Long> upsertJsonString(String json) {
    // TODO call concourse.upsert(json) when method is ready
    // NOTE: The following implementation is very inefficient, but will
    // suffice until the upsert functionality is available
    Set<Long> records = Sets.newHashSet();
    for (Multimap<String, Object> data : Convert.anyJsonToJava(json)) {
        Long record = MoreObjects.firstNonNull(
                (Long) Iterables.getOnlyElement(data.get(Constants.JSON_RESERVED_IDENTIFIER_NAME), null),
                Time.now());
        data.removeAll(Constants.JSON_RESERVED_IDENTIFIER_NAME);
        for (String key : data.keySet()) {
            for (Object value : data.get(key)) {
                concourse.add(key, value, record);
            }
        }
        records.add(record);
    }
    return records;
}

From source file:edu.umn.msi.tropix.webgui.server.SearchImpl.java

private List<ServiceBean> convertResults(final Multimap<String, SearchHit> shBeans) {
    final List<ServiceBean> serviceBeans = new LinkedList<ServiceBean>();
    for (final String catalogId : shBeans.keySet()) {
        final Collection<SearchHit> hits = shBeans.get(catalogId);
        BasicEntry[] bsBeans = null;//w w w.j av  a2 s. co  m
        try {
            bsBeans = this.catalogClient.getEntryAPI(catalogId)
                    .getBasicDetails(CatalogUtils.getServiceIDsFromSHBeanList(hits), 500);
        } catch (final RemoteException e) {
            ExceptionUtils.logQuietly(SearchImpl.LOG, e, "Failed to obtain basic details");
            continue;
        }
        if (bsBeans == null) {
            bsBeans = new BasicEntry[0];
        }
        try {
            serviceBeans.addAll(convertBasicServiceBeanToServiceBean(
                    this.catalogClient.getOntologAPI(catalogId), Arrays.asList(bsBeans), true));
        } catch (final Exception e) {
            ExceptionUtils.logQuietly(SearchImpl.LOG, e, "Failed to convert catalog results");
            continue;
        }
        for (final SearchHit searchBean : hits) {
            for (final ServiceBean serviceBean : serviceBeans) {
                if (searchBean.getEntryID().equals(serviceBean.getId())) {
                    serviceBean.setCatalogId(catalogId);
                    if (searchBean.getInstances() != null && searchBean.getInstances().length > 0) {
                        serviceBean.setSearchHits(getUIHitInsts(searchBean.getInstances()));
                    }
                    serviceBean.setLuceneScore(searchBean.getWeightedScore());
                }
            }
        }
    }
    return serviceBeans;

}

From source file:org.mondo.collaboration.security.lens.arbiter.LockArbiter.java

private void preInitializeMatchers(Multimap<IQuerySpecification<?>, Lock> lockQueries)
        throws IncQueryException {
    if (!lockQueries.isEmpty())
        new GenericPatternGroup(lockQueries.keySet()).prepare(getQueryEngine());
    for (IQuerySpecification<?> lockQuery : lockQueries.keySet()) {
        IncQueryMatcher<? extends IPatternMatch> matcher = getQueryEngine().getMatcher(lockQuery);
        for (Lock lock : lockQueries.get(lockQuery)) {
            matcherForLock.put(lock, matcher);
        }/*from w  ww .  j  a  va2s.  c om*/
    }
}

From source file:google.registry.cron.TldFanoutAction.java

private TaskOptions createTaskOptions(String tld, Multimap<String, String> params) {
    TaskOptions options = withUrl(endpoint.replace(TLD_PATHARG, String.valueOf(tld))).countdownMillis(
            jitterSeconds.isPresent() ? random.nextInt((int) SECONDS.toMillis(jitterSeconds.get())) : 0);
    options.param(RequestParameters.PARAM_TLD, tld);
    for (String param : params.keySet()) {
        // TaskOptions.param() does not accept null values.
        options.param(param, nullToEmpty((getFirst(params.get(param), null))));
    }//www . j  a  va  2  s  . c o  m
    return options;
}

From source file:io.tilt.minka.business.leader.distributor.Distributor.java

private void sendCurrentIssues() {
    final Multimap<Shard, ShardDuty> issues = auditor.getCurrentReallocation().getGroupedIssues();
    final Iterator<Shard> it = issues.keySet().iterator();
    while (it.hasNext()) {
        final Shard shard = it.next();
        // check it's still in ptable
        if (partitionTable.getShardsByState(ONLINE).contains(shard)) {
            final Collection<ShardDuty> duties = auditor.getCurrentReallocation().getGroupedIssues().get(shard);
            if (!duties.isEmpty()) {
                if (transportMany(duties, shard)) {
                    // dont mark to wait for those already confirmed (from fallen shards)
                    duties.forEach(//from   w w w .  j a v a2 s .  c  om
                            duty -> duty.registerEvent((duty.getState() == PREPARED ? SENT : CONFIRMED)));
                } else {
                    logger.error("{}: Couldnt transport current issues !!!", getClass().getSimpleName());
                }
            } else {
                throw new IllegalStateException("No duties grouped by shard at Reallocation !!");
            }
        } else {
            logger.error("{}: PartitionTable lost transport's target shard: {}", getClass().getSimpleName(),
                    shard);
        }
    }
}

From source file:org.ow2.proactive.scheduler.authentication.ManageUsers.java

/**
 * Update the accounts in the login and config files
 *
 * @throws ManageUsersException//w  ww.j  a v  a 2  s.c o  m
 */
private static void updateAccounts(final PublicKey pubKey, final UserInfo userInfo, final String loginFilePath,
        final String groupFilePath, final Action action, final String sourceLoginFile,
        final String sourceGroupFile) throws ManageUsersException {
    try {
        Properties destinationLoginProps = new Properties();
        try (InputStreamReader stream = new InputStreamReader(new FileInputStream(loginFilePath))) {
            destinationLoginProps.load(stream);
        } catch (Exception e) {
            exitWithErrorMessage("could not read login file : " + loginFilePath, null, e);
        }

        Multimap<String, String> destinationGroupsMap = loadGroups(groupFilePath);

        Properties sourceLoginProps = new Properties();
        if (sourceLoginFile != null) {
            try (InputStreamReader stream = new InputStreamReader(new FileInputStream(sourceLoginFile))) {
                sourceLoginProps.load(stream);
            } catch (Exception e) {
                exitWithErrorMessage("could not read source login file : " + sourceLoginFile, null, e);
            }
        } else if (userInfo != null) {
            if (userInfo.getPassword() == null) {
                // password can be null in case of account deletion
                sourceLoginProps.put(userInfo.getLogin(), "");
            } else {
                sourceLoginProps.put(userInfo.getLogin(), userInfo.getPassword());
            }
        }

        Multimap<String, String> sourceGroupsMap = null;

        if (sourceGroupFile != null) {
            sourceGroupsMap = loadGroups(sourceGroupFile);
        } else {
            sourceGroupsMap = TreeMultimap.create();
            if (userInfo != null && !userInfo.getGroups().isEmpty()) {
                for (String group : userInfo.getGroups()) {
                    sourceGroupsMap.put(userInfo.getLogin(), group);
                }
            }
        }
        Collection<String> sourceLoginNames = sourceLoginProps.stringPropertyNames();
        if (sourceLoginNames.isEmpty()) {
            sourceLoginNames = sourceGroupsMap.keySet();
        }

        boolean bulkMode = sourceLoginNames.size() > 1;

        for (String user : sourceLoginNames) {
            UserInfo sourceUserInfo = new UserInfo();
            sourceUserInfo.setLogin(user);
            sourceUserInfo.setPassword((String) sourceLoginProps.get(user));
            if (sourceGroupsMap.containsKey(user)) {
                sourceUserInfo.setGroups(sourceGroupsMap.get(user));
            }

            switch (action) {
            case CREATE:
                createAccount(pubKey, sourceUserInfo, loginFilePath, groupFilePath, destinationLoginProps,
                        destinationGroupsMap);
                break;
            case UPDATE:
                updateAccount(pubKey, sourceUserInfo, loginFilePath, destinationLoginProps,
                        destinationGroupsMap, bulkMode);
                break;
            case DELETE:
                deleteAccount(sourceUserInfo, loginFilePath, groupFilePath, destinationLoginProps,
                        destinationGroupsMap);
                break;
            }
        }

        storeLoginFile(loginFilePath, destinationLoginProps);

        storeGroups(groupFilePath, destinationGroupsMap);

    } catch (Throwable t) {
        exitWithErrorMessage("Unexpected error", null, t);
    }
}

From source file:org.sonar.plugins.pitest.SourceFileReport.java

public String toJSON() {
    if (mutants.isEmpty()) {
        return null;
    }//from  www  . j ava  2 s .c o m

    Multimap<Integer, String> mutantsByLine = ArrayListMultimap.create();

    for (Mutant mutant : mutants) {
        mutantsByLine.put(mutant.lineNumber, mutant.toString());
    }

    StringBuilder builder = new StringBuilder();
    builder.append("{");
    boolean first = true;
    for (int line : mutantsByLine.keySet()) {
        if (!first) {
            builder.append(",");
        }
        first = false;
        builder.append("\"");
        builder.append(line);
        builder.append("\":[");
        builder.append(Joiner.on(",").join(mutantsByLine.get(line)));
        builder.append("]");
    }
    builder.append("}");

    return builder.toString();
}

From source file:org.eclipse.xtext.ui.refactoring.impl.DefaultReferenceUpdater.java

@Override
protected void createReferenceUpdates(ElementRenameArguments elementRenameArguments,
        Multimap<URI, IReferenceDescription> resource2references, ResourceSet resourceSet,
        IRefactoringUpdateAcceptor updateAcceptor, IProgressMonitor monitor) {
    SubMonitor progress = SubMonitor.convert(monitor, "Creating reference updates",
            resource2references.keySet().size());
    for (URI referringResourceURI : resource2references.keySet()) {
        if (progress.isCanceled())
            return;
        Resource referringResource = resourceSet.getResource(referringResourceURI, false);
        if (!(referringResource instanceof XtextResource)) {
            updateAcceptor.getRefactoringStatus().add(ERROR, "Resource {0} is not an XtextResource.",
                    referringResource.getURI(), resourceSet);
        } else {/*  w  w w . ja  v  a2s .co m*/
            Iterable<IReferenceDescription> referenceDescriptions = resource2references
                    .get(referringResourceURI);
            processReferringResource(referringResource, referenceDescriptions, elementRenameArguments,
                    updateAcceptor);
        }
        progress.worked(1);
    }
}

From source file:com.google.errorprone.bugpatterns.inject.guice.AssistedParameters.java

private Multimap<Type, VariableTree> partitionParametersByType(List<VariableTree> parameters,
        VisitorState state) {/*  w  ww  .ja v a  2  s  .  c  o  m*/

    Types types = state.getTypes();
    Multimap<Type, VariableTree> multimap = LinkedListMultimap.create();

    variables: for (VariableTree node : parameters) {
        // Normalize Integer => int
        Type type = types.unboxedTypeOrType(ASTHelpers.getType(node));
        for (Type existingType : multimap.keySet()) {
            if (types.isSameType(existingType, type)) {
                multimap.put(existingType, node);
                continue variables;
            }
        }

        // A new type for the map.
        multimap.put(type, node);
    }

    return multimap;
}

From source file:org.jboss.tools.windup.ui.internal.explorer.Group.java

private List<IssueGroupNode<?>> createGroupNodesHelper(IssueGroupNode<?> parent, List<IMarker> markers) {
    List<IssueGroupNode<?>> nodes = Lists.newArrayList();
    Multimap<T, IMarker> groups = ArrayListMultimap.create();
    markers.forEach(marker -> {//w ww  .jav  a2 s. c  o  m
        T identifier = findIdentifier(marker);
        if (identifier != null) {
            groups.put(identifier, marker);
        }
    });
    for (T id : groups.keySet()) {
        List<IMarker> groupMarkers = Lists.newArrayList(groups.get(id));
        E node = createGroupNode(parent, id, groupMarkers);
        if (!children.isEmpty()) {
            List<IssueGroupNode<?>> nodeChildren = Lists.newArrayList();
            for (Group<?, ?> child : children) {
                List<IssueGroupNode<?>> tempChildren = child.createGroupNodesHelper(node, groupMarkers);
                if (!tempChildren.isEmpty()) {
                    nodeChildren.addAll(tempChildren);
                }
            }
            node.setChildren(nodeChildren);
        }
        nodes.add(node);
    }
    return nodes;
}