Example usage for com.google.common.collect HashMultimap create

List of usage examples for com.google.common.collect HashMultimap create

Introduction

In this page you can find the example usage for com.google.common.collect HashMultimap create.

Prototype

public static <K, V> HashMultimap<K, V> create() 

Source Link

Document

Creates a new, empty HashMultimap with the default initial capacities.

Usage

From source file:eu.esdihumboldt.util.resource.Resources.java

private static synchronized void init() {
    if (resolvers == null) {
        resolvers = new HashMap<String, Multimap<String, ResourceResolver>>();

        // register resolvers
        for (ResolverConfiguration resolverConf : ResolverExtension.getInstance().getElements()) {
            String resourceType = resolverConf.getResourceTypeId();

            Multimap<String, ResourceResolver> typeResolvers = resolvers.get(resourceType);
            if (typeResolvers == null) {
                typeResolvers = HashMultimap.create();
                resolvers.put(resourceType, typeResolvers);
            }//from   w w  w .j a v  a  2 s  .  c  om

            for (String host : resolverConf.getHosts()) {
                typeResolvers.put(host, resolverConf.getResourceResolver());
            }
        }
    }
}

From source file:eu.esdihumboldt.hale.ui.style.TypeStyleHandler.java

/**
 * @see IHandler#execute(ExecutionEvent)
 *//*from   w  w w  . java  2 s  .  c o m*/
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    ISelection selection = HandlerUtil.getCurrentSelection(event);

    // collect types and associated data sets
    SetMultimap<DataSet, TypeDefinition> types = HashMultimap.create();
    if (selection instanceof IStructuredSelection && !selection.isEmpty()) {
        for (Object object : ((IStructuredSelection) selection).toArray()) {
            if (object instanceof TypeDefinition) {
                TypeDefinition type = (TypeDefinition) object;
                if (!types.containsValue(type)) {
                    DataSet dataSet = findDataSet(type);
                    types.put(dataSet, type);
                }
            }
            if (object instanceof EntityDefinition) {
                EntityDefinition entityDef = (EntityDefinition) object;
                if (entityDef.getPropertyPath().isEmpty()) {
                    DataSet dataSet = (entityDef.getSchemaSpace() == SchemaSpaceID.SOURCE) ? (DataSet.SOURCE)
                            : (DataSet.TRANSFORMED);
                    types.put(dataSet, entityDef.getType());
                }
            }
            if (object instanceof InstanceReference) {
                InstanceService is = (InstanceService) HandlerUtil.getActiveWorkbenchWindow(event)
                        .getWorkbench().getService(InstanceService.class);
                object = is.getInstance((InstanceReference) object);
            }
            if (object instanceof Instance) {
                Instance instance = (Instance) object;
                types.put(instance.getDataSet(), instance.getDefinition());
            }
        }
    }

    Pair<TypeDefinition, DataSet> typeInfo = null;

    // select a type
    if (types.size() == 1) {
        Entry<DataSet, TypeDefinition> entry = types.entries().iterator().next();
        typeInfo = new Pair<TypeDefinition, DataSet>(entry.getValue(), entry.getKey());
    } else if (!types.isEmpty()) {
        // choose through dialog
        DataSetTypeSelectionDialog dialog = new DataSetTypeSelectionDialog(
                Display.getCurrent().getActiveShell(), "Multiple types: select which to change the style for",
                null, types);
        if (dialog.open() == DataSetTypeSelectionDialog.OK) {
            typeInfo = dialog.getObject();
        }
    }

    if (typeInfo != null) {
        try {
            FeatureStyleDialog dialog = new FeatureStyleDialog(typeInfo.getFirst(), typeInfo.getSecond());
            dialog.setBlockOnOpen(false);
            dialog.open();
        } catch (Exception e) {
            throw new ExecutionException("Could not open style dialog", e);
        }
    }
    return null;
}

From source file:org.sonar.batch.BatchPluginRepository.java

public void start() {
    HashMultimap<String, URL> urlsByKey = HashMultimap.create();
    for (JpaPluginFile pluginFile : dao.getPluginFiles()) {
        try {/*  ww  w .  ja  v a 2s  . com*/
            String key = getClassloaderKey(pluginFile.getPluginKey());
            URL url = new URL(baseUrl + pluginFile.getPath());
            urlsByKey.put(key, url);

        } catch (MalformedURLException e) {
            throw new SonarException("Can not build the classloader of the plugin " + pluginFile.getPluginKey(),
                    e);
        }
    }

    classloaders = new HashMap<String, ClassLoader>();
    for (String key : urlsByKey.keySet()) {
        Set<URL> urls = urlsByKey.get(key);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Classloader of plugin " + key + ":");
            for (URL url : urls) {
                LOG.debug("   -> " + url);
            }
        }
        classloaders.put(key,
                new RemoteClassLoader(urls, Thread.currentThread().getContextClassLoader()).getClassLoader());
    }
}

From source file:edu.cmu.lti.oaqa.baseqa.answer.collective_score.scorers.EditDistanceCollectiveAnswerScorer.java

@SuppressWarnings("unchecked")
@Override//www  .ja va 2  s. c  o m
public void prepare(JCas jcas) {
    answers = TypeUtil.getRankedAnswers(jcas);
    distances = HashBasedTable.create();
    ImmutableSet<Answer> answerSet = ImmutableSet.copyOf(answers);
    SetMultimap<Answer, String> answer2names = HashMultimap.create();
    answers.forEach(answer -> TypeUtil.getCandidateAnswerVariantNames(answer).stream().map(String::toLowerCase)
            .forEach(name -> answer2names.put(answer, name)));
    for (List<Answer> pair : Sets.cartesianProduct(answerSet, answerSet)) {
        Answer answer1 = pair.get(0);
        Answer answer2 = pair.get(1);
        if (answer1.equals(answer2)) {
            distances.put(answer1, answer2, 1.0);
        } else {
            Sets.cartesianProduct(answer2names.get(answer1), answer2names.get(answer2)).stream()
                    .mapToDouble(namepair -> getDistance(namepair.get(0), namepair.get(1))).min()
                    .ifPresent(x -> distances.put(answer1, answer2, 1.0 - x));
        }
    }
}

From source file:com.b2international.snowowl.snomed.datastore.internal.id.reservations.UniqueInStoreReservation.java

@Override
public Set<SnomedIdentifier> intersection(Set<SnomedIdentifier> identifiers) {
    final Multimap<ComponentCategory, String> identifiersByCategory = HashMultimap.create();
    identifiers.forEach(identifier -> {
        identifiersByCategory.put(identifier.getComponentCategory(), identifier.toString());
    });/*from   w w w .j a va  2 s . c  o  m*/

    final ImmutableSet.Builder<SnomedIdentifier> intersection = ImmutableSet.builder();

    for (ComponentCategory category : identifiersByCategory.keySet()) {
        final SnomedSearchRequestBuilder<?, ? extends PageableCollectionResource<?>> searchRequest;
        final Collection<String> identifiersToCheck = identifiersByCategory.get(category);

        switch (category) {
        case CONCEPT:
            searchRequest = SnomedRequests.prepareSearchConcept();
            break;
        case DESCRIPTION:
            searchRequest = SnomedRequests.prepareSearchDescription();
            break;
        case RELATIONSHIP:
            searchRequest = SnomedRequests.prepareSearchRelationship();
            break;
        default:
            throw new NotImplementedException("Cannot check whether components of type '%s' are unique.",
                    category);
        }

        final PageableCollectionResource<?> results = searchRequest.all().filterByIds(identifiersToCheck)
                .setFields(SnomedComponentDocument.Fields.ID)
                .build(SnomedDatastoreActivator.REPOSITORY_UUID, BranchPathUtils.createMainPath().getPath())
                .execute(bus.get()).getSync();

        results.stream().filter(SnomedComponent.class::isInstance).map(SnomedComponent.class::cast)
                .map(SnomedComponent::getId).map(SnomedIdentifiers::create).forEach(intersection::add);
    }

    return intersection.build();
}

From source file:uk.ac.ebi.mnb.dialog.tools.RemoveWorstStructures.java

/**
 * @inheritDoc/*from  w w w  . j  a va2  s . c  om*/
 */
@Override
public void actionPerformed(ActionEvent e) {

    Collection<Metabolite> metabolites = getSelection().get(Metabolite.class);

    CompoundEdit edit = new CompoundEdit();

    for (Metabolite m : metabolites) {

        if (m.hasAnnotation(MolecularFormula.class) && m.hasAnnotation(Charge.class)) {

            Multimap<Category, ChemicalStructure> map = HashMultimap.create();

            Charge charge = m.getAnnotations(Charge.class).iterator().next();
            Collection<MolecularFormula> formulas = m.getAnnotations(MolecularFormula.class);
            Set<ChemicalStructure> structures = m.getAnnotationsExtending(ChemicalStructure.class);
            Category best = Category.UNKNOWN;

            for (ChemicalStructure structure : structures) {

                Category validity = StructuralValidity.getValidity(formulas, structure, charge).getCategory();

                map.put(validity, structure);

                if (validity.ordinal() > best.ordinal()) {
                    best = validity;
                }
            }

            if (best == Category.CORRECT) {
                map.removeAll(Category.CORRECT);
                Collection<Annotation> worse = new ArrayList<Annotation>(map.values());
                edit.addEdit(new RemoveAnnotationEdit(m, worse));
                for (Annotation annotation : worse)
                    m.removeAnnotation(annotation);
            } else if (best == Category.WARNING) {
                map.removeAll(Category.WARNING);
                Collection<Annotation> worse = new ArrayList<Annotation>(map.values());
                edit.addEdit(new RemoveAnnotationEdit(m, worse));
                for (Annotation annotation : worse)
                    m.removeAnnotation(annotation);
            }
        }
    }

    edit.end();

    getController().getUndoManager().addEdit(edit);
    update(getSelection());

}

From source file:org.opennms.features.topology.plugins.topo.linkd.internal.OspfLinkStatusProvider.java

@Override
protected List<EdgeAlarmStatusSummary> getEdgeAlarmSummaries(List<Integer> linkIds) {
    org.opennms.core.criteria.Criteria criteria = new org.opennms.core.criteria.Criteria(OspfLink.class);
    criteria.addRestriction(new InRestriction("id", linkIds));

    List<OspfLink> links = getOspfLinkDao().findMatching(criteria);
    Multimap<String, EdgeAlarmStatusSummary> summaryMap = HashMultimap.create();
    for (OspfLink sourceLink : links) {
        OnmsNode sourceNode = sourceLink.getNode();
        for (OspfLink targetLink : links) {
            boolean ipAddrCheck = sourceLink.getOspfRemIpAddr().equals(targetLink.getOspfIpAddr())
                    && targetLink.getOspfRemIpAddr().equals(sourceLink.getOspfIpAddr());
            if (ipAddrCheck) {
                summaryMap.put(sourceNode.getNodeId() + ":" + sourceLink.getOspfIfIndex(),
                        new EdgeAlarmStatusSummary(sourceLink.getId(), targetLink.getId(), null));
            }/* w  w w.  j  a v  a 2 s  .c  o m*/
        }
    }

    List<OnmsAlarm> alarms = getLinkDownAlarms();

    for (OnmsAlarm alarm : alarms) {
        String key = alarm.getNodeId() + ":" + alarm.getIfIndex();
        if (summaryMap.containsKey(key)) {

            Collection<EdgeAlarmStatusSummary> summaries = summaryMap.get(key);
            for (EdgeAlarmStatusSummary summary : summaries) {
                summary.setEventUEI(alarm.getUei());
            }

        }

    }

    return new ArrayList<EdgeAlarmStatusSummary>(summaryMap.values());

}

From source file:unioeste.geral.servlet.GraficosServlet.java

public long carregaDadosAnoAtual(Object ano, Object curso) {

    Multimap<String, Object> condicaoAND = HashMultimap.create();

    condicaoAND.put("curso", curso);
    condicaoAND.put("anoAtual", ano);

    return new AlunoManager().recuperarQtdAlunosPorAtributos(condicaoAND, null);

}

From source file:com.enitalk.opentok.OpenTokListener.java

@Scheduled(fixedDelay = 10000L)
public void updateFinalStatus() {
    try {//from  w ww. j ava  2s .c o m
        Criteria cc3 = Criteria.where("status").is(2);
        Criteria cc1 = Criteria.where("video").exists(false);
        Query q = Query.query(Criteria.where("endDate").lt(new DateTime().toDate()).andOperator(cc3, cc1));
        q.fields().exclude("_id").include("opentok").include("ii");

        List<HashMap> eligibleEvents = mongo.find(q, HashMap.class, "events");
        if (!eligibleEvents.isEmpty()) {
            ArrayNode evs = jackson.convertValue(eligibleEvents, ArrayNode.class);
            Iterator<JsonNode> evIt = evs.elements();
            while (evIt.hasNext()) {
                JsonNode ev = evIt.next();
                HashMultimap<String, String> mmap = HashMultimap.create();

                List<JsonNode> alls = ev.path("opentok").findParents("id");
                alls.forEach((JsonNode op) -> {
                    mmap.put(op.path("id").asText(), op.path("status").asText());
                });

                logger.info("Opentok multimap {}", mmap);
                long uploadedArchives = mmap.keySet().stream().filter((String id) -> {
                    return mmap.get(id).contains("uploaded");
                }).count();
                if (uploadedArchives == mmap.keySet().size()) {
                    logger.info("All archives uploaded, process further");
                    mongo.updateFirst(Query.query(Criteria.where("ii").is(ev.path("ii").asText())),
                            new Update().set("video", 0), "events");

                } else {
                    logger.info("Only {} of {} archives uploaded", uploadedArchives, mmap);
                }
            }
        }

    } catch (Exception e) {
        logger.error(ExceptionUtils.getFullStackTrace(e));
    }
}

From source file:edu.byu.nlp.data.util.EmpiricalAnnotations.java

public Multimap<Integer, FlatInstance<D, L>> getAnnotationsFor(String source, D data) {
    if (source == null) {
        // measurement request (not attached to any specific document)
        return getPerAnnotatorMeasurements();
    } else if (annotations.containsKey(source)) {
        return annotations.get(source);
    }//w  w  w .  j a  va2  s.  co  m
    return HashMultimap.create();
}