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:cn.lynx.emi.license.GenerateLicense.java

public static void main(String[] args) throws ClassNotFoundException, ParseException {
    if (args == null || args.length != 4) {
        System.err.println("Please provide [machine code] [cpu] [memory in gb] [yyyy-MM-dd] as parameter");
        return;//  w  ww.  jav a  2s .  com
    }

    InputStream is = GenerateLicense.class.getResourceAsStream("/privatekey");
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String key = null;
    try {
        key = br.readLine();
    } catch (IOException e) {
        System.err.println(
                "Can't read the private key file, make sure there's a file named \"privatekey\" in the root classpath");
        e.printStackTrace();
        return;
    }

    if (key == null) {
        System.err.println(
                "Can't read the private key file, make sure there's a file named \"privatekey\" in the root classpath");
        return;
    }

    String machineCode = args[0];
    int cpu = Integer.parseInt(args[1]);
    long mem = Long.parseLong(args[2]) * 1024 * 1024 * 1024;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    long expDate = sdf.parse(args[3]).getTime();

    LicenseBean lb = new LicenseBean();
    lb.setCpuCount(cpu);
    lb.setMemCount(mem);
    lb.setMachineCode(machineCode);
    lb.setExpireDate(expDate);

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(baos);
        os.writeObject(lb);
        os.close();

        String serializedLicense = Base64.encodeBase64String(baos.toByteArray());
        System.out.println("License:" + encrypt(key, serializedLicense));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:edu.illinois.cs.cogcomp.wikifier.utils.freebase.cleanDL.java

public static void main(String[] args) throws IOException {
    List<String> lines = FileUtils.readLines(new File("/Users/Shyam/mention.eval.dl"));

    for (String line : lines) {
        String[] parts = line.split("\\s+");
        System.out.println(parts[0] + parts[1] + parts[2]);
        StringBuilder sb = new StringBuilder();
        for (int i = 3; i < parts.length; i++)
            sb.append(parts[i] + " ");
        if (mentionFilter(parts)) {
            System.out.println("removing " + Arrays.asList(parts));
            continue;
        }//from w  ww  . j  a  v  a  2s  .co m
        if (mentions.containsKey(parts[0])) {
            mentions.get(parts[0]).add(new DocMention(parts[0], sb.toString(), Integer.parseInt(parts[1]),
                    Integer.parseInt(parts[2])));
        } else {
            mentions.put(parts[0], new ArrayList<DocMention>());
            mentions.get(parts[0]).add(new DocMention(parts[0], sb.toString(), Integer.parseInt(parts[1]),
                    Integer.parseInt(parts[2])));
        }
    }
    for (String doc : mentions.keySet()) {
        handleDoc(mentions.get(doc));
    }

    outputMentions();
}

From source file:com.google.flightmap.parsing.faa.nasr.tools.RecordClassMaker.java

public static void main(String[] args) {
    try {/*from  www . ja  v  a2  s.c o m*/
        final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        final String name = in.readLine();
        final List<RecordEntry> entries = new LinkedList<RecordEntry>();
        String line;
        while ((line = in.readLine()) != null) {
            final String[] parts = line.split("\\s+");
            final int length = Integer.parseInt(parts[0]);
            final int start = Integer.parseInt(parts[1]);
            final String entryName = parts[2];
            entries.add(new RecordEntry(length, start, entryName));
        }
        (new RecordClassMaker(name, entries)).execute();
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(1);
    }
}

From source file:org.eclipse.swt.snippets.Snippet310.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Snippet 310");
    shell.setLayout(new GridLayout());
    final Spinner spinner = new Spinner(shell, SWT.BORDER);
    spinner.setValues(0, -100, 100, 0, 1, 10);
    spinner.setLayoutData(new GridData(200, SWT.DEFAULT));
    final ToolTip toolTip = new ToolTip(shell, SWT.BALLOON | SWT.ICON_WARNING);
    spinner.addModifyListener(e -> {/*from w  w w  .  ja  v  a2  s .c  o  m*/
        String string = spinner.getText();
        String message = null;
        try {
            int value = Integer.parseInt(string);
            int maximum = spinner.getMaximum();
            int minimum = spinner.getMinimum();
            if (value > maximum) {
                message = "Current input is greater than the maximum limit (" + maximum + ")";
            } else if (value < minimum) {
                message = "Current input is less than the minimum limit (" + minimum + ")";
            }
        } catch (Exception ex) {
            message = "Current input is not numeric";
        }
        if (message != null) {
            spinner.setForeground(display.getSystemColor(SWT.COLOR_RED));
            Rectangle rect = spinner.getBounds();
            GC gc = new GC(spinner);
            Point pt = gc.textExtent(string);
            gc.dispose();
            toolTip.setLocation(display.map(shell, null, rect.x + pt.x, rect.y + rect.height));
            toolTip.setMessage(message);
            toolTip.setVisible(true);
        } else {
            toolTip.setVisible(false);
            spinner.setForeground(null);
        }
    });
    shell.setSize(300, 100);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

From source file:net.java.sen.tools.MkCompoundTable.java

/**
 * Build compound word table./*from   www. j av a2  s.  co  m*/
 */
public static void main(String args[]) {
    ResourceBundle rb = ResourceBundle.getBundle("dictionary");
    int pos_start = Integer.parseInt(rb.getString("pos_start"));
    int pos_size = Integer.parseInt(rb.getString("pos_size"));

    try {
        log.info("reading compound word information ... ");
        HashMap compoundTable = new HashMap();

        log.info("load dic: " + rb.getString("compound_word_file"));
        BufferedReader dicStream = new BufferedReader(new InputStreamReader(
                new FileInputStream(rb.getString("compound_word_file")), rb.getString("dic.charset")));

        String t;
        int line = 0;

        StringBuffer pos_b = new StringBuffer();
        while ((t = dicStream.readLine()) != null) {
            CSVParser parser = new CSVParser(t);
            String csv[] = parser.nextTokens();
            if (csv.length < (pos_size + pos_start)) {
                throw new RuntimeException("format error:" + line);
            }

            pos_b.setLength(0);
            for (int i = pos_start; i < (pos_start + pos_size - 1); i++) {
                pos_b.append(csv[i]);
                pos_b.append(',');
            }

            pos_b.append(csv[pos_start + pos_size - 1]);
            pos_b.append(',');

            for (int i = pos_start + pos_size; i < (csv.length - 2); i++) {
                pos_b.append(csv[i]);
                pos_b.append(',');
            }
            pos_b.append(csv[csv.length - 2]);
            compoundTable.put(pos_b.toString(), csv[csv.length - 1]);
        }
        dicStream.close();
        log.info("done.");
        log.info("writing compound word table ... ");
        ObjectOutputStream os = new ObjectOutputStream(
                new FileOutputStream(rb.getString("compound_word_table")));
        os.writeObject(compoundTable);
        os.close();
        log.info("done.");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:MondrianService.java

public static void main(String[] arg) {
    System.out.println("Starting Mondrian Connector for Infoveave");
    Properties prop = new Properties();
    InputStream input = null;/*from w  w  w . j  a va  2 s .  co m*/
    int listenPort = 9998;
    int threads = 100;
    try {
        System.out.println("Staring from :" + getSettingsPath());
        input = new FileInputStream(getSettingsPath() + File.separator + "MondrianService.properties");
        prop.load(input);
        listenPort = Integer.parseInt(prop.getProperty("port"));
        threads = Integer.parseInt(prop.getProperty("maxThreads"));
        if (input != null) {
            input.close();
        }
        System.out.println("Found MondrianService.Properties");
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }

    port(listenPort);
    threadPool(threads);
    enableCORS("*", "*", "*");

    ObjectMapper mapper = new ObjectMapper();
    MondrianConnector connector = new MondrianConnector();
    get("/ping", (request, response) -> {
        response.type("application/json");
        return "\"Here\"";
    });

    post("/cubes", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            return mapper.writeValueAsString(connector.GetCubes(queryObject));
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });

    post("/measures", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            return mapper.writeValueAsString(connector.GetMeasures(queryObject));
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });

    post("/dimensions", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            return mapper.writeValueAsString(connector.GetDimensions(queryObject));
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });

    post("/cleanCache", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            return mapper.writeValueAsString(connector.CleanCubeCache(queryObject));
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });

    post("/executeQuery", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            String content = mapper.writeValueAsString(connector.ExecuteQuery2(queryObject));
            return content;
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });
}

From source file:httpscheduler.HttpScheduler.java

/**
 * @param args the command line arguments
 * @throws java.lang.Exception/*from  ww  w .ja va  2 s. c om*/
 */

public static void main(String[] args) throws Exception {

    if (args.length != 2) {
        System.err.println("Invalid command line parameters for worker");
        System.exit(-1);
    }

    int fixedExecutorSize = 4;

    //Creating fixed size executor
    ThreadPoolExecutor taskCommExecutor = new ThreadPoolExecutor(fixedExecutorSize, fixedExecutorSize, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
    // Used for late binding
    JobMap jobMap = new JobMap();

    // Set port number
    int port = Integer.parseInt(args[0]);

    // Set worker mode
    String mode = args[1].substring(2);

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    // Different handlers for late binding and generic cases
    if (mode.equals("late"))
        reqistry.register("*", new LateBindingRequestHandler(taskCommExecutor, jobMap));
    else
        reqistry.register("*", new GenericRequestHandler(taskCommExecutor, mode));

    // Set up the HTTP service
    HttpService httpService = new HttpService(httpproc, reqistry);

    SSLServerSocketFactory sf = null;

    // create a thread to listen for possible client available connections
    Thread t;
    if (mode.equals("late"))
        t = new LateBindingRequestListenerThread(port, httpService, sf);
    else
        t = new GenericRequestListenerThread(port, httpService, sf);
    System.out.println("Request Listener Thread created");
    t.setDaemon(false);
    t.start();

    // main thread should wait for the listener to exit before shutdown the
    // task executor pool
    t.join();

    // shutdown task executor pool and wait for any taskCommExecutor thread
    // still running
    taskCommExecutor.shutdown();
    while (!taskCommExecutor.isTerminated()) {
    }

    System.out.println("Finished all task communication executor threads");
    System.out.println("Finished all tasks");

}

From source file:koper.demo.performance.KafkaReceiverPerf.java

/**
 * ??//from   w  w w  .ja  v a 2  s. com
 * @param args : ?(?)????
 */
public static void main(String[] args) {
    final ApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:kafka/context-data-consumer.xml");

    if (args.length > 0) {
        int statLine = Integer.parseInt(args[0]);
        OrderListener listener = context.getBean(OrderListener.class);
        listener.changeStatLine(statLine);
    }

    final ConsumerLauncher consumerLauncher = context.getBean(ConsumerLauncher.class);
    // we have close the switch in context-data-consumer.xml profile(autoStart) temporary
    consumerLauncher.start();

    logger.info("KafkaReceiverPerf started!");
}

From source file:nl.knaw.dans.easy.sword2examples.ContinuedDeposit.java

public static void main(String[] args) throws Exception {
    if (args.length != 5) {
        System.err.println(//w  w w.jav  a2  s  .c  o m
                "Usage: java nl.knaw.dans.easy.sword2examples.ContinuedDeposit <Col-IRI> <EASY uid> <EASY passwd> <chunk size> <bag dirname>");
        System.exit(1);
    }

    // 0. Read command line arguments
    final IRI colIri = new IRI(args[0]);
    final String uid = args[1];
    final String pw = args[2];
    final int chunkSize = Integer.parseInt(args[3]);
    final String bagFileName = args[4];

    depositPackage(new File(bagFileName), colIri, uid, pw, chunkSize);
}

From source file:com.tonygalati.sprites.SpriteGenerator.java

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

    //        if (args.length != 3)
    //        {// w ww  .  j av  a  2s  .  com
    //           System.out.print("Usage: com.tonygalati.sprites.SpriteGenerator {path to images} {margin between images in px} {output file}\n");
    //           System.out.print("Note: The max height should only be around 32,767px due to Microsoft GDI using a 16bit signed integer to store dimensions\n");
    //           System.out.print("going beyond this dimension is possible with this tool but the generated sprite image will not work correctly with\n");
    //           System.out.print("most browsers.\n\n");
    //           return;
    //        }

    //        Integer margin = Integer.parseInt(args[1]);
    Integer margin = Integer.parseInt("1");
    String spriteFile = "icons-" + RandomStringUtils.randomAlphanumeric(10) + ".png";
    SpriteCSSGenerator cssGenerator = new SpriteCSSGenerator();

    ClassLoader classLoader = SpriteGenerator.class.getClassLoader();
    URL folderPath = classLoader.getResource(NAIC_SMALL_ICON);
    if (folderPath != null) {
        File imageFolder = new File(folderPath.getPath());

        // Read images
        ArrayList<BufferedImage> imageList = new ArrayList<BufferedImage>();
        Integer yCoordinate = null;

        for (File f : imageFolder.listFiles()) {
            if (f.isFile()) {
                String fileName = f.getName();
                String ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());

                if (ext.equals("png")) {
                    System.out.println("adding file " + fileName);
                    BufferedImage image = ImageIO.read(f);
                    imageList.add(image);

                    if (yCoordinate == null) {
                        yCoordinate = 0;
                    } else {
                        yCoordinate += (image.getHeight() + margin);
                    }

                    // add to cssGenerator
                    cssGenerator.addSpriteCSS(fileName.substring(0, fileName.indexOf(".")), 0, yCoordinate);
                }
            }
        }

        // Find max width and total height
        int maxWidth = 0;
        int totalHeight = 0;

        for (BufferedImage image : imageList) {
            totalHeight += image.getHeight() + margin;

            if (image.getWidth() > maxWidth)
                maxWidth = image.getWidth();
        }

        System.out.format("Number of images: %s, total height: %spx, width: %spx%n", imageList.size(),
                totalHeight, maxWidth);

        // Create the actual sprite
        BufferedImage sprite = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_ARGB);

        int currentY = 0;
        Graphics g = sprite.getGraphics();
        for (BufferedImage image : imageList) {
            g.drawImage(image, 0, currentY, null);
            currentY += image.getHeight() + margin;
        }

        System.out.format("Writing sprite: %s%n", spriteFile);
        ImageIO.write(sprite, "png", new File(spriteFile));
        File cssFile = cssGenerator.getFile(spriteFile);
        System.out.println(cssFile.getAbsolutePath() + " created");
    } else {
        System.err.println("Could not find folder: " + NAIC_SMALL_ICON);

    }

}