Example usage for java.lang String length

List of usage examples for java.lang String length

Introduction

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

Prototype

public int length() 

Source Link

Document

Returns the length of this string.

Usage

From source file:cz.muni.fi.crocs.EduHoc.Main.java

/**
 * @param args the command line arguments
 *///from w w  w .j a  v  a2 s.com
public static void main(String[] args) {
    System.out.println("JeeTool \n");

    Options options = OptionsMain.createOptions();

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println("cannot parse parameters");
        OptionsMain.printHelp(options);
        System.err.println(ex.toString());
        return;
    }
    boolean silent = cmd.hasOption("s");
    boolean verbose = cmd.hasOption("v");

    if (!silent) {
        System.out.println(ANSI_GREEN + "EduHoc home is: " + System.getenv("EDU_HOC_HOME") + "\n" + ANSI_RESET);
    }

    //help
    if (cmd.hasOption("h")) {
        OptionsMain.printHelp(options);
        return;
    }

    String filepath;
    //path to config list of nodes
    if (cmd.hasOption("a")) {
        filepath = cmd.getOptionValue("a");
    } else {
        filepath = System.getenv("EDU_HOC_HOME") + "/config/motePaths.txt";
    }

    //create motelist
    MoteList moteList = new MoteList(filepath);
    if (verbose) {
        moteList.setVerbose();
    }
    if (silent) {
        moteList.setSilent();
    }

    if (verbose) {
        System.out.println("reading motelist from file " + filepath);
    }

    if (cmd.hasOption("i")) {
        List<Integer> ids = new ArrayList<Integer>();
        String arg = cmd.getOptionValue("i");
        String[] IdArgs = arg.split(",");
        for (String s : IdArgs) {
            if (s.contains("-")) {
                int start = Integer.parseInt(s.substring(0, s.indexOf("-")));
                int end = Integer.parseInt(s.substring(s.indexOf("-") + 1, s.length()));
                for (int i = start; i <= end; i++) {
                    ids.add(i);
                }
            } else {
                ids.add(Integer.parseInt(s));
            }
        }
        moteList.setIds(ids);
    }

    moteList.readFile();

    if (cmd.hasOption("d")) {
        //only detect nodes
        return;
    }

    //if make
    if (cmd.hasOption("m") || cmd.hasOption("c") || cmd.hasOption("u")) {
        UploadMain upload = new UploadMain(moteList, cmd);
        upload.runMake();
    }

    //if execute command
    if (cmd.hasOption("E")) {
        try {
            ExecuteShellCommand com = new ExecuteShellCommand();
            if (verbose) {
                System.out.println("Executing shell command " + cmd.getOptionValue("E"));
            }

            com.executeCommand(cmd.getOptionValue("E"));
        } catch (IOException ex) {
            System.err.println("Execute command " + cmd.getOptionValue("E") + " failed");
        }
    }

    //if serial
    if (cmd.hasOption("l") || cmd.hasOption("w")) {
        SerialMain serial = new SerialMain(cmd, moteList);
        if (silent) {
            serial.setSilent();
        }
        if (verbose) {
            serial.setVerbose();
        }
        serial.startSerial();
    }

}

From source file:com.sun.faban.harness.util.CLI.java

/**
 * The first argument to the CLI is the action. It can be:<ul>
 * <li>pending</li>//from  w w  w  .  j a va 2s  .  co m
 * <li>status runId</li>
 * <li>submit benchmark profile configfile.xml</ul>
 * </ul>
 *
 * @param args The command line arguments.
 */
public static void main(String[] args) {

    if (args.length == 0) {
        printUsage();
        System.exit(1);
    }

    ArrayList<String> argList = new ArrayList<String>();
    // Do the getopt thing.
    char opt = (char) -1;
    String master = null;
    String user = null;
    String password = null;

    for (String arg : args) {
        if (arg.startsWith("-M")) {
            String optArg = arg.substring(2);
            if (optArg.length() == 0) {
                opt = 'M';
                continue;
            }
            master = optArg;
        } else if (arg.startsWith("-U")) {
            String optArg = arg.substring(2);
            if (optArg.length() == 0) {
                opt = 'U';
                continue;
            }
            user = optArg;
        } else if (arg.startsWith("-P")) {
            String optArg = arg.substring(2);
            if (optArg.length() == 0) {
                opt = 'P';
                continue;
            }
            password = optArg;
        } else if (opt != (char) -1) {
            switch (opt) {
            case 'M':
                master = arg;
                opt = (char) -1;
                break;
            case 'U':
                user = arg;
                opt = (char) -1;
                break;
            case 'P':
                password = arg;
                opt = (char) -1;
                break;
            }
        } else {
            argList.add(arg);
            opt = (char) -1;
        }
    }

    if (master == null)
        master = "http://localhost:9980/";
    else if (!master.endsWith("/"))
        master += '/';

    CLI cli = new CLI();
    String action = argList.get(0);

    try {
        if ("pending".equals(action)) {
            cli.doGet(master + "pending");
        } else if ("status".equals(action)) {
            if (argList.size() > 1)
                cli.doGet(master + "status/" + argList.get(1));
            else
                printUsage();
        } else if ("submit".equals(action)) {
            if (argList.size() > 3) {
                cli.doPostSubmit(master, user, password, argList);
            } else {
                printUsage();
                System.exit(1);
            }
        } else if ("kill".equals(action)) {
            if (argList.size() > 1) {
                cli.doPostKill(master, user, password, argList);
            } else {
                printUsage();
                System.exit(1);
            }
        } else if ("wait".equals(action)) {
            if (argList.size() > 1) {
                cli.pollStatus(master + "status/" + argList.get(1));
            } else {
                printUsage();
                System.exit(1);
            }
        } else if ("showlogs".equals(action)) {
            StringBuilder url = new StringBuilder();
            if (argList.size() > 1) {
                url.append(master).append("logs/");
                url.append(argList.get(1));
            } else {
                printUsage();
            }
            for (int i = 2; i < argList.size(); i++) {
                if ("-t".equals(argList.get(i)))
                    url.append("/tail");
                if ("-f".equals(argList.get(i)))
                    url.append("/follow");
                if ("-ft".equals(argList.get(i)))
                    url.append("/tail/follow");
                if ("-tf".equals(argList.get(i)))
                    url.append("/tail/follow");
            }
            cli.doGet(url.toString());
        } else {
            printUsage();
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
}

From source file:com.traffic.common.utils.http.HttpClientUtils.java

public static void main(String[] args) {
    //cst??GMT?//  w  ww  .  j  a va 2 s .com
    DateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
    format.setTimeZone(TimeZone.getTimeZone("GMT"));
    String date = format.format(new Date());

    String s = "license_plate_num=%E7%B2%A4BA804D&engine_num=C32764&body_num=064484&city_pinyin=shenzhen";
    //??
    String SIGNATURE = MD5Encrypt.encrypt("POST&/v3/violations&" + date + "&" + s.length() + "&"
            + MD5Encrypt.encrypt("uTIYrJn6vJTyt1ztBNbqQQDexDjpAM4m"));
    //
    headers.put("Host", "api.buding.cn");
    headers.put("Authorization", "dLSQ1ZjK7exqlwqx:" + SIGNATURE);
    headers.put("Date", date);

    JSONObject reqParam = new JSONObject();
    reqParam.put("license_plate_num", "BA804D");
    reqParam.put("engine_num", "C32764");
    reqParam.put("body_num", "064484");
    reqParam.put("city_pinyin", "shenzhen");
    String respBody = HttpClientUtils.httpPost_JSONObject("http://api.buding.cn/v3/violations", reqParam);
    System.out.println(JSONObject.parse(respBody));
}

From source file:amulet.appbuilder.AppBuilder.java

public static void main(String[] args) {
    try {//from w  ww.  j a va  2 s.  c  om
        if (args.length != 1) {
            System.out.println("ERROR: Provide filename that needs to be translated");
            return;
        }
        String inputFile = args[0];
        if (inputFile.length() < 1) {
            System.out.println("ERROR: Provide filename that needs to be translated");
            return;
        }

        ResourceProfiler resourceProfiler = new ResourceProfiler();
        resourceProfiler.add(inputFile);
        new AppBuilder(inputFile, true, true, resourceProfiler);

    } catch (Exception exp) {
        System.err.println("Unexpected exception:" + exp.getMessage());
        exp.printStackTrace();
        return;
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    SecureRandom random = new SecureRandom();
    IvParameterSpec ivSpec = createCtrIvForAES(1, random);
    Key key = createKeyForAES(256, random);
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    String input = "www.java2s.com";
    Mac mac = Mac.getInstance("DES", "BC");
    byte[] macKeyBytes = "12345678".getBytes();
    Key macKey = new SecretKeySpec(macKeyBytes, "DES");
    System.out.println("input : " + input);

    // encryption step
    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    byte[] cipherText = new byte[cipher.getOutputSize(input.length() + mac.getMacLength())];
    int ctLength = cipher.update(input.getBytes(), 0, input.length(), cipherText, 0);
    mac.init(macKey);/*from w  w  w  . j  a va2 s .  co m*/
    mac.update(input.getBytes());
    ctLength += cipher.doFinal(mac.doFinal(), 0, mac.getMacLength(), cipherText, ctLength);
    System.out.println("cipherText : " + new String(cipherText));

    // decryption step
    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
    byte[] plainText = cipher.doFinal(cipherText, 0, ctLength);
    int messageLength = plainText.length - mac.getMacLength();

    mac.init(macKey);
    mac.update(plainText, 0, messageLength);

    byte[] messageHash = new byte[mac.getMacLength()];
    System.arraycopy(plainText, messageLength, messageHash, 0, messageHash.length);

    System.out.println("plain : " + new String(plainText) + " verified: "
            + MessageDigest.isEqual(mac.doFinal(), messageHash));
}

From source file:fr.romainf.QRCode.java

public static void main(String[] args) {
    Options options = buildOptions();//from   ww w. j a v a2s.c  o  m

    CommandLineParser parser = new BasicParser();

    try {
        CommandLine cmd = parser.parse(options, args);
        args = cmd.getArgs();

        int l = args.length;
        if (l != 1) {
            System.out.println("Can only encode one datum at a time (" + l + " given)");
            printUsage(options);
            System.exit(1);
        }
        if (cmd.hasOption("help")) {
            printUsage(options);
            System.exit(0);
        }

        String output = cmd.getOptionValue("o", DEFAULT_OUTPUT_FILE);
        String pixelColourText = cmd.getOptionValue("c", DEFAULT_PIXEL_COLOUR);
        if (pixelColourText.startsWith("0x")) {
            pixelColourText = pixelColourText.substring(2);
        }
        Color pixelColour;
        if (pixelColourText.length() == 6) {
            pixelColour = new Color(Integer.parseInt(pixelColourText, 16));
        } else {
            pixelColour = new Color((int) Long.parseLong(pixelColourText, 16), true);
        }

        writeQRCode(args[l - 1], output, pixelColour);

    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printUsage(options);
        System.exit(1);
    } catch (WriterException e) {
        System.out.println("Could not create QRCode from data (" + e.getMessage() + ")");
        System.exit(2);
    } catch (IOException e) {
        System.out.println("Could not save QRCode to file (" + e.getMessage() + ")");
        System.exit(4);
    }
    System.exit(0);
}

From source file:edu.ku.brc.helpers.Encryption.java

/** I am leaving this here for documentation purposes
 * @param args input from the command line
 * @throws Exception some error/* w ww .ja  va 2s  .c o  m*/
 */
public static void main(final String[] args) throws Exception {
    /*
     * If we're configured to use a third-party cryptography provider, where that provider is
     * not permanently installed, then we need to install it first.
     */
    if (EXTRA_PROVIDER != null) {
        Provider prov = (Provider) Class.forName(EXTRA_PROVIDER).newInstance();
        Security.addProvider(prov);
    }

    /*
     * The Encryption() function above uses a byte[] as input, so it's more general (it can Encryption
     * anything, not just a String), as well as using a char[] for the password, because it can
     * be overwritten once it's finished. Strings are immutable, so to purge them from RAM you
     * have to hope they get garbage collected and then the RAM gets reused. For char[]s you can
     * simply fill up the array with junk to erase the password from RAM. Anyway, use char[] if
     * you're concerned about security, but for a test case, a String works fine.
     */
    /* Our input text and password. */
    String input = "Hello World!"; //$NON-NLS-1$
    String password = "abcd"; //$NON-NLS-1$

    byte[] inputBytes = input.getBytes();
    char[] passwordChars = password.toCharArray();

    /* Encrypt the data. */
    byte[] ciphertext = encrypt(inputBytes, passwordChars);

    System.out.println("Ciphertext:"); //$NON-NLS-1$

    /*
     * This is just a little loop I made up which displays the encrypted data in hexadecimal, 30
     * bytes to a line. Obviously, the ciphertext won't necessarily be a recognizable String,
     * and it'll probably have control characters and such in it. We don't even want to convert
     * it to a String, let alone display it onscreen. If you need text, investigate some kind of
     * encoding at this point on top of the encryption, like Base64. It's not that hard to
     * implement and it'll give you text to carry from place to place. Just remember to *de*code
     * the text before calling decrypt().
     */
    int i;
    for (i = 0; i < ciphertext.length; i++) {
        String s = Integer.toHexString(ciphertext[i] & 0xFF);
        if (s.length() == 1)
            s = "0" + s; //$NON-NLS-1$
        System.out.print(s);
        if (i % 30 == 29)
            System.out.println();
    }
    if ((ciphertext.length - 1) % 30 != 29)
        System.out.println();

    String hexText = makeHEXStr(ciphertext);
    System.out.println("To:   [" + hexText + "]"); //$NON-NLS-1$ //$NON-NLS-2$
    System.out.println("From: [" + reverseHEXStr(hexText) + "]****"); //$NON-NLS-1$ //$NON-NLS-2$

    /*
     * Now, decrypt the data. Note that all we need is the password and the ciphertext.
     */
    byte[] output = decrypt(ciphertext, passwordChars);

    /* Transform the output into a string. */
    String sOutput = new String(output);

    /* Display it. */
    System.out.println("Plaintext:\n" + sOutput); //$NON-NLS-1$
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSaxDb2LUWLoaderCLI.CFAsteriskSaxDb2LUWLoaderCLI.java

public static void main(String args[]) {
    final String S_ProcName = "CFAsteriskSaxDb2LUWLoaderCLI.main() ";
    initConsoleLog();//  ww w  .  j  a  va2s . com
    int numArgs = args.length;
    if (numArgs >= 2) {
        String homeDirName = System.getProperty("HOME");
        if (homeDirName == null) {
            homeDirName = System.getProperty("user.home");
            if (homeDirName == null) {
                log.message(S_ProcName + "ERROR: Home directory not set");
                return;
            }
        }
        File homeDir = new File(homeDirName);
        if (!homeDir.exists()) {
            log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" does not exist");
            return;
        }
        if (!homeDir.isDirectory()) {
            log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" is not a directory");
            return;
        }
        CFAsteriskConfigurationFile cFAsteriskConfig = new CFAsteriskConfigurationFile();
        String cFAsteriskConfigFileName = homeDir.getPath() + File.separator + ".cfasteriskdb2luwrc";
        cFAsteriskConfig.setFileName(cFAsteriskConfigFileName);
        File cFAsteriskConfigFile = new File(cFAsteriskConfigFileName);
        if (!cFAsteriskConfigFile.exists()) {
            cFAsteriskConfig.setDbServer("127.0.0.1");
            cFAsteriskConfig.setDbPort(5432);
            cFAsteriskConfig.setDbDatabase("CFAst24");
            cFAsteriskConfig.setDbUserName("luw");
            cFAsteriskConfig.setDbPassword("edit-me-please");
            cFAsteriskConfig.save();
            log.message(S_ProcName + "INFO: Created configuration file " + cFAsteriskConfigFileName
                    + ", please edit configuration and restart.");
            return;
        }
        if (!cFAsteriskConfigFile.isFile()) {
            log.message(S_ProcName + "ERROR: Proposed configuration file " + cFAsteriskConfigFileName
                    + " is not a file.");
            return;
        }
        if (!cFAsteriskConfigFile.canRead()) {
            log.message(S_ProcName + "ERROR: Permission denied attempting to read configuration file "
                    + cFAsteriskConfigFileName);
            return;
        }
        cFAsteriskConfig.load();
        boolean fastExit = false;
        CFAsteriskClientConfigurationFile cFDbTestClientConfig = new CFAsteriskClientConfigurationFile();
        String cFDbTestClientConfigFileName = homeDir.getPath() + File.separator + ".cfdbtestclientrc";
        cFDbTestClientConfig.setFileName(cFDbTestClientConfigFileName);
        File cFDbTestClientConfigFile = new File(cFDbTestClientConfigFileName);
        if (!cFDbTestClientConfigFile.exists()) {
            String cFDbTestKeyStoreFileName = homeDir.getPath() + File.separator + ".msscfjceks";
            cFDbTestClientConfig.setKeyStore(cFDbTestKeyStoreFileName);
            InetAddress localHost;
            try {
                localHost = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                localHost = null;
            }
            if (localHost == null) {
                log.message(S_ProcName + "ERROR: LocalHost is null");
                return;
            }
            String hostName = localHost.getHostName();
            if ((hostName == null) || (hostName.length() <= 0)) {
                log.message("ERROR: LocalHost.HostName is null or empty");
                return;
            }
            String userName = System.getProperty("user.name");
            if ((userName == null) || (userName.length() <= 0)) {
                log.message("ERROR: user.name is null or empty");
                return;
            }
            String deviceName = hostName.replaceAll("[^\\w]", "_").toLowerCase() + "-"
                    + userName.replaceAll("[^\\w]", "_").toLowerCase();
            cFDbTestClientConfig.setDeviceName(deviceName);
            cFDbTestClientConfig.save();
            log.message(S_ProcName + "INFO: Created CFAsterisk client configuration file "
                    + cFDbTestClientConfigFileName);
            fastExit = true;
        }
        if (!cFDbTestClientConfigFile.isFile()) {
            log.message(S_ProcName + "ERROR: Proposed client configuration file " + cFDbTestClientConfigFileName
                    + " is not a file.");
            fastExit = true;
        }
        if (!cFDbTestClientConfigFile.canRead()) {
            log.message(S_ProcName + "ERROR: Permission denied attempting to read client configuration file "
                    + cFDbTestClientConfigFileName);
            fastExit = true;
        }
        cFDbTestClientConfig.load();

        if (fastExit) {
            return;
        }

        // Configure logging
        Properties sysProps = System.getProperties();
        sysProps.setProperty("log4j.rootCategory", "WARN");
        sysProps.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Logger httpLogger = Logger.getLogger("org.apache.http");
        httpLogger.setLevel(Level.WARN);

        ICFAsteriskSchema cFAsteriskSchema = new CFAsteriskDb2LUWSchema();
        cFAsteriskSchema.setConfigurationFile(cFAsteriskConfig);
        ICFAsteriskSchemaObj cFAsteriskSchemaObj = new CFAsteriskSchemaObj();
        cFAsteriskSchemaObj.setBackingStore(cFAsteriskSchema);
        CFAsteriskSaxLoaderCLI cli = new CFAsteriskSaxDb2LUWLoaderCLI();
        CFAsteriskSaxLoader loader = cli.getSaxLoader();
        loader.setSchemaObj(cFAsteriskSchemaObj);
        cFAsteriskSchema.connect();
        String url = args[1];
        if (numArgs >= 5) {
            cli.setClusterName(args[2]);
            cli.setTenantName(args[3]);
            cli.setSecUserName(args[4]);
        } else {
            cli.setClusterName("default");
            cli.setTenantName("system");
            cli.setSecUserName("system");
        }
        loader.setUseCluster(cli.getClusterObj());
        loader.setUseTenant(cli.getTenantObj());
        try {
            cFAsteriskSchema.beginTransaction();
            cFAsteriskSchemaObj.setSecCluster(cli.getClusterObj());
            cFAsteriskSchemaObj.setSecTenant(cli.getTenantObj());
            cFAsteriskSchemaObj.setSecUser(cli.getSecUserObj());
            cFAsteriskSchemaObj.setSecSession(cli.getSecSessionObj());
            CFSecurityAuthorization auth = new CFSecurityAuthorization();
            auth.setSecCluster(cFAsteriskSchemaObj.getSecCluster());
            auth.setSecTenant(cFAsteriskSchemaObj.getSecTenant());
            auth.setSecSession(cFAsteriskSchemaObj.getSecSession());
            cFAsteriskSchemaObj.setAuthorization(auth);
            applyLoaderOptions(loader, args[0]);
            if (numArgs >= 5) {
                cli.evaluateRemainingArgs(args, 5);
            } else {
                cli.evaluateRemainingArgs(args, 2);
            }
            loader.parseFile(url);
            cFAsteriskSchema.commit();
            cFAsteriskSchema.disconnect(true);
        } catch (Exception e) {
            log.message(S_ProcName + "EXCEPTION: Could not parse XML file \"" + url + "\": " + e.getMessage());
            e.printStackTrace(System.out);
        } catch (Error e) {
            log.message(S_ProcName + "ERROR: Could not parse XML file \"" + url + "\": " + e.getMessage());
            e.printStackTrace(System.out);
        } finally {
            if (cFAsteriskSchema.isConnected()) {
                cFAsteriskSchema.rollback();
                cFAsteriskSchema.disconnect(false);
            }
        }
    } else {
        log.message(S_ProcName
                + "ERROR: Expected at least two argument specifying the loader options and the name of the XML file to parse.  The first argument may be empty.");
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSaxMSSqlLoaderCLI.CFAsteriskSaxMSSqlLoaderCLI.java

public static void main(String args[]) {
    final String S_ProcName = "CFAsteriskSaxMSSqlLoaderCLI.main() ";
    initConsoleLog();//from w ww  . j  a  v  a2s  . c  o  m
    int numArgs = args.length;
    if (numArgs >= 2) {
        String homeDirName = System.getProperty("HOME");
        if (homeDirName == null) {
            homeDirName = System.getProperty("user.home");
            if (homeDirName == null) {
                log.message(S_ProcName + "ERROR: Home directory not set");
                return;
            }
        }
        File homeDir = new File(homeDirName);
        if (!homeDir.exists()) {
            log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" does not exist");
            return;
        }
        if (!homeDir.isDirectory()) {
            log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" is not a directory");
            return;
        }
        CFAsteriskConfigurationFile cFAsteriskConfig = new CFAsteriskConfigurationFile();
        String cFAsteriskConfigFileName = homeDir.getPath() + File.separator + ".cfasteriskmssqlrc";
        cFAsteriskConfig.setFileName(cFAsteriskConfigFileName);
        File cFAsteriskConfigFile = new File(cFAsteriskConfigFileName);
        if (!cFAsteriskConfigFile.exists()) {
            cFAsteriskConfig.setDbServer("127.0.0.1");
            cFAsteriskConfig.setDbPort(1433);
            cFAsteriskConfig.setDbDatabase("CFAst24");
            cFAsteriskConfig.setDbUserName("sa");
            cFAsteriskConfig.setDbPassword("edit-me-please");
            cFAsteriskConfig.save();
            log.message(S_ProcName + "INFO: Created configuration file " + cFAsteriskConfigFileName
                    + ", please edit configuration and restart.");
            return;
        }
        if (!cFAsteriskConfigFile.isFile()) {
            log.message(S_ProcName + "ERROR: Proposed configuration file " + cFAsteriskConfigFileName
                    + " is not a file.");
            return;
        }
        if (!cFAsteriskConfigFile.canRead()) {
            log.message(S_ProcName + "ERROR: Permission denied attempting to read configuration file "
                    + cFAsteriskConfigFileName);
            return;
        }
        cFAsteriskConfig.load();
        boolean fastExit = false;
        CFAsteriskClientConfigurationFile cFDbTestClientConfig = new CFAsteriskClientConfigurationFile();
        String cFDbTestClientConfigFileName = homeDir.getPath() + File.separator + ".cfdbtestclientrc";
        cFDbTestClientConfig.setFileName(cFDbTestClientConfigFileName);
        File cFDbTestClientConfigFile = new File(cFDbTestClientConfigFileName);
        if (!cFDbTestClientConfigFile.exists()) {
            String cFDbTestKeyStoreFileName = homeDir.getPath() + File.separator + ".msscfjceks";
            cFDbTestClientConfig.setKeyStore(cFDbTestKeyStoreFileName);
            InetAddress localHost;
            try {
                localHost = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                localHost = null;
            }
            if (localHost == null) {
                log.message(S_ProcName + "ERROR: LocalHost is null");
                return;
            }
            String hostName = localHost.getHostName();
            if ((hostName == null) || (hostName.length() <= 0)) {
                log.message("ERROR: LocalHost.HostName is null or empty");
                return;
            }
            String userName = System.getProperty("user.name");
            if ((userName == null) || (userName.length() <= 0)) {
                log.message("ERROR: user.name is null or empty");
                return;
            }
            String deviceName = hostName.replaceAll("[^\\w]", "_").toLowerCase() + "-"
                    + userName.replaceAll("[^\\w]", "_").toLowerCase();
            cFDbTestClientConfig.setDeviceName(deviceName);
            cFDbTestClientConfig.save();
            log.message(S_ProcName + "INFO: Created CFAsterisk client configuration file "
                    + cFDbTestClientConfigFileName);
            fastExit = true;
        }
        if (!cFDbTestClientConfigFile.isFile()) {
            log.message(S_ProcName + "ERROR: Proposed client configuration file " + cFDbTestClientConfigFileName
                    + " is not a file.");
            fastExit = true;
        }
        if (!cFDbTestClientConfigFile.canRead()) {
            log.message(S_ProcName + "ERROR: Permission denied attempting to read client configuration file "
                    + cFDbTestClientConfigFileName);
            fastExit = true;
        }
        cFDbTestClientConfig.load();

        if (fastExit) {
            return;
        }

        // Configure logging
        Properties sysProps = System.getProperties();
        sysProps.setProperty("log4j.rootCategory", "WARN");
        sysProps.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Logger httpLogger = Logger.getLogger("org.apache.http");
        httpLogger.setLevel(Level.WARN);

        ICFAsteriskSchema cFAsteriskSchema = new CFAsteriskMSSqlSchema();
        cFAsteriskSchema.setConfigurationFile(cFAsteriskConfig);
        ICFAsteriskSchemaObj cFAsteriskSchemaObj = new CFAsteriskSchemaObj();
        cFAsteriskSchemaObj.setBackingStore(cFAsteriskSchema);
        CFAsteriskSaxLoaderCLI cli = new CFAsteriskSaxMSSqlLoaderCLI();
        CFAsteriskSaxLoader loader = cli.getSaxLoader();
        loader.setSchemaObj(cFAsteriskSchemaObj);
        cFAsteriskSchema.connect();
        String url = args[1];
        if (numArgs >= 5) {
            cli.setClusterName(args[2]);
            cli.setTenantName(args[3]);
            cli.setSecUserName(args[4]);
        } else {
            cli.setClusterName("default");
            cli.setTenantName("system");
            cli.setSecUserName("system");
        }
        loader.setUseCluster(cli.getClusterObj());
        loader.setUseTenant(cli.getTenantObj());
        try {
            cFAsteriskSchema.beginTransaction();
            cFAsteriskSchemaObj.setSecCluster(cli.getClusterObj());
            cFAsteriskSchemaObj.setSecTenant(cli.getTenantObj());
            cFAsteriskSchemaObj.setSecUser(cli.getSecUserObj());
            cFAsteriskSchemaObj.setSecSession(cli.getSecSessionObj());
            CFSecurityAuthorization auth = new CFSecurityAuthorization();
            auth.setSecCluster(cFAsteriskSchemaObj.getSecCluster());
            auth.setSecTenant(cFAsteriskSchemaObj.getSecTenant());
            auth.setSecSession(cFAsteriskSchemaObj.getSecSession());
            cFAsteriskSchemaObj.setAuthorization(auth);
            applyLoaderOptions(loader, args[0]);
            if (numArgs >= 5) {
                cli.evaluateRemainingArgs(args, 5);
            } else {
                cli.evaluateRemainingArgs(args, 2);
            }
            loader.parseFile(url);
            cFAsteriskSchema.commit();
            cFAsteriskSchema.disconnect(true);
        } catch (Exception e) {
            log.message(S_ProcName + "EXCEPTION: Could not parse XML file \"" + url + "\": " + e.getMessage());
            e.printStackTrace(System.out);
        } catch (Error e) {
            log.message(S_ProcName + "ERROR: Could not parse XML file \"" + url + "\": " + e.getMessage());
            e.printStackTrace(System.out);
        } finally {
            if (cFAsteriskSchema.isConnected()) {
                cFAsteriskSchema.rollback();
                cFAsteriskSchema.disconnect(false);
            }
        }
    } else {
        log.message(S_ProcName
                + "ERROR: Expected at least two argument specifying the loader options and the name of the XML file to parse.  The first argument may be empty.");
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSaxMySqlLoaderCLI.CFAsteriskSaxMySqlLoaderCLI.java

public static void main(String args[]) {
    final String S_ProcName = "CFAsteriskSaxMySqlLoaderCLI.main() ";
    initConsoleLog();/*from  w w w.  ja v  a 2s . c o m*/
    int numArgs = args.length;
    if (numArgs >= 2) {
        String homeDirName = System.getProperty("HOME");
        if (homeDirName == null) {
            homeDirName = System.getProperty("user.home");
            if (homeDirName == null) {
                log.message(S_ProcName + "ERROR: Home directory not set");
                return;
            }
        }
        File homeDir = new File(homeDirName);
        if (!homeDir.exists()) {
            log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" does not exist");
            return;
        }
        if (!homeDir.isDirectory()) {
            log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" is not a directory");
            return;
        }
        CFAsteriskConfigurationFile cFAsteriskConfig = new CFAsteriskConfigurationFile();
        String cFAsteriskConfigFileName = homeDir.getPath() + File.separator + ".cfasteriskmysqlrc";
        cFAsteriskConfig.setFileName(cFAsteriskConfigFileName);
        File cFAsteriskConfigFile = new File(cFAsteriskConfigFileName);
        if (!cFAsteriskConfigFile.exists()) {
            cFAsteriskConfig.setDbServer("127.0.0.1");
            cFAsteriskConfig.setDbPort(3306);
            cFAsteriskConfig.setDbDatabase("CFAst24");
            cFAsteriskConfig.setDbUserName("root");
            cFAsteriskConfig.setDbPassword("edit-me-please");
            cFAsteriskConfig.save();
            log.message(S_ProcName + "INFO: Created configuration file " + cFAsteriskConfigFileName
                    + ", please edit configuration and restart.");
            return;
        }
        if (!cFAsteriskConfigFile.isFile()) {
            log.message(S_ProcName + "ERROR: Proposed configuration file " + cFAsteriskConfigFileName
                    + " is not a file.");
            return;
        }
        if (!cFAsteriskConfigFile.canRead()) {
            log.message(S_ProcName + "ERROR: Permission denied attempting to read configuration file "
                    + cFAsteriskConfigFileName);
            return;
        }
        cFAsteriskConfig.load();
        boolean fastExit = false;
        CFAsteriskClientConfigurationFile cFDbTestClientConfig = new CFAsteriskClientConfigurationFile();
        String cFDbTestClientConfigFileName = homeDir.getPath() + File.separator + ".cfdbtestclientrc";
        cFDbTestClientConfig.setFileName(cFDbTestClientConfigFileName);
        File cFDbTestClientConfigFile = new File(cFDbTestClientConfigFileName);
        if (!cFDbTestClientConfigFile.exists()) {
            String cFDbTestKeyStoreFileName = homeDir.getPath() + File.separator + ".msscfjceks";
            cFDbTestClientConfig.setKeyStore(cFDbTestKeyStoreFileName);
            InetAddress localHost;
            try {
                localHost = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                localHost = null;
            }
            if (localHost == null) {
                log.message(S_ProcName + "ERROR: LocalHost is null");
                return;
            }
            String hostName = localHost.getHostName();
            if ((hostName == null) || (hostName.length() <= 0)) {
                log.message("ERROR: LocalHost.HostName is null or empty");
                return;
            }
            String userName = System.getProperty("user.name");
            if ((userName == null) || (userName.length() <= 0)) {
                log.message("ERROR: user.name is null or empty");
                return;
            }
            String deviceName = hostName.replaceAll("[^\\w]", "_").toLowerCase() + "-"
                    + userName.replaceAll("[^\\w]", "_").toLowerCase();
            cFDbTestClientConfig.setDeviceName(deviceName);
            cFDbTestClientConfig.save();
            log.message(S_ProcName + "INFO: Created CFAsterisk client configuration file "
                    + cFDbTestClientConfigFileName);
            fastExit = true;
        }
        if (!cFDbTestClientConfigFile.isFile()) {
            log.message(S_ProcName + "ERROR: Proposed client configuration file " + cFDbTestClientConfigFileName
                    + " is not a file.");
            fastExit = true;
        }
        if (!cFDbTestClientConfigFile.canRead()) {
            log.message(S_ProcName + "ERROR: Permission denied attempting to read client configuration file "
                    + cFDbTestClientConfigFileName);
            fastExit = true;
        }
        cFDbTestClientConfig.load();

        if (fastExit) {
            return;
        }

        // Configure logging
        Properties sysProps = System.getProperties();
        sysProps.setProperty("log4j.rootCategory", "WARN");
        sysProps.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Logger httpLogger = Logger.getLogger("org.apache.http");
        httpLogger.setLevel(Level.WARN);

        ICFAsteriskSchema cFAsteriskSchema = new CFAsteriskMySqlSchema();
        cFAsteriskSchema.setConfigurationFile(cFAsteriskConfig);
        ICFAsteriskSchemaObj cFAsteriskSchemaObj = new CFAsteriskSchemaObj();
        cFAsteriskSchemaObj.setBackingStore(cFAsteriskSchema);
        CFAsteriskSaxLoaderCLI cli = new CFAsteriskSaxMySqlLoaderCLI();
        CFAsteriskSaxLoader loader = cli.getSaxLoader();
        loader.setSchemaObj(cFAsteriskSchemaObj);
        cFAsteriskSchema.connect();
        String url = args[1];
        if (numArgs >= 5) {
            cli.setClusterName(args[2]);
            cli.setTenantName(args[3]);
            cli.setSecUserName(args[4]);
        } else {
            cli.setClusterName("default");
            cli.setTenantName("system");
            cli.setSecUserName("system");
        }
        loader.setUseCluster(cli.getClusterObj());
        loader.setUseTenant(cli.getTenantObj());
        try {
            cFAsteriskSchema.beginTransaction();
            cFAsteriskSchemaObj.setSecCluster(cli.getClusterObj());
            cFAsteriskSchemaObj.setSecTenant(cli.getTenantObj());
            cFAsteriskSchemaObj.setSecUser(cli.getSecUserObj());
            cFAsteriskSchemaObj.setSecSession(cli.getSecSessionObj());
            CFSecurityAuthorization auth = new CFSecurityAuthorization();
            auth.setSecCluster(cFAsteriskSchemaObj.getSecCluster());
            auth.setSecTenant(cFAsteriskSchemaObj.getSecTenant());
            auth.setSecSession(cFAsteriskSchemaObj.getSecSession());
            cFAsteriskSchemaObj.setAuthorization(auth);
            applyLoaderOptions(loader, args[0]);
            if (numArgs >= 5) {
                cli.evaluateRemainingArgs(args, 5);
            } else {
                cli.evaluateRemainingArgs(args, 2);
            }
            loader.parseFile(url);
            cFAsteriskSchema.commit();
            cFAsteriskSchema.disconnect(true);
        } catch (Exception e) {
            log.message(S_ProcName + "EXCEPTION: Could not parse XML file \"" + url + "\": " + e.getMessage());
            e.printStackTrace(System.out);
        } catch (Error e) {
            log.message(S_ProcName + "ERROR: Could not parse XML file \"" + url + "\": " + e.getMessage());
            e.printStackTrace(System.out);
        } finally {
            if (cFAsteriskSchema.isConnected()) {
                cFAsteriskSchema.rollback();
                cFAsteriskSchema.disconnect(false);
            }
        }
    } else {
        log.message(S_ProcName
                + "ERROR: Expected at least two argument specifying the loader options and the name of the XML file to parse.  The first argument may be empty.");
    }
}