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

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

Introduction

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

Prototype

@Override
List<V> get(@Nullable K key);

Source Link

Document

Because the values for a given key may have duplicates and follow the insertion ordering, this method returns a List , instead of the java.util.Collection specified in the Multimap interface.

Usage

From source file:eu.esdihumboldt.hale.ui.service.groovy.internal.PreferencesGroovyService.java

/**
 * Calculates the current alignments script hash.
 * //from  w ww  . j a  v  a2 s.c o  m
 * @return the current alignments script hash
 */
private synchronized String getScriptHash() {
    if (scriptHash == null) {
        List<String> scripts = new ArrayList<>();
        // get all Groovy scripts
        for (Cell cell : alignmentService.getAlignment().getCells()) {
            ListMultimap<String, ParameterValue> parameters = cell.getTransformationParameters();
            if (parameters == null)
                continue;
            // Groovy transformations
            if (cell.getTransformationIdentifier().contains("groovy")) {
                List<ParameterValue> val = parameters.get(GroovyConstants.PARAMETER_SCRIPT);
                if (!val.isEmpty()) {
                    String script = getScriptString(val.get(0));
                    if (script != null) {
                        scripts.add(script);
                    }
                }
            }
            // GroovyScript function parameters
            for (ParameterValue value : parameters.values()) {
                if (GroovyScript.GROOVY_SCRIPT_ID.equals(value.getType())) {
                    String script = getScriptString(value);
                    if (script != null) {
                        scripts.add(script);
                    }
                }
            }
        }

        // Groovy scripts of custom property functions
        for (CustomPropertyFunction customFunction : alignmentService.getAlignment()
                .getAllCustomPropertyFunctions().values()) {
            if (customFunction instanceof DefaultCustomPropertyFunction) {
                DefaultCustomPropertyFunction cf = (DefaultCustomPropertyFunction) customFunction;
                if (CustomPropertyFunctionType.GROOVY.equals(cf.getFunctionType())) {
                    Value functionDef = cf.getFunctionDefinition();
                    if (functionDef != null && !functionDef.isEmpty()) {
                        String script = getScriptString(functionDef);
                        if (script != null) {
                            scripts.add(script);
                        }
                    }
                }
            }
        }

        // order scripts (for consistent hash)
        Collections.sort(scripts);

        // compute hash
        // not simply using hashCode, because it would be far to easy to
        // modify the script in a undetectable way
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            for (String script : scripts)
                md.update(script.getBytes("UTF-8"));
            byte[] hash = md.digest();
            StringBuilder sb = new StringBuilder(2 * hash.length);
            for (byte b : hash) {
                sb.append(String.format("%02x", b & 0xff));
            }
            scriptHash = sb.toString();
            // Both exceptions cannot happen in a valid Java platform.
            // Anyways, if they happen, execution should stop here!
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("No MD5 MessageDigest!");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("No UTF-8 Charset!");
        }
    }
    return scriptHash;
}

From source file:com.qcadoo.mes.workPlans.pdf.document.component.OperationSection.java

public void print(PdfWriter pdfWriter, GroupingContainer groupingContainer, Document document, Locale locale)
        throws DocumentException {
    if (notPrintOperationAtFirstPage()) {
        document.newPage();/*from ww  w.  ja v a 2  s.co m*/
    }

    ListMultimap<String, OrderOperationComponent> titleToOperationComponent = groupingContainer
            .getTitleToOperationComponent();
    for (String title : titleToOperationComponent.keySet()) {
        operationSectionHeader.print(document, title);
        int count = 0;
        for (OrderOperationComponent orderOperationComponent : groupingContainer.getTitleToOperationComponent()
                .get(title)) {
            count++;
            operationOrderSection.print(pdfWriter, groupingContainer, orderOperationComponent.getOrder(),
                    orderOperationComponent.getOperationComponent(), document, locale);
            if (count != titleToOperationComponent.get(title).size()) {
                if (notPrintOperationAtFirstPage()) {
                    document.add(Chunk.NEXTPAGE);
                }
            }
        }
    }
}

From source file:org.apache.jackrabbit.oak.plugins.index.lucene.IndexAugmentorFactory.java

private void refreshIndexFieldProviders() {
    ListMultimap<String, IndexFieldProvider> providerMultimap = LinkedListMultimap.create();
    for (IndexFieldProvider provider : indexFieldProviders) {
        Set<String> supportedNodeTypes = provider.getSupportedTypes();
        for (String nodeType : supportedNodeTypes) {
            providerMultimap.put(nodeType, provider);
        }// ww w. ja va 2s .c  o  m
    }

    Map<String, CompositeIndexFieldProvider> providerMap = Maps.newHashMap();
    for (String nodeType : providerMultimap.keySet()) {
        List<IndexFieldProvider> providers = providerMultimap.get(nodeType);
        CompositeIndexFieldProvider compositeIndexFieldProvider = new CompositeIndexFieldProvider(nodeType,
                providers);
        providerMap.put(nodeType, compositeIndexFieldProvider);
    }

    indexFieldProviderMap = ImmutableMap.copyOf(providerMap);
}

From source file:org.obiba.onyx.quartz.editor.locale.LabelsPanel.java

/**
 * @param id/*from  w  w  w. jav a2 s . c  o  m*/
 * @param model
 * @param elementModel
 * @param feedbackPanel
 * @param feedbackWindow
 * @param tooltips
 * @param visibleStates  Map with label element as key and a boolean set to true to show it or false to hide it.
 *                       Set to null to display all labels.
 */
public LabelsPanel(String id, IModel<LocaleProperties> model,
        IModel<? extends IQuestionnaireElement> elementModel, FeedbackPanel feedbackPanel,
        FeedbackWindow feedbackWindow, Map<String, IModel<String>> tooltips,
        final Map<String, Boolean> visibleStates) {
    super(id, model);
    this.elementModel = elementModel;
    this.tooltips = tooltips;
    setOutputMarkupId(true);

    add(CSSPackageResource.getHeaderContribution(LabelsPanel.class, "LabelsPanel.css"));

    LocaleProperties localeProperties = (LocaleProperties) getDefaultModelObject();
    final ListMultimap<Locale, KeyValue> elementLabels = localeProperties
            .getElementLabels(elementModel.getObject());
    Locale userLocale = Session.get().getLocale();

    List<ITab> tabs = new ArrayList<ITab>();
    for (final Locale locale : localeProperties.getLocales()) {
        AbstractTab tab = new AbstractTab(new Model<String>(locale.getDisplayLanguage(userLocale))) {
            @Override
            public Panel getPanel(String panelId) {
                return new InputPanel(panelId, new ListModel<KeyValue>(elementLabels.get(locale)),
                        visibleStates);
            }
        };
        ITab panelCachingTab = new PanelCachingTab(tab);
        tabs.add(panelCachingTab);
        tabByLocale.put(locale, panelCachingTab);
    }

    tabbedPanel = new AjaxSubmitTabbedPanel("tabs", feedbackPanel, feedbackWindow, tabs);
    tabbedPanel.setVisible(tabs.size() > 0);

    tabsContainer = new WebMarkupContainer("tabsContainer");
    tabsContainer.setOutputMarkupId(true);
    tabsContainer.add(tabbedPanel);

    Form<LocaleProperties> form = new Form<LocaleProperties>("form", model);
    form.setMultiPart(false);
    form.setOutputMarkupId(true);
    form.add(tabsContainer);
    add(form);
}

From source file:org.opencb.opencga.storage.mongodb.variant.load.stage.MongoDBVariantStageLoader.java

/**
 * Given a map of id -> binary[], inserts the binary objects in the stage collection.
 *
 * {//from   w  w w .  j a va2s  . com
 *     <studyId> : {
 *         <fileId> : [ BinData(), BinData() ]
 *     }
 * }
 *
 * The field <fileId> is an array to detect duplicated variants within the same file.
 *
 * It may happen that an update with upsert:true fail if two different threads try to
 * update the same non existing document.
 * See https://jira.mongodb.org/browse/SERVER-14322
 *
 * In that case, the non inserted values will be returned.
 *
 * @param values        Map with all the values to insert
 * @param result        MongoDBVariantWriteResult to fill
 * @param retryIds      List of IDs to retry. If not null, only will update those documents within this set
 * @return              List of non updated documents.
 * @throws MongoBulkWriteException if the exception was not a DuplicatedKeyException (e:11000)
 */
private Set<String> updateMongo(ListMultimap<Document, Binary> values, MongoDBVariantWriteResult result,
        Set<String> retryIds) {

    Set<String> nonInsertedIds = Collections.emptySet();
    if (values.isEmpty()) {
        return nonInsertedIds;
    }
    List<Bson> queries = new LinkedList<>();
    List<Bson> updates = new LinkedList<>();
    for (Document id : values.keySet()) {
        if (retryIds == null || retryIds.contains(id.getString("_id"))) {
            List<Binary> binaryList = values.get(id);
            queries.add(eq("_id", id.getString("_id")));
            if (binaryList.size() == 1) {
                updates.add(combine(
                        resumeStageLoad ? addToSet(fieldName, binaryList.get(0))
                                : push(fieldName, binaryList.get(0)),
                        setOnInsert(END_FIELD, id.get(END_FIELD)), setOnInsert(REF_FIELD, id.get(REF_FIELD)),
                        setOnInsert(ALT_FIELD, id.get(ALT_FIELD))));
            } else {
                updates.add(combine(
                        resumeStageLoad ? addEachToSet(fieldName, binaryList) : pushEach(fieldName, binaryList),
                        setOnInsert(END_FIELD, id.get(END_FIELD)), setOnInsert(REF_FIELD, id.get(REF_FIELD)),
                        setOnInsert(ALT_FIELD, id.get(ALT_FIELD))));
            }
        }
    }

    try {
        final BulkWriteResult mongoResult = collection.update(queries, updates, QUERY_OPTIONS).first();
        result.setNewVariants(mongoResult.getInsertedCount())
                .setUpdatedVariants(mongoResult.getModifiedCount());
    } catch (MongoBulkWriteException e) {
        result.setNewVariants(e.getWriteResult().getInsertedCount())
                .setUpdatedVariants(e.getWriteResult().getModifiedCount());

        if (retryIds != null) {
            // If retryIds != null, means that this this was the second attempt to update. In this case, do fail.
            LOGGER.error("BulkWriteErrors when retrying the updates");
            throw e;
        }

        nonInsertedIds = new HashSet<>();
        for (BulkWriteError writeError : e.getWriteErrors()) {
            if (ErrorCategory.fromErrorCode(writeError.getCode()).equals(ErrorCategory.DUPLICATE_KEY)) { //Dup Key error code
                Matcher matcher = DUP_KEY_WRITE_RESULT_ERROR_PATTERN.matcher(writeError.getMessage());
                if (matcher.find()) {
                    String id = matcher.group(1);
                    nonInsertedIds.add(id);
                    LOGGER.warn("Catch error : {}", writeError.toString());
                    LOGGER.warn("DupKey exception inserting '{}'. Retry!", id);
                } else {
                    LOGGER.error("WriteError with code {} does not match with the pattern {}",
                            writeError.getCode(), DUP_KEY_WRITE_RESULT_ERROR_PATTERN.pattern());
                    throw e;
                }
            } else {
                throw e;
            }
        }
    }
    return nonInsertedIds;
}

From source file:org.nmdp.validation.tools.ExtractMugs.java

@Override
public Integer call() throws Exception {
    BufferedReader reader = null;
    PrintWriter writer = null;/*  w ww. java 2 s. c  om*/
    try {
        reader = reader(inputHmlFile);
        writer = writer(outputFile);

        Hml hml = HmlReader.read(reader);
        for (Sample sample : hml.getSample()) {
            String sampleId = sample.getId();
            List<String> genotypes = new ArrayList<String>();
            if (!subjectId.isEmpty() && subjectId.equals(sampleId)) {
                for (Typing typing : sample.getTyping()) {
                    String geneFamily = typing.getGeneFamily();
                    for (AlleleAssignment alleleAssignment : typing.getAlleleAssignment()) {
                        String alleleDb = alleleAssignment.getAlleleDb();
                        String alleleVersion = alleleAssignment.getAlleleVersion();

                        ListMultimap<String, Haploid> haploidsByLocus = ArrayListMultimap.create();
                        for (Object child : alleleAssignment.getPropertyAndHaploidAndGenotypeList()) {
                            if (child instanceof Haploid) {
                                Haploid haploid = (Haploid) child;
                                haploidsByLocus.put(haploid.getLocus(), haploid);
                            }
                        }
                        for (String locus : haploidsByLocus.keySet()) {
                            List<Haploid> haploids = haploidsByLocus.get(locus);

                            String genotype = toGenotype(haploids.get(0),
                                    haploids.size() > 1 ? haploids.get(1) : null);
                            genotypes.add(genotype);
                        }
                    }
                }
                String glstring = Joiner.on("^").join(genotypes);
                writer.println(sampleId + "\t" + glstring);
            }
        }
        return 0;
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
            // ignore
        }
        try {
            writer.close();
        } catch (Exception e) {
            // ignore
        }
    }
}

From source file:com.google.template.soy.PerInputOutputFiles.java

void writeFiles(List<File> srcs, List<String> jsOuts, @Nullable String locale) {
    if (srcs.size() != jsOuts.size()) {
        throw new AssertionError(
                String.format("Expected to generate %d code chunk(s), got %d", srcs.size(), jsOuts.size()));
    }//from   w w w . ja v a 2  s . c  o m

    ListMultimap<Path, String> outputPathToJs = MultimapBuilder.linkedHashKeys().arrayListValues().build();
    for (int i = 0; i < srcs.size(); i++) {
        outputPathToJs.put(getOutputPath(srcs.get(i), locale), jsOuts.get(i));
    }
    for (Path outputPath : outputPathToJs.keySet()) {
        if (outputPath.getParent() != null) {
            outputPath.getParent().toFile().mkdirs();
        }
        try {
            // Having multiple input files map to the same output file is only possible with the
            // --outputPathFormat flag
            MoreFiles.asCharSink(outputPath, UTF_8).write(fileJoiner.join(outputPathToJs.get(outputPath)));
        } catch (IOException ioe) {
            throw new CommandLineError("Failed to write: " + outputPath + ": " + ioe.getMessage(), ioe);
        }
    }
}

From source file:org.nmdp.ngs.tools.ValidateInterpretation.java

@Override
public Integer call() throws Exception {
    PrintWriter writer = null;//from  ww w  .  j  a va2  s.c  o m

    int passes = 0;
    int failures = 0;
    try {
        writer = writer(outputFile);

        // interpretations keyed by sample
        ListMultimap<String, Interpretation> expected = read(expectedFile);
        ListMultimap<String, Interpretation> observed = read(observedFile);

        // for each sample in observed
        for (String sample : observed.keySet()) {

            // for each interpretation in expected with matching sample
            for (Interpretation e : expected.get(sample)) {
                Genotype expectedGenotype = asGenotype(e);
                for (Haplotype expectedHaplotype : expectedGenotype.getHaplotypes()) {
                    for (AlleleList expectedAlleleList : expectedHaplotype.getAlleleLists()) {
                        if (shouldValidate(e, expectedAlleleList)) {

                            // for each pair of expected and observed alleles
                            for (Allele expectedAllele : expectedAlleleList.getAlleles()) {
                                boolean match = false;
                                for (Interpretation o : observed.get(sample)) {
                                    AlleleList observedAlleleList = asAlleleList(o);
                                    if (sameLocus(observedAlleleList, expectedAlleleList)) {
                                        for (Allele observedAllele : observedAlleleList.getAlleles()) {
                                            if (matchByField(expectedAllele.getGlstring(),
                                                    observedAllele.getGlstring()) >= resolution) {
                                                match = true;
                                                break;
                                            }
                                        }
                                    }
                                    if (match) {
                                        passes++;
                                    } else {
                                        failures++;
                                    }
                                }
                                if (!printSummary) {
                                    writer.println(
                                            (match ? "PASS" : "FAIL") + "\t" + sample + "\t" + expectedAllele);
                                }
                            }
                        }
                    }
                }
            }
        }
        if (printSummary) {
            writer.println("PASS\t" + passes);
            writer.println("FAIL\t" + failures);
        }

        return 0;
    } finally {
        try {
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}

From source file:com.b2international.snowowl.snomed.datastore.converter.SnomedConceptConverter.java

private void expandDescriptions(List<SnomedConcept> results, final Set<String> conceptIds) {
    if (!expand().containsKey(SnomedConcept.Expand.DESCRIPTIONS)) {
        return;/*  w  ww  . ja  va 2  s .c om*/
    }

    final Options expandOptions = expand().get(SnomedConcept.Expand.DESCRIPTIONS, Options.class);
    final SnomedDescriptions descriptions = SnomedRequests.prepareSearchDescription().all()
            .setExpand(expandOptions.get("expand", Options.class))
            .filterByType(expandOptions.containsKey("typeId") ? expandOptions.getString("typeId") : null)
            .filterByConceptId(conceptIds).setLocales(locales()).build().execute(context());

    final ListMultimap<String, SnomedDescription> descriptionsByConceptId = Multimaps.index(descriptions,
            description -> description.getConceptId());

    for (SnomedConcept concept : results) {
        final List<SnomedDescription> conceptDescriptions = descriptionsByConceptId.get(concept.getId());
        concept.setDescriptions(new SnomedDescriptions(conceptDescriptions, null, null,
                conceptDescriptions.size(), conceptDescriptions.size()));
    }
}

From source file:org.onos.yangtools.yang.model.repo.util.AbstractSchemaRepository.java

@Override
public <T extends SchemaSourceRepresentation> CheckedFuture<T, SchemaSourceException> getSchemaSource(
        final SourceIdentifier id, final Class<T> representation) {
    final ListMultimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> srcs = sources
            .get(id);/*from   w  w w . ja  va2s . co  m*/
    if (srcs == null) {
        return Futures.<T, SchemaSourceException>immediateFailedCheckedFuture(
                new MissingSchemaSourceException("No providers registered for source" + id, id));
    }

    // TODO, remove and make sources keep sorted multimap (e.g. ArrayListMultimap with SortedLists)
    final ArrayList<AbstractSchemaSourceRegistration<?>> sortedSchemaSourceRegistrations = Lists
            .newArrayList(srcs.get(representation));
    Collections.sort(sortedSchemaSourceRegistrations, SchemaProviderCostComparator.INSTANCE);

    final Iterator<AbstractSchemaSourceRegistration<?>> regs = sortedSchemaSourceRegistrations.iterator();
    if (!regs.hasNext()) {
        return Futures.<T, SchemaSourceException>immediateFailedCheckedFuture(new MissingSchemaSourceException(
                "No providers for source " + id + " representation " + representation + " available", id));
    }

    CheckedFuture<T, SchemaSourceException> fetchSourceFuture = fetchSource(id, regs);
    // Add callback to notify cache listeners about encountered schema
    Futures.addCallback(fetchSourceFuture, new FutureCallback<T>() {
        @Override
        public void onSuccess(final T result) {
            for (final SchemaListenerRegistration listener : listeners) {
                listener.getInstance().schemaSourceEncountered(result);
            }
        }

        @Override
        public void onFailure(final Throwable t) {
            LOG.trace("Skipping notification for encountered source {}, fetching source failed", id, t);
        }
    });

    return fetchSourceFuture;
}