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.l2jfree.loginserver.tools.L2GameServerRegistrar.java

/**
 * Launches the interactive game server registration.
 * //  w  w w  .  ja  v a 2 s .  c  o m
 * @param args ignored
 */
public static void main(String[] args) {
    // LOW rework this crap
    Util.printSection("Game Server Registration");
    _log.info("Please choose:");
    _log.info("list - list registered game servers");
    _log.info("reg - register a game server");
    _log.info("rem - remove a registered game server");
    _log.info("hexid - generate a legacy hexid file");
    _log.info("quit - exit this application");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    L2GameServerRegistrar reg = new L2GameServerRegistrar();

    String line;
    try {
        RegistrationState next = RegistrationState.INITIAL_CHOICE;
        while ((line = br.readLine()) != null) {
            line = line.trim().toLowerCase();
            switch (reg.getState()) {
            case GAMESERVER_ID:
                try {
                    int id = Integer.parseInt(line);
                    if (id < 1 || id > 127)
                        throw new IllegalArgumentException("ID must be in [1;127].");
                    reg.setId(id);
                    reg.setState(next);
                } catch (RuntimeException e) {
                    _log.info("You must input a number between 1 and 127");
                }

                if (reg.getState() == RegistrationState.ALLOW_BANS) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con
                                .prepareStatement("SELECT allowBans FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        ResultSet rs = ps.executeQuery();
                        if (rs.next()) {
                            _log.info("A game server is already registered on ID " + reg.getId());
                            reg.setState(RegistrationState.INITIAL_CHOICE);
                        } else
                            _log.info("Allow account bans from this game server? [y/n]:");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not remove a game server!", e);
                    } finally {
                        L2Database.close(con);
                    }
                } else if (reg.getState() == RegistrationState.REMOVE) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement("DELETE FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        int cnt = ps.executeUpdate();
                        if (cnt == 0)
                            _log.info("No game server registered on ID " + reg.getId());
                        else
                            _log.info("Game server removed.");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not remove a game server!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } else if (reg.getState() == RegistrationState.GENERATE) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con
                                .prepareStatement("SELECT authData FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        ResultSet rs = ps.executeQuery();

                        if (rs.next()) {
                            reg.setAuth(rs.getString("authData"));
                            byte[] b = HexUtil.hexStringToBytes(reg.getAuth());

                            Properties pro = new Properties();
                            pro.setProperty("ServerID", String.valueOf(reg.getId()));
                            pro.setProperty("HexID", HexUtil.hexToString(b));

                            BufferedOutputStream os = new BufferedOutputStream(
                                    new FileOutputStream("hexid.txt"));
                            pro.store(os, "the hexID to auth into login");
                            IOUtils.closeQuietly(os);
                            _log.info("hexid.txt has been generated.");
                        } else
                            _log.info("No game server registered on ID " + reg.getId());

                        rs.close();
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not generate hexid.txt!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                }
                break;
            case ALLOW_BANS:
                try {
                    if (line.length() != 1)
                        throw new IllegalArgumentException("One char required.");
                    else if (line.charAt(0) == 'y')
                        reg.setTrusted(true);
                    else if (line.charAt(0) == 'n')
                        reg.setTrusted(false);
                    else
                        throw new IllegalArgumentException("Invalid choice.");

                    byte[] auth = Rnd.nextBytes(new byte[BYTES]);
                    reg.setAuth(HexUtil.bytesToHexString(auth));

                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement(
                                "INSERT INTO gameserver (id, authData, allowBans) VALUES (?, ?, ?)");
                        ps.setInt(1, reg.getId());
                        ps.setString(2, reg.getAuth());
                        ps.setBoolean(3, reg.isTrusted());
                        ps.executeUpdate();
                        ps.close();

                        _log.info("Registered game server on ID " + reg.getId());
                        _log.info("The authorization string is:");
                        _log.info(reg.getAuth());
                        _log.info("Use it when registering this login server.");
                        _log.info("If you need a legacy hexid file, use the 'hexid' command.");
                    } catch (SQLException e) {
                        _log.error("Could not register gameserver!", e);
                    } finally {
                        L2Database.close(con);
                    }

                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } catch (IllegalArgumentException e) {
                    _log.info("[y/n]?");
                }
                break;
            default:
                if (line.equals("list")) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement("SELECT id, allowBans FROM gameserver");
                        ResultSet rs = ps.executeQuery();
                        while (rs.next())
                            _log.info("ID: " + rs.getInt("id") + ", trusted: " + rs.getBoolean("allowBans"));
                        rs.close();
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not register gameserver!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } else if (line.equals("reg")) {
                    _log.info("Enter the desired ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.ALLOW_BANS;
                } else if (line.equals("rem")) {
                    _log.info("Enter game server ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.REMOVE;
                } else if (line.equals("hexid")) {
                    _log.info("Enter game server ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.GENERATE;
                } else if (line.equals("quit"))
                    Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN);
                else
                    _log.info("Incorrect command.");
                break;
            }
        }
    } catch (IOException e) {
        _log.fatal("Could not process input!", e);
    } finally {
        IOUtils.closeQuietly(br);
    }
}

From source file:com.alibaba.rocketmq.example.operation.Producer.java

public static void main(String[] args) throws MQClientException, InterruptedException {
    CommandLine commandLine = buildCommandline(args);
    if (commandLine != null) {
        String group = commandLine.getOptionValue('g');
        String topic = commandLine.getOptionValue('t');
        String tags = commandLine.getOptionValue('a');
        String keys = commandLine.getOptionValue('k');
        String msgCount = commandLine.getOptionValue('c');

        DefaultMQProducer producer = new DefaultMQProducer(group);
        producer.setInstanceName(Long.toString(System.currentTimeMillis()));

        producer.start();/* ww  w  .j  a  v a2s  . c  o m*/

        for (int i = 0; i < Integer.parseInt(msgCount); i++) {
            try {
                Message msg = new Message(//
                        topic, // topic
                        tags, // tag
                        keys, // key
                        ("Hello RocketMQ " + i).getBytes());// body
                SendResult sendResult = producer.send(msg);

                System.out.printf("%-8d %s\n", i, sendResult);
            } catch (Exception e) {
                e.printStackTrace();
                Thread.sleep(1000);
            }
        }

        producer.shutdown();
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.BuildInMemFwdIndexApp.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);
    options.addOption(EXCLUDE_FIELDS_PARAM, null, true, EXCLUDE_FIELDS_DESC);

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

    try {/* w  w w  . j  a va  2  s  .  c o m*/
        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 outPrefix = cmd.getOptionValue(CommonParams.OUT_INDEX_PARAM);

        if (null == outPrefix)
            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);
            }
        }

        String[] exclFields = new String[0];
        tmp = cmd.getOptionValue(EXCLUDE_FIELDS_PARAM);
        if (null != tmp) {
            exclFields = tmp.split(",");
        }

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

        for (int k = 0; k < FeatureExtractor.mFieldNames.length; ++k) {
            String field = FeatureExtractor.mFieldsSOLR[k];
            String fieldName = FeatureExtractor.mFieldNames[k];

            boolean bOk = !StringUtilsLeo.isInArrayNoCase(fieldName, exclFields);

            if (bOk)
                System.out.println("Processing field: " + field);
            else {
                System.out.println("Skipping field: " + field);
                continue;
            }

            String[] fileNames = new String[subDirs.length];
            for (int i = 0; i < fileNames.length; ++i)
                fileNames[i] = rootDir + "/" + subDirs[i] + "/" + solrFileName;

            InMemForwardIndex indx = new InMemForwardIndex(field, fileNames, maxNumRec);

            indx.save(InMemIndexFeatureExtractor.indexFileName(outPrefix, fieldName));
        }

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

From source file:DIA_Umpire_To_Skyline.DIA_Umpire_To_Skyline.java

/**
 * @param args the command line arguments
 *///from w  ww.  j  av a 2 s . c  om
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println("DIA-Umpire_To_Skyline (version: " + UmpireInfo.GetInstance().Version + ")");
    if (args.length < 1) {
        System.out.println(
                "command format error, it should be like: java -jar -Xmx20G DIA_Umpire_To_Skyline.jar Path NoThreads");
        System.out.println("command : java -jar -Xmx20G DIA_Umpire_To_Skyline.jar Path [Option]\n");
        System.out.println("\nOptions");
        System.out.println("\t-t\tNo. of threads, Ex: -t4 (using four threads, default value)");
        System.out.println(
                "\t-cP\tPath of msconvert.exe for mzXML conversion, Ex: -cP (using four threads, default value)");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.DEBUG);
        ConsoleLogger.SetFileLogger(Level.DEBUG,
                FilenameUtils.getFullPath(args[0]) + "diaumpire_to_skyline.log");
    } catch (Exception e) {
        System.out.println("Logger initialization failed");
    }

    Logger.getRootLogger().info("Path:" + args[0]);
    String msconvertpath = "C:/inetpub/tpp-bin/msconvert";

    String WorkFolder = args[0];
    int NoCPUs = 4;

    for (int i = 1; i < args.length; i++) {
        if (args[i].startsWith("-")) {
            if (args[i].startsWith("-cP")) {
                msconvertpath = args[i].substring(3);
                Logger.getRootLogger().info("MSConvert path: " + msconvertpath);
            }
            if (args[i].startsWith("-t")) {
                NoCPUs = Integer.parseInt(args[i].substring(2));
                Logger.getRootLogger().info("No. of threads: " + NoCPUs);
            }
        }
    }

    HashMap<String, File> AssignFiles = new HashMap<>();

    try {
        File folder = new File(WorkFolder);
        if (!folder.exists()) {
            Logger.getRootLogger().info("Path: " + folder.getAbsolutePath() + " cannot be found.");
        }
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isFile() && fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
            }
            if (fileEntry.isDirectory()) {
                for (final File fileEntry2 : fileEntry.listFiles()) {
                    if (fileEntry2.isFile() && fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                        AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                    }
                }
            }
        }

        Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
        for (File fileEntry : AssignFiles.values()) {
            Logger.getRootLogger().info(fileEntry.getAbsolutePath());
        }

        ExecutorService executorPool = null;
        executorPool = Executors.newFixedThreadPool(3);

        for (File fileEntry : AssignFiles.values()) {
            String mzXMLFile = fileEntry.getAbsolutePath();
            FileThread thread = new FileThread(mzXMLFile, NoCPUs, msconvertpath);
            executorPool.execute(thread);
        }
        executorPool.shutdown();
        try {
            executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            Logger.getRootLogger().info("interrupted..");
        }
    } catch (Exception e) {
        Logger.getRootLogger().error(e.getMessage());
        throw e;
    }
    Logger.getRootLogger().info("Job done");
    Logger.getRootLogger().info(
            "=================================================================================================");

}

From source file:fr.inria.edelweiss.kgdqp.core.FedQueryingCLI.java

@SuppressWarnings("unchecked")
public static void main(String args[]) throws ParseException, EngineException {

    List<String> endpoints = new ArrayList<String>();
    String queryPath = null;/*from  ww  w.j av a2 s .  c  o m*/
    int slice = -1;

    Options options = new Options();
    Option helpOpt = new Option("h", "help", false, "print this message");
    Option queryOpt = new Option("q", "query", true, "specify the sparql query file");
    Option endpointOpt = new Option("e", "endpoints", true, "the list of federated sparql endpoint URLs");
    Option groupingOpt = new Option("g", "grouping", true, "triple pattern optimisation");
    Option slicingOpt = new Option("s", "slicing", true, "size of the slicing parameter");
    Option versionOpt = new Option("v", "version", false, "print the version information and exit");
    options.addOption(queryOpt);
    options.addOption(endpointOpt);
    options.addOption(helpOpt);
    options.addOption(versionOpt);
    options.addOption(groupingOpt);
    options.addOption(slicingOpt);

    String header = "Corese/KGRAM DQP command line interface";
    String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr";

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("kgdqp", header, options, footer, true);
        System.exit(0);
    }
    if (!cmd.hasOption("e")) {
        logger.info("You must specify at least the URL of one sparql endpoint !");
        System.exit(0);
    } else {
        endpoints = new ArrayList<String>(Arrays.asList(cmd.getOptionValues("e")));
    }
    if (!cmd.hasOption("q")) {
        logger.info("You must specify a path for a sparql query !");
        System.exit(0);
    } else {
        queryPath = cmd.getOptionValue("q");
    }
    if (cmd.hasOption("s")) {
        try {
            slice = Integer.parseInt(cmd.getOptionValue("s"));
        } catch (NumberFormatException ex) {
            logger.warn(cmd.getOptionValue("s") + " is not formatted as number for the slicing parameter");
            logger.warn("Slicing disabled");
        }
    }
    if (cmd.hasOption("v")) {
        logger.info("version 3.0.4-SNAPSHOT");
        System.exit(0);
    }

    /////////////////
    Graph graph = Graph.create();
    QueryProcessDQP exec = QueryProcessDQP.create(graph);
    exec.setGroupingEnabled(cmd.hasOption("g"));
    if (slice > 0) {
        exec.setSlice(slice);
    }
    Provider sProv = ProviderImplCostMonitoring.create();
    exec.set(sProv);

    for (String url : endpoints) {
        try {
            exec.addRemote(new URL(url), WSImplem.REST);
        } catch (MalformedURLException ex) {
            logger.error(url + " is not a well-formed URL");
            System.exit(1);
        }
    }

    StringBuffer fileData = new StringBuffer(1000);
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(queryPath));
    } catch (FileNotFoundException ex) {
        logger.error("Query file " + queryPath + " not found !");
        System.exit(1);
    }
    char[] buf = new char[1024];
    int numRead = 0;
    try {
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();
    } catch (IOException ex) {
        logger.error("Error while reading query file " + queryPath);
        System.exit(1);
    }

    String sparqlQuery = fileData.toString();

    //        Query q = exec.compile(sparqlQuery, null);
    //        System.out.println(q);

    StopWatch sw = new StopWatch();
    sw.start();
    Mappings map = exec.query(sparqlQuery);
    int dqpSize = map.size();
    System.out.println("--------");
    long time = sw.getTime();
    System.out.println(time + " " + dqpSize);
}

From source file:io.s4.MainApp.java

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

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(//from   ww w . j  av  a  2 s . co m
            OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a"));

    options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d"));

    options.addOption(OptionBuilder.withArgName("seedtime").hasArg()
            .withDescription("event clock initialization time").create("s"));

    options.addOption(
            OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e"));

    options.addOption(
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;
    String clockType = "wall";

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    if (commandLine.hasOption("a")) {
        appsHome = commandLine.getOptionValue("a");
    }

    if (commandLine.hasOption("d")) {
        clockType = commandLine.getOptionValue("d");
    }

    if (commandLine.hasOption("e")) {
        extsHome = commandLine.getOptionValue("e");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    long seedTime = 0;
    if (commandLine.hasOption("s")) {
        seedTime = Long.parseLong(commandLine.getOptionValue("s"));
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    File appsHomeFile = new File(appsHome);
    if (!appsHomeFile.isDirectory()) {
        System.err.println("Bad applications home: " + appsHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    List loArgs = commandLine.getArgList();

    if (loArgs.size() < 1) {
        // System.err.println("No bean configuration file specified");
        // System.exit(1);
    }

    // String s4ConfigXml = (String) loArgs.get(0);
    // System.out.println("s4ConfigXml is " + s4ConfigXml);

    ClassPathResource propResource = new ClassPathResource("s4-core.properties");
    Properties prop = new Properties();
    if (propResource.exists()) {
        prop.load(propResource.getInputStream());
    } else {
        System.err.println("Unable to find s4-core.properties. It must be available in classpath");
        System.exit(1);
    }

    ApplicationContext coreContext = null;
    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = "";
    List<String> coreConfigUrls = new ArrayList<String>();
    File configFile = null;

    // load clock configuration
    configPath = configBase + File.separatorChar + clockType + "-clock.xml";
    coreConfigUrls.add(configPath);

    // load core config xml
    configPath = configBase + File.separatorChar + "s4-core-conf.xml";
    configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("S4 core config file %s does not exist\n", configPath);
        System.exit(1);
    }

    coreConfigUrls.add(configPath);
    String[] coreConfigFiles = new String[coreConfigUrls.size()];
    coreConfigUrls.toArray(coreConfigFiles);

    String[] coreConfigFileUrls = new String[coreConfigFiles.length];
    for (int i = 0; i < coreConfigFiles.length; i++) {
        coreConfigFileUrls[i] = "file:" + coreConfigFiles[i];
    }

    coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext);
    ApplicationContext context = coreContext;

    Clock s4Clock = (Clock) context.getBean("clock");
    if (s4Clock instanceof EventClock && seedTime > 0) {
        EventClock s4EventClock = (EventClock) s4Clock;
        s4EventClock.updateTime(seedTime);
        System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime());
    }

    PEContainer peContainer = (PEContainer) context.getBean("peContainer");

    Watcher w = (Watcher) context.getBean("watcher");
    w.setConfigFilename(configPath);

    // load extension modules
    String[] configFileNames = getModuleConfigFiles(extsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
    }

    // load application modules
    configFileNames = getModuleConfigFiles(appsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
        // attach any beans that implement ProcessingElement to the PE
        // Container
        String[] processingElementBeanNames = context.getBeanNamesForType(ProcessingElement.class);
        for (String processingElementBeanName : processingElementBeanNames) {
            Object bean = context.getBean(processingElementBeanName);
            try {
                Method getS4ClockMethod = bean.getClass().getMethod("getS4Clock");

                if (getS4ClockMethod.getReturnType().equals(Clock.class)) {
                    if (getS4ClockMethod.invoke(bean) == null) {
                        Method setS4ClockMethod = bean.getClass().getMethod("setS4Clock", Clock.class);
                        setS4ClockMethod.invoke(bean, coreContext.getBean("clock"));
                    }
                }
            } catch (NoSuchMethodException mnfe) {
                // acceptable
            }
            System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id "
                    + ((ProcessingElement) bean).getId());
            peContainer.addProcessor((ProcessingElement) bean, processingElementBeanName);
        }
    }
}

From source file:cc.wikitools.lucene.SearchWikipedia.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(/*from w  ww  . java2 s .c  o m*/
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));

    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));
    options.addOption(new Option(TITLE_OPTION, "search title"));
    options.addOption(new Option(ARTICLE_OPTION, "search article"));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(QUERY_OPTION) || !cmdline.hasOption(INDEX_OPTION)
            || !cmdline.hasOption(QUERY_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(SearchWikipedia.class.getName(), options);
        System.exit(-1);
    }

    File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION));
    if (!indexLocation.exists()) {
        System.err.println("Error: " + indexLocation + " does not exist!");
        System.exit(-1);
    }

    String queryText = cmdline.getOptionValue(QUERY_OPTION);
    int numResults = cmdline.hasOption(NUM_RESULTS_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION))
            : DEFAULT_NUM_RESULTS;
    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);
    boolean searchArticle = !cmdline.hasOption(TITLE_OPTION);

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    WikipediaSearcher searcher = new WikipediaSearcher(indexLocation);
    TopDocs rs = null;
    if (searchArticle) {
        rs = searcher.searchArticle(queryText, numResults);
    } else {
        rs = searcher.searchTitle(queryText, numResults);
    }

    int i = 1;
    for (ScoreDoc scoreDoc : rs.scoreDocs) {
        Document hit = searcher.doc(scoreDoc.doc);

        out.println(String.format("%d. %s (wiki id = %s, lucene id = %d) %f", i,
                hit.getField(IndexField.TITLE.name).stringValue(),
                hit.getField(IndexField.ID.name).stringValue(), scoreDoc.doc, scoreDoc.score));
        if (verbose) {
            out.println("# " + hit.toString().replaceAll("[\\n\\r]+", " "));
        }
        i++;
    }

    searcher.close();
    out.close();
}

From source file:com.emc.ecs.sync.EcsSync.java

public static void main(String[] args) {
    int exitCode = 0;

    System.out.println(versionLine());

    RestServer restServer = null;/*  www . java2s  . c  o  m*/
    try {

        // first, hush up the JDK logger (why does this default to INFO??)
        java.util.logging.LogManager.getLogManager().getLogger("").setLevel(java.util.logging.Level.WARNING);

        CliConfig cliConfig = CliHelper.parseCliConfig(args);

        if (cliConfig != null) {

            // configure logging for startup
            if (cliConfig.getLogLevel() != null)
                SyncJobService.getInstance().setLogLevel(cliConfig.getLogLevel());

            // start REST service
            if (cliConfig.isRestEnabled()) {
                if (cliConfig.getRestEndpoint() != null) {
                    String[] endpoint = cliConfig.getRestEndpoint().split(":");
                    restServer = new RestServer(endpoint[0], Integer.parseInt(endpoint[1]));
                } else {
                    restServer = new RestServer();
                    restServer.setAutoPortEnabled(true);
                }
                // set DB connect string if provided
                if (cliConfig.getDbConnectString() != null) {
                    SyncJobService.getInstance().setDbConnectString(cliConfig.getDbConnectString());
                }
                restServer.start();
            }

            // if REST-only, skip remaining logic (REST server thread will keep the VM running)
            if (cliConfig.isRestOnly())
                return;

            try {
                // determine sync config
                SyncConfig syncConfig;
                if (cliConfig.getXmlConfig() != null) {
                    syncConfig = loadXmlFile(new File(cliConfig.getXmlConfig()));
                } else {
                    syncConfig = CliHelper.parseSyncConfig(cliConfig, args);
                }

                // create the sync instance
                final EcsSync sync = new EcsSync();
                sync.setSyncConfig(syncConfig);

                // register for REST access
                SyncJobService.getInstance().registerJob(sync);

                // start sync job (this blocks until the sync is complete)
                sync.run();

                // print completion stats
                System.out.print(sync.getStats().getStatsString());
                if (sync.getStats().getObjectsFailed() > 0)
                    exitCode = 3;
            } finally {
                if (restServer != null)
                    try {
                        restServer.stop(0);
                    } catch (Throwable t) {
                        log.warn("could not stop REST service", t);
                    }
            }
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.out.println("    use --help for a detailed (quite long) list of options");
        exitCode = 1;
    } catch (Throwable t) {
        t.printStackTrace();
        exitCode = 2;
    }

    System.exit(exitCode);
}

From source file:examples.mail.IMAPImportMbox.java

public static void main(String[] args) throws IOException {
    if (args.length < 2) {
        System.err.println(//from w  w w . ja  v a 2 s.  c  o  m
                "Usage: IMAPImportMbox imap[s]://user:password@host[:port]/folder/path <mboxfile> [selectors]");
        System.err.println("\tWhere: a selector is a list of numbers/number ranges - 1,2,3-10"
                + " - or a list of strings to match in the initial From line");
        System.exit(1);
    }

    final URI uri = URI.create(args[0]);
    final String file = args[1];

    final File mbox = new File(file);
    if (!mbox.isFile() || !mbox.canRead()) {
        throw new IOException("Cannot read mailbox file: " + mbox);
    }

    String path = uri.getPath();
    if (path == null || path.length() < 1) {
        throw new IllegalArgumentException("Invalid folderPath: '" + path + "'");
    }
    String folder = path.substring(1); // skip the leading /

    List<String> contains = new ArrayList<String>(); // list of strings to find
    BitSet msgNums = new BitSet(); // list of message numbers

    for (int i = 2; i < args.length; i++) {
        String arg = args[i];
        if (arg.matches("\\d+(-\\d+)?(,\\d+(-\\d+)?)*")) { // number,m-n
            for (String entry : arg.split(",")) {
                String[] parts = entry.split("-");
                if (parts.length == 2) { // m-n
                    int low = Integer.parseInt(parts[0]);
                    int high = Integer.parseInt(parts[1]);
                    for (int j = low; j <= high; j++) {
                        msgNums.set(j);
                    }
                } else {
                    msgNums.set(Integer.parseInt(entry));
                }
            }
        } else {
            contains.add(arg); // not a number/number range
        }
    }
    //        System.out.println(msgNums.toString());
    //        System.out.println(java.util.Arrays.toString(contains.toArray()));

    // Connect and login
    final IMAPClient imap = IMAPUtils.imapLogin(uri, 10000, null);

    int total = 0;
    int loaded = 0;
    try {
        imap.setSoTimeout(6000);

        final BufferedReader br = new BufferedReader(new FileReader(file)); // TODO charset?

        String line;
        StringBuilder sb = new StringBuilder();
        boolean wanted = false; // Skip any leading rubbish
        while ((line = br.readLine()) != null) {
            if (line.startsWith("From ")) { // start of message; i.e. end of previous (if any)
                if (process(sb, imap, folder, total)) { // process previous message (if any)
                    loaded++;
                }
                sb.setLength(0);
                total++;
                wanted = wanted(total, line, msgNums, contains);
            } else if (startsWith(line, PATFROM)) { // Unescape ">+From " in body text
                line = line.substring(1);
            }
            // TODO process first Received: line to determine arrival date?
            if (wanted) {
                sb.append(line);
                sb.append(CRLF);
            }
        }
        br.close();
        if (wanted && process(sb, imap, folder, total)) { // last message (if any)
            loaded++;
        }
    } catch (IOException e) {
        System.out.println(imap.getReplyString());
        e.printStackTrace();
        System.exit(10);
        return;
    } finally {
        imap.logout();
        imap.disconnect();
    }
    System.out.println("Processed " + total + " messages, loaded " + loaded);
}

From source file:es.upm.oeg.tools.quality.ldsniffer.cmd.LDSnifferApp.java

public static void main(String[] args) {

    HelpFormatter help = new HelpFormatter();
    String header = "Assess a list of Linked Data resources using Linked Data Quality Model.";
    String footer = "Please report issues at https://github.com/nandana/ld-sniffer";

    try {/*from   w ww. j  a v  a  2  s .  c o m*/
        CommandLine line = parseArguments(args);
        if (line.hasOption("help")) {
            help.printHelp("LDSnifferApp", header, OPTIONS, footer, true);
            System.exit(0);
        }

        evaluationTimeout = Integer.parseInt(line.getOptionValue("t", "10"));

        if (line.hasOption("md")) {
            includeMetricDefinitions = true;
        }
        if (line.hasOption("rdf")) {
            rdfOutput = true;
        }

        logger.info("URL List: " + line.getOptionValue("ul"));
        logger.info("TDB Path: " + line.getOptionValue("tdb"));
        logger.info("Metrics Path: " + line.getOptionValue("ml"));
        logger.info("Include Metric definitions: " + line.getOptionValue("ml"));
        logger.info("RDF output: " + line.getOptionValue("rdf"));
        logger.info("Timeout (mins): " + evaluationTimeout);

        if (line.hasOption("ml")) {
            Path path = Paths.get(line.getOptionValue("ml"));
            if (!Files.exists(path)) {
                throw new IOException(path.toAbsolutePath().toString() + " : File doesn't exit.");
            }
        }

        //Set the TDB path
        String tdbDirectory;
        if (line.hasOption("tdb")) {
            tdbDirectory = line.getOptionValue("tdb");
        } else {
            Path tempPath = Files.createTempDirectory("tdb_");
            tdbDirectory = tempPath.toAbsolutePath().toString();
        }

        // Create the URL list for the evaluation
        if (!line.hasOption("ul") && !line.hasOption("url")) {
            System.out.println("One of the following parameters are required: url or urlList ");
            help.printHelp("LDSnifferApp", header, OPTIONS, footer, true);
            System.exit(0);
        } else if (line.hasOption("ul") && line.hasOption("url")) {
            System.out.println("You have to specify either url or urlList, not both.");
            help.printHelp("LDSnifferApp", header, OPTIONS, footer, true);
            System.exit(0);
        }

        List<String> urlList = null;
        if (line.hasOption("ul")) {
            Path path = Paths.get(line.getOptionValue("ul"));
            logger.info("Path : " + path.toAbsolutePath().toString());
            logger.info("Path exits : " + Files.exists(path));
            urlList = Files.readAllLines(path, Charset.defaultCharset());
        } else if (line.hasOption("url")) {
            urlList = new ArrayList<>();
            urlList.add(line.getOptionValue("url"));
        }

        Executor executor = new Executor(tdbDirectory, urlList);
        executor.execute();

    } catch (MissingOptionException e) {
        help.printHelp("LDSnifferApp", header, OPTIONS, footer, true);
        logger.error("Missing arguments.  Reason: " + e.getMessage(), e);
        System.exit(1);
    } catch (ParseException e) {
        logger.error("Parsing failed.  Reason: " + e.getMessage(), e);
        System.exit(1);
    } catch (IOException e) {
        logger.error("Execution failed.  Reason: " + e.getMessage(), e);
        System.exit(1);
    }

}