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:fr.inria.atlanmod.emf.graphs.Connectedness.java

public static void main(String[] args) {

    Options options = createOptions();//from  w  w  w.  j a  v  a  2 s.  c  om

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);
        String inputMetamodel = commandLine.getOptionValue(INPUT_METAMODEL);
        String inputModel = commandLine.getOptionValue(INPUT_MODEL);
        Boolean logUnreachable = commandLine.hasOption(LOG_UNREACHABLE);

        ResourceSet resourceSet = new ResourceSetImpl();
        Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap()
                .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());

        {
            LOG.log(Level.INFO, "Loading input metamodel");
            URI uri = URI.createFileURI(inputMetamodel);
            Resource resource = resourceSet.getResource(uri, true);
            registerEPackages(resource);
        }

        URI uri = URI.createFileURI(inputModel);

        LOG.log(Level.INFO, "Loading input model");
        Resource resource = resourceSet.getResource(uri, true);

        LOG.log(Level.INFO, "Getting input model contents");
        Set<EObject> resourceContents = getResourceContents(resource);
        int totalCount = resourceContents.size();

        LOG.log(Level.INFO, MessageFormat.format("Input model contains {0} elements", totalCount));

        List<EClassifier> candidateEClassifiers = buildCandidateEClassifiers();

        for (Iterator<EObject> it = resource.getAllContents(); it.hasNext();) {
            EObject eObject = it.next();
            if (candidateEClassifiers.contains(eObject.eClass())) {
                Set<EObject> reachableEObjects = getReachableEObjects(eObject);
                int i = reachableEObjects.size();
                LOG.log(Level.INFO, MessageFormat.format("Found {0} reachable objects from {1} (EClass {2})", i,
                        EcoreUtil.getURI(eObject), eObject.eClass().getName()));
                if (logUnreachable) {
                    Set<EObject> unreachableEObjects = new HashSet<>(resourceContents);
                    unreachableEObjects.removeAll(reachableEObjects);
                    LOG.log(Level.INFO,
                            MessageFormat.format("{0} elements are unreachable from {1} (EClass {2})",
                                    unreachableEObjects.size(), EcoreUtil.getURI(eObject),
                                    eObject.eClass().getName()));
                    for (EObject unreachableEObject : unreachableEObjects) {
                        LOG.log(Level.INFO, MessageFormat.format("Unreachable EObject {0} is of type {1}",
                                EcoreUtil.getURI(unreachableEObject), unreachableEObject.eClass()));
                    }
                }
            }
        }

    } catch (ParseException e) {
        LOG.log(Level.SEVERE, e.getLocalizedMessage(), e);
        LOG.log(Level.INFO, "Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        LOG.log(Level.SEVERE, e.getLocalizedMessage(), e);
        MessageUtil.showError(e.toString());
    }
}

From source file:Inmemantlr.java

public static void main(String[] args) {
    LOGGER.info("Inmemantlr tool");

    HelpFormatter hformatter = new HelpFormatter();

    Options options = new Options();

    // Binary arguments
    options.addOption("h", "print this message");

    Option grmr = Option.builder().longOpt("grmrfiles").hasArgs().desc("comma-separated list of ANTLR files")
            .required(true).argName("grmrfiles").type(String.class).valueSeparator(',').build();

    Option infiles = Option.builder().longOpt("infiles").hasArgs()
            .desc("comma-separated list of files to parse").required(true).argName("infiles").type(String.class)
            .valueSeparator(',').build();

    Option utilfiles = Option.builder().longOpt("utilfiles").hasArgs()
            .desc("comma-separated list of utility files to be added for " + "compilation").required(false)
            .argName("utilfiles").type(String.class).valueSeparator(',').build();

    Option odir = Option.builder().longOpt("outdir")
            .desc("output directory in which the dot files will be " + "created").required(false).hasArg(true)
            .argName("outdir").type(String.class).build();

    options.addOption(infiles);//  w w w  .j  av a 2  s. c  o m
    options.addOption(grmr);
    options.addOption(utilfiles);
    options.addOption(odir);

    CommandLineParser parser = new DefaultParser();

    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption('h')) {
            hformatter.printHelp("java -jar inmemantlr.jar", options);
            System.exit(0);
        }
    } catch (ParseException e) {
        hformatter.printHelp("java -jar inmemantlr.jar", options);
        LOGGER.error(e.getMessage());
        System.exit(-1);
    }

    // input files
    Set<File> ins = getFilesForOption(cmd, "infiles");
    // grammar files
    Set<File> gs = getFilesForOption(cmd, "grmrfiles");
    // utility files
    Set<File> uf = getFilesForOption(cmd, "utilfiles");
    // output dir
    Set<File> od = getFilesForOption(cmd, "outdir");

    if (od.size() > 1) {
        LOGGER.error("output directories must be less than or equal to 1");
        System.exit(-1);
    }

    if (ins.size() <= 0) {
        LOGGER.error("no input files were specified");
        System.exit(-1);
    }

    if (gs.size() <= 0) {
        LOGGER.error("no grammar files were specified");
        System.exit(-1);
    }

    LOGGER.info("create generic parser");
    GenericParser gp = null;
    try {
        gp = new GenericParser(gs.toArray(new File[gs.size()]));
    } catch (FileNotFoundException e) {
        LOGGER.error(e.getMessage());
        System.exit(-1);
    }

    if (!uf.isEmpty()) {
        try {
            gp.addUtilityJavaFiles(uf.toArray(new String[uf.size()]));
        } catch (FileNotFoundException e) {
            LOGGER.error(e.getMessage());
            System.exit(-1);
        }
    }

    LOGGER.info("create and add parse tree listener");
    DefaultTreeListener dt = new DefaultTreeListener();
    gp.setListener(dt);

    LOGGER.info("compile generic parser");
    try {
        gp.compile();
    } catch (CompilationException e) {
        LOGGER.error("cannot compile generic parser: {}", e.getMessage());
        System.exit(-1);
    }

    String fpfx = "";
    for (File of : od) {
        if (!of.exists() || !of.isDirectory()) {
            LOGGER.error("output directory does not exist or is not a " + "directory");
            System.exit(-1);
        }
        fpfx = of.getAbsolutePath();
    }

    Ast ast;
    for (File f : ins) {
        try {
            gp.parse(f);
        } catch (IllegalWorkflowException | FileNotFoundException e) {
            LOGGER.error(e.getMessage());
            System.exit(-1);
        }
        ast = dt.getAst();

        if (!fpfx.isEmpty()) {
            String of = fpfx + "/" + FilenameUtils.removeExtension(f.getName()) + ".dot";

            LOGGER.info("write file {}", of);

            try {
                FileUtils.writeStringToFile(new File(of), ast.toDot(), "UTF-8");
            } catch (IOException e) {
                LOGGER.error(e.getMessage());
                System.exit(-1);
            }
        } else {
            LOGGER.info("Tree for {} \n {}", f.getName(), ast.toDot());
        }
    }

    System.exit(0);
}

From source file:com.ignorelist.kassandra.steam.scraper.TaggerCli.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/*from  w  ww  .  ja  v a 2s. com*/
 * @throws org.antlr.runtime.RecognitionException
 * @throws org.apache.commons.cli.ParseException
 */
public static void main(String[] args) throws IOException, RecognitionException, ParseException {
    Options options = buildOptions();
    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine;
    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.out.println(pe.getMessage());
        System.out.println();
        printHelp(options);
        System.exit(0);
        return;
    }
    if (commandLine.hasOption("h")) {
        printHelp(options);
        System.exit(0);
    }
    final PathResolver pathResolver = new PathResolver();

    Configuration configuration;
    Path configurationFile = pathResolver.findConfiguration();
    if (Files.isRegularFile(configurationFile)) {
        configuration = Configuration.fromPropertiesFile(configurationFile);
    } else {
        configuration = new Configuration();
    }
    configuration = toConfiguration(configuration, commandLine);
    //configuration.toProperties().store(System.err, null);

    if (!Files.isRegularFile(configurationFile)) {
        configuration.writeProperties(configurationFile);
        System.err.println(
                "no configuration file present, write based on CLI options: " + configurationFile.toString());
        configuration.toProperties().store(System.err, null);
    }

    Set<Path> sharedConfigPaths = configuration.getSharedConfigPaths();
    if (sharedConfigPaths.size() > 1 && !commandLine.hasOption("w")) {
        System.err.println("multiple sharedconfig.vdf available:\n" + Joiner.on("\n").join(sharedConfigPaths)
                + "\n, can not write to stdout. Need to specify -w or -f with a single sharedconfig.vdf");
        System.exit(1);
    }

    Tagger.Options taggerOptions = Tagger.Options.fromConfiguration(configuration);

    final String[] removeTagsValues = commandLine.getOptionValues("remove");
    if (null != removeTagsValues) {
        taggerOptions.setRemoveTags(Sets.newHashSet(removeTagsValues));
    }

    Set<TagType> tagTypes = configuration.getTagTypes();
    if (null == tagTypes) {
        System.err.println("no tag types!");
        System.exit(1);
    }

    final boolean printTags = commandLine.hasOption("p");

    final HtmlTagLoader htmlTagLoader = new HtmlTagLoader(pathResolver.findCachePath("html"),
            null == configuration.getCacheExpiryDays() ? 7 : configuration.getCacheExpiryDays());
    final BatchTagLoader tagLoader = new BatchTagLoader(htmlTagLoader, configuration.getDownloadThreads());
    if (true || commandLine.hasOption("v")) {
        tagLoader.registerEventListener(new CliEventLoggerLoaded());
    }
    Tagger tagger = new Tagger(tagLoader);

    if (printTags) {
        Set<String> availableTags = tagger.getAvailableTags(sharedConfigPaths, taggerOptions);
        Joiner.on("\n").appendTo(System.out, availableTags);
    } else {
        for (Path path : sharedConfigPaths) {
            VdfNode tagged = tagger.tag(path, taggerOptions);
            if (commandLine.hasOption("w")) {
                Path backup = path.getParent()
                        .resolve(path.getFileName().toString() + ".bak" + new Date().getTime());
                Files.copy(path, backup, StandardCopyOption.REPLACE_EXISTING);
                System.err.println("backup up " + path + " to " + backup);
                Files.copy(new ByteArrayInputStream(tagged.toPrettyString().getBytes(StandardCharsets.UTF_8)),
                        path, StandardCopyOption.REPLACE_EXISTING);
                try {
                    Files.setPosixFilePermissions(path, SHARED_CONFIG_POSIX_PERMS);
                } catch (Exception e) {
                    System.err.println(e);
                }
                System.err.println("wrote " + path);
            } else {
                System.out.println(tagged.toPrettyString());
                System.err.println("pipe to file and copy to: " + path.toString());
            }
        }
    }
}

From source file:Main.java

public static void main(String[] argv) {
    // Create the sorted set
    Set<String> set = new TreeSet<String>();

    set.add("b");
    set.add("c");
    set.add("a");

    Iterator it = set.iterator();
    while (it.hasNext()) {

        Object element = it.next();
        System.out.println(element);
    }/*from  w ww  .  j av  a 2 s  . com*/

    // Create an array containing the elements in a set
    String[] array = (String[]) set.toArray(new String[set.size()]);
    Arrays.toString(array);
}

From source file:MyObject.java

public static void main(String[] args) {
    Set<MyObject> set = new TreeSet<>(new Comparator<MyObject>() {
        @Override/*from  w  ww  .j  av  a  2  s.  c o  m*/
        public int compare(MyObject left, MyObject right) {
            return left.value - right.value;
        }
    });
    set.add(new MyObject(1));
    set.add(new MyObject(2));
    set.add(new MyObject(3));
    set.add(new MyObject(1)); // '1' is already in set
    System.out.println("size:" + set.size());// print 3
    System.out.println(set.remove(new MyObject(3)));
    System.out.println("size:" + set.size());
}

From source file:com.joliciel.lefff.Lefff.java

/**
 * @param args/* w  w w.j  a va 2 s .  c  o  m*/
 */
public static void main(String[] args) throws Exception {
    long startTime = (new Date()).getTime();
    String command = args[0];

    String memoryBaseFilePath = "";
    String lefffFilePath = "";
    String posTagSetPath = "";
    String posTagMapPath = "";
    String word = null;
    List<String> categories = null;
    int startLine = -1;
    int stopLine = -1;

    boolean firstArg = true;
    for (String arg : args) {
        if (firstArg) {
            firstArg = false;
            continue;
        }
        int equalsPos = arg.indexOf('=');
        String argName = arg.substring(0, equalsPos);
        String argValue = arg.substring(equalsPos + 1);
        if (argName.equals("memoryBase"))
            memoryBaseFilePath = argValue;
        else if (argName.equals("lefffFile"))
            lefffFilePath = argValue;
        else if (argName.equals("startLine"))
            startLine = Integer.parseInt(argValue);
        else if (argName.equals("stopLine"))
            stopLine = Integer.parseInt(argValue);
        else if (argName.equals("posTagSet"))
            posTagSetPath = argValue;
        else if (argName.equals("posTagMap"))
            posTagMapPath = argValue;
        else if (argName.equals("word"))
            word = argValue;
        else if (argName.equals("categories")) {
            String[] parts = argValue.split(",");
            categories = new ArrayList<String>();
            for (String part : parts) {
                categories.add(part);
            }
        } else
            throw new RuntimeException("Unknown argument: " + argName);
    }

    final LefffServiceLocator locator = new LefffServiceLocator();
    locator.setDataSourcePropertiesFile("jdbc-live.properties");

    TalismaneServiceLocator talismaneServiceLocator = TalismaneServiceLocator.getInstance();

    final LefffService lefffService = locator.getLefffService();
    if (command.equals("load")) {
        if (lefffFilePath.length() == 0)
            throw new RuntimeException("Required argument: lefffFile");
        final LefffLoader loader = lefffService.getLefffLoader();
        File file = new File(lefffFilePath);
        if (startLine > 0)
            loader.setStartLine(startLine);
        if (stopLine > 0)
            loader.setStopLine(stopLine);

        loader.LoadFile(file);
    } else if (command.equals("serialiseBase")) {
        if (memoryBaseFilePath.length() == 0)
            throw new RuntimeException("Required argument: memoryBase");
        if (posTagSetPath.length() == 0)
            throw new RuntimeException("Required argument: posTagSet");
        if (posTagMapPath.length() == 0)
            throw new RuntimeException("Required argument: posTagMap");

        PosTaggerServiceLocator posTaggerServiceLocator = talismaneServiceLocator.getPosTaggerServiceLocator();
        PosTaggerService posTaggerService = posTaggerServiceLocator.getPosTaggerService();
        File posTagSetFile = new File(posTagSetPath);
        PosTagSet posTagSet = posTaggerService.getPosTagSet(posTagSetFile);

        File posTagMapFile = new File(posTagMapPath);
        LefffPosTagMapper posTagMapper = lefffService.getPosTagMapper(posTagMapFile, posTagSet);

        Map<PosTagSet, LefffPosTagMapper> posTagMappers = new HashMap<PosTagSet, LefffPosTagMapper>();
        posTagMappers.put(posTagSet, posTagMapper);

        LefffMemoryLoader loader = new LefffMemoryLoader();
        LefffMemoryBase memoryBase = loader.loadMemoryBaseFromDatabase(lefffService, posTagMappers, categories);
        File memoryBaseFile = new File(memoryBaseFilePath);
        memoryBaseFile.delete();
        loader.serializeMemoryBase(memoryBase, memoryBaseFile);
    } else if (command.equals("deserialiseBase")) {
        if (memoryBaseFilePath.length() == 0)
            throw new RuntimeException("Required argument: memoryBase");

        LefffMemoryLoader loader = new LefffMemoryLoader();
        File memoryBaseFile = new File(memoryBaseFilePath);
        LefffMemoryBase memoryBase = loader.deserializeMemoryBase(memoryBaseFile);

        String[] testWords = new String[] { "avoir" };
        if (word != null) {
            testWords = word.split(",");
        }

        for (String testWord : testWords) {
            Set<PosTag> possiblePosTags = memoryBase.findPossiblePosTags(testWord);
            LOG.debug("##### PosTags for '" + testWord + "': " + possiblePosTags.size());
            int i = 1;
            for (PosTag posTag : possiblePosTags) {
                LOG.debug("### PosTag " + (i++) + ":" + posTag);
            }

            List<? extends LexicalEntry> entriesForWord = memoryBase.getEntries(testWord);
            LOG.debug("##### Entries for '" + testWord + "': " + entriesForWord.size());
            i = 1;
            for (LexicalEntry entry : entriesForWord) {
                LOG.debug("### Entry " + (i++) + ":" + entry.getWord());
                LOG.debug("Category " + entry.getCategory());
                LOG.debug("Predicate " + entry.getPredicate());
                LOG.debug("Lemma " + entry.getLemma());
                LOG.debug("Morphology " + entry.getMorphology());
            }

            List<? extends LexicalEntry> entriesForLemma = memoryBase.getEntriesForLemma(testWord, "");
            LOG.debug("##### Entries for '" + testWord + "' lemma: " + entriesForLemma.size());
            for (LexicalEntry entry : entriesForLemma) {
                LOG.debug("### Entry " + entry.getWord());
                LOG.debug("Category " + entry.getCategory());
                LOG.debug("Predicate " + entry.getPredicate());
                LOG.debug("Lemma " + entry.getLemma());
                LOG.debug("Morphology " + entry.getMorphology());
                for (PredicateArgument argument : entry.getPredicateArguments()) {
                    LOG.debug("Argument: " + argument.getFunction() + ",Optional? " + argument.isOptional());
                    for (String realisation : argument.getRealisations()) {
                        LOG.debug("Realisation: " + realisation);
                    }
                }
            }
        }

    } else {
        System.out.println("Usage : Lefff load filepath");
    }
    long endTime = (new Date()).getTime() - startTime;
    LOG.debug("Total runtime: " + ((double) endTime / 1000) + " seconds");
}

From source file:edu.umass.cs.reconfiguration.reconfigurationpackets.CreateServiceName.java

public static void main(String[] args) {
    try {//www  .j  av  a2s.c  om
        Util.assertAssertionsEnabled();
        InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName("localhost"), 2345);
        int numNames = 1000;
        String[] reconfigurators = { "RC43", "RC22", "RC78", "RC21", "RC143" };
        String namePrefix = "someName";
        String defaultState = "default_initial_state";
        String[] names = new String[numNames];
        String[] states = new String[numNames];
        for (int i = 0; i < numNames; i++) {
            names[i] = namePrefix + i;
            states[i] = defaultState + i;
        }
        CreateServiceName bcreate1 = new CreateServiceName(isa, "random0", 0, "hello");
        HashMap<String, String> nameStates = new HashMap<String, String>();
        for (int i = 0; i < names.length; i++)
            nameStates.put(names[i], states[i]);
        CreateServiceName bcreate2 = new CreateServiceName(isa, names[0], 0, states[0], nameStates);
        System.out.println(bcreate1.toString());
        System.out.println(bcreate2.toString());

        // translate a batch into consistent constituent batches
        Collection<Set<String>> batches = ConsistentReconfigurableNodeConfig.splitIntoRCGroups(
                new HashSet<String>(Arrays.asList(names)), new HashSet<String>(Arrays.asList(reconfigurators)));
        int totalSize = 0;
        int numBatches = 0;
        for (Set<String> batch : batches)
            System.out.println("batch#" + numBatches++ + " of size " + batch.size() + " (totalSize = "
                    + (totalSize += batch.size()) + ")" + " = " + batch);
        assert (totalSize == numNames);
        System.out.println(bcreate2.getSummary());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.CdoQueryGetBranchStatements.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);// w  w  w .ja  v a 2s .  c  o  m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoQueryGetBranchStatements.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();
            {
                Runtime.getRuntime().gc();
                long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
                LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}",
                        MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                Set<TextElement> list = ASE2015JavaQueries.getCommentsTagContent(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
                Runtime.getRuntime().gc();
                long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
                LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}",
                        MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
                LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                        MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

            }

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.NeoEMFGraphQueryGetBranchStatements.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);//from  ww w  . j a  v a  2s  .c o  m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(optFileOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME,
                new BlueprintsPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = NeoEMFGraphQueryGetBranchStatements.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
                .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                loadOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        // Add the LoadedObjectCounter store
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        //         storeOptions.add(PersistentResourceOptions.EStoreOption.LOADED_OBJECT_COUNTER_LOGGING);
        storeOptions.add(BlueprintsResourceOptions.EStoreGraphOption.AUTOCOMMIT);
        loadOpts.put(PersistentResourceOptions.STORE_OPTIONS, storeOptions);
        resource.load(loadOpts);
        {
            Runtime.getRuntime().gc();
            long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}",
                    MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            Set<TextElement> list = ASE2015JavaQueries.getCommentsTagContent(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            Runtime.getRuntime().gc();
            long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
            LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:com.amazonaws.services.iot.demo.danbo.rpi.Danbo.java

public static void main(String[] args) throws Exception {
    log.debug("starting");

    // uses pin 6 for the red Led
    final Led redLed = new Led(6);
    // uses pin 26 for the green Led
    final Led greenLed = new Led(26);

    // turns the red led on initially
    redLed.on();/*w  w w . j  a va2 s .c  om*/

    // turns the green led off initially
    greenLed.off();

    // loads properties from danbo.properties file - make sure this file is
    // available on the pi's home directory
    InputStream input = new FileInputStream("/home/pi/danbo/danbo.properties");
    Properties properties = new Properties();
    properties.load(input);
    endpoint = properties.getProperty("awsiot.endpoint");
    rootCA = properties.getProperty("awsiot.rootCA");
    privateKey = properties.getProperty("awsiot.privateKey");
    certificate = properties.getProperty("awsiot.certificate");
    url = protocol + endpoint + ":" + port;

    log.debug("properties loaded");

    // turns off both eyes
    RGBLed rgbLed = new RGBLed("RGBLed1", Danbo.pinLayout1, Danbo.pinLayout2, new Color(0, 0, 0),
            new Color(0, 0, 0), 0, 100);
    new Thread(rgbLed).start();

    // resets servo to initial positon
    Servo servo = new Servo("Servo", 1);
    new Thread(servo).start();

    // gets the Pi serial number and uses it as part of the thing
    // registration name
    clientId = clientId + getSerialNumber();

    // AWS IoT things shadow topics
    updateTopic = "$aws/things/" + clientId + "/shadow/update";
    deltaTopic = "$aws/things/" + clientId + "/shadow/update/delta";
    rejectedTopic = "$aws/things/" + clientId + "/shadow/update/rejected";

    // AWS IoT controller things shadow topic (used to register new things)
    controllerUpdateTopic = "$aws/things/Controller/shadow/update";

    // defines an empty danbo shadow POJO
    final DanboShadow danboShadow = new DanboShadow();
    DanboShadow.State state = danboShadow.new State();
    final DanboShadow.State.Reported reported = state.new Reported();
    reported.setEyes("readyToBlink");
    reported.setHead("readyToMove");
    reported.setMouth("readyToSing");
    reported.setName(clientId);
    state.setReported(reported);
    danboShadow.setState(state);

    // defines an empty controller shadow POJO
    final ControllerShadow controllerShadow = new ControllerShadow();
    ControllerShadow.State controllerState = controllerShadow.new State();
    final ControllerShadow.State.Reported controllerReported = controllerState.new Reported();
    controllerReported.setThingName(clientId);
    controllerState.setReported(controllerReported);
    controllerShadow.setState(controllerState);

    try {
        log.debug("registering");

        // registers the thing (creates a new thing) by updating the
        // controller
        String message = gson.toJson(controllerShadow);
        MQTTPublisher controllerUpdatePublisher = new MQTTPublisher(controllerUpdateTopic, qos, message, url,
                clientId + "-controllerupdate" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                certificate);
        new Thread(controllerUpdatePublisher).start();

        log.debug("registered");

        // clears the thing status (in case the thing already existed)
        Danbo.deleteStatus("initialDelete");

        // creates an MQTT subscriber to the things shadow delta topic
        // (command execution notification)
        MQTTSubscriber deltaSubscriber = new MQTTSubscriber(new DanboShadowDeltaCallback(), deltaTopic, qos,
                url, clientId + "-delta" + rand.nextInt(100000), cleanSession, rootCA, privateKey, certificate);
        new Thread(deltaSubscriber).start();

        // creates an MQTT subscriber to the things shadow error topic
        MQTTSubscriber errorSubscriber = new MQTTSubscriber(new DanboShadowRejectedCallback(), rejectedTopic,
                qos, url, clientId + "-rejected" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                certificate);
        new Thread(errorSubscriber).start();

        // turns the red LED off
        redLed.off();

        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                // turns the green LED on
                greenLed.on();

                log.debug("running publish state thread");

                int temp = -300;
                int humid = -300;

                reported.setTemperature(new Integer(temp).toString());
                reported.setHumidity(new Integer(humid).toString());

                try {
                    // reads the temperature and humidity data
                    Set<Sensor> sensors = Sensors.getSensors();
                    log.debug(sensors.size());

                    for (Sensor sensor : sensors) {
                        log.debug(sensor.getPhysicalQuantity());
                        log.debug(sensor.getValue());
                        if (sensor.getPhysicalQuantity().toString().equals("Temperature")) {
                            temp = sensor.getValue().intValue();
                        }
                        if (sensor.getPhysicalQuantity().toString().equals("Humidity")) {
                            humid = sensor.getValue().intValue();
                        }
                    }

                    log.debug("temperature: " + temp);
                    log.debug("humidity: " + humid);
                    reported.setTemperature(new Integer(temp).toString());
                    reported.setHumidity(new Integer(humid).toString());
                } catch (Exception e) {
                    log.error("an error has ocurred: " + e.getMessage());
                    e.printStackTrace();
                }

                try {
                    // reports current state - last temperature and humidity
                    // read
                    String message = gson.toJson(danboShadow);
                    MQTTPublisher updatePublisher = new MQTTPublisher(updateTopic, qos, message, url,
                            clientId + "-update" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                            certificate);
                    new Thread(updatePublisher).start();
                } catch (Exception e) {
                    log.error("an error has ocurred: " + e.getMessage());
                    e.printStackTrace();
                }

                // turns the green LED off
                greenLed.off();
            }
        }, 0, 5, TimeUnit.SECONDS); // runs this thread every 5 seconds,
        // with an initial delay of 5 seconds
    } catch (MqttException me) {
        // Display full details of any exception that occurs
        log.error("reason " + me.getReasonCode());
        log.error("msg " + me.getMessage());
        log.error("loc " + me.getLocalizedMessage());
        log.error("cause " + me.getCause());
        log.error("excep " + me);
        me.printStackTrace();
    } catch (Throwable th) {
        log.error("msg " + th.getMessage());
        log.error("loc " + th.getLocalizedMessage());
        log.error("cause " + th.getCause());
        log.error("excep " + th);
        th.printStackTrace();
    }
}