Example usage for java.lang Integer parseInt

List of usage examples for java.lang Integer parseInt

Introduction

In this page you can find the example usage for java.lang Integer parseInt.

Prototype

public static int parseInt(String s) throws NumberFormatException 

Source Link

Document

Parses the string argument as a signed decimal integer.

Usage

From source file:com.smith.http.webservice.WebSocketServer.java

public static void main(String[] args) {
    int port;/*ww  w  . j  a va  2 s.  c  o m*/
    if (args.length > 0) {
        port = Integer.parseInt(args[0]);
    } else {
        port = 8080;
    }
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    TNUtil.dao = context.getBean("dao", DaoImpl.class);
    new WebSocketServer(port).run();
}

From source file:com.cloudera.impala.testutil.SentryServicePinger.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    // Parse command line options to get config file path.
    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("config_file")
            .withDescription("Absolute path to a sentry-site.xml config file (string)").hasArg()
            .withArgName("CONFIG_FILE").isRequired().create('c'));
    options.addOption(OptionBuilder.withLongOpt("num_pings")
            .withDescription("Max number of pings to try before failing (int)").hasArg().isRequired()
            .withArgName("NUM_PINGS").create('n'));
    options.addOption(//w w w. ja  va2  s.c om
            OptionBuilder.withLongOpt("sleep_secs").withDescription("Time (s) to sleep between pings (int)")
                    .hasArg().withArgName("SLEEP_SECS").create('s'));
    BasicParser optionParser = new BasicParser();
    CommandLine cmdArgs = optionParser.parse(options, args);

    SentryConfig sentryConfig = new SentryConfig(cmdArgs.getOptionValue("config_file"));
    int numPings = Integer.parseInt(cmdArgs.getOptionValue("num_pings"));
    int maxPings = numPings;
    int sleepSecs = Integer.parseInt(cmdArgs.getOptionValue("sleep_secs"));

    sentryConfig.loadConfig();
    while (numPings > 0) {
        SentryPolicyService policyService = new SentryPolicyService(sentryConfig);
        try {
            policyService.listAllRoles(new User(System.getProperty("user.name")));
            LOG.info("Sentry Service ping succeeded.");
            System.exit(0);
        } catch (Exception e) {
            LOG.error(String.format("Error issing RPC to Sentry Service (attempt %d/%d): ",
                    maxPings - numPings + 1, maxPings), e);
            Thread.sleep(sleepSecs * 1000);
        }
        --numPings;
    }
    System.exit(1);
}

From source file:com.espertech.esper.example.autoid.AutoIdSimMain.java

public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
    if (args.length < 1) {
        System.out.println("Arguments are: <numberOfEvents>");
        System.exit(-1);//  w w w  .j av  a2  s .co m
    }

    int events;
    try {
        events = Integer.parseInt(args[0]);
    } catch (NullPointerException e) {
        System.out.println("Invalid numberOfEvents: " + args[0]);
        System.exit(-2);
        return;
    }

    if (events > 1000) {
        System.out.println("Invalid numberOfEvents: " + args[0]);
        System.out.println(
                "The maxiumum for this example is 1000 events, since the example retains the last 60 seconds of events and each event is an XML document, and heap memory size is 256k for this example.");
        System.exit(-2);
        return;
    }

    // Run the sample
    AutoIdSimMain autoIdSimMain = new AutoIdSimMain(events, "AutoIDSim", false);
    autoIdSimMain.run();
}

From source file:com.sebuilder.interpreter.SeInterpreter.java

public static void main(String[] args) {
    if (args.length == 0) {
        System.out.println(/* w w  w. java2  s.c  o  m*/
                "Usage: [--driver=<drivername] [--driver.<configkey>=<configvalue>...] [--implicitlyWait=<ms>] [--pageLoadTimeout=<ms>] [--stepTypePackage=<package name>] <script path>...");
        System.exit(0);
    }

    Log log = LogFactory.getFactory().getInstance(SeInterpreter.class);

    WebDriverFactory wdf = DEFAULT_DRIVER_FACTORY;
    ScriptFactory sf = new ScriptFactory();
    StepTypeFactory stf = new StepTypeFactory();
    sf.setStepTypeFactory(stf);
    TestRunFactory trf = new TestRunFactory();
    sf.setTestRunFactory(trf);

    ArrayList<String> paths = new ArrayList<String>();
    HashMap<String, String> driverConfig = new HashMap<String, String>();
    for (String s : args) {
        if (s.startsWith("--")) {
            String[] kv = s.split("=", 2);
            if (kv.length < 2) {
                log.fatal("Driver configuration option \"" + s
                        + "\" is not of the form \"--driver=<name>\" or \"--driver.<key>=<value\".");
                System.exit(1);
            }
            if (s.startsWith("--implicitlyWait")) {
                trf.setImplicitlyWaitDriverTimeout(Integer.parseInt(kv[1]));
            } else if (s.startsWith("--pageLoadTimeout")) {
                trf.setPageLoadDriverTimeout(Integer.parseInt(kv[1]));
            } else if (s.startsWith("--stepTypePackage")) {
                stf.setPrimaryPackage(kv[1]);
            } else if (s.startsWith("--driver.")) {
                driverConfig.put(kv[0].substring("--driver.".length()), kv[1]);
            } else if (s.startsWith("--driver")) {
                try {
                    wdf = (WebDriverFactory) Class
                            .forName("com.sebuilder.interpreter.webdriverfactory." + kv[1]).newInstance();
                } catch (ClassNotFoundException e) {
                    log.fatal("Unknown WebDriverFactory: " + "com.sebuilder.interpreter.webdriverfactory."
                            + kv[1], e);
                } catch (InstantiationException e) {
                    log.fatal("Could not instantiate WebDriverFactory "
                            + "com.sebuilder.interpreter.webdriverfactory." + kv[1], e);
                } catch (IllegalAccessException e) {
                    log.fatal("Could not instantiate WebDriverFactory "
                            + "com.sebuilder.interpreter.webdriverfactory." + kv[1], e);
                }
            } else {
                paths.add(s);
            }
        } else {
            paths.add(s);
        }
    }

    if (paths.isEmpty()) {
        log.info("Configuration successful but no paths to scripts specified. Exiting.");
        System.exit(0);
    }

    HashMap<String, String> cfg = new HashMap<String, String>(driverConfig);

    for (String path : paths) {
        try {
            TestRun lastRun = null;
            for (Script script : sf.parse(new File(path))) {
                for (Map<String, String> data : script.dataRows) {
                    try {
                        lastRun = script.testRunFactory.createTestRun(script, log, wdf, driverConfig, data,
                                lastRun);
                        if (lastRun.finish()) {
                            log.info(script.name + " succeeded");
                        } else {
                            log.info(script.name + " failed");
                        }
                    } catch (Exception e) {
                        log.info(script.name + " failed", e);
                    }
                }
            }
        } catch (Exception e) {
            log.fatal("Run error.", e);
            System.exit(1);
        }
    }
}

From source file:com.framework_technology.esper.examples.autoid.AutoIdSimMain.java

public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {

    if (args.length < 1) {
        System.out.println("Arguments are: <numberOfEvents>");
        System.exit(-1);//from  ww w  . j a  v  a2  s.c o m
    }

    int events;
    try {
        events = Integer.parseInt(args[0]);
    } catch (NullPointerException e) {
        System.out.println("Invalid numberOfEvents: " + args[0]);
        System.exit(-2);
        return;
    }

    if (events > 1000) {
        System.out.println("Invalid numberOfEvents: " + args[0]);
        System.out.println(
                "The maxiumum for this example is 1000 events, since the example retains the last 60 seconds of events and each event is an XML document, and heap memory size is 256k for this example.");
        System.exit(-2);
        return;
    }

    // Run the sample
    AutoIdSimMain autoIdSimMain = new AutoIdSimMain(events, "AutoIDSim", false);
    autoIdSimMain.run();
}

From source file:ktdiedrich.imagek.SegmentationCMD.java

/**
 * @author ktdiedrich@gmail.com/*w  w  w  . j a v a 2  s.c  o  m*/
 * @param ags:  [file path] [Median filter size] [imageId]
 * Command line segmentation
 * @throws org.apache.commons.cli.ParseException 
 */
public static void main(String[] args) throws org.apache.commons.cli.ParseException {
    int imageIds[] = null;
    int medianFilterSize = 0;
    float seed = Extractor3D.SEED_HIST_THRES;
    String paths[] = null;

    Options options = new Options();
    options.addOption("p", true, "path name to file including filename");
    options.addOption("m", true, "median filter size, m*2+1");
    options.addOption("i", true, "image ID");
    options.addOption("f", true, "Image ID from");
    options.addOption("t", true, "Image ID to, (inclusive)");
    options.addOption("s", true, "Seed threshold default " + seed);
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("s")) {
        seed = Float.parseFloat(cmd.getOptionValue("s"));
    }
    if (cmd.hasOption("i")) {
        imageIds = new int[1];
        imageIds[0] = Integer.parseInt(cmd.getOptionValue("i"));
        paths = new String[1];
        paths[0] = getImageIdPath(imageIds[0]);
        // TODO get path to image ID from database and properties file. 
    }
    if (cmd.hasOption("f") && cmd.hasOption("t")) {
        int from = Integer.parseInt(cmd.getOptionValue("f"));
        int to = Integer.parseInt(cmd.getOptionValue("t"));
        int range = to - from + 1;
        paths = new String[range];
        imageIds = new int[range];
        for (int i = 0, imId = from; i < range; i++, imId++) {
            imageIds[i] = imId;
            paths[i] = getImageIdPath(imId);
        }
    }
    if (paths == null && cmd.hasOption("p")) {
        paths = new String[1];
        paths[0] = cmd.getOptionValue("p");
    }
    if (cmd.hasOption("m")) {
        medianFilterSize = Integer.parseInt(cmd.getOptionValue("m"));
    }

    // System.out.println("ImageID: "+imageId+" Path: "+paths+" Median filter: "+medianFilterSize);
    if (paths != null) {
        int i = 0;
        for (String path : paths) {
            String p[] = parseDirectoryFileName(path);
            String dirPath = p[0];
            ImagePlus segImage = segment(path, medianFilterSize, imageIds[i], seed);
            String title = segImage.getShortTitle();
            if (title.contains(File.separator))
                ;
            {
                title = parseDirectoryFileName(title)[1];
            }
            String outputPath = null;
            if (!dirPath.endsWith(File.separator))
                dirPath = dirPath + File.separator;
            outputPath = dirPath + title + ".zip";

            FileSaver fs = new FileSaver(segImage);
            fs.saveAsZip(outputPath);
            System.out.println("Saved: " + outputPath);
            ImagePlus mipYim = MIP.createShortMIP(segImage, MIP.Y_AXIS);
            fs = new FileSaver(mipYim);
            title = mipYim.getShortTitle();
            if (title.contains(File.separator))
                ;
            {
                title = parseDirectoryFileName(title)[1];
            }
            outputPath = dirPath + title + ".png";
            fs.saveAsPng(outputPath);
            System.out.println("Saved: " + outputPath + "\n");
            i++;
        }
    }
}

From source file:com.baystep.jukeberry.JukeBerry.java

/**
 * @param args the command line arguments
 *///  w  ww .jav  a  2s  .  c om
public static void main(String[] args) {
    System.out.println("Berry Music\n");

    JukeBerry bm = new JukeBerry();

    buildOptions();
    CommandLineParser cmdParser = new DefaultParser();
    try {
        CommandLine cmd = cmdParser.parse(cmdOptions, args);

        if (cmd.hasOption("h")) {
            cmdHelp.printHelp("BerryMusic", help_Header, cmdOptions, help_Footer, true);
            System.exit(0);
        }

        if (cmd.hasOption("pw"))
            bm.config.httpPort = Integer.parseInt(cmd.getOptionValue("pw"));

        if (cmd.hasOption("ps"))
            bm.config.websocketPort = Integer.parseInt(cmd.getOptionValue("ps"));

        if (cmd.hasOption("d")) {
            String dOpt = cmd.getOptionValue("d");
            bm.config.setDisableOption(dOpt);
        }

        if (cmd.hasOption("ss"))
            bm.config.mpStartService = cmd.getOptionValue("ss");

        if (cmd.hasOption("sc")) {
            BerryLogger.supressConsole();
        }

    } catch (ParseException pe) {
        System.err.println("Command line parsing failed, reason: " + pe.getMessage());
    }

    bm.init();
}

From source file:com.aerospike.example.cache.AsACache.java

public static void main(String[] args) throws AerospikeException {
    try {/*from  w  w w  .j  a v  a 2s.  c  o  m*/
        Options options = new Options();
        options.addOption("h", "host", true, "Server hostname (default: 127.0.0.1)");
        options.addOption("p", "port", true, "Server port (default: 3000)");
        options.addOption("n", "namespace", true, "Namespace (default: test)");
        options.addOption("s", "set", true, "Set (default: demo)");
        options.addOption("u", "usage", false, "Print usage.");

        CommandLineParser parser = new PosixParser();
        CommandLine cl = parser.parse(options, args, false);

        String host = cl.getOptionValue("h", "127.0.0.1");
        String portString = cl.getOptionValue("p", "3000");
        int port = Integer.parseInt(portString);
        String namespace = cl.getOptionValue("n", "test");
        String set = cl.getOptionValue("s", "demo");
        log.debug("Host: " + host);
        log.debug("Port: " + port);
        log.debug("Namespace: " + namespace);
        log.debug("Set: " + set);

        @SuppressWarnings("unchecked")
        List<String> cmds = cl.getArgList();
        if (cmds.size() == 0 && cl.hasOption("u")) {
            logUsage(options);
            return;
        }

        AsACache as = new AsACache(host, port, namespace, set);

        as.work();

    } catch (Exception e) {
        log.error("Critical error", e);
    }
}

From source file:com.dataartisans.timeoutmonitoring.TimeoutMonitoring.java

public static void main(String[] args) throws Exception {
    ParameterTool params = ParameterTool.fromArgs(args);

    String filePath = params.get("filePath");
    String delayStr = params.get("eventDelay");
    String sessionTimeoutStr = params.get("sessionTimeout");

    if (filePath == null || delayStr == null || sessionTimeoutStr == null) {
        System.out.println(//  w  w  w  .  j a v a2s . c  o m
                "Job requires the --filePath, --sessionTimeout and --eventDelay option to be specified.");
    } else {
        int delay = Integer.parseInt(delayStr);
        int sessionTimeout = Integer.parseInt(sessionTimeoutStr);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        final String[] inputKeys = { "_context_request_id", "payload:instance_type_id", "timestamp",
                "event_type", "publisher_id", "_context_user_name", "_context_project_name", "_context_tenant",
                "_context_project_id" };
        final String key = "_context_request_id";
        final String[] resultFields = { "_context_request_id", "timestamp" };
        final String errorKey = "event_type";
        final String errorRegex = "trove.+error";
        final String timestampPattern = "yyyy-MM-dd HH:mm:ss.SSSSSS";

        final Pattern errorPattern = Pattern.compile(errorRegex);

        DataStream<String> input = env.readTextFile(filePath);
        DataStream<JSONObject> jsonObjects = input.map(new MapFunction<String, JSONObject>() {
            @Override
            public JSONObject map(String s) throws Exception {
                return new JSONObject(s);
            }
        });

        Function<JSONObject, Long> timestampExtractor = new TimestampExtractorFunction("timestamp",
                timestampPattern);

        @SuppressWarnings("unchecked")
        DataStream<JSONObject> sessionMonitoring = JSONSessionMonitoring.createSessionMonitoring(jsonObjects, // input data set
                inputKeys, // json elements to keep from the input
                key, // key to group on
                new JSONObjectPredicateAnd( // session start element
                        new JSONObjectPredicateMatchRegex("publisher_id", Pattern.compile("api.*novactl.*")),
                        new JSONObjectPredicateMatchEquals<>("event_type", "compute.instance.update")),
                new JSONObjectPredicateMatchEquals<>("event_type", "compute.instance.create.end"), // session end element
                timestampExtractor, delay, // maximum delay of events
                sessionTimeout, // session timeout
                new LatencyWindowFunction(resultFields), // create the latency from the first and last element of the session
                new LatencyTimeoutFunction(resultFields, sessionTimeout));

        TypeInformation<JSONObject> jsonObjectTypeInformation = TypeExtractor.getForClass(JSONObject.class);

        DataStream<JSONObject> sessionTimeouts = sessionMonitoring.filter(new FilterFunction<JSONObject>() {
            @Override
            public boolean filter(JSONObject jsonObject) throws Exception {
                return jsonObject.has("sessionTimeout"); // we only want to keep the session timeouts
            }
        });

        DataStream<JSONObject> sessionAlerts = Alert.createAlert(sessionTimeouts, // filtered input for session timeouts
                "SessionAlerts", // name of operator
                5, // number of trigger events
                300000, // interval length in which the trigger events have to occur (milliseconds)
                new JSONObjectAlertFunction("alert", // alert key
                        "sessionTimeout", // alert value
                        "timestamp", // timestamp key
                        timestampPattern // timestamp pattern to generate
                ), jsonObjectTypeInformation // output type information
        );

        DataStream<JSONObject> troveEvents = jsonObjects.filter(new FilterFunction<JSONObject>() {
            @Override
            public boolean filter(JSONObject jsonObject) throws Exception {
                return errorPattern.matcher(jsonObject.optString(errorKey)).matches();
            }
        });

        DataStream<JSONObject> troveAlerts = Alert.createAlert(troveEvents, "TroveAlerts", 3, 50000,
                new JSONObjectAlertFunction("alert", "troveAlert", "timestamp", timestampPattern),
                jsonObjectTypeInformation);

        sessionAlerts.print();
        troveAlerts.print();

        env.execute("Execute timeout monitoring");
    }
}

From source file:com.jivesoftware.os.routing.bird.deployable.config.extractor.ConfigExtractor.java

public static void main(String[] args) {
    String configHost = args[0];/*  w w  w . j a  va 2s.c om*/
    String configPort = args[1];
    String instanceKey = args[2];
    String instanceVersion = args[3];
    String setPath = args[4];
    String getPath = args[5];

    HttpRequestHelper buildRequestHelper = buildRequestHelper(null, configHost, Integer.parseInt(configPort));

    try {
        Set<URL> packages = new HashSet<>();
        for (int i = 5; i < args.length; i++) {
            packages.addAll(ClasspathHelper.forPackage(args[i]));
        }

        Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(packages)
                .setScanners(new SubTypesScanner(), new TypesScanner()));

        Set<Class<? extends Config>> subTypesOf = reflections.getSubTypesOf(Config.class);

        File configDir = new File("./config");
        configDir.mkdirs();

        Set<Class<? extends Config>> serviceConfig = new HashSet<>();
        Set<Class<? extends Config>> healthConfig = new HashSet<>();
        for (Class<? extends Config> type : subTypesOf) {
            if (HealthCheckConfig.class.isAssignableFrom(type)) {
                healthConfig.add(type);
            } else {
                serviceConfig.add(type);
            }
        }

        Map<String, String> defaultServiceConfig = extractAndPublish(serviceConfig,
                new File(configDir, "default-service-config.properties"), "default", instanceKey,
                instanceVersion, buildRequestHelper, setPath);

        DeployableConfig getServiceOverrides = new DeployableConfig("override", instanceKey, instanceVersion,
                defaultServiceConfig);
        DeployableConfig gotSerivceConfig = buildRequestHelper.executeRequest(getServiceOverrides, getPath,
                DeployableConfig.class, null);
        if (gotSerivceConfig == null) {
            System.out.println("Failed to publish default service config for " + Arrays.deepToString(args));
        } else {
            Properties override = createKeySortedProperties();
            override.putAll(gotSerivceConfig.properties);
            override.store(new FileOutputStream("config/override-service-config.properties"), "");
        }

        Map<String, String> defaultHealthConfig = extractAndPublish(healthConfig,
                new File(configDir, "default-health-config.properties"), "default-health", instanceKey,
                instanceVersion, buildRequestHelper, setPath);

        DeployableConfig getHealthOverrides = new DeployableConfig("override-health", instanceKey,
                instanceVersion, defaultHealthConfig);
        DeployableConfig gotHealthConfig = buildRequestHelper.executeRequest(getHealthOverrides, getPath,
                DeployableConfig.class, null);
        if (gotHealthConfig == null) {
            System.out.println("Failed to publish default health config for " + Arrays.deepToString(args));
        } else {
            Properties override = createKeySortedProperties();
            override.putAll(gotHealthConfig.properties);
            override.store(new FileOutputStream("config/override-health-config.properties"), "");
        }

        Properties instanceProperties = createKeySortedProperties();
        File configFile = new File("config/instance.properties");
        if (configFile.exists()) {
            instanceProperties.load(new FileInputStream(configFile));
        }

        Properties serviceOverrideProperties = createKeySortedProperties();
        configFile = new File("config/override-service-config.properties");
        if (configFile.exists()) {
            serviceOverrideProperties.load(new FileInputStream(configFile));
        }

        Properties healthOverrideProperties = createKeySortedProperties();
        configFile = new File("config/override-health-config.properties");
        if (configFile.exists()) {
            healthOverrideProperties.load(new FileInputStream(configFile));
        }

        Properties properties = createKeySortedProperties();
        properties.putAll(defaultServiceConfig);
        properties.putAll(defaultHealthConfig);
        properties.putAll(serviceOverrideProperties);
        properties.putAll(healthOverrideProperties);
        properties.putAll(instanceProperties);
        properties.store(new FileOutputStream("config/config.properties"), "");

        System.exit(0);
    } catch (Exception x) {
        x.printStackTrace();
        System.exit(1);
    }

}