Example usage for java.lang String substring

List of usage examples for java.lang String substring

Introduction

In this page you can find the example usage for java.lang String substring.

Prototype

public String substring(int beginIndex) 

Source Link

Document

Returns a string that is a substring of this string.

Usage

From source file:com.cedarsoft.serialization.SplittingPerformanceRunner.java

public static void main(String[] args) throws Exception {
    final String uri = "http://www.cedarsoft.com/some/slashes/1.0.0";

    run("String.plit", new Callable<String>() {
        @Override/*w w w.  j a  va2 s .c  o  m*/
        public String call() throws Exception {
            String[] parts = uri.split("/");
            return parts[parts.length - 1];
        }
    });

    run("Splitter", new Callable<String>() {
        @Override
        public String call() throws Exception {
            Splitter splitter = Splitter.on("/");
            Iterable<String> parts = splitter.split(uri);

            Iterator<String> iterator = parts.iterator();
            while (true) {
                String current = iterator.next();
                if (!iterator.hasNext()) {
                    return current;
                }
            }
        }
    });

    run("static Splitter", new Callable<String>() {
        @Override
        public String call() throws Exception {
            Iterable<String> parts = SPLITTER.split(uri);

            Iterator<String> iterator = parts.iterator();
            while (true) {
                String current = iterator.next();
                if (!iterator.hasNext()) {
                    return current;
                }
            }
        }
    });

    run("indexOf", new Callable<String>() {
        @Override
        public String call() throws Exception {
            int index = uri.lastIndexOf("/");
            return uri.substring(index + 1);
        }
    });
}

From source file:examples.mail.IMAPExportMbox.java

public static void main(String[] args) throws IOException {
    int connect_timeout = CONNECT_TIMEOUT;
    int read_timeout = READ_TIMEOUT;

    int argIdx = 0;
    String eol = EOL_DEFAULT;//from  ww w.ja  v a  2  s.c  o  m
    boolean printHash = false;
    boolean printMarker = false;
    int retryWaitSecs = 0;

    for (argIdx = 0; argIdx < args.length; argIdx++) {
        if (args[argIdx].equals("-c")) {
            connect_timeout = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-r")) {
            read_timeout = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-R")) {
            retryWaitSecs = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-LF")) {
            eol = LF;
        } else if (args[argIdx].equals("-CRLF")) {
            eol = CRLF;
        } else if (args[argIdx].equals("-.")) {
            printHash = true;
        } else if (args[argIdx].equals("-X")) {
            printMarker = true;
        } else {
            break;
        }
    }

    final int argCount = args.length - argIdx;

    if (argCount < 2) {
        System.err.println("Usage: IMAPExportMbox [-LF|-CRLF] [-c n] [-r n] [-R n] [-.] [-X]"
                + " imap[s]://user:password@host[:port]/folder/path [+|-]<mboxfile> [sequence-set] [itemnames]");
        System.err.println(
                "\t-LF | -CRLF set end-of-line to LF or CRLF (default is the line.separator system property)");
        System.err.println("\t-c connect timeout in seconds (default 10)");
        System.err.println("\t-r read timeout in seconds (default 10)");
        System.err.println("\t-R temporary failure retry wait in seconds (default 0; i.e. disabled)");
        System.err.println("\t-. print a . for each complete message received");
        System.err.println("\t-X print the X-IMAP line for each complete message received");
        System.err.println(
                "\tthe mboxfile is where the messages are stored; use '-' to write to standard output.");
        System.err.println(
                "\tPrefix filename with '+' to append to the file. Prefix with '-' to allow overwrite.");
        System.err.println(
                "\ta sequence-set is a list of numbers/number ranges e.g. 1,2,3-10,20:* - default 1:*");
        System.err
                .println("\titemnames are the message data item name(s) e.g. BODY.PEEK[HEADER.FIELDS (SUBJECT)]"
                        + " or a macro e.g. ALL - default (INTERNALDATE BODY.PEEK[])");
        System.exit(1);
    }

    final URI uri = URI.create(args[argIdx++]);
    final String file = args[argIdx++];
    String sequenceSet = argCount > 2 ? args[argIdx++] : "1:*";
    final String itemNames;
    // Handle 0, 1 or multiple item names
    if (argCount > 3) {
        if (argCount > 4) {
            StringBuilder sb = new StringBuilder();
            sb.append("(");
            for (int i = 4; i <= argCount; i++) {
                if (i > 4) {
                    sb.append(" ");
                }
                sb.append(args[argIdx++]);
            }
            sb.append(")");
            itemNames = sb.toString();
        } else {
            itemNames = args[argIdx++];
        }
    } else {
        itemNames = "(INTERNALDATE BODY.PEEK[])";
    }

    final boolean checkSequence = sequenceSet.matches("\\d+:(\\d+|\\*)"); // are we expecting a sequence?
    final MboxListener chunkListener;
    if (file.equals("-")) {
        chunkListener = null;
    } else if (file.startsWith("+")) {
        final File mbox = new File(file.substring(1));
        System.out.println("Appending to file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, true)), eol, printHash,
                printMarker, checkSequence);
    } else if (file.startsWith("-")) {
        final File mbox = new File(file.substring(1));
        System.out.println("Writing to file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, false)), eol, printHash,
                printMarker, checkSequence);
    } else {
        final File mbox = new File(file);
        if (mbox.exists()) {
            throw new IOException("mailbox file: " + mbox + " already exists!");
        }
        System.out.println("Creating file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox)), eol, printHash, printMarker,
                checkSequence);
    }

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

    // suppress login details
    final PrintCommandListener listener = new PrintCommandListener(System.out, true) {
        @Override
        public void protocolReplyReceived(ProtocolCommandEvent event) {
            if (event.getReplyCode() != IMAPReply.PARTIAL) { // This is dealt with by the chunk listener
                super.protocolReplyReceived(event);
            }
        }
    };

    // Connect and login
    final IMAPClient imap = IMAPUtils.imapLogin(uri, connect_timeout * 1000, listener);

    String maxIndexInFolder = null;

    try {

        imap.setSoTimeout(read_timeout * 1000);

        if (!imap.select(folder)) {
            throw new IOException("Could not select folder: " + folder);
        }

        for (String line : imap.getReplyStrings()) {
            maxIndexInFolder = matches(line, PATEXISTS, 1);
            if (maxIndexInFolder != null) {
                break;
            }
        }

        if (chunkListener != null) {
            imap.setChunkListener(chunkListener);
        } // else the command listener displays the full output without processing

        while (true) {
            boolean ok = imap.fetch(sequenceSet, itemNames);
            // If the fetch failed, can we retry?
            if (!ok && retryWaitSecs > 0 && chunkListener != null && checkSequence) {
                final String replyString = imap.getReplyString(); //includes EOL
                if (startsWith(replyString, PATTEMPFAIL)) {
                    System.err.println("Temporary error detected, will retry in " + retryWaitSecs + "seconds");
                    sequenceSet = (chunkListener.lastSeq + 1) + ":*";
                    try {
                        Thread.sleep(retryWaitSecs * 1000);
                    } catch (InterruptedException e) {
                        // ignored
                    }
                } else {
                    throw new IOException(
                            "FETCH " + sequenceSet + " " + itemNames + " failed with " + replyString);
                }
            } else {
                break;
            }
        }

    } catch (IOException ioe) {
        String count = chunkListener == null ? "?" : Integer.toString(chunkListener.total);
        System.err.println("FETCH " + sequenceSet + " " + itemNames + " failed after processing " + count
                + " complete messages ");
        if (chunkListener != null) {
            System.err.println("Last complete response seen: " + chunkListener.lastFetched);
        }
        throw ioe;
    } finally {

        if (printHash) {
            System.err.println();
        }

        if (chunkListener != null) {
            chunkListener.close();
            final Iterator<String> missingIds = chunkListener.missingIds.iterator();
            if (missingIds.hasNext()) {
                StringBuilder sb = new StringBuilder();
                for (;;) {
                    sb.append(missingIds.next());
                    if (!missingIds.hasNext()) {
                        break;
                    }
                    sb.append(",");
                }
                System.err.println("*** Missing ids: " + sb.toString());
            }
        }
        imap.logout();
        imap.disconnect();
    }
    if (chunkListener != null) {
        System.out.println("Processed " + chunkListener.total + " messages.");
    }
    if (maxIndexInFolder != null) {
        System.out.println("Folder contained " + maxIndexInFolder + " messages.");
    }
}

From source file:irckafka.ChatApp.java

public static void main(String[] args) {

    groupId = RandomStringUtils.random(8, true, true);

    boolean isOnline = true;

    Scanner in = new Scanner(System.in);
    while (isOnline) {

        String[] input = in.nextLine().split(" ");
        String command = input[0].toLowerCase();

        switch (command) {
        case "/nick":
            if (input.length >= 2) {
                nickname = input[1];//from  w  w  w .ja  va2 s.c o m
                System.out.println("your nickname is " + nickname);
            } else {
                System.out.println("write nick name please!");
            }
            break;
        case "/join":
            if (input.length >= 2) {
                KafkaConsumer consume = new KafkaConsumer(groupId, input[1]);
                consume.start();

                channelGroup.put(input[1], consume);
            } else {
                System.out.println("write channel name please!");
            }
            break;
        case "/leave":
            if (input.length >= 2) {
                if (channelGroup.containsKey(input[1])) {
                    KafkaConsumer consume = channelGroup.get(input[1]);
                    consume.shutdown();
                    channelGroup.remove(input[1]);
                    System.out.println("your leave channel " + input[1]);
                } else {
                    System.out.println("wrong channel name!!");
                }
            } else {
                System.out.println("write channel name please!");
            }
            break;
        case "/exit":
            System.out.println("bye");
            System.exit(0);
            break;
        default: //broadcast
            if (command.contains("@")) {
                String channelname = command.substring(1);
                KafkaProducer produce = new KafkaProducer();
                if (channelGroup.containsKey(channelname)) {
                    String message = "";
                    for (int i = 1; i < input.length; i++) {
                        message += input[i] + " ";
                    }
                    produce.sendMessage(channelname, message, nickname);
                }
                produce.closeConnection();
            } else {
                String message = "";
                for (int i = 0; i < input.length; i++) {
                    message += input[i] + " ";
                }

                KafkaProducer produce = new KafkaProducer();
                for (String cList : channelGroup.keySet()) {
                    produce.sendMessage(cList, message, nickname);
                }
                produce.closeConnection();
            }
        }
    }
}

From source file:net.massbank.validator.RecordValidator.java

public static void main(String[] args) {
    RequestDummy request;//from ww  w .ja v  a 2s .  c om

    PrintStream out = System.out;

    Options lvOptions = new Options();
    lvOptions.addOption("h", "help", false, "show this help.");
    lvOptions.addOption("r", "recdata", true,
            "points to the recdata directory containing massbank records. Reads all *.txt files in there.");

    CommandLineParser lvParser = new BasicParser();
    CommandLine lvCmd = null;
    try {
        lvCmd = lvParser.parse(lvOptions, args);
        if (lvCmd.hasOption('h')) {
            printHelp(lvOptions);
            return;
        }
    } catch (org.apache.commons.cli.ParseException pvException) {
        System.out.println(pvException.getMessage());
    }

    String recDataPath = lvCmd.getOptionValue("recdata");

    // ---------------------------------------------
    // ????
    // ---------------------------------------------

    final String baseUrl = MassBankEnv.get(MassBankEnv.KEY_BASE_URL);
    final String dbRootPath = "./";
    final String dbHostName = MassBankEnv.get(MassBankEnv.KEY_DB_HOST_NAME);
    final String tomcatTmpPath = ".";
    final String tmpPath = (new File(tomcatTmpPath + sdf.format(new Date()))).getPath() + File.separator;
    GetConfig conf = new GetConfig(baseUrl);
    int recVersion = 2;
    String selDbName = "";
    Object up = null; // Was: file Upload
    boolean isResult = true;
    String upFileName = "";
    boolean upResult = false;
    DatabaseAccess db = null;

    try {
        // ----------------------------------------------------
        // ???
        // ----------------------------------------------------
        // if (FileUpload.isMultipartContent(request)) {
        // (new File(tmpPath)).mkdir();
        // String os = System.getProperty("os.name");
        // if (os.indexOf("Windows") == -1) {
        // isResult = FileUtil.changeMode("777", tmpPath);
        // if (!isResult) {
        // out.println(msgErr("[" + tmpPath
        // + "]  chmod failed."));
        // return;
        // }
        // }
        // up = new FileUpload(request, tmpPath);
        // }

        // ----------------------------------------------------
        // ?DB????
        // ----------------------------------------------------
        List<String> dbNameList = Arrays.asList(conf.getDbName());
        ArrayList<String> dbNames = new ArrayList<String>();
        dbNames.add("");
        File[] dbDirs = (new File(dbRootPath)).listFiles();
        if (dbDirs != null) {
            for (File dbDir : dbDirs) {
                if (dbDir.isDirectory()) {
                    int pos = dbDir.getName().lastIndexOf("\\");
                    String dbDirName = dbDir.getName().substring(pos + 1);
                    pos = dbDirName.lastIndexOf("/");
                    dbDirName = dbDirName.substring(pos + 1);
                    if (dbNameList.contains(dbDirName)) {
                        // DB???massbank.conf???DB????
                        dbNames.add(dbDirName);
                    }
                }
            }
        }
        if (dbDirs == null || dbNames.size() == 0) {
            out.println(msgErr("[" + dbRootPath + "] directory not exist."));
            return;
        }
        Collections.sort(dbNames);

        // ----------------------------------------------------
        // ?
        // ----------------------------------------------------
        // if (FileUpload.isMultipartContent(request)) {
        // HashMap<String, String[]> reqParamMap = new HashMap<String,
        // String[]>();
        // reqParamMap = up.getRequestParam();
        // if (reqParamMap != null) {
        // for (Map.Entry<String, String[]> req : reqParamMap
        // .entrySet()) {
        // if (req.getKey().equals("ver")) {
        // try {
        // recVersion = Integer
        // .parseInt(req.getValue()[0]);
        // } catch (NumberFormatException nfe) {
        // }
        // } else if (req.getKey().equals("db")) {
        // selDbName = req.getValue()[0];
        // }
        // }
        // }
        // } else {
        // if (request.getParameter("ver") != null) {
        // try {
        // recVersion = Integer.parseInt(request
        // .getParameter("ver"));
        // } catch (NumberFormatException nfe) {
        // }
        // }
        // selDbName = request.getParameter("db");
        // }
        // if (selDbName == null || selDbName.equals("")
        // || !dbNames.contains(selDbName)) {
        // selDbName = dbNames.get(0);
        // }

        // ---------------------------------------------
        // 
        // ---------------------------------------------
        out.println("Database: ");
        for (int i = 0; i < dbNames.size(); i++) {
            String dbName = dbNames.get(i);
            out.print("dbName");
            if (dbName.equals(selDbName)) {
                out.print(" selected");
            }
            if (i == 0) {
                out.println("------------------");
            } else {
                out.println(dbName);
            }
        }
        out.println("Record Version : ");
        out.println(recVersion);

        out.println("Record Archive :");

        // ---------------------------------------------
        // 
        // ---------------------------------------------
        //         HashMap<String, Boolean> upFileMap = up.doUpload();
        //         if (upFileMap != null) {
        //            for (Map.Entry<String, Boolean> e : upFileMap.entrySet()) {
        //               upFileName = e.getKey();
        //               upResult = e.getValue();
        //               break;
        //            }
        //            if (upFileName.equals("")) {
        //               out.println(msgErr("please select file."));
        //               isResult = false;
        //            } else if (!upResult) {
        //               out.println(msgErr("[" + upFileName
        //                     + "] upload failed."));
        //               isResult = false;
        //            } else if (!upFileName.endsWith(ZIP_EXTENSION)
        //                  && !upFileName.endsWith(MSBK_EXTENSION)) {
        //               out.println(msgErr("please select ["
        //                     + UPLOAD_RECDATA_ZIP
        //                     + "] or ["
        //                     + UPLOAD_RECDATA_MSBK + "]."));
        //               up.deleteFile(upFileName);
        //               isResult = false;
        //            }
        //         } else {
        //            out.println(msgErr("server error."));
        //            isResult = false;
        //         }
        //         up.deleteFileItem();
        //         if (!isResult) {
        //            return;
        //         }

        // ---------------------------------------------
        // ???
        // ---------------------------------------------
        //         final String upFilePath = (new File(tmpPath + File.separator
        //               + upFileName)).getPath();
        //         isResult = FileUtil.unZip(upFilePath, tmpPath);
        //         if (!isResult) {
        //            out.println(msgErr("["
        //                  + upFileName
        //                  + "]  extraction failed. possibility of time-out."));
        //            return;
        //         }

        // ---------------------------------------------
        // ??
        // ---------------------------------------------
        final String recPath = (new File(dbRootPath + File.separator + selDbName)).getPath();
        File tmpRecDir = new File(recDataPath);
        if (!tmpRecDir.isDirectory()) {
            tmpRecDir.mkdirs();
        }

        // ---------------------------------------------
        // ???
        // ---------------------------------------------
        // data?
        //         final String recDataPath = (new File(tmpPath + File.separator
        //               + RECDATA_DIR_NAME)).getPath()
        //               + File.separator;
        //
        //         if (!(new File(recDataPath)).isDirectory()) {
        //            if (upFileName.endsWith(ZIP_EXTENSION)) {
        //               out.println(msgErr("["
        //                     + RECDATA_DIR_NAME
        //                     + "]  directory is not included in the up-loading file."));
        //            } else if (upFileName.endsWith(MSBK_EXTENSION)) {
        //               out.println(msgErr("The uploaded file is not record data."));
        //            }
        //            return;
        //         }

        // ---------------------------------------------
        // DB
        // ---------------------------------------------
        //         db = new DatabaseAccess(dbHostName, selDbName);
        //         isResult = db.open();
        //         if (!isResult) {
        //            db.close();
        //            out.println(msgErr("not connect to database."));
        //            return;
        //         }

        // ---------------------------------------------
        // ??
        // ---------------------------------------------
        TreeMap<String, String> resultMap = validationRecord(db, out, recDataPath, recPath, recVersion);
        if (resultMap.size() == 0) {
            return;
        }

        // ---------------------------------------------
        // ?
        // ---------------------------------------------
        isResult = dispResult(out, resultMap);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (db != null) {
            db.close();
        }
        File tmpDir = new File(tmpPath);
        if (tmpDir.exists()) {
            FileUtil.removeDir(tmpDir.getPath());
        }
    }

}

From source file:com.github.vatbub.tictactoe.view.Main.java

public static void main(String[] args) {
    Common.getInstance().setAppName("tictactoev2");
    FOKLogger.enableLoggingOfUncaughtExceptions();

    try {//  w w w  .j a  v  a2s  .  co  m
        applicationConfiguration = new Config(new URL(
                "https://raw.githubusercontent.com/vatbub/tictactoe/master/remoteconfig/client.properties"),
                Main.class.getResource("fallbackConfig.properties"), true,
                "tictactoeClientConfigCache.properties", true);
    } catch (IOException e) {
        FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not read the remote config", e);
    }

    for (String arg : args) {
        if (arg.toLowerCase().matches("mockappversion=.*")) {
            // Set the mock version
            String version = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockAppVersion(version);
        } else if (arg.toLowerCase().matches("mockbuildnumber=.*")) {
            // Set the mock build number
            String buildnumber = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockBuildNumber(buildnumber);
        } else if (arg.toLowerCase().matches("mockpackaging=.*")) {
            // Set the mock packaging
            String packaging = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockPackaging(packaging);
        } else if (arg.toLowerCase().matches("locale=.*")) {
            // set the gui language
            String guiLanguageCode = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            FOKLogger.info(Main.class.getName(), "Setting language: " + guiLanguageCode);
            Locale.setDefault(new Locale(guiLanguageCode));
        }
    }

    launch(args);
}

From source file:me.gloriouseggroll.quorrabot.Quorrabot.java

public static void main(String[] args) throws IOException {
    String user = "";
    String oauth = "";
    String apioauth = "";
    String channelName = "";
    String webauth = "";
    String webauthro = "";
    String clientid = "";
    String owner = "";
    String hostname = "";
    int baseport = 25300;
    InetAddress ip = InetAddress.getByName("127.0.0.1");
    int port = 0;
    double msglimit30 = 18.75;
    String datastore = "";
    String datastoreconfig = "";
    String youtubekey = "";
    String gamewispauth = "";
    String gamewisprefresh = "";
    String twitchalertstoken = "";
    String lastfmuser = "";
    String tpetoken = "";
    String twittertoken = "";
    String twittertokensecret = "";
    String streamtiptoken = "";
    String streamtipid = "";
    boolean webenable = true;
    boolean musicenable = true;
    boolean usehttps = false;
    String keystorepath = "";
    String keystorepassword = "";
    String timeZone = "";
    String mySqlConn = "";
    String mySqlHost = "";
    String mySqlPort = "";
    String mySqlName = "";
    String mySqlUser = "";
    String mySqlPass = "";
    FollowersCache followersCache;//from  w  w w  . jav a 2  s  .co  m
    ChannelUsersCache channelUsersCache;
    ChannelHostCache hostCache;
    SubscribersCache subscribersCache;
    String discordToken = "";
    String discordMainChannel = "";

    boolean changed = false;

    try {
        if (new File("./botlogin.txt").exists()) {
            String data = FileUtils.readFileToString(new File("./botlogin.txt"));
            String[] lines = data.replaceAll("\\r", "").split("\\n");

            for (String line : lines) {

                if (line.startsWith("logtimezone=") && line.length() >= 15) {
                    timeZone = line.substring(12);
                }
                if (line.startsWith("websocketircab")) {
                    Quorrabot.webSocketIRCAB = true;
                }
                if (line.startsWith("user=") && line.length() > 8) {
                    user = line.substring(5);
                }
                if (line.startsWith("oauth=") && line.length() > 9) {
                    oauth = line.substring(6);
                }
                if (line.startsWith("apioauth=") && line.length() > 12) {
                    apioauth = line.substring(9);
                }
                if (line.startsWith("clientid=") && line.length() > 12) {
                    clientid = line.substring(9);
                }
                if (line.startsWith("channel=") && line.length() > 11) {
                    channelName = line.substring(8);
                }
                if (line.startsWith("owner=") && line.length() > 9) {
                    owner = line.substring(6);
                }
                if (line.startsWith("baseport=") && line.length() > 10) {
                    baseport = Integer.parseInt(line.substring(9));
                }
                if (line.startsWith("ip=") && line.length() > 4) {
                    ip = InetAddress.getByName(line.substring(3));
                }
                if (line.startsWith("hostname=") && line.length() > 10) {
                    hostname = line.substring(9);
                }
                if (line.startsWith("port=") && line.length() > 6) {
                    port = Integer.parseInt(line.substring(5));
                }
                if (line.startsWith("msglimit30=") && line.length() > 12) {
                    msglimit30 = Double.parseDouble(line.substring(11));
                }
                if (line.startsWith("datastore=") && line.length() > 11) {
                    datastore = line.substring(10);
                }
                if (line.startsWith("youtubekey=") && line.length() > 12) {
                    youtubekey = line.substring(11);
                }
                if (line.startsWith("gamewispauth=") && line.length() > 14) {
                    gamewispauth = line.substring(13);
                }
                if (line.startsWith("gamewisprefresh=") && line.length() > 17) {
                    gamewisprefresh = line.substring(16);
                }
                if (line.startsWith("twitchalertstoken=") && line.length() > 19) {
                    twitchalertstoken = line.substring(18);
                }
                if (line.startsWith("lastfmuser=") && line.length() > 12) {
                    lastfmuser = line.substring(11);
                }
                if (line.startsWith("tpetoken=") && line.length() > 10) {
                    tpetoken = line.substring(9);
                }
                if (line.startsWith("twittertoken=") && line.length() > 14) {
                    twittertoken = line.substring(13);
                }
                if (line.startsWith("twittertokensecret=") && line.length() > 20) {
                    twittertokensecret = line.substring(19);
                }
                if (line.startsWith("streamtiptoken=") && line.length() > 16) {
                    streamtiptoken = line.substring(15);
                }
                if (line.startsWith("streamtipid=") && line.length() > 13) {
                    streamtipid = line.substring(12);
                }
                if (line.startsWith("webenable=") && line.length() > 11) {
                    webenable = Boolean.valueOf(line.substring(10));
                }
                if (line.startsWith("musicenable=") && line.length() > 13) {
                    musicenable = Boolean.valueOf(line.substring(12));
                }
                if (line.startsWith("usehttps=") && line.length() > 10) {
                    usehttps = Boolean.valueOf(line.substring(9));
                }
                if (line.startsWith("mysqlhost=") && line.length() > 11) {
                    mySqlHost = line.substring(10);
                }
                if (line.startsWith("mysqlport=") && line.length() > 11) {
                    mySqlPort = line.substring(10);
                }
                if (line.startsWith("mysqlname=") && line.length() > 11) {
                    mySqlName = line.substring(10);
                }
                if (line.startsWith("mysqluser=") && line.length() > 11) {
                    mySqlUser = line.substring(10);
                }
                if (line.startsWith("mysqlpass=") && line.length() > 11) {
                    mySqlPass = line.substring(10);
                }
                if (line.startsWith("keystorepath=") && line.length() > 14) {
                    keystorepath = line.substring(13);
                }
                if (line.startsWith("keystorepassword=") && line.length() > 18) {
                    keystorepassword = line.substring(17);
                }
                if (line.startsWith("webauth=") && line.length() > 9) {
                    webauth = line.substring(8);
                }
                if (line.startsWith("webauthro=") && line.length() > 11) {
                    webauthro = line.substring(10);
                }
                if (line.startsWith("discordtoken=") && line.length() >= 14) {
                    discordToken = line.substring(13);
                }
                if (line.startsWith("discordmainchannel=") && line.length() >= 20) {
                    discordMainChannel = line.substring(19);
                }
            }
        }
    } catch (IOException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }

    /**
     * Check to see if there's a soundboardauth set
     */
    if (webauth.isEmpty()) {
        webauth = generateWebAuth();
        com.gmt2001.Console.debug.println("New webauth key has been generated for botlogin.txt");
        changed = true;
    }
    /**
     * Check to see if there's a soundboardauthread set
     */
    if (webauthro.isEmpty()) {
        webauthro = generateWebAuth();
        com.gmt2001.Console.debug.println("New webauth read-only key has been generated for botlogin.txt");
        changed = true;
    }

    try {
        if (user.isEmpty()) {
            com.gmt2001.Console.out.print("Please enter the bot's twitch username: ");
            user = System.console().readLine().trim().toLowerCase();
            changed = true;
        }
        if (oauth.isEmpty()) {
            com.gmt2001.Console.out.println(
                    "Visit http://quorrabot.com/pages/twitchapi/ to generate oAuth tokens for both the bot and the channel owner accounts (including 'oauth:') & type it below.");
            com.gmt2001.Console.out
                    .println("IMPORTANT: This MUST be done while logged in as the BOT account!" + "\n");
            com.gmt2001.Console.out.println("Please enter the bot's tmi oauth token: ");
            oauth = System.console().readLine().trim();
            changed = true;
        }
        if (channelName.isEmpty()) {
            com.gmt2001.Console.out.print(
                    "Please enter the name of the twitch channel the bot should join (not the url, just the name): ");
            channelName = System.console().readLine().trim().toLowerCase();
            changed = true;
        }
        if (apioauth.isEmpty()) {
            com.gmt2001.Console.out.println(
                    "Visit http://quorrabot.com/pages/twitchapi/ to generate oAuth tokens for both the bot and the channel owner accounts (including 'oauth:') & type it below.");
            com.gmt2001.Console.out.println(
                    "IMPORTANT: This MUST be done while logged in on the CHANNEL OWNER account!" + "\n");
            com.gmt2001.Console.out.println("Please enter the channel owner's tmi oauth token: ");
            apioauth = System.console().readLine().trim();
            changed = true;
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }

    if (owner.isEmpty()) {
        owner = channelName;

        changed = true;
    }

    if (args.length > 0) {
        for (String arg : args) {
            if (arg.equalsIgnoreCase("printlogin")) {
                com.gmt2001.Console.out.println("user='" + user + "'");
                com.gmt2001.Console.out.println("oauth='" + oauth + "'");
                com.gmt2001.Console.out.println("apioauth='" + apioauth + "'");
                com.gmt2001.Console.out.println("clientid='" + clientid + "'");
                com.gmt2001.Console.out.println("channel='" + channelName + "'");
                com.gmt2001.Console.out.println("owner='" + owner + "'");
                com.gmt2001.Console.out.println("baseport='" + baseport + "'");
                com.gmt2001.Console.out.println("ip='" + ip.getHostAddress() + "'");
                com.gmt2001.Console.out.println("hostname='" + hostname + "'");
                com.gmt2001.Console.out.println("port='" + port + "'");
                com.gmt2001.Console.out.println("msglimit30='" + msglimit30 + "'");
                com.gmt2001.Console.out.println("datastore='" + datastore + "'");
                com.gmt2001.Console.out.println("youtubekey='" + youtubekey + "'");
                com.gmt2001.Console.out.println("gamewispauth=" + gamewispauth + "'");
                com.gmt2001.Console.out.println("gamewisprefresh=" + gamewisprefresh + "'");
                com.gmt2001.Console.out.println("twitchalertstoken='" + twitchalertstoken + "'");
                com.gmt2001.Console.out.println("lastfmuser='" + lastfmuser + "'");
                com.gmt2001.Console.out.println("tpetoken='" + tpetoken + "'");
                com.gmt2001.Console.out.println("twittertoken='" + twittertoken + "'");
                com.gmt2001.Console.out.println("twittertokensecret='" + twittertokensecret + "'");
                com.gmt2001.Console.out.println("streamtiptoken='" + streamtiptoken + "'");
                com.gmt2001.Console.out.println("streamtipid='" + streamtipid + "'");
                com.gmt2001.Console.out.println("webenable=" + webenable);
                com.gmt2001.Console.out.println("musicenable=" + musicenable);
                com.gmt2001.Console.out.println("usehttps=" + usehttps);
                com.gmt2001.Console.out.println("keystorepath='" + keystorepath + "'");
                com.gmt2001.Console.out.println("keystorepassword='" + keystorepassword + "'");
                com.gmt2001.Console.out.println("discordtoken='" + discordToken + "'");
                com.gmt2001.Console.out.println("discordmainchannel='" + discordMainChannel + "'");
            }
            if (arg.equalsIgnoreCase("debugon")) {
                Quorrabot.enableDebugging = true;
            }
            if (arg.equalsIgnoreCase("ini2sqlite")) {
                com.gmt2001.Console.out.println("Converting default IniStore to default SqliteStore...");
                ini2sqlite(false);
                com.gmt2001.Console.out.println("Operation complete. The bot will now exit");
                System.exit(0);
                return;
            }
            if (arg.toLowerCase().startsWith("user=") && arg.length() > 8) {
                if (!user.equals(arg.substring(5))) {
                    user = arg.substring(5).toLowerCase();
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("oauth=") && arg.length() > 9) {
                if (!oauth.equals(arg.substring(6))) {
                    oauth = arg.substring(6);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("apioauth=") && arg.length() > 12) {
                if (!apioauth.equals(arg.substring(9))) {
                    apioauth = arg.substring(9);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqlhost=") && arg.length() > 11) {
                if (!mySqlHost.equals(arg.substring(10))) {
                    mySqlHost = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqlport=") && arg.length() > 11) {
                if (!mySqlPort.equals(arg.substring(10))) {
                    mySqlPort = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqlname=") && arg.length() > 11) {
                if (!mySqlName.equals(arg.substring(10))) {
                    mySqlName = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqluser=") && arg.length() > 11) {
                if (!mySqlUser.equals(arg.substring(14))) {
                    mySqlUser = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqlpass=") && arg.length() > 11) {
                if (!mySqlPass.equals(arg.substring(10))) {
                    mySqlPass = arg.substring(10);
                    changed = true;
                }
            }

            if (arg.toLowerCase().startsWith("clientid=") && arg.length() > 12) {
                if (!clientid.equals(arg.substring(9))) {
                    clientid = arg.substring(9);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("channel=") && arg.length() > 11) {
                if (!channelName.equals(arg.substring(8))) {
                    channelName = arg.substring(8).toLowerCase();
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("owner=") && arg.length() > 9) {
                if (!owner.equals(arg.substring(6))) {
                    owner = arg.substring(6).toLowerCase();
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("baseport=") && arg.length() > 10) {
                if (baseport != Integer.parseInt(arg.substring(9))) {
                    baseport = Integer.parseInt(arg.substring(9));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("ip=") && arg.length() > 4) {
                if (ip != InetAddress.getByName(arg.substring(3))) {
                    ip = InetAddress.getByName(arg.substring(3));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("hostname=") && arg.length() > 10) {
                if (!hostname.equals(arg.substring(9))) {
                    hostname = arg.substring(9);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("port=") && arg.length() > 6) {
                if (port != Integer.parseInt(arg.substring(5))) {
                    port = Integer.parseInt(arg.substring(5));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("msglimit30=") && arg.length() > 12) {
                if (msglimit30 != Double.parseDouble(arg.substring(11))) {
                    msglimit30 = Double.parseDouble(arg.substring(11));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("datastore=") && arg.length() > 11) {
                if (!datastore.equals(arg.substring(10))) {
                    datastore = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("datastoreconfig=") && arg.length() > 17) {
                datastoreconfig = arg.substring(16);
            }
            if (arg.toLowerCase().startsWith("youtubekey=") && arg.length() > 12) {
                if (!youtubekey.equals(arg.substring(11))) {
                    youtubekey = arg.substring(11);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("gamewispauth=") && arg.length() > 14) {
                if (!gamewispauth.equals(arg.substring(13))) {
                    gamewispauth = arg.substring(13);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("gamewisprefresh=") && arg.length() > 17) {
                if (!gamewisprefresh.equals(arg.substring(16))) {
                    gamewisprefresh = arg.substring(16);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("twitchalertstoken=") && arg.length() > 19) {
                if (!twitchalertstoken.equals(arg.substring(18))) {
                    twitchalertstoken = arg.substring(18);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("lastfmuser=") && arg.length() > 12) {
                if (!lastfmuser.equals(arg.substring(11))) {
                    lastfmuser = arg.substring(11);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("tpetoken=") && arg.length() > 10) {
                if (!tpetoken.equals(arg.substring(9))) {
                    tpetoken = arg.substring(9);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("twittertoken=") && arg.length() > 14) {
                if (!twittertoken.equals(arg.substring(13))) {
                    twittertoken = arg.substring(13);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("twittertokensecret=") && arg.length() > 20) {
                if (!twittertokensecret.equals(arg.substring(19))) {
                    twittertokensecret = arg.substring(19);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("streamtiptoken=") && arg.length() > 16) {
                if (!streamtiptoken.equals(arg.substring(15))) {
                    streamtiptoken = arg.substring(15);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("streamtipid=") && arg.length() > 13) {
                if (!streamtipid.equals(arg.substring(12))) {
                    streamtipid = arg.substring(12);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("webenable=") && arg.length() > 11) {
                if (webenable != Boolean.valueOf(arg.substring(10))) {
                    webenable = Boolean.valueOf(arg.substring(10));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("musicenable=") && arg.length() > 13) {
                if (musicenable != Boolean.valueOf(arg.substring(12))) {
                    musicenable = Boolean.valueOf(arg.substring(12));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("usehttps=") && arg.length() > 10) {
                if (usehttps != Boolean.valueOf(arg.substring(9))) {
                    usehttps = Boolean.valueOf(arg.substring(9));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("keystorepath=") && arg.length() > 14) {
                if (!keystorepath.equals(arg.substring(13))) {
                    keystorepath = arg.substring(13);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("keystorepassword=") && arg.length() > 18) {
                if (!keystorepassword.equals(arg.substring(17))) {
                    keystorepassword = arg.substring(17);
                    changed = true;
                }
            }

            if (arg.equalsIgnoreCase("help") || arg.equalsIgnoreCase("--help") || arg.equalsIgnoreCase("-h")
                    || arg.equalsIgnoreCase("-?")) {
                com.gmt2001.Console.out.println(
                        "Usage: java -Dfile.encoding=UTF-8 -jar QuorraBot.jar [printlogin] [user=<bot username>] "
                                + "[oauth=<bot irc oauth>] [apioauth=<editor oauth>] [clientid=<oauth clientid>] [channel=<channel to join>] "
                                + "[owner=<bot owner username>] [baseport=<bot webserver port, music server will be +1>] [ip=<IP address (optional) to bind to>] [hostname=<custom irc server>] "
                                + "[port=<custom irc port>] [msglimit30=<message limit per 30 seconds>] "
                                + "[datastore=<DataStore type, for a list, run java -jar QuorraBot.jar storetypes>] "
                                + "[datastoreconfig=<Optional DataStore config option, different for each DataStore type>] "
                                + "[youtubekey=<youtube api key>] [webenable=<true | false>] [musicenable=<true | false>] "
                                + "[gamewispauth=<gamewisp oauth>] "
                                + "[gamewisprefresh=<gamewisp refresh key>] "
                                + "[twitchalertstoken=<TwitchAlerts access token>] "
                                + "[lastfmuser=<Last.FM username>] " + "[tpetoken=<Tipeeestream access token>] "
                                + "[streamtiptoken=<StreamTip access token>] "
                                + "[streamtipid=<StreamTip Client ID>] "
                                + "[twittertoken=<Twitter access token>] "
                                + "[twittertokensecret=<Twitter access token secret>]");

                return;
            }
            if (arg.equalsIgnoreCase("storetypes")) {
                com.gmt2001.Console.out.println(
                        "DataStore types: IniStore (datastoreconfig parameter is folder name, stores in .ini files), "
                                + "TempStore (Stores in memory, lost on shutdown), "
                                + "SqliteStore (Default, Stores in a SQLite3 database, datastoreconfig parameter is a config file");
                return;
            }
        }
    }

    if (changed) {
        String data = "";
        data += "user=" + user + "\r\n";
        data += "oauth=" + oauth + "\r\n";
        data += "apioauth=" + apioauth + "\r\n";
        data += "clientid=" + clientid + "\r\n";
        data += "webauth=" + webauth + "\r\n";
        data += "webauthro=" + webauthro + "\r\n";
        data += "channel=" + channelName + "\r\n";
        data += "owner=" + owner + "\r\n";
        data += "baseport=" + baseport + "\r\n";
        data += "ip=" + ip.getHostAddress() + "\r\n";
        data += "hostname=" + hostname + "\r\n";
        data += "port=" + port + "\r\n";
        data += "msglimit30=" + msglimit30 + "\r\n";
        data += "datastore=" + datastore + "\r\n";
        data += "youtubekey=" + youtubekey + "\r\n";
        data += "gamewispauth=" + gamewispauth + "\r\n";
        data += "gamewisprefresh=" + gamewisprefresh + "\r\n";
        data += "twitchalertstoken=" + twitchalertstoken + "\r\n";
        data += "lastfmuser=" + lastfmuser + "\r\n";
        data += "tpetoken=" + tpetoken + "\r\n";
        data += "twittertoken=" + twittertoken + "\r\n";
        data += "twittertokensecret=" + twittertokensecret + "\r\n";
        data += "streamtiptoken=" + streamtiptoken + "\r\n";
        data += "streamtipid=" + streamtipid + "\r\n";
        data += "webenable=" + webenable + "\r\n";
        data += "musicenable=" + musicenable + "\r\n";
        data += "usehttps=" + usehttps + "\r\n";
        data += "logtimezone=" + timeZone + "\r\n";
        data += "mysqlhost=" + mySqlHost + "\r\n";
        data += "mysqlport=" + mySqlPort + "\r\n";
        data += "mysqlname=" + mySqlName + "\r\n";
        data += "mysqluser=" + mySqlUser + "\r\n";
        data += "mysqlpass=" + mySqlPass + "\r\n";
        data += "keystorepath=" + keystorepath + "\r\n";
        data += "keystorepassword=" + keystorepassword + "\r\n";
        data += "discordtoken=" + discordToken + "\r\n";
        data += "discordmainchannel=" + discordMainChannel;

        Files.write(Paths.get("./botlogin.txt"), data.getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
    }
    channelUsersCache = ChannelUsersCache.instance(owner);
    followersCache = FollowersCache.instance(owner);
    hostCache = ChannelHostCache.instance(owner);
    subscribersCache = SubscribersCache.instance(owner);

    Quorrabot.instance = new Quorrabot(user, oauth, apioauth, clientid, channelName, owner, baseport, ip,
            hostname, port, msglimit30, datastore, datastoreconfig, youtubekey, gamewispauth, gamewisprefresh,
            twitchalertstoken, lastfmuser, tpetoken, twittertoken, twittertokensecret, streamtiptoken,
            streamtipid, webenable, webauth, webauthro, musicenable, usehttps, timeZone, mySqlHost, mySqlPort,
            mySqlConn, mySqlPass, mySqlUser, mySqlName, keystorepath, followersCache, hostCache,
            channelUsersCache, subscribersCache, discordToken, discordMainChannel);
}

From source file:com.termmed.statistics.runner.Runner.java

/**
 * The main method./*ww w.  j  av  a  2 s . c  o  m*/
 *
 * @param args the arguments
 */
public static void main(String[] args) {

    logger = new ProcessLogger();
    if (args.length == 0) {
        logger.logInfo("Error happened getting params. Params file doesn't exist");
        System.exit(0);
        //      }else{
        //         args=new String[]{"config/complete_nl-edition11320160930.xml"};
    }
    File infoFolder = new File(I_Constants.PROCESS_INFO_FOLDER);
    if (!infoFolder.exists()) {
        infoFolder.mkdirs();
    }
    OutputInfoFactory.get().setExecutionId(UUID.randomUUID().toString());
    String msg;
    int posIni;
    long start = logger.startTime();
    File file = new File(args[0]);
    Config configFile = getConfig(file);
    OutputInfoFactory.get().setConfig(configFile);
    System.setProperty("textdb.allow_full_path", "true");
    Connection c;
    try {
        boolean clean = false;
        if (args.length >= 2) {
            for (int i = 1; i < args.length; i++) {
                logger.logInfo("Arg " + i + ": " + args[i]);
                if (args[i].toLowerCase().equals("clean")) {
                    clean = true;
                }
            }
        }
        dataFolder = new File(I_Constants.REPO_FOLDER);
        if (!dataFolder.exists()) {
            dataFolder.mkdirs();
        }

        changedDate = true;
        changedPreviousDate = true;
        getParams(file);
        checkDates();
        /*******************************/
        //         changedDate=false;
        //         changedPreviousDate=false;
        /********************************/
        if (clean || changedDate || changedPreviousDate) {
            logger.logInfo("Removing old data");
            removeDBFolder();
            removeRepoFolder();
            removeReducedFolder();
            changedDate = true;
            changedPreviousDate = true;
        }

        Class.forName("org.hsqldb.jdbcDriver");
        logger.logInfo("Connecting to DB. This task can take several minutes... wait please.");
        c = DriverManager.getConnection("jdbc:hsqldb:file:" + I_Constants.DB_FOLDER, "sa", "sa");

        initFileProviders(file);
        //         OutputInfoFactory.get().getStatisticProcess().setOutputFolder(I_Constants.STATS_OUTPUT_FOLDER);

        /*******************************/
        //         DbSetup dbs=new DbSetup(c);
        //         dbs.recreatePath("org/ihtsdo/statistics/db/setup/storedprocedure");
        //         dbs=null;
        /*******************************/

        ImportManager impor = new ImportManager(c, file, changedDate, changedPreviousDate);
        impor.execute();

        impor = null;

        Processor proc = new Processor(c, file);

        proc.execute();

        proc = null;

        msg = logger.endTime(start);
        posIni = msg.indexOf("ProcessingTime:") + 16;
        OutputInfoFactory.get().getStatisticProcess().setTimeTaken(msg.substring(posIni));
        //         OutputInfoFactory.get().getPatternProcess().setOutputFolder(I_Constants.PATTERN_OUTPUT_FOLDER);
        long startPattern = logger.startTime();
        PatternExecutor pe = new PatternExecutor(file);

        pe.execute();

        pe = null;
        msg = logger.endTime(startPattern);
        posIni = msg.indexOf("ProcessingTime:") + 16;
        OutputInfoFactory.get().getPatternProcess().setTimeTaken(msg.substring(posIni));

        OutputInfoFactory.get().setStatus("Complete");
    } catch (Exception e) {
        OutputInfoFactory.get().setStatus("Error: " + e.getMessage() + " - View log for details.");
        e.printStackTrace();
    }
    msg = logger.endTime(start);
    posIni = msg.indexOf("ProcessingTime:") + 16;
    OutputInfoFactory.get().setTimeTaken(msg.substring(posIni));

    try {
        saveInfo();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:at.tuwien.ifs.somtoolbox.apps.VisualisationImageSaver.java

public static void main(String[] args) {
    JSAPResult res = OptionFactory.parseResults(args, OPTIONS);

    String uFile = res.getString("unitDescriptionFile");
    String wFile = res.getString("weightVectorFile");
    String dwmFile = res.getString("dataWinnerMappingFile");
    String cFile = res.getString("classInformationFile");
    String vFile = res.getString("inputVectorFile");
    String tFile = res.getString("templateVectorFile");
    String ftype = res.getString("filetype");
    boolean unitGrid = res.getBoolean("unitGrid");

    String basename = res.getString("basename");
    if (basename == null) {
        basename = FileUtils.extractSOMLibInputPrefix(uFile);
    }//w  w  w  . j av a  2 s  .  com
    basename = new File(basename).getAbsolutePath();
    int unitW = res.getInt("width");
    int unitH = res.getInt("height", unitW);

    String[] vizs = res.getStringArray("vis");

    GrowingSOM gsom = null;
    CommonSOMViewerStateData state = CommonSOMViewerStateData.getInstance();
    try {
        SOMLibFormatInputReader inputReader = new SOMLibFormatInputReader(wFile, uFile, null);
        gsom = new GrowingSOM(inputReader);

        SharedSOMVisualisationData d = new SharedSOMVisualisationData(cFile, null, null, dwmFile, vFile, tFile,
                null);
        d.readAvailableData();
        state.inputDataObjects = d;
        gsom.setSharedInputObjects(d);

        Visualizations.initVisualizations(d, inputReader, 0, Palettes.getDefaultPalette(),
                Palettes.getAvailablePalettes());

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.exit(1);
    } catch (SOMLibFileFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.exit(1);
    }

    if (ArrayUtils.isEmpty(vizs)) {
        System.out.println("No specific visualisation specified - saving all available visualisations.");
        vizs = Visualizations.getReadyVisualizationNames();
        System.out.println("Found " + vizs.length + ": " + Arrays.toString(vizs));
    }

    for (String viz : vizs) {
        BackgroundImageVisualizerInstance v = Visualizations.getVisualizationByName(viz);
        if (v == null) {
            System.out.println("Visualization '" + viz + "' not found!");
            continue;
        }
        BackgroundImageVisualizer i = v.getVis();

        GrowingLayer layer = gsom.getLayer();
        try {
            int height = unitH * layer.getYSize();
            int width = unitW * layer.getXSize();
            HashMap<String, BufferedImage> visualizationFlavours = i.getVisualizationFlavours(v.getVariant(),
                    gsom, width, height);
            ArrayList<String> keys = new ArrayList<String>(visualizationFlavours.keySet());
            Collections.sort(keys);

            // if the visualisation has more than 5 flavours, we create a sub-dir for it
            String subDirName = "";
            String oldBasename = basename; // save original base name for later
            if (keys.size() > 5) {
                String parentDir = new File(basename).getParentFile().getPath(); // get the parent path
                String filePrefix = basename.substring(parentDir.length()); // end the file name prefix
                subDirName = parentDir + File.separator + filePrefix + "_" + viz + File.separator; // compose a new
                // subdir name
                new File(subDirName).mkdir(); // create the dir
                basename = subDirName + filePrefix; // and extend the base name by the subdir
            }
            for (String key : keys) {
                File out = new File(basename + "_" + viz + key + "." + ftype);
                System.out.println("Generating visualisation '" + viz + "' as '" + out.getPath() + "'.");
                BufferedImage image = visualizationFlavours.get(key);
                if (unitGrid) {
                    VisualisationUtils.drawUnitGrid(image, gsom, width, height);
                }
                ImageIO.write(image, ftype, out);
            }
            basename = oldBasename; // reset base name
        } catch (SOMToolboxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    System.exit(0);
}

From source file:com.admc.jcreole.JCreole.java

/**
 * Run this method with no parameters to see syntax requirements and the
 * available parameters.//from  ww  w  . j  a  va 2  s.  c  om
 *
 * N.b. do not call this method from a persistent program, because it
 * may call System.exit!
 * <p>
 * Any long-running program should use the lower-level methods in this
 * class instead (or directly use CreoleParser and CreoleScanner
 * instances).
 * </p> <p>
 * This method executes with all JCreole privileges.
 * </p> <p>
 * This method sets up the following htmlExpander mappings (therefore you
 * can reference these in both Creole and boilerplate text).<p>
 * <ul>
 *   <li>sys|*: mappings for Java system properties
 *   <li>isoDateTime
 *   <li>isoDate
 *   <li>pageTitle: Value derived from the specified Creole file name.
 * </ul>
 *
 * @throws IOException for any I/O problem that makes it impossible to
 *         satisfy the request.
 * @throws CreoleParseException
 *         if can not generate output, or if the run generates 0 output.
 *         If the problem is due to input formatting, in most cases you
 *         will get a CreoleParseException, which is a RuntimException, and
 *         CreoleParseException has getters for locations in the source
 *         data (though they will be offset for \r's in the provided
 *         Creole source, if any).
 */
public static void main(String[] sa) throws IOException {
    String bpResPath = null;
    String bpFsPath = null;
    String outPath = null;
    String inPath = null;
    boolean debugs = false;
    boolean troubleshoot = false;
    boolean noBp = false;
    int param = -1;
    try {
        while (++param < sa.length) {
            if (sa[param].equals("-d")) {
                debugs = true;
                continue;
            }
            if (sa[param].equals("-t")) {
                troubleshoot = true;
                continue;
            }
            if (sa[param].equals("-r") && param + 1 < sa.length) {
                if (bpFsPath != null || bpResPath != null || noBp)
                    throw new IllegalArgumentException();
                bpResPath = sa[++param];
                continue;
            }
            if (sa[param].equals("-f") && param + 1 < sa.length) {
                if (bpResPath != null || bpFsPath != null || noBp)
                    throw new IllegalArgumentException();
                bpFsPath = sa[++param];
                continue;
            }
            if (sa[param].equals("-")) {
                if (noBp || bpFsPath != null || bpResPath != null)
                    throw new IllegalArgumentException();
                noBp = true;
                continue;
            }
            if (sa[param].equals("-o") && param + 1 < sa.length) {
                if (outPath != null)
                    throw new IllegalArgumentException();
                outPath = sa[++param];
                continue;
            }
            if (inPath != null)
                throw new IllegalArgumentException();
            inPath = sa[param];
        }
        if (inPath == null)
            throw new IllegalArgumentException();
    } catch (IllegalArgumentException iae) {
        System.err.println(SYNTAX_MSG);
        System.exit(1);
    }
    if (!noBp && bpResPath == null && bpFsPath == null)
        bpResPath = DEFAULT_BP_RES_PATH;
    String rawBoilerPlate = null;
    if (bpResPath != null) {
        if (bpResPath.length() > 0 && bpResPath.charAt(0) == '/')
            // Classloader lookups are ALWAYS relative to CLASSPATH roots,
            // and will abort if you specify a beginning "/".
            bpResPath = bpResPath.substring(1);
        InputStream iStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(bpResPath);
        if (iStream == null)
            throw new IOException("Boilerplate inaccessible: " + bpResPath);
        rawBoilerPlate = IOUtil.toString(iStream);
    } else if (bpFsPath != null) {
        rawBoilerPlate = IOUtil.toString(new File(bpFsPath));
    }
    String creoleResPath = (inPath.length() > 0 && inPath.charAt(0) == '/') ? inPath.substring(1) : inPath;
    // Classloader lookups are ALWAYS relative to CLASSPATH roots,
    // and will abort if you specify a beginning "/".
    InputStream creoleStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(creoleResPath);
    File inFile = (creoleStream == null) ? new File(inPath) : null;
    JCreole jCreole = (rawBoilerPlate == null) ? (new JCreole()) : (new JCreole(rawBoilerPlate));
    if (debugs) {
        jCreole.setInterWikiMapper(new InterWikiMapper() {
            // This InterWikiMapper is just for prototyping.
            // Use wiki name of "nil" to force lookup failure for path.
            // Use wiki page of "nil" to force lookup failure for label.
            public String toPath(String wikiName, String wikiPage) {
                if (wikiName != null && wikiName.equals("nil"))
                    return null;
                return "{WIKI-LINK to: " + wikiName + '|' + wikiPage + '}';
            }

            public String toLabel(String wikiName, String wikiPage) {
                if (wikiPage == null)
                    throw new RuntimeException("Null page name sent to InterWikiMapper");
                if (wikiPage.equals("nil"))
                    return null;
                return "{LABEL for: " + wikiName + '|' + wikiPage + '}';
            }
        });
        Expander creoleExpander = new Expander(Expander.PairedDelims.RECTANGULAR);
        creoleExpander.put("testMacro",
                "\n\n<<prettyPrint>>\n{{{\n" + "!/bin/bash -p\n\ncp /etc/inittab /tmp\n}}}\n");
        jCreole.setCreoleExpander(creoleExpander);
    }
    jCreole.setPrivileges(EnumSet.allOf(JCreolePrivilege.class));
    Expander exp = jCreole.getHtmlExpander();
    Date now = new Date();
    exp.putAll("sys", System.getProperties(), false);
    exp.put("isoDateTime", isoDateTimeFormatter.format(now), false);
    exp.put("isoDate", isoDateFormatter.format(now), false);
    exp.put("pageTitle",
            (inFile == null) ? creoleResPath.replaceFirst("[.][^.]*$", "").replaceFirst(".*[/\\\\.]", "")
                    : inFile.getName().replaceFirst("[.][^.]*$", ""));
    if (troubleshoot) {
        // We don't write any HMTL output here.
        // Goal is just to output diagnostics.
        StringBuilder builder = (creoleStream == null) ? IOUtil.toStringBuilder(inFile)
                : IOUtil.toStringBuilder(creoleStream);
        int newlineCount = 0;
        int lastOffset = -1;
        int offset = builder.indexOf("\n");
        for (; offset >= 0; offset = builder.indexOf("\n", offset + 1)) {
            lastOffset = offset;
            newlineCount++;
        }
        // Accommodate input files with no terminating newline:
        if (builder.length() > lastOffset + 1)
            newlineCount++;
        System.out.println("Input lines:  " + newlineCount);
        Exception lastException = null;
        while (true) {
            try {
                jCreole.parseCreole(builder);
                break;
            } catch (Exception e) {
                lastException = e;
            }
            if (builder.charAt(builder.length() - 1) == '\n')
                builder.setLength(builder.length() - 1);
            offset = builder.lastIndexOf("\n");
            if (offset < 1)
                break;
            newlineCount--;
            builder.setLength(builder.lastIndexOf("\n"));
        }
        System.out.println((lastException == null) ? "Input validates"
                : String.format("Error around input line %d:  %s", newlineCount, lastException.getMessage()));
        return;
    }
    String generatedHtml = (creoleStream == null) ? jCreole.parseCreole(inFile)
            : jCreole.parseCreole(IOUtil.toStringBuilder(creoleStream));
    String html = jCreole.postProcess(generatedHtml, SystemUtils.LINE_SEPARATOR);
    if (outPath == null) {
        System.out.print(html);
    } else {
        FileUtils.writeStringToFile(new File(outPath), html, "UTF-8");
    }
}

From source file:io.compgen.cgpipe.CGPipe.java

public static void main(String[] args) {
    String fname = null;//from  w  ww.j  a  va 2  s. com
    String logFilename = null;
    String outputFilename = null;
    PrintStream outputStream = null;

    int verbosity = 0;
    boolean silent = false;
    boolean dryrun = false;
    boolean silenceStdErr = false;
    boolean showHelp = false;

    List<String> targets = new ArrayList<String>();
    Map<String, VarValue> confVals = new HashMap<String, VarValue>();

    String k = null;

    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        if (i == 0) {
            if (new File(arg).exists()) {
                fname = arg;
                silenceStdErr = true;
                continue;
            }
        } else if (args[i - 1].equals("-f")) {
            fname = arg;
            continue;
        } else if (args[i - 1].equals("-l")) {
            logFilename = arg;
            continue;
        } else if (args[i - 1].equals("-o")) {
            outputFilename = arg;
            continue;
        }

        if (arg.equals("-h") || arg.equals("-help") || arg.equals("--help")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            showHelp = true;
        } else if (arg.equals("-license")) {
            license();
            System.exit(1);
        } else if (arg.equals("-s")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            silent = true;
        } else if (arg.equals("-nolog")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            silenceStdErr = true;
        } else if (arg.equals("-v")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            verbosity++;
        } else if (arg.equals("-vv")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            verbosity += 2;
        } else if (arg.equals("-vvv")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            verbosity += 3;
        } else if (arg.equals("-dr")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            dryrun = true;
        } else if (arg.startsWith("--")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            k = arg.substring(2);
        } else if (k != null) {
            if (k.contains("-")) {
                k = k.replaceAll("-", "_");
            }
            if (confVals.containsKey(k)) {
                try {
                    VarValue val = confVals.get(k);
                    if (val.getClass().equals(VarList.class)) {
                        ((VarList) val).add(VarValue.parseStringRaw(arg));
                    } else {
                        VarList list = new VarList();
                        list.add(val);
                        list.add(VarValue.parseStringRaw(arg));
                        confVals.put(k, list);
                    }
                } catch (VarTypeException e) {
                    System.err.println("Error setting variable: " + k + " => " + arg);
                    System.exit(1);
                    ;
                }
            } else {
                confVals.put(k, VarValue.parseStringRaw(arg));
            }
            k = null;
        } else if (arg.charAt(0) != '-') {
            targets.add(arg);
        }
    }
    if (k != null) {
        if (k.contains("-")) {
            k = k.replaceAll("-", "_");
        }
        confVals.put(k, VarBool.TRUE);
    }

    confVals.put("cgpipe.loglevel", new VarInt(verbosity));

    if (fname == null) {
        usage();
        System.exit(1);
    }

    if (!showHelp) {
        switch (verbosity) {
        case 0:
            SimpleFileLoggerImpl.setLevel(Level.INFO);
            break;
        case 1:
            SimpleFileLoggerImpl.setLevel(Level.DEBUG);
            break;
        case 2:
            SimpleFileLoggerImpl.setLevel(Level.TRACE);
            break;
        case 3:
        default:
            SimpleFileLoggerImpl.setLevel(Level.ALL);
            break;
        }
    } else {
        SimpleFileLoggerImpl.setLevel(Level.FATAL);
    }

    SimpleFileLoggerImpl.setSilent(silenceStdErr || showHelp);

    Log log = LogFactory.getLog(CGPipe.class);
    log.info("Starting new run: " + fname);

    if (logFilename != null) {
        confVals.put("cgpipe.log", new VarString(logFilename));
    }

    if (System.getenv("CGPIPE_DRYRUN") != null && !System.getenv("CGPIPE_DRYRUN").equals("")) {
        dryrun = true;
    }

    JobRunner runner = null;
    try {
        // Load config values from global config. 
        RootContext root = new RootContext();
        loadInitFiles(root);

        // Load settings from environment variables.
        root.loadEnvironment();

        // Set cmd-line arguments
        if (silent) {
            root.setOutputStream(null);
        }

        if (outputFilename != null) {
            outputStream = new PrintStream(new FileOutputStream(outputFilename));
            root.setOutputStream(outputStream);
        }

        for (String k1 : confVals.keySet()) {
            log.info("config: " + k1 + " => " + confVals.get(k1).toString());
        }

        root.update(confVals);
        root.set("cgpipe.procs", new VarInt(Runtime.getRuntime().availableProcessors()));

        // update the URL Source loader configs
        SourceLoader.updateRemoteHandlers(root.cloneString("cgpipe.remote"));

        // Now check for help, only after we've setup the remote handlers...
        if (showHelp) {
            try {
                Parser.showHelp(fname);
                System.exit(0);
            } catch (IOException e) {
                System.err.println("Unable to find pipeline: " + fname);
                System.exit(1);
            }
        }

        // Set the global config values
        //         globalConfig.putAll(root.cloneValues());

        // Parse the AST and run it
        Parser.exec(fname, root);

        // Load the job runner *after* we execute the script to capture any config changes
        runner = JobRunner.load(root, dryrun);

        // find a build-target, and submit the job(s) to a runner
        if (targets.size() > 0) {
            for (String target : targets) {
                log.debug("building: " + target);

                BuildTarget initTarget = root.build(target);
                if (initTarget != null) {
                    runner.submitAll(initTarget, root);
                } else {
                    System.out.println("CGPIPE ERROR: Unable to find target: " + target);
                }
            }
        } else {
            BuildTarget initTarget = root.build();
            if (initTarget != null) {
                runner.submitAll(initTarget, root);
                // Leave this commented out - it should be allowed to run cgpipe scripts w/o a target defined (testing)
                //            } else {
                //               System.out.println("CGPIPE ERROR: Unable to find default target");
            }
        }
        runner.done();

        if (outputStream != null) {
            outputStream.close();
        }

    } catch (ASTParseException | ASTExecException | RunnerException | FileNotFoundException e) {
        if (outputStream != null) {
            outputStream.close();
        }
        if (runner != null) {
            runner.abort();
        }

        if (e.getClass().equals(ExitException.class)) {
            System.exit(((ExitException) e).getReturnCode());
        }

        System.out.println("CGPIPE ERROR " + e.getMessage());
        if (verbosity > 0) {
            e.printStackTrace();
        }
        System.exit(1);
    }
}