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.aerospike.examples.travel.FlighAggregation.java

public static void main(String[] args) throws AerospikeException {
    try {/*from w  w  w  .j  a  va  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;
        }

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

        as.init();
        as.work();

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

From source file:search.java

public static void main(String argv[]) {
    int optind;//from   www . j  av  a2 s .  c  om

    String subject = null;
    String from = null;
    boolean or = false;
    boolean today = false;
    int size = -1;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-or")) {
            or = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-subject")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-from")) {
            from = argv[++optind];
        } else if (argv[optind].equals("-today")) {
            today = true;
        } else if (argv[optind].equals("-size")) {
            size = Integer.parseInt(argv[++optind]);
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: search [-D] [-L url] [-T protocol] [-H host] "
                    + "[-U user] [-P password] [-f mailbox] "
                    + "[-subject subject] [-from from] [-or] [-today]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {

        if ((subject == null) && (from == null) && !today && size < 0) {
            System.out.println("Specify either -subject, -from, -today, or -size");
            System.exit(1);
        }

        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("Cant find default namespace");
            System.exit(1);
        }

        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        folder.open(Folder.READ_ONLY);
        SearchTerm term = null;

        if (subject != null)
            term = new SubjectTerm(subject);
        if (from != null) {
            FromStringTerm fromTerm = new FromStringTerm(from);
            if (term != null) {
                if (or)
                    term = new OrTerm(term, fromTerm);
                else
                    term = new AndTerm(term, fromTerm);
            } else
                term = fromTerm;
        }
        if (today) {
            Calendar c = Calendar.getInstance();
            c.set(Calendar.HOUR, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
            c.set(Calendar.AM_PM, Calendar.AM);
            ReceivedDateTerm startDateTerm = new ReceivedDateTerm(ComparisonTerm.GE, c.getTime());
            c.add(Calendar.DATE, 1); // next day
            ReceivedDateTerm endDateTerm = new ReceivedDateTerm(ComparisonTerm.LT, c.getTime());
            SearchTerm dateTerm = new AndTerm(startDateTerm, endDateTerm);
            if (term != null) {
                if (or)
                    term = new OrTerm(term, dateTerm);
                else
                    term = new AndTerm(term, dateTerm);
            } else
                term = dateTerm;
        }

        if (size >= 0) {
            SizeTerm sizeTerm = new SizeTerm(ComparisonTerm.GT, size);
            if (term != null) {
                if (or)
                    term = new OrTerm(term, sizeTerm);
                else
                    term = new AndTerm(term, sizeTerm);
            } else
                term = sizeTerm;
        }

        Message[] msgs = folder.search(term);
        System.out.println("FOUND " + msgs.length + " MESSAGES");
        if (msgs.length == 0) // no match
            System.exit(1);

        // Use a suitable FetchProfile
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        folder.fetch(msgs, fp);

        for (int i = 0; i < msgs.length; i++) {
            System.out.println("--------------------------");
            System.out.println("MESSAGE #" + (i + 1) + ":");
            dumpPart(msgs[i]);
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
    }

    System.exit(1);
}

From source file:httpserver.ElementalHttpServer.java

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

    // Clay code, adding arguments to simulate command line execution
    args = new String[2];
    args[0] = "C://Users/Clay/Documents";
    args[1] = "80";

    if (args.length < 1) {
        System.err.println("Please specify document root directory");
        System.exit(1);/*from   w  w w.j  a  v  a2  s  . c o  m*/
    }
    // Document root directory
    String docRoot = args[0];

    // Setting up port, if port was specified, then use that one
    int port = 8080;
    if (args.length >= 2) {
        port = Integer.parseInt(args[1]);
    }

    // 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();
    reqistry.register("*", new HttpFileHandler(docRoot));

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

    SSLServerSocketFactory sf = null;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = ElementalHttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            System.out.println("Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        sf = sslcontext.getServerSocketFactory();
    }

    Thread t = new RequestListenerThread(port, httpService, sf);
    t.setDaemon(false);
    t.start();
}

From source file:uk.dsxt.voting.tests.TestDataGenerator.java

public static void main(String[] args) {
    try {//from   w  w  w  . j ava2s . c  om
        if (args.length == 1) {
            generateCredentialsJSON();
            return;
        }
        if (args.length > 0 && args.length < 10) {
            System.out.println(
                    "<name> <totalParticipant> <holdersCount> <vmCount> <levelsCount> <minutes> <generateVotes> <victimsCount>");
            throw new IllegalArgumentException("Invalid arguments count exception.");
        }
        int argId = 0;
        String name = args.length == 0 ? "ss_10_100000_30" : args[argId++];
        int totalParticipant = args.length == 0 ? 100000 : Integer.parseInt(args[argId++]);
        int holdersCount = args.length == 0 ? 10 : Integer.parseInt(args[argId++]);
        int vmCount = args.length == 0 ? 1 : Integer.parseInt(args[argId++]);
        int levelsCount = args.length == 0 ? 3 : Integer.parseInt(args[argId++]);
        int minutes = args.length == 0 ? 30 : Integer.parseInt(args[argId++]);
        boolean generateVotes = args.length == 0 ? true : Boolean.parseBoolean(args[argId++]);
        int victimsCount = args.length == 0 ? 0 : Integer.parseInt(args[argId++]);
        boolean generateDisconnect = args.length == 0 ? false : Boolean.parseBoolean(args[argId++]);
        int disconnectNodes = args.length == 0 ? 0 : Integer.parseInt(args[argId]);
        TestDataGenerator generator = new TestDataGenerator();
        generator.generate(name, totalParticipant, holdersCount, vmCount, levelsCount, minutes, generateVotes,
                victimsCount, generateDisconnect, disconnectNodes);
    } catch (Exception e) {
        log.error("Test generation was failed.", e);
    }
}

From source file:com.cloudera.nav.sdk.examples.lineage3.LineageExport.java

/**
 * @param args 1. config file path//ww  w  .  j  a  v  a 2  s.co m
 *             2. query to fetch entities for which lineage
 *             would be downloaded.
 *             3. direction
 *             4. length
 *             5. lineage options
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    Preconditions.checkArgument(args.length == 5);
    Preconditions.checkArgument(
            "downstream".equals(args[2].toLowerCase()) || "upstream".equals(args[2].toLowerCase()));
    Preconditions.checkArgument(Integer.parseInt(args[3]) > 0);
    Preconditions.checkArgument(Integer.parseInt(args[4]) >= -1);

    (new LineageExport(args[0], args[1], args[2].toUpperCase(), args[3], args[4])).run();
}

From source file:msgshow.java

public static void main(String argv[]) {
    int optind;//  w ww . ja v a2s  . co m
    InputStream msgStream = System.in;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-p")) {
            port = Integer.parseInt(argv[++optind]);
        } else if (argv[optind].equals("-s")) {
            showStructure = true;
        } else if (argv[optind].equals("-S")) {
            saveAttachments = true;
        } else if (argv[optind].equals("-m")) {
            showMessage = true;
        } else if (argv[optind].equals("-a")) {
            showAlert = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
            System.out.println("\t[-P password] [-f mailbox] [msgnum ...] [-v] [-D] [-s] [-S] [-a]");
            System.out.println("or     msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        if (showMessage) {
            MimeMessage msg;
            if (mbox != null)
                msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox)));
            else
                msg = new MimeMessage(session, msgStream);
            dumpPart(msg);
            System.exit(0);
        }

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            if (showAlert) {
                store.addStoreListener(new StoreListener() {
                    public void notification(StoreEvent e) {
                        String s;
                        if (e.getMessageType() == StoreEvent.ALERT)
                            s = "ALERT: ";
                        else
                            s = "NOTICE: ";
                        System.out.println(s + e.getMessage());
                    }
                });
            }
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, port, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        if (mbox == null)
            mbox = "INBOX";
        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }
        int totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (optind >= argv.length) {
            // Attributes & Flags for all messages ..
            Message[] msgs = folder.getMessages();

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE #" + (i + 1) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            while (optind < argv.length) {
                int msgnum = Integer.parseInt(argv[optind++]);
                System.out.println("Getting message number: " + msgnum);
                Message m = null;

                try {
                    m = folder.getMessage(msgnum);
                    dumpPart(m);
                } catch (IndexOutOfBoundsException iex) {
                    System.out.println("Message number out of range");
                }
            }
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}

From source file:com.aerospike.examples.ldt.ttl.LdtExpire.java

public static void main(String[] args) throws AerospikeException {
    try {//from   w  w  w  .j  a  va 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.");
        options.addOption("d", "data", false, "Generate data.");

        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;
        }

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

        as.registerUDF();

        if (cl.hasOption("d")) {
            as.generateData();
        } else {
            as.expire();
        }

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

From source file:bboss.org.artofsolving.jodconverter.cli.Convert.java

public static void main(String[] arguments) throws ParseException, JSONException, IOException {
    CommandLineParser commandLineParser = new PosixParser();
    CommandLine commandLine = commandLineParser.parse(OPTIONS, arguments);

    String outputFormat = null;//www  .  ja v  a 2s .c o  m
    if (commandLine.hasOption(OPTION_OUTPUT_FORMAT.getOpt())) {
        outputFormat = commandLine.getOptionValue(OPTION_OUTPUT_FORMAT.getOpt());
    }

    int port = DEFAULT_OFFICE_PORT;
    if (commandLine.hasOption(OPTION_PORT.getOpt())) {
        port = Integer.parseInt(commandLine.getOptionValue(OPTION_PORT.getOpt()));
    }

    String[] fileNames = commandLine.getArgs();
    if ((outputFormat == null && fileNames.length != 2) || fileNames.length < 1) {
        String syntax = "java -jar jodconverter-core.jar [options] input-file output-file\n"
                + "or [options] -o output-format input-file [input-file...]";
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(syntax, OPTIONS);
        System.exit(STATUS_INVALID_ARGUMENTS);
    }

    DocumentFormatRegistry registry;
    if (commandLine.hasOption(OPTION_REGISTRY.getOpt())) {
        File registryFile = new File(commandLine.getOptionValue(OPTION_REGISTRY.getOpt()));
        registry = new JsonDocumentFormatRegistry(FileUtils.readFileToString(registryFile));
    } else {
        registry = new DefaultDocumentFormatRegistry();
    }

    DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
    configuration.setPortNumber(port);
    if (commandLine.hasOption(OPTION_TIMEOUT.getOpt())) {
        int timeout = Integer.parseInt(commandLine.getOptionValue(OPTION_TIMEOUT.getOpt()));
        configuration.setTaskExecutionTimeout(timeout * 1000);
    }
    if (commandLine.hasOption(OPTION_USER_PROFILE.getOpt())) {
        String templateProfileDir = commandLine.getOptionValue(OPTION_USER_PROFILE.getOpt());
        configuration.setTemplateProfileDir(new File(templateProfileDir));
    }

    OfficeManager officeManager = configuration.buildOfficeManager();
    officeManager.start();
    OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager, registry);
    try {
        if (outputFormat == null) {
            File inputFile = new File(fileNames[0]);
            File outputFile = new File(fileNames[1]);
            converter.convert(inputFile, outputFile);
        } else {
            for (int i = 0; i < fileNames.length; i++) {
                File inputFile = new File(fileNames[i]);
                String outputName = FilenameUtils.getBaseName(fileNames[i]) + "." + outputFormat;
                File outputFile = new File(FilenameUtils.getFullPath(fileNames[i]) + outputName);
                converter.convert(inputFile, outputFile);
            }
        }
    } finally {
        officeManager.stop();
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.LuceneIndexer.java

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

    options.addOption(CommonParams.ROOT_DIR_PARAM, null, true, CommonParams.ROOT_DIR_DESC);
    options.addOption(CommonParams.SUB_DIR_TYPE_PARAM, null, true, CommonParams.SUB_DIR_TYPE_DESC);
    options.addOption(CommonParams.MAX_NUM_REC_PARAM, null, true, CommonParams.MAX_NUM_REC_DESC);
    options.addOption(CommonParams.SOLR_FILE_NAME_PARAM, null, true, CommonParams.SOLR_FILE_NAME_DESC);
    options.addOption(CommonParams.OUT_INDEX_PARAM, null, true, CommonParams.OUT_MINDEX_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {/*from w w w .  j  a  v  a2  s . com*/
        CommandLine cmd = parser.parse(options, args);

        String rootDir = null;

        rootDir = cmd.getOptionValue(CommonParams.ROOT_DIR_PARAM);

        if (null == rootDir)
            Usage("Specify: " + CommonParams.ROOT_DIR_DESC, options);

        String outputDirName = cmd.getOptionValue(CommonParams.OUT_INDEX_PARAM);

        if (null == outputDirName)
            Usage("Specify: " + CommonParams.OUT_MINDEX_DESC, options);

        String subDirTypeList = cmd.getOptionValue(CommonParams.SUB_DIR_TYPE_PARAM);

        if (null == subDirTypeList || subDirTypeList.isEmpty())
            Usage("Specify: " + CommonParams.SUB_DIR_TYPE_DESC, options);

        String solrFileName = cmd.getOptionValue(CommonParams.SOLR_FILE_NAME_PARAM);
        if (null == solrFileName)
            Usage("Specify: " + CommonParams.SOLR_FILE_NAME_DESC, options);

        int maxNumRec = Integer.MAX_VALUE;

        String tmp = cmd.getOptionValue(CommonParams.MAX_NUM_REC_PARAM);

        if (tmp != null) {
            try {
                maxNumRec = Integer.parseInt(tmp);
                if (maxNumRec <= 0) {
                    Usage("The maximum number of records should be a positive integer", options);
                }
            } catch (NumberFormatException e) {
                Usage("The maximum number of records should be a positive integer", options);
            }
        }

        File outputDir = new File(outputDirName);
        if (!outputDir.exists()) {
            if (!outputDir.mkdirs()) {
                System.out.println("couldn't create " + outputDir.getAbsolutePath());
                System.exit(1);
            }
        }
        if (!outputDir.isDirectory()) {
            System.out.println(outputDir.getAbsolutePath() + " is not a directory!");
            System.exit(1);
        }
        if (!outputDir.canWrite()) {
            System.out.println("Can't write to " + outputDir.getAbsolutePath());
            System.exit(1);
        }

        String subDirs[] = subDirTypeList.split(",");

        int docNum = 0;

        // No English analyzer here, all language-related processing is done already,
        // here we simply white-space tokenize and index tokens verbatim.
        Analyzer analyzer = new WhitespaceAnalyzer();
        FSDirectory indexDir = FSDirectory.open(outputDir);
        IndexWriterConfig indexConf = new IndexWriterConfig(analyzer.getVersion(), analyzer);

        System.out.println("Creating a new Lucene index, maximum # of docs to process: " + maxNumRec);
        indexConf.setOpenMode(OpenMode.CREATE);
        IndexWriter indexWriter = new IndexWriter(indexDir, indexConf);

        for (int subDirId = 0; subDirId < subDirs.length && docNum < maxNumRec; ++subDirId) {
            String inputFileName = rootDir + "/" + subDirs[subDirId] + "/" + solrFileName;

            System.out.println("Input file name: " + inputFileName);

            BufferedReader inpText = new BufferedReader(
                    new InputStreamReader(CompressUtils.createInputStream(inputFileName)));
            String docText = XmlHelper.readNextXMLIndexEntry(inpText);

            for (; docText != null && docNum < maxNumRec; docText = XmlHelper.readNextXMLIndexEntry(inpText)) {
                ++docNum;
                Map<String, String> docFields = null;

                Document luceneDoc = new Document();

                try {
                    docFields = XmlHelper.parseXMLIndexEntry(docText);
                } catch (Exception e) {
                    System.err.println(String.format("Parsing error, offending DOC #%d:\n%s", docNum, docText));
                    System.exit(1);
                }

                String id = docFields.get(UtilConst.TAG_DOCNO);

                if (id == null) {
                    System.err.println(String.format("No ID tag '%s', offending DOC #%d:\n%s",
                            UtilConst.TAG_DOCNO, docNum, docText));
                }

                luceneDoc.add(new StringField(UtilConst.TAG_DOCNO, id, Field.Store.YES));

                for (Map.Entry<String, String> e : docFields.entrySet())
                    if (!e.getKey().equals(UtilConst.TAG_DOCNO)) {
                        luceneDoc.add(new TextField(e.getKey(), e.getValue(), Field.Store.YES));
                    }
                indexWriter.addDocument(luceneDoc);
                if (docNum % 1000 == 0)
                    System.out.println("Indexed " + docNum + " docs");
            }
            System.out.println("Indexed " + docNum + " docs");
        }

        indexWriter.commit();
        indexWriter.close();

    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

From source file:za.co.taung.httpdotserver.main.HttpDotServer.java

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

    LOG.info("Initialise server");

    // The parameter is the Port to listen on. Default is 8080. 
    int port = 8080;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }/*from w  w  w .j a  va2  s . c om*/

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

    // Set up request handler. This is the method that generates SVG. 
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new Dot2SVGHandler());

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

    // Set up SSL if listening on 8443 for https.
    SSLServerSocketFactory serverSocketFactory = null;
    if (port == 8443) {
        // Get the location of the keystore secrets.
        ClassLoader cl = HttpDotServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            LOG.error("Keystore not found");
            System.exit(1);
        }
        // Load the secret into a keystore and manage the key material.
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        // Prepare the socket factory for use by the RequestListenerThread.
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        serverSocketFactory = sslcontext.getServerSocketFactory();
    }

    LOG.debug("Start the RequestListenerThread");
    Thread thread = new RequestListenerThread(port, httpService, serverSocketFactory);
    thread.setDaemon(false);
    thread.start();
}