Example usage for org.apache.commons.lang3 StringUtils split

List of usage examples for org.apache.commons.lang3 StringUtils split

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils split.

Prototype

public static String[] split(final String str, final String separatorChars) 

Source Link

Document

Splits the provided text into an array, separators specified.

Usage

From source file:net.ontopia.persistence.rdbms.DDLWriter.java

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

    // Initialize logging
    CmdlineUtils.initializeLogging();// w ww .  j a v a2 s.  c o m

    // Initialize command line option parser and listeners
    CmdlineOptions options = new CmdlineOptions("DDLWriter", argv);

    // Register logging options
    CmdlineUtils.registerLoggingOptions(options);

    // Parse command line options
    try {
        options.parse();
    } catch (CmdlineOptions.OptionsException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    // Get command line arguments
    String[] args = options.getArguments();
    if (args.length < 3) {
        System.err.println("Error: need exactly two files as arguments.");
        usage();
        System.exit(1);
    }

    String schema = args[0];
    String dbtype = args[1];
    String[] platforms = StringUtils.split(args[2], ",");
    String createfile = args[3];
    String dropfile = args[4];

    Project project = DatabaseProjectReader.loadProject(schema);

    GenericSQLProducer producer;
    switch (dbtype) {
    case "postgresql":
        producer = new PostgreSQLProducer(project, platforms);
        break;
    case "oracle":
        producer = new OracleSQLProducer(project, platforms);
        break;
    case "sqlserver":
        producer = new SQLServerSQLProducer(project, platforms);
        break;
    case "mysql":
        producer = new MySqlSQLProducer(project, platforms);
        break;
    case "db2":
        producer = new DB2SQLProducer(project, platforms);
        break;
    case "firebird":
        producer = new FirebirdSQLProducer(project, platforms);
        break;
    default:
        producer = new GenericSQLProducer(project, platforms);
        break;
    }

    // Generate create file
    Writer cwriter = new FileWriter(createfile);
    producer.writeCreate(cwriter);
    cwriter.close();

    // Generate create file
    Writer dwriter = new FileWriter(dropfile);
    producer.writeDrop(dwriter);
    dwriter.close();
}

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   www . j av a2  s .c o  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:net.ontopia.persistence.rdbms.DDLExecuter.java

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

    // Initialize logging
    CmdlineUtils.initializeLogging();//from w  w w .  j  ava  2s  .  com

    // Initialize command line option parser and listeners
    CmdlineOptions options = new CmdlineOptions("DDLExecuter", argv);

    // Register logging options
    CmdlineUtils.registerLoggingOptions(options);

    // Parse command line options
    try {
        options.parse();
    } catch (CmdlineOptions.OptionsException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    // Get command line arguments
    String[] args = options.getArguments();
    if (args.length < 2) {
        System.err.println("Error: wrong number of arguments.");
        usage();
        System.exit(1);
    }

    String schema = args[0];
    String dbprops = args[1];
    String action = args[2];

    if (!("create".equals(action) || "drop".equals(action) || "recreate".equals(action))) {
        System.err.println("Error: unknown action: " + action);
        usage();
        System.exit(1);
    }

    // Load property file
    Properties props = new Properties();
    props.load(new FileInputStream(dbprops));

    // Get database properties from property file
    String[] platforms = StringUtils.split(props.getProperty("net.ontopia.topicmaps.impl.rdbms.Platforms"),
            ",");

    Project project = DatabaseProjectReader.loadProject(schema);

    //! //! if (dbtype.equals("generic"))
    //! //!   producer = new GenericSQLProducer(project, StringUtils.split(dbtype, ","));
    //! //! else
    //! if (dbtype.equals("mysql"))
    //!   producer = new MySqlSQLProducer(project);
    //! else if (dbtype.equals("oracle"))
    //!   producer = new OracleSQLProducer(project);
    //! else {
    //!   producer = new GenericSQLProducer(project, StringUtils.split(dbtype, ","));
    //!   //! System.err.println("Error: unknown database type: " + dbtype);
    //!   //! usage();
    //!   //! System.exit(1);
    //! }

    // Create SQL producer
    GenericSQLProducer producer = getSQLProducer(project, platforms);
    log.debug("Using SQL producer: " + producer);

    // Create database connection
    DefaultConnectionFactory cfactory = new DefaultConnectionFactory(props, false);
    Connection conn = cfactory.requestConnection();

    // Execute statements
    try {
        if ("create".equals(action))
            producer.executeCreate(conn);
        else if ("drop".equals(action))
            producer.executeDrop(conn);
        else if ("recreate".equals(action)) {
            producer.executeDrop(conn);
            producer.executeCreate(conn);
        }
        conn.commit();
    } finally {
        if (conn != null)
            conn.close();
    }
}

From source file:io.wcm.devops.conga.tooling.cli.CongaCli.java

/**
 * CLI entry point/*from  w ww . j a  v a 2 s.  com*/
 * @param args Command line arguments
 * @throws Exception
 */
//CHECKSTYLE:OFF
public static void main(String[] args) throws Exception {
    //CHECKSTYLE:ON
    CommandLine commandLine = new DefaultParser().parse(CLI_OPTIONS, args);

    if (commandLine.hasOption("?")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(150);
        formatter.printHelp("java -cp io.wcm.devops.conga.tooling.cli-<version>.jar "
                + "io.wcm.devops.conga.tooling.cli.CongaCli <arguments>", CLI_OPTIONS);
        return;
    }

    String templateDir = commandLine.getOptionValue("templateDir", "templates");
    String roleDir = commandLine.getOptionValue("roleDir", "roles");
    String environmentDir = commandLine.getOptionValue("environmentDir", "environments");
    String targetDir = commandLine.getOptionValue("target", "target");
    String[] environments = StringUtils.split(commandLine.getOptionValue("environments", null), ",");

    ResourceLoader resourceLoader = new ResourceLoader();
    List<ResourceCollection> roleDirs = ImmutableList
            .of(resourceLoader.getResourceCollection(ResourceLoader.FILE_PREFIX + roleDir));
    List<ResourceCollection> templateDirs = ImmutableList
            .of(resourceLoader.getResourceCollection(ResourceLoader.FILE_PREFIX + templateDir));
    List<ResourceCollection> environmentDirs = ImmutableList
            .of(resourceLoader.getResourceCollection(ResourceLoader.FILE_PREFIX + environmentDir));
    File targetDirecotry = new File(targetDir);

    Generator generator = new Generator(roleDirs, templateDirs, environmentDirs, targetDirecotry);
    generator.setDeleteBeforeGenerate(true);
    generator.generate(environments);
}

From source file:net.ontopia.persistence.rdbms.CSVExport.java

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

    // Initialize logging
    CmdlineUtils.initializeLogging();/*from w  w w.j a  va  2s  . c  o  m*/

    // Initialize command line option parser and listeners
    CmdlineOptions options = new CmdlineOptions("CSVExport", argv);
    OptionsListener ohandler = new OptionsListener();

    // Register local options
    options.addLong(ohandler, "separator", 's', true);

    // Register logging options
    CmdlineUtils.registerLoggingOptions(options);

    // Parse command line options
    try {
        options.parse();
    } catch (CmdlineOptions.OptionsException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    // Get command line arguments
    String[] args = options.getArguments();
    if (args.length < 3) {
        System.err.println("Error: wrong number of arguments.");
        usage();
        System.exit(1);
    }

    String dbprops = args[0];
    String table = args[1];
    String[] columns = StringUtils.split(args[2], ",");

    // Load property file
    Properties props = new Properties();
    props.load(new FileInputStream(dbprops));

    // Create database connection
    DefaultConnectionFactory cfactory = new DefaultConnectionFactory(props, true);
    Connection conn = cfactory.requestConnection();

    CSVExport ce = new CSVExport(conn);
    ce.setSeparator(ohandler.separator);
    //! ce.setUseQuotes(ohandler.usequotes);

    ce.exportCSV(new OutputStreamWriter(System.out), table, columns);
}

From source file:net.ontopia.persistence.rdbms.CSVImport.java

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

    // Initialize logging
    CmdlineUtils.initializeLogging();/*from  w  ww .  j  a  v  a 2  s. c  o  m*/

    // Initialize command line option parser and listeners
    CmdlineOptions options = new CmdlineOptions("CSVImport", argv);
    OptionsListener ohandler = new OptionsListener();

    // Register local options
    options.addLong(ohandler, "separator", 's', true);
    options.addLong(ohandler, "stripquotes", 'q');
    options.addLong(ohandler, "ignorelines", 'i', true);

    // Register logging options
    CmdlineUtils.registerLoggingOptions(options);

    // Parse command line options
    try {
        options.parse();
    } catch (CmdlineOptions.OptionsException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    // Get command line arguments
    String[] args = options.getArguments();
    if (args.length < 4) {
        System.err.println("Error: wrong number of arguments.");
        usage();
        System.exit(1);
    }

    String schema = args[0];
    String dbprops = args[1];
    String csvfile = args[2];
    String table = args[3];
    String[] columns = StringUtils.split(args[4], ",");

    // Load property file
    Properties props = new Properties();
    props.load(new FileInputStream(dbprops));

    // Create database connection
    DefaultConnectionFactory cfactory = new DefaultConnectionFactory(props, false);
    Connection conn = cfactory.requestConnection();

    CSVImport ci = new CSVImport(DatabaseProjectReader.loadProject(schema), conn);
    ci.setTable(table);
    ci.setColumns(columns);
    ci.setSeparator(ohandler.separator);
    ci.setClearTable(true);
    ci.setStripQuotes(ohandler.stripquotes);
    ci.setIgnoreColumns(true);
    ci.setIgnoreLines(ohandler.ignorelines);

    ci.importCSV(new FileInputStream(csvfile));
}

From source file:net.ontopia.topicmaps.db2tm.Execute.java

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

    // Initialize logging
    CmdlineUtils.initializeLogging();/*from   w ww. j a va2s  . co m*/

    // Register logging options
    CmdlineOptions options = new CmdlineOptions("Execute", argv);
    CmdlineUtils.registerLoggingOptions(options);
    OptionsListener ohandler = new OptionsListener();
    options.addLong(ohandler, "tm", 't', true);
    options.addLong(ohandler, "baseuri", 'b', true);
    options.addLong(ohandler, "out", 'o', true);
    options.addLong(ohandler, "relations", 'r', true);
    options.addLong(ohandler, "force-rescan", 'f', true);

    // Parse command line options
    try {
        options.parse();
    } catch (CmdlineOptions.OptionsException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    // Get command line arguments
    String[] args = options.getArguments();

    if (args.length < 2) {
        usage();
        System.exit(3);
    }

    // Arguments
    String operation = args[0];
    String cfgfile = args[1];

    if (!"add".equals(operation) && !"sync".equals(operation) && !"remove".equals(operation)) {
        usage();
        System.err.println("Operation '" + operation + "' not supported.");
        System.exit(3);
    }

    try {
        // Read mapping file
        log.debug("Reading relation mapping file {}", cfgfile);
        RelationMapping mapping = RelationMapping.read(new File(cfgfile));

        // open topic map
        String tmurl = ohandler.tm;
        log.debug("Opening topic map {}", tmurl);
        TopicMapIF topicmap;
        if (tmurl == null || "tm:in-memory:new".equals(tmurl))
            topicmap = new InMemoryTopicMapStore().getTopicMap();
        else if ("tm:rdbms:new".equals(tmurl))
            topicmap = new RDBMSTopicMapStore().getTopicMap();
        else {
            TopicMapReaderIF reader = ImportExportUtils.getReader(tmurl);
            topicmap = reader.read();
        }
        TopicMapStoreIF store = topicmap.getStore();

        // base locator
        String outfile = ohandler.out;
        LocatorIF baseloc = (outfile == null ? store.getBaseAddress() : new URILocator(new File(outfile)));
        if (baseloc == null && tmurl != null)
            baseloc = (ohandler.baseuri == null ? new URILocator(tmurl) : new URILocator(ohandler.baseuri));

        // figure out which relations to actually process
        Collection<String> relations = null;
        if (ohandler.relations != null) {
            String[] relnames = StringUtils.split(ohandler.relations, ",");
            if (relnames.length > 0) {
                relations = new HashSet<String>(relnames.length);
                relations.addAll(Arrays.asList(relnames));
            }
        }

        try {
            // Process data sources in mapping
            if ("add".equals(operation))
                Processor.addRelations(mapping, relations, topicmap, baseloc);
            else if ("sync".equals(operation)) {
                boolean rescan = ohandler.forceRescan != null
                        && Boolean.valueOf(ohandler.forceRescan).booleanValue();
                Processor.synchronizeRelations(mapping, relations, topicmap, baseloc, rescan);
            } else if ("remove".equals(operation))
                Processor.removeRelations(mapping, relations, topicmap, baseloc);
            else
                throw new UnsupportedOperationException("Unsupported operation: " + operation);

            // export topicmap
            if (outfile != null) {
                log.debug("Exporting topic map to {}", outfile);
                TopicMapWriterIF writer = ImportExportUtils.getWriter(new File(outfile));
                writer.write(topicmap);
            }

            // commit transaction
            store.commit();
            log.debug("Transaction committed.");
        } catch (Exception t) {
            log.error("Error occurred while running operation '" + operation + "'", t);
            // abort transaction
            store.abort();
            log.debug("Transaction aborted.");
            throw t;
        } finally {
            if (store.isOpen())
                store.close();
        }

    } catch (Exception e) {
        Throwable cause = e.getCause();
        if (cause instanceof DB2TMException)
            System.err.println("Error: " + e.getMessage());
        else
            throw e;
    }
}

From source file:hu.bme.mit.sette.run.Run.java

public static void main(String[] args) {
    LOG.debug("main() called");

    // parse properties
    Properties prop = new Properties();
    InputStream is = null;//from w  w  w .j  av  a2 s.com

    try {
        is = new FileInputStream(SETTE_PROPERTIES);
        prop.load(is);
    } catch (IOException e) {
        System.err.println("Parsing  " + SETTE_PROPERTIES + " has failed");
        e.printStackTrace();
        System.exit(1);
    } finally {
        IOUtils.closeQuietly(is);
    }

    String[] basedirs = StringUtils.split(prop.getProperty("basedir"), '|');
    String snippetDir = prop.getProperty("snippet-dir");
    String snippetProject = prop.getProperty("snippet-project");
    String catgPath = prop.getProperty("catg");
    String catgVersionFile = prop.getProperty("catg-version-file");
    String jPETPath = prop.getProperty("jpet");
    String jPETDefaultBuildXml = prop.getProperty("jpet-default-build.xml");
    String jPETVersionFile = prop.getProperty("jpet-version-file");
    String spfPath = prop.getProperty("spf");
    String spfDefaultBuildXml = prop.getProperty("spf-default-build.xml");
    String spfVersionFile = prop.getProperty("spf-version-file");
    String outputDir = prop.getProperty("output-dir");

    Validate.notEmpty(basedirs, "At least one basedir must be specified in " + SETTE_PROPERTIES);
    Validate.notBlank(snippetDir, "The property snippet-dir must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(snippetProject, "The property snippet-project must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(catgPath, "The property catg must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(jPETPath, "The property jpet must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(spfPath, "The property spf must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(outputDir, "The property output-dir must be set in " + SETTE_PROPERTIES);

    String basedir = null;
    for (String bd : basedirs) {
        bd = StringUtils.trimToEmpty(bd);

        if (bd.startsWith("~")) {
            // Linux home
            bd = System.getProperty("user.home") + bd.substring(1);
        }

        FileValidator v = new FileValidator(new File(bd));
        v.type(FileType.DIRECTORY);

        if (v.isValid()) {
            basedir = bd;
            break;
        }
    }

    if (basedir == null) {
        System.err.println("basedir = " + Arrays.toString(basedirs));
        System.err.println("ERROR: No valid basedir was found, please check " + SETTE_PROPERTIES);
        System.exit(2);
    }

    BASEDIR = new File(basedir);
    SNIPPET_DIR = new File(basedir, snippetDir);
    SNIPPET_PROJECT = snippetProject;
    OUTPUT_DIR = new File(basedir, outputDir);

    try {
        String catgVersion = readToolVersion(new File(BASEDIR, catgVersionFile));
        if (catgVersion != null) {
            new CatgTool(new File(BASEDIR, catgPath), catgVersion);
        }

        String jPetVersion = readToolVersion(new File(BASEDIR, jPETVersionFile));
        if (jPetVersion != null) {
            new JPetTool(new File(BASEDIR, jPETPath), new File(BASEDIR, jPETDefaultBuildXml), jPetVersion);
        }

        String spfVersion = readToolVersion(new File(BASEDIR, spfVersionFile));
        if (spfVersion != null) {
            new SpfTool(new File(BASEDIR, spfPath), new File(BASEDIR, spfDefaultBuildXml), spfVersion);
        }

        // TODO stuff
        stuff(args);
    } catch (Exception e) {
        System.err.println(ExceptionUtils.getStackTrace(e));

        ValidatorException vex = (ValidatorException) e;

        for (ValidationException v : vex.getValidator().getAllExceptions()) {
            v.printStackTrace();
        }

        // System.exit(0);

        e.printStackTrace();
        System.err.println("==========");
        e.printStackTrace();

        if (e instanceof ValidatorException) {
            System.err.println("Details:");
            System.err.println(((ValidatorException) e).getFullMessage());
        } else if (e.getCause() instanceof ValidatorException) {
            System.err.println("Details:");
            System.err.println(((ValidatorException) e.getCause()).getFullMessage());
        }
    }
}

From source file:ddc.commons.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  ww. j a  va  2 s  .  c om*/
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = 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;

    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("-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("-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("-t")) {
            mlst = true;
            minParams = 3;
        } 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("-PrH")) {
            proxyHost = args[++base];
            String parts[] = StringUtils.split(proxyHost, ':');
            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]
    {
        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);
    }
    ftp.setListHiddenFiles(hidden);

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

    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();
        } else if (listFiles) {
            if (lenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                ftp.configure(config);
            }

            for (FTPFile f : ftp.listFiles(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlsd) {
            for (FTPFile f : ftp.mlistDir(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlst) {
            FTPFile f = ftp.mlistFile(remote);
            if (f != null) {
                System.out.println(f.toFormattedString());
            }
        } else if (listNames) {
            for (String s : ftp.listNames(remote)) {
                System.out.println(s);
            }
        } 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:net.ontopia.topicmaps.db2tm.CSVImport.java

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

    // Initialize logging
    CmdlineUtils.initializeLogging();/* w w  w.  j a v a  2 s .  c o  m*/

    // Initialize command line option parser and listeners
    CmdlineOptions options = new CmdlineOptions("CSVImport", argv);
    OptionsListener ohandler = new OptionsListener();

    // Register local options
    options.addLong(ohandler, "separator", 's', true);
    options.addLong(ohandler, "stripquotes", 'q');
    options.addLong(ohandler, "ignorelines", 'i', true);

    // Register logging options
    CmdlineUtils.registerLoggingOptions(options);

    // Parse command line options
    try {
        options.parse();
    } catch (CmdlineOptions.OptionsException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    // Get command line arguments
    String[] args = options.getArguments();
    if (args.length < 2) {
        System.err.println("Error: wrong number of arguments.");
        usage();
        System.exit(1);
    }

    String dbprops = args[0];
    String csvfile = args[1];
    String table = (args.length >= 3 ? args[2] : null);
    if (table == null) {
        if (csvfile.endsWith(".csv"))
            table = csvfile.substring(0, csvfile.length() - 4);
        else
            table = csvfile;
    }
    String[] columns = (args.length >= 4 ? StringUtils.split(args[3], ",") : null);

    // Load property file
    Properties props = new Properties();
    props.load(new FileInputStream(dbprops));

    // Create database connection
    DefaultConnectionFactory cfactory = new DefaultConnectionFactory(props, false);
    Connection conn = cfactory.requestConnection();

    CSVImport ci = new CSVImport(conn);
    ci.setTable(table);
    ci.setColumns(columns);
    ci.setSeparator(ohandler.separator);
    ci.setClearTable(true);
    ci.setStripQuotes(ohandler.stripquotes);
    ci.setIgnoreColumns(true);
    ci.setIgnoreLines(ohandler.ignorelines);

    ci.importCSV(new FileInputStream(csvfile));
}