Example usage for java.lang String split

List of usage examples for java.lang String split

Introduction

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

Prototype

public String[] split(String regex) 

Source Link

Document

Splits this string around matches of the given regular expression.

Usage

From source file:com.xiangzhurui.util.ftp.FTPClientExample.java

public static void main(String[] args) throws UnknownHostException {
    boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false,
            hidden = false;//from   w w  w.ja  v a  2  s .  c  om
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false, mdtm = false, saveUnparseable = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;
    String encoding = null;
    String serverTimeZoneId = null;
    String displayTimeZoneId = null;
    String serverType = null;
    String defaultDateFormat = null;
    String recentDateFormat = null;

    int base = 0;
    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        } else if (args[base].equals("-b")) {
            binaryTransfer = true;
        } else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-E")) {
            encoding = args[++base];
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-m")) {
            mdtm = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-S")) {
            serverType = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-U")) {
            saveUnparseable = true;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-y")) {
            defaultDateFormat = args[++base];
        } else if (args[base].equals("-Y")) {
            recentDateFormat = args[++base];
        } else if (args[base].equals("-Z")) {
            serverTimeZoneId = args[++base];
        } else if (args[base].equals("-z")) {
            displayTimeZoneId = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String[] parts = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        if (args.length > 0) {
            System.err.println("Actual Parameters: " + Arrays.toString(args));
        }
        System.err.println(USAGE);
        System.exit(1);
    }

    String server = args[base++];
    int port = 0;
    String[] parts = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String[] prot = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    if (encoding != null) {
        ftp.setControlEncoding(encoding);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    final FTPClientConfig config;
    if (serverType != null) {
        config = new FTPClientConfig(serverType);
    } else {
        config = new FTPClientConfig();
    }
    config.setUnparseableEntries(saveUnparseable);
    if (defaultDateFormat != null) {
        config.setDefaultDateFormatStr(defaultDateFormat);
    }
    if (recentDateFormat != null) {
        config.setRecentDateFormatStr(recentDateFormat);
    }
    ftp.configure(config);

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to
        // verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should
            // default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);

            ftp.storeFile(remote, input);

            input.close();
        }
        // Allow multiple list types for single invocation
        else if (listFiles || mlsd || mdtm || mlst || listNames) {
            if (mlsd) {
                for (FTPFile f : ftp.mlistDir(remote)) {
                    System.out.println(f.getRawListing());
                    System.out.println(f.toFormattedString(displayTimeZoneId));
                }
            }
            if (mdtm) {
                FTPFile f = ftp.mdtmFile(remote);
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString(displayTimeZoneId));
            }
            if (mlst) {
                FTPFile f = ftp.mlistFile(remote);
                if (f != null) {
                    System.out.println(f.toFormattedString(displayTimeZoneId));
                }
            }
            if (listNames) {
                for (String s : ftp.listNames(remote)) {
                    System.out.println(s);
                }
            }
            // Do this last because it changes the client
            if (listFiles) {
                if (lenient || serverTimeZoneId != null) {
                    config.setLenientFutureDates(lenient);
                    if (serverTimeZoneId != null) {
                        config.setServerTimeZoneId(serverTimeZoneId);
                    }
                    ftp.configure(config);
                }

                for (FTPFile f : ftp.listFiles(remote)) {
                    System.out.println(f.getRawListing());
                    System.out.println(f.toFormattedString(displayTimeZoneId));
                }
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    // Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                // Command listener has already printed the output
                // for(String s : com.xzr.practice.util.ftp.getReplyStrings()) {
                // System.out.println(s);
                // }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftp.retrieveFile(remote, output);

            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:demo.FTP.FTPClientExample.java

public static void main(String[] args) throws UnknownHostException {
    boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false,
            hidden = false;//from   ww w. j  a va2 s  .  c  o m
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false, mdtm = false, saveUnparseable = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;
    String encoding = null;
    String serverTimeZoneId = null;
    String displayTimeZoneId = null;
    String serverType = null;
    String defaultDateFormat = null;
    String recentDateFormat = null;

    int base = 0;
    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        } else if (args[base].equals("-b")) {
            binaryTransfer = true;
        } else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-E")) {
            encoding = args[++base];
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-m")) {
            mdtm = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
            System.out.println("protocal:" + protocol);
        } else if (args[base].equals("-S")) {
            serverType = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-U")) {
            saveUnparseable = true;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-y")) {
            defaultDateFormat = args[++base];
        } else if (args[base].equals("-Y")) {
            recentDateFormat = args[++base];
        } else if (args[base].equals("-Z")) {
            serverTimeZoneId = args[++base];
        } else if (args[base].equals("-z")) {
            displayTimeZoneId = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        if (args.length > 0) {
            System.err.println("Actual Parameters: " + Arrays.toString(args));
        }
        System.err.println(USAGE);
        System.exit(1);
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
        System.out.println("server:" + server);
        System.out.println("port:" + port);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
        System.out.println("username:" + username);
        System.out.println("password:" + password);
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    if (encoding != null) {
        ftp.setControlEncoding(encoding);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    final FTPClientConfig config;
    if (serverType != null) {
        config = new FTPClientConfig(serverType);
    } else {
        config = new FTPClientConfig();
    }
    config.setUnparseableEntries(saveUnparseable);
    if (defaultDateFormat != null) {
        config.setDefaultDateFormatStr(defaultDateFormat);
    }
    if (recentDateFormat != null) {
        config.setRecentDateFormatStr(recentDateFormat);
    }
    ftp.configure(config);

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);

            ftp.storeFile(remote, input);

            input.close();
        }
        // Allow multiple list types for single invocation
        else if (listFiles || mlsd || mdtm || mlst || listNames) {
            if (mlsd) {
                for (FTPFile f : ftp.mlistDir(remote)) {
                    System.out.println(f.getRawListing());
                    System.out.println(f.toFormattedString(displayTimeZoneId));
                }
            }
            if (mdtm) {
                FTPFile f = ftp.mdtmFile(remote);
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString(displayTimeZoneId));
            }
            if (mlst) {
                FTPFile f = ftp.mlistFile(remote);
                if (f != null) {
                    System.out.println(f.toFormattedString(displayTimeZoneId));
                }
            }
            if (listNames) {
                for (String s : ftp.listNames(remote)) {
                    System.out.println(s);
                }
            }
            // Do this last because it changes the client
            if (listFiles) {
                if (lenient || serverTimeZoneId != null) {
                    config.setLenientFutureDates(lenient);
                    if (serverTimeZoneId != null) {
                        config.setServerTimeZoneId(serverTimeZoneId);
                    }
                    ftp.configure(config);
                }

                for (FTPFile f : ftp.listFiles(remote)) {
                    System.out.println(f.getRawListing());
                    System.out.println(f.toFormattedString(displayTimeZoneId));
                }
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    //                        Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                //                  Command listener has already printed the output
                //                    for(String s : ftp.getReplyStrings()) {
                //                        System.out.println(s);
                //                    }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftp.retrieveFile(remote, output);

            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:com.ikanow.infinit.e.utility.MongoIndexerMain.java

/**
 * This is just a placeholder to invoke MongoDocumentTxfer, MongoEventFeatureTxfer, or MongoEntityFeatureTxfer
 * @param args/*w  ww .  ja va  2s.  co  m*/
 * @throws ParseException 
 * @throws MongoException 
 * @throws NumberFormatException 
 * @throws IOException 
 */

public static void main(String[] args) {

    try {
        CommandLineParser cliParser = new BasicParser();
        Options allOps = new Options();
        // Fork
        allOps.addOption("d", "doc", false, "Document transfer");
        allOps.addOption("n", "entity", false, "Entity feature transfer");
        allOps.addOption("a", "assoc", false, "Association feature transfer");
        allOps.addOption("A", "associations", false, "Association feature transfer");
        // Common
        allOps.addOption("q", "query", true, "MongoDB query to select records to transfer");
        allOps.addOption("D", "delete", false,
                "Delete the records in both MongoDB and Elasticsearch (instead of transferring them)");
        allOps.addOption("c", "config", true, "Override the default config path");
        allOps.addOption("l", "limit", true, "Caps the number of records to act upon");
        allOps.addOption("s", "skip", true, "The record at which to start (not in delete mode)");
        allOps.addOption("r", "rebuild", false, "Rebuild the index before transferring");
        allOps.addOption("v", "verify", false,
                "Verifies the document indexes all exist | resync the entity frequencies (INTERNAL ONLY)");
        allOps.addOption("f", "features", false,
                "Updates features present in the queried documents (--doc only; INTERNAL ONLY)");
        allOps.addOption("C", "chunks", true,
                "Loop over chunks, '--chunks all' for all chunks, '--chunks A,B,..' for specific chunks, '--chunks +A' for all chunks after A (currently -doc only)");

        CommandLine cliOpts = cliParser.parse(allOps, args);

        //Set up common parameters

        String configOverride = null;
        String query = null;
        String chunksDescription = null;
        boolean bDelete = false;
        boolean bRebuildIndex = false;
        boolean bVerifyIndex = false;
        boolean bUpdateFeatures = false;
        int nLimit = 0;
        int nSkip = 0;
        if (cliOpts.hasOption("config")) {
            configOverride = (String) cliOpts.getOptionValue("config");
        }
        if (cliOpts.hasOption("query")) {
            query = (String) cliOpts.getOptionValue("query");
        }
        if (cliOpts.hasOption("delete")) {
            bDelete = true;
        }
        if (cliOpts.hasOption("limit")) {
            try {
                nLimit = Integer.parseInt((String) cliOpts.getOptionValue("limit"));
            } catch (Exception e) {
                System.out.println("Error parsing --limit: " + (String) cliOpts.getOptionValue("limit"));
                query = null; // exit in if clause below
            }
        }
        if (cliOpts.hasOption("skip")) {
            try {
                nSkip = Integer.parseInt((String) cliOpts.getOptionValue("skip"));
            } catch (Exception e) {
                System.out.println("Error parsing --skip: " + (String) cliOpts.getOptionValue("skip"));
                query = null; // exit in if clause below
            }
        }
        if (cliOpts.hasOption("rebuild")) {
            bRebuildIndex = true;
        }
        if (cliOpts.hasOption("features")) {
            bUpdateFeatures = true;
        }
        if (cliOpts.hasOption("verify")) {
            if (cliOpts.hasOption("doc") && !bRebuildIndex) {
                bVerifyIndex = true; // (doc only)
            } else if (cliOpts.hasOption("entity")) {
                bVerifyIndex = true; // (ents only)               
            }
        }
        if (cliOpts.hasOption("chunks")) {
            if (bDelete) {
                System.out.println("Can't specify --chunks in conjunction with --delete");
                query = null; // exit in if clause below
            } else if ((nSkip != 0) || (nLimit != 0)) {
                System.out.println("Can't specify --chunks in conjunction with --skip or --limit");
                query = null; // exit in if clause below
            }
            chunksDescription = (String) cliOpts.getOptionValue("chunks");
        }
        if ((0 == args.length)
                || ((null == query) && (0 == nLimit) && !bVerifyIndex && (null == chunksDescription))) {
            System.out.println(
                    "Usage: MongoIndexerMain --doc|--assoc|--entity [--rebuild] [--verify] [--query <query>] [--chunks all|<chunklist>|+<chunk>] [--config <path>] [--delete] [--skip <start record>] [--limit <max records>]");
            if (args.length > 0) {
                System.out.println(
                        "(Note you must either specify a limit or a query or chunks - the query can be {} to get all records)");
            }
            System.exit(-1);
        }

        // Invoke appropriate manager to perform processing

        if (cliOpts.hasOption("doc")) {
            MongoDocumentTxfer.main(configOverride, query, bDelete, bRebuildIndex, bVerifyIndex,
                    bUpdateFeatures, nSkip, nLimit, chunksDescription);
        } else if (cliOpts.hasOption("assoc") || cliOpts.hasOption("association")) {
            MongoAssociationFeatureTxfer.main(configOverride, query, bDelete, bRebuildIndex, nSkip, nLimit,
                    chunksDescription);
        } else if (cliOpts.hasOption("entity")) {
            if (bVerifyIndex) {
                String[] dbDotColl = query.split("\\.");
                MongoEntitySyncFreq.syncFreq(dbDotColl[0], dbDotColl[1], configOverride);
            } else {
                MongoEntityFeatureTxfer.main(configOverride, query, bDelete, bRebuildIndex, nSkip, nLimit,
                        chunksDescription);
            }
        } else {
            System.out.println(
                    "Usage: MongoIndexerMain --doc|--assoc|--entity [--rebuild] [--query <query>] [--config <path>] [--delete] [--skip <start record>] [--limit <max records>]");
            System.exit(-1);
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    main_completed = false;//from  w  w w. j  a  v a 2s. c o m

    Options options = new Options();
    options.addOption(Option.builder("?").desc("Print this message").longOpt("help").build());
    options.addOption(Option.builder("n").hasArg().desc("C++ namespace for newly generated classes.")
            .longOpt("namespace").build());
    options.addOption(
            Option.builder("c").hasArgs().desc("Single Java class to extract.").longOpt("classes").build());
    options.addOption(
            Option.builder("p").hasArgs().desc("Java Package prefix to extract").longOpt("packages").build());
    options.addOption(Option.builder("o").hasArg().desc("Output C++ source file.").longOpt("output").build());
    options.addOption(Option.builder("j").hasArg().desc("Input jar file").longOpt("jar").build());
    options.addOption(Option.builder("h").hasArg().desc("Output C++ header file.").longOpt("header").build());
    options.addOption(Option.builder("l").hasArg()
            .desc("Maximum limit on classes to extract from jars.[default=200]").longOpt("limit").build());
    options.addOption(Option.builder("v").desc("enable verbose output").longOpt("verbose").build());
    options.addOption(Option.builder().hasArg().desc("Classes per output file.[default=10]")
            .longOpt(CLASSESPEROUTPUT).build());
    options.addOption(Option.builder().hasArgs().desc(
            "Comma seperated list of nativeclass=javaclass native where nativeclass will be generated as an extension/implementation of the java class.")
            .longOpt("natives").build());
    options.addOption(Option.builder().hasArg()
            .desc("library name for System.loadLibrary(...) for native extension classes")
            .longOpt("loadlibname").build());
    String output = null;
    String header = null;
    String jar = null;
    Set<String> classnamesToFind = null;
    Set<String> packageprefixes = null;
    String loadlibname = null;

    Map<String, String> nativesNameMap = null;
    Map<String, Class> nativesClassMap = null;
    int limit = DEFAULT_LIMIT;
    int classes_per_file = 10;
    List<Class> classes = new ArrayList<>();

    String limitstring = Integer.toString(limit);

    try {
        // parse the command line arguments
        System.out.println("args = " + Arrays.toString(args));
        CommandLine line = new DefaultParser().parse(options, args);
        loadlibname = line.getOptionValue("loadlibname");
        verbose = line.hasOption("verbose");
        if (line.hasOption(CLASSESPEROUTPUT)) {
            String cpoStr = line.getOptionValue(CLASSESPEROUTPUT);
            try {
                int cpoI = Integer.valueOf(cpoStr);
                classes_per_file = cpoI;
            } catch (Exception e) {
                System.err.println("Option for " + CLASSESPEROUTPUT + "=\"" + cpoStr + "\"");
                printHelpAndExit(options, args);
            }
        }

        if (line.hasOption("natives")) {
            String natives[] = line.getOptionValues("natives");
            if (verbose) {
                System.out.println("natives = " + Arrays.toString(natives));
            }
            nativesNameMap = new HashMap<>();
            nativesClassMap = new HashMap<>();
            for (int i = 0; i < natives.length; i++) {
                int eq_index = natives[i].indexOf('=');
                String nativeClassName = natives[i].substring(0, eq_index).trim();
                String javaClassName = natives[i].substring(eq_index + 1).trim();
                Class javaClass = null;
                try {
                    javaClass = Class.forName(javaClassName);
                } catch (ClassNotFoundException e) {
                    //e.printStackTrace();
                    System.err.println("Class for " + javaClassName
                            + " not found. (It may be found later in jar if specified.)");
                }
                nativesNameMap.put(javaClassName, nativeClassName);
                if (javaClass != null) {
                    nativesClassMap.put(nativeClassName, javaClass);
                    if (!classes.contains(javaClass)) {
                        classes.add(javaClass);
                    }
                }
            }
        }
        //            // validate that block-size has been set
        //            if (line.hasOption("block-size")) {
        //                // print the value of block-size
        //                if(verbose) System.out.println(line.getOptionValue("block-size"));
        //            }
        jar = line.getOptionValue("jar", jar);
        if (verbose) {
            System.out.println("jar = " + jar);
        }
        if (null != jar) {
            if (jar.startsWith("~/")) {
                jar = new File(new File(getHomeDir()), jar.substring(2)).getCanonicalPath();
            }
            if (jar.startsWith("./")) {
                jar = new File(new File(getCurrentDir()), jar.substring(2)).getCanonicalPath();
            }
            if (jar.startsWith("../")) {
                jar = new File(new File(getCurrentDir()).getParentFile(), jar.substring(3)).getCanonicalPath();
            }
        }
        if (line.hasOption("classes")) {
            classnamesToFind = new HashSet<String>();
            String classStrings[] = line.getOptionValues("classes");
            if (verbose) {
                System.out.println("classStrings = " + Arrays.toString(classStrings));
            }
            classnamesToFind.addAll(Arrays.asList(classStrings));
            if (verbose) {
                System.out.println("classnamesToFind = " + classnamesToFind);
            }
        }
        //                if (!line.hasOption("namespace")) {
        //                    if (classname != null && classname.length() > 0) {
        //                        namespace = classname.toLowerCase().replace(".", "_");
        //                    } else if (jar != null && jar.length() > 0) {
        //                        int lastSep = jar.lastIndexOf(File.separator);
        //                        int start = Math.max(0, lastSep + 1);
        //                        int period = jar.indexOf('.', start + 1);
        //                        int end = Math.max(start + 1, period);
        //                        namespace = jar.substring(start, end).toLowerCase();
        //                        namespace = namespace.replace(" ", "_");
        //                        if (namespace.indexOf("-") > 0) {
        //                            namespace = namespace.substring(0, namespace.indexOf("-"));
        //                        }
        //                    }
        //                }

        namespace = line.getOptionValue("namespace", namespace);
        if (verbose) {
            System.out.println("namespace = " + namespace);
        }
        if (null != namespace) {
            output = namespace + ".cpp";
        }
        output = line.getOptionValue("output", output);
        if (verbose) {
            System.out.println("output = " + output);
        }
        if (null != output) {
            if (output.startsWith("~/")) {
                output = System.getProperty("user.home") + output.substring(1);
            }
            header = output.substring(0, output.lastIndexOf('.')) + ".h";
        } else {
            output = "out.cpp";
        }
        header = line.getOptionValue("header", header);
        if (verbose) {
            System.out.println("header = " + header);
        }
        if (null != header) {
            if (header.startsWith("~/")) {
                header = System.getProperty("user.home") + header.substring(1);
            }
        } else {
            header = "out.h";
        }

        if (line.hasOption("packages")) {
            packageprefixes = new HashSet<String>();
            packageprefixes.addAll(Arrays.asList(line.getOptionValues("packages")));
        }
        if (line.hasOption("limit")) {
            limitstring = line.getOptionValue("limit", Integer.toString(DEFAULT_LIMIT));
            limit = Integer.valueOf(limitstring);
        }
        if (line.hasOption("help")) {
            printHelpAndExit(options, args);
        }
    } catch (ParseException exp) {
        if (verbose) {
            System.out.println("Unexpected exception:" + exp.getMessage());
        }
        printHelpAndExit(options, args);
    }

    Set<Class> excludedClasses = new HashSet<>();
    Set<String> foundClassNames = new HashSet<>();
    excludedClasses.add(Object.class);
    excludedClasses.add(String.class);
    excludedClasses.add(void.class);
    excludedClasses.add(Void.class);
    excludedClasses.add(Class.class);
    excludedClasses.add(Enum.class);
    Set<String> packagesSet = new TreeSet<>();
    List<URL> urlsList = new ArrayList<>();
    String cp = System.getProperty("java.class.path");
    if (verbose) {
        System.out.println("System.getProperty(\"java.class.path\") = " + cp);
    }
    if (null != cp) {
        for (String cpe : cp.split(File.pathSeparator)) {
            if (verbose) {
                System.out.println("class path element = " + cpe);
            }
            File f = new File(cpe);
            if (f.isDirectory()) {
                urlsList.add(new URL("file:" + f.getCanonicalPath() + File.separator));
            } else if (cpe.endsWith(".jar")) {
                urlsList.add(new URL("jar:file:" + f.getCanonicalPath() + "!/"));
            }
        }
    }
    cp = System.getenv("CLASSPATH");
    if (verbose) {
        System.out.println("System.getenv(\"CLASSPATH\") = " + cp);
    }
    if (null != cp) {
        for (String cpe : cp.split(File.pathSeparator)) {
            if (verbose) {
                System.out.println("class path element = " + cpe);
            }
            File f = new File(cpe);
            if (f.isDirectory()) {
                urlsList.add(new URL("file:" + f.getCanonicalPath() + File.separator));
            } else if (cpe.endsWith(".jar")) {
                urlsList.add(new URL("jar:file:" + f.getCanonicalPath() + "!/"));
            }
        }
    }
    if (verbose) {
        System.out.println("urlsList = " + urlsList);
    }

    if (null != jar && jar.length() > 0) {
        Path jarPath = FileSystems.getDefault().getPath(jar);
        ZipInputStream zip = new ZipInputStream(Files.newInputStream(jarPath, StandardOpenOption.READ));

        URL jarUrl = new URL("jar:file:" + jarPath.toFile().getCanonicalPath() + "!/");
        urlsList.add(jarUrl);
        URL[] urls = urlsList.toArray(new URL[urlsList.size()]);
        if (verbose) {
            System.out.println("urls = " + Arrays.toString(urls));
        }
        URLClassLoader cl = URLClassLoader.newInstance(urls);
        for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
            // This ZipEntry represents a class. Now, what class does it represent?
            String entryName = entry.getName();
            if (verbose) {
                System.out.println("entryName = " + entryName);
            }

            if (!entry.isDirectory() && entryName.endsWith(".class")) {

                if (entryName.indexOf('$') >= 0) {
                    continue;
                }
                String classFileName = entry.getName().replace('/', '.');
                String className = classFileName.substring(0, classFileName.length() - ".class".length());
                if (classnamesToFind != null && classnamesToFind.size() > 0
                        && !classnamesToFind.contains(className)) {
                    if (verbose) {
                        System.out.println("skipping className=" + className + " because it does not found in="
                                + classnamesToFind);
                    }
                    continue;
                }
                try {
                    Class clss = cl.loadClass(className);
                    if (null != nativesClassMap && null != nativesNameMap
                            && nativesNameMap.containsKey(className)) {
                        nativesClassMap.put(nativesNameMap.get(className), clss);
                        if (!classes.contains(clss)) {
                            classes.add(clss);
                        }
                    }
                    if (packageprefixes != null && packageprefixes.size() > 0) {
                        if (null == clss.getPackage()) {
                            continue;
                        }
                        final String pkgName = clss.getPackage().getName();
                        boolean matchFound = false;
                        for (String prefix : packageprefixes) {
                            if (pkgName.startsWith(prefix)) {
                                matchFound = true;
                                break;
                            }
                        }
                        if (!matchFound) {
                            continue;
                        }
                    }
                    Package p = clss.getPackage();
                    if (null != p) {
                        packagesSet.add(clss.getPackage().getName());
                    }
                    if (!classes.contains(clss) && isAddableClass(clss, excludedClasses)) {
                        if (null != classnamesToFind && classnamesToFind.contains(className)
                                && !foundClassNames.contains(className)) {
                            foundClassNames.add(className);
                            if (verbose) {
                                System.out.println("foundClassNames = " + foundClassNames);
                            }
                        }
                        //                        if(verbose) System.out.println("clss = " + clss);
                        classes.add(clss);
                        //                        Class superClass = clss.getSuperclass();
                        //                        while (null != superClass
                        //                                && !classes.contains(superClass)
                        //                                && isAddableClass(superClass, excludedClasses)) {
                        //                            classes.add(superClass);
                        //                            superClass = superClass.getSuperclass();
                        //                        }
                    }
                } catch (ClassNotFoundException | NoClassDefFoundError ex) {
                    System.err.println(
                            "Caught " + ex.getClass().getName() + ":" + ex.getMessage() + " for className="
                                    + className + ", entryName=" + entryName + ", jarPath=" + jarPath);
                }
            }
        }
    }
    if (null != classnamesToFind) {
        if (verbose) {
            System.out.println("Checking classnames arguments");
        }
        for (String classname : classnamesToFind) {
            if (verbose) {
                System.out.println("classname = " + classname);
            }
            if (foundClassNames.contains(classname)) {
                if (verbose) {
                    System.out.println("foundClassNames.contains(" + classname + ")");
                }
                continue;
            }
            try {
                if (classes.contains(Class.forName(classname))) {
                    if (verbose) {
                        System.out.println("Classes list already contains:  " + classname);
                    }
                    continue;
                }
            } catch (Exception e) {

            }

            if (null != classname && classname.length() > 0) {
                urlsList.add(new URL("file://" + System.getProperty("user.dir") + "/"));

                URL[] urls = urlsList.toArray(new URL[urlsList.size()]);
                if (verbose) {
                    System.out.println("urls = " + Arrays.toString(urls));
                }
                URLClassLoader cl = URLClassLoader.newInstance(urls);
                Class c = null;
                try {
                    c = cl.loadClass(classname);
                } catch (ClassNotFoundException e) {
                    System.err.println("Class " + classname + " not found ");
                }
                if (verbose) {
                    System.out.println("c = " + c);
                }
                if (null == c) {
                    try {
                        c = ClassLoader.getSystemClassLoader().loadClass(classname);
                    } catch (ClassNotFoundException e) {
                        if (verbose) {
                            System.out.println("System ClassLoader failed to find " + classname);
                        }
                    }
                }
                if (null != c) {
                    classes.add(c);
                } else {
                    System.err.println("Class " + classname + " not found");
                }
            }
        }
        if (verbose) {
            System.out.println("Finished checking classnames arguments");
        }
    }
    if (classes == null || classes.size() < 1) {
        if (null == nativesClassMap || nativesClassMap.keySet().size() < 1) {
            System.err.println("No Classes specified or found.");
            System.exit(1);
        }
    }
    if (verbose) {
        System.out.println("Classes found = " + classes.size());
    }
    if (classes.size() > limit) {
        System.err.println("limit=" + limit);
        System.err.println(
                "Too many classes please use -c or -p options to limit classes or -l to increase limit.");
        if (verbose) {
            System.out.println("packagesSet = " + packagesSet);
        }
        System.exit(1);
    }
    List<Class> newClasses = new ArrayList<Class>();
    for (Class clss : classes) {
        Class superClass = clss.getSuperclass();
        while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass)
                && isAddableClass(superClass, excludedClasses)) {
            newClasses.add(superClass);
            superClass = superClass.getSuperclass();
        }
        try {
            Field fa[] = clss.getDeclaredFields();
            for (Field f : fa) {
                if (Modifier.isPublic(f.getModifiers())) {
                    Class fClass = f.getType();
                    if (!classes.contains(fClass) && !newClasses.contains(fClass)
                            && isAddableClass(fClass, excludedClasses)) {
                        newClasses.add(fClass);
                    }
                }
            }
        } catch (NoClassDefFoundError e) {
            e.printStackTrace();
        }
        for (Method m : clss.getDeclaredMethods()) {
            if (m.isSynthetic()) {
                continue;
            }
            if (!Modifier.isPublic(m.getModifiers()) || Modifier.isAbstract(m.getModifiers())) {
                continue;
            }
            Class retType = m.getReturnType();
            if (verbose) {
                System.out.println("Checking dependancies for Method = " + m);
            }
            if (!classes.contains(retType) && !newClasses.contains(retType)
                    && isAddableClass(retType, excludedClasses)) {
                newClasses.add(retType);
                superClass = retType.getSuperclass();
                while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass)
                        && isAddableClass(superClass, excludedClasses)) {
                    newClasses.add(superClass);
                    superClass = superClass.getSuperclass();
                }
            }
            for (Class paramType : m.getParameterTypes()) {
                if (!classes.contains(paramType) && !newClasses.contains(paramType)
                        && isAddableClass(paramType, excludedClasses)) {
                    newClasses.add(paramType);
                    superClass = paramType.getSuperclass();
                    while (null != superClass && !classes.contains(superClass)
                            && !newClasses.contains(superClass) && !excludedClasses.contains(superClass)) {
                        newClasses.add(superClass);
                        superClass = superClass.getSuperclass();
                    }
                }
            }
        }
    }
    if (null != nativesClassMap) {
        for (Class clss : nativesClassMap.values()) {
            if (null != clss) {
                Class superClass = clss.getSuperclass();
                while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass)
                        && !excludedClasses.contains(superClass)) {
                    newClasses.add(superClass);
                    superClass = superClass.getSuperclass();
                }
            }
        }
    }
    if (verbose) {
        System.out.println("Dependency classes needed = " + newClasses.size());
    }
    classes.addAll(newClasses);
    List<Class> newOrderClasses = new ArrayList<>();
    for (Class clss : classes) {
        if (newOrderClasses.contains(clss)) {
            continue;
        }
        Class superClass = clss.getSuperclass();
        Stack<Class> stack = new Stack<>();
        while (null != superClass && !newOrderClasses.contains(superClass)
                && !superClass.equals(java.lang.Object.class)) {
            stack.push(superClass);
            superClass = superClass.getSuperclass();
        }
        while (!stack.empty()) {
            newOrderClasses.add(stack.pop());
        }
        newOrderClasses.add(clss);
    }
    classes = newOrderClasses;
    if (verbose) {
        System.out.println("Total number of classes = " + classes.size());
        System.out.println("classes = " + classes);
    }

    String forward_header = header.substring(0, header.lastIndexOf('.')) + "_fwd.h";
    Map<String, String> map = new HashMap<>();
    map.put(JAR, jar != null ? jar : "");
    map.put("%CLASSPATH_PREFIX%",
            getCurrentDir() + ((jar != null)
                    ? (File.pathSeparator + ((new File(jar).getCanonicalPath()).replace("\\", "\\\\")))
                    : ""));
    map.put("%FORWARD_HEADER%", forward_header);
    map.put("%HEADER%", header);
    map.put("%PATH_SEPERATOR%", File.pathSeparator);
    String tabs = "";
    String headerDefine = forward_header.substring(Math.max(0, forward_header.indexOf(File.separator)))
            .replace(".", "_");
    map.put(HEADER_DEFINE, headerDefine);
    map.put(NAMESPACE, namespace);
    if (null != nativesClassMap) {
        for (Entry<String, Class> e : nativesClassMap.entrySet()) {
            final Class javaClass = e.getValue();
            final String nativeClassName = e.getKey();
            try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassName + ".java"))) {
                if (javaClass.isInterface()) {
                    pw.println("public class " + nativeClassName + " implements " + javaClass.getCanonicalName()
                            + ", AutoCloseable{");
                } else {
                    pw.println("public class " + nativeClassName + " extends " + javaClass.getCanonicalName()
                            + " implements AutoCloseable{");
                }
                if (null != loadlibname && loadlibname.length() > 0) {
                    pw.println(TAB_STRING + "static {");
                    pw.println(TAB_STRING + TAB_STRING + "System.loadLibrary(\"" + loadlibname + "\");");
                    pw.println(TAB_STRING + "}");
                    pw.println();
                }
                pw.println(TAB_STRING + "public " + nativeClassName + "() {");
                pw.println(TAB_STRING + "}");
                pw.println();
                pw.println(TAB_STRING + "private long nativeAddress=0;");
                pw.println(TAB_STRING + "private boolean nativeDeleteOnClose=false;");
                pw.println();

                pw.println(TAB_STRING + "protected " + nativeClassName + "(final long nativeAddress) {");
                pw.println(TAB_STRING + TAB_STRING + "this.nativeAddress = nativeAddress;");
                pw.println(TAB_STRING + "}");

                pw.println(TAB_STRING + "private native void nativeDelete();");
                pw.println();
                pw.println(TAB_STRING + "@Override");
                pw.println(TAB_STRING + "public synchronized void  close() {");
                //                        pw.println(TAB_STRING + TAB_STRING + "if(nativeAddress != 0 && nativeDeleteOnClose) {");
                pw.println(TAB_STRING + TAB_STRING + "nativeDelete();");
                //                        pw.println(TAB_STRING + TAB_STRING + "}");
                //                        pw.println(TAB_STRING + TAB_STRING + "nativeAddress=0;");
                //                        pw.println(TAB_STRING + TAB_STRING + "nativeDeleteOnClose=false;");
                pw.println(TAB_STRING + "}");

                pw.println();
                pw.println(TAB_STRING + "protected void finalizer() {");
                pw.println(TAB_STRING + TAB_STRING + "close();");
                pw.println(TAB_STRING + "}");

                pw.println();
                Method ma[] = javaClass.getDeclaredMethods();
                for (Method m : ma) {
                    int modifiers = m.getModifiers();
                    if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                            && !Modifier.isStatic(modifiers)
                            //                                && !m.isDefault()
                            && !m.isSynthetic()) {
                        pw.println();
                        pw.println(TAB_STRING + "@Override");
                        String params = "";
                        for (int i = 0; i < m.getParameterTypes().length; i++) {
                            params += m.getParameterTypes()[i].getCanonicalName() + " param" + i;
                            if (i < m.getParameterTypes().length - 1) {
                                params += ",";
                            }
                        }
                        pw.println(TAB_STRING + "native public " + m.getReturnType().getCanonicalName() + " "
                                + m.getName() + "(" + params + ");");
                        //                                    + IntStream.range(0, m.getParameterTypes().length)
                        //                                    .mapToObj(i -> m.getParameterTypes()[i].getCanonicalName() + " param" + i)
                        //                                    .collect(Collectors.joining(",")) + ");");
                    }
                }
                pw.println("}");
            }
        }
    }
    try (PrintWriter pw = new PrintWriter(new FileWriter(forward_header))) {
        tabs = "";
        processTemplate(pw, map, "header_fwd_template_start.h", tabs);
        Class lastClass = null;
        for (int class_index = 0; class_index < classes.size(); class_index++) {
            Class clss = classes.get(class_index);
            String clssOnlyName = getCppClassName(clss);
            tabs = openClassNamespace(clss, pw, tabs, lastClass);
            tabs += TAB_STRING;
            pw.println(tabs + "class " + clssOnlyName + ";");
            tabs = tabs.substring(0, tabs.length() - 1);
            Class nextClass = (class_index < (classes.size() - 1)) ? classes.get(class_index + 1) : null;
            tabs = closeClassNamespace(clss, pw, tabs, nextClass);
            lastClass = clss;
        }
        processTemplate(pw, map, "header_fwd_template_end.h", tabs);
    }
    headerDefine = header.substring(Math.max(0, header.indexOf(File.separator))).replace(".", "_");
    map.put(HEADER_DEFINE, headerDefine);
    map.put(NAMESPACE, namespace);
    if (classes_per_file < 1) {
        classes_per_file = classes.size();
    }
    final int num_class_segments = (classes.size() > 1)
            ? ((classes.size() + classes_per_file - 1) / classes_per_file)
            : 1;
    String fmt = "%d";
    if (num_class_segments > 10) {
        fmt = "%02d";
    }
    if (num_class_segments > 100) {
        fmt = "%03d";
    }
    String header_file_base = header;
    if (header_file_base.endsWith(".h")) {
        header_file_base = header_file_base.substring(0, header_file_base.length() - 2);
    } else if (header_file_base.endsWith(".hh")) {
        header_file_base = header_file_base.substring(0, header_file_base.length() - 3);
    } else if (header_file_base.endsWith(".hpp")) {
        header_file_base = header_file_base.substring(0, header_file_base.length() - 4);
    }
    try (PrintWriter pw = new PrintWriter(new FileWriter(header))) {
        tabs = "";
        processTemplate(pw, map, HEADER_TEMPLATE_STARTH, tabs);
        for (int segment_index = 0; segment_index < num_class_segments; segment_index++) {
            String header_segment_file = header_file_base + String.format(fmt, segment_index) + ".h";
            pw.println("#include \"" + header_segment_file + "\"");
        }
        if (null != nativesClassMap) {
            tabs = TAB_STRING;
            for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                final Class javaClass = e.getValue();
                final String nativeClassName = e.getKey();
                pw.println();
                pw.println(tabs + "class " + nativeClassName + "Context;");
                pw.println();
                map.put(CLASS_NAME, nativeClassName);
                map.put("%BASE_CLASS_FULL_NAME%",
                        "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::"));
                map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object");
                processTemplate(pw, map, HEADER_CLASS_STARTH, tabs);
                tabs += TAB_STRING;
                pw.println(tabs + nativeClassName + "Context *context;");
                pw.println(tabs + nativeClassName + "();");
                pw.println(tabs + "~" + nativeClassName + "();");
                Method methods[] = javaClass.getDeclaredMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];
                    int modifiers = method.getModifiers();
                    if (!Modifier.isPublic(modifiers)) {
                        continue;
                    }
                    if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                            && !Modifier.isStatic(modifiers)
                            //                                && !method.isDefault()
                            && !method.isSynthetic()) {
                        pw.println(tabs + getNativeMethodCppDeclaration(method, javaClass));
                    }
                }
                pw.println(tabs + "void initContext(" + nativeClassName + "Context *ctx,bool isref);");
                pw.println(tabs + "void deleteContext();");
                tabs = tabs.substring(TAB_STRING.length());
                pw.println(tabs + "}; // end class " + nativeClassName);
            }
        }
        tabs = "";
        processTemplate(pw, map, HEADER_TEMPLATE_ENDH, tabs);
    }
    for (int segment_index = 0; segment_index < num_class_segments; segment_index++) {
        String header_segment_file = header_file_base + String.format(fmt, segment_index) + ".h";
        try (PrintWriter pw = new PrintWriter(new FileWriter(header_segment_file))) {
            tabs = "";
            //processTemplate(pw, map, HEADER_TEMPLATE_STARTH, tabs);
            pw.println("// Never include this file (" + header_segment_file + ") directly. include " + header
                    + " instead.");
            pw.println();
            Class lastClass = null;
            final int start_segment_index = segment_index * classes_per_file;
            final int end_segment_index = Math.min(segment_index * classes_per_file + classes_per_file,
                    classes.size());
            List<Class> classesSegList = classes.subList(start_segment_index, end_segment_index);
            pw.println();
            pw.println(tabs + "// start_segment_index = " + start_segment_index);
            pw.println(tabs + "// start_segment_index = " + end_segment_index);
            pw.println(tabs + "// segment_index = " + segment_index);
            pw.println(tabs + "// classesSegList=" + classesSegList);
            pw.println();
            for (int class_index = 0; class_index < classesSegList.size(); class_index++) {
                Class clss = classesSegList.get(class_index);
                pw.println();
                pw.println(tabs + "// class_index = " + class_index + " clss=" + clss);
                pw.println();
                String clssName = clss.getCanonicalName();
                tabs = openClassNamespace(clss, pw, tabs, lastClass);
                String clssOnlyName = getCppClassName(clss);
                map.put(CLASS_NAME, clssOnlyName);
                map.put("%BASE_CLASS_FULL_NAME%", classToCppBase(clss));
                map.put(OBJECT_CLASS_FULL_NAME, getCppRelativeName(Object.class, clss));
                tabs += TAB_STRING;
                processTemplate(pw, map, HEADER_CLASS_STARTH, tabs);
                tabs += TAB_STRING;

                Constructor constructors[] = clss.getDeclaredConstructors();
                if (!hasNoArgConstructor(constructors)) {
                    if (Modifier.isAbstract(clss.getModifiers()) || clss.isInterface()) {
                        pw.println(tabs + "protected:");
                        pw.println(tabs + clssOnlyName + "() {};");
                        pw.println(tabs + "public:");
                    } else {
                        if (constructors.length > 0) {
                            pw.println(tabs + "protected:");
                        }
                        pw.println(tabs + clssOnlyName + "();");
                        if (constructors.length > 0) {
                            pw.println(tabs + "public:");
                        }
                    }
                }
                for (Constructor c : constructors) {
                    if (c.getParameterTypes().length == 0 && Modifier.isProtected(c.getModifiers())) {
                        pw.println(tabs + "protected:");
                        pw.println(tabs + clssOnlyName + "();");
                        pw.println(tabs + "public:");
                    }
                    if (checkConstructor(c, clss, classes)) {
                        continue;
                    }

                    if (c.getParameterTypes().length == 1 && clss.isAssignableFrom(c.getParameterTypes()[0])) {
                        continue;
                    }
                    if (!Modifier.isPublic(c.getModifiers())) {
                        continue;
                    }
                    if (c.getParameterTypes().length == 1) {
                        if (c.getParameterTypes()[0].getName().equals(clss.getName())) {
                            //                                    if(verbose) System.out.println("skipping constructor.");
                            continue;
                        }
                    }

                    if (!checkParameters(c.getParameterTypes(), classes)) {
                        continue;
                    }
                    pw.println(
                            tabs + clssOnlyName + getCppParamDeclarations(c.getParameterTypes(), clss) + ";");
                    if (isConstructorToMakeEasy(c, clss)) {
                        pw.println(tabs + clssOnlyName
                                + getEasyCallCppParamDeclarations(c.getParameterTypes(), clss) + ";");
                    }
                }

                pw.println(tabs + "~" + clssOnlyName + "();");
                Field fa[] = clss.getDeclaredFields();
                for (int findex = 0; findex < fa.length; findex++) {
                    Field field = fa[findex];
                    if (addGetterMethod(field, clss, classes)) {
                        pw.println(tabs + getCppFieldGetterDeclaration(field, clss));
                    }
                    if (addSetterMethod(field, clss, classes)) {
                        pw.println(tabs + getCppFieldSetterDeclaration(field, clss));
                    }
                }
                Method methods[] = clss.getDeclaredMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];
                    if (!checkMethod(method, classes)) {
                        continue;
                    }
                    if ((method.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC) {
                        pw.println(tabs + getCppDeclaration(method, clss));
                    }
                    if (isArrayStringMethod(method)) {
                        pw.println(tabs + getCppModifiers(method.getModifiers())
                                + getCppType(method.getReturnType(), clss) + " " + fixMethodName(method)
                                + "(int argc,const char **argv);");
                    }
                    if (isMethodToMakeEasy(method)) {
                        pw.println(tabs + getEasyCallCppDeclaration(method, clss));
                    }
                }
                tabs = tabs.substring(TAB_STRING.length());
                pw.println(tabs + "}; // end class " + clssOnlyName);
                tabs = tabs.substring(0, tabs.length() - 1);
                Class nextClass = (class_index < (classesSegList.size() - 1))
                        ? classesSegList.get(class_index + 1)
                        : null;
                tabs = closeClassNamespace(clss, pw, tabs, nextClass);
                pw.println();
                lastClass = clss;
            }
            //processTemplate(pw, map, HEADER_TEMPLATE_ENDH, tabs);
        }
    }
    for (int segment_index = 0; segment_index < num_class_segments; segment_index++) {
        String output_segment_file = output;
        if (output_segment_file.endsWith(".cpp")) {
            output_segment_file = output_segment_file.substring(0, output_segment_file.length() - 4);
        } else if (output_segment_file.endsWith(".cc")) {
            output_segment_file = output_segment_file.substring(0, output_segment_file.length() - 3);
        }
        output_segment_file += "" + String.format(fmt, segment_index) + ".cpp";
        try (PrintWriter pw = new PrintWriter(new FileWriter(output_segment_file))) {
            tabs = "";
            if (segment_index < 1) {
                processTemplate(pw, map, "cpp_template_start_first.cpp", tabs);
            } else {
                processTemplate(pw, map, CPP_TEMPLATE_STARTCPP, tabs);
            }
            final int start_segment_index = segment_index * classes_per_file;
            final int end_segment_index = Math.min(segment_index * classes_per_file + classes_per_file,
                    classes.size());
            List<Class> classesSegList = classes.subList(start_segment_index, end_segment_index);
            pw.println();
            pw.println(tabs + "// start_segment_index = " + start_segment_index);
            pw.println(tabs + "// start_segment_index = " + end_segment_index);
            pw.println(tabs + "// segment_index = " + segment_index);
            pw.println(tabs + "// classesSegList=" + classesSegList);
            pw.println();
            Class lastClass = null;
            for (int class_index = 0; class_index < classesSegList.size(); class_index++) {
                Class clss = classesSegList.get(class_index);
                pw.println();
                pw.println(tabs + "// class_index = " + class_index + " clss=" + clss);
                pw.println();
                String clssName = clss.getCanonicalName();
                tabs = openClassNamespace(clss, pw, tabs, lastClass);
                String clssOnlyName = getCppClassName(clss);
                map.put(CLASS_NAME, clssOnlyName);
                map.put("%BASE_CLASS_FULL_NAME%", classToCppBase(clss));

                map.put(FULL_CLASS_NAME, clssName);
                String fcjs = classToJNISignature(clss);
                fcjs = fcjs.substring(1, fcjs.length() - 1);
                map.put(FULL_CLASS_JNI_SIGNATURE, fcjs);
                if (verbose) {
                    System.out.println("fcjs = " + fcjs);
                }
                map.put(OBJECT_CLASS_FULL_NAME, getCppRelativeName(Object.class, clss));
                map.put("%INITIALIZE_CONTEXT%", "");
                map.put("%INITIALIZE_CONTEXT_REF%", "");
                processTemplate(pw, map, CPP_START_CLASSCPP, tabs);
                Constructor constructors[] = clss.getDeclaredConstructors();

                if (!hasNoArgConstructor(constructors)) {
                    if (!Modifier.isAbstract(clss.getModifiers()) && !clss.isInterface()) {
                        pw.println(tabs + clssOnlyName + "::" + clssOnlyName + "() : " + classToCppBase(clss)
                                + "((jobject)NULL,false) {");
                        map.put(JNI_SIGNATURE, "()V");
                        map.put(CONSTRUCTOR_ARGS, "");
                        processTemplate(pw, map, CPP_NEWCPP, tabs);
                        pw.println(tabs + "}");
                        pw.println();
                    }

                }
                for (Constructor c : constructors) {
                    if (checkConstructor(c, clss, classes)) {
                        continue;
                    }
                    Class[] paramClasses = c.getParameterTypes();
                    pw.println(tabs + clssOnlyName + "::" + clssOnlyName
                            + getCppParamDeclarations(paramClasses, clss) + " : " + classToCppBase(clss)
                            + "((jobject)NULL,false) {");
                    tabs = tabs + TAB_STRING;
                    map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(paramClasses) + ")V");
                    map.put(CONSTRUCTOR_ARGS,
                            (paramClasses.length > 0 ? "," : "") + getCppParamNames(paramClasses));
                    processTemplate(pw, map, CPP_NEWCPP, tabs);
                    tabs = tabs.substring(0, tabs.length() - 1);
                    pw.println(tabs + "}");
                    pw.println();
                    if (isConstructorToMakeEasy(c, clss)) {
                        pw.println(tabs + clssOnlyName + "::" + clssOnlyName
                                + getEasyCallCppParamDeclarations(c.getParameterTypes(), clss) + " : "
                                + classToCppBase(clss) + "((jobject)NULL,false) {");
                        processTemplate(pw, map, "cpp_start_easy_constructor.cpp", tabs);
                        for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) {
                            Class paramClasse = paramClasses[paramIndex];
                            String parmName = getParamNameIn(paramClasse, paramIndex);
                            if (isString(paramClasse)) {
                                pw.println(tabs + "jstring " + parmName + " = env->NewStringUTF(easyArg_"
                                        + paramIndex + ");");
                            } else if (isPrimitiveArray(paramClasse)) {
                                String callString = getMethodCallString(paramClasse.getComponentType());
                                pw.println(tabs + getCppArrayType(paramClasse.getComponentType()) + " "
                                        + classToParamNameDecl(paramClasse, paramIndex) + "= env->New"
                                        + callString + "Array(easyArg_" + paramIndex + "_length);");
                                pw.println(tabs + "env->Set" + callString + "ArrayRegion("
                                        + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_"
                                        + paramIndex + "_length,easyArg_" + paramIndex + ");");
                            } else {
                                pw.println(tabs + getCppType(paramClasse, clss) + " "
                                        + classToParamNameDecl(paramClasse, paramIndex) + "= easyArg_"
                                        + paramIndex + ";");
                            }
                        }
                        processTemplate(pw, map, "cpp_new_easy_internals.cpp", tabs);
                        for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) {
                            Class paramClasse = paramClasses[paramIndex];
                            String parmName = getParamNameIn(paramClasse, paramIndex);
                            if (isString(paramClasse)) {
                                pw.println(tabs + "jobjectRefType ref_" + paramIndex
                                        + " = env->GetObjectRefType(" + parmName + ");");
                                pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {");
                                pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");");
                                pw.println(tabs + "}");
                            } else if (isPrimitiveArray(paramClasse)) {
                                String callString = getMethodCallString(paramClasse.getComponentType());
                                pw.println(tabs + "env->Get" + callString + "ArrayRegion("
                                        + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_"
                                        + paramIndex + "_length,easyArg_" + paramIndex + ");");
                                pw.println(tabs + "jobjectRefType ref_" + paramIndex
                                        + " = env->GetObjectRefType(" + parmName + ");");
                                pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {");
                                pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");");
                                pw.println(tabs + "}");
                            } else {

                            }
                        }
                        processTemplate(pw, map, "cpp_end_easy_constructor.cpp", tabs);
                        pw.println(tabs + "}");
                    }
                }

                pw.println();
                pw.println(tabs + "// Destructor for " + clssName);
                pw.println(tabs + clssOnlyName + "::~" + clssOnlyName + "() {");
                pw.println(tabs + "\t// Place-holder for later extensibility.");
                pw.println(tabs + "}");
                pw.println();
                Field fa[] = clss.getDeclaredFields();
                for (int findex = 0; findex < fa.length; findex++) {
                    Field field = fa[findex];
                    if (addGetterMethod(field, clss, classes)) {
                        pw.println();
                        pw.println(tabs + "// Field getter for " + field.getName());
                        pw.println(getCppFieldGetterDefinitionStart(tabs, clssOnlyName, field, clss));
                        map.put("%FIELD_NAME%", field.getName());
                        map.put(JNI_SIGNATURE, classToJNISignature(field.getType()));
                        Class returnClass = field.getType();
                        map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss));
                        map.put(METHOD_ARGS, "");
                        map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return");
                        map.put("%METHOD_CALL_TYPE%", getMethodCallString(returnClass));
                        map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss));
                        map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                        String retStore = isVoid(returnClass) ? ""
                                : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                        map.put("%METHOD_RETURN_STORE%", retStore);
                        map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss));

                        if (Modifier.isStatic(field.getModifiers())) {
                            processTemplate(pw, map, "cpp_static_getfield.cpp", tabs);
                        } else {
                            processTemplate(pw, map, "cpp_getfield.cpp", tabs);
                        }

                        pw.println(tabs + "}");
                    }
                    if (addSetterMethod(field, clss, classes)) {
                        pw.println();
                        pw.println(tabs + "// Field setter for " + field.getName());
                        pw.println(getCppFieldSetterDefinitionStart(tabs, clssOnlyName, field, clss));
                        map.put("%FIELD_NAME%", field.getName());
                        map.put(JNI_SIGNATURE, classToJNISignature(field.getType()));
                        Class returnClass = void.class;
                        map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss));
                        Class[] paramClasses = new Class[] { field.getType() };
                        String methodArgs = getCppParamNames(paramClasses);
                        map.put(METHOD_ARGS, (paramClasses.length > 0 ? "," : "") + methodArgs);
                        map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return");
                        map.put("%METHOD_CALL_TYPE%", getMethodCallString(field.getType()));
                        map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss));
                        map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                        String retStore = isVoid(returnClass) ? ""
                                : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                        map.put("%METHOD_RETURN_STORE%", retStore);
                        map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss));

                        if (Modifier.isStatic(field.getModifiers())) {
                            processTemplate(pw, map, "cpp_static_setfield.cpp", tabs);
                        } else {
                            processTemplate(pw, map, "cpp_setfield.cpp", tabs);
                        }

                        pw.println(tabs + "}");
                    }
                }
                Method methods[] = clss.getDeclaredMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];

                    if (checkMethod(method, classes)) {
                        pw.println();
                        pw.println(getCppMethodDefinitionStart(tabs, clssOnlyName, method, clss));
                        map.put(METHOD_NAME, method.getName());
                        if (fixMethodName(method).contains("equals2")) {
                            if (verbose) {
                                System.out.println("debug me");
                            }
                        }
                        map.put("%JAVA_METHOD_NAME%", method.getName());
                        Class[] paramClasses = method.getParameterTypes();
                        String methodArgs = getCppParamNames(paramClasses);
                        map.put(METHOD_ARGS, (paramClasses.length > 0 ? "," : "") + methodArgs);
                        Class returnClass = method.getReturnType();
                        map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(paramClasses) + ")"
                                + classToJNISignature(returnClass));
                        map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss));
                        map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return");
                        map.put("%METHOD_CALL_TYPE%", getMethodCallString(returnClass));
                        map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss));
                        map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                        String retStore = isVoid(returnClass) ? ""
                                : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                        map.put("%METHOD_RETURN_STORE%", retStore);
                        map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss));
                        tabs += TAB_STRING;
                        if (!Modifier.isStatic(method.getModifiers())) {
                            processTemplate(pw, map, CPP_METHODCPP, tabs);
                        } else {
                            processTemplate(pw, map, CPP_STATIC_METHODCPP, tabs);
                        }
                        tabs = tabs.substring(0, tabs.length() - TAB_STRING.length());
                        pw.println(tabs + "}");
                        if (isArrayStringMethod(method)) {
                            map.put(METHOD_RETURN_STORE,
                                    isVoid(returnClass) ? "" : getCppType(returnClass, clss) + " returnVal=");
                            map.put(METHOD_RETURN_GET, isVoid(returnClass) ? "return ;" : "return returnVal;");
                            processTemplate(pw, map, CPP_EASY_STRING_ARRAY_METHODCPP, tabs);
                        } else if (isMethodToMakeEasy(method)) {
                            pw.println();
                            pw.println(tabs + "// Easy call alternative for " + method.getName());
                            pw.println(getEasyCallCppMethodDefinitionStart(tabs, clssOnlyName, method, clss));
                            tabs += TAB_STRING;
                            map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclareOut(returnClass, clss));
                            processTemplate(pw, map, "cpp_start_easy_method.cpp", tabs);
                            for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) {
                                Class paramClasse = paramClasses[paramIndex];
                                String parmName = getParamNameIn(paramClasse, paramIndex);
                                if (isString(paramClasse)) {
                                    pw.println(tabs + "jstring " + parmName + " = env->NewStringUTF(easyArg_"
                                            + paramIndex + ");");
                                } else if (isPrimitiveArray(paramClasse)) {
                                    String callString = getMethodCallString(paramClasse.getComponentType());
                                    pw.println(tabs + getCppArrayType(paramClasse.getComponentType()) + " "
                                            + classToParamNameDecl(paramClasse, paramIndex) + "= env->New"
                                            + callString + "Array(easyArg_" + paramIndex + "_length);");
                                    pw.println(tabs + "env->Set" + callString + "ArrayRegion("
                                            + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_"
                                            + paramIndex + "_length,easyArg_" + paramIndex + ");");
                                } else {
                                    pw.println(tabs + getCppType(paramClasse, clss) + " "
                                            + classToParamNameDecl(paramClasse, paramIndex) + "= easyArg_"
                                            + paramIndex + ";");
                                }
                            }
                            String methodArgsIn = getCppParamNamesIn(paramClasses);
                            String retStoreOut = isVoid(returnClass) ? ""
                                    : "retVal= (" + getMethodReturnOutVarType(returnClass, clss) + ") ";

                            pw.println(tabs + retStoreOut + fixMethodName(method) + "(" + methodArgsIn + ");");
                            for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) {
                                Class paramClasse = paramClasses[paramIndex];
                                String parmName = getParamNameIn(paramClasse, paramIndex);
                                if (isString(paramClasse)) {
                                    pw.println(tabs + "jobjectRefType ref_" + paramIndex
                                            + " = env->GetObjectRefType(" + parmName + ");");
                                    pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {");
                                    pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");");
                                    pw.println(tabs + "}");
                                } else if (isPrimitiveArray(paramClasse)) {
                                    String callString = getMethodCallString(paramClasse.getComponentType());
                                    pw.println(tabs + "env->Get" + callString + "ArrayRegion("
                                            + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_"
                                            + paramIndex + "_length,easyArg_" + paramIndex + ");");
                                    pw.println(tabs + "jobjectRefType ref_" + paramIndex
                                            + " = env->GetObjectRefType(" + parmName + ");");
                                    pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {");
                                    pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");");
                                    pw.println(tabs + "}");
                                } else {

                                }
                            }
                            processTemplate(pw, map, "cpp_end_easy_method.cpp", tabs);
                            if (!isVoid(returnClass)) {
                                pw.println(tabs + "return retVal;");
                            }
                            tabs = tabs.substring(TAB_STRING.length());
                            pw.println(tabs + "}");
                            pw.println();
                        }
                    }
                }
                processTemplate(pw, map, CPP_END_CLASSCPP, tabs);
                tabs = tabs.substring(0, tabs.length() - 1);
                Class nextClass = (class_index < (classesSegList.size() - 1))
                        ? classesSegList.get(class_index + 1)
                        : null;
                tabs = closeClassNamespace(clss, pw, tabs, nextClass);
                lastClass = clss;
            }

            if (segment_index < 1) {
                if (null != nativesClassMap) {
                    for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                        final Class javaClass = e.getValue();
                        final String nativeClassName = e.getKey();
                        map.put(CLASS_NAME, nativeClassName);
                        map.put(FULL_CLASS_NAME, nativeClassName);
                        map.put(FULL_CLASS_JNI_SIGNATURE, nativeClassName);
                        map.put("%BASE_CLASS_FULL_NAME%",
                                "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::"));
                        map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object");
                        map.put("%INITIALIZE_CONTEXT%", "context=NULL; initContext(NULL,false);");
                        map.put("%INITIALIZE_CONTEXT_REF%", "context=NULL; initContext(objref.context,true);");
                        tabs += TAB_STRING;

                        processTemplate(pw, map, CPP_START_CLASSCPP, tabs);
                        pw.println();
                        pw.println(tabs + nativeClassName + "::" + nativeClassName + "() : "
                                + getModifiedClassName(javaClass).replace(".", "::")
                                + "((jobject)NULL,false) {");
                        tabs += TAB_STRING;
                        pw.println(tabs + "context=NULL;");
                        pw.println(tabs + "initContext(NULL,false);");
                        map.put(JNI_SIGNATURE, "()V");
                        map.put(CONSTRUCTOR_ARGS, "");
                        processTemplate(pw, map, "cpp_new_native.cpp", tabs);
                        tabs = tabs.substring(TAB_STRING.length());
                        pw.println(tabs + "}");
                        pw.println();
                        pw.println(tabs + "// Destructor for " + nativeClassName);
                        pw.println(tabs + nativeClassName + "::~" + nativeClassName + "() {");
                        pw.println(tabs + TAB_STRING + "if(NULL != context) {");
                        pw.println(tabs + TAB_STRING + TAB_STRING + "deleteContext();");
                        pw.println(tabs + TAB_STRING + "}");
                        pw.println(tabs + TAB_STRING + "context=NULL;");
                        pw.println(tabs + "}");
                        pw.println();
                        //                            pw.println(tabs + "public:");
                        //                            pw.println(tabs + nativeClassName + "();");
                        //                            pw.println(tabs + "~" + nativeClassName + "();");
                        tabs = tabs.substring(TAB_STRING.length());
                        //                            Method methods[] = javaClass.getDeclaredMethods();
                        //                            for (int j = 0; j < methods.length; j++) {
                        //                                Method method = methods[j];
                        //                                int modifiers = method.getModifiers();
                        //                                if (!Modifier.isPublic(modifiers)) {
                        //                                    continue;
                        //                                }
                        //                                pw.println(tabs + getCppDeclaration(method, javaClass));
                        //                            }
                        //                            pw.println(tabs + "}; // end class " + nativeClassName);
                        processTemplate(pw, map, CPP_END_CLASSCPP, tabs);
                    }
                }
                processTemplate(pw, map, "cpp_template_end_first.cpp", tabs);
                tabs = "";
                if (null != nativesClassMap) {
                    pw.println("using namespace " + namespace + ";");
                    pw.println("#ifdef __cplusplus");
                    pw.println("extern \"C\" {");
                    pw.println("#endif");
                    int max_method_count = 0;
                    tabs = "";
                    for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                        final Class javaClass = e.getValue();
                        final String nativeClassName = e.getKey();
                        map.put(CLASS_NAME, nativeClassName);
                        map.put(FULL_CLASS_NAME, nativeClassName);
                        map.put("%BASE_CLASS_FULL_NAME%",
                                "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::"));
                        map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object");
                        map.put(FULL_CLASS_JNI_SIGNATURE, nativeClassName);
                        map.put(METHOD_ONFAIL, "return;");
                        Method methods[] = javaClass.getDeclaredMethods();
                        if (max_method_count < methods.length) {
                            max_method_count = methods.length;
                        }
                        for (int j = 0; j < methods.length; j++) {
                            Method method = methods[j];
                            int modifiers = method.getModifiers();
                            if (!Modifier.isPublic(modifiers)) {
                                continue;
                            }
                            if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                                    && !Modifier.isStatic(modifiers)
                                    //                                        && !method.isDefault()
                                    && !method.isSynthetic()) {
                                Class[] paramClasses = method.getParameterTypes();
                                String methodArgs = getCppParamNames(paramClasses);
                                map.put(METHOD_ARGS, methodArgs);
                                map.put(METHOD_NAME, method.getName());
                                Class returnClass = method.getReturnType();
                                String retStore = isVoid(returnClass) ? ""
                                        : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                                map.put(METHOD_ONFAIL, getOnFailString(returnClass, javaClass));
                                map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                                map.put("%METHOD_RETURN_STORE%", retStore);
                                map.put("%METHOD_RETURN_GET%",
                                        getMethodReturnGet(tabs, returnClass, javaClass));
                                pw.println();
                                String paramDecls = getCppParamDeclarations(paramClasses, javaClass);
                                String argsToAdd = method.getParameterTypes().length > 0
                                        ? "," + paramDecls.substring(1, paramDecls.length() - 1)
                                        : "";
                                pw.println("JNIEXPORT " + getCppType(returnClass, javaClass) + " JNICALL Java_"
                                        + nativeClassName + "_" + method.getName()
                                        + "(JNIEnv *env, jobject jthis" + argsToAdd + ") {");
                                tabs = TAB_STRING;
                                processTemplate(pw, map, "cpp_native_wrap.cpp", tabs);
                                tabs = tabs.substring(TAB_STRING.length());
                                pw.println("}");
                                pw.println();
                            }
                        }
                        pw.println("JNIEXPORT void JNICALL Java_" + nativeClassName
                                + "_nativeDelete(JNIEnv *env, jobject jthis) {");
                        tabs += TAB_STRING;
                        map.put(METHOD_ONFAIL, getOnFailString(void.class, javaClass));
                        processTemplate(pw, map, "cpp_native_delete.cpp", tabs);
                        tabs = tabs.substring(TAB_STRING.length());
                        pw.println(tabs + "}");
                        pw.println();
                    }
                    pw.println("#ifdef __cplusplus");
                    pw.println("} // end extern \"C\"");
                    pw.println("#endif");
                    map.put("%MAX_METHOD_COUNT%", Integer.toString(max_method_count + 1));
                    processTemplate(pw, map, "cpp_start_register_native.cpp", tabs);
                    for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                        final Class javaClass = e.getValue();
                        final String nativeClassName = e.getKey();
                        map.put(CLASS_NAME, nativeClassName);
                        map.put(FULL_CLASS_NAME, nativeClassName);
                        map.put("%BASE_CLASS_FULL_NAME%",
                                "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::"));
                        map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object");
                        processTemplate(pw, map, "cpp_start_register_native_class.cpp", tabs);
                        tabs += TAB_STRING;
                        Method methods[] = javaClass.getDeclaredMethods();
                        int method_number = 0;
                        for (int j = 0; j < methods.length; j++) {
                            Method method = methods[j];
                            int modifiers = method.getModifiers();
                            if (!Modifier.isPublic(modifiers)) {
                                continue;
                            }
                            if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                                    && !Modifier.isStatic(modifiers)
                                    //                                        && !method.isDefault()
                                    && !method.isSynthetic()) {
                                map.put("%METHOD_NUMBER%", Integer.toString(method_number));
                                map.put(METHOD_NAME, method.getName());

                                map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(method.getParameterTypes())
                                        + ")" + classToJNISignature(method.getReturnType()));
                                processTemplate(pw, map, "cpp_register_native_item.cpp", tabs);
                                method_number++;
                            }
                        }
                        map.put("%METHOD_NUMBER%", Integer.toString(method_number));
                        map.put(METHOD_NAME, "nativeDelete");
                        map.put(JNI_SIGNATURE, "()V");
                        processTemplate(pw, map, "cpp_register_native_item.cpp", tabs);
                        map.put("%NUM_NATIVE_METHODS%", Integer.toString(method_number));
                        processTemplate(pw, map, "cpp_end_register_native_class.cpp", tabs);
                        tabs = tabs.substring(TAB_STRING.length());
                    }
                    processTemplate(pw, map, "cpp_end_register_native.cpp", tabs);
                } else {
                    pw.println("// No Native classes : registerNativMethods not needed.");
                    pw.println("static void registerNativeMethods(JNIEnv *env) {}");
                }

            } else {
                processTemplate(pw, map, CPP_TEMPLATE_ENDCPP, tabs);
            }
        }
        if (null != nativesClassMap) {
            tabs = "";
            for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                String nativeClassName = e.getKey();
                File nativeClassHeaderFile = new File(
                        namespace.toLowerCase() + "_" + nativeClassName.toLowerCase() + ".h");
                map.put("%NATIVE_CLASS_HEADER%", nativeClassHeaderFile.getName());
                map.put(CLASS_NAME, nativeClassName);
                if (nativeClassHeaderFile.exists()) {
                    if (verbose) {
                        System.out.println("skipping " + nativeClassHeaderFile.getCanonicalPath()
                                + " since it already exists.");
                    }
                } else {
                    try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassHeaderFile))) {
                        processTemplate(pw, map, "header_native_imp.h", tabs);
                    }
                }
                File nativeClassCppFile = new File(
                        namespace.toLowerCase() + "_" + nativeClassName.toLowerCase() + ".cpp");
                if (nativeClassCppFile.exists()) {
                    if (verbose) {
                        System.out.println("skipping " + nativeClassCppFile.getCanonicalPath()
                                + " since it already exists.");
                    }
                } else {
                    try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassCppFile))) {
                        processTemplate(pw, map, "cpp_native_imp_start.cpp", tabs);
                        Class javaClass = e.getValue();
                        Method methods[] = javaClass.getDeclaredMethods();
                        int method_number = 0;
                        for (int j = 0; j < methods.length; j++) {
                            Method method = methods[j];
                            int modifiers = method.getModifiers();
                            if (!Modifier.isPublic(modifiers)) {
                                continue;
                            }
                            if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                                    && !Modifier.isStatic(modifiers)
                                    //                                        && !method.isDefault()
                                    && !method.isSynthetic()) {
                                Class[] paramClasses = method.getParameterTypes();
                                //                                    String methodArgs = getCppParamNames(paramClasses);
                                String paramDecls = getCppParamDeclarations(paramClasses, javaClass);
                                String methodArgs = method.getParameterTypes().length > 0
                                        ? paramDecls.substring(1, paramDecls.length() - 1)
                                        : "";
                                map.put(METHOD_ARGS, methodArgs);
                                map.put(METHOD_NAME, method.getName());
                                Class returnClass = method.getReturnType();
                                String retStore = isVoid(returnClass) ? ""
                                        : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                                map.put(METHOD_ONFAIL, getOnFailString(returnClass, javaClass));
                                map.put("%RETURN_TYPE%", getCppType(returnClass, javaClass));
                                map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                                map.put("%METHOD_RETURN_STORE%", retStore);
                                map.put("%METHOD_RETURN_GET%",
                                        getMethodReturnGet(tabs, returnClass, javaClass));
                                processTemplate(pw, map, "cpp_native_imp_stub.cpp", tabs);
                            }
                        }
                        processTemplate(pw, map, "cpp_native_imp_end.cpp", tabs);
                    }
                }
            }
        }
    }

    main_completed = true;
}

From source file:com.ywh.train.Test.java

public static void main(String[] args) throws Exception {
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("includeStudent", "00"));
    parameters.add(new BasicNameValuePair("orderRequest.from_station_telecode", "SHH"));
    parameters.add(new BasicNameValuePair("orderRequest.start_time_str", "00:00--24:00"));
    parameters.add(new BasicNameValuePair("orderRequest.to_station_telecode", "CSQ"));
    parameters.add(new BasicNameValuePair("orderRequest.train_date", "2011-11-24"));
    parameters.add(new BasicNameValuePair("orderRequest.train_no", ""));
    parameters.add(new BasicNameValuePair("seatTypeAndNum", ""));
    parameters.add(new BasicNameValuePair("trainClass", "QB#D#Z#T#K#QT#"));
    parameters.add(new BasicNameValuePair("trainPassType", "QB"));

    String responseBody = "0,<span id='id_5l0000D10502' class='base_txtdiv' onmouseover=javascript:onStopHover('5l0000D10502#AOH#CSQ') onmouseout='onStopOut()'>D105</span>,<img src='/otsweb/images/tips/first.gif'>&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;09:08,<img src='/otsweb/images/tips/last.gif'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;18:21,09:13,--,--,<font color='darkgray'></font>,<font color='#008800'></font>,--,--,--,--,--,--,--,<input type='button' class='yuding_u' onmousemove=this.className='yuding_u_over' onmousedown=this.className='yuding_u_down' onmouseout=this.className='yuding_u' onclick=javascript:getSelected('D105#553#09:08#5l0000D10502#AOH#CSQ') value=''></input>,"
            + "<span id='id_5l0000D10502' class='base_txtdiv' onmouseover=javascript:onStopHover('5l0000D10502#EPH#PXG') onmouseout='onStopOut()'>D105</span>,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;?&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;09:38,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;??&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;17:09,07:31,--,--,<font color='darkgray'></font>,<font color='darkgray'></font>,--,--,--,--,--,--,--,<input type='button' class='yuding_x'  value=''></input>";

    List<TrainQueryInfo> tqis = Util.parserQueryInfo(responseBody);

    for (TrainQueryInfo tqi : tqis) {
        System.out.println(tqi);/* ww w .  ja  v  a2s.co m*/
    }

    String citys = "@bji||BJP|0@bjn|?|VNP|1@bjx||BXP|2@cqb|?|CUW|3@sha||SHH|4@shn|?|SNH|5@shq||AOH|6@shx||SXH|7@tji||TJP|8@tjn|?|TIP|9@tjx||TXP|10@cch||CCT|11@cdd|?|ICW|12@cdu|?|CDW|13@csh||CSQ|14@csn|?|CWQ|15@fzh|?|FZS|16@fzn|??|FYS|17@gzb||GBQ|18@gzd||GGQ|19@gzh||GZQ|20@gzn|?|IZQ|21@heb||HBB|22@hfe|?|HFH|23@hkd|?|HMQ|24@hko|?|VUQ|25@hzh|?|HZH|26@hzn|??|XHH|27@jna|?|JNK|28@jnd|?|JAK|29@jnx|?|JGK|30@lzh||LZJ|31@nch|?|NCG|32@nji|?|NJH|33@njn|??|NKH|34@sjb||VVP|35@sjz||SJP|36@sya||SYT|37@syb||SBT|38@tyu||TYV|39@wha||WHN|40@xab||EAY|41@xan||XAY|42@zzh||ZZF|43@aya||AYF|44@bbu||BBH|45@bji|?|BJY|46@cna|??|CEH|47@czh||CZH|48@djy||DDW|49@dli||DLT|50@dsq||DQT|51@dzh||RXW|52@fdi|?|FES|53@han||AUH|54@hda||HDP|55@hko|?|HKN|56@hnx|?|EUH|57@hsh||HSP|58@hsh||HSN|59@jan|?|VAG|60@jgs||JGG|61@jhx|?|JBH|62@jji|?|JJG|63@jli|?|JLL|64@jsh||JUH|65@kfe|?|KFF|66@ksn|?|KNH|67@lan||UAH|68@lhe||LON|69@ljy|?|LKP|70@lym||LLF|71@lzh||LZD|72@nbd|?|NVH|73@nch|?|NCW|74@nto|?|NUH|75@pxi|??|PXG|76@pxx||PCW|77@qcs|?|QSW|78@qda|?|QDK|79@qzh||QEH|80@qzh||QYS|81@shg||SHD|82@sni|??|NIW|83@spi||SPT|84@sqi||SQF|85@sra||SRG|86@sya|??|SNN|87@sya||SEQ|88@szh|?|SZN|89@szh|?|SZH|90@szh||SZQ|91@tgu||TGP|92@tli|?|TLT|93@tsb|?|FUP|94@tsh|?|TSP|95@wch||WCN|96@wfd||WDT|97@wna|?|WNY|98@wxi||WXH|99@wys||WAS|100@wzn|?|VRH|101@xch||XCF|102@xhu||EFQ|103@xmb||XKS|104@xme||XMS|105@xxi||XXF|106@xya||XUN|107@xya||XFN|108@xyu||XUG|109@xzh|?|XCH|110@yan||YWY|111@ych|?|AFH|112@ych||YCG|113@yta||YTG|114@ywu||YWH|115@yxi||YON|116@yzh||YLH|117@zbo|?|ZBK|118@zhb|?|ZIQ|119@zji||ZJH|120@zmd||ZDN|121@zzh||ZZQ|122@zzh||ZEK|123@zzx||ZFK|124@aji||ARH|125@atb||ASH|126@bao|?|BWQ|127@bbn|?|BMH|128@bdh||BEP|129@bdi|?|BDP|130@bhs|??|BWH|131@bji||IBQ|132@bji||BLQ|133@cbb|?|CIN|134@cle|?|CLK|135@czb||ESH|136@czh|?|CXH|137@czx||ICQ|138@czx||CBP|139@dan||DAG|140@dgu||DAQ|141@dsh|?|DRQ|142@dtu||RUH|143@dya||DYH|144@dyb||EXH|145@dyd||IAW|146@dyu||EWH|147@dzd||DIP|148@dzh||DXP|149@ezh||ECN|150@fan|?|FAS|151@fdo||FIH|152@fhu||FHH|153@fqi|?|FQS|154@gmi||GMK|155@gqc|?|GAG|156@gyn|?|GYF|157@gzh|?|GNQ|158@hax||HIH|159@hax||VXN|160@hch|??|WKW|161@hgz||IGW|162@hji||HJS|163@hlb||HPD|164@hni|?|HNH|165@hqi||VQH|166@hsb|?|HDY|167@hsh||VCH|168@hsx||HEQ|169@hyd||HVQ|170@hzh||VON|171@jji||JJS|172@jme||JWQ|173@jsb||EGH|174@jsn|?|EAH|175@jxi||JXH|176@jxn|?|EPH|177@jzb||JZK|178@jzh||JZH|179@jzn|?|JOD|180@lbx|??|LPF|181@lch|?|UCK|182@lfa|?|LJP|183@lha||UFH|184@lji||LKS|185@lsh|?|LSG|186@lsh||LIQ|187@lxi||UXP|188@lyo||LMH|189@lyu|?|LVS|190@lyx||LPQ|191@mcb||MBN|192@mcn|?|MNF|193@mla||MHQ|194@mld||MQQ|195@nde|?|NES|196@nha|?|NHH|197@nla|?|NNQ|198@nxb|?|NEH|199@pjb||PBD|200@pti||PTS|201@qfd||QAK|202@qha|?|QYQ|203@qji||INH|204@qsy||QYH|205@qyu||QBQ|206@qzs|?|QZK|207@ran||RAH|208@rch||RCG|209@rgu||RUQ|210@sde||ORQ|211@sfa|?|OLH|212@sgu||SNQ|213@sjn|??|IMH|214@slo||SLQ|215@smn|?|SCF|216@smx||OQH|217@sxi|?|SOH|218@syu||BDH|219@szb||SND|220@szb|?|OHH|221@szd||SRH|222@szq|?|ITH|223@szq|?|KAH|224@tan|?|TID|225@tan||TMK|226@tms||TLS|227@tna|?|TVW|228@txi|?|TCH|229@tzd||TEK|230@tzh|?|TZH|231@wch||WEQ|232@wfa|??|WFK|233@wli||VHH|234@wnb|?|WBY|235@wni|?|WNQ|236@wqi||WWP|237@wxd||WGH|238@wxq||IFH|239@xga|?|XGN|240@xla|?|EAQ|241@xli||XPH|242@xnb|?|XRN|243@xpu||XOS|244@xpu||XIW|245@xta|?|XTP|246@xzd|?|UUH|247@ych||AIH|248@yds|??|YGH|249@yha|?|EVH|250@yji||URH|251@ylw||TWQ|252@ylz|?|YSY|253@yqb||YPP|254@yqi|?|UPH|255@yxi||ACG|256@yya||YYH|257@yyd||YIQ|258@zji||ZDH|259@zjn|?|ZEH|260@zmt||ZOQ|261@zqi||ZTK|262@zsb||ZGQ|263@zsh||ZSQ|264@zzx||ZAQ|265";
    String city[] = citys.split("@");
    System.out.println("---------start--------");
    for (String tmp : city) {
        System.out.println(tmp);
    }
    System.out.println("---------end--------");

    //String test = "?                      ?     ??     ?               ?     ?          ?               -->             ??    ???                 : 260.0()-->       ? Sat Nov 26 14:04:16 CST 2011       1    ?        ??        ?        ?       Mon Nov 28 00:00:00 CST 2011        D105                Thu Jan 01 09:08:00 CST 1970        02        052               ?,        260.0               ?                        -->                              -->                                                                                                          ??";
    String test = "1 vxv";
    System.out.println(test.replaceAll("\\s", ""));

}

From source file:asl.seedscan.SeedScan.java

public static void main(String args[]) {
    // Default locations of config and schema files
    File configFile = new File("config.xml");
    File schemaFile = new File("schemas/SeedScanConfig.xsd");
    boolean parseConfig = true;

    ArrayList<File> schemaFiles = new ArrayList<File>();
    schemaFiles.add(schemaFile);//  w  w  w  . jav  a2 s .c  o m

    // ==== Command Line Parsing ====
    Options options = new Options();
    Option opConfigFile = new Option("c", "config-file", true,
            "The config file to use for seedscan. XML format according to SeedScanConfig.xsd.");
    Option opSchemaFile = new Option("s", "schema-file", true,
            "The xsd schema file which should be used to verify the config file format. ");

    OptionGroup ogConfig = new OptionGroup();
    ogConfig.addOption(opConfigFile);

    OptionGroup ogSchema = new OptionGroup();
    ogConfig.addOption(opSchemaFile);

    options.addOptionGroup(ogConfig);
    options.addOptionGroup(ogSchema);

    PosixParser optParser = new PosixParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = optParser.parse(options, args, true);
    } catch (org.apache.commons.cli.ParseException e) {
        logger.error("Error while parsing command-line arguments.");
        System.exit(1);
    }

    Option opt;
    Iterator<?> iter = cmdLine.iterator();
    while (iter.hasNext()) {
        opt = (Option) iter.next();
        if (opt.getOpt().equals("c")) {
            configFile = new File(opt.getValue());
        } else if (opt.getOpt().equals("s")) {
            schemaFile = new File(opt.getValue());
        }
    }

    // ==== Configuration Read and Parse Actions ====
    ConfigParser parser = new ConfigParser(schemaFiles);
    ConfigT config = parser.parseConfig(configFile);

    // Print out configuration file contents
    Formatter formatter = new Formatter(new StringBuilder(), Locale.US);

    // ===== CONFIG: LOCK FILE =====
    File lockFile = new File(config.getLockfile());
    logger.info("SeedScan lock file is '" + lockFile + "'");
    LockFile lock = new LockFile(lockFile);
    if (!lock.acquire()) {
        logger.error("Could not acquire lock.");
        System.exit(1);
    }

    // ===== CONFIG: LOGGING =====
    // MTH: This is now done in log4j.properties file

    // ===== CONFIG: DATABASE =====
    MetricDatabase readDB = new MetricDatabase(config.getDatabase());
    MetricDatabase writeDB = new MetricDatabase(config.getDatabase());
    MetricReader reader = new MetricReader(readDB);
    MetricInjector injector = new MetricInjector(writeDB);

    // ===== CONFIG: SCANS =====
    Hashtable<String, Scan> scans = new Hashtable<String, Scan>();
    if (config.getScans().getScan() == null) {
        logger.error("No scans in configuration.");
        System.exit(1);
    } else {
        for (ScanT scanCfg : config.getScans().getScan()) {
            String name = scanCfg.getName();
            if (scans.containsKey(name)) {
                logger.error("Duplicate scan name '" + name + "' encountered.");
                System.exit(1);
            }

            // This should really be handled by jaxb by setting it up in schemas/SeedScanConfig.xsd
            if (scanCfg.getStartDay() == null && scanCfg.getStartDate() == null) {
                logger.error(
                        "== SeedScan Error: Must set EITHER cfg:start_day -OR- cfg:start_date in config.xml to start Scan!");
                System.exit(1);
            }

            // Configure this Scan
            Scan scan = new Scan(scanCfg.getName());
            scan.setPathPattern(scanCfg.getPath());
            scan.setDatalessDir(scanCfg.getDatalessDir());
            scan.setEventsDir(scanCfg.getEventsDir());
            scan.setPlotsDir(scanCfg.getPlotsDir());
            scan.setDaysToScan(scanCfg.getDaysToScan().intValue());
            if (scanCfg.getStartDay() != null) {
                scan.setStartDay(scanCfg.getStartDay().intValue());
            }
            if (scanCfg.getStartDate() != null) {
                scan.setStartDate(scanCfg.getStartDate().intValue());
            }

            if (scanCfg.getNetworkSubset() != null) {
                logger.debug("Filter on Network Subset=[{}]", scanCfg.getNetworkSubset());
                Filter filter = new Filter(false);
                for (String network : scanCfg.getNetworkSubset().split(",")) {
                    logger.debug("Network =[{}]", network);
                    filter.addFilter(network);
                }
                scan.setNetworks(filter);
            }
            if (scanCfg.getStationSubset() != null) {
                logger.debug("Filter on Station Subset=[{}]", scanCfg.getStationSubset());
                Filter filter = new Filter(false);
                for (String station : scanCfg.getStationSubset().split(",")) {
                    logger.debug("Station =[{}]", station);
                    filter.addFilter(station);
                }
                scan.setStations(filter);
            }
            if (scanCfg.getLocationSubset() != null) {
                logger.debug("Filter on Location Subset=[{}]", scanCfg.getLocationSubset());
                Filter filter = new Filter(false);
                for (String location : scanCfg.getLocationSubset().split(",")) {
                    logger.debug("Location =[{}]", location);
                    filter.addFilter(location);
                }
                scan.setLocations(filter);
            }
            if (scanCfg.getChannelSubset() != null) {
                logger.debug("Filter on Channel Subset=[{}]", scanCfg.getChannelSubset());
                Filter filter = new Filter(false);
                for (String channel : scanCfg.getChannelSubset().split(",")) {
                    logger.debug("Channel =[{}]", channel);
                    filter.addFilter(channel);
                }
                scan.setChannels(filter);
            }

            for (MetricT met : scanCfg.getMetrics().getMetric()) {
                try {
                    Class<?> metricClass = Class.forName(met.getClassName());
                    MetricWrapper wrapper = new MetricWrapper(metricClass);
                    for (ArgumentT arg : met.getArgument()) {
                        wrapper.add(arg.getName(), arg.getValue());
                    }
                    scan.addMetric(wrapper);
                } catch (ClassNotFoundException ex) {
                    logger.error("No such metric class '" + met.getClassName() + "'");
                    System.exit(1);
                } catch (InstantiationException ex) {
                    logger.error("Could not dynamically instantiate class '" + met.getClassName() + "'");
                    System.exit(1);
                } catch (IllegalAccessException ex) {
                    logger.error("Illegal access while loading class '" + met.getClassName() + "'");
                    System.exit(1);
                } catch (NoSuchFieldException ex) {
                    logger.error("Invalid dynamic argument to Metric subclass '" + met.getClassName() + "'");
                    System.exit(1);
                }

            }
            scans.put(name, scan);
        }
    }

    // ==== Establish Database Connection ====
    // TODO: State Tracking in the Database
    // - Record scan started in database.
    // - Track our progress as we go so a new process can pick up where
    //   we left off if our process dies.
    // - Mark when each date-station-channel-operation is complete
    //LogDatabaseHandler logDB = new LogDatabaseHandler(configuration.get

    // For each day ((yesterday - scanDepth) to yesterday)
    // scan for these channel files, only process them if
    // they have not yet been scanned, or if changes have
    // occurred to the file since its last scan. Do this for
    // each scan type. Do not re-scan data for each type,
    // launch processes for each scan and use the same data set
    // for each. If we can pipe the data as it is read, do so.
    // If we need to push all of it at once, do these in sequence
    // in order to preserve overall system memory resources.

    Scan scan = null;

    // ==== Perform Scans ====

    scan = scans.get("daily");

    //MTH: This part could/should be moved up higher except that we need to know datalessDir, which,
    //     at this point, is configured on a per scan basis ... so we need to know what scan we're doing
    MetaServer metaServer = null;
    if (config.getMetaserver() != null) {
        if (config.getMetaserver().getUseRemote().equals("yes")
                || config.getMetaserver().getUseRemote().equals("true")) {
            String remoteServer = config.getMetaserver().getRemoteUri();
            try {
                metaServer = new MetaServer(new URI(remoteServer));
            } catch (Exception e) {
                logger.error("caught URI exception:" + e.getMessage());
            }
        } else {
            metaServer = new MetaServer(scan.getDatalessDir());
        }
    } else { // Use local MetaServer
        metaServer = new MetaServer(scan.getDatalessDir());
    }

    List<Station> stations = null;

    if (config.getStationList() == null) { // get StationList from MetaServer
        logger.info("Get StationList from MetaServer");
        stations = metaServer.getStationList();
    } else { // read StationList from config.xml
        logger.info("Read StationList from config.xml");
        List<String> stationList = config.getStationList().getStation();
        if (stationList.size() > 0) {
            stations = new ArrayList<Station>();
            for (String station : stationList) {
                String[] words = station.split("_");
                if (words.length != 2) {
                    logger.warn(String.format("stationList: station=[%s] is NOT a valid station --> Skip",
                            station));
                } else {
                    stations.add(new Station(words[0], words[1]));
                    logger.info("config.xml: Read station:" + station);
                }
            }
        } else {
            logger.error("Error: No valid stations read from config.xml");
        }
    }

    if (stations == null) {
        logger.error("Found NO stations to scan --> EXITTING SeedScan");
        System.exit(1);
    }

    Thread readerThread = new Thread(reader);
    readerThread.start();
    logger.info("Reader thread started.");

    Thread injectorThread = new Thread(injector);
    injectorThread.start();
    logger.info("Injector thread started.");

    // Loop over scans and hand each one to a ScanManager
    logger.info("Hand scan to ScanManager");
    for (String key : scans.keySet()) {
        scan = scans.get(key);
        logger.info(String.format("Scan=[%s] startDay=%d startDate=%d daysToScan=%d\n", key, scan.getStartDay(),
                scan.getStartDate(), scan.getDaysToScan()));
        ScanManager scanManager = new ScanManager(reader, injector, stations, scan, metaServer);
    }

    logger.info("ScanManager is [ FINISHED ] --> stop the injector and reader threads");

    try {
        injector.halt();
        logger.info("All stations processed. Waiting for injector thread to finish...");
        synchronized (injectorThread) {
            //injectorThread.wait();
            injectorThread.interrupt();
        }
        logger.info("Injector thread halted.");
    } catch (InterruptedException ex) {
        logger.warn("The injector thread was interrupted while attempting to complete requests.");
    }

    try {
        reader.halt();
        logger.info("All stations processed. Waiting for reader thread to finish...");
        synchronized (readerThread) {
            //readerThread.wait();
            readerThread.interrupt();
        }
        logger.info("Reader thread halted.");
    } catch (InterruptedException ex) {
        logger.warn("The reader thread was interrupted while attempting to complete requests.");
    }

    try {
        lock.release();
    } catch (IOException e) {
        ;
    } finally {
        logger.info("Release seedscan lock and quit metaServer");
        lock = null;
        metaServer.quit();
    }
}

From source file:Main.java

private static void addToCountMap(String test) {
    String[] split = test.split(" ");
    for (String string : split) {
        if (!count.containsKey(string)) {
            count.put(string, 0);/*from   www . ja  va 2s . com*/
        }
        count.put(string, count.get(string) + 1);
    }
}

From source file:Main.java

public static String trim(String s) {
    s = s.split("\n")[0];
    s = s.trim();
    return s;
}

From source file:Main.java

public static String[] parseMockDataSec(String str) {
    return str.split("(\\d+\\.\\d)");
}

From source file:Main.java

public static String getUserFromJID(String jid) {
    return jid.split("@")[0];
}