Example usage for java.io File getPath

List of usage examples for java.io File getPath

Introduction

In this page you can find the example usage for java.io File getPath.

Prototype

public String getPath() 

Source Link

Document

Converts this abstract pathname into a pathname string.

Usage

From source file:com.rtl.http.Upload.java

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

    if (args.length != 4) {
        // Jxj001 20150603 d:\rpt_rtl_0001.txt d:\confDir
        logger.error("??4,dataTypedataVersionfilePathconfDir");
        // System.out.println("??3,dataTypedataVersionfilePath");
        return;/*ww  w  . java 2s.  c o m*/
    } else {
        Upload upload = new Upload();
        upload.readInfo(args[3]);

        Date date = new Date();
        DateFormat format1 = new SimpleDateFormat("yyyyMMdd");
        String todayDir = format1.format(date);

        File dir = new File(logDir + File.separator + todayDir);
        if (dir != null && !dir.exists()) {
            dir.mkdirs();
        }

        //         SimpleLayout layout = new SimpleLayout();
        PatternLayout layout = new PatternLayout("%d %-5p %c - %m%n");

        FileAppender appender = null;

        try {

            appender = new FileAppender(layout, dir.getPath() + File.separator + todayDir + "client.log", true);

        } catch (Exception e) {
            logger.error("");
        }

        logger.addAppender(appender);
        logger.setLevel(Level.INFO);

        InputStream fileIn;
        dataType = args[0];
        dataVersion = args[1];
        filePath = args[2];

        logger.info("dataType=" + dataType);
        logger.info("dataVersion=" + dataVersion);
        logger.info("filePath=" + filePath);

        try {
            File file = new File(filePath);
            if (!file.exists()) {
                // System.out.println("?:"+filePath);
                logger.error("?:" + filePath);
                return;
            }
            fileIn = new FileInputStream(filePath);
            String responseStr = send(upload.getJson(), fileIn, url);
            if (responseStr != null) {
                String[] values = responseStr.split(",");
                if ("ok".equals(values[0])) {
                    System.out.println("0");
                    logger.info("ok");
                } else {
                    System.out.println("1");
                    logger.info(" A" + values[1]);
                }
            } else {
                System.out.println("1");
                logger.info(" B????");
            }

        } catch (Exception e) {
            System.out.println("1");
            logger.error(" C" + e.getMessage());
        }
    }

    logger.info("??");
    // System.out.println("??");

}

From source file:be.redlab.maven.yamlprops.create.YamlConvertCli.java

public static void main(String... args) throws IOException {
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();
    HelpFormatter formatter = new HelpFormatter();
    options.addOption(Option.builder("s").argName("source").desc("the source folder or file to convert")
            .longOpt("source").hasArg(true).build());
    options.addOption(Option.builder("t").argName("target").desc("the target file to store in")
            .longOpt("target").hasArg(true).build());
    options.addOption(Option.builder("h").desc("print help").build());

    try {/*from   w w w  .  ja v a2  s .  co m*/
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption('h')) {
            formatter.printHelp("converter", options);
        }
        File source = new File(cmd.getOptionValue("s", System.getProperty("user.dir")));
        String name = source.getName();
        if (source.isDirectory()) {
            PropertiesToYamlConverter yamlConverter = new PropertiesToYamlConverter();
            String[] ext = { "properties" };
            Iterator<File> fileIterator = FileUtils.iterateFiles(source, ext, true);
            while (fileIterator.hasNext()) {
                File next = fileIterator.next();
                System.out.println(next);
                String s = StringUtils.removeStart(next.getParentFile().getPath(), source.getPath());
                System.out.println(s);
                String f = StringUtils.split(s, IOUtils.DIR_SEPARATOR)[0];
                System.out.println("key = " + f);
                Properties p = new Properties();
                try {
                    p.load(new FileReader(next));
                    yamlConverter.addProperties(f, p);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileWriter fileWriter = new FileWriter(
                    new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml"));
            yamlConverter.writeYaml(fileWriter);
            fileWriter.close();
        } else {
            Properties p = new Properties();
            p.load(new FileReader(source));
            FileWriter fileWriter = new FileWriter(
                    new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml"));
            new PropertiesToYamlConverter().addProperties(name, p).writeYaml(fileWriter);
            fileWriter.close();
        }
    } catch (ParseException e) {
        e.printStackTrace();
        formatter.printHelp("converter", options);
    }
}

From source file:com.zimbra.cs.lmtpserver.utils.LmtpInject.java

public static void main(String[] args) {
    CliUtil.toolSetup();//from w  w  w. j a  v a2s.  com
    CommandLine cl = parseArgs(args);

    if (cl.hasOption("h")) {
        usage(null);
    }
    boolean quietMode = cl.hasOption("q");
    int threads = 1;
    if (cl.hasOption("t")) {
        threads = Integer.valueOf(cl.getOptionValue("t")).intValue();
    }

    String host = null;
    if (cl.hasOption("a")) {
        host = cl.getOptionValue("a");
    } else {
        host = "localhost";
    }

    int port;
    Protocol proto = null;
    if (cl.hasOption("smtp")) {
        proto = Protocol.SMTP;
        port = 25;
    } else
        port = 7025;
    if (cl.hasOption("p"))
        port = Integer.valueOf(cl.getOptionValue("p")).intValue();

    String[] recipients = cl.getOptionValues("r");
    String sender = cl.getOptionValue("s");
    boolean tracingEnabled = cl.hasOption("T");

    int everyN;
    if (cl.hasOption("N")) {
        everyN = Integer.valueOf(cl.getOptionValue("N")).intValue();
    } else {
        everyN = 100;
    }

    // Process files from the -d option.
    List<File> files = new ArrayList<File>();
    if (cl.hasOption("d")) {
        File dir = new File(cl.getOptionValue("d"));
        if (!dir.isDirectory()) {
            System.err.format("%s is not a directory.\n", dir.getPath());
            System.exit(1);
        }
        File[] fileArray = dir.listFiles();
        if (fileArray == null || fileArray.length == 0) {
            System.err.format("No files found in directory %s.\n", dir.getPath());
        }
        Collections.addAll(files, fileArray);
    }

    // Process files specified as arguments.
    for (String arg : cl.getArgs()) {
        files.add(new File(arg));
    }

    // Validate file content.
    if (!cl.hasOption("noValidation")) {
        Iterator<File> i = files.iterator();
        while (i.hasNext()) {
            InputStream in = null;
            File file = i.next();
            boolean valid = false;
            try {
                in = new FileInputStream(file);
                if (FileUtil.isGzipped(file)) {
                    in = new GZIPInputStream(in);
                }
                in = new BufferedInputStream(in); // Required for RFC 822 check
                if (!EmailUtil.isRfc822Message(in)) {
                    System.err.format("%s does not contain a valid RFC 822 message.\n", file.getPath());
                } else {
                    valid = true;
                }
            } catch (IOException e) {
                System.err.format("Unable to validate %s: %s.\n", file.getPath(), e.toString());
            } finally {
                ByteUtil.closeStream(in);
            }
            if (!valid) {
                i.remove();
            }
        }
    }

    if (files.size() == 0) {
        System.err.println("No files to inject.");
        System.exit(1);
    }

    if (!quietMode) {
        System.out.format(
                "Injecting %d message(s) to %d recipient(s).  Server %s, port %d, using %d thread(s).\n",
                files.size(), recipients.length, host, port, threads);
    }

    int totalFailed = 0;
    int totalSucceeded = 0;
    long startTime = System.currentTimeMillis();
    boolean verbose = cl.hasOption("v");
    boolean skipTLSCertValidation = cl.hasOption("skipTLSCertValidation");

    LmtpInject injector = null;
    try {
        injector = new LmtpInject(threads, sender, recipients, files, host, port, proto, quietMode,
                tracingEnabled, verbose, skipTLSCertValidation);
    } catch (Exception e) {
        mLog.error("Unable to initialize LmtpInject", e);
        System.exit(1);
    }

    injector.setReportEvery(everyN);
    injector.markStartTime();
    try {
        injector.run();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    int succeeded = injector.getSuccessCount();
    int failedThisTime = injector.getFailureCount();
    long elapsedMS = System.currentTimeMillis() - startTime;
    double elapsed = elapsedMS / 1000.0;
    double msPerMsg = 0.0;
    double msgSizeKB = 0.0;
    if (succeeded > 0) {
        msPerMsg = elapsedMS;
        msPerMsg /= succeeded;
        msgSizeKB = injector.mFileSizeTotal / 1024.0;
        msgSizeKB /= succeeded;
    }
    double msgPerSec = ((double) succeeded / (double) elapsedMS) * 1000;
    if (!quietMode) {
        System.out.println();
        System.out.printf(
                "LmtpInject Finished\n" + "submitted=%d failed=%d\n" + "%.2fs, %.2fms/msg, %.2fmsg/s\n"
                        + "average message size = %.2fKB\n",
                succeeded, failedThisTime, elapsed, msPerMsg, msgPerSec, msgSizeKB);
    }

    totalFailed += failedThisTime;
    totalSucceeded += succeeded;

    if (totalFailed != 0)
        System.exit(1);
}

From source file:com.shieldsbetter.sbomg.Cli.java

public static void main(String[] args) {
    int result;// w  ww .  j a v  a2  s  .c om

    try {
        Options options = new Options();
        options.addOption("f", false, "Force overwrite of files that already exist.");
        options.addOption("q", false, "Quiet all non-error output.");

        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);

        try {
            Plan p = makePlan(cmd);

            for (File input : p.files()) {
                if (!cmd.hasOption('q')) {
                    System.out.println("Processing " + input.getPath() + "...");
                }

                String modelName = nameWithoutExtension(input);
                File targetPath = p.getDestinationPath(input);
                try (Scanner inputScan = fileToScanner("input", input);
                        Writer outputWriter = outputPathToWriter(targetPath, modelName, cmd);) {
                    Object modelDesc = parseSbomgV1(inputScan);

                    try {
                        ViewModelGenerator.generate(p.getPackage(input), modelName, modelDesc, outputWriter);
                    } catch (IOException ioe) {
                        throw new FileException(buildOutputFile(targetPath, modelName), "writing to target",
                                ioe.getMessage());
                    }
                } catch (IOException ioe) {
                    throw new FileException(buildOutputFile(targetPath, modelName), "opening target",
                            ioe.getMessage());
                }
            }

            result = 0;
        } catch (OperationException oe) {
            System.err.println();
            System.err.println(oe.getMessage());
            result = 1;
        }
    } catch (FileException fe) {
        System.err.println();
        System.err.println("Error " + fe.getTask() + " file " + fe.getFile().getPath() + ":");
        System.err.println("    " + fe.getMessage());

        result = 1;
    } catch (ParseException pe) {
        throw new RuntimeException(pe);
    }

    System.exit(result);
}

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

public static void main(String args[]) {
    final String S_ProcName = "CFAsteriskSwingHttpCLI.main() ";
    initConsoleLog();//from   www .j  av a 2 s. c  o m
    boolean fastExit = false;

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

    CFAsteriskClientConfigurationFile cFAsteriskClientConfig = new CFAsteriskClientConfigurationFile();
    String cFAsteriskClientConfigFileName = homeDir.getPath() + File.separator + ".cfasteriskclientrc";
    cFAsteriskClientConfig.setFileName(cFAsteriskClientConfigFileName);
    File cFAsteriskClientConfigFile = new File(cFAsteriskClientConfigFileName);
    if (!cFAsteriskClientConfigFile.exists()) {
        String cFAsteriskKeyStoreFileName = homeDir.getPath() + File.separator + ".msscfjceks";
        cFAsteriskClientConfig.setKeyStore(cFAsteriskKeyStoreFileName);
        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();
        cFAsteriskClientConfig.setDeviceName(deviceName);
        cFAsteriskClientConfig.save();
        log.message(S_ProcName + "INFO: Created CFAsterisk client configuration file "
                + cFAsteriskClientConfigFileName);
        fastExit = true;
    }
    if (!cFAsteriskClientConfigFile.isFile()) {
        log.message(S_ProcName + "ERROR: Proposed client configuration file " + cFAsteriskClientConfigFileName
                + " is not a file.");
        fastExit = true;
    }
    if (!cFAsteriskClientConfigFile.canRead()) {
        log.message(S_ProcName + "ERROR: Permission denied attempting to read client configuration file "
                + cFAsteriskClientConfigFileName);
        fastExit = true;
    }
    cFAsteriskClientConfig.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);

    // The Invoker and it's implementation
    CFAsteriskXMsgClientHttpSchema invoker = new CFAsteriskXMsgClientHttpSchema();

    // And now for the client side cache implementation that invokes it
    ICFAsteriskSchemaObj clientSchemaObj = new CFAsteriskSchemaObj() {
        public void logout() {
            CFAsteriskXMsgClientHttpSchema invoker = (CFAsteriskXMsgClientHttpSchema) getBackingStore();
            try {
                invoker.logout(getAuthorization());
            } catch (RuntimeException e) {
            }
            setAuthorization(null);
        }
    };
    clientSchemaObj.setBackingStore(invoker);
    // And stitch the response handler to reference our client instance
    invoker.setResponseHandlerSchemaObj(clientSchemaObj);
    // And now we can stitch together the CLI to the SAX loader code
    CFAsteriskSwingHttpCLI cli = new CFAsteriskSwingHttpCLI();
    cli.setXMsgClientHttpSchema(invoker);
    cli.setSchema(clientSchemaObj);
    ICFAsteriskSwingSchema swing = cli.getSwingSchema();
    swing.setClientConfigurationFile(cFAsteriskClientConfig);
    swing.setSchema(clientSchemaObj);
    swing.setClusterName("system");
    swing.setTenantName("system");
    swing.setSecUserName("system");
    JFrame jframe = cli.getDesktop();
    jframe.setVisible(true);
    jframe.toFront();
}

From source file:com.siva.filewritterprogram.Mp3FileWritterTool.java

public static void main(String[] args) {
    File directory = new File("D:\\Siva\\Entertainment\\EvergreenHits");

    FileFilter filter = new FileFilter() {
        @Override/*from   w  ww .  j  av a  2s . c  o  m*/
        public boolean accept(File file) {
            if (file.getName().endsWith(".mp3")) {
                return true;
            } else {
                return false;
            }
        }
    };
    File[] subdirs = directory.listFiles();
    for (File subDir : subdirs) {
        try {
            System.out.println("Going to read files under : " + subDir);
            if (subDir.isDirectory()) {
                File[] files = subDir.listFiles(filter);
                if (files != null) {
                    for (File file : files) {
                        FileUtils.copyFileToDirectory(file, new File(directory.getPath() + "\\toTransfer"));
                    }
                } else {
                    System.out.println("There are no songs inside. [" + subDir.getName() + "]");
                }
            } else {
                System.out.println("Not a directory. [" + subDir.getName() + "]");
            }
        } catch (IOException ex) {
            Logger.getLogger(Mp3FileWritterTool.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.github.xbn.examples.io.non_xbn.SizeOrderAllFilesInDirXmpl.java

public static final void main(String[] ignored) {
    File fDir = (new File("R:\\jeffy\\programming\\sandbox\\xbnjava\\xbn\\"));
    Collection<File> cllf = FileUtils.listFiles(fDir, (new String[] { "java" }), true);

    //Add all file paths to a Map, keyed by size.
    //It's actually a map of lists-of-files, to
    //allow multiple files that happen to have the
    //same length.

    TreeMap<Long, List<File>> tmFilesBySize = new TreeMap<Long, List<File>>();
    Iterator<File> itrf = cllf.iterator();
    while (itrf.hasNext()) {
        File f = itrf.next();
        Long LLen = f.length();//w  ww .  ja v  a2s  . co  m
        if (!tmFilesBySize.containsKey(LLen)) {
            ArrayList<File> alf = new ArrayList<File>();
            alf.add(f);
            tmFilesBySize.put(LLen, alf);
        } else {
            tmFilesBySize.get(LLen).add(f);
        }
    }

    //Iterate backwards by key through the map. For each
    //List<File>, iterate through the files, printing out
    //its size and path.

    ArrayList<Long> alSize = new ArrayList<Long>(tmFilesBySize.keySet());
    for (int i = alSize.size() - 1; i >= 0; i--) {
        itrf = tmFilesBySize.get(alSize.get(i)).iterator();
        while (itrf.hasNext()) {
            File f = itrf.next();
            System.out.println(f.length() + ": " + f.getPath());
        }
    }
}

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();/*  w w w .  j  ava 2s . c  om*/
    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();//  ww w .j  a  v  a  2  s. 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();/*  ww w  . j  av 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 + ".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.");
    }
}