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

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

Introduction

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

Prototype

@Override
Map<K, Collection<V>> asMap();

Source Link

Document

Note: The returned map's values are guaranteed to be of type List .

Usage

From source file:com.rk.grid.server.ExecutionServer.java

private final <T> void submitBatch(Collection<ITask<T>> batch, ProxyJobResultHandler<T> proxyHandler) {
    if (batch.size() == 0)
        return;//from  ww  w. j  a va 2 s . c o  m

    ListMultimap<String, ITask<T>> tasksByService = Multimaps.index(batch, new Function<ITask<T>, String>() {
        public String apply(ITask<T> task) {
            return task.getInvocationNamespace();
        }
    });

    Map<String, Collection<ITask<T>>> tasksByServiceMap = tasksByService.asMap();

    for (String requiredService : tasksByServiceMap.keySet()) {
        if (this.executorMap.containsKey(requiredService)) {
            ITaskExecutor taskExecutor = this.executorMap.get(requiredService);
            try {
                IResultHandler<T> delegate = proxyHandler.newDelegate();
                taskExecutor.execute(tasksByServiceMap.get(requiredService), delegate);
            } catch (Exception e) {
                e.printStackTrace();
                proxyHandler.onError(e);
            }
        } else {
            System.out.println("XXX" + requiredService);
            proxyHandler.onRejection(tasksByServiceMap.get(requiredService));
        }
    }
}

From source file:com.google.gerrit.server.change.WalkSorter.java

public Iterable<PatchSetData> sort(Iterable<ChangeData> in) throws OrmException, IOException {
    ListMultimap<Project.NameKey, ChangeData> byProject = MultimapBuilder.hashKeys().arrayListValues().build();
    for (ChangeData cd : in) {
        byProject.put(cd.change().getProject(), cd);
    }//from www .j  av a  2s  . c o m

    List<List<PatchSetData>> sortedByProject = new ArrayList<>(byProject.keySet().size());
    for (Map.Entry<Project.NameKey, Collection<ChangeData>> e : byProject.asMap().entrySet()) {
        sortedByProject.add(sortProject(e.getKey(), e.getValue()));
    }
    Collections.sort(sortedByProject, PROJECT_LIST_SORTER);
    return Iterables.concat(sortedByProject);
}

From source file:com.google.gerrit.server.change.IncludedIn.java

public IncludedInInfo apply(Project.NameKey project, String revisionId) throws RestApiException, IOException {
    try (Repository r = repoManager.openRepository(project); RevWalk rw = new RevWalk(r)) {
        rw.setRetainBody(false);//  ww w  . j  a  v a 2  s  . c  om
        RevCommit rev;
        try {
            rev = rw.parseCommit(ObjectId.fromString(revisionId));
        } catch (IncorrectObjectTypeException err) {
            throw new BadRequestException(err.getMessage());
        } catch (MissingObjectException err) {
            throw new ResourceConflictException(err.getMessage());
        }

        IncludedInResolver.Result d = IncludedInResolver.resolve(r, rw, rev);
        ListMultimap<String, String> external = MultimapBuilder.hashKeys().arrayListValues().build();
        for (ExternalIncludedIn ext : externalIncludedIn) {
            ListMultimap<String, String> extIncludedIns = ext.getIncludedIn(project.get(), rev.name(),
                    d.getTags(), d.getBranches());
            if (extIncludedIns != null) {
                external.putAll(extIncludedIns);
            }
        }
        return new IncludedInInfo(d.getBranches(), d.getTags(),
                (!external.isEmpty() ? external.asMap() : null));
    }
}

From source file:com.teradata.benchto.service.model.BenchmarkRun.java

public Map<String, AggregatedMeasurement> getAggregatedMeasurements() {
    if (aggregatedMeasurements == null && Hibernate.isInitialized(executions)) {
        ListMultimap<Measurement, Double> measurementValues = ArrayListMultimap.create();
        for (BenchmarkRunExecution execution : executions) {
            for (Measurement measurement : execution.getMeasurements()) {
                measurementValues.put(measurement, measurement.getValue());
            }/*www. j a  va 2  s .  c o  m*/
        }
        aggregatedMeasurements = measurementValues.asMap().entrySet().stream()
                .collect(toMap(entry -> entry.getKey().getName(),
                        entry -> aggregate(entry.getKey().getUnit(), entry.getValue())));
    }
    return aggregatedMeasurements;
}

From source file:gobblin.runtime.SafeDatasetCommit.java

@Override
public Void call() throws Exception {
    if (this.datasetState.getState() == JobState.RunningState.COMMITTED) {
        log.info(this.datasetUrn + " have been committed.");
        return null;
    }// w ww.ja  v  a 2  s  . c om
    finalizeDatasetStateBeforeCommit(this.datasetState);
    Class<? extends DataPublisher> dataPublisherClass;
    try (Closer closer = Closer.create()) {
        dataPublisherClass = JobContext.getJobDataPublisherClass(this.jobContext.getJobState()).or(
                (Class<? extends DataPublisher>) Class.forName(ConfigurationKeys.DEFAULT_DATA_PUBLISHER_TYPE));
        if (!canCommitDataset(datasetState)) {
            log.warn(String.format("Not committing dataset %s of job %s with commit policy %s and state %s",
                    this.datasetUrn, this.jobContext.getJobId(), this.jobContext.getJobCommitPolicy(),
                    this.datasetState.getState()));
            checkForUnpublishedWUHandling(this.datasetUrn, this.datasetState, dataPublisherClass, closer);
            throw new RuntimeException(
                    String.format("Not committing dataset %s of job %s with commit policy %s and state %s",
                            this.datasetUrn, this.jobContext.getJobId(), this.jobContext.getJobCommitPolicy(),
                            this.datasetState.getState()));
        }
    } catch (ReflectiveOperationException roe) {
        log.error("Failed to instantiate data publisher for dataset %s of job %s.", this.datasetUrn,
                this.jobContext.getJobId(), roe);
        throw new RuntimeException(roe);
    }

    if (this.isJobCancelled) {
        log.info("Executing commit steps although job is cancelled due to job commit policy: "
                + this.jobContext.getJobCommitPolicy());
    }

    Optional<CommitSequence.Builder> commitSequenceBuilder = Optional.absent();
    boolean canPersistStates = true;
    try (Closer closer = Closer.create()) {
        if (this.shouldCommitDataInJob) {
            log.info(String.format("Committing dataset %s of job %s with commit policy %s and state %s",
                    this.datasetUrn, this.jobContext.getJobId(), this.jobContext.getJobCommitPolicy(),
                    this.datasetState.getState()));

            ListMultimap<TaskFactoryWrapper, TaskState> taskStatesByFactory = groupByTaskFactory(
                    this.datasetState);

            for (Map.Entry<TaskFactoryWrapper, Collection<TaskState>> entry : taskStatesByFactory.asMap()
                    .entrySet()) {
                TaskFactory taskFactory = entry.getKey().getTaskFactory();

                if (this.deliverySemantics == DeliverySemantics.EXACTLY_ONCE) {
                    if (taskFactory != null) {
                        throw new RuntimeException(
                                "Custom task factories do not support exactly once delivery semantics.");
                    }
                    generateCommitSequenceBuilder(this.datasetState, entry.getValue());
                } else {
                    DataPublisher publisher = taskFactory == null
                            ? closer.register(DataPublisher.getInstance(dataPublisherClass,
                                    this.jobContext.getJobState()))
                            : taskFactory.createDataPublisher(this.datasetState);
                    if (this.isJobCancelled) {
                        if (publisher.canBeSkipped()) {
                            log.warn(publisher.getClass() + " will be skipped.");
                        } else {
                            canPersistStates = false;
                            throw new RuntimeException(
                                    "Cannot persist state upon cancellation because publisher has unfinished work and cannot be skipped.");
                        }
                    } else if (this.isMultithreaded && !publisher.isThreadSafe()) {
                        log.warn(String.format(
                                "Gobblin is set up to parallelize publishing, however the publisher %s is not thread-safe. "
                                        + "Falling back to serial publishing.",
                                publisher.getClass().getName()));
                        safeCommitDataset(entry.getValue(), publisher);
                    } else {
                        commitDataset(entry.getValue(), publisher);
                    }
                }
            }
            this.datasetState.setState(JobState.RunningState.COMMITTED);
        } else {
            if (this.datasetState.getState() == JobState.RunningState.SUCCESSFUL) {
                this.datasetState.setState(JobState.RunningState.COMMITTED);
            }
        }
    } catch (ReflectiveOperationException roe) {
        log.error(String.format("Failed to instantiate data publisher for dataset %s of job %s.",
                this.datasetUrn, this.jobContext.getJobId()), roe);
        throw new RuntimeException(roe);
    } catch (Throwable throwable) {
        log.error(String.format("Failed to commit dataset state for dataset %s of job %s", this.datasetUrn,
                this.jobContext.getJobId()), throwable);
        throw new RuntimeException(throwable);
    } finally {
        try {
            finalizeDatasetState(datasetState, datasetUrn);
            if (commitSequenceBuilder.isPresent()) {
                buildAndExecuteCommitSequence(commitSequenceBuilder.get(), datasetState, datasetUrn);
                datasetState.setState(JobState.RunningState.COMMITTED);
            } else if (canPersistStates) {
                persistDatasetState(datasetUrn, datasetState);
            }
        } catch (IOException | RuntimeException ioe) {
            log.error(String.format("Failed to persist dataset state for dataset %s of job %s", datasetUrn,
                    this.jobContext.getJobId()), ioe);
            throw new RuntimeException(ioe);
        }
    }
    return null;
}

From source file:org.exolin.sudoku.solver.Sudoku.java

private boolean solveUnit(Iterable<SudokoCell> unit) throws InconsistenceException {
    ListMultimap<Integer, SudokoCell> possiblities = Multimaps.newListMultimap(new HashMap<>(), ArrayList::new);

    for (SudokoCell cell : unit) {
        for (int possibleNumber : cell.getPossibleValues()) {
            possiblities.put(possibleNumber, cell);
        }//from  w ww .  j  ava  2s.c o m
    }

    boolean progress = false;

    for (Entry<Integer, Collection<SudokoCell>> e : possiblities.asMap().entrySet()) {
        int possibleNumber = e.getKey();
        Collection<SudokoCell> possibleCells = e.getValue();

        if (possibleCells.size() == 1) {
            SudokoCell next = possibleCells.iterator().next();

            if (!next.isComplete()) {
                next.setNumber(possibleNumber);
                progress = true;
            }
        }
    }

    return progress;
}

From source file:org.quil.interpreter.strata.QuilMarketDataBuilder.java

/**
 * Gets all rates curves./*from w ww.ja va2  s.co  m*/
 *
 * @return the map of all rates curves
 */
public SortedMap<LocalDate, CurveGroup> loadAllRatesCurves() {
    if (!subdirectoryExists(CURVES_DIR)) {
        throw new IllegalArgumentException("No rates curves directory found");
    }
    ResourceLocator curveGroupsResource = getResource(CURVES_DIR, CURVES_GROUPS_FILE);
    if (curveGroupsResource == null) {
        throw new IllegalArgumentException(
                Messages.format("Unable to load rates curves: curve groups file not found at {}/{}", CURVES_DIR,
                        CURVES_GROUPS_FILE));
    }
    ResourceLocator curveSettingsResource = getResource(CURVES_DIR, CURVES_SETTINGS_FILE);
    if (curveSettingsResource == null) {
        throw new IllegalArgumentException(
                Messages.format("Unable to load rates curves: curve settings file not found at {}/{}",
                        CURVES_DIR, CURVES_SETTINGS_FILE));
    }
    ListMultimap<LocalDate, CurveGroup> curveGroups = RatesCurvesCsvLoader.loadAllDates(curveGroupsResource,
            curveSettingsResource, getRatesCurvesResources());

    // There is only one curve group in the market data file so this will always succeed
    Map<LocalDate, CurveGroup> curveGroupMap = Maps.transformValues(curveGroups.asMap(),
            groups -> groups.iterator().next());
    return new TreeMap<>(curveGroupMap);
}

From source file:additionalpipes.inventory.ContainerTeleportManager.java

private void rebuildPipeProps() {
    ListMultimap<PropertyInteger, ITeleportPipe> pipeMultimap = ArrayListMultimap.create();
    for (ITeleportPipe pipe : TeleportManager.getPipes()) {
        for (int map : manager.getMapsLinkTo(pipe)) {
            pipeMultimap.put(PropertyInteger.create(map), pipe);
        }//from  w  w  w. j a  v a2  s .c  om
    }
    pipes = Maps.newHashMap(Maps.transformEntries(pipeMultimap.asMap(),
            new EntryTransformer<PropertyInteger, Collection<ITeleportPipe>, PropertyIntArray>() {
                @Override
                public PropertyIntArray transformEntry(PropertyInteger key, Collection<ITeleportPipe> value) {
                    int[] result = new int[value.size() * 3];
                    int i = 0;
                    for (ITeleportPipe pipe : value) {
                        result[i++] = pipe.getType().ordinal();
                        ChunkCoordinates pos = pipe.getPosition();
                        MapData mapData = Item.map.getMapData(
                                APUtils.createMapStack(key.value, manager.worldObj), manager.worldObj);
                        int size = 1 << mapData.scale;
                        float var11 = (pos.posX - mapData.xCenter) / (float) size;
                        float var12 = (pos.posZ - mapData.zCenter) / (float) size;
                        result[i++] = (int) (var11 * 2.0F + 0.5D);
                        result[i++] = (int) (var12 * 2.0F + 0.5D);
                    }
                    return PropertyIntArray.create(result);
                }
            }));

    if (!needToRebuild) {
        MinecraftForge.EVENT_BUS.post(new ContainerModifyEvent(this, manager));
    }
}

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

/**
 * The value is a sorted list with most recent version of index at the start
 */// w w w  . j  ava  2  s .  co  m
private Map<String, List<LocalIndexDir>> getIndexesPerPath() throws IOException {
    File[] dirs = indexRootDir.listFiles(LOCAL_DIR_FILTER);

    ListMultimap<String, LocalIndexDir> pathToDirMap = ArrayListMultimap.create();
    for (File indexDir : dirs) {
        LocalIndexDir localIndexDir = new LocalIndexDir(indexDir);
        pathToDirMap.get(localIndexDir.getJcrPath()).add(localIndexDir);
    }

    Map<String, List<LocalIndexDir>> result = Maps.newHashMap();
    for (Map.Entry<String, Collection<LocalIndexDir>> e : pathToDirMap.asMap().entrySet()) {
        List<LocalIndexDir> sortedDirs = new ArrayList<>(e.getValue());
        Collections.sort(sortedDirs, Collections.<LocalIndexDir>reverseOrder());
        result.put(e.getKey(), sortedDirs);
    }
    return result;
}

From source file:org.zanata.model.PersonProjectMemberships.java

public PersonProjectMemberships(HPerson person, Collection<ProjectRole> projectRoles,
        ListMultimap<HLocale, LocaleRole> localeRoleMappings) {
    this.person = person;
    maintainer = projectRoles != null && projectRoles.contains(ProjectRole.Maintainer);
    translationMaintainer = projectRoles != null && projectRoles.contains(ProjectRole.TranslationMaintainer);
    localeRoles = Sets.newHashSet();//from   w  ww .j  a  va2 s .c o  m
    if (localeRoleMappings != null) {
        for (Map.Entry<HLocale, Collection<LocaleRole>> entry : localeRoleMappings.asMap().entrySet()) {
            localeRoles.add(new LocaleRoles(entry.getKey(), entry.getValue()));
        }
    }
}