Example usage for java.lang Runtime getRuntime

List of usage examples for java.lang Runtime getRuntime

Introduction

In this page you can find the example usage for java.lang Runtime getRuntime.

Prototype

public static Runtime getRuntime() 

Source Link

Document

Returns the runtime object associated with the current Java application.

Usage

From source file:edu.cmu.cs.lti.ark.fn.identification.latentmodel.LatentAlphabetCreationThreaded.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    final FNModelOptions options = new FNModelOptions(args);

    LogManager.getLogManager().reset();
    final FileHandler fileHandler = new FileHandler(options.logOutputFile.get(), true);
    fileHandler.setFormatter(new SimpleFormatter());
    logger.addHandler(fileHandler);//from www.jav  a 2s  .  co  m

    final int startIndex = options.startIndex.get();
    final int endIndex = options.endIndex.get();
    logger.info("Start:" + startIndex + " end:" + endIndex);
    final RequiredDataForFrameIdentification r = SerializedObjects.readObject(options.fnIdReqDataFile.get());
    final Relations wnRelations = new CachedRelations(r.getRevisedRelMap(), r.getRelatedWordsForWord());
    final Lemmatizer lemmatizer = new CachedLemmatizer(r.getHvLemmaCache());
    final int numThreads = options.numThreads.present() ? options.numThreads.get()
            : Runtime.getRuntime().availableProcessors();
    final File alphabetDir = new File(options.modelFile.get());
    final LatentAlphabetCreationThreaded events = new LatentAlphabetCreationThreaded(alphabetDir,
            options.trainFrameElementFile.get(), options.trainParseFile.get(), r.getFrameMap(),
            new LatentFeatureExtractor(wnRelations, lemmatizer), startIndex, endIndex, numThreads);
    events.createLocalAlphabets();
    combineAlphabets(alphabetDir);
}

From source file:com.vitco.Main.java

public static void main(String[] args) throws Exception {
    // display version number on splash screen
    final SplashScreen splash = SplashScreen.getSplashScreen();
    if (splash != null) {
        Graphics2D g = splash.createGraphics();
        if (g != null) {
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            Font font = Font
                    .createFont(Font.TRUETYPE_FONT,
                            new SaveResourceLoader("resource/font/arcade.ttf").asInputStream())
                    .deriveFont(Font.PLAIN, 42f);
            g.setFont(font);/*w  w w.j  a  va2s .co  m*/
            //g.setFont(g.getFont().deriveFont(9f));
            g.setColor(VitcoSettings.SPLASH_SCREEN_OVERLAY_TEXT_COLOR);
            int width = g.getFontMetrics().stringWidth(VitcoSettings.VERSION_ID);
            g.drawString(VitcoSettings.VERSION_ID, 400 - 20 - width, 110);
            splash.update();
            g.dispose();
        }
    }

    // the JIDE license
    SaveResourceLoader saveResourceLoader = new SaveResourceLoader("resource/jidelicense.txt");
    if (!saveResourceLoader.error) {
        String[] jidelicense = saveResourceLoader.asLines();
        if (jidelicense.length == 3) {
            com.jidesoft.utils.Lm.verifyLicense(jidelicense[0], jidelicense[1], jidelicense[2]);
        }
    }

    // check if we are in debug mode
    if ((args.length > 0) && args[0].equals("debug")) {
        ErrorHandler.setDebugMode();
        debug = true;
    }

    // build the application
    final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "com/vitco/glue/config.xml");

    // for debugging
    if (debug) {
        ((ActionManager) context.getBean("ActionManager")).performValidityCheck();
        ((ComplexActionManager) context.getBean("ComplexActionManager")).performValidityCheck();
    }

    // open vsd file when program is started with "open with"
    MainMenuLogic mainMenuLogic = ((MainMenuLogic) context.getBean("MainMenuLogic"));
    for (String arg : args) {
        if (arg.endsWith(".vsd")) {
            File file = new File(arg);
            if (file.exists() && !file.isDirectory()) {
                mainMenuLogic.openFile(file);
                break;
            }
        }
    }

    // perform shortcut check
    ((ShortcutManager) context.getBean("ShortcutManager")).doSanityCheck(debug);
    //        // test console
    //        final Console console = ((Console) context.getBean("Console"));
    //        new Thread() {
    //            public void run() {
    //                while (true) {
    //                    console.addLine("text");
    //                    try {
    //                        sleep(2000);
    //                    } catch (InterruptedException e) {
    //                       //e.printStackTrace();
    //                    }
    //                }
    //            }
    //        }.start();

    // add a shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            // make reference so Preferences object doesn't get destroyed
            Preferences pref = ((Preferences) context.getBean("Preferences"));
            // trigger @PreDestroy
            context.close();
            // store the preferences (this needs to be done here, b/c
            // some PreDestroys are used to store preferences!)
            pref.save();
        }
    });
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.MorsaCreator.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);/*  ww  w . java  2 s. c  om*/
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output directory");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

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

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

    CommandLineParser parser = new PosixParser();

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

        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        URI targetUri = URI.createURI("morsa://" + commandLine.getOptionValue(OUT));

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

        ResourceSet resourceSet = new ResourceSetImpl();

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put("morsa",
                new MorsaResourceFactoryImpl(new MongoDBMorsaBackendFactory()));

        Resource sourceResource = resourceSet.createResource(sourceUri);
        Map<String, Object> loadOpts = new HashMap<String, Object>();
        if ("zxmi".equals(sourceUri.fileExtension())) {
            loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        }

        Runtime.getRuntime().gc();
        long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}",
                MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
        LOG.log(Level.INFO, "Loading source resource");
        sourceResource.load(loadOpts);
        LOG.log(Level.INFO, "Source resource loaded");
        Runtime.getRuntime().gc();
        long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
        LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

        Resource targetResource = resourceSet.createResource(targetUri);

        Map<String, Object> saveOpts = new HashMap<String, Object>();
        //URI of the MongoDB database (e.g. localhost)
        saveOpts.put(IMorsaResource.OPTION_SERVER_URI, "localhost");
        saveOpts.put(IMorsaResource.OPTION_MAX_SAVE_CACHE_SIZE, 30000);
        saveOpts.put(IMorsaResource.OPTION_DEMAND_LOAD, false);
        targetResource.save(saveOpts);

        LOG.log(Level.INFO, "Start moving elements");
        targetResource.getContents().clear();
        targetResource.getContents().addAll(sourceResource.getContents());
        LOG.log(Level.INFO, "End moving elements");
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saved");

        targetResource.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.griddynamics.jagger.JaggerLauncher.java

public static void main(String[] args) throws Exception {
    Thread memoryMonitorThread = new Thread("memory-monitor") {
        @Override//from w  w w  .j  ava2  s .  co  m
        public void run() {
            for (;;) {
                try {
                    log.info("Memory info: totalMemory={}, freeMemory={}", Runtime.getRuntime().totalMemory(),
                            Runtime.getRuntime().freeMemory());

                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    };
    memoryMonitorThread.setDaemon(true);
    memoryMonitorThread.start();

    String pid = ManagementFactory.getRuntimeMXBean().getName();
    System.out.println(String.format("PID:%s", pid));

    Properties props = System.getProperties();
    for (Map.Entry<Object, Object> prop : props.entrySet()) {
        log.info("{}: '{}'", prop.getKey(), prop.getValue());
    }
    log.info("");

    URL directory = new URL("file:" + System.getProperty("user.dir") + "/");
    loadBootProperties(directory, args[0], environmentProperties);

    log.debug("Bootstrap properties:");
    for (String propName : environmentProperties.stringPropertyNames()) {
        log.debug("   {}={}", propName, environmentProperties.getProperty(propName));
    }

    String[] roles = environmentProperties.getProperty(ROLES).split(",");
    Set<String> rolesSet = Sets.newHashSet(roles);

    if (rolesSet.contains(Role.COORDINATION_SERVER.toString())) {
        launchCoordinationServer(directory);
    }
    if (rolesSet.contains(Role.HTTP_COORDINATION_SERVER.toString())) {
        launchCometdCoordinationServer(directory);
    }
    if (rolesSet.contains(Role.RDB_SERVER.toString())) {
        launchRdbServer(directory);
    }
    if (rolesSet.contains(Role.MASTER.toString())) {
        launchMaster(directory);
    }
    if (rolesSet.contains(Role.KERNEL.toString())) {
        launchKernel(directory);
    }

    if (rolesSet.contains(Role.REPORTER.toString())) {
        launchReporter(directory);
    }

    LaunchManager launchManager = builder.build();

    int result = launchManager.launch();

    System.exit(result);

}

From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoCreator.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);/*w  w w  .  j a v a2  s  .  c o m*/
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output directory");
    outputOpt.setArgs(1);
    outputOpt.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(outputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);
        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));

        String outputDir = commandLine.getOptionValue(OUT);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

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

        ResourceSet resourceSet = new ResourceSetImpl();

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());

        Resource sourceResource = resourceSet.createResource(sourceUri);
        Map<String, Object> loadOpts = new HashMap<String, Object>();
        if ("zxmi".equals(sourceUri.fileExtension())) {
            loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        }

        Runtime.getRuntime().gc();
        long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}",
                MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
        LOG.log(Level.INFO, "Loading source resource");
        sourceResource.load(loadOpts);
        LOG.log(Level.INFO, "Source resource loaded");
        Runtime.getRuntime().gc();
        long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
        LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

        EmbeddedCDOServer server = new EmbeddedCDOServer(outputDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            transaction.getRootResource().getContents().clear();
            LOG.log(Level.INFO, "Start moving elements");
            transaction.getRootResource().getContents().addAll(sourceResource.getContents());
            LOG.log(Level.INFO, "End moving elements");
            LOG.log(Level.INFO, "Commiting");
            transaction.commit();
            LOG.log(Level.INFO, "Commit done");
            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:com.arpnetworking.metrics.mad.Main.java

/**
 * Entry point for Metrics Aggregator Daemon (MAD).
 *
 * @param args the command line arguments
 *//*from www .  j  a v  a  2s. c  o  m*/
public static void main(final String[] args) {
    // Global initialization
    Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
        System.err.println("Unhandled exception! exception: " + throwable.toString());
        throwable.printStackTrace(System.err);
    });

    Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> LOGGER.error()
            .setMessage("Unhandled exception!").setThrowable(throwable).log());

    LOGGER.info().setMessage("Launching mad").log();

    Runtime.getRuntime().addShutdownHook(SHUTDOWN_THREAD);

    System.setProperty("org.vertx.logger-delegate-factory-class-name",
            "org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory");

    // Run the tsd aggregator
    if (args.length != 1) {
        throw new RuntimeException("No configuration file specified");
    }
    LOGGER.debug().setMessage("Loading configuration").addData("file", args[0]).log();

    Optional<DynamicConfiguration> configuration = Optional.empty();
    Optional<Configurator<Main, AggregatorConfiguration>> configurator = Optional.empty();
    try {
        final File configurationFile = new File(args[0]);
        configurator = Optional.of(new Configurator<>(Main::new, AggregatorConfiguration.class));
        configuration = Optional.of(new DynamicConfiguration.Builder().setObjectMapper(OBJECT_MAPPER)
                .addSourceBuilder(getFileSourceBuilder(configurationFile))
                .addTrigger(new FileTrigger.Builder().setFile(configurationFile).build())
                .addListener(configurator.get()).build());

        configuration.get().launch();
        // Wait for application shutdown
        SHUTDOWN_SEMAPHORE.acquire();
    } catch (final InterruptedException e) {
        throw Throwables.propagate(e);
    } finally {
        if (configurator.isPresent()) {
            configurator.get().shutdown();
        }
        if (configuration.isPresent()) {
            configuration.get().shutdown();
        }
        // Notify the shutdown that we're done
        SHUTDOWN_SEMAPHORE.release();
    }
}

From source file:com.curecomp.primefaces.migrator.PrimefacesMigration.java

public static void main(String[] args) throws Exception {
    // Let's use some colors :)
    //        AnsiConsole.systemInstall();
    CommandLineParser cliParser = new BasicParser();
    CommandLine cli = null;//from w w  w  . jav  a  2  s  . c  om
    try {
        cli = cliParser.parse(OPTIONS, args);
    } catch (ParseException e) {
        printHelp();
    }
    if (!cli.hasOption("s")) {
        printHelp();
    }

    String sourcePattern;
    if (cli.hasOption("p")) {
        sourcePattern = cli.getOptionValue("p");
    } else {
        sourcePattern = DEFAULT_SOURCE_PATTERN;
    }

    String defaultAnswer;
    if (cli.hasOption("default-answer")) {
        defaultAnswer = cli.getOptionValue("default-answer");
    } else {
        defaultAnswer = DEFAULT_DEFAULT_PROMPT_ANSWER;
    }

    boolean defaultAnswerYes = defaultAnswer.equalsIgnoreCase("y");
    boolean quiet = cli.hasOption("q");
    boolean testWrite = cli.hasOption("t");
    Path sourceDirectory = Paths.get(cli.getOptionValue("s")).toAbsolutePath();
    // Since we use IO we will have some blocking threads hanging around
    int threadCount = Runtime.getRuntime().availableProcessors() * 2;
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>());
    BlockingQueue<WidgetVarLocation> foundUsages = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> unusedOrAmbiguous = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> skippedUsages = new LinkedBlockingQueue<>();
    List<Future<?>> futures = new ArrayList<>();

    findWidgetVars(sourceDirectory, sourcePattern, threadPool).forEach(widgetVarLocation -> {
        // We can't really find usages of widget vars that use EL expressions :(
        if (widgetVarLocation.widgetVar.contains("#")) {
            unusedOrAmbiguous.add(widgetVarLocation);
            return;
        }

        try {
            FileActionVisitor visitor = new FileActionVisitor(sourceDirectory, sourcePattern,
                    sourceFile -> futures.add(threadPool.submit((Callable<?>) () -> {
                        findWidgetVarUsages(sourceFile, widgetVarLocation, foundUsages, skippedUsages,
                                unusedOrAmbiguous);
                        return null;
                    })));

            Files.walkFileTree(sourceDirectory, visitor);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });

    awaitAll(futures);

    new TreeSet<>(skippedUsages).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped " + relativePath + " at line " + widgetUsage.lineNr + " and col "
                + widgetUsage.columnNr + " for widgetVar '" + widgetUsage.widgetVar + "'");
        System.out.println("\t" + previous);
    });

    Map<WidgetVarLocation, List<WidgetVarLocation>> written = new HashMap<>();

    new TreeSet<>(foundUsages).forEach(widgetUsage -> {
        WidgetVarLocation key = new WidgetVarLocation(null, widgetUsage.location, widgetUsage.lineNr, -1, null);
        List<WidgetVarLocation> writtenList = written.get(key);
        int existing = writtenList == null ? 0 : writtenList.size();
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String next = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED)
                .a("PF('" + widgetUsage.widgetVar + "')").reset().toString());
        System.out
                .println(relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + next);
        System.out.print("Replace (Y/N)? [" + (defaultAnswerYes ? "Y" : "N") + "]: ");

        String input;

        if (quiet) {
            input = "";
            System.out.println();
        } else {
            try {
                do {
                    input = in.readLine();
                } while (input != null && !input.isEmpty() && !"y".equalsIgnoreCase(input)
                        && !"n".equalsIgnoreCase(input));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        if (input == null) {
            System.out.println("Aborted!");
        } else if (input.isEmpty() && defaultAnswerYes || !input.isEmpty() && !"n".equalsIgnoreCase(input)) {
            System.out.println("Replaced!");
            System.out.print("\t");
            if (writtenList == null) {
                writtenList = new ArrayList<>();
                written.put(key, writtenList);
            }

            writtenList.add(widgetUsage);
            List<String> lines;
            try {
                lines = Files.readAllLines(widgetUsage.location);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

            try (OutputStream os = testWrite ? new ByteArrayOutputStream()
                    : Files.newOutputStream(widgetUsage.location);
                    PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
                String line;

                for (int i = 0; i < lines.size(); i++) {
                    int lineNr = i + 1;
                    line = lines.get(i);

                    if (lineNr == widgetUsage.lineNr) {
                        int begin = widgetUsage.columnNr + (testWrite ? 0 : existing * 6);
                        int end = begin + widgetUsage.widgetVar.length();
                        String newLine = replace(line, begin, end, "PF('" + widgetUsage.widgetVar + "')",
                                false);

                        if (testWrite) {
                            System.out.println(newLine);
                        } else {
                            pw.println(newLine);
                        }
                    } else {
                        if (!testWrite) {
                            pw.println(line);
                        }
                    }
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } else {
            System.out.println("Skipped!");
        }
    });

    new TreeSet<>(unusedOrAmbiguous).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped unused or ambiguous " + relativePath + " at line " + widgetUsage.lineNr
                + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + previous);
    });

    threadPool.shutdown();
}

From source file:com.linkedin.pinot.server.starter.FileBasedServer.java

public static void main(String[] args) throws Exception {
    //Process Command Line to get config and port
    processCommandLineArgs(args);/*  w  ww . j av  a  2  s  .  com*/

    LOGGER.info("Trying to build server config");
    MetricsRegistry metricsRegistry = new MetricsRegistry();
    ServerBuilder serverBuilder = new ServerBuilder(new File(_serverConfigPath), metricsRegistry);

    LOGGER.info("Trying to build InstanceDataManager");
    final DataManager instanceDataManager = serverBuilder.buildInstanceDataManager();
    LOGGER.info("Trying to start InstanceDataManager");
    instanceDataManager.start();
    //    bootstrapSegments(instanceDataManager);

    LOGGER.info("Trying to build QueryExecutor");
    final QueryExecutor queryExecutor = serverBuilder.buildQueryExecutor(instanceDataManager);
    final QueryScheduler queryScheduler = serverBuilder.buildQueryScheduler(queryExecutor);
    LOGGER.info("Trying to build RequestHandlerFactory");
    RequestHandlerFactory simpleRequestHandlerFactory = serverBuilder
            .buildRequestHandlerFactory(queryScheduler);
    LOGGER.info("Trying to build NettyServer");

    NettyServer nettyServer = new NettyTCPServer(_serverPort, simpleRequestHandlerFactory, null);
    Thread serverThread = new Thread(nettyServer);
    ShutdownHook shutdownHook = new ShutdownHook(nettyServer);
    serverThread.start();
    Runtime.getRuntime().addShutdownHook(shutdownHook);
}

From source file:com.chigix.autosftp.Application.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(Option.builder("P").longOpt("port").hasArg().build())
            .addOption(Option.builder("h").longOpt("help").desc("Print this message").build())
            .addOption(Option.builder("i").argName("identity_file").hasArg().build());
    int port = 22;
    CommandLine line;/* w  w  w . j  a  va  2s. c  o m*/
    try {
        line = new DefaultParser().parse(options, args);
    } catch (UnrecognizedOptionException ex) {
        System.err.println(ex.getMessage());
        return;
    } catch (ParseException ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }
    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("autosftp /path/to/watch [user@]host2:[file2]", options, true);
        return;
    }
    String givenPort;
    if (line.hasOption("port") && StringUtils.isNumeric(givenPort = line.getOptionValue("port"))) {
        port = Integer.valueOf(givenPort);
    }
    if (line.getArgs().length < 0) {
        System.err.println("Please provide a path to watch.");
        return;
    }
    localPath = Paths.get(line.getArgs()[0]);
    if (line.getArgs().length < 1) {
        System.err.println("Please provide remote ssh information.");
        return;
    }
    SshAddressParser addressParse;
    try {
        addressParse = new SshAddressParser().parse(line.getArgs()[1]);
    } catch (SshAddressParser.InvalidAddressException ex) {
        System.err.println(ex.getMessage());
        return;
    }
    if (addressParse.getDefaultDirectory() != null) {
        remotePath = Paths.get(addressParse.getDefaultDirectory());
    }
    try {
        sshSession = new JSch().getSession(addressParse.getUsername(), addressParse.getHost(), port);
    } catch (JSchException ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }
    try {
        sshOpen();
    } catch (JSchException ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        sshClose();
    }
    System.out.println("Remote Default Path: " + remotePath);
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            sshClose();
            System.out.println("Bye~~~");
        }

    });
    try {
        watchDir(Paths.get(line.getArgs()[0]));
    } catch (Exception ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:cloudworker.RemoteWorker.java

public static void main(String[] args) throws Exception {
    //Command interpreter
    CommandLineInterface cmd = new CommandLineInterface(args);
    final int poolSize = Integer.parseInt(cmd.getOptionValue("s"));
    long idle_time = Long.parseLong(cmd.getOptionValue("i")); //idle time = 60 sec

    init();/*from w  w  w  . ja v  a2s.c  om*/
    System.out.println("Initialized one remote worker.\n");

    //Create thread pool
    ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
    BlockingExecutor blockingPool = new BlockingExecutor(threadPool, poolSize);

    //Get queue url
    GetQueueUrlResult urlResult = sqs.getQueueUrl("JobQueue");
    String jobQueueUrl = urlResult.getQueueUrl();

    // Receive messages
    //System.out.println("Receiving messages from JobQueue.\n");

    //...Check idle state
    boolean terminate = false;
    boolean startClock = true;
    long start_time = 0, end_time;

    JSONParser parser = new JSONParser();
    Runtime runtime = Runtime.getRuntime();
    String task_id = null;
    boolean runAnimoto = false;

    while (!terminate || idle_time == 0) {
        while (getQueueSize(sqs, jobQueueUrl) > 0) {

            //Batch retrieving messages
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest().withQueueUrl(jobQueueUrl)
                    .withMaxNumberOfMessages(10);

            List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();

            for (Message message : messages) {
                //System.out.println("  Message");
                //                  System.out.println("    MessageId:     " + message.getMessageId());
                //                  System.out.println("    ReceiptHandle: " + message.getReceiptHandle());
                //                  System.out.println("    MD5OfBody:     " + message.getMD5OfBody());
                //System.out.println("    Body:          " + message.getBody());

                //Get task
                String messageBody = message.getBody();
                JSONObject json = (JSONObject) parser.parse(messageBody);

                task_id = json.get("task_id").toString();
                String task = json.get("task").toString();

                try {
                    //Check duplicate task
                    dynamoDB.addTask(task_id, task);

                    //Execute task, will be blocked if no more thread is currently available 
                    blockingPool.submitTask(new Animoto(task_id, task, sqs));

                    // Delete the message
                    String messageRecieptHandle = message.getReceiptHandle();
                    sqs.deleteMessage(new DeleteMessageRequest(jobQueueUrl, messageRecieptHandle));
                } catch (ConditionalCheckFailedException ccf) {
                    //DO something...
                }

            }

            startClock = true;

        }

        //Start clock to measure idle time
        if (startClock) {
            startClock = false;
            start_time = System.currentTimeMillis();
        } else {
            end_time = System.currentTimeMillis();
            long elapsed_time = (end_time - start_time) / 1000;
            if (elapsed_time > idle_time) {
                terminate = true;
            }
        }
    }

    //System.out.println();

    threadPool.shutdown();
    // Wait until all threads are finished
    while (!threadPool.isTerminated()) {

    }

    //Terminate running instance
    cleanUpInstance();

}