Example usage for java.util Collection addAll

List of usage examples for java.util Collection addAll

Introduction

In this page you can find the example usage for java.util Collection addAll.

Prototype

boolean addAll(Collection<? extends E> c);

Source Link

Document

Adds all of the elements in the specified collection to this collection (optional operation).

Usage

From source file:cn.net.withub.demo.bootsec.hello.security.CustomFilterInvocationSecurityMetadataSource.java

@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
    FilterInvocation fi = (FilterInvocation) object;

    HttpServletRequest request = fi.getRequest();

    System.out.println("requestUrl is " + fi.getRequestUrl());

    if (resourceMap == null || databaseChanged) {
        loadResourceMatchAuthority();// w ww  . j  a  va  2s . com
    }

    Collection<ConfigAttribute> attrs = new ArrayList<ConfigAttribute>();
    for (String urlPattern : resourceMap.keySet()) {
        //?
        AntPathRequestMatcher matcher = new AntPathRequestMatcher(urlPattern);
        if (matcher.matches(request)) {
            System.out.println("matched resource url patterns: " + urlPattern);
            attrs.addAll(resourceMap.get(urlPattern));
        }
    }

    return attrs;
}

From source file:com.screenslicer.core.util.Util.java

public static int diff(Collection<String> collectionA, Collection<String> collectionB) {
    Collection<String> composite = new HashSet<String>();
    composite.addAll(collectionA);
    composite.addAll(collectionB);//  w w  w .j  a  v a  2s  . co  m
    int diff = 0;
    for (String string : composite) {
        if (!collectionA.contains(string) || !collectionB.contains(string)) {
            diff++;
        }
    }
    return diff;
}

From source file:com.icfcc.cache.annotation.AnnotationCacheOperationSource.java

/**
 * Determine the cache operation(s) for the given method or class.
 * <p>This implementation delegates to configured
 * {@link CacheAnnotationParser}s for parsing known annotations into
 * Spring's metadata attribute class.//  w w w .ja va2  s .c  o  m
 * <p>Can be overridden to support custom annotations that carry
 * caching metadata.
 * @param ae the annotated method or class
 * @return the configured caching operations, or {@code null} if none found
 */
protected Collection<CacheOperation> determineCacheOperations(AnnotatedElement ae) {
    Collection<CacheOperation> ops = null;

    for (CacheAnnotationParser annotationParser : this.annotationParsers) {
        Collection<CacheOperation> annOps = annotationParser.parseCacheAnnotations(ae);
        if (annOps != null) {
            if (ops == null) {
                ops = new ArrayList<CacheOperation>();
            }
            ops.addAll(annOps);
        }
    }
    return ops;
}

From source file:de.dentrassi.rpm.builder.YumMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    this.logger = new Logger(getLog());

    try {//  w  ww. j a  v  a  2 s.  c o  m
        final Builder builder = new RepositoryCreator.Builder();
        builder.setTarget(new FileSystemSpoolOutTarget(this.outputDirectory.toPath()));

        if (!this.skipSigning) {
            final PGPPrivateKey privateKey = SigningHelper.loadKey(this.signature, this.logger);
            if (privateKey != null) {
                final int digestAlgorithm = HashAlgorithm.from(this.signature.getHashAlgorithm()).getValue();
                builder.setSigning(output -> new SigningStream(output, privateKey, digestAlgorithm, false,
                        "RPM builder Mojo - de.dentrassi.maven:rpm"));
            }
        }

        final RepositoryCreator creator = builder.build();

        this.packagesPath = new File(this.outputDirectory, "packages");
        Files.createDirectories(this.packagesPath.toPath());

        final Collection<Path> paths = Lists.newArrayList();

        if (!this.skipDependencies) {
            final Set<Artifact> deps = this.project.getArtifacts();
            if (deps != null) {
                paths.addAll(deps.stream()//
                        .filter(d -> d.getType().equalsIgnoreCase("rpm"))//
                        .map(d -> d.getFile().toPath())//
                        .collect(Collectors.toList()));
            }
        } else {
            this.logger.debug("Skipped RPM artifacts from maven dependencies");
        }

        if (this.files != null) {
            paths.addAll(this.files.stream().map(f -> f.toPath()).collect(Collectors.toList()));
        }
        if (this.directories != null) {
            for (final File dir : this.directories) {
                Files.walkFileTree(dir.toPath(), new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                            throws IOException {
                        if (file.getFileName().toString().toLowerCase().endsWith(".rpm")) {
                            paths.add(file);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
            }
        }

        addPackageList(creator, paths);
    } catch (final IOException e) {
        throw new MojoExecutionException("Failed to write repository", e);
    }
}

From source file:com.addthis.hydra.query.web.HttpQueryHandler.java

private void fastHandle(ChannelHandlerContext ctx, FullHttpRequest request, String target, KVPairs kv)
        throws Exception {
    StringBuilderWriter writer = new StringBuilderWriter(50);
    HttpResponse response = HttpUtils.startResponse(writer);
    response.headers().add("Access-Control-Allow-Origin", "*");

    switch (target) {
    case "/metrics": {
        fakeMetricsServlet.writeMetrics(writer, kv);
        break;/*  ww w  .  j  a v a 2  s . c o m*/
    }
    case "/running":
    case "/query/list":
    case "/query/running":
    case "/v2/queries/running.list": {
        Jackson.defaultMapper().writerWithDefaultPrettyPrinter().writeValue(writer, tracker.getRunning());
        break;
    }
    case "/done":
    case "/complete":
    case "/query/done":
    case "/query/complete":
    case "/completed/list":
    case "/v2/queries/finished.list": {
        Jackson.defaultMapper().writerWithDefaultPrettyPrinter().writeValue(writer, tracker.getCompleted());
        break;
    }
    case "/query/all":
    case "/v2/queries/list": {
        Collection<QueryEntryInfo> aggregatingSnapshot = tracker.getRunning();
        aggregatingSnapshot.addAll(tracker.getCompleted());
        Jackson.defaultMapper().writerWithDefaultPrettyPrinter().writeValue(writer, aggregatingSnapshot);
        break;
    }
    case "/cancel":
    case "/query/cancel": {
        if (tracker.cancelRunning(kv.getValue("uuid"))) {
            writer.write("canceled " + kv.getValue("uuid"));
        } else {
            writer.write("canceled failed for " + kv.getValue("uuid"));
            response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
        break;
    }
    case "/workers":
    case "/query/workers":
    case "/v2/queries/workers": {
        Map<String, Integer> workerSnapshot = meshQueryMaster.worky().values().stream()
                .collect(toMap(WorkerData::hostName, WorkerData::queryLeases));
        Jackson.defaultMapper().writerWithDefaultPrettyPrinter().writeValue(writer, workerSnapshot);
        break;
    }
    case "/host":
    case "/host/list":
    case "/v2/host/list":
        String queryStatusUuid = kv.getValue("uuid");
        QueryEntry queryEntry = tracker.getQueryEntry(queryStatusUuid);
        if (queryEntry != null) {
            DetailedStatusHandler hostDetailsHandler = new DetailedStatusHandler(writer, response, ctx, request,
                    queryEntry);
            hostDetailsHandler.handle();
            return;
        } else {
            QueryEntryInfo queryEntryInfo = tracker.getCompletedQueryInfo(queryStatusUuid);
            if (queryEntryInfo != null) {
                Jackson.defaultMapper().writerWithDefaultPrettyPrinter().writeValue(writer, queryEntryInfo);
            } else {
                log.trace("could not find query for status");
                if (ctx.channel().isActive()) {
                    sendError(ctx, new HttpResponseStatus(NOT_FOUND.code(), "could not find query"));
                }
                return;
            }
            break;
        }
    case "/git":
    case "/v2/settings/git.properties": {
        try {
            Jackson.defaultMapper().writeValue(writer,
                    ConfigFactory.parseResourcesAnySyntax("/hydra-git.properties").getConfig("git"));
        } catch (Exception ex) {
            String noGitWarning = "Error loading git.properties, possibly jar was not compiled with maven.";
            log.warn(noGitWarning);
            writer.write(noGitWarning);
        }
        break;
    }
    case "/query/encode": {
        Query q = new Query(null, new String[] { kv.getValue("query", kv.getValue("path", "")) }, null);
        JSONArray path = CodecJSON.encodeJSON(q).getJSONArray("path");
        writer.write(path.toString());
        break;
    }
    case "/query/decode": {
        String qo = "{path:" + kv.getValue("query", kv.getValue("path", "")) + "}";
        Query q = CodecJSON.decodeString(Query.class, qo);
        writer.write(q.getPaths()[0]);
        break;
    }
    default:
        // forward to static file server
        ctx.pipeline().addLast(staticFileHandler);
        request.retain();
        ctx.fireChannelRead(request);
        return; // don't do text response clean up
    }
    log.trace("response being sent {}", writer);
    ByteBuf textResponse = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(writer.getBuilder()), UTF_8);
    HttpContent content = new DefaultHttpContent(textResponse);
    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, textResponse.readableBytes());
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    ctx.write(response);
    ctx.write(content);
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    log.trace("response pending");
    if (!HttpHeaders.isKeepAlive(request)) {
        log.trace("Setting close listener");
        ((Future<Void>) lastContentFuture).addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:es.osoco.grails.plugins.otp.access.AbstractMultipleVoterFilterInvocationDefinition.java

/**
 * {@inheritDoc}//from   w w w.ja  v a 2 s .  c  o  m
 * @see org.springframework.security.access.SecurityMetadataSource#getAllConfigAttributes()
 */
public Collection<ConfigAttribute> getAllConfigAttributes() {
    try {
        initialize();
    } catch (Exception e) {
        GrailsUtil.deepSanitize(e);
        _log.error(e.getMessage(), e);
    }

    Collection<ConfigAttribute> all = new HashSet<ConfigAttribute>();
    for (Collection<ConfigAttribute> configs : _compiled.values()) {
        all.addAll(configs);
    }
    return Collections.unmodifiableCollection(all);
}

From source file:org.trpr.platform.servicefw.impl.spring.web.HomeController.java

private List<ResourceInfo> findMethods(Map<String, Object> handlerMap, Set<String> urls) {

    SortedSet<ResourceInfo> result = new TreeSet<ResourceInfo>();

    for (String key : urls) {

        Object handler = handlerMap.get(key);
        Class<?> handlerType = ClassUtils.getUserClass(handler);
        HandlerMethodResolver resolver = new HandlerMethodResolver();
        resolver.init(handlerType);/*from w  w w.j  a v a 2s  .c  o m*/

        String[] typeMappings = null;
        RequestMapping typeMapping = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class);
        if (typeMapping != null) {
            typeMappings = typeMapping.value();
        }

        Set<Method> handlerMethods = resolver.getHandlerMethods();
        for (Method method : handlerMethods) {

            RequestMapping mapping = method.getAnnotation(RequestMapping.class);

            Collection<String> computedMappings = new HashSet<String>();
            if (typeMappings != null) {
                computedMappings.addAll(Arrays.asList(typeMappings));
            }

            for (String path : mapping.value()) {
                if (typeMappings != null) {
                    for (String parent : computedMappings) {
                        if (parent.endsWith("/")) {
                            parent = parent.substring(0, parent.length() - 1);
                        }
                        computedMappings.add(parent + path);
                    }
                } else {
                    computedMappings.add(path);
                }
            }

            logger.debug("Analysing mappings for method:" + method.getName() + ", key:" + key
                    + ", computed mappings: " + computedMappings);
            if (computedMappings.contains(key)) {
                RequestMethod[] methods = mapping.method();
                if (methods != null && methods.length > 0) {
                    for (RequestMethod requestMethod : methods) {
                        logger.debug(
                                "Added explicit mapping for path=" + key + "to RequestMethod=" + requestMethod);
                        result.add(new ResourceInfo(key, requestMethod));
                    }
                } else {
                    logger.debug("Added implicit mapping for path=" + key + "to RequestMethod=GET");
                    result.add(new ResourceInfo(key, RequestMethod.GET));
                }
            }

        }

        if (handlerMethods.isEmpty()) {
            result.add(new ResourceInfo(key, RequestMethod.GET));
        }

    }

    return new ArrayList<ResourceInfo>(result);

}

From source file:com.zia.freshdocs.preference.CMISPreferencesManager.java

public Collection<CMISHost> getAllPreferences(Context ctx) {
    Collection<CMISHost> results = new TreeSet<CMISHost>();

    Map<String, CMISHost> prefs = readPreferences(ctx);

    if (prefs.size() == 0) {
        initDefaultPrefs(ctx);/*w w w  .  j a  v  a2  s  . co  m*/
        prefs = readPreferences(ctx);
    }

    if (prefs != null) {
        results.addAll(prefs.values());
        results.add(createAddServer(ctx));
    }

    return results;
}

From source file:com.ppp.prm.portal.server.service.gwt.HibernateDetachUtility.java

/**
* @param value the object needing to be detached/scrubbed.
* @param checkedObjectMap This maps identityHashCodes to Objects we've already detached. In that way we can
* quickly determine if we've already done the work for the incoming value and avoid taversing it again. This
* works well almost all of the time, but it is possible that two different objects can have the same identity hash
* (conflicts are always possible with a hash). In that case we utilize the checkedObjectCollisionMap (see below).
* @param checkedObjectCollisionMap checkedObjectMap maps the identityhash to the *first* object with that hash. In
* most cases there will only be mapping for one hash, but it is possible to encounter the same hash for multiple
* objects, especially on 32bit or IBM JVMs. It is important to know if an object has already been detached
* because if it is somehow self-referencing, we have to stop the recursion. This map holds the 2nd..Nth mapping
* for a single hash and is used to ensure we never try to detach an object already processed.
* @param depth used to stop infinite recursion, defaults to a depth we don't expectto see, but it is configurable.
* @param serializationType//from   w  ww.  j a v a2 s. c  o m
* @throws Exception if a problem occurs
* @throws IllegalStateException if the recursion depth limit is reached
*/
private static void nullOutUninitializedFields(Object value, Map<Integer, Object> checkedObjectMap,
        Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, SerializationType serializationType)
        throws Exception {
    if (depth > depthAllowed) {
        String warningMessage = "Recursed too deep [" + depth + " > " + depthAllowed
                + "], will not attempt to detach object of type ["
                + ((value != null) ? value.getClass().getName() : "N/A")
                + "]. This may cause serialization errors later. "
                + "You can try to work around this by setting the system property [" + DEPTH_ALLOWED_SYSPROP
                + "] to a value higher than [" + depth + "] or you can set the system property ["
                + THROW_EXCEPTION_ON_DEPTH_LIMIT_SYSPROP + "] to 'false'";
        LOG.warn(warningMessage);
        if (throwExceptionOnDepthLimit) {
            throw new IllegalStateException(warningMessage);
        }
        return;
    }

    if (null == value) {
        return;
    }

    // System.identityHashCode is a hash code, and therefore not guaranteed to be unique. And we've seen this
    // be the case.  So, we use it to try and avoid duplicating work, but handle the case when two objects may
    // have an identity crisis.
    Integer valueIdentity = hashCodeGenerator.getHashCode(value);
    Object checkedObject = checkedObjectMap.get(valueIdentity);

    if (null == checkedObject) {
        // if we have not yet encountered an object with this hash, store it in our map and start scrubbing            
        checkedObjectMap.put(valueIdentity, value);

    } else if (value == checkedObject) {
        // if we have scrubbed this already, no more work to be done            
        return;

    } else {
        // we have a situation where multiple objects have the same identity hashcode, work with our
        // collision map to decide whether it needs to be scrubbed and add if necessary.
        // Note that this code block is infrequently hit, it is by design that we've pushed the extra
        // work, map, etc, involved for this infrequent case into its own block. The standard cases must
        // be as fast and lean as possible.

        boolean alreadyDetached = false;
        List<Object> collisionObjects = checkedObjectCollisionMap.get(valueIdentity);

        if (null == collisionObjects) {
            // if this is the 2nd occurrence for this hash, create a new map entry                
            collisionObjects = new ArrayList<Object>(1);
            checkedObjectCollisionMap.put(valueIdentity, collisionObjects);

        } else {
            // if we have scrubbed this already, no more work to be done                
            for (Object collisionObject : collisionObjects) {
                if (value == collisionObject) {
                    alreadyDetached = true;
                    break;
                }
            }
        }

        if (LOG.isDebugEnabled()) {
            StringBuilder message = new StringBuilder("\n\tIDENTITY HASHCODE COLLISION [hash=");
            message.append(valueIdentity);
            message.append(", alreadyDetached=");
            message.append(alreadyDetached);
            message.append("]");
            message.append("\n\tCurrent  : ");
            message.append(value.getClass().getName());
            message.append("\n\t    ");
            message.append(value);
            message.append("\n\tPrevious : ");
            message.append(checkedObject.getClass().getName());
            message.append("\n\t    ");
            message.append(checkedObject);
            for (Object collisionObject : collisionObjects) {
                message.append("\n\tPrevious : ");
                message.append(collisionObject.getClass().getName());
                message.append("\n\t    ");
                message.append(collisionObject);
            }

            LOG.debug(message);
        }

        // now that we've done our logging, if already detached we're done. Otherwise add to the list of collision
        // objects for this hash, and start scrubbing
        if (alreadyDetached) {
            return;
        }

        collisionObjects.add(value);
    }

    // Perform the detaching
    if (value instanceof Object[]) {
        Object[] objArray = (Object[]) value;
        for (int i = 0; i < objArray.length; i++) {
            Object listEntry = objArray[i];
            Object replaceEntry = replaceObject(listEntry);
            if (replaceEntry != null) {
                objArray[i] = replaceEntry;
            }
            nullOutUninitializedFields(objArray[i], checkedObjectMap, checkedObjectCollisionMap, depth + 1,
                    serializationType);
        }
    } else if (value instanceof List) {
        // Null out any entries in initialized collections
        ListIterator i = ((List) value).listIterator();
        while (i.hasNext()) {
            Object val = i.next();
            Object replace = replaceObject(val);
            if (replace != null) {
                val = replace;
                i.set(replace);
            }
            nullOutUninitializedFields(val, checkedObjectMap, checkedObjectCollisionMap, depth + 1,
                    serializationType);
        }

    } else if (value instanceof Collection) {
        Collection collection = (Collection) value;
        Collection itemsToBeReplaced = new ArrayList();
        Collection replacementItems = new ArrayList();
        for (Object item : collection) {
            Object replacementItem = replaceObject(item);
            if (replacementItem != null) {
                itemsToBeReplaced.add(item);
                replacementItems.add(replacementItem);
                item = replacementItem;
            }
            nullOutUninitializedFields(item, checkedObjectMap, checkedObjectCollisionMap, depth + 1,
                    serializationType);
        }
        collection.removeAll(itemsToBeReplaced);
        collection.addAll(replacementItems); // watch out! if this collection is a Set, HashMap$MapSet doesn't support addAll. See BZ 688000
    } else if (value instanceof Map) {
        Map originalMap = (Map) value;
        HashMap<Object, Object> replaceMap = new HashMap<Object, Object>();
        for (Iterator i = originalMap.keySet().iterator(); i.hasNext();) {
            // get original key and value - these might be hibernate proxies
            Object originalKey = i.next();
            Object originalKeyValue = originalMap.get(originalKey);

            // replace with non-hibernate classes, if appropriate (will be null otherwise)
            Object replaceKey = replaceObject(originalKey);
            Object replaceValue = replaceObject(originalKeyValue);

            // if either original key or original value was a hibernate proxy object, we have to 
            // remove it from the original map, and remember the replacement objects for later
            if (replaceKey != null || replaceValue != null) {
                Object newKey = (replaceKey != null) ? replaceKey : originalKey;
                Object newValue = (replaceValue != null) ? replaceValue : originalKeyValue;
                replaceMap.put(newKey, newValue);
                i.remove();
            }
        }

        // all hibernate proxies have been removed, we need to replace them with their
        // non-proxy object representations that we got from replaceObject() calls
        originalMap.putAll(replaceMap);

        // now go through each item in the map and null out their internal fields
        for (Object key : originalMap.keySet()) {
            nullOutUninitializedFields(originalMap.get(key), checkedObjectMap, checkedObjectCollisionMap,
                    depth + 1, serializationType);
            nullOutUninitializedFields(key, checkedObjectMap, checkedObjectCollisionMap, depth + 1,
                    serializationType);
        }
    } else if (value instanceof Enum) {
        // don't need to detach enums, treat them as special objects
        return;
    }

    if (serializationType == SerializationType.JAXB) {
        XmlAccessorType at = value.getClass().getAnnotation(XmlAccessorType.class);
        if (at != null && at.value() == XmlAccessType.FIELD) {
            nullOutFieldsByFieldAccess(value, checkedObjectMap, checkedObjectCollisionMap, depth,
                    serializationType);
        } else {
            nullOutFieldsByAccessors(value, checkedObjectMap, checkedObjectCollisionMap, depth,
                    serializationType);
        }
    } else if (serializationType == SerializationType.SERIALIZATION) {
        nullOutFieldsByFieldAccess(value, checkedObjectMap, checkedObjectCollisionMap, depth,
                serializationType);
    }

}

From source file:de.rrze.idmone.utils.jidgen.cli.IdGenOptions.java

/**
 * Fill the internal variable data by parsing a given
 * array of command line options.//w w w .  j  ava  2s  .  co  m
 * 
 * @param args
 *          the String array containing all command line options
 * @return the data collection
 * @throws ParseException
 */
public HashMap<String, String> parse(String[] args) throws ParseException {
    // get a list of all stored option objects to be processed
    // excluding all dummy options
    Collection<IdGenOption> options = new HashSet<IdGenOption>();
    options.addAll(this.getOptions());
    options.removeAll(this.dummyOptions.values());
    Iterator<IdGenOption> iter = options.iterator();

    // init the parser
    BasicParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(this, args);

    // iterate over all possible options
    while (iter.hasNext()) {
        IdGenOption currentOption = iter.next();
        //logger.trace("Processing option \"" + currentOption.getShortOpt() + "\"");

        if (commandLine.hasOption(currentOption.getShortOpt())) {
            // option was specified
            String value = commandLine.getOptionValue(currentOption.getShortOpt());
            if (value != null) {
                // option has a specified value
                this.data.put(currentOption.getShortOpt(), value);
                logger.info(currentOption.getShortOpt() + " = " + value);
            } else if (currentOption.hasArg()) {
                // option does NOT have a specified value
                logger.error(currentOption.getShortOpt() + " "
                        + Messages.getString("IdGenOptions.MISSING_ARGUMENT"));
                System.out.println(this.getHelp(false));
                System.exit(170);
            } else {
                // at least put an entry with an empty string in the data array
                // to mark that the option was specified
                this.data.put(currentOption.getShortOpt(), "");
            }
        } else {
            // option was NOT specified, so use default if available
            if (currentOption.hasDefaultValue()) {
                // has default
                logger.info(currentOption.getShortOpt() + " " + Messages.getString("IdGenOptions.USING_DEFAULT")
                        + " " + currentOption.getDefaultValue());
                this.data.put(currentOption.getShortOpt(), currentOption.getDefaultValue());
            }
        }
    }

    return this.data;
}