Example usage for java.lang String equals

List of usage examples for java.lang String equals

Introduction

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

Prototype

public boolean equals(Object anObject) 

Source Link

Document

Compares this string to the specified object.

Usage

From source file:json_cmp.Comparer.java

public static void main(String[] args) {
    System.out.println("Testing Begin");
    try {// w ww . j  a v a2s  . c o  m

        String accessLogFolder = "/Users/herizhao/workspace/accessLog/";
        //        String yqlFileName = "json_cmp/test1.log";
        //        String yqlpFileName = "json_cmp/test2.log";
        String yqlFileName = "tempLog/0812_yql.res";
        String yqlpFileName = "tempLog/0812_yqlp.res";
        ReadResults input1 = new ReadResults(accessLogFolder + yqlFileName);
        ReadResults input2 = new ReadResults(accessLogFolder + yqlpFileName);
        Integer diffNum = 0;
        Integer errorCount = 0;
        Integer totalIDNum1 = 0;
        Integer totalIDNum2 = 0;
        Integer equalIDwithDuplicate = 0;
        Integer beacons = 0;
        Integer lineNum = 0;
        Integer tempCount = 0;
        HashMap<String, IDclass> IDarray = new HashMap<String, IDclass>();
        FileOutputStream fos = new FileOutputStream(
                "/Users/herizhao/workspace/accessLog/json_cmp/cmp_result.txt");
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        BufferedWriter bw = new BufferedWriter(osw);
        FileOutputStream consoleStream = new FileOutputStream(
                "/Users/herizhao/workspace/accessLog/json_cmp/console");
        OutputStreamWriter consoleOSW = new OutputStreamWriter(consoleStream);
        BufferedWriter console = new BufferedWriter(consoleOSW);
        while (true) {
            input1.ReadNextLine();
            if (input1.line == null)
                break;
            input2.ReadNextLine();
            if (input2.line == null)
                break;
            while (input1.line.equals("")) {
                lineNum++;
                input1.ReadNextLine();
                input2.ReadNextLine();
            }
            if (input2.line == null)
                break;
            if (input1.line == null)
                break;
            lineNum++;
            System.out.println("lineNum = " + lineNum);
            String str1 = input1.line;
            String str2 = input2.line;
            ObjectMapper mapper1 = new ObjectMapper();
            ObjectMapper mapper2 = new ObjectMapper();
            JsonNode root1 = mapper1.readTree(str1);
            JsonNode root2 = mapper2.readTree(str2);
            JsonNode mediaNode1 = root1.path("query").path("results").path("mediaObj");
            JsonNode mediaNode2 = root2.path("query").path("results").path("mediaObj");
            if (mediaNode2.isMissingNode() && !mediaNode1.isMissingNode())
                tempCount += mediaNode1.size();
            //For yqlp
            if (mediaNode2.isArray()) {
                totalIDNum2 += mediaNode2.size();
                for (int i = 0; i < mediaNode2.size(); i++) {
                    ObjectNode mediaObj = (ObjectNode) mediaNode2.get(i);
                    mediaObj.put("yvap", "");
                    JsonNode streamsNode = mediaObj.path("streams");
                    //streams
                    if (streamsNode.isArray()) {
                        for (int j = 0; j < streamsNode.size(); j++) {
                            ObjectNode streamsObj = (ObjectNode) streamsNode.get(j);
                            changeStreamsPath(streamsObj);
                            ChangedHost(streamsObj);
                            //if(streamsObj.path("h264_profile").isMissingNode())
                            streamsObj.put("h264_profile", "");
                            if (streamsObj.path("is_primary").isMissingNode())
                                streamsObj.put("is_primary", false);
                        }
                    }
                    //meta
                    if (!mediaObj.path("meta").isMissingNode()) {
                        ObjectNode metaObj = (ObjectNode) mediaObj.path("meta");
                        changeMetaThumbnail(metaObj);
                        if (metaObj.path("show_name").isMissingNode())
                            metaObj.put("show_name", "");
                        if (metaObj.path("event_start").isMissingNode())
                            metaObj.put("event_start", "");
                        if (metaObj.path("event_stop").isMissingNode())
                            metaObj.put("event_stop", "");
                        //if(metaObj.path("credits").path("label").isMissingNode())
                        ((ObjectNode) metaObj.path("credits")).put("label", "");
                    }
                    //Metrics -> plidl & isrc
                    changeMetrics(mediaObj);
                }
            }

            //For yql
            if (mediaNode1.isArray()) {
                totalIDNum1 += mediaNode1.size();
                for (int i = 0; i < mediaNode1.size(); i++) {
                    JsonNode mediaObj = mediaNode1.get(i);
                    ((ObjectNode) mediaObj).put("yvap", "");
                    //Meta
                    //System.out.println("meta: ");
                    if (!mediaObj.path("meta").isMissingNode()) {
                        ObjectNode metaObj = (ObjectNode) mediaObj.path("meta");
                        changeMetaThumbnail(metaObj);
                        metaObj.put("event_start", "");
                        metaObj.put("event_stop", "");
                        FloatingtoInt(metaObj, "duration");
                        if (metaObj.path("show_name").isMissingNode())
                            metaObj.put("show_name", "");
                        //System.out.println("thub_dem: ");
                        if (!metaObj.path("thumbnail_dimensions").isMissingNode()) {
                            ObjectNode thub_demObj = (ObjectNode) metaObj.path("thumbnail_dimensions");
                            FloatingtoInt(thub_demObj, "height");
                            FloatingtoInt(thub_demObj, "width");
                        }
                        ((ObjectNode) metaObj.path("credits")).put("label", "");
                    }
                    //Visualseek
                    //System.out.println("visualseek: ");
                    if (!mediaObj.path("visualseek").isMissingNode()) {
                        ObjectNode visualseekObj = (ObjectNode) mediaObj.path("visualseek");
                        FloatingtoInt(visualseekObj, "frequency");
                        FloatingtoInt(visualseekObj, "width");
                        FloatingtoInt(visualseekObj, "height");
                        //visualseek -> images, float to int
                        JsonNode imagesNode = visualseekObj.path("images");
                        if (imagesNode.isArray()) {
                            for (int j = 0; j < imagesNode.size(); j++) {
                                ObjectNode imageObj = (ObjectNode) imagesNode.get(j);
                                FloatingtoInt(imageObj, "start_index");
                                FloatingtoInt(imageObj, "count");
                            }
                        }
                    }
                    //Streams
                    //System.out.println("streams: ");
                    JsonNode streamsNode = mediaObj.path("streams");
                    if (streamsNode.isArray()) {
                        for (int j = 0; j < streamsNode.size(); j++) {
                            ObjectNode streamsObj = (ObjectNode) streamsNode.get(j);
                            FloatingtoInt(streamsObj, "height");
                            FloatingtoInt(streamsObj, "bitrate");
                            FloatingtoInt(streamsObj, "duration");
                            FloatingtoInt(streamsObj, "width");
                            changeStreamsPath(streamsObj);
                            ChangedHost(streamsObj);
                            //                        if(streamsObj.path("h264_profile").isMissingNode())
                            streamsObj.put("h264_profile", "");
                            if (streamsObj.path("is_primary").isMissingNode())
                                streamsObj.put("is_primary", false);
                        }
                    }
                    //Metrics -> plidl & isrc
                    changeMetrics(mediaObj);
                }
            }

            //Compare
            if (mediaNode2.isArray() && mediaNode1.isArray()) {
                for (int i = 0; i < mediaNode2.size() && i < mediaNode1.size(); i++) {
                    JsonNode mediaObj1 = mediaNode1.get(i);
                    JsonNode mediaObj2 = mediaNode2.get(i);
                    if (!mediaObj1.equals(mediaObj2)) {
                        if (!mediaObj1.path("id").toString().equals(mediaObj2.path("id").toString())) {
                            errorCount++;
                        } else {
                            Integer IFdiffStreams = 0;
                            Integer IFdiffMeta = 0;
                            Integer IFdiffvisualseek = 0;
                            Integer IFdiffMetrics = 0;
                            Integer IFdifflicense = 0;
                            Integer IFdiffclosedcaptions = 0;
                            String statusCode = "";
                            MetaClass tempMeta = new MetaClass();
                            if (!mediaObj1.path("status").equals(mediaObj2.path("status"))) {
                                JsonNode statusNode1 = mediaObj1.path("status");
                                JsonNode statusNode2 = mediaObj2.path("status");
                                if (statusNode2.path("code").toString().equals("\"100\"")
                                        || (statusNode1.path("code").toString().equals("\"400\"")
                                                && statusNode1.path("code").toString().equals("\"404\""))
                                        || (statusNode1.path("code").toString().equals("\"200\"")
                                                && statusNode1.path("code").toString().equals("\"200\""))
                                        || (statusNode1.path("code").toString().equals("\"200\"")
                                                && statusNode1.path("code").toString().equals("\"403\"")))
                                    statusCode = "";
                                else
                                    statusCode = "yql code: " + mediaObj1.path("status").toString()
                                            + " yqlp code:" + mediaObj2.path("status").toString();
                            } else {//Status code is 100
                                if (!mediaObj1.path("streams").equals(mediaObj2.path("streams")))
                                    IFdiffStreams = 1;
                                if (!tempMeta.CompareMeta(mediaObj1.path("meta"), mediaObj2.path("meta"),
                                        lineNum))
                                    IFdiffMeta = 1;
                                if (!mediaObj1.path("visualseek").equals(mediaObj2.path("visualseek")))
                                    IFdiffvisualseek = 1;
                                if (!mediaObj1.path("metrics").equals(mediaObj2.path("metrics"))) {
                                    IFdiffMetrics = 1;
                                    JsonNode metrics1 = mediaObj1.path("metrics");
                                    JsonNode metrics2 = mediaObj2.path("metrics");
                                    if (!metrics1.path("beacons").equals(metrics2.path("beacons")))
                                        beacons++;
                                }
                                if (!mediaObj1.path("license").equals(mediaObj2.path("license")))
                                    IFdifflicense = 1;
                                if (!mediaObj1.path("closedcaptions").equals(mediaObj2.path("closedcaptions")))
                                    IFdiffclosedcaptions = 1;
                            }
                            if (IFdiffStreams + IFdiffMeta + IFdiffvisualseek + IFdiffMetrics + IFdifflicense
                                    + IFdiffclosedcaptions != 0 || !statusCode.equals("")) {
                                String ID_str = mediaObj1.path("id").toString();
                                if (!IDarray.containsKey(ID_str)) {
                                    IDclass temp_IDclass = new IDclass(ID_str);
                                    temp_IDclass.addNum(IFdiffStreams, IFdiffMeta, IFdiffvisualseek,
                                            IFdiffMetrics, IFdifflicense, IFdiffclosedcaptions, lineNum);
                                    if (!statusCode.equals(""))
                                        temp_IDclass.statusCode = statusCode;
                                    IDarray.put(ID_str, temp_IDclass);
                                } else {
                                    IDarray.get(ID_str).addNum(IFdiffStreams, IFdiffMeta, IFdiffvisualseek,
                                            IFdiffMetrics, IFdifflicense, IFdiffclosedcaptions, lineNum);
                                    if (!statusCode.equals(""))
                                        IDarray.get(ID_str).statusCode = statusCode;
                                }
                                IDarray.get(ID_str).stream.CompareStream(IFdiffStreams,
                                        mediaObj1.path("streams"), mediaObj2.path("streams"), lineNum);
                                if (!IDarray.get(ID_str).metaDone) {
                                    IDarray.get(ID_str).meta = tempMeta;
                                    IDarray.get(ID_str).metaDone = true;
                                }
                            } else
                                equalIDwithDuplicate++;
                        }
                    } else
                        equalIDwithDuplicate++;
                }
            }
            bw.flush();
            console.flush();

        } //while
        System.out.println("done");
        bw.write("Different ID" + "   " + "num   ");
        bw.write(PrintStreamsTitle());
        bw.write(PrintMetaTitle());
        bw.write(PrintTitle());
        bw.newLine();
        Iterator<String> iter = IDarray.keySet().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            bw.write(key + "   ");
            bw.write(IDarray.get(key).num.toString() + "   ");
            bw.write(IDarray.get(key).stream.print());
            bw.write(IDarray.get(key).meta.print());
            bw.write(IDarray.get(key).print());
            bw.newLine();
            //System.out.println(key);
        }
        //System.out.println("different log num = " + diffNum);
        //System.out.println("same log num = " + sameLogNum);
        System.out.println("Different ID size = " + IDarray.size());
        //         System.out.println("streamEqual = " + streamEqual);
        //         System.out.println("metaEqual = " + metaEqual);
        //         System.out.println("metricsEqual = " + metricsEqual);
        //         System.out.println("visualseekEqual = " + visualseekEqual);
        //         System.out.println("licenseEqual = " + licenseEqual);
        //         System.out.println("closedcaptionsEqualEqual = " + closedcaptionsEqual);
        System.out.println(tempCount);
        System.out.println("beacons = " + beacons);
        System.out.println("equalIDwithDuplicate = " + equalIDwithDuplicate);
        System.out.println("Total ID num yql (including duplicates) = " + totalIDNum1);
        System.out.println("Total ID num yqpl (including duplicates) = " + totalIDNum2);
        System.out.println("Error " + errorCount);
        bw.close();
        console.close();
    } catch (IOException e) {
    }
}

From source file:com.mijecu25.sqlplus.SQLPlus.java

public static void main(String[] args) throws IOException {
    // Create and load the properties from the application properties file
    Properties properties = new Properties();
    properties.load(SQLPlus.class.getClassLoader().getResourceAsStream(SQLPlus.APPLICATION_PROPERTIES_FILE));

    SQLPlus.logger.info("Initializing " + SQLPlus.PROGRAM_NAME + " version "
            + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION));

    // Check if the user is using a valid console (i.e. not from Eclipse)
    if (System.console() == null) {
        // The Console object for the JVM could not be found. Alert the user 
        SQLPlus.logger.fatal(Messages.FATAL + "A JVM Console object was not found. Try running "
                + SQLPlus.PROGRAM_NAME + "from the command line");
        System.out.println(//from w  w  w . j  a va2  s  .c om
                Messages.FATAL + SQLPlus.PROGRAM_NAME + " was not able to find your JVM's Console object. "
                        + "Try running " + SQLPlus.PROGRAM_NAME + " from the command line.");

        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(PROGRAM_NAME));
        return;
    }

    // UI intro
    System.out.println("Welcome to " + SQLPlus.PROGRAM_NAME
            + "! This program has a DSL to add alerts to various SQL DML events.");
    System.out.println("Be sure to use " + SQLPlus.PROGRAM_NAME + " from the command line.");
    System.out.println();

    // Get the version
    System.out.println("Version: " + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION));
    System.out.println();

    // Read the license file
    BufferedReader bufferedReader;
    bufferedReader = new BufferedReader(new FileReader(SQLPlus.LICENSE_FILE));

    // Read a line
    String line = bufferedReader.readLine();

    // While the line is not null
    while (line != null) {
        System.out.println(line);

        // Read a new lines
        line = bufferedReader.readLine();
    }

    // Close the buffer
    bufferedReader.close();
    System.out.println();

    // Create the jline console that allows us to remember commands, use arrow keys, and catch interruptions
    // from the user
    SQLPlus.console = new ConsoleReader();
    SQLPlus.console.setHandleUserInterrupt(true);

    try {
        // Get credentials from the user
        SQLPlus.logger.info("Create SQLPlusConnection");
        SQLPlus.createSQLPlusConnection();
    } catch (NullPointerException | SQLException | IllegalArgumentException e) {
        // NPE: This exception can occur if the user is running the program where the JVM Console
        // object cannot be found.
        // SQLE: TODO should I add here the error code?
        // This exception can occur when trying to establish a connection
        // IAE: This exception can occur when trying to establish a connection
        SQLPlus.logger
                .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, e.getClass().getName()));
        System.out.println(Messages.FATAL + Messages.FATAL_EXCEPTION_ACTION(e.getClass().getSimpleName()) + " "
                + Messages.CHECK_LOG_FILES);
        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME));
        return;
    } catch (UserInterruptException uie) {
        SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction.");
        SQLPlus.exitSQLPlus();

        return;
    }

    System.out.println("Connection established! Commands end with " + SQLPlus.END_OF_COMMAND);
    System.out.println("Type " + SQLPlus.EXIT + " or " + SQLPlus.QUIT + " to exit the application ");

    try {
        // Execute the input scanner
        while (true) {
            // Get a line from the user until the hit enter (carriage return, line feed/ new line).
            System.out.print(SQLPlus.PROMPT);
            try {
                line = SQLPlus.console.readLine().trim();
            } catch (NullPointerException npe) {
                // TODO test this behavior
                // If this exception is catch, it is very likely that the user entered the end of line command.
                // This means that the program should quit.
                SQLPlus.logger.warn(Messages.WARNING + "The input from the user is null. It is very likely that"
                        + "the user entered the end of line command and they want to quit.");
                SQLPlus.exitSQLPlus();

                return;
            }

            // If the user did not enter anything
            if (line.isEmpty()) {
                // Continue to the next iteration
                continue;
            }

            if (line.equals(".")) {
                line = "use courses;";
            }

            if (line.equals("-")) {
                line = "select created_at from classes;";
            }

            if (line.equals("--")) {
                line = "select name, year from classes;";
            }

            if (line.equals("*")) {
                line = "select * from classes;";
            }

            if (line.equals("x")) {
                line = "select name from classes, classes;";
            }

            if (line.equals("e")) {
                line = "select * feom classes;";
            }

            // Logic to quit
            if (line.equals(SQLPlus.QUIT) || line.equals(SQLPlus.EXIT)) {
                SQLPlus.logger.info("The user wants to quit " + SQLPlus.PROGRAM_NAME);
                SQLPlus.exitSQLPlus();
                break;
            }

            // Use a StringBuilder since jline works weird when it has read a line. The issue we were having was with the
            // end of command logic. jline does not keep the input from the user in the variable that was stored in. Each
            // time jline reads a new line, the variable is empty
            StringBuilder query = new StringBuilder();
            query.append(line);

            // While the user does not finish the command with the SQLPlus.END_OF_COMMAND
            while (query.charAt(query.length() - 1) != SQLPlus.END_OF_COMMAND) {
                // Print the wait for command prompt and get the next line for the user
                System.out.print(SQLPlus.WAIT_FOR_END_OF_COMMAND);
                query.append(" ");
                line = StringUtils.stripEnd(SQLPlus.console.readLine(), null);
                query.append(line);
            }

            SQLPlus.logger.info("Raw input from the user: " + query);

            try {
                Statement statement;

                try {
                    // Execute the antlr code to parse the user input
                    SQLPlus.logger.info("Will parse the user input to determine what to execute");
                    ANTLRStringStream input = new ANTLRStringStream(query.toString());
                    SQLPlusLex lexer = new SQLPlusLex(input);
                    CommonTokenStream tokens = new CommonTokenStream(lexer);
                    SQLPlusParser parser = new SQLPlusParser(tokens);

                    statement = parser.sqlplus();
                } catch (RecognitionException re) {
                    // TODO move this to somehwere else
                    //                        String message = Messages.WARNING + "You have an error in your SQL syntax. Check the manual"
                    //                                + " that corresponds to your " + SQLPlus.sqlPlusConnection.getCurrentDatabase()
                    //                                + " server or " + SQLPlus.PROGRAM_NAME + " for the correct syntax";
                    //                        SQLPlus.logger.warn(message);
                    //                        System.out.println(message);
                    statement = new StatementDefault();
                }

                statement.setStatement(query.toString());
                SQLPlus.sqlPlusConnection.execute(statement);
            } catch (UnsupportedOperationException uoe) {
                // This exception can occur when the user entered a command allowed by the parsers, but not currently
                // supported by SQLPlus. This can occur because the parser is written in such a way that supports
                // the addition of features.
                SQLPlus.logger.warn(Messages.WARNING + uoe);
                System.out.println(
                        Messages.WARNING + Messages.FATAL_EXCEPTION_ACTION(uoe.getClass().getSimpleName()) + " "
                                + Messages.CHECK_LOG_FILES);
                SQLPlus.logger.warn(Messages.WARNING + "The previous command is not currently supported.");
            }

        }
    } catch (IllegalArgumentException iae) {
        // This exception can occur when a command is executed but it had illegal arguments. Most likely
        // it is a programmer's error and should be addressed by the developer.
        SQLPlus.logger
                .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, iae.getClass().getName()));
        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME));
    } catch (UserInterruptException uie) {
        SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction.");
        SQLPlus.exitSQLPlus();
    }
}

From source file:com.datatorrent.stram.cli.DTCli.java

public static void main(final String[] args) throws Exception {
    final DTCli shell = new DTCli();
    shell.preImpersonationInit(args);//ww  w .j a v a  2s. co m
    String hadoopUserName = System.getenv("HADOOP_USER_NAME");
    if (UserGroupInformation.isSecurityEnabled() && StringUtils.isNotBlank(hadoopUserName)
            && !hadoopUserName.equals(UserGroupInformation.getLoginUser().getUserName())) {
        LOG.info("You ({}) are running as user {}", UserGroupInformation.getLoginUser().getUserName(),
                hadoopUserName);
        UserGroupInformation ugi = UserGroupInformation.createProxyUser(hadoopUserName,
                UserGroupInformation.getLoginUser());
        ugi.doAs(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                shell.mainHelper();
                return null;
            }
        });
    } else {
        shell.mainHelper();
    }
}

From source file:de.micromata.tpsb.doc.StaticTestDocGenerator.java

public static void main(String[] args) {

    ParserConfig.Builder bCfg = new ParserConfig.Builder();
    ParserConfig.Builder tCfg = new ParserConfig.Builder();
    tCfg.generateIndividualFiles(true);/* ww  w .  ja  v  a2  s.  co  m*/
    bCfg.generateIndividualFiles(true);
    List<String> la = Arrays.asList(args);
    Iterator<String> it = la.iterator();
    boolean baseDirSet = false;
    boolean ignoreLocalSettings = false;
    List<String> addRepos = new ArrayList<String>();
    StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT,
            new StringResourceRepositoryImpl());
    try {
        while (it.hasNext()) {
            String arg = it.next();
            String value = null;

            if ((value = getArgumentOption(it, arg, "--project-root", "-pr")) != null) {
                File f = new File(value);
                if (f.exists() == false) {
                    System.err.print("project root doesn't exists: " + f.getAbsolutePath());
                    continue;
                }
                TpsbEnvironment.get().addProjectRoots(f);
                File ts = new File(f, "src/test");
                if (ts.exists() == true) {
                    tCfg.addSourceFileRespository(new FileSystemSourceFileRepository(ts.getAbsolutePath()));
                    bCfg.addSourceFileRespository(new FileSystemSourceFileRepository(ts.getAbsolutePath()));
                }
                continue;
            }
            if ((value = getArgumentOption(it, arg, "--test-input", "-ti")) != null) {
                File f = new File(value);
                if (f.exists() == false) {
                    System.err.print("test-input doesn't exists: " + f.getAbsolutePath());
                }
                tCfg.addSourceFileRespository(new FileSystemSourceFileRepository(value));
                bCfg.addSourceFileRespository(new FileSystemSourceFileRepository(value));
                continue;
            }
            if ((value = getArgumentOption(it, arg, "--output-path", "-op")) != null) {
                if (baseDirSet == false) {
                    tCfg.outputDir(value);
                    bCfg.outputDir(value);
                    TpsbEnvironment.setBaseDir(value);
                    baseDirSet = true;
                } else {
                    addRepos.add(value);
                }
                continue;
            }
            if ((value = getArgumentOption(it, arg, "--index-vmtemplate", "-ivt")) != null) {
                try {
                    String content = FileUtils.readFileToString(new File(value), CharEncoding.UTF_8);
                    StringResourceRepository repo = StringResourceLoader.getRepository();
                    repo.putStringResource("customIndexTemplate", content, CharEncoding.UTF_8);
                    tCfg.indexTemplate("customIndexTemplate");
                } catch (IOException ex) {
                    throw new RuntimeException(
                            "Cannot load file " + new File(value).getAbsolutePath() + ": " + ex.getMessage(),
                            ex);
                }
                continue;
            }
            if ((value = getArgumentOption(it, arg, "--test-vmtemplate", "-tvt")) != null) {
                try {
                    String content = FileUtils.readFileToString(new File(value), CharEncoding.UTF_8);
                    StringResourceRepository repo = StringResourceLoader.getRepository();
                    repo.putStringResource("customTestTemplate", content, CharEncoding.UTF_8);
                    tCfg.testTemplate("customTestTemplate");
                } catch (IOException ex) {
                    throw new RuntimeException(
                            "Cannot load file " + new File(value).getAbsolutePath() + ": " + ex.getMessage(),
                            ex);
                }
                continue;
            }
            if (arg.equals("--singlexml") == true) {
                tCfg.generateIndividualFiles(false);
                bCfg.generateIndividualFiles(false);
            } else if (arg.equals("--ignore-local-settings") == true) {
                ignoreLocalSettings = true;
                continue;
            }
        }
    } catch (RuntimeException ex) {
        System.err.print(ex.getMessage());
        return;
    }
    if (ignoreLocalSettings == false) {
        readLocalSettings(bCfg, tCfg);
    }
    bCfg// .addSourceFileFilter(new MatcherSourceFileFilter("*Builder,*App,*builder")) //
            .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbBuilder.class)) //
            .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbApplication.class)) //
    ;
    tCfg// .addSourceFileFilter(new MatcherSourceFileFilter("*Test,*TestCase")) //
            .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbTestSuite.class)) //
    ;

    StaticTestDocGenerator docGenerator = new StaticTestDocGenerator(bCfg.build(), tCfg.build());
    TpsbEnvironment env = TpsbEnvironment.get();
    if (addRepos.isEmpty() == false) {
        env.setIncludeRepos(addRepos);
    }
    docGenerator.parseTestBuilders();
    docGenerator.parseTestCases();
}

From source file:it.infn.ct.GridEngine.Job.JSagaJobSubmission.java

public static void main(String[] args) {
    //JSagaJobSubmission tmpJSaga1 = new JSagaJobSubmission("jdbc:mysql://localhost/userstracking","tracking_user","usertracking");
    //tmpJSaga1.removeNotAllowedCharacter("Job-1");
    //tmpJSaga1.removeNotAllowedCharacter("Stre:ss:: te%st job n. 1");

    int num_job = 1;
    //String bdiiCometa = "ldap://infn-bdii-01.ct.pi2s2.it:2170"; 
    String bdiiCometa = "ldap://gridit-bdii-01.cnaf.infn.it:2170";
    //String bdiiCometa = "ldap://bdii.eela.ufrj.br:2170";
    String wmsList[] = { "wms://wms-4.dir.garr.it:7443/glite_wms_wmproxy_server"//,
            //"wms://wms005.cnaf.infn.it:7443/glite_wms_wmproxy_server"//,
            //         "wms://gridit-wms-01.cnaf.infn.it:7443/glite_wms_wmproxy_server",
            //         "wms://egee-rb-09.cnaf.infn.it:7443/glite_wms_wmproxy_server"};//,
            //         "wms://egee-wms-01.cnaf.infn.it:7443/glite_wms_wmproxy_server",
            //         /*"wms://wms013.cnaf.infn.it:7443/glite_wms_wmproxy_server",*/
            //         "wms://egee-wms-01.cnaf.infn.it:7443/glite_wms_wmproxy_server"
    };//from w  w  w  .  j  a  v  a  2  s .c o m
    String EUMEDwmsList[] = { "wms://wms.ulakbim.gov.tr:7443/glite_wms_wmproxy_server" };
    String bdiiEumed = "ldap://bdii.eumedgrid.eu:2170";
    String sshList[] = { "ssh://api.ct.infn.it" };
    //String CEs[] = {"grisuce.scope.unina.it", "ce-02.roma3.infn.it", "gridce3.pi.infn.it"};
    String CEs[] = { //"ce-02.roma3.infn.it:8443/cream-pbs-grid"
            //"grisuce.scope.unina.it:8443/cream-pbs-grisu_short", 
            //"cccreamceli09.in2p3.fr:8443/cream-sge-long"
            "ce-01.roma3.infn.it:8443/cream-pbs-grid" };

    //      String OCCI_ENDPOINT_HOST = "rocci://carach5.ics.muni.cz";
    //      String OCCI_ENDPOINT_PORT = "11443";        
    //      String OCCI_AUTH = "x509";

    // Possible RESOURCE values: 'os_tpl', 'resource_tpl', 'compute'
    //      String OCCI_RESOURCE = "compute";
    //String OCCI_RESOURCE_ID = "https://carach5.ics.muni.cz:11443/compute/a0ad539e-ad17-4309-bc9c-4f9f91aecbaa";
    //      String OCCI_VM_TITLE = "MyDebianROCCITest";

    // Possible OCCI_OS values: 'debianvm', 'octave', 'r' and 'generic_www'
    //      String OCCI_OS = "debianvm";        
    //      String OCCI_FLAVOUR = "small";                

    // Possible ACTION values: 'list', 'describe', 'create' and 'delete'
    //      String OCCI_ACTION = "create";    
    //        String OCCI_PUBLIC_KEY = "/home/diego/.ssh/id_rsa.pub";
    //        String OCCI_PRIVATE_KEY = "/home/diego/.ssh/id_rsa";
    //        
    //      String rOCCIURL = OCCI_ENDPOINT_HOST + ":" + 
    //                 OCCI_ENDPOINT_PORT + 
    //                 System.getProperty("file.separator") + "?" +
    //                 "action=" + OCCI_ACTION + 
    //                 "&resource=" + OCCI_RESOURCE +
    //                 "&attributes_title=" + OCCI_VM_TITLE +
    //                 "&mixin_os_tpl=" + OCCI_OS +
    //                 "&mixin_resource_tpl=" + OCCI_FLAVOUR +
    //                 "&auth=" + OCCI_AUTH +
    //                 "&publickey_file=" + OCCI_PUBLIC_KEY +                                     
    //                 "&privatekey_file=" + OCCI_PRIVATE_KEY;
    //      
    //      String rOCCIResourcesList[] = {rOCCIURL};
    //String wmsList[] = {"wms://infn-wms-01.ct.pi2s2.it:7443/glite_wms_wmproxy_server"//,
    //   "unicore://zam052v01.zam.kfa-juelich.de:8080/?Target=EMI-UNICOREX"
    //};

    //JSagaJobSubmission tmpJSaga = new JSagaJobSubmission();
    //JSagaJobSubmission tmpJSaga = new JSagaJobSubmission("jdbc:mysql://10.70.1.99/userstracking","tracking_user","usertracking");
    //String bdiiGilda = "ldap://egee-bdii.cnaf.infn.it:2170"; 
    //tmpJSaga.setBDII(bdiiGilda);
    //tmpJSaga.useRobotProxy("101", "gilda", "gilda", true);
    //      tmpJSga.setJobOutput("myOutput.txt");
    //      tmpJSaga.setJobError("myError.txt");
    System.out.println("#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#1#");
    //      JobId[] newJobsId = new JobId[num_job];

    //      /*SUBMISSION SPECIFYING JOB DESCRIPTION
    for (int i = 0; i < num_job; i++) {
        GEJobDescription description = new GEJobDescription();
        description.setExecutable("/bin/sh");
        description.setArguments("hostname.sh");
        description.setInputFiles("/home/mario/Documenti/hostname.sh");
        description.setOutputFiles("output.README");
        description.setOutputPath("/tmp");
        description.setOutput("Output.txt");
        description.setError("Error.txt");
        //         String jdlRequirements = "JDLRequirements=(Member(\"MPI-START\",other.GlueHostApplicationSoftwareRunTimeEnvironment));JDLRequirements=(Member(\"MPICH\", other.GlueHostApplicationSoftwareRunTimeEnvironment))";
        //         description.setJDLRequirements(jdlRequirements);
        JSagaJobSubmission tmpJSaga = new JSagaJobSubmission("jdbc:mysql://localhost/userstracking",
                "tracking_user", "usertracking", description);
        tmpJSaga.setUserEmail("mario.torrisi@ct.infn.it");
        tmpJSaga.setSenderEmail("mario.torrisi@ct.infn.it");
        //         tmpJSaga.setWMSList(rOCCIResourcesList);
        //         tmpJSaga.useRobotProxy("etokenserver.ct.infn.it", "8082", "332576f78a4fe70a52048043e90cd11f", "fedcloud.egi.eu", "fedcloud.egi.eu", true);
        //         tmpJSaga.setWMSList(sshList);
        //         tmpJSaga.setWMSList(wmsList);
        tmpJSaga.setWMSList(EUMEDwmsList);
        //         tmpJSaga.setCEList(CEs);
        //         tmpJSaga.setRandomCE(true);
        //         tmpJSaga.setSSHCredential("liferayadmin", "liferayadmin");
        //         tmpJSaga.setSSHCredential("root", "Passw0rd!");
        tmpJSaga.useRobotProxy("etokenserver2.ct.infn.it", "8082", "bc779e33367eaad7882b9dfaa83a432c", "eumed",
                "eumed", true, true, "test");
        //         tmpJSaga.submitJobAsync("mtorrisi", "193.206.208.183:8162", 1, "ssh://gilda-liferay-vm-06.ct.infn.it:5000", "SSH - Stress test job - "+i);
        //         tmpJSaga.submitJobAsync("mtorrisi", "193.206.208.183:8162", 1, "ssh://api.ct.infn.it", "SSH - Stress test job - "+i);
        //         tmpJSaga.submitJobAsync("mtorrisi", "193.206.208.183:8162", 1, "wms://wms-4.dir.garr.it:7443/glite_wms_wmproxy_server", "WMS - Stress test job - "+i);
        tmpJSaga.submitJobAsync("test", "193.206.208.183:8162", 1, "test job n. " + i);
    }
    //         
    /*SUBMISSION WITHOUT SPECIFYING JOB DESCRIPTION
    for (int i=0;i<num_job;i++) {
       JSagaJobSubmission tmpJSaga = new JSagaJobSubmission("jdbc:mysql://localhost/userstracking","tracking_user","usertracking");
       tmpJSaga.setUserEmail("diego.scardaci@ct.infn.it");
            
       //tmpJSaga.setSSHCredential("root", "Passw0rd!");
       tmpJSaga.setExecutable("/bin/sh");
       tmpJSaga.setArguments("hostname.sh");
       tmpJSaga.setInputFiles("/home/mario/Documenti/hostname.sh");
       tmpJSaga.setOutputFiles("output.README");
       tmpJSaga.setOutputPath("/tmp");
       tmpJSaga.setJobOutput("myOutput.txt");
       tmpJSaga.setJobError("myError.txt");
       tmpJSaga.setWMSList(wmsList);
       tmpJSaga.useRobotProxy("etokenserver.ct.infn.it", "8082", "332576f78a4fe70a52048043e90cd11f", "gridit", "gridit", true);
       tmpJSaga.setJDLRequirements(new String[] {"JDLRequirements=(Member(\"MPI-START\",other.GlueHostApplicationSoftwareRunTimeEnvironment))","JDLRequirements=(Member(\"MPICH\", other.GlueHostApplicationSoftwareRunTimeEnvironment))" });
       tmpJSaga.submitJobAsync("test", "193.206.208.183:8162", 1, "test job n. "+i);
    //         tmpJSaga.submitJobAsync("mtorrisi", "193.206.208.183:8162", 1, "ssh://api.ct.infn.it", "SSH - Stress test job - "+i);
    }
    //      */
    //         tmpJSaga.setRandomCE(true);

    //         //tmpJSaga.setUserEmail("mario.torrisi@ct.infn.it");
    //         //tmpJSaga.setJobQueue("infn-ce-01.ct.pi2s2.it:8443/cream-lsf-short");
    //         //tmpJSaga.setBDII(bdiiCometa);
    //         //tmpJSaga.setWMSList(wmsList);
    //         //tmpJSaga.setCEList(CEs);
    //         //String selectedCE=tmpJSaga.getRandomCEFromCElist();
    //         //tmpJSaga.setUserProxy("/tmp/proxy");
    //         
    //         //tmpJSaga.useRobotProxy("etokenserver.ct.infn.it", "8082", "332576f78a4fe70a52048043e90cd11f", "gridit", "gridit", true);
    //         //tmpJSaga.setJKS("/home/diego/UnicoreOutput/robot2012.jks", "robot2012");
    //         //tmpJSaga.setGenesisJKS("/home/diego/genesisII/genesis-keys.jks", "srt5mInfn");
    //         //tmpJSaga.useRobotProxy("myproxy.ct.infn.it", "8082", "22002", "gridit", "gridit", true);
    //         //tmpJSaga.useRobotProxy("myproxy.ct.infn.it", "8082", "21873", "prod.vo.eu-eela.eu", "prod.vo.eu-eela.eu", true);
    //         //tmpJSaga.setOurGridCredential("diego", "scardaci");
    ////         tmpJSaga.setSPMDVariation("OpenMPI");
    ////         tmpJSaga.setTotalCPUCount("4");
    ////         tmpJSaga.setNumberOfProcesses("4");
    ////         tmpJSaga.setExecutable("diego_mpi_xn03");
    ////         tmpJSaga.setInputFiles("/home/diego/mpitest/diego_mpi_xn03");
    //         
    ////      
    //         tmpJSaga.setExecutable("lsf.sh");
    //         tmpJSaga.setArguments("hostname.job");
    //         tmpJSaga.setOutputPath("/tmp");
    //         
    ////         tmpJSaga.setExecutable("/bin/hostname");
    ////         tmpJSaga.setArguments("-f");
    ////         tmpJSaga.setOutputPath("/tmp");
    ////         tmpJSaga.setJobOutput("myOutput-" + i + ".txt");
    ////         tmpJSaga.setJobError("myError-" + i + ".txt");
    //         tmpJSaga.setJobOutput("output.txt");
    //         tmpJSaga.setJobError("error.txt");
    //         tmpJSaga.setInputFiles("/home/mario/Documenti/ls.sh,/home/mario/Documenti/hostname.sh,/home/mario/Documenti/pwd.sh");
    //         //tmpJSaga.setOutputFiles("output.txt,error.txt");//,/home/diego/Enea/output/job.output<job.output,/home/diego/Enea/output/job.error<job.error,/home/diego/Enea/output/pwd.out<pwd.out");
    ////         tmpJSaga.setCheckJobsStatus(false);
    //         
    ////         String jdlRequirements[] = new String[1];
    ////         jdlRequirements[0] = "JDLRequirements=(Member(\"Rank\", other.GlueCEStateFreeCPUs))";
    ////         tmpJSaga.setJDLRequirements(jdlRequirements);
    //
    //         //tmpJSaga.submitJobAsync("scardaci", "193.206.208.183:8162", 1, "wms://egee-wms-01.cnaf.infn.it:7443/glite_wms_wmproxy_server", "Job-"+i);
    //         //tmpJSaga.submitJobAsync("scardaci", "193.206.208.183:8162", 1, "wms://prod-wms-01.pd.infn.it:7443/glite_wms_wmproxy_server", "Job-"+i);
    //         //tmpJSaga.submitJobAsync("scardaci", "193.206.208.183:8162", 1, "wms://infn-wms-01.ct.pi2s2.it:7443/glite_wms_wmproxy_server", "Job-"+i);
    //         //tmpJSaga.submitJobAsync("scardaci", "193.206.208.183:8162", 1, "wms://wms013.cnaf.infn.it:7443/glite_wms_wmproxy_server", "Job-"+i);
    //         //tmpJSaga.submitJobAsync("scardaci", "193.206.208.183:8162", 1, "wms://wms.eela.ufrj.br:7443/glite_wms_wmproxy_server", "Job-"+i);
    ////          String descr = "paperino";
    ////         if ((i==1) || (i==3) || (i==4))
    ////            descr = "pippo";
    ////         tmpJSaga.submitJobAsync("scardaci", "193.206.208.183:8162", 1, "unicore://zam052v01.zam.kfa-juelich.de:8080/?Target=EMI-UNICOREX", "UNICORE - Stress test job n. "+i);
    //         //tmpJSaga.submitJobAsync("scardaci", "193.206.208.183:8162", 1, "bes-genesis2://xcg-server1.uvacse.virginia.edu:20443/axis/services/GeniiBESPortType?genii-container-id=93B641B7-9422-EA4C-A90B-CA6A9D98E344", "GenesisII - Stress test job n. "+i);
    //            
    //         //tmpJSaga.submitJob("scardaci", "193.206.208.183:8162", 1, "gLite - Stress test job n. "+i);
    ////         if ((i%3)==0)
    //            //tmpJSaga.submitJobAsync("mtorrisi", "193.206.208.183:8162", 1, "gLite - Stress test job n. "+i);
    ////         else if ((i%3)==1)
    ////            tmpJSaga.submitJobAsync("scardaci", "193.206.208.183:8162", 1, "wsgram://xn03.ctsf.cdacb.in:8443/PBS", "GARUDA - Stress test job n. "+i);
    ////         else if ((i%3)==2)
    ////            tmpJSaga.submitJobAsync("scardaci", "193.206.208.183:8162", 1, "ourgrid://api.ourgrid.org", "OurGrid - Stress test job n. "+i);
    //         
    //   //      tmpJSaga.submitJobAsync("mtorrisi", "193.206.208.183:8162", 1, "ssh://cresco1-f1.portici.enea.it", "SSH - Stress test job n. "+i);
    //         tmpJSaga.submitJobAsync("mtorrisi", "193.206.208.183:8162", 1, "ssh://gilda-liferay-vm-06.ct.infn.it:5000", "SSH - Stress test job n. "+i, null, null);
    //         
    ////         try {
    ////            Thread.sleep(180000);
    ////         }
    ////         catch (Exception e) {}
    //         //newJobsId[i] = tmpJSaga.submitJob("ricceri", "193.206.208.183:8162", 1, "Job-"+i);
    //         //newJobsId[i] = tmpJSaga.submitJob("scardaci", "193.206.208.183:8162", 1, "Job-"+i);
    //         //newJobsId[i] = tmpJSaga.submitJob("scardaci", "193.206.208.183:8162", 1, "wms://gilda-wms-02.ct.infn.it:7443/glite_wms_wmproxy_server", "Job-"+i);
    //         //newJobsId[i] = tmpJSaga.submitJob("scardaci", "193.206.208.183:8162", 1, "wms://infn-wms-01.ct.pi2s2.it:7443/glite_wms_wmproxy_server", "Job-"+i);
    //         //System.out.println("#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#2#");
    //         //System.out.println(newJobsId[i].getGridJobId());
    //         //System.out.println(newJobsId[i].getDbId());
    ////         try {
    ////            Thread.sleep(10000);
    ////         }
    ////         catch (Exception e) {}
    ////         
    //      }

    System.out.println("Vado in sleep...");
    try {
        Thread.sleep(60000);
    } catch (Exception e) {
    }

    System.out.println("Checking jobs...");

    UsersTrackingDBInterface DBInterface = new UsersTrackingDBInterface("jdbc:mysql://localhost/userstracking",
            "tracking_user", "usertracking");
    DBInterface.setJobsUpdatingInterval(30);
    String status = "RUNNING";
    Vector<ActiveInteractions> jobList = null;
    //      Vector<String[]> cesListwithCoord = null;

    //      if (!DBInterface.isUpdateJobsStatusAsyncRunning("ViralGrid", "scardaci")) {
    //         System.out.println("1- Running checking thread...");
    //         DBInterface.updateJobsStatusAsync2("ViralGrid","scardaci","/tmp");
    //      }
    //      
    //      if (!DBInterface.isUpdateJobsStatusAsyncRunning("ViralGrid", "scardaci")) {
    //         System.out.println("2- Running checking thread...");
    //         DBInterface.updateJobsStatusAsync2("ViralGrid","scardaci","/tmp");
    //      }

    while (status.equals("RUNNING")) {

        //DBInterface.updateJobsStatus("ViralGrid","scardaci");

        try {
            Thread.sleep(15000);
        } catch (Exception e) {
        }

        status = "DONE";
        jobList = DBInterface.getActiveInteractionsByName("test");

        if (jobList != null) {
            for (int i = 0; i < jobList.size(); i++) {

                if (jobList.get(i).getSubJobs() == null) {

                    System.out.println("DBID = " + jobList.elementAt(i).getInteractionInfos()[0] + " Portal = "
                            + jobList.elementAt(i).getInteractionInfos()[1] + " - Application = "
                            + jobList.elementAt(i).getInteractionInfos()[2] + " - Description = "
                            + jobList.elementAt(i).getInteractionInfos()[3] + " - Timestamp = "
                            + jobList.elementAt(i).getInteractionInfos()[4] + " - Status = "
                            + jobList.elementAt(i).getInteractionInfos()[5]);

                } else {
                    System.out.println(
                            "***COLLECTION INFOS*** DBID = " + jobList.elementAt(i).getInteractionInfos()[0]
                                    + " Portal = " + jobList.elementAt(i).getInteractionInfos()[1]
                                    + " - Application = " + jobList.elementAt(i).getInteractionInfos()[2]
                                    + " - Description = " + jobList.elementAt(i).getInteractionInfos()[3]
                                    + " - Timestamp = " + jobList.elementAt(i).getInteractionInfos()[4]
                                    + " - Status = " + jobList.elementAt(i).getInteractionInfos()[5]);
                    Vector<String[]> subJobs = jobList.get(i).getSubJobs();
                    for (String[] subJobInfos : subJobs)
                        System.out.println("\t|_***SUBJOB INFOS*** DBID = " + subJobInfos[0] + " Portal = "
                                + subJobInfos[1] + " - Application = " + subJobInfos[2] + " - Description = "
                                + subJobInfos[3] + " - Timestamp = " + subJobInfos[4] + " - Status = "
                                + subJobInfos[5]);
                }
                if (!jobList.elementAt(i).getInteractionInfos()[5].equals("DONE"))
                    status = "RUNNING";
            }
        }

        //         cesListwithCoord = DBInterface.getCEsGeographicDistribution("ViralGrid","scardaci");
        //         
        //         if (cesListwithCoord!=null) {
        //            for (int i=0;i<cesListwithCoord.size();i++) {
        //               System.out.println("CE = " + cesListwithCoord.elementAt(i)[0] + " Num Jobs = " + cesListwithCoord.elementAt(i)[1] + " - Lat = " + cesListwithCoord.elementAt(i)[2] + " - Long = " + cesListwithCoord.elementAt(i)[3]);
        //            }
        //         }

        //         if (!DBInterface.isUpdateJobsStatusAsyncRunning("ViralGrid", "scardaci")) {
        //            System.out.println("3- Running checking thread...");
        //            DBInterface.updateJobsStatusAsync2("ViralGrid","scardaci","/tmp");
        //         }

        if (status.equals("RUNNING")) {
            try {
                Thread.sleep(15000);
            } catch (Exception e) {
            }
        }

    }

    String allTarPath = DBInterface.createAllJobsArchive("mtorrisi", "/tmp");
    System.out.println("allTarPath=" + allTarPath);
    //      String allTarPathForDesc = DBInterface.createAllJobsFromDescriptionArchive("scardaci","pippo","/tmp");
    //      System.out.println("allTarPathForDesc="+allTarPathForDesc);

    //      for (int i=0;i<num_job;i++) {
    //         String outputFile = "";
    //         outputFile = tmpJSaga.getJobOutput(newJobsId[i].getDbId());
    //         System.out.println("outputFile="+outputFile);
    //      }

    Vector<ActiveInteractions> jobList1 = null;
    jobList1 = DBInterface.getActiveInteractionsByName("mtorrisi");
    //      for (int i=0;i<jobList1.size();i++) {
    //         JSagaJobSubmission tmpJSaga = new JSagaJobSubmission("jdbc:mysql://localhost/userstracking","tracking_user","usertracking");
    //         //tmpJSaga.useRobotProxy("21174", "cometa", "cometa", true);
    //         tmpJSaga.setOutputPath("/tmp/");
    //         String outputFile = "";
    //         outputFile = tmpJSaga.getJobOutput(new Integer(jobList.elementAt(i)[0]).intValue());
    //         System.out.println("outputFile="+outputFile);
    //      }

    if (jobList1.size() == 0)
        System.out.println("No jobs for user mtorrisi");
    //      for (int i=0;i<jobList1.size();i++) {
    //         System.out.println("Portal = " + jobList1.elementAt(i)[1] + " - Application = " + jobList1.elementAt(i)[2] + " - Description = " + jobList1.elementAt(i)[3] + " - Timestamp = " + jobList1.elementAt(i)[4] + " - Status = " + jobList1.elementAt(i)[5] );
    //      }

    //      if (!DBInterface.isUpdateJobsStatusAsyncRunning("ViralGrid", "scardaci")) {
    //         System.out.println("4- Running checking thread...");
    //         DBInterface.updateJobsStatusAsync2("ViralGrid","scardaci","/tmp");
    //      }

    //      Vector<String[]> jobList2 = null;
    //      jobList2 = DBInterface.getDoneJobsListByName("scardaci");
    //      for (int i=0;i<jobList2.size();i++) {
    //         System.out.println("DONE JOB - Portal = " + jobList2.elementAt(i)[1] + " - Application = " + jobList2.elementAt(i)[2] + " - Description = " + jobList2.elementAt(i)[3] + " - Timestamp = " + jobList2.elementAt(i)[4]);
    //      }
    System.exit(0);
}

From source file:com.datatorrent.stram.cli.ApexCli.java

public static void main(final String[] args) throws Exception {
    LoggerUtil.setupMDC("client");
    final ApexCli shell = new ApexCli();
    shell.preImpersonationInit(args);/* ww  w .j  a  v a2s  .  co m*/
    String hadoopUserName = System.getenv("HADOOP_USER_NAME");
    if (UserGroupInformation.isSecurityEnabled() && StringUtils.isNotBlank(hadoopUserName)
            && !hadoopUserName.equals(UserGroupInformation.getLoginUser().getUserName())) {
        LOG.info("You ({}) are running as user {}", UserGroupInformation.getLoginUser().getUserName(),
                hadoopUserName);
        UserGroupInformation ugi = UserGroupInformation.createProxyUser(hadoopUserName,
                UserGroupInformation.getLoginUser());
        ugi.doAs(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                shell.mainHelper();
                return null;
            }
        });
    } else {
        shell.mainHelper();
    }
}

From source file:createSod.java

/**
 * @param args//from www  .ja  v a  2s . c  o  m
 * @throws CMSException 
 */
public static void main(String[] args) throws Exception {

    try {
        CommandLine options = verifyArgs(args);
        String privateKeyLocation = options.getOptionValue("privatekey");
        String keyPassword = options.getOptionValue("keypass");
        String certificate = options.getOptionValue("certificate");
        String sodContent = options.getOptionValue("content");
        String sod = "";
        if (options.hasOption("out")) {
            sod = options.getOptionValue("out");
        }

        // CHARGEMENT DU FICHIER PKCS#12

        KeyStore ks = null;
        char[] password = null;

        Security.addProvider(new BouncyCastleProvider());
        try {
            ks = KeyStore.getInstance("PKCS12");
            // Password pour le fichier personnal_nyal.p12
            password = keyPassword.toCharArray();
            ks.load(new FileInputStream(privateKeyLocation), password);
        } catch (Exception e) {
            System.out.println("Erreur: fichier " + privateKeyLocation
                    + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect");
            return;
        }

        // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE

        X509Certificate cert = null;
        PrivateKey privatekey = null;
        PublicKey publickey = null;

        try {
            Enumeration en = ks.aliases();
            String ALIAS = "";
            Vector vectaliases = new Vector();

            while (en.hasMoreElements())
                vectaliases.add(en.nextElement());
            String[] aliases = (String[]) (vectaliases.toArray(new String[0]));
            for (int i = 0; i < aliases.length; i++)
                if (ks.isKeyEntry(aliases[i])) {
                    ALIAS = aliases[i];
                    break;
                }
            privatekey = (PrivateKey) ks.getKey(ALIAS, password);
            cert = (X509Certificate) ks.getCertificate(ALIAS);
            publickey = ks.getCertificate(ALIAS).getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // Chargement du certificat  partir du fichier

        InputStream inStream = new FileInputStream(certificate);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        // Chargement du fichier qui va tre sign

        File file_to_sign = new File(sodContent);
        byte[] buffer = new byte[(int) file_to_sign.length()];
        DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign));
        in.readFully(buffer);
        in.close();

        // Chargement des certificats qui seront stocks dans le fichier .p7
        // Ici, seulement le certificat personnal_nyal.cer sera associ.
        // Par contre, la chane des certificats non.

        ArrayList certList = new ArrayList();
        certList.add(cert);
        CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                "BC");

        CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();

        // privatekey correspond  notre cl prive rcupre du fichier PKCS#12
        // cert correspond au certificat publique personnal_nyal.cer
        // Le dernier argument est l'algorithme de hachage qui sera utilis

        signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1);
        signGen.addCertificatesAndCRLs(certs);
        CMSProcessable content = new CMSProcessableByteArray(buffer);

        // Generation du fichier CMS/PKCS#7
        // L'argument deux permet de signifier si le document doit tre attach avec la signature
        //     Valeur true:  le fichier est attach (c'est le cas ici)
        //     Valeur false: le fichier est dtach

        CMSSignedData signedData = signGen.generate(content, true, "BC");
        byte[] signeddata = signedData.getEncoded();

        // Ecriture du buffer dans un fichier.   

        if (sod.equals("")) {
            System.out.print(signeddata.toString());
        } else {
            FileOutputStream envfos = new FileOutputStream(sod);
            envfos.write(signeddata);
            envfos.close();
        }

    } catch (OptionException oe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(NAME, getOptions());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

}

From source file:it.unimi.dsi.webgraph.algo.HyperBall.java

public static void main(String arg[])
        throws IOException, JSAPException, IllegalArgumentException, ClassNotFoundException,
        IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
    SimpleJSAP jsap = new SimpleJSAP(HyperBall.class.getName(),
            "Runs HyperBall on the given graph, possibly computing positive geometric centralities.\n\nPlease note that to compute negative centralities on directed graphs (which is usually what you want) you have to compute positive centralities on the transpose.",
            new Parameter[] {
                    new FlaggedOption("log2m", JSAP.INTEGER_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'l',
                            "log2m", "The logarithm of the number of registers."),
                    new FlaggedOption("upperBound", JSAP.LONGSIZE_PARSER, Long.toString(Long.MAX_VALUE),
                            JSAP.NOT_REQUIRED, 'u', "upper-bound",
                            "An upper bound to the number of iterations."),
                    new FlaggedOption("threshold", JSAP.DOUBLE_PARSER, "-1", JSAP.NOT_REQUIRED, 't',
                            "threshold",
                            "A threshold that will be used to stop the computation by relative increment. If it is -1, the iteration will stop only when all registers do not change their value (recommended)."),
                    new FlaggedOption("threads", JSAP.INTSIZE_PARSER, "0", JSAP.NOT_REQUIRED, 'T', "threads",
                            "The number of threads to be used. If 0, the number will be estimated automatically."),
                    new FlaggedOption("granularity", JSAP.INTSIZE_PARSER, Integer.toString(DEFAULT_GRANULARITY),
                            JSAP.NOT_REQUIRED, 'g', "granularity",
                            "The number of node per task in a multicore environment."),
                    new FlaggedOption("bufferSize", JSAP.INTSIZE_PARSER,
                            Util.formatBinarySize(DEFAULT_BUFFER_SIZE), JSAP.NOT_REQUIRED, 'b', "buffer-size",
                            "The size of an I/O buffer in bytes."),
                    new FlaggedOption("neighbourhoodFunction", JSAP.STRING_PARSER, JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'n', "neighbourhood-function",
                            "Store an approximation the neighbourhood function in text format."),
                    new FlaggedOption("sumOfDistances", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            'd', "sum-of-distances",
                            "Store an approximation of the sum of distances from each node as a binary list of floats."),
                    new FlaggedOption("harmonicCentrality", JSAP.STRING_PARSER, JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'h', "harmonic-centrality",
                            "Store an approximation of the positive harmonic centrality (the sum of the reciprocals of distances from each node) as a binary list of floats."),
                    new FlaggedOption("discountedGainCentrality", JSAP.STRING_PARSER, JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'z', "discounted-gain-centrality",
                            "A positive discounted gain centrality to be approximated and stored; it is specified as O:F where O is the spec of an object of type Int2DoubleFunction and F is the name of the file where the binary list of floats will be stored. The spec can be either the name of a public field of HyperBall, or a constructor invocation of a class implementing Int2DoubleFunction.")
                                    .setAllowMultipleDeclarations(true),
                    new FlaggedOption("closenessCentrality", JSAP.STRING_PARSER, JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'c', "closeness-centrality",
                            "Store an approximation of the positive closeness centrality of each node (the reciprocal of sum of the distances from each node) as a binary list of floats. Terminal nodes will have centrality equal to zero."),
                    new FlaggedOption("linCentrality", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            'L', "lin-centrality",
                            "Store an approximation of the positive Lin centrality of each node (the reciprocal of sum of the distances from each node multiplied by the square of the number of nodes reachable from the node) as a binary list of floats. Terminal nodes will have centrality equal to one."),
                    new FlaggedOption("nieminenCentrality", JSAP.STRING_PARSER, JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'N', "nieminen-centrality",
                            "Store an approximation of the positive Nieminen centrality of each node (the square of the number of nodes reachable from each node minus the sum of the distances from the node) as a binary list of floats."),
                    new FlaggedOption("reachable", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'r',
                            "reachable",
                            "Store an approximation of the number of nodes reachable from each node as a binary list of floats."),
                    new FlaggedOption("seed", JSAP.LONG_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'S', "seed",
                            "The random seed."),
                    new Switch("spec", 's', "spec",
                            "The basename is not a basename but rather a specification of the form <ImmutableGraphImplementation>(arg,arg,...)."),
                    new Switch("offline", 'o', "offline",
                            "Do not load the graph in main memory. If this option is used, the graph will be loaded in offline (for one thread) or mapped (for several threads) mode."),
                    new Switch("external", 'e', "external",
                            "Use an external dump file instead of core memory to store new counter values. Note that the file might be very large: you might need to set suitably the Java temporary directory (-Djava.io.tmpdir=DIR)."),
                    new UnflaggedOption("basename", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED,
                            JSAP.NOT_GREEDY, "The basename of the graph."),
                    new UnflaggedOption("basenamet", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            JSAP.NOT_GREEDY,
                            "The basename of the transpose graph for systolic computations (strongly suggested). If it is equal to <basename>, the graph will be assumed to be symmetric and will be loaded just once."), });

    JSAPResult jsapResult = jsap.parse(arg);
    if (jsap.messagePrinted())
        System.exit(1);//from  w  w  w .j  av  a2 s.  co  m

    final boolean spec = jsapResult.getBoolean("spec");
    final boolean external = jsapResult.getBoolean("external");
    final boolean offline = jsapResult.getBoolean("offline");
    final String neighbourhoodFunctionFile = jsapResult.getString("neighbourhoodFunction");
    final boolean neighbourhoodFunction = jsapResult.userSpecified("neighbourhoodFunction");
    final String sumOfDistancesFile = jsapResult.getString("sumOfDistances");
    final boolean sumOfDistances = jsapResult.userSpecified("sumOfDistances");
    final String harmonicCentralityFile = jsapResult.getString("harmonicCentrality");
    final boolean harmonicCentrality = jsapResult.userSpecified("harmonicCentrality");
    final String closenessCentralityFile = jsapResult.getString("closenessCentrality");
    final boolean closenessCentrality = jsapResult.userSpecified("closenessCentrality");
    final String linCentralityFile = jsapResult.getString("linCentrality");
    final boolean linCentrality = jsapResult.userSpecified("linCentrality");
    final String nieminenCentralityFile = jsapResult.getString("nieminenCentrality");
    final boolean nieminenCentrality = jsapResult.userSpecified("nieminenCentrality");
    final String reachableFile = jsapResult.getString("reachable");
    final boolean reachable = jsapResult.userSpecified("reachable");
    final String basename = jsapResult.getString("basename");
    final String basenamet = jsapResult.getString("basenamet");
    final ProgressLogger pl = new ProgressLogger(LOGGER);
    final int log2m = jsapResult.getInt("log2m");
    final int threads = jsapResult.getInt("threads");
    final int bufferSize = jsapResult.getInt("bufferSize");
    final int granularity = jsapResult.getInt("granularity");
    final long seed = jsapResult.userSpecified("seed") ? jsapResult.getLong("seed") : Util.randomSeed();

    final String[] discountedGainCentralitySpec = jsapResult.getStringArray("discountedGainCentrality");
    final Int2DoubleFunction[] discountFunction = new Int2DoubleFunction[discountedGainCentralitySpec.length];
    final String[] discountedGainCentralityFile = new String[discountedGainCentralitySpec.length];
    for (int i = 0; i < discountedGainCentralitySpec.length; i++) {
        int pos = discountedGainCentralitySpec[i].indexOf(':');
        if (pos < 0)
            throw new IllegalArgumentException("Wrong spec <" + discountedGainCentralitySpec[i] + ">");
        discountedGainCentralityFile[i] = discountedGainCentralitySpec[i].substring(pos + 1);
        String gainSpec = discountedGainCentralitySpec[i].substring(0, pos);
        Int2DoubleFunction candidateFunction;
        try {
            candidateFunction = (Int2DoubleFunction) HyperBall.class.getField(gainSpec).get(null);
        } catch (SecurityException e) {
            throw new IllegalArgumentException("Field " + gainSpec + " exists but cannot be accessed", e);
        } catch (ClassCastException e) {
            throw new IllegalArgumentException(
                    "Field " + gainSpec + " exists but it is not of type Int2DoubleFunction", e);
        } catch (NoSuchFieldException e) {
            candidateFunction = null;
        }
        discountFunction[i] = candidateFunction == null
                ? ObjectParser.fromSpec(gainSpec, Int2DoubleFunction.class)
                : candidateFunction;
    }

    final ImmutableGraph graph = spec
            ? ObjectParser.fromSpec(basename, ImmutableGraph.class, GraphClassParser.PACKAGE)
            : offline
                    ? ((numberOfThreads(threads) == 1 && basenamet == null
                            ? ImmutableGraph.loadOffline(basename)
                            : ImmutableGraph.loadMapped(basename, new ProgressLogger())))
                    : ImmutableGraph.load(basename, new ProgressLogger());

    final ImmutableGraph grapht = basenamet == null ? null
            : basenamet.equals(basename) ? graph
                    : spec ? ObjectParser.fromSpec(basenamet, ImmutableGraph.class, GraphClassParser.PACKAGE)
                            : offline ? ImmutableGraph.loadMapped(basenamet, new ProgressLogger())
                                    : ImmutableGraph.load(basenamet, new ProgressLogger());

    final HyperBall hyperBall = new HyperBall(graph, grapht, log2m, pl, threads, bufferSize, granularity,
            external, sumOfDistances || closenessCentrality || linCentrality || nieminenCentrality,
            harmonicCentrality, discountFunction, seed);
    hyperBall.run(jsapResult.getLong("upperBound"), jsapResult.getDouble("threshold"));
    hyperBall.close();

    if (neighbourhoodFunction) {
        final PrintStream stream = new PrintStream(
                new FastBufferedOutputStream(new FileOutputStream(neighbourhoodFunctionFile)));
        for (DoubleIterator i = hyperBall.neighbourhoodFunction.iterator(); i.hasNext();)
            stream.println(BigDecimal.valueOf(i.nextDouble()).toPlainString());
        stream.close();
    }

    if (sumOfDistances)
        BinIO.storeFloats(hyperBall.sumOfDistances, sumOfDistancesFile);
    if (harmonicCentrality)
        BinIO.storeFloats(hyperBall.sumOfInverseDistances, harmonicCentralityFile);
    for (int i = 0; i < discountedGainCentralitySpec.length; i++)
        BinIO.storeFloats(hyperBall.discountedCentrality[i], discountedGainCentralityFile[i]);
    if (closenessCentrality) {
        final int n = graph.numNodes();
        final DataOutputStream dos = new DataOutputStream(
                new FastBufferedOutputStream(new FileOutputStream(closenessCentralityFile)));
        for (int i = 0; i < n; i++)
            dos.writeFloat(hyperBall.sumOfDistances[i] == 0 ? 0 : 1 / hyperBall.sumOfDistances[i]);
        dos.close();
    }
    if (linCentrality) {
        final int n = graph.numNodes();
        final DataOutputStream dos = new DataOutputStream(
                new FastBufferedOutputStream(new FileOutputStream(linCentralityFile)));
        for (int i = 0; i < n; i++) {
            // Lin's index for isolated nodes is by (our) definition one (it's smaller than any other node).
            if (hyperBall.sumOfDistances[i] == 0)
                dos.writeFloat(1);
            else {
                final double count = hyperBall.count(i);
                dos.writeFloat((float) (count * count / hyperBall.sumOfDistances[i]));
            }
        }
        dos.close();
    }
    if (nieminenCentrality) {
        final int n = graph.numNodes();
        final DataOutputStream dos = new DataOutputStream(
                new FastBufferedOutputStream(new FileOutputStream(nieminenCentralityFile)));
        for (int i = 0; i < n; i++) {
            final double count = hyperBall.count(i);
            dos.writeFloat((float) (count * count - hyperBall.sumOfDistances[i]));
        }
        dos.close();
    }
    if (reachable) {
        final int n = graph.numNodes();
        final DataOutputStream dos = new DataOutputStream(
                new FastBufferedOutputStream(new FileOutputStream(reachableFile)));
        for (int i = 0; i < n; i++)
            dos.writeFloat((float) hyperBall.count(i));
        dos.close();
    }
}

From source file:com.interflora.ftp.SampleFTPS.java

public static final void main(String[] args) {
    boolean storeFile = true, binaryTransfer = false, error = false, listFiles = false, listNames = false,
            hidden = false;//from  ww w  . j  a  v  a2 s . c  o m
    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 = "TLS,false"; // SSL protocol
    String doCommand = null;
    String trustmgr = "all";
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    //sample : rose-misc01.hyd.ftd.untd.com rosedev test123 /TestSftp  C:/Users/skarin/Desktop/RosePaths.txt 
    //172.16.160.70 demand quevfoc5 /TestSftp C:/Users/skarin/Desktop/RosePaths.txt 
    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("-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[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (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]);
    }
    String username = args[base++];
    String 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);
        }
        /* try{
         //ftps.setFileType(FTP.ASCII_FILE_TYPE);
         ftps.execPBSZ(0); // Set protection buffer size
         ftps.execPROT("C"); // Set data channel protection to private
         }catch(IOException ex ){ex.printStackTrace();};
        */
    }
    // System.out.println("After I/O Exception");

    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 {
            System.out.println("Trying to Connect to the server \t" + server);
            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);
        }

        // 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;
            File fname = new File(local);

            FileInputStream input = new FileInputStream(fname);
            String localfilename = fname.getName();
            System.out.println("Local file name " + localfilename);

            ftp.storeFile(remote + "/test/" + localfilename, 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:com.paul.linknet.FTPClientExample.java

public static void main(String[] args) throws UnknownHostException {
    boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false,
            hidden = false;//from  ww w . j  a  v  a2  s.  c o  m
    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[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        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);
        }

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