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:modula.parser.io.ModelUpdater.java

/**
 * state//from w  ww  . j  av a  2s.c o  m
 */
private static void updateState(final State state, final Map<String, TransitionTarget> targets)
        throws ModelException {
    List<EnterableState> children = state.getChildren();
    if (state.isComposite()) {
        //initialize next / initial
        Initial ini = state.getInitial();
        if (ini == null) {
            state.setFirst(children.get(0).getId());
            ini = state.getInitial();
        }
        SimpleTransition initialTransition = ini.getTransition();
        updateTransition(initialTransition, targets);
        Set<TransitionTarget> initialStates = initialTransition.getTargets();
        // we have to allow for an indirect descendant initial (targets)
        //check that initialState is a descendant of s
        if (initialStates.size() == 0) {
            logAndThrowModelError(ERR_STATE_BAD_INIT, new Object[] { getName(state) });
        } else {
            for (TransitionTarget initialState : initialStates) {
                if (!initialState.isDescendantOf(state)) {
                    logAndThrowModelError(ERR_STATE_BAD_INIT, new Object[] { getName(state) });
                }
            }
        }
    } else if (state.getInitial() != null) {
        logAndThrowModelError(ERR_UNSUPPORTED_INIT, new Object[] { getName(state) });
    }

    List<History> histories = state.getHistory();
    if (histories.size() > 0 && state.isSimple()) {
        logAndThrowModelError(ERR_HISTORY_SIMPLE_STATE, new Object[] { getName(state) });
    }
    for (History history : histories) {
        updateHistory(history, targets, state);
    }
    for (Transition transition : state.getTransitionsList()) {
        updateTransition(transition, targets);
    }

    for (Invoke inv : state.getInvokes()) {
        if (inv.getType() == null) {
            logAndThrowModelError(ERR_INVOKE_NO_TYPE, new Object[] { getName(state) });
        }
        if (inv.getSrc() == null && inv.getSrcexpr() == null) {
            logAndThrowModelError(ERR_INVOKE_NO_SRC, new Object[] { getName(state) });
        }
        if (inv.getSrc() != null && inv.getSrcexpr() != null) {
            logAndThrowModelError(ERR_INVOKE_AMBIGUOUS_SRC, new Object[] { getName(state) });
        }
    }

    for (EnterableState es : children) {
        if (es instanceof State) {
            updateState((State) es, targets);
        }
    }
}

From source file:com.cdd.bao.Main.java

private static void diffVocab(String[] options) throws Exception {
    String fn1 = options[0], fn2 = options[1], fn3 = options.length >= 3 ? options[2] : null;
    Util.writeln("Differences between vocab dumps...");
    Util.writeln("    OLD:" + fn1);
    Util.writeln("    NEW:" + fn2);

    InputStream istr = new FileInputStream(fn1);
    SchemaVocab sv1 = SchemaVocab.deserialise(istr, new Schema[0]); // note: giving no schemata works for this purpose
    istr.close();//from   w  ww.j  a  v  a2s .co m
    istr = new FileInputStream(fn2);
    SchemaVocab sv2 = SchemaVocab.deserialise(istr, new Schema[0]); // note: giving no schemata works for this purpose
    istr.close();

    Schema schema = null;
    if (fn3 != null)
        schema = ModelSchema.deserialise(new File(fn3));

    Util.writeln("Term counts: [" + sv1.numTerms() + "] -> [" + sv2.numTerms() + "]");
    Util.writeln("Prefixes: [" + sv1.numPrefixes() + "] -> [" + sv2.numPrefixes() + "]");

    // note: only shows trees on both sides
    for (SchemaVocab.StoredTree tree1 : sv1.getTrees())
        for (SchemaVocab.StoredTree tree2 : sv2.getTrees()) {
            if (!tree1.schemaPrefix.equals(tree2.schemaPrefix) || !tree1.locator.equals(tree2.locator))
                continue;

            String info = "locator: " + tree1.locator;
            if (schema != null && tree1.schemaPrefix.equals(schema.getSchemaPrefix())) {
                Schema.Assignment assn = schema.obtainAssignment(tree1.locator);
                info = "assignment: " + assn.name + " (locator: " + tree1.locator + ")";
            }

            Util.writeln("Schema [" + tree1.schemaPrefix + "], " + info);
            Set<String> terms1 = new HashSet<>(), terms2 = new HashSet<>();
            for (SchemaTree.Node node : tree1.tree.getFlat())
                terms1.add(node.uri);
            for (SchemaTree.Node node : tree2.tree.getFlat())
                terms2.add(node.uri);

            Set<String> extra1 = new TreeSet<>(), extra2 = new TreeSet<>();
            for (String uri : terms1)
                if (!terms2.contains(uri))
                    extra1.add(uri);
            for (String uri : terms2)
                if (!terms1.contains(uri))
                    extra2.add(uri);

            Util.writeln("    terms removed: " + extra1.size());
            for (String uri : extra1)
                Util.writeln("        <" + uri + "> " + sv1.getLabel(uri));

            Util.writeln("    terms added: " + extra2.size());
            for (String uri : extra2)
                Util.writeln("        <" + uri + "> " + sv2.getLabel(uri));
        }
}

From source file:com.hurence.logisland.classloading.PluginProxy.java

private static Object createProxy(Object object, Class superClass, Class[] interfaces, ClassLoader cl) {
    CglibProxyHandler handler = new CglibProxyHandler(object);

    Enhancer enhancer = new Enhancer();

    if (superClass != null && !AbstractConfigurableComponent.class.isAssignableFrom(superClass)) {
        enhancer.setSuperclass(superClass);
    }/*from  w  w w .  j  a v  a  2 s  .c o m*/

    enhancer.setCallback(handler);

    Set<Class<?>> il = new LinkedHashSet<>();
    il.add(SerializationMagik.class);
    il.add(DelegateAware.class);

    if (interfaces != null) {

        for (Class<?> i : interfaces) {
            if (i.isInterface()) {
                il.add(i);
            }
        }

        enhancer.setInterfaces(il.toArray(new Class[il.size()]));
    }

    enhancer.setClassLoader(cl == null ? Thread.currentThread().getContextClassLoader() : cl);

    return enhancer.create();
}

From source file:edu.wpi.checksims.submission.Submission.java

/**
 * Turn a list of files and a name into a Submission.
 *
 * The contents of a submission are built deterministically by reading in files in alphabetical order and appending
 * their contents./* w ww .j a va  2s .c  o  m*/
 *
 * @param name Name of the new submission
 * @param files List of files to include in submission
 * @param splitter Tokenizer for files in the submission
 * @return A new submission formed from the contents of all given files, appended and tokenized
 * @throws IOException Thrown on error reading from file
 * @throws NoMatchingFilesException Thrown if no files are given
 */
static Submission submissionFromFiles(String name, Set<File> files, Tokenizer splitter)
        throws IOException, NoMatchingFilesException {
    checkNotNull(name);
    checkArgument(!name.isEmpty(), "Submission name cannot be empty");
    checkNotNull(files);
    checkNotNull(splitter);

    Logger logs = LoggerFactory.getLogger(Submission.class);

    if (files.size() == 0) {
        throw new NoMatchingFilesException("No matching files found, cannot create submission!");
    }

    // To ensure submission generation is deterministic, sort files by name, and read them in that order
    List<File> orderedFiles = Ordering
            .from((File file1, File file2) -> file1.getName().compareTo(file2.getName()))
            .immutableSortedCopy(files);

    TokenList tokenList = new TokenList(splitter.getType());

    StringBuilder fileContent = new StringBuilder();

    // Could do this with a .stream().forEach(...) but we'd have to handle the IOException inside
    for (File f : orderedFiles) {
        String content = FileUtils.readFileToString(f, StandardCharsets.UTF_8);

        fileContent.append(content);

        if (!content.endsWith("\n") && !content.isEmpty()) {
            fileContent.append("\n");
        }
    }

    String contentString = fileContent.toString();

    // Split the content
    tokenList.addAll(splitter.splitFile(contentString));

    if (tokenList.size() > 7500) {
        logs.warn("Warning: Submission " + name + " has very large token count (" + tokenList.size() + ")");
    }

    return new ConcreteSubmission(name, contentString, tokenList);
}

From source file:ml.shifu.shifu.core.binning.UpdateBinningInfoReducer.java

private static String limitedFrequentItems(Set<String> fis) {
    StringBuilder sb = new StringBuilder(200);
    int size = Math.min(fis.size(), CountAndFrequentItemsWritable.FREQUET_ITEM_MAX_SIZE * 10);
    Iterator<String> iterator = fis.iterator();
    int i = 0;/*from  w  ww.  j a  v  a 2 s. com*/
    while (i < size) {
        String next = iterator.next().replaceAll("\\" + Constants.DEFAULT_DELIMITER, " ").replace(",", " ");
        sb.append(next);
        if (i != size - 1) {
            sb.append(",");
        }
        i += 1;
    }
    return sb.toString();
}

From source file:fedora.server.security.servletfilters.CacheElement.java

private static final void auditNamedValues(String m, Map namedValues) {
    if (LOG.isDebugEnabled()) {
        assert namedValues != null;
        for (Iterator outer = namedValues.keySet().iterator(); outer.hasNext();) {
            Object name = outer.next();
            assert name instanceof String : "not a string, name==" + name;
            StringBuffer sb = new StringBuffer(m + name + "==");
            Object temp = namedValues.get(name);
            assert temp instanceof String || temp instanceof Set : "neither string nor set, temp==" + temp;
            if (temp instanceof String) {
                sb.append(temp.toString());
            } else if (temp instanceof Set) {
                Set values = (Set) temp;
                sb.append("(" + values.size() + ") {");
                String punct = "";
                for (Iterator it = values.iterator(); it.hasNext();) {
                    temp = it.next();/*from  www .  j  a  v a 2s. c o  m*/
                    if (!(temp instanceof String)) {
                        LOG.error(m + "set member not string, ==" + temp);
                    } else {
                        String value = (String) temp;
                        sb.append(punct + value);
                        punct = ",";
                    }
                }
                sb.append("}");
            }
            LOG.debug(sb.toString());
        }
    }
}

From source file:com.reactivetechnologies.platform.datagrid.util.EntityFinder.java

/**
 * //from ww w.j a  va  2s. c  o  m
 * @param basePkg
 * @return
 * @throws ClassNotFoundException
 */
public static Collection<Class<?>> findEntityClasses(String basePkg) throws ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.addIncludeFilter(new TypeFilter() {

        @Override
        public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
                throws IOException {
            AnnotationMetadata aMeta = metadataReader.getAnnotationMetadata();
            return aMeta.hasAnnotation(HzMapConfig.class.getName());
        }
    });
    //consider the finder class to be in the root package
    Set<BeanDefinition> beans = null;
    try {
        beans = provider.findCandidateComponents(StringUtils.hasText(basePkg) ? basePkg
                : EntityFinder.class.getName().substring(0, EntityFinder.class.getName().lastIndexOf(".")));
    } catch (Exception e) {
        throw new IllegalArgumentException("Unable to scan for entities under base package", e);
    }

    Set<Class<?>> classes = new HashSet<>();
    if (beans != null && !beans.isEmpty()) {
        classes = new HashSet<>(beans.size());
        for (BeanDefinition bd : beans) {
            classes.add(Class.forName(bd.getBeanClassName()));
        }
    } else {
        log.warn(">> Did not find any key value entities under the given base scan package [" + basePkg + "]");
    }
    return classes;

}

From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T> T produceBean(Class<T> clazz, ControlParam countrolParam, Stack<Class> parseClassList) {
    try {// w  w w.  j  a va2 s.  c  om
        T item = clazz.newInstance();
        for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(clazz)) {
            Method writeMethod = pd.getWriteMethod();
            if (writeMethod == null || pd.getReadMethod() == null || //
                    countrolParam.getExcludeFieldList() != null
                            && countrolParam.getExcludeFieldList().contains(pd.getName())//
            ) {//
                continue;
            }
            Class fieldClazz = pd.getPropertyType();
            Long numIndex = countrolParam.getNumIndex();
            // int enumIndex = countrolParam.getEnumIndex();
            Random random = countrolParam.getRandom();
            long strIndex = countrolParam.getStrIndex();
            int charIndex = countrolParam.getCharIndex();
            Calendar time = countrolParam.getTime();
            if (TypeUtil.isBaseType(fieldClazz)) {
                if (TypeUtil.isNumberType(fieldClazz)) {
                    if (fieldClazz == Byte.class) {
                        writeMethod.invoke(item, Byte.valueOf((byte) (numIndex & 0x7F)));
                    } else if (fieldClazz == Short.class) {
                        writeMethod.invoke(item, Short.valueOf((short) (numIndex & 0x7FFF)));
                    } else if (fieldClazz == Integer.class) {
                        writeMethod.invoke(item, Integer.valueOf((int) (numIndex & 0x7FFFFFFF)));
                    } else if (fieldClazz == Long.class) {
                        writeMethod.invoke(item, Long.valueOf((long) numIndex));
                    } else if (fieldClazz == Float.class) {
                        writeMethod.invoke(item, Float.valueOf((float) numIndex));
                    } else if (fieldClazz == Double.class) {
                        writeMethod.invoke(item, Double.valueOf((double) numIndex));
                    } else if (fieldClazz == byte.class) {//
                        writeMethod.invoke(item, (byte) (numIndex & 0x7F));
                    } else if (fieldClazz == short.class) {
                        writeMethod.invoke(item, (short) (numIndex & 0x7FFF));
                    } else if (fieldClazz == int.class) {
                        writeMethod.invoke(item, (int) (numIndex & 0x7FFFFFFF));
                    } else if (fieldClazz == long.class) {
                        writeMethod.invoke(item, (long) numIndex);
                    } else if (fieldClazz == float.class) {
                        writeMethod.invoke(item, (float) numIndex);
                    } else if (fieldClazz == double.class) {
                        writeMethod.invoke(item, (double) numIndex);
                    }
                    numIndex++;
                    if (numIndex < 0) {
                        numIndex &= 0x7FFFFFFFFFFFFFFFL;
                    }
                    countrolParam.setNumIndex(numIndex);
                } else if (fieldClazz == boolean.class) {
                    writeMethod.invoke(item, random.nextBoolean());
                } else if (fieldClazz == Boolean.class) {
                    writeMethod.invoke(item, Boolean.valueOf(random.nextBoolean()));
                } else if (fieldClazz == char.class) {
                    writeMethod.invoke(item, CHAR_RANGE[charIndex]);
                    charIndex++;
                    if (charIndex >= CHAR_RANGE.length) {
                        charIndex = 0;
                    }
                    countrolParam.setCharIndex(charIndex);
                } else if (fieldClazz == Character.class) {
                    writeMethod.invoke(item, Character.valueOf(CHAR_RANGE[charIndex]));
                    charIndex++;
                    if (charIndex >= CHAR_RANGE.length) {
                        charIndex = 0;
                    }
                    countrolParam.setCharIndex(charIndex);
                } else if (fieldClazz == String.class) {
                    if (countrolParam.getUniqueFieldList() != null
                            && countrolParam.getUniqueFieldList().contains(pd.getName())) {
                        StringBuilder sb = new StringBuilder();
                        convertNum(strIndex, STRING_RANGE, countrolParam.getRandom(), sb);
                        writeMethod.invoke(item, sb.toString());
                        strIndex += countrolParam.getStrStep();
                        if (strIndex < 0) {
                            strIndex &= 0x7FFFFFFFFFFFFFFFL;
                        }
                        countrolParam.setStrIndex(strIndex);
                    } else {
                        writeMethod.invoke(item, String.valueOf(CHAR_RANGE[charIndex]));
                        charIndex++;
                        if (charIndex >= CHAR_RANGE.length) {
                            charIndex = 0;
                        }
                        countrolParam.setCharIndex(charIndex);
                    }

                } else if (fieldClazz == Date.class) {
                    writeMethod.invoke(item, time.getTime());
                    time.add(Calendar.DAY_OF_YEAR, 1);
                } else if (fieldClazz.isEnum()) {
                    int index = random.nextInt(fieldClazz.getEnumConstants().length);
                    writeMethod.invoke(item, fieldClazz.getEnumConstants()[index]);
                } else {
                    //
                    throw new RuntimeException("out of countrol Class " + fieldClazz.getName());
                }
            } else {
                parseClassList.push(fieldClazz);
                // TODO ?
                Set<Class> set = new HashSet<Class>(parseClassList);
                if (parseClassList.size() - set.size() <= countrolParam.getRecursiveCycleLimit()) {
                    Object bean = produceBean(fieldClazz, countrolParam, parseClassList);
                    writeMethod.invoke(item, bean);
                }
                parseClassList.pop();
            }
        }
        return item;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:io.apicurio.hub.api.codegen.OpenApi2Thorntail.java

/**
 * Converts a set of strings into an array literal format.
 * @param values//from www .j a v  a  2s . c om
 */
private static String toStringArrayLiteral(Set<String> values) {
    StringBuilder builder = new StringBuilder();

    if (values.size() == 1) {
        builder.append("\"");
        builder.append(values.iterator().next().replace("\"", "\\\""));
        builder.append("\"");
    } else {
        builder.append("{");
        boolean first = true;
        for (String value : values) {
            if (!first) {
                builder.append(", ");
            }
            builder.append("\"");
            builder.append(value.replace("\"", "\\\""));
            builder.append("\"");
            first = false;
        }
        builder.append("}");
    }
    return builder.toString();
}

From source file:io.werval.cli.DamnSmallDevShell.java

private static void devshellCommand(boolean debug, File tmpDir, CommandLine cmd) throws IOException {
    final File classesDir = createClassesDirectory(debug, tmpDir);
    Set<File> sourceRoots = prepareSourcesRoots(debug, cmd);
    Set<URL> applicationSourcesSet = new LinkedHashSet<>(sourceRoots.size());
    for (File sourceRoot : sourceRoots) {
        applicationSourcesSet.add(sourceRoot.toURI().toURL());
    }/*  w w  w .j  ava2s  . c  om*/
    URL[] applicationSources = applicationSourcesSet.toArray(new URL[applicationSourcesSet.size()]);
    URL[] applicationClasspath = prepareApplicationClasspath(debug, classesDir);
    URL[] runtimeClasspath = prepareRuntimeClasspath(debug, sourceRoots, cmd);
    applySystemProperties(debug, cmd);
    System.out.println("Loading...");

    // Watch Sources
    SourceWatcher watcher = new JavaWatcher();

    // First build
    rebuild(applicationClasspath, runtimeClasspath, sourceRoots, classesDir);

    // Run DevShell
    Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHook(tmpDir), "werval-cli-cleanup"));
    new DevShellCommand(new SPI(applicationSources, applicationClasspath, runtimeClasspath, sourceRoots,
            watcher, classesDir)).run();
}