Example usage for java.util Set size

List of usage examples for java.util Set size

Introduction

In this page you can find the example usage for java.util Set size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java

public static void splitZip(File inputFile, File outputFile, Set<String> includeEnties) throws IOException {
    if (outputFile.exists()) {
        FileUtils.deleteQuietly(outputFile);
    }// w ww .j a  v  a  2 s . co m
    if (null == includeEnties || includeEnties.size() < 1) {
        return;
    }
    FileOutputStream fos = new FileOutputStream(outputFile);
    ZipOutputStream jos = new ZipOutputStream(fos);
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(inputFile);
    ZipInputStream zis = new ZipInputStream(fis);

    try {
        // loop on the entries of the jar file package and put them in the final jar
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory()) {
                continue;
            }
            String name = entry.getName();
            if (!includeEnties.contains(name)) {
                continue;
            }
            JarEntry newEntry;
            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }
            // add the entry to the jar archive
            jos.putNextEntry(newEntry);

            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            while ((count = zis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }
            // close the entries for this file
            jos.closeEntry();
            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
    fis.close();
    jos.close();
}

From source file:org.eclipse.gemini.blueprint.test.internal.util.jar.ManifestUtils.java

/**
 * Determine the Import-Package value based on the Export-Package entries in
 * the jars given as Resources.//  www  .  j a v  a  2  s.c  o  m
 * @param resources
 * @return
 */
public static String[] determineImportPackages(Resource[] resources) {
    Set collection = new LinkedHashSet();
    // for each resource
    for (int i = 0; i < resources.length; i++) {
        Resource resource = resources[i];
        Manifest man = JarUtils.getManifest(resource);
        if (man != null) {
            // read the manifest
            // get the Export-Package
            Attributes attrs = man.getMainAttributes();
            String exportedPackages = attrs.getValue(Constants.EXPORT_PACKAGE);
            // add it to the StringBuilder
            if (StringUtils.hasText(exportedPackages)) {
                collection.addAll(StringUtils.commaDelimitedListToSet(exportedPackages));
            }
        }
    }
    // return the result as string
    String[] array = (String[]) collection.toArray(new String[collection.size()]);

    // clean whitespace just in case
    for (int i = 0; i < array.length; i++) {
        array[i] = StringUtils.trimWhitespace(array[i]);
    }
    return array;
}

From source file:io.divolte.server.recordmapping.ConfigRecordMapper.java

private static List<FieldSetter> setterListFromConfig(final Schema schema, final Config config) {
    if (!config.hasPath("divolte.tracking.schema_mapping.fields")) {
        throw new SchemaMappingException("Schema mapping configuration has no field mappings.");
    }//from   w  ww .  ja  v  a2s  .  c  o  m

    final Set<Entry<String, ConfigValue>> entrySet = config.getConfig("divolte.tracking.schema_mapping.fields")
            .root().entrySet();

    return entrySet.stream().map((e) -> fieldSetterFromConfig(schema, e))
            .collect(Collectors.toCollection(() -> new ArrayList<>(entrySet.size())));
}

From source file:net.antidot.semantic.rdf.rdb2rdf.r2rml.core.R2RMLMappingFactory.java

/**
 * Extract triplesMap contents./* w w w .  j a  v  a 2 s  .  c  om*/
 * 
 * @param triplesMap
 * @param r2rmlMappingGraph
 * @param triplesMapSubject
 * @param triplesMapResources
 * @param storedTriplesMaps
 * @throws InvalidR2RMLStructureException
 * @throws InvalidR2RMLSyntaxException
 * @throws R2RMLDataError
 */
private static void extractTriplesMap(SesameDataSet r2rmlMappingGraph, Resource triplesMapSubject,
        Map<Resource, TriplesMap> triplesMapResources)
        throws InvalidR2RMLStructureException, InvalidR2RMLSyntaxException, R2RMLDataError {

    if (log.isDebugEnabled())
        log.debug("[R2RMLMappingFactory:extractTriplesMap] Extract TriplesMap subject : "
                + triplesMapSubject.stringValue());

    TriplesMap result = triplesMapResources.get(triplesMapSubject);

    // Extract TriplesMap properties
    LogicalTable logicalTable = extractLogicalTable(r2rmlMappingGraph, triplesMapSubject);

    // Extract subject
    // Create a graph maps storage to save all met graph uri during parsing.
    Set<GraphMap> graphMaps = new HashSet<GraphMap>();
    log.debug("[R2RMLMappingFactory:extractTriplesMap] Current number of created graphMaps : "
            + graphMaps.size());
    SubjectMap subjectMap = extractSubjectMap(r2rmlMappingGraph, triplesMapSubject, graphMaps, result);
    log.debug("[R2RMLMappingFactory:extractTriplesMap] Current number of created graphMaps : "
            + graphMaps.size());
    // Extract predicate-object maps
    Set<PredicateObjectMap> predicateObjectMaps = extractPredicateObjectMaps(r2rmlMappingGraph,
            triplesMapSubject, graphMaps, result, triplesMapResources);
    log.debug("[R2RMLMappingFactory:extractTriplesMap] Current number of created graphMaps : "
            + graphMaps.size());
    // Fill triplesMap
    for (PredicateObjectMap predicateObjectMap : predicateObjectMaps)
        result.addPredicateObjectMap(predicateObjectMap);
    result.setLogicalTable(logicalTable);
    result.setSubjectMap(subjectMap);
    log.debug("[R2RMLMappingFactory:extractTriplesMap] Extract of TriplesMap subject : "
            + triplesMapSubject.stringValue() + " done.");
}

From source file:com.none.tom.simplerssreader.utils.SharedPrefUtils.java

public static String[] getSubscriptionCategories(final Context context, final boolean edit) {
    final LinkedListMultimap<String, String> subscriptions = getSubscriptions(context);
    final Set<String> categories = new TreeSet<>();

    if (!edit) {/*from   www . j  av a2 s .  c  o  m*/
        categories.add(context.getString(R.string.all_categories));
    } else {
        categories.add(context.getString(R.string.clear_category));
    }

    for (final String title : subscriptions.asMap().keySet()) {
        categories.add(subscriptions.get(title).get(0));
    }

    return categories.toArray(new String[categories.size()]);
}

From source file:edu.pitt.csb.stability.StabilitySearch.java

/**
 * returns a complementary set of integers ranging from 0 to n-1 to s both of size floor n/2
 * if n is odd, one int is not in either set at random
 * @param s/*from  w  ww  .ja  v a  2  s.co  m*/
 * @param n
 * @return
 */
public static Set<Integer> getComplement(Set<Integer> s, int n) {
    if (s.size() != (int) Math.floor(n / 2.0)) {
        throw new IllegalArgumentException(
                "Set s must be of size floor(n/2) found s: " + s.size() + " n: " + n);
    }
    Set<Integer> c = new HashSet<Integer>(s.size());

    boolean dropOne = n % 2 > 0;
    int skipI = -1;
    if (dropOne)
        skipI = (new Random()).nextInt((int) Math.ceil(n / 2.0));

    for (int i = 0; i < n; i++) {
        if (!s.contains(i)) {
            if (dropOne && c.size() == skipI) {
                dropOne = false;
                continue;
            } else
                c.add(i);
        }
    }

    if (s.size() != c.size())
        throw new IllegalStateException("Complement is not same size as original!");

    return c;
}

From source file:org.uimafit.factory.TypeSystemDescriptionFactory.java

/**
 * Resolve a list of patterns to a set of URLs.
 *
 * @return an array of locations./*w ww . j  a v  a2  s  .c  o m*/
 * @throws ResourceInitializationException
 *             if the locations could not be resolved.
 */
public static String[] resolve(String... patterns) throws ResourceInitializationException {
    Set<String> locations = new HashSet<String>();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
        // Scan auto-import locations. Using a set to avoid scanning a pattern twice.
        for (String pattern : new TreeSet<String>(Arrays.asList(patterns))) {
            String p = pattern.trim();
            if (p.length() == 0) {
                continue;
            }
            for (Resource r : resolver.getResources(pattern)) {
                locations.add(r.getURL().toString());
            }
        }
        return locations.toArray(new String[locations.size()]);
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }
}

From source file:net.lldp.checksims.algorithm.similaritymatrix.SimilarityMatrix.java

/**
 * Generate a similarity matrix from a given set of submissions.
 *
 * @param inputSubmissions Submissions to generate from
 * @param results Results to build from. Must contain results for every possible unordered pair of input submissions
 * @return Similarity Matrix built from given results
 * @throws InternalAlgorithmError Thrown on missing results, or results containing a submission not in the input
 *///  w  ww  . j a  v  a  2 s  .c  o  m
public static SimilarityMatrix generateMatrix(Set<Submission> inputSubmissions, Set<AlgorithmResults> results)
        throws InternalAlgorithmError {
    checkNotNull(inputSubmissions);
    checkNotNull(results);
    checkArgument(!inputSubmissions.isEmpty(), "Must provide at least 1 submission to build matrix from");
    checkArgument(!results.isEmpty(), "Must provide at least 1 AlgorithmResults to build matrix from!");

    // Generate the matrix we'll use
    AlgorithmResults[][] matrix = new AlgorithmResults[inputSubmissions.size()][inputSubmissions.size()];

    //Ordering sortBy = Ordering.natural();
    Ordering<Submission> sortBy = Ordering.from(new Comparator<Submission>() {
        public int compare(Submission a, Submission b) {
            return ((Double) b.getTotalCopyScore()).compareTo(a.getTotalCopyScore());
        }
    });

    // Order the submissions
    List<Submission> orderedSubmissions = sortBy.immutableSortedCopy(inputSubmissions);

    // Generate the matrix

    // Start with the diagonal, filling with 100% similarity
    for (int i = 0; i < orderedSubmissions.size(); i++) {
        Submission s = orderedSubmissions.get(i);

        matrix[i][i] = new AlgorithmResults(Pair.of(s, s), Real.ONE, Real.ONE);
    }

    // Now go through all the results, and build appropriate two MatrixEntry objects for each
    for (AlgorithmResults result : results) {
        int aIndex = orderedSubmissions.indexOf(result.a);
        int bIndex = orderedSubmissions.indexOf(result.b);

        if (aIndex == -1) {
            if (!result.a.testFlag("invalid")) {
                throw new InternalAlgorithmError(
                        "Processed Algorithm Result with submission not in given input submissions with name \""
                                + result.a.getName() + "\"");
            }
        } else if (bIndex == -1) {
            if (!result.b.testFlag("invalid")) {
                throw new InternalAlgorithmError(
                        "Processed Algorithm Result with submission not in given input submissions with name \""
                                + result.b.getName() + "\"");
            }
        } else {
            matrix[aIndex][bIndex] = result.inverse();
            matrix[bIndex][aIndex] = result;
        }
    }

    // Verification pass: Go through and ensure that the entire array was populated
    for (int x = 0; x < orderedSubmissions.size(); x++) {
        for (int y = 0; y < orderedSubmissions.size(); y++) {
            if (matrix[x][y] == null) {
                throw new InternalAlgorithmError("Missing Algorithm Results for comparison of submissions \""
                        + orderedSubmissions.get(x).getName() + "\" and \""
                        + orderedSubmissions.get(y).getName() + "\"");
            }
        }
    }

    return new SimilarityMatrix(matrix, orderedSubmissions, orderedSubmissions, results);
}

From source file:com.cpjit.swagger4j.util.ReflectUtils.java

/**
 * ????/* w  w  w.  j av  a 2 s .c o  m*/
 * 
 * @param packageName
 * @return ????null
 *       0
 *       <li>?packNames0</li>
 *       <li>??</li>
 * @throws FileNotFoundException ?
 * @throws IllegalArgumentException ???
 * @since 1.0.0
 */
public static List<String> scanClazzName(String packageName)
        throws FileNotFoundException, IllegalArgumentException {
    String pack2path = packageName.replaceAll("\\.", "/");
    if (StringUtils.isBlank(packageName)) {
        pack2path = "";
    }

    URL fullPath = ResourceUtil.getResource(pack2path);
    if (fullPath == null) {
        throw new FileNotFoundException("[" + packageName + "]?");
    }
    Path pack;
    try {
        pack = Paths.get(fullPath.toURI());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
    if (!Files.isDirectory(pack)) {
        throw new IllegalArgumentException("[" + packageName + "]????");
    }

    Set<String> clazzNames = new HashSet<String>();
    String prefix = StringUtils.isBlank(packageName) ? "" : packageName + ".";
    // ?Java?
    try (DirectoryStream<Path> clazzs = Files.newDirectoryStream(pack, "*.class");) {
        clazzs.forEach(clazz -> { // ???
            String clazzName = prefix + clazz.getFileName().toString().replace(".class", "");
            clazzNames.add(clazzName);
        });
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }

    if (clazzNames.size() < 1) { // ?
        return Collections.emptyList();
    }
    return new ArrayList<String>(clazzNames);
}

From source file:edu.stanford.muse.xword.Crossword.java

public static ArrayList<NameInfoMemory> removeBadCandidatesandCap_ReturnsNameInfo(
        ArrayList<NameInfoMemory> terms, Set<String> tabooTokens) {
    log.info("removing bad candidates with " + tabooTokens.size() + " taboo words");

    // create list of candidates words 
    ArrayList<NameInfoMemory> result = new ArrayList<NameInfoMemory>();
    next_term: for (NameInfoMemory term : terms) {
        // any token in term matches any taboo token, and the entire term is nuked
        Set<String> tokens = cleanAndTokenize(Util.canonicalizeSpaces(term.title));
        System.out.println(tokens);
        for (String token : tokens) {
            if ((tabooTokens.contains(token)) || (tabooTokens.contains(token.toLowerCase())))
                continue next_term;
            //if (IndexUtils.topNames.contains(token))
            //continue next_term;
            if (DictUtils.hasOnlyCommonDictWords(token)) // hasOnlyCommonDictWords is robust for case
                continue next_term;
            if (DictUtils.fullDictWords.contains(token))
                continue next_term;
        }/*from w ww.  ja  v a 2 s  .com*/

        result.add(term);
    }
    log.info("after removing taboo candidates, answer terms: " + result.size() + " original terms: "
            + terms.size());
    return result;
}