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:rapture.kernel.DocApiImpl.java

public Map<String, String> getDocsInternal(CallingContext context, List<String> docUris) {
    Map<String, String> ret = new LinkedHashMap<>();
    ListMultimap<String, RaptureURI> repoToUriMap = ArrayListMultimap.create();

    // Group all the documents by the correct repo
    for (String docUri : docUris) {
        if (StringUtils.isBlank(docUri)) {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                    apiMessageCatalog.getMessage("NullOrEmpty"));
        }/*from w  ww  .  j a v  a 2  s.  com*/
        RaptureURI internalUri = new RaptureURI(docUri, Scheme.DOCUMENT);
        repoToUriMap.put(internalUri.getAuthority(), internalUri);
    }

    // Request each set of the documents from the repo at once
    for (final String authority : repoToUriMap.keySet()) {
        Repository repository = getRepoFromCache(authority);
        if (repository != null) {
            List<RaptureURI> uris = repoToUriMap.get(authority);
            List<String> docs = repository
                    .getDocuments(Lists.transform(uris, new Function<RaptureURI, String>() {
                        @Override
                        public String apply(RaptureURI uri) {
                            return uri.getDocPath();
                        }
                    }));
            for (int i = 0; i < docs.size(); i++) {
                ret.put(uris.get(i).toString(), docs.get(i));
            }
        }
    }
    return ret;
}

From source file:eu.esdihumboldt.hale.io.appschema.writer.internal.ClassificationHandler.java

/**
 * @see eu.esdihumboldt.hale.io.appschema.writer.internal.AbstractPropertyTransformationHandler#getSourceExpressionAsCQL()
 *//*from  w  ww. j  a va2s. co m*/
@Override
protected String getSourceExpressionAsCQL() {
    Property source = AppSchemaMappingUtils.getSourceProperty(propertyCell);
    PropertyDefinition sourceDef = source.getDefinition().getDefinition();
    Property target = AppSchemaMappingUtils.getTargetProperty(propertyCell);
    PropertyDefinition targetDef = target.getDefinition().getDefinition();

    String sourceName = source.getDefinition().getDefinition().getName().getLocalPart();

    ListMultimap<String, ParameterValue> parameters = propertyCell.getTransformationParameters();

    LookupTable lookup = ClassificationMappingUtil.getClassificationLookup(parameters,
            new ServiceManager(ServiceManager.SCOPE_PROJECT));
    if (lookup == null) {
        log.warn("No classification specified");
        return "''";
    } else {
        String cqlTemplate = "if_then_else(in(%s), Recode(%s,%s), %s)";

        // build args to Recode function
        StringBuilder recodeArgsBuilder = new StringBuilder();
        Map<Value, Value> valueMap = lookup.asMap();
        int counter = 0;
        for (Value sourceValue : valueMap.keySet()) {
            Value targetValue = valueMap.get(sourceValue);

            String sourceLiteral = asCqlLiteral(sourceDef, sourceValue.as(String.class));
            String targetLiteral = asCqlLiteral(targetDef, targetValue.as(String.class));
            recodeArgsBuilder.append(sourceLiteral).append(",").append(targetLiteral);
            if (counter < valueMap.size() - 1) {
                recodeArgsBuilder.append(",");
            }
            counter++;
        }
        String recodeArgs = recodeArgsBuilder.toString();

        // build args for in function
        List<String> values = new ArrayList<String>();
        for (Value v : valueMap.keySet()) {
            String valueLiteral = asCqlLiteral(sourceDef, v.as(String.class));
            values.add(valueLiteral);
        }
        values.add(0, sourceName);
        String inArgs = Joiner.on(",").join(values);

        // determine what to put in the "else" branch, based on
        // transformation parameters
        String elsePart = null;
        List<ParameterValue> notClassifiedParam = parameters.get(PARAMETER_NOT_CLASSIFIED_ACTION);
        String notClassifiedAction = null;
        if (notClassifiedParam != null && notClassifiedParam.size() > 0) {
            notClassifiedAction = notClassifiedParam.get(0).as(String.class);
        } else {
            notClassifiedAction = USE_NULL_ACTION;
        }
        if (USE_SOURCE_ACTION.equals(notClassifiedAction))
            elsePart = sourceName;
        else if (notClassifiedAction.startsWith(USE_FIXED_VALUE_ACTION_PREFIX))
            elsePart = asCqlLiteral(targetDef,
                    notClassifiedAction.substring(notClassifiedAction.indexOf(':') + 1));
        else if (USE_NULL_ACTION.equals(notClassifiedAction))
            elsePart = "Expression.NIL";

        return String.format(cqlTemplate, inArgs, sourceName, recodeArgs, elsePart);
    }
}

From source file:com.sk89q.worldguard.protection.managers.storage.sql.DataLoader.java

private void loadPolygons() throws SQLException {
    ListMultimap<String, BlockVector2> pointsCache = ArrayListMultimap.create();

    // First get all the vertices and store them in memory
    Closer closer = Closer.create();/*from  w  ww  . j  av  a 2  s  . c  o  m*/
    try {
        PreparedStatement stmt = closer.register(conn.prepareStatement("SELECT region_id, x, z " + "FROM "
                + config.getTablePrefix() + "region_poly2d_point " + "WHERE world_id = " + worldId));

        ResultSet rs = closer.register(stmt.executeQuery());

        while (rs.next()) {
            pointsCache.put(rs.getString("region_id"), BlockVector2.at(rs.getInt("x"), rs.getInt("z")));
        }
    } finally {
        closer.closeQuietly();
    }

    // Now we pull the regions themselves
    closer = Closer.create();
    try {
        PreparedStatement stmt = closer.register(conn.prepareStatement(
                "SELECT g.min_y, g.max_y, r.id, r.priority, p.id AS parent " + "FROM " + config.getTablePrefix()
                        + "region_poly2d AS g " + "LEFT JOIN " + config.getTablePrefix() + "region AS r "
                        + "          ON (g.region_id = r.id AND g.world_id = r.world_id) " + "LEFT JOIN "
                        + config.getTablePrefix() + "region AS p "
                        + "          ON (r.parent = p.id AND r.world_id = p.world_id) " + "WHERE r.world_id = "
                        + worldId));

        ResultSet rs = closer.register(stmt.executeQuery());

        while (rs.next()) {
            String id = rs.getString("id");

            // Get the points from the cache
            List<BlockVector2> points = pointsCache.get(id);

            if (points.size() < 3) {
                log.log(Level.WARNING, "Invalid polygonal region '" + id + "': region has " + points.size()
                        + " point(s) (less than the required 3). Skipping this region.");
                continue;
            }

            Integer minY = rs.getInt("min_y");
            Integer maxY = rs.getInt("max_y");

            ProtectedRegion region = new ProtectedPolygonalRegion(id, points, minY, maxY);
            region.setPriority(rs.getInt("priority"));

            loaded.put(id, region);

            String parentId = rs.getString("parent");
            if (parentId != null) {
                parentSets.put(region, parentId);
            }
        }
    } finally {
        closer.closeQuietly();
    }
}

From source file:com.google.gerrit.server.git.MergeOp.java

public void merge() throws MergeException, NoSuchProjectException {
    setDestProject();/*from w ww.  ja  va  2  s. c  o  m*/
    try {
        openSchema();
        openRepository();
        openBranch();
        final ListMultimap<SubmitType, Change> toSubmit = validateChangeList(
                db.changes().submitted(destBranch).toList());

        final ListMultimap<SubmitType, CodeReviewCommit> toMergeNextTurn = ArrayListMultimap.create();
        final List<CodeReviewCommit> potentiallyStillSubmittableOnNextRun = new ArrayList<CodeReviewCommit>();
        while (!toMerge.isEmpty()) {
            toMergeNextTurn.clear();
            final Set<SubmitType> submitTypes = new HashSet<Project.SubmitType>(toMerge.keySet());
            for (final SubmitType submitType : submitTypes) {
                final RefUpdate branchUpdate = openBranch();
                final SubmitStrategy strategy = createStrategy(submitType);
                preMerge(strategy, toMerge.get(submitType));
                updateBranch(strategy, branchUpdate);
                updateChangeStatus(toSubmit.get(submitType));
                updateSubscriptions(toSubmit.get(submitType));

                for (final Iterator<CodeReviewCommit> it = potentiallyStillSubmittable.iterator(); it
                        .hasNext();) {
                    final CodeReviewCommit commit = it.next();
                    if (containsMissingCommits(toMerge, commit)
                            || containsMissingCommits(toMergeNextTurn, commit)) {
                        // change has missing dependencies, but all commits which are
                        // missing are still attempted to be merged with another submit
                        // strategy, retry to merge this commit in the next turn
                        it.remove();
                        commit.statusCode = null;
                        commit.missing = null;
                        toMergeNextTurn.put(submitType, commit);
                    }
                }
                potentiallyStillSubmittableOnNextRun.addAll(potentiallyStillSubmittable);
                potentiallyStillSubmittable.clear();
            }
            toMerge.clear();
            toMerge.putAll(toMergeNextTurn);
        }

        for (final CodeReviewCommit commit : potentiallyStillSubmittableOnNextRun) {
            final Capable capable = isSubmitStillPossible(commit);
            if (capable != Capable.OK) {
                sendMergeFail(commit.change, message(commit.change, capable.getMessage()), false);
            }
        }
    } catch (OrmException e) {
        throw new MergeException("Cannot query the database", e);
    } finally {
        if (inserter != null) {
            inserter.release();
        }
        if (rw != null) {
            rw.release();
        }
        if (repo != null) {
            repo.close();
        }
        if (db != null) {
            db.close();
        }
    }
}

From source file:org.opentestsystem.delivery.testadmin.scheduling.SchedulerHelper.java

/**
 * Returns a list of EligibleStudents that only contain those students that match the assessments
 * //  w  ww . jav  a 2 s. c  o m
 * @param eligibleStudents
 * @param assessments
 * @return
 */
public List<EligibleStudent> filterStudents(final List<EligibleStudent> eligibleStudents,
        final List<Assessment> assessments) {

    final List<EligibleStudent> filtered = new ArrayList<EligibleStudent>();

    final com.google.common.collect.ListMultimap<Assessment, EligibleStudent> multimap = ArrayListMultimap
            .create();

    for (final EligibleStudent eligStudent : eligibleStudents) {
        // create multimap so we know which eligible students go with which assessments
        for (final Assessment assess : eligStudent.getAssessments()) {
            multimap.put(assess, eligStudent);
        }
    }

    // iterate through assessments and get the eligible students for each, putting them into filtered and then
    // return filtered

    for (final Assessment assess : assessments) {
        if (multimap.containsKey(assess)) {
            filtered.addAll(multimap.get(assess));
        }
    }

    return filtered;
}

From source file:org.gradle.api.internal.changedetection.state.OrderInsensitiveTaskFilePropertyCompareStrategy.java

private Iterator<TaskStateChange> iterateChangesForRelativePaths(
        final Map<String, NormalizedFileSnapshot> current, Map<String, NormalizedFileSnapshot> previous,
        final String fileType) {
    final ListMultimap<NormalizedFileSnapshot, IncrementalFileSnapshotWithAbsolutePath> unaccountedForPreviousSnapshots = MultimapBuilder
            .hashKeys().linkedListValues().build();
    for (Entry<String, NormalizedFileSnapshot> entry : previous.entrySet()) {
        String absolutePath = entry.getKey();
        NormalizedFileSnapshot previousSnapshot = entry.getValue();
        unaccountedForPreviousSnapshots.put(previousSnapshot,
                new IncrementalFileSnapshotWithAbsolutePath(absolutePath, previousSnapshot.getSnapshot()));
    }/*  w ww. java2 s .  c  o m*/
    final Iterator<Entry<String, NormalizedFileSnapshot>> currentEntries = current.entrySet().iterator();
    return new AbstractIterator<TaskStateChange>() {
        private Iterator<Entry<NormalizedFileSnapshot, IncrementalFileSnapshotWithAbsolutePath>> unaccountedForPreviousSnapshotsIterator;
        private final ListMultimap<String, IncrementalFileSnapshotWithAbsolutePath> addedFiles = MultimapBuilder
                .hashKeys().linkedListValues().build();
        private Iterator<IncrementalFileSnapshotWithAbsolutePath> addedFilesIterator;

        @Override
        protected TaskStateChange computeNext() {
            while (currentEntries.hasNext()) {
                Entry<String, NormalizedFileSnapshot> entry = currentEntries.next();
                String currentAbsolutePath = entry.getKey();
                NormalizedFileSnapshot currentNormalizedSnapshot = entry.getValue();
                IncrementalFileSnapshot currentSnapshot = currentNormalizedSnapshot.getSnapshot();
                List<IncrementalFileSnapshotWithAbsolutePath> previousSnapshotsForNormalizedPath = unaccountedForPreviousSnapshots
                        .get(currentNormalizedSnapshot);
                if (previousSnapshotsForNormalizedPath.isEmpty()) {
                    IncrementalFileSnapshotWithAbsolutePath currentSnapshotWithAbsolutePath = new IncrementalFileSnapshotWithAbsolutePath(
                            currentAbsolutePath, currentSnapshot);
                    addedFiles.put(currentNormalizedSnapshot.getNormalizedPath(),
                            currentSnapshotWithAbsolutePath);
                } else {
                    IncrementalFileSnapshotWithAbsolutePath previousSnapshotWithAbsolutePath = previousSnapshotsForNormalizedPath
                            .remove(0);
                    IncrementalFileSnapshot previousSnapshot = previousSnapshotWithAbsolutePath.getSnapshot();
                    if (!currentSnapshot.isContentUpToDate(previousSnapshot)) {
                        return new FileChange(currentAbsolutePath, ChangeType.MODIFIED, fileType);
                    }
                }
            }

            // Create a single iterator to use for all of the still unaccounted files
            if (unaccountedForPreviousSnapshotsIterator == null) {
                if (unaccountedForPreviousSnapshots.isEmpty()) {
                    unaccountedForPreviousSnapshotsIterator = Iterators.emptyIterator();
                } else {
                    List<Entry<NormalizedFileSnapshot, IncrementalFileSnapshotWithAbsolutePath>> entries = Lists
                            .newArrayList(unaccountedForPreviousSnapshots.entries());
                    Collections.sort(entries, ENTRY_COMPARATOR);
                    unaccountedForPreviousSnapshotsIterator = entries.iterator();
                }
            }

            if (unaccountedForPreviousSnapshotsIterator.hasNext()) {
                Entry<NormalizedFileSnapshot, IncrementalFileSnapshotWithAbsolutePath> unaccountedForPreviousSnapshotEntry = unaccountedForPreviousSnapshotsIterator
                        .next();
                String normalizedPath = unaccountedForPreviousSnapshotEntry.getKey().getNormalizedPath();
                List<IncrementalFileSnapshotWithAbsolutePath> addedFilesForNormalizedPath = addedFiles
                        .get(normalizedPath);
                if (!addedFilesForNormalizedPath.isEmpty()) {
                    // There might be multiple files with the same normalized path, here we choose one of them
                    IncrementalFileSnapshotWithAbsolutePath modifiedSnapshot = addedFilesForNormalizedPath
                            .remove(0);
                    return new FileChange(modifiedSnapshot.getAbsolutePath(), ChangeType.MODIFIED, fileType);
                } else {
                    IncrementalFileSnapshotWithAbsolutePath removedSnapshot = unaccountedForPreviousSnapshotEntry
                            .getValue();
                    return new FileChange(removedSnapshot.getAbsolutePath(), ChangeType.REMOVED, fileType);
                }
            }

            if (includeAdded) {
                // Create a single iterator to use for all of the added files
                if (addedFilesIterator == null) {
                    addedFilesIterator = addedFiles.values().iterator();
                }

                if (addedFilesIterator.hasNext()) {
                    IncrementalFileSnapshotWithAbsolutePath addedFile = addedFilesIterator.next();
                    return new FileChange(addedFile.getAbsolutePath(), ChangeType.ADDED, fileType);
                }
            }

            return endOfData();
        }
    };
}

From source file:ca.sqlpower.architect.ProjectLoader.java

/**
 * Loads the project data from the given input stream.
 * <p>// w  w  w  .  j  a  v  a2s.com
 * Note: the input stream is always closed afterwards.
 *
 * @param in
 *            Used to load in the project data, must support mark.
 * @param dataSources
 *            Collection of the data sources used in the project
 */
public void load(InputStream in, DataSourceCollection<? extends SPDataSource> dataSources,
        ArchitectSession messageDelegate) throws IOException, SQLObjectException {
    UnclosableInputStream uin = new UnclosableInputStream(in);
    siblingSession = messageDelegate;
    try {
        dbcsLoadIdMap = new HashMap<String, JDBCDataSource>();
        sqlObjectLoadIdMap = new HashMap<String, SQLObject>();

        Digester digester = null;

        // use digester to read from file
        try {
            digester = setupDigester();
            digester.parse(uin);
        } catch (SAXException ex) {
            //The digester likes to wrap the cancelled exception in a SAXException.
            if (ex.getException() instanceof DigesterCancelledException) {
                //Digeseter was cancelled by the user. Do not load anything.
                throw new RuntimeException(new InterruptedIOException("progress"));
            }
            logger.error("SAX Exception in project file parse!", ex);
            String message;
            if (digester == null) {
                message = "Couldn't create an XML parser";
            } else {
                message = "There is an XML parsing error in project file at Line:"
                        + digester.getDocumentLocator().getLineNumber() + " Column:"
                        + digester.getDocumentLocator().getColumnNumber();
            }
            throw new SQLObjectException(message, ex);
        } catch (IOException ex) {
            logger.error("IO Exception in project file parse!", ex);
            throw new SQLObjectException("There was an I/O error while reading the file", ex);
        } catch (Exception ex) {
            logger.error("General Exception in project file parse!", ex);
            throw new SQLObjectException("Unexpected Exception", ex);
        }

        SQLObject dbConnectionContainer = ((SQLObject) getSession().getRootObject());

        // hook up data source parent types
        for (SQLDatabase db : dbConnectionContainer.getChildren(SQLDatabase.class)) {
            JDBCDataSource ds = db.getDataSource();
            String parentTypeId = ds.getPropertiesMap().get(JDBCDataSource.DBCS_CONNECTION_TYPE);
            if (parentTypeId != null) {
                for (JDBCDataSourceType dstype : dataSources.getDataSourceTypes()) {
                    if (dstype.getName().equals(parentTypeId)) {
                        ds.setParentType(dstype);
                        // TODO unit test that this works
                    }
                }
                if (ds.getParentType() == null) {
                    logger.error("Data Source \"" + ds.getName() + "\" has type \"" + parentTypeId
                            + "\", which is not configured in the user prefs.");
                    // TODO either reconstruct the parent type, or bring this problem to the attention of the user.
                    // TODO test this
                } else {
                    // TODO test that the referenced parent type is properly configured (has a driver, etc)
                    // TODO test for this behaviour
                }
            }

        }

        /*
         * for backward compatibilty, in the old project file, we have
         * primaryKeyName in the table attrbute, but nothing
         * in the sqlIndex that indicates primary key index,
         * so, we have to set the index as primary key index
         * if the index name == table.primaryKeyName after load the project,
         * table.primaryKeyName is save in the map now, not in the table object
         */
        for (SQLTable table : (List<SQLTable>) getSession().getTargetDatabase().getTables()) {

            if (logger.isDebugEnabled()) {
                if (!table.isPopulated()) {
                    logger.debug("Table [" + table.getName() + "] not populated");
                } else {
                    logger.debug(
                            "Table [" + table.getName() + "] index folder contents: " + table.getIndices());
                }
            }

            if (table.getPrimaryKeyIndex() == null) {
                logger.debug("primary key index is null in table: " + table);
                logger.debug("number of children found in indices folder: " + table.getIndices().size());
                for (SQLIndex index : table.getIndices()) {
                    if (sqlObjectLoadIdMap.get(table.getName() + "." + index.getName()) != null) {
                        table.getPrimaryKeyIndex().updateToMatch(index);
                        break;
                    }
                }
            }
            logger.debug("Table [" + table.getName() + "]2 index folder contents: " + table.getIndices());
            logger.debug("Table [" + table.getName() + "]3 index folder contents: " + table.getIndices());

            if (logger.isDebugEnabled()) {
                if (!table.isPopulated()) {
                    logger.debug("Table [" + table.getName() + "] not populated");
                } else {
                    logger.debug("Table [" + table.getName() + "] index folder contents: "
                            + table.getIndices().size());
                }
            }

        }

        /*
         * In old versions of the architect, user defined types weren't
         * available, so all columns stored their type as a JDBC type code.
         * For all columns in the playpen, we need to hook up upstream user
         * defined types.
         */
        ListMultimap<String, SQLColumn> columns = ArrayListMultimap.create();
        for (SQLTable table : getSession().getTargetDatabase().getTables()) {
            for (SQLColumn column : table.getChildren(SQLColumn.class)) {
                SQLColumn sourceColumn = column.getSourceColumn();
                if (sourceColumn != null && sourceColumn.getPlatform() != null) {
                    columns.put(column.getSourceColumn().getPlatform(), column);
                } else {
                    columns.put(SQLTypePhysicalPropertiesProvider.GENERIC_PLATFORM, column);
                }
            }
        }
        for (String platform : columns.keySet()) {
            SQLColumn.assignTypes(columns.get(platform), dataSources, platform,
                    new DefaultUserPrompterFactory());
        }

        setModified(false);
    } finally {
        uin.forceClose();
    }
}

From source file:org.openmicroscopy.shoola.agents.fsimporter.chooser.LocationDialog.java

/**
 * Sorts the nodes.//  w w  w  .  jav  a 2  s .  c om
 * 
 * @param nodes The nodes to sort.
 * @return See above.
 */
private List<DataNode> sortByUser(List<DataNode> nodes) {
    if (CollectionUtils.isEmpty(nodes))
        return nodes;
    List<DataNode> sorted = new ArrayList<DataNode>();
    ListMultimap<Long, DataNode> map = ArrayListMultimap.create();
    sorted.add(nodes.get(0)); //default node.
    Iterator<DataNode> i = nodes.iterator();
    DataNode node;
    while (i.hasNext()) {
        node = i.next();
        if (!node.isDefaultNode()) {
            map.put(node.getDataObject().getOwner().getId(), node);
        }
    }
    ExperimenterData exp = getSelectedUser();
    List<DataNode> l = map.get(exp.getId());
    if (CollectionUtils.isNotEmpty(l))
        sorted.addAll(sort(l));
    //items are ordered by users.
    long id;
    ExperimenterData user;
    for (int j = 0; j < usersBox.getItemCount(); j++) {
        user = getUser(j);
        if (user != null) {
            id = user.getId();
            if (id != exp.getId())
                sorted.addAll(sort(map.get(id)));
        }
    }
    return sorted;
}

From source file:com.android.build.gradle.internal.transforms.MergeJavaResourcesTransform.java

@Override
public void transform(@NonNull TransformInvocation invocation) throws IOException, TransformException {

    TransformOutputProvider outputProvider = invocation.getOutputProvider();
    checkNotNull(outputProvider, "Missing output object for transform " + getName());

    // folder to copy the files that were originally in folders.
    File outFolder = null;/*from www .j  a  va2 s . c o m*/
    // jar to copy the files that came from jars.  We want copy files from jar into a jar to
    // avoid case sensitivity issue on a case insensitive file system.
    File outJar = null;

    if (invocation.isIncremental()) {
        throw new IllegalStateException("Incremental mode is not supported yet.");
    } else {
        outputProvider.deleteAll();

        // gather all the inputs.
        ListMultimap<String, QualifiedContent> sourceFileList = ArrayListMultimap.create();
        for (TransformInput input : invocation.getInputs()) {
            for (JarInput jarInput : input.getJarInputs()) {
                gatherListFromJar(jarInput, sourceFileList);
            }

            for (DirectoryInput directoryInput : input.getDirectoryInputs()) {
                gatherListFromFolder(directoryInput, sourceFileList);
            }
        }

        // at this point we have what we need, write the output.

        // we're recording all the files that must be merged.
        // this is a map of (archive path -> source folder/jar)
        ListMultimap<String, File> mergedFiles = ArrayListMultimap.create();

        // we're also going to record for each jar which files comes from it.
        ListMultimap<File, String> jarSources = ArrayListMultimap.create();

        for (String key : sourceFileList.keySet()) {
            PackagingFileAction packagingAction = packagingOptions.getAction(key);

            // first thing we do is check if it's excluded.
            if (packagingAction == PackagingFileAction.EXCLUDE) {
                // skip, no need to do anything else.
                continue;
            }

            List<QualifiedContent> contentSourceList = sourceFileList.get(key);

            // if no action is specified, and the key is META-INF/services,
            // default action is merge
            if (packagingAction == PackagingFileAction.NONE && isMetaServices(key)) {
                packagingAction = PackagingFileAction.MERGE;
            }

            QualifiedContent selectedContent;
            if (packagingAction == PackagingFileAction.MERGE) {
                // if merge is specified, project files have no precedence
                selectedContent = null;
            } else {
                // if there is only one content or if one of the source is PROJECT then it wins.
                // This is similar behavior as the other merger (assets, res, manifest).
                selectedContent = findUniqueOrProjectContent(contentSourceList);
            }

            // otherwise search for a selection
            if (selectedContent == null) {
                if (packagingAction == PackagingFileAction.PICK_FIRST) {
                    // if pickFirst then just pick the first one.
                    selectedContent = contentSourceList.get(0);
                } else if (packagingAction == PackagingFileAction.MERGE) {
                    // if it's selected for merging, we need to record this for later where
                    // we'll merge all the files we've found.
                    for (QualifiedContent content : contentSourceList) {
                        mergedFiles.put(key, content.getFile());
                    }
                } else {
                    // finally if it's not excluded, then this is an error.
                    // collect the sources.
                    List<File> sources = contentSourceList.stream().map(QualifiedContent::getFile)
                            .collect(Collectors.toList());
                    throw new TransformException(new DuplicateFileException(key, sources));
                }
            }

            // if a file was selected, write it here.
            if (selectedContent != null) {
                if (selectedContent instanceof JarInput) {
                    // or just record it for now if it's coming from a jar.
                    // This will allow to open these source jars just once to copy
                    // all their content out.
                    jarSources.put(selectedContent.getFile(), key);
                } else {
                    if (outFolder == null) {
                        outFolder = outputProvider.getContentLocation("main", getOutputTypes(), getScopes(),
                                Format.DIRECTORY);
                        mkdirs(outFolder);
                    }
                    copyFromFolder(selectedContent.getFile(), outFolder, key);
                }
            }
        }

        // now copy all the non-merged files into the jar.
        JarMerger jarMerger = null;
        if (!jarSources.isEmpty()) {
            outJar = outputProvider.getContentLocation("main", getOutputTypes(), getScopes(), Format.JAR);
            mkdirs(outJar.getParentFile());
            jarMerger = copyIntoJar(jarSources, outJar);
        }

        // then handle the merged files.
        if (!mergedFiles.isEmpty()) {
            for (String key : mergedFiles.keySet()) {
                List<File> sourceFiles = mergedFiles.get(key);

                // first check if we have a jar source
                boolean hasJarSource = false;
                for (File sourceFile : sourceFiles) {
                    if (sourceFile.isDirectory()) {
                        hasJarSource = true;
                        break;
                    }
                }

                // merge the content into a ByteArrayOutputStream.
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                for (File sourceFile : sourceFiles) {
                    if (sourceFile.isDirectory()) {
                        File actualFile = computeFile(sourceFile, validator.keyToFolderPath(key));
                        baos.write(Files.toByteArray(actualFile));
                    } else {
                        try (ZipFile zipFile = new ZipFile(sourceFile)) {
                            ByteStreams.copy(zipFile.getInputStream(zipFile.getEntry(key)), baos);
                        }
                    }
                    if (isMetaServices(key)) {
                        // With this, files without newline at the end will be merged
                        // successfully for the ServiceLoader
                        baos.write(System.getProperty("line.separator").getBytes());
                    }
                }

                if (hasJarSource) {
                    // if we haven't written into the outjar, create it.
                    if (outJar == null) {
                        outJar = outputProvider.getContentLocation("main", getOutputTypes(), getScopes(),
                                Format.JAR);
                        mkdirs(outJar.getParentFile());
                        jarMerger = new JarMerger(outJar);
                    }

                    jarMerger.addEntry(key, baos.toByteArray());
                } else {
                    if (outFolder == null) {
                        outFolder = outputProvider.getContentLocation("main", getOutputTypes(), getScopes(),
                                Format.DIRECTORY);
                        mkdirs(outFolder);
                    }

                    File computedFile = computeFile(outFolder, key);
                    Files.createParentDirs(computedFile);
                    Files.write(baos.toByteArray(), computedFile);
                }
            }
        }

        if (jarMerger != null) {
            jarMerger.close();
        }
    }
}

From source file:dagger.internal.codegen.ModuleValidator.java

private void validateProvidesOverrides(TypeElement subject, ModuleDescriptor.Kind moduleKind,
        ValidationReport.Builder<TypeElement> builder, ListMultimap<String, ExecutableElement> allMethodsByName,
        ListMultimap<String, ExecutableElement> bindingMethodsByName) {
    // For every @Provides method, confirm it overrides nothing *and* nothing overrides it.
    // Consider the following hierarchy:
    // class Parent {
    //    @Provides Foo a() {}
    //    @Provides Foo b() {}
    //    Foo c() {}
    // }/*from   w  ww .j  ava  2s  . c  om*/
    // class Child extends Parent {
    //    @Provides Foo a() {}
    //    Foo b() {}
    //    @Provides Foo c() {}
    // }
    // In each of those cases, we want to fail.  "a" is clear, "b" because Child is overriding
    // a method marked @Provides in Parent, and "c" because Child is defining an @Provides
    // method that overrides Parent.
    TypeElement currentClass = subject;
    TypeMirror objectType = elements.getTypeElement(Object.class.getCanonicalName()).asType();
    // We keep track of methods that failed so we don't spam with multiple failures.
    Set<ExecutableElement> failedMethods = Sets.newHashSet();
    while (!types.isSameType(currentClass.getSuperclass(), objectType)) {
        currentClass = MoreElements.asType(types.asElement(currentClass.getSuperclass()));
        List<ExecutableElement> superclassMethods = ElementFilter.methodsIn(currentClass.getEnclosedElements());
        for (ExecutableElement superclassMethod : superclassMethods) {
            String name = superclassMethod.getSimpleName().toString();
            // For each method in the superclass, confirm our @Provides methods don't override it
            for (ExecutableElement providesMethod : bindingMethodsByName.get(name)) {
                if (!failedMethods.contains(providesMethod)
                        && elements.overrides(providesMethod, superclassMethod, subject)) {
                    failedMethods.add(providesMethod);
                    /**
                    builder.addError(
                        String.format(
                            PROVIDES_METHOD_OVERRIDES_ANOTHER,
                            moduleKind.methodAnnotation().getSimpleName(),
                            methodSignatureFormatter.format(superclassMethod)),
                        providesMethod);
                     **/
                }
            }
            // For each @Provides method in superclass, confirm our methods don't override it.
            if (isAnnotationPresent(superclassMethod, moduleKind.methodAnnotation())) {
                for (ExecutableElement method : allMethodsByName.get(name)) {
                    if (!failedMethods.contains(method)
                            && elements.overrides(method, superclassMethod, subject)) {
                        failedMethods.add(method);
                        builder.addError(String.format(METHOD_OVERRIDES_PROVIDES_METHOD,
                                moduleKind.methodAnnotation().getSimpleName(),
                                methodSignatureFormatter.format(superclassMethod)), method);
                    }
                }
            }
            allMethodsByName.put(superclassMethod.getSimpleName().toString(), superclassMethod);
        }
    }
}