Example usage for java.util Collections addAll

List of usage examples for java.util Collections addAll

Introduction

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

Prototype

@SafeVarargs
public static <T> boolean addAll(Collection<? super T> c, T... elements) 

Source Link

Document

Adds all of the specified elements to the specified collection.

Usage

From source file:com.mmnaseri.dragonfly.runtime.session.impl.AbstractSessionPreparator.java

private void registerEntities(Collection<SessionInitializationEventHandler> eventHandlers) {
    log.info("Finding entity classes ...");
    final List<Class> entityClasses = new ArrayList<Class>();
    for (LookupSource source : entityDefinitionSources) {
        Collections.addAll(entityClasses, source.getClasses(basePackages));
    }//from  w  w w . j a  va 2s. c om
    for (SessionInitializationEventHandler eventHandler : eventHandlers) {
        eventHandler.beforeRegisteringEntities(entityDefinitionContext, entityClasses);
    }
    for (Class entityClass : entityClasses) {
        log.debug("Registering entity " + entityClass.getCanonicalName());
        //noinspection unchecked
        final ImmutableEntityDefinition<Object> entityDefinition = new ImmutableEntityDefinition<Object>(
                entityClass, Collections.<Class<?>, Class<?>>emptyMap());
        for (SessionInitializationEventHandler eventHandler : eventHandlers) {
            eventHandler.beforeRegisteringEntity(entityDefinitionContext, entityDefinition);
        }
        entityDefinitionContext.addDefinition(entityDefinition);
        for (SessionInitializationEventHandler eventHandler : eventHandlers) {
            eventHandler.afterRegisteringEntity(entityDefinitionContext, entityDefinition);
        }
    }
    for (SessionInitializationEventHandler eventHandler : eventHandlers) {
        eventHandler.afterRegisteringEntities(entityDefinitionContext, entityClasses);
    }
}

From source file:ddf.catalog.source.solr.SolrFilterDelegate.java

private void combineXpathFilterQueries(SolrQuery query, List<SolrQuery> subQueries, String operator) {
    List<String> queryParams = new ArrayList<>();
    // Use Set to remove duplicates now that the namespaces have been stripped out
    Set<String> xpathFilters = new TreeSet<>();
    Set<String> xpathIndexes = new TreeSet<>();

    for (SolrQuery subQuery : subQueries) {
        String[] params = subQuery.getParams(FILTER_QUERY_PARAM_NAME);
        if (params != null) {
            for (String param : params) {
                if (StringUtils.startsWith(param, XPATH_QUERY_PARSER_PREFIX)) {
                    if (StringUtils.contains(param, XPATH_FILTER_QUERY_INDEX)) {
                        xpathIndexes/*  w w w.j  a va2 s .  c  o m*/
                                .add(StringUtils.substringAfter(StringUtils.substringBeforeLast(param, "\""),
                                        XPATH_FILTER_QUERY_INDEX + ":\""));
                    } else if (StringUtils.startsWith(param, XPATH_QUERY_PARSER_PREFIX + XPATH_FILTER_QUERY)) {
                        xpathFilters.add(StringUtils.substringAfter(
                                StringUtils.substringBeforeLast(param, "\""), XPATH_FILTER_QUERY + ":\""));
                    }
                }
                Collections.addAll(queryParams, param);
            }
        }
    }

    if (xpathFilters.size() > 1) {
        // More than one XPath found, need to combine
        String filter = XPATH_QUERY_PARSER_PREFIX + XPATH_FILTER_QUERY + ":\"("
                + StringUtils.join(xpathFilters, operator.toLowerCase()) + ")\"";

        List<String> indexes = new ArrayList<>();
        for (String xpath : xpathIndexes) {
            indexes.add("(" + XPATH_FILTER_QUERY_INDEX + ":\"" + xpath + "\")");
        }
        // TODO DDF-1882 add pre-filter xpath index
        //String index = XPATH_QUERY_PARSER_PREFIX + StringUtils.join(indexes, operator);
        //query.setParam(FILTER_QUERY_PARAM_NAME, filter, index);
        query.setParam(FILTER_QUERY_PARAM_NAME, filter);
    } else if (queryParams.size() > 0) {
        // Pass through original filter queries if only a single XPath is present
        query.setParam(FILTER_QUERY_PARAM_NAME, queryParams.toArray(new String[queryParams.size()]));
    }
}

From source file:com.adobe.cq.wcm.core.components.models.impl.v1.PageImpl.java

private void addPolicyClientLibs(List<String> categories) {
    if (currentStyle != null) {
        Collections.addAll(categories, currentStyle.get(PN_CLIENTLIBS, ArrayUtils.EMPTY_STRING_ARRAY));
    }//from   w ww  .  j a  v  a 2  s . com
}

From source file:com.manydesigns.portofino.pageactions.crud.ModelSelectionProviderSupport.java

protected boolean setupSelectionProvider(@Nullable SelectionProviderReference ref,
        DatabaseSelectionProvider current, Set<String> configuredSPs) {
    List<Reference> references = current.getReferences();

    String[] fieldNames = new String[references.size()];
    Class[] fieldTypes = new Class[references.size()];

    int i = 0;//from  w w  w . java  2  s .  c o  m
    for (Reference reference : references) {
        Column column = reference.getActualFromColumn();
        fieldNames[i] = column.getActualPropertyName();
        fieldTypes[i] = column.getActualJavaType();
        i++;
    }

    availableSelectionProviders.put(Arrays.asList(fieldNames), current);
    for (String fieldName : fieldNames) {
        //If another SP is configured for the same field, stop
        if (configuredSPs.contains(fieldName)) {
            return false;
        }
    }

    if (ref == null || ref.isEnabled()) {
        DisplayMode dm = ref != null ? ref.getDisplayMode() : DisplayMode.DROPDOWN;
        SearchDisplayMode sdm = ref != null ? ref.getSearchDisplayMode() : SearchDisplayMode.DROPDOWN;
        String newHref = ref != null ? ref.getCreateNewValueHref() : null;
        String newText = ref != null ? ref.getCreateNewValueText() : null;
        SelectionProvider selectionProvider = createSelectionProvider(current, fieldNames, fieldTypes, dm, sdm,
                newHref, newText);

        CrudSelectionProvider crudSelectionProvider = new CrudSelectionProvider(selectionProvider, fieldNames,
                newHref, newText);
        crudSelectionProviders.add(crudSelectionProvider);
        Collections.addAll(configuredSPs, fieldNames);
        return true;
    } else {
        //To avoid automatically adding a FK later
        CrudSelectionProvider crudSelectionProvider = new CrudSelectionProvider(null, fieldNames, null, null);
        crudSelectionProviders.add(crudSelectionProvider);
        return false;
    }
}

From source file:com.tango.elasticsearch.rest.action.unique.UniqueTermsAction.java

private void submitSearchRequests(final RestRequest request, final RestChannel channel,
        Map<SearchRequest, String> searchRequestsToCacheKeyMap, final List<TermsResult> cachedResponses) {
    int indexIndex = 0;
    final AtomicArray<Throwable> searchErrors = new AtomicArray<Throwable>(searchRequestsToCacheKeyMap.size());
    final AtomicInteger counter = new AtomicInteger(searchRequestsToCacheKeyMap.size());
    final AtomicArray<TermsResult> searchResults = new AtomicArray<TermsResult>(
            searchRequestsToCacheKeyMap.size());
    for (Map.Entry<SearchRequest, String> searchRequestEntry : searchRequestsToCacheKeyMap.entrySet()) {
        final String requestKey = searchRequestEntry.getValue();
        final SearchRequest searchRequest = searchRequestEntry.getKey();
        final int index = indexIndex;
        client.search(searchRequest, new ActionListener<SearchResponse>() {
            @Override// w w w. j a  v a2s.c o m
            public void onResponse(SearchResponse response) {
                try {
                    TermsResult result = extractTermsResult(response);
                    searchResults.set(index, result);
                    if (requestKey.length() > 0 && result != null && result.getOtherCount() == 0) {
                        putToCache(requestKey, result);
                    }
                    if (counter.decrementAndGet() == 0) {
                        Throwable throwable = checkErrors(searchErrors);
                        if (throwable != null) {
                            processFailure(throwable, channel, request);
                        } else {
                            Collections.addAll(cachedResponses,
                                    searchResults.toArray(new TermsResult[searchResults.length()]));
                            aggregateResults(cachedResponses, request, channel);
                        }
                    }
                } catch (Exception e) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("failed to execute search (building response)", e);
                    }
                    onFailure(e);
                }
            }

            private Throwable checkErrors(AtomicArray<Throwable> searchErrors) {
                Throwable result = null;
                for (int i = 0; i < searchErrors.length(); i++) {
                    Throwable th = searchErrors.get(i);
                    if (th != null) {
                        result = th;
                        break;
                    }
                }
                return result;
            }

            @Override
            public void onFailure(Throwable e) {
                searchErrors.set(index, e);
                if (counter.decrementAndGet() <= 0) {
                    processFailure(e, channel, request);
                }
            }
        });
        indexIndex++;
    }
}

From source file:com.baidu.rigel.biplatform.ma.model.builder.impl.DirectorImpl.java

/**
 * //from www .j a  v  a2 s.  com
 * update {@link Cube} with {@link StarModel}
 * 
 * @param builder -- CubeBuilder
 * @param oriSchema -- original schema
 * @param starModel -- new star model
 * @return cube -- already update cube
 * @see com.baidu.rigel.biplatform.ma.model.builder.impl.CubeBuilder
 * @see com.baidu.rigel.biplatform.ac.model.Schema
 * 
 */
private Cube modifyCubeWithModel(CubeBuilder builder, Schema oriSchema, StarModel starModel) {
    MiniCube oriCube = (MiniCube) oriSchema.getCubes().get(starModel.getCubeId());
    //        StarModelBuilder modelBuilder = new StarModelBuilder();
    //        StarModel oriModel = modelBuilder.buildModel((MiniCube) oriCube);
    // if true the star model not changed
    //        if (oriModel.equals(starModel)) {
    //            return oriCube;
    //        }
    MiniCube cube = new MiniCube();
    cube.setCaption(oriCube.getCaption());
    cube.setId(oriCube.getId());
    cube.setMutilple(oriCube.isMutilple());
    cube.setSource(oriCube.getSource());
    cube.setName(oriCube.getName());
    cube.setVisible(oriCube.isVisible());
    Map<String, Measure> newMeasures = modifyMeasures(starModel, oriCube);
    cube.setMeasures(newMeasures);

    // store the newest dimension
    Map<String, Dimension> dims = new HashMap<String, Dimension>();
    Map<String, Dimension> oriDims = oriCube.getDimensions();
    DimensionBuilder dimBuilder = new DimensionBuilder();
    List<Dimension> newDimensions = Lists.newArrayList();

    for (DimTableMetaDefine dimTable : starModel.getDimTables()) {
        Dimension[] buildDims = dimBuilder.buildDimensions(dimTable, starModel.getFactTable());
        Collections.addAll(newDimensions, buildDims);
    }
    dims = addOrReplaceDims(oriDims, newDimensions);

    dims = modifyDimGroup(dims, DeepcopyUtils.deepCopy(oriDims));
    resetMeasures(dims, oriCube.getDimensions(), cube);
    cube.setDimensions(dims);
    return cube;
}

From source file:de.openali.odysseus.chart.factory.config.resolver.ChartTypeResolver.java

private LayerType findUrlLayerType(final URL context, final String uri, final String identifier)
        throws XmlException, IOException {
    final ChartConfigurationLoader loader = getLoader(context, uri);
    final ChartType[] charts = loader.getCharts();

    final List<ChartType> chartTypes = new ArrayList<>();
    Collections.addAll(chartTypes, charts);

    for (final ChartType chart : chartTypes) {
        try {/*from  ww  w  .java  2s. c  o m*/
            final LayersType layers = chart.getLayers();

            final LayerType layer = findLayer(layers, identifier, context);
            if (layer != null)
                return layer;
        } catch (final CoreException e) {
            OdysseusChartFactory.getDefault().getLog()
                    .log(new Status(IStatus.ERROR, OdysseusChartFactory.PLUGIN_ID, e.getLocalizedMessage(), e));
        }
    }

    return null;
}

From source file:net.itransformers.idiscover.discoverylisteners.XmlTopologyDeviceLogger.java

public void handleDevice(String deviceName, RawDeviceData rawData, DiscoveredDeviceData discoveredDeviceData,
        Resource resource) {// ww  w  .  ja  v a 2 s .  co m
    ByteArrayOutputStream graphMLOutputStream = new ByteArrayOutputStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        JaxbMarshalar.marshal(discoveredDeviceData, os, "DiscoveredDevice");
    } catch (JAXBException e) {
        logger.error(e.getMessage(), e);
    }
    XsltTransformer transformer = new XsltTransformer();
    try {
        transformer.transformXML(new ByteArrayInputStream(os.toByteArray()), xsltFileName, graphMLOutputStream,
                null, null);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

    try {
        final String fileName = "node-" + deviceName + ".graphml";
        //            String fullFileName = path + File.separator + fileName;
        final File nodeFile = new File(deviceCentricPath, fileName);
        String graphml = null;
        try {
            graphml = new XmlFormatter().format(new String(graphMLOutputStream.toByteArray()));
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        FileUtils.writeStringToFile(nodeFile, graphml);

        try {
            final File networkGraphml = new File(networkCentricPath + File.separator + "network.graphml");
            if (networkGraphml.exists()) {
                Map<String, String> edgesTypes = new HashMap<String, String>();
                edgesTypes.put("name", "string");
                edgesTypes.put("method", "string");
                edgesTypes.put("dataLink", "string");
                edgesTypes.put("ipLink", "string");
                edgesTypes.put("IPv4Forwarding", "string");
                edgesTypes.put("IPv6Forwarding", "string");
                edgesTypes.put("InterfaceNameA", "string");
                edgesTypes.put("InterfaceNameB", "string");
                edgesTypes.put("IPv4AddressA", "string");
                edgesTypes.put("IPv4AddressB", "string");
                edgesTypes.put("edgeTooltip", "string");
                edgesTypes.put("diff", "string");
                edgesTypes.put("diffs", "string");
                edgesTypes.put("bgpAutonomousSystemA", "string");
                edgesTypes.put("bgpAutonomousSystemB", "string");

                Map<String, String> vertexTypes = new HashMap<String, String>();
                vertexTypes.put("deviceModel", "string");
                vertexTypes.put("deviceType", "string");
                vertexTypes.put("nodeInfo", "string");
                vertexTypes.put("hostname", "string");
                vertexTypes.put("deviceStatus", "string");
                vertexTypes.put("DiscoveredIPv4Address", "string");
                vertexTypes.put("geoCoordinates", "string");
                vertexTypes.put("SubnetPrefix", "string");
                vertexTypes.put("site", "string");
                vertexTypes.put("diff", "string");
                vertexTypes.put("diffs", "string");
                vertexTypes.put("diffs", "string");
                vertexTypes.put("IPv6Forwarding", "string");
                vertexTypes.put("IPv4Forwarding", "string");
                vertexTypes.put("bgpLocalAS", "string");

                Map<String, MergeConflictResolver> edgeConflictResolver = new HashMap<String, MergeConflictResolver>();
                Map<String, MergeConflictResolver> nodeConflictResolver = new HashMap<String, MergeConflictResolver>();
                edgeConflictResolver.put("method", new MergeConflictResolver() {
                    @Override
                    public Object resolveConflict(Object srcValue, Object targetValue) {
                        // if (srcValue instanceof String && targetValue instanceof String) {
                        String[] srcArray = ((String) srcValue).split(",");
                        String[] targetArray = ((String) targetValue).split(",");

                        String[] both = (String[]) ArrayUtils.addAll(srcArray, targetArray);
                        Arrays.sort(both);
                        LinkedHashSet<String> m = new LinkedHashSet<String>();
                        Collections.addAll(m, both);

                        return StringUtils.join(m, ',');

                    }
                });
                new GrahmlMerge(nodeConflictResolver, edgeConflictResolver).merge(nodeFile, networkGraphml,
                        networkGraphml, vertexTypes, edgesTypes, graphtType);
            } else {
                //networkGraphml.createNewFile();
                FileUtils.writeStringToFile(networkGraphml, graphml);
                // new GrahmlMerge().merge(nodeFile, networkGraphml, networkGraphml);
            }
            //TODO remove when you have some time and do the diff in the correct way!
            //                File networkGraphmls = new File(labelPath,graphtType+".graphmls");
            //                if (!networkGraphmls.exists()){
            //                     FileWriter writer = new FileWriter(networkGraphmls);
            //                     writer.write("network.graphml\n");
            //                     writer.close();
            //                }

        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.rockagen.commons.util.ClassUtil.java

/**
 * obtain constructor list of specified class If recursively is true, obtain
 * constructor from all class hierarchy/*from  ww w  .j ava2  s.  c o m*/
 * 
 * 
 * @param clazz class
 *            where fields are searching
 * @param recursively
 *            param
 * @return array of constructors
 */
public static Constructor<?>[] getDeclaredConstructors(Class<?> clazz, boolean recursively) {
    List<Constructor<?>> constructors = new LinkedList<Constructor<?>>();
    Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
    Collections.addAll(constructors, declaredConstructors);

    Class<?> superClass = clazz.getSuperclass();

    if (superClass != null && recursively) {
        Constructor<?>[] declaredConstructorsOfSuper = getDeclaredConstructors(superClass, true);
        if (declaredConstructorsOfSuper.length > 0)
            Collections.addAll(constructors, declaredConstructorsOfSuper);
    }
    return constructors.toArray(new Constructor<?>[constructors.size()]);
}

From source file:net.lldp.checksims.submission.Submission.java

/**
 * Recursively find all files matching in a directory.
 *
 * @param directory Directory to search in
 * @param glob Match pattern used to identify files to include
 * @return List of all matching files in this directory and subdirectories
 *//*from   ww  w. j a  va2  s  . c  o m*/
static Set<File> getAllMatchingFiles(File directory, String glob, boolean recursive)
        throws NoSuchFileException, NotDirectoryException {
    checkNotNull(directory);
    checkNotNull(glob);
    checkArgument(!glob.isEmpty(), "Glob pattern cannot be empty");

    if (!directory.exists()) {
        throw new NoSuchFileException("Does not exist: " + directory.getAbsolutePath());
    } else if (!directory.isDirectory()) {
        throw new NotDirectoryException("Not a directory: " + directory.getAbsolutePath());
    }

    PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + glob);

    Set<File> allFiles = new HashSet<>();
    Logger logs = LoggerFactory.getLogger(Submission.class);

    if (recursive) {
        logs.trace("Recursively traversing directory " + directory.getName());
    }

    // Get files in this directory
    File[] contents = directory
            .listFiles((f) -> matcher.matches(Paths.get(f.getAbsolutePath()).getFileName()) && f.isFile());

    // TODO consider mapping to absolute paths?

    // Add this directory
    Collections.addAll(allFiles, contents);

    // Get subdirectories
    File[] subdirs = directory.listFiles(File::isDirectory);

    // Recursively call on all subdirectories if specified
    if (recursive) {
        for (File subdir : subdirs) {
            allFiles.addAll(getAllMatchingFiles(subdir, glob, true));
        }
    }

    return allFiles;
}