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:Writer.java

/** Main program entry point. */
public static void main(String argv[]) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();//from   w  w w.  j  a  v a 2s. com
        System.exit(1);
    }

    // variables
    Writer writer = null;
    XMLReader parser = null;
    boolean namespaces = DEFAULT_NAMESPACES;
    boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES;
    boolean validation = DEFAULT_VALIDATION;
    boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD;
    boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
    boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
    boolean xincludeProcessing = DEFAULT_XINCLUDE;
    boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
    boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;
    boolean canonical = DEFAULT_CANONICAL;

    // process arguments
    for (int i = 0; i < argv.length; i++) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = XMLReaderFactory.createXMLReader(parserName);
                } catch (Exception e) {
                    try {
                        Parser sax1Parser = ParserFactory.makeParser(parserName);
                        parser = new ParserAdapter(sax1Parser);
                        System.err.println("warning: Features and properties not supported on SAX1 parsers.");
                    } catch (Exception ex) {
                        parser = null;
                        System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                        e.printStackTrace(System.err);
                    }
                }
                continue;
            }
            if (option.equalsIgnoreCase("n")) {
                namespaces = option.equals("n");
                continue;
            }
            if (option.equalsIgnoreCase("np")) {
                namespacePrefixes = option.equals("np");
                continue;
            }
            if (option.equalsIgnoreCase("v")) {
                validation = option.equals("v");
                continue;
            }
            if (option.equalsIgnoreCase("xd")) {
                externalDTD = option.equals("xd");
                continue;
            }
            if (option.equalsIgnoreCase("s")) {
                schemaValidation = option.equals("s");
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                continue;
            }
            if (option.equalsIgnoreCase("dv")) {
                dynamicValidation = option.equals("dv");
                continue;
            }
            if (option.equalsIgnoreCase("xi")) {
                xincludeProcessing = option.equals("xi");
                continue;
            }
            if (option.equalsIgnoreCase("xb")) {
                xincludeFixupBaseURIs = option.equals("xb");
                continue;
            }
            if (option.equalsIgnoreCase("xl")) {
                xincludeFixupLanguage = option.equals("xl");
                continue;
            }
            if (option.equalsIgnoreCase("c")) {
                canonical = option.equals("c");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
        }

        // use default parser?
        if (parser == null) {

            // create parser
            try {
                parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
            } catch (Exception e) {
                System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
                e.printStackTrace(System.err);
                continue;
            }
        }

        // set parser features
        try {
            parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(VALIDATION_FEATURE_ID, validation);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err
                    .println("warning: Parser does not support feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err
                    .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Parser does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            parser.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }
        try {
            parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Parser does not recognize feature (" + XINCLUDE_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        }

        // setup writer
        if (writer == null) {
            writer = new Writer();
            try {
                writer.setOutput(System.out, "UTF8");
            } catch (UnsupportedEncodingException e) {
                System.err.println("error: Unable to set output. Exiting.");
                System.exit(1);
            }
        }

        // set parser
        parser.setContentHandler(writer);
        parser.setErrorHandler(writer);
        try {
            parser.setProperty(LEXICAL_HANDLER_PROPERTY_ID, writer);
        } catch (SAXException e) {
            // ignore
        }

        // parse file
        writer.setCanonical(canonical);
        try {
            parser.parse(arg);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            System.err.println("error: Parse error occurred - " + e.getMessage());
            if (e instanceof SAXException) {
                Exception nested = ((SAXException) e).getException();
                if (nested != null) {
                    e = nested;
                }
            }
            e.printStackTrace(System.err);
        }
    }

}

From source file:isi.pasco2.Main.java

public static void main(String[] args) {
    CommandLineParser parser = new PosixParser();

    Options options = new Options();
    Option undelete = new Option("d", "Undelete activity records");
    options.addOption(undelete);//from   ww  w.  j a  va2  s . c  om
    Option disableAllocation = new Option("M", "Disable allocation detection");
    options.addOption(disableAllocation);
    Option fieldDelimeter = OptionBuilder.withArgName("field-delimeter").hasArg()
            .withDescription("Field Delimeter (TAB by default)").create("t");
    options.addOption(fieldDelimeter);

    Option timeFormat = OptionBuilder.withArgName("time-format").hasArg()
            .withDescription("xsd or standard (pasco1 compatible)").create("f");
    options.addOption(timeFormat);

    Option fileTypeOption = OptionBuilder.withArgName("file-type").hasArg()
            .withDescription("The type of file: cache or history").create("T");

    options.addOption(fileTypeOption);

    try {
        CommandLine line = parser.parse(options, args);
        boolean undeleteMethod = false;
        String delimeter = null;
        String format = null;
        String fileType = null;
        boolean disableAllocationTest = false;

        if (line.hasOption("d")) {
            undeleteMethod = true;
        }

        if (line.hasOption('t')) {
            delimeter = line.getOptionValue('t');
        }

        if (line.hasOption('M')) {
            disableAllocationTest = true;
        }

        if (line.hasOption('T')) {
            fileType = line.getOptionValue('T');
        }

        if (line.hasOption('f')) {
            format = line.getOptionValue('f');
        }

        if (line.getArgs().length != 1) {
            System.err.println("No file specified.");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("pasco2", options);
            System.exit(1);
        }
        String fileName = line.getArgs()[0];

        try {
            IndexFile fr = new FastReadIndexFile(fileName, "r");

            CountingCacheHandler handler = null;

            if (fileType == null) {
                handler = new CountingCacheHandler();
            }
            if (fileType == null) {
                handler = new CountingCacheHandler();
            } else if (fileType.equals("cache")) {
                handler = new CountingCacheHandler();
            } else if (fileType.equals("history")) {
                handler = new Pasco2HistoryHandler();
            }

            if (format != null) {
                if (format.equals("pasco")) {
                    DateFormat regularDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS");
                    handler.setDateFormat(regularDateFormat);
                    TimeZone tz = TimeZone.getTimeZone("Australia/Brisbane");
                    regularDateFormat.setTimeZone(tz);

                } else if (format.equals("standard")) {
                    DateFormat xsdDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                    handler.setDateFormat(xsdDateFormat);
                    xsdDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                } else {
                    System.err.println("Format not supported.");
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.printHelp("pasco2", options);
                    System.exit(1);
                }
            }

            if (delimeter != null) {
                handler.setDelimeter(delimeter);
            }

            IEIndexFileParser logparser = null;
            if (fileType == null) {
                System.err.println("Using cache file parser.");
                logparser = new IECacheFileParser(fileName, fr, handler);
            } else if (fileType.equals("cache")) {
                logparser = new IECacheFileParser(fileName, fr, handler);
            } else if (fileType.equals("history")) {
                logparser = new IEHistoryFileParser(fileName, fr, handler);
            } else {
                System.err.println("Unsupported file type.");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("pasco2", options);
                System.exit(1);
            }
            if (disableAllocationTest) {
                logparser.setDisableAllocationTest(true);
            }
            logparser.parseFile();

        } catch (Exception ex) {
            System.err.println(ex.getMessage());
            ex.printStackTrace();
        }

    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
    }
}

From source file:Base64.java

public static void main(String[] args) throws IOException {
    boolean decode = false;
    int mode = 0;
    for (String arg : args) {
        if (arg.equals("-e")) {
            decode = false;//from w w  w.j av  a2s . c  o  m
        } else if (arg.equals("-d")) {
            decode = true;
        } else if (arg.equals("-b64")) {
            mode = 0;
        } else if (arg.equals("-hqx")) {
            mode = 1;
        } else if (arg.equals("-a85")) {
            mode = 2;
        } else if (arg.equals("-l85")) {
            mode = 3;
        } else if (arg.equals("-k85")) {
            mode = 4;
        } else if (arg.equals("-uue")) {
            mode = 5;
        } else if (arg.equals("-xxe")) {
            mode = 6;
        } else if (arg.equals("--")) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[1048576];
            int len = 0;
            while ((len = System.in.read(buf)) >= 0) {
                out.write(buf, 0, len);
            }
            out.close();
            if (decode) {
                switch (mode) {
                case 0:
                    System.out.println(new String(decodeBase64(out.toString())));
                    break;
                case 1:
                    System.out.println(new String(decodeBinHex(out.toString())));
                    break;
                case 2:
                    System.out.println(new String(decodeASCII85(out.toString())));
                    break;
                case 3:
                    System.out.println(new String(decodeLegacy85(out.toString())));
                    break;
                case 4:
                    System.out.println(new String(decodeKreative85(out.toString())));
                    break;
                case 5:
                    System.out.println(new String(decodeUU(out.toString())));
                    break;
                case 6:
                    System.out.println(new String(decodeXX(out.toString())));
                    break;
                }
            } else {
                switch (mode) {
                case 0:
                    System.out.println(encodeBase64(out.toByteArray()));
                    break;
                case 1:
                    System.out.println(encodeBinHex(out.toByteArray()));
                    break;
                case 2:
                    System.out.println(encodeASCII85(out.toByteArray()));
                    break;
                case 3:
                    System.out.println(encodeLegacy85(out.toByteArray()));
                    break;
                case 4:
                    System.out.println(encodeKreative85(out.toByteArray()));
                    break;
                case 5:
                    System.out.println(encodeUU(out.toByteArray()));
                    break;
                case 6:
                    System.out.println(encodeXX(out.toByteArray()));
                    break;
                }
            }
        } else if (decode) {
            switch (mode) {
            case 0:
                System.out.println(new String(decodeBase64(arg)));
                break;
            case 1:
                System.out.println(new String(decodeBinHex(arg)));
                break;
            case 2:
                System.out.println(new String(decodeASCII85(arg)));
                break;
            case 3:
                System.out.println(new String(decodeLegacy85(arg)));
                break;
            case 4:
                System.out.println(new String(decodeKreative85(arg)));
                break;
            case 5:
                System.out.println(new String(decodeUU(arg)));
                break;
            case 6:
                System.out.println(new String(decodeXX(arg)));
                break;
            }
        } else {
            switch (mode) {
            case 0:
                System.out.println(encodeBase64(arg.getBytes()));
                break;
            case 1:
                System.out.println(encodeBinHex(arg.getBytes()));
                break;
            case 2:
                System.out.println(encodeASCII85(arg.getBytes()));
                break;
            case 3:
                System.out.println(encodeLegacy85(arg.getBytes()));
                break;
            case 4:
                System.out.println(encodeKreative85(arg.getBytes()));
                break;
            case 5:
                System.out.println(encodeUU(arg.getBytes()));
                break;
            case 6:
                System.out.println(encodeXX(arg.getBytes()));
                break;
            }
        }
    }
}

From source file:com.ilopez.jasperemail.JasperEmail.java

public static void main(String[] args) throws Exception {
    JasperEmail runJasperReports = new JasperEmail();
    // Set up command line parser
    Options options = new Options();

    Option reports = OptionBuilder.withArgName("reportlist").hasArg()
            .withDescription("Comma separated list of JasperReport XML input files").create("reports");
    options.addOption(reports);/*from  ww  w  .  j  ava 2  s . c o  m*/

    Option emailTo = OptionBuilder.withArgName("emailaddress").hasArg()
            .withDescription("Email address to send generated reports to").create("emailto");
    options.addOption(emailTo);

    Option emailFrom = OptionBuilder.withArgName("emailaddress").hasArg()
            .withDescription("Sender email address").create("emailfrom");
    options.addOption(emailFrom);

    Option emailSubjectLine = OptionBuilder.withArgName("emailsubject").hasArg()
            .withDescription("Subject line of email").create("emailsubject");
    options.addOption(emailSubjectLine);

    Option smtpHostOption = OptionBuilder.withArgName("smtphost").hasArg()
            .withDescription("Address of email server").create("smtphost");
    options.addOption(smtpHostOption);

    Option smtpUserOption = OptionBuilder.withArgName("smtpuser").hasArg()
            .withDescription("Username if email server requires authentication").create("smtpuser");
    options.addOption(smtpUserOption);

    Option smtpPassOption = OptionBuilder.withArgName("smtppass").hasArg()
            .withDescription("Password if email server requires authentication").create("smtppass");
    options.addOption(smtpPassOption);

    Option smtpAuthOption = OptionBuilder.withArgName("smtpauth").hasArg()
            .withDescription("Set SMTP Authentication").create("smtpauth");
    options.addOption(smtpAuthOption);

    Option smtpPortOption = OptionBuilder.withArgName("smtpport").hasArg()
            .withDescription("Port for the SMTP server 25/468/587/2525/2526").create("smtpport");
    options.addOption(smtpPortOption);

    Option smtpTypeOption = OptionBuilder.withArgName("smtptype").hasArg()
            .withDescription("Define SMTP Type, one of: " + Arrays.asList(OptionValues.SMTPType.values()))
            .create("smtptype");
    options.addOption(smtpTypeOption);

    Option outputFolder = OptionBuilder.withArgName("foldername").hasArg()
            .withDescription(
                    "Folder to write generated reports to, with trailing separator (slash or backslash)")
            .create("folder");
    options.addOption(outputFolder);

    Option dbJDBCClass = OptionBuilder.withArgName("jdbcclass").hasArg()
            .withDescription("Provide the JDBC Database Class ").create("jdbcclass");
    options.addOption(dbJDBCClass);

    Option dbJDBCURL = OptionBuilder.withArgName("jdbcurl").hasArg()
            .withDescription("Provide the JDBC Database URL").create("jdbcurl");
    options.addOption(dbJDBCURL);

    Option dbUserOption = OptionBuilder.withArgName("username").hasArg()
            .withDescription("Username to connect to databasewith").create("dbuser");
    options.addOption(dbUserOption);

    Option dbPassOption = OptionBuilder.withArgName("password").hasArg().withDescription("Database password")
            .create("dbpass");
    options.addOption(dbPassOption);

    Option outputTypeOption = OptionBuilder.withArgName("outputtype").hasArg()
            .withDescription("Output type, one of: " + Arrays.asList(OutputType.values())).create("output");
    options.addOption(outputTypeOption);

    Option outputFilenameOption = OptionBuilder.withArgName("outputfilename").hasArg()
            .withDescription("Output filename (excluding filetype suffix)").create("filename");
    options.addOption(outputFilenameOption);

    Option paramsOption = OptionBuilder.withArgName("parameters").hasArg().withDescription(
            "Parameters, e.g. param1=boolean:true,param2=string:ABC,param3=double:134.2,param4=integer:85")
            .create("params");
    options.addOption(paramsOption);

    // Parse command line
    CommandLineParser parser = new GnuParser();

    CommandLine commandLine = parser.parse(options, args);

    String reportsDefinitionFileNamesCvs = commandLine.getOptionValue("reports");
    if (reportsDefinitionFileNamesCvs == null) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar JasperEmail.jar", options);
        System.out.println();
        System.out.println("See http://github.com/ilopez/JasperEmail for further documentation");
        System.out.println();
        throw new IllegalArgumentException("No reports specified");
    }

    String outputPath = commandLine.getOptionValue("folder");
    List<String> reportDefinitionFileNames = Arrays.asList(reportsDefinitionFileNamesCvs.split(","));
    List<String> outputFileNames = new ArrayList<String>();

    String jdbcClass = commandLine.getOptionValue("jdbcclass");

    String jdbcURL = commandLine.getOptionValue("jdbcurl");
    String databaseUsername = commandLine.getOptionValue("dbuser");
    String databasePassword = commandLine.getOptionValue("dbpass");

    OutputType outputType = OutputType.PDF;
    String outputTypeString = commandLine.getOptionValue("output");
    if (outputTypeString != null) {
        outputType = OutputType.valueOf(outputTypeString.toUpperCase());
    }

    String parametersString = commandLine.getOptionValue("params");
    Map parameters = runJasperReports.prepareParameters(parametersString);
    String outputFilenameSpecified = commandLine.getOptionValue("filename");
    if (outputFilenameSpecified == null) {
        outputFilenameSpecified = "";
    }

    // SMTP PORT

    Integer smtpport = Integer.parseInt(commandLine.getOptionValue("smtpport"));
    Boolean smtpauth = Boolean.parseBoolean(commandLine.getOptionValue("smtpauth"));

    OptionValues.SMTPType smtptype;
    String smtptypestring = commandLine.getOptionValue("smtpenc");
    if (smtptypestring != null) {
        smtptype = OptionValues.SMTPType.valueOf(smtptypestring.toUpperCase());
    } else {
        smtptype = OptionValues.SMTPType.PLAIN;
    }

    // SMTP TLS
    // SMTP 

    // Iterate over reports, generating output for each
    for (String reportsDefinitionFileName : reportDefinitionFileNames) {
        String outputFilename = null;
        if ((reportDefinitionFileNames.size() == 1) && (!outputFilenameSpecified.equals(""))) {
            outputFilename = outputFilenameSpecified;
        } else {
            outputFilename = outputFilenameSpecified + reportsDefinitionFileName.replaceAll("\\..*$", "");
            outputFilename = outputFilename.replaceAll("^.*\\/", "");
            outputFilename = outputFilename.replaceAll("^.*\\\\", "");
        }
        outputFilename = outputFilename.replaceAll("\\W", "").toLowerCase() + "."
                + outputType.toString().toLowerCase();
        if (outputPath != null) {
            if (!outputPath.endsWith("\\") && !outputPath.endsWith("/")) {
                outputPath += java.io.File.separator;
            }
            outputFilename = outputPath + outputFilename;
        }
        System.out.println("Going to generate report " + outputFilename);

        runJasperReports.generateReport(reportsDefinitionFileName, jdbcClass, jdbcURL, databaseUsername,
                databasePassword, jdbcURL, parameters);
        outputFileNames.add(outputFilename);
    }
    String emailRecipientList = commandLine.getOptionValue("emailto");
    if (emailRecipientList != null) {
        Set<String> emailRecipients = new HashSet<String>(Arrays.asList(emailRecipientList.split(",")));
        String emailSender = commandLine.getOptionValue("emailfrom");
        String emailSubject = commandLine.getOptionValue("emailsubject");
        if (emailSubject == null) {
            emailSubject = "Report attached";
        }
        String emailHost = commandLine.getOptionValue("smtphost");
        if (emailHost == null) {
            emailHost = "localhost";
        }
        String emailUser = commandLine.getOptionValue("smtpuser");
        String emailPass = commandLine.getOptionValue("smtppass");
        System.out.println("Emailing reports to " + emailRecipients);
        runJasperReports.emailReport(emailHost, emailUser, emailPass, emailRecipients, emailSender,
                emailSubject, outputFileNames, smtpauth, smtptype, smtpport);
    } else {
        System.out.println("Email not generated (no recipients specified)");
    }
}

From source file:ie.aib.nbp.zosresttest.RunTest.java

/**
 * @param args the command line arguments
 */// w w w.  j  a va  2 s .  c  om
public static void main(String[] args) {
    PrintStream printer = null;

    if (args.length < 2) {
        System.out.println("***************************************************************************");
        System.out.println("*                   Z/OS REST SERVICES PERFORMANCE TESTER                 *");
        System.out.println("*                                                                         *");
        System.out.println("* At least 2 run parameters are required:                                 *");
        System.out.println("*  1 username: your mainframe username                                    *");
        System.out.println("*  2 password: your mainframe passeord                                    *");
        System.out.println("*  3 runtime behaviour switch: 1 - active, everything else - inactive     *");
        System.out.println("*    this parameter is optional and causes the app to run the test or not *");
        System.out.println("*    lack of it assings default value: 0                                  *");
        System.out.println("*    which triggers the service discovery feature                         *");
        System.out.println("*    and displays all currently available services                        *");
        System.out.println("*  4 output type:                                                         *");
        System.out.println("*     F - output to file (then fifth parameter hold the file location)    *");
        System.out.println("*     Everything else (including no parameter at all) outputs to console  *");
        System.out.println("***************************************************************************");
        return;
    }

    readConfig(CONFIG_FILE_PATH);
    String username = args[0];
    String password = args[1];

    String runPerformanceTest;
    try {
        runPerformanceTest = args[2];
    } catch (ArrayIndexOutOfBoundsException ex) {
        runPerformanceTest = "0";
    }

    String outputType;
    String outputFileLocation;
    try {
        outputType = args[3]; // F saves to file, everything else output to console            
    } catch (ArrayIndexOutOfBoundsException ex) {
        outputType = "C";
    }

    if (outputType.equalsIgnoreCase("F")) { // write to file
        String outputFile;
        try {
            outputFile = args[4]; // if prev param is F then this one may contain the file name (default name instead)
        } catch (ArrayIndexOutOfBoundsException ex) {
            SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy-HHmmssZ");
            outputFile = "ZosPerformanceTest".concat("-".concat(sdf.format(new Date()))).concat(".txt");
        }
        try {
            String filePath = config.getProperty("OUT_FILE_PATH").concat(outputFile);
            printer = new PrintStream(new FileOutputStream(filePath, true));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(RunTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else { // othewise write to java console
        printer = new PrintStream(System.out);
    }

    if (runPerformanceTest.equals("1"))
        runPerformanceTest(username, password, printer, true, false);
    else
        runServiceDiscovery(username, password, printer);
}

From source file:iristk.flow.FlowCompiler.java

public static void main(String[] args) {
    try {/*from  w ww . ja  v a 2 s.c  o  m*/
        boolean compileToBinary = false;
        //boolean compileToXSD = false;
        String file = null;
        for (String arg : args) {
            if (arg.equals("-b"))
                compileToBinary = true;
            //else if (arg.equals("-x")) 
            //   compileToXSD = true;
            else
                file = arg;
        }
        if (file != null) {
            compile(file, System.getProperty("user.dir"), compileToBinary);

            //if (compileToXSD)
            //   FlowSchemaCompiler.compile(file, System.getProperty("user.dir"));
        } else {
            System.out.println("Compiles flow XML to Java source.\n");
            System.out.println("Usage:");
            System.out.println("iristk cflow [OPTIONS] XML\n");
            System.out.println("Options:");
            System.out.println("-b  Also compile Java source to binary");
            //System.out.println("-x  Also compile templates to XSD Schema");
        }
    } catch (FlowCompilerException e) {
        System.err.println("Error on line " + e.getLineNumber() + ": " + e.getMessage());
    }
}

From source file:edu.nyu.vida.data_polygamy.relationship_computation.Relationship.java

/**
 * @param args/*from  ww  w . j  a  v  a  2 s.c o m*/
 * @throws ParseException 
 */
@SuppressWarnings({ "deprecation" })
public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {

    Options options = new Options();

    Option forceOption = new Option("f", "force", false,
            "force the computation of the relationship " + "even if files already exist");
    forceOption.setRequired(false);
    options.addOption(forceOption);

    Option scoreOption = new Option("sc", "score", true, "set threhsold for relationship score");
    scoreOption.setRequired(false);
    scoreOption.setArgName("SCORE THRESHOLD");
    options.addOption(scoreOption);

    Option strengthOption = new Option("st", "strength", true, "set threhsold for relationship strength");
    strengthOption.setRequired(false);
    strengthOption.setArgName("STRENGTH THRESHOLD");
    options.addOption(strengthOption);

    Option completeRandomizationOption = new Option("c", "complete-randomization", false,
            "use complete randomization when performing significance tests");
    completeRandomizationOption.setRequired(false);
    options.addOption(completeRandomizationOption);

    Option idOption = new Option("id", "ids", false, "output id instead of names for datasets and attributes");
    idOption.setRequired(false);
    options.addOption(idOption);

    Option g1Option = new Option("g1", "first-group", true, "set first group of datasets");
    g1Option.setRequired(true);
    g1Option.setArgName("FIRST GROUP");
    g1Option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(g1Option);

    Option g2Option = new Option("g2", "second-group", true, "set second group of datasets");
    g2Option.setRequired(false);
    g2Option.setArgName("SECOND GROUP");
    g2Option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(g2Option);

    Option machineOption = new Option("m", "machine", true, "machine identifier");
    machineOption.setRequired(true);
    machineOption.setArgName("MACHINE");
    machineOption.setArgs(1);
    options.addOption(machineOption);

    Option nodesOption = new Option("n", "nodes", true, "number of nodes");
    nodesOption.setRequired(true);
    nodesOption.setArgName("NODES");
    nodesOption.setArgs(1);
    options.addOption(nodesOption);

    Option s3Option = new Option("s3", "s3", false, "data on Amazon S3");
    s3Option.setRequired(false);
    options.addOption(s3Option);

    Option awsAccessKeyIdOption = new Option("aws_id", "aws-id", true,
            "aws access key id; " + "this is required if the execution is on aws");
    awsAccessKeyIdOption.setRequired(false);
    awsAccessKeyIdOption.setArgName("AWS-ACCESS-KEY-ID");
    awsAccessKeyIdOption.setArgs(1);
    options.addOption(awsAccessKeyIdOption);

    Option awsSecretAccessKeyOption = new Option("aws_key", "aws-id", true,
            "aws secrect access key; " + "this is required if the execution is on aws");
    awsSecretAccessKeyOption.setRequired(false);
    awsSecretAccessKeyOption.setArgName("AWS-SECRET-ACCESS-KEY");
    awsSecretAccessKeyOption.setArgs(1);
    options.addOption(awsSecretAccessKeyOption);

    Option bucketOption = new Option("b", "s3-bucket", true,
            "bucket on s3; " + "this is required if the execution is on aws");
    bucketOption.setRequired(false);
    bucketOption.setArgName("S3-BUCKET");
    bucketOption.setArgs(1);
    options.addOption(bucketOption);

    Option helpOption = new Option("h", "help", false, "display this message");
    helpOption.setRequired(false);
    options.addOption(helpOption);

    Option removeOption = new Option("r", "remove-not-significant", false,
            "remove relationships that are not" + "significant from the final output");
    removeOption.setRequired(false);
    options.addOption(removeOption);

    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        formatter.printHelp("hadoop jar data-polygamy.jar "
                + "edu.nyu.vida.data_polygamy.relationship_computation.Relationship", options, true);
        System.exit(0);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("hadoop jar data-polygamy.jar "
                + "edu.nyu.vida.data_polygamy.relationship_computation.Relationship", options, true);
        System.exit(0);
    }

    boolean s3 = cmd.hasOption("s3");
    String s3bucket = "";
    String awsAccessKeyId = "";
    String awsSecretAccessKey = "";

    if (s3) {
        if ((!cmd.hasOption("aws_id")) || (!cmd.hasOption("aws_key")) || (!cmd.hasOption("b"))) {
            System.out.println(
                    "Arguments 'aws_id', 'aws_key', and 'b'" + " are mandatory if execution is on AWS.");
            formatter.printHelp(
                    "hadoop jar data-polygamy.jar "
                            + "edu.nyu.vida.data_polygamy.relationship_computation.Relationship",
                    options, true);
            System.exit(0);
        }
        s3bucket = cmd.getOptionValue("b");
        awsAccessKeyId = cmd.getOptionValue("aws_id");
        awsSecretAccessKey = cmd.getOptionValue("aws_key");
    }

    boolean snappyCompression = false;
    boolean bzip2Compression = false;
    String machine = cmd.getOptionValue("m");
    int nbNodes = Integer.parseInt(cmd.getOptionValue("n"));

    Configuration s3conf = new Configuration();
    if (s3) {
        s3conf.set("fs.s3.awsAccessKeyId", awsAccessKeyId);
        s3conf.set("fs.s3.awsSecretAccessKey", awsSecretAccessKey);
        s3conf.set("bucket", s3bucket);
    }

    Path path = null;
    FileSystem fs = FileSystem.get(new Configuration());

    ArrayList<String> shortDataset = new ArrayList<String>();
    ArrayList<String> firstGroup = new ArrayList<String>();
    ArrayList<String> secondGroup = new ArrayList<String>();
    HashMap<String, String> datasetAgg = new HashMap<String, String>();

    boolean removeNotSignificant = cmd.hasOption("r");
    boolean removeExistingFiles = cmd.hasOption("f");
    boolean completeRandomization = cmd.hasOption("c");
    boolean hasScoreThreshold = cmd.hasOption("sc");
    boolean hasStrengthThreshold = cmd.hasOption("st");
    boolean outputIds = cmd.hasOption("id");
    String scoreThreshold = hasScoreThreshold ? cmd.getOptionValue("sc") : "";
    String strengthThreshold = hasStrengthThreshold ? cmd.getOptionValue("st") : "";

    // all datasets
    ArrayList<String> all_datasets = new ArrayList<String>();
    if (s3) {
        path = new Path(s3bucket + FrameworkUtils.datasetsIndexDir);
        fs = FileSystem.get(path.toUri(), s3conf);
    } else {
        path = new Path(fs.getHomeDirectory() + "/" + FrameworkUtils.datasetsIndexDir);
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(path)));
    String line = br.readLine();
    while (line != null) {
        all_datasets.add(line.split("\t")[0]);
        line = br.readLine();
    }
    br.close();
    if (s3)
        fs.close();
    String[] all_datasets_array = new String[all_datasets.size()];
    all_datasets.toArray(all_datasets_array);

    String[] firstGroupCmd = cmd.getOptionValues("g1");
    String[] secondGroupCmd = cmd.hasOption("g2") ? cmd.getOptionValues("g2") : all_datasets_array;
    addDatasets(firstGroupCmd, firstGroup, shortDataset, datasetAgg, path, fs, s3conf, s3, s3bucket);
    addDatasets(secondGroupCmd, secondGroup, shortDataset, datasetAgg, path, fs, s3conf, s3, s3bucket);

    if (shortDataset.size() == 0) {
        System.out.println("No datasets to process.");
        System.exit(0);
    }

    if (firstGroup.isEmpty()) {
        System.out.println("No indices from datasets in G1.");
        System.exit(0);
    }

    if (secondGroup.isEmpty()) {
        System.out.println("No indices from datasets in G2.");
        System.exit(0);
    }

    // getting dataset ids

    String datasetNames = "";
    String datasetIds = "";
    HashMap<String, String> datasetId = new HashMap<String, String>();
    Iterator<String> it = shortDataset.iterator();
    while (it.hasNext()) {
        datasetId.put(it.next(), null);
    }

    if (s3) {
        path = new Path(s3bucket + FrameworkUtils.datasetsIndexDir);
        fs = FileSystem.get(path.toUri(), s3conf);
    } else {
        path = new Path(fs.getHomeDirectory() + "/" + FrameworkUtils.datasetsIndexDir);
    }
    br = new BufferedReader(new InputStreamReader(fs.open(path)));
    line = br.readLine();
    while (line != null) {
        String[] dt = line.split("\t");
        all_datasets.add(dt[0]);
        if (datasetId.containsKey(dt[0])) {
            datasetId.put(dt[0], dt[1]);
            datasetNames += dt[0] + ",";
            datasetIds += dt[1] + ",";
        }
        line = br.readLine();
    }
    br.close();
    if (s3)
        fs.close();

    datasetNames = datasetNames.substring(0, datasetNames.length() - 1);
    datasetIds = datasetIds.substring(0, datasetIds.length() - 1);
    it = shortDataset.iterator();
    while (it.hasNext()) {
        String dataset = it.next();
        if (datasetId.get(dataset) == null) {
            System.out.println("No dataset id for " + dataset);
            System.exit(0);
        }
    }

    String firstGroupStr = "";
    String secondGroupStr = "";
    for (String dataset : firstGroup) {
        firstGroupStr += datasetId.get(dataset) + ",";
    }
    for (String dataset : secondGroup) {
        secondGroupStr += datasetId.get(dataset) + ",";
    }
    firstGroupStr = firstGroupStr.substring(0, firstGroupStr.length() - 1);
    secondGroupStr = secondGroupStr.substring(0, secondGroupStr.length() - 1);

    String relationshipsDir = "";
    if (outputIds) {
        relationshipsDir = FrameworkUtils.relationshipsIdsDir;
    } else {
        relationshipsDir = FrameworkUtils.relationshipsDir;
    }

    FrameworkUtils.createDir(s3bucket + relationshipsDir, s3conf, s3);

    String random = completeRandomization ? "complete" : "restricted";

    String indexInputDirs = "";
    String noRelationship = "";

    HashSet<String> dirs = new HashSet<String>();

    String dataset1;
    String dataset2;
    String datasetId1;
    String datasetId2;
    for (int i = 0; i < firstGroup.size(); i++) {
        for (int j = 0; j < secondGroup.size(); j++) {

            if (Integer.parseInt(datasetId.get(firstGroup.get(i))) < Integer
                    .parseInt(datasetId.get(secondGroup.get(j)))) {
                dataset1 = firstGroup.get(i);
                dataset2 = secondGroup.get(j);
            } else {
                dataset1 = secondGroup.get(j);
                dataset2 = firstGroup.get(i);
            }

            datasetId1 = datasetId.get(dataset1);
            datasetId2 = datasetId.get(dataset2);

            if (dataset1.equals(dataset2))
                continue;
            String correlationOutputFileName = s3bucket + relationshipsDir + "/" + dataset1 + "-" + dataset2
                    + "/";

            if (removeExistingFiles) {
                FrameworkUtils.removeFile(correlationOutputFileName, s3conf, s3);
            }
            if (!FrameworkUtils.fileExists(correlationOutputFileName, s3conf, s3)) {
                dirs.add(s3bucket + FrameworkUtils.indexDir + "/" + dataset1);
                dirs.add(s3bucket + FrameworkUtils.indexDir + "/" + dataset2);
            } else {
                noRelationship += datasetId1 + "-" + datasetId2 + ",";
            }
        }
    }

    if (dirs.isEmpty()) {
        System.out.println("All the relationships were already computed.");
        System.out.println("Use -f in the beginning of the command line to force the computation.");
        System.exit(0);
    }

    for (String dir : dirs) {
        indexInputDirs += dir + ",";
    }

    Configuration conf = new Configuration();
    Machine machineConf = new Machine(machine, nbNodes);

    String jobName = "relationship" + "-" + random;
    String relationshipOutputDir = s3bucket + relationshipsDir + "/tmp/";

    FrameworkUtils.removeFile(relationshipOutputDir, s3conf, s3);

    for (int i = 0; i < shortDataset.size(); i++) {
        conf.set("dataset-" + datasetId.get(shortDataset.get(i)) + "-agg", datasetAgg.get(shortDataset.get(i)));
    }
    for (int i = 0; i < shortDataset.size(); i++) {
        conf.set("dataset-" + datasetId.get(shortDataset.get(i)) + "-agg-size",
                Integer.toString(datasetAgg.get(shortDataset.get(i)).split(",").length));
    }
    conf.set("dataset-keys", datasetIds);
    conf.set("dataset-names", datasetNames);
    conf.set("first-group", firstGroupStr);
    conf.set("second-group", secondGroupStr);
    conf.set("complete-random", String.valueOf(completeRandomization));
    conf.set("output-ids", String.valueOf(outputIds));
    conf.set("complete-random-str", random);
    conf.set("main-dataset-id", datasetId.get(shortDataset.get(0)));
    conf.set("remove-not-significant", String.valueOf(removeNotSignificant));
    if (noRelationship.length() > 0) {
        conf.set("no-relationship", noRelationship.substring(0, noRelationship.length() - 1));
    }
    if (hasScoreThreshold) {
        conf.set("score-threshold", scoreThreshold);
    }
    if (hasStrengthThreshold) {
        conf.set("strength-threshold", strengthThreshold);
    }

    conf.set("mapreduce.tasktracker.map.tasks.maximum", String.valueOf(machineConf.getMaximumTasks()));
    conf.set("mapreduce.tasktracker.reduce.tasks.maximum", String.valueOf(machineConf.getMaximumTasks()));
    conf.set("mapreduce.jobtracker.maxtasks.perjob", "-1");
    conf.set("mapreduce.reduce.shuffle.parallelcopies", "20");
    conf.set("mapreduce.input.fileinputformat.split.minsize", "0");
    conf.set("mapreduce.task.io.sort.mb", "200");
    conf.set("mapreduce.task.io.sort.factor", "100");
    conf.set("mapreduce.task.timeout", "2400000");

    if (s3) {
        machineConf.setMachineConfiguration(conf);
        conf.set("fs.s3.awsAccessKeyId", awsAccessKeyId);
        conf.set("fs.s3.awsSecretAccessKey", awsSecretAccessKey);
        conf.set("bucket", s3bucket);
    }

    if (snappyCompression) {
        conf.set("mapreduce.map.output.compress", "true");
        conf.set("mapreduce.map.output.compress.codec", "org.apache.hadoop.io.compress.SnappyCodec");
        //conf.set("mapreduce.output.fileoutputformat.compress.codec", "org.apache.hadoop.io.compress.SnappyCodec");
    }
    if (bzip2Compression) {
        conf.set("mapreduce.map.output.compress", "true");
        conf.set("mapreduce.map.output.compress.codec", "org.apache.hadoop.io.compress.BZip2Codec");
        //conf.set("mapreduce.output.fileoutputformat.compress.codec", "org.apache.hadoop.io.compress.BZip2Codec");
    }

    Job job = new Job(conf);
    job.setJobName(jobName);

    job.setMapOutputKeyClass(PairAttributeWritable.class);
    job.setMapOutputValueClass(TopologyTimeSeriesWritable.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(Text.class);

    job.setMapperClass(CorrelationMapper.class);
    job.setReducerClass(CorrelationReducer.class);
    job.setNumReduceTasks(machineConf.getNumberReduces());

    job.setInputFormatClass(SequenceFileInputFormat.class);
    //job.setOutputFormatClass(TextOutputFormat.class);
    LazyOutputFormat.setOutputFormatClass(job, TextOutputFormat.class);

    FileInputFormat.setInputDirRecursive(job, true);
    FileInputFormat.setInputPaths(job, indexInputDirs.substring(0, indexInputDirs.length() - 1));
    FileOutputFormat.setOutputPath(job, new Path(relationshipOutputDir));

    job.setJarByClass(Relationship.class);

    long start = System.currentTimeMillis();
    job.submit();
    job.waitForCompletion(true);
    System.out.println(jobName + "\t" + (System.currentTimeMillis() - start));

    // moving files to right place
    for (int i = 0; i < firstGroup.size(); i++) {
        for (int j = 0; j < secondGroup.size(); j++) {

            if (Integer.parseInt(datasetId.get(firstGroup.get(i))) < Integer
                    .parseInt(datasetId.get(secondGroup.get(j)))) {
                dataset1 = firstGroup.get(i);
                dataset2 = secondGroup.get(j);
            } else {
                dataset1 = secondGroup.get(j);
                dataset2 = firstGroup.get(i);
            }

            if (dataset1.equals(dataset2))
                continue;

            String from = s3bucket + relationshipsDir + "/tmp/" + dataset1 + "-" + dataset2 + "/";
            String to = s3bucket + relationshipsDir + "/" + dataset1 + "-" + dataset2 + "/";
            FrameworkUtils.renameFile(from, to, s3conf, s3);
        }
    }
}

From source file:Messenger.TorLib.java

public static void main(String[] args) {
    String req = "-r";
    String targetHostname = "tor.eff.org";
    String targetDir = "index.html";
    int targetPort = 80;

    if (args.length > 0 && args[0].equals("-h")) {
        System.out.println("Tinfoil/TorLib - interface for using Tor from Java\n"
                + "By Joe Foley<foley@mit.edu>\n" + "Usage: java Tinfoil.TorLib <cmd> <args>\n"
                + "<cmd> can be: -h for help\n" + "              -r for resolve\n"
                + "              -w for wget\n" + "For -r, the arg is:\n"
                + "  <hostname> Hostname to DNS resolve\n" + "For -w, the args are:\n"
                + "   <host> <path> <optional port>\n"
                + " for example, http://tor.eff.org:80/index.html would be\n" + "   tor.eff.org index.html 80\n"
                + " Since this is a demo, the default is the tor website.\n");
        System.exit(2);/* w  ww  .j av a  2 s .  c o m*/
    }

    if (args.length >= 4)
        targetPort = new Integer(args[2]).intValue();
    if (args.length >= 3)
        targetDir = args[2];
    if (args.length >= 2)
        targetHostname = args[1];
    if (args.length >= 1)
        req = args[0];

    if (req.equals("-r")) {
        System.out.println(TorResolve(targetHostname));
    } else if (req.equals("-w")) {
        try {
            Socket s = TorSocket(targetHostname, targetPort);
            DataInputStream is = new DataInputStream(s.getInputStream());
            PrintStream out = new java.io.PrintStream(s.getOutputStream());

            //Construct an HTTP request
            out.print("GET  /" + targetDir + " HTTP/1.0\r\n");
            out.print("Host: " + targetHostname + ":" + targetPort + "\r\n");
            out.print("Accept: */*\r\n");
            out.print("Connection: Keep-Aliv\r\n");
            out.print("Pragma: no-cache\r\n");
            out.print("\r\n");
            out.flush();

            // this is from Java Examples In a Nutshell
            final InputStreamReader from_server = new InputStreamReader(is);
            char[] buffer = new char[1024];
            int chars_read;

            // read until stream closes
            while ((chars_read = from_server.read(buffer)) != -1) {
                // loop through array of chars
                // change \n to local platform terminator
                // this is a nieve implementation
                for (int j = 0; j < chars_read; j++) {
                    if (buffer[j] == '\n')
                        System.out.println();
                    else
                        System.out.print(buffer[j]);
                }
                System.out.flush();
            }
            s.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.cloud.test.stress.StressTestDirectAttach.java

public static void main(String[] args) {
    String host = "http://localhost";
    String port = "8092";
    String devPort = "8080";
    String apiUrl = "/client/api";

    try {/*from  ww w. j a va  2s.c  o  m*/
        // Parameters
        List<String> argsList = Arrays.asList(args);
        Iterator<String> iter = argsList.iterator();
        while (iter.hasNext()) {
            String arg = iter.next();
            // host
            if (arg.equals("-h")) {
                host = "http://" + iter.next();
            }

            if (arg.equals("-p")) {
                port = iter.next();
            }
            if (arg.equals("-dp")) {
                devPort = iter.next();
            }

            if (arg.equals("-t")) {
                numThreads = Integer.parseInt(iter.next());
            }

            if (arg.equals("-s")) {
                sleepTime = Long.parseLong(iter.next());
            }
            if (arg.equals("-a")) {
                accountName = iter.next();
            }

            if (arg.equals("-c")) {
                cleanUp = Boolean.parseBoolean(iter.next());
                if (!cleanUp)
                    sleepTime = 0L; // no need to wait if we don't ever
                // cleanup
            }

            if (arg.equals("-r")) {
                repeat = Boolean.parseBoolean(iter.next());
            }

            if (arg.equals("-i")) {
                internet = Boolean.parseBoolean(iter.next());
            }

            if (arg.equals("-w")) {
                wait = Integer.parseInt(iter.next());
            }

            if (arg.equals("-z")) {
                zoneId = iter.next();
            }

            if (arg.equals("-so")) {
                serviceOfferingId = iter.next();
            }

        }

        final String server = host + ":" + port + "/";
        final String developerServer = host + ":" + devPort + apiUrl;
        s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)");
        if (cleanUp)
            s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up");

        for (int i = 0; i < numThreads; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    do {
                        String username = null;
                        try {
                            long now = System.currentTimeMillis();
                            Random ran = new Random();
                            username = Math.abs(ran.nextInt()) + "-user";
                            NDC.push(username);

                            s_logger.info("Starting test for the user " + username);
                            int response = executeDeployment(server, developerServer, username);
                            boolean success = false;
                            String reason = null;

                            if (response == 200) {
                                success = true;
                                if (internet) {
                                    s_logger.info("Deploy successful...waiting 5 minute before SSH tests");
                                    Thread.sleep(300000L); // Wait 60
                                    // seconds so
                                    // the windows VM
                                    // can boot up and do a sys prep.

                                    s_logger.info("Begin Linux SSH test for account " + _account.get());
                                    reason = sshTest(_linuxIP.get(), _linuxPassword.get());

                                    if (reason == null) {
                                        s_logger.info(
                                                "Linux SSH test successful for account " + _account.get());
                                    }
                                }
                                if (reason == null) {
                                    if (internet) {
                                        s_logger.info(
                                                "Windows SSH test successful for account " + _account.get());
                                    } else {
                                        s_logger.info("deploy test successful....now cleaning up");
                                        if (cleanUp) {
                                            s_logger.info(
                                                    "Waiting " + sleepTime + " ms before cleaning up vms");
                                            Thread.sleep(sleepTime);
                                        } else {
                                            success = true;
                                        }
                                    }

                                    if (usageIterator >= numThreads) {
                                        int eventsAndBillingResponseCode = executeEventsAndBilling(server,
                                                developerServer);
                                        s_logger.info(
                                                "events and usage records command finished with response code: "
                                                        + eventsAndBillingResponseCode);
                                        usageIterator = 1;

                                    } else {
                                        s_logger.info(
                                                "Skipping events and usage records for this user: usageIterator "
                                                        + usageIterator + " and number of Threads "
                                                        + numThreads);
                                        usageIterator++;
                                    }

                                    if ((users == null) && (accountName == null)) {
                                        s_logger.info("Sending cleanup command");
                                        int cleanupResponseCode = executeCleanup(server, developerServer,
                                                username);
                                        s_logger.info("cleanup command finished with response code: "
                                                + cleanupResponseCode);
                                        success = (cleanupResponseCode == 200);
                                    } else {
                                        s_logger.info("Sending stop DomR / destroy VM command");
                                        int stopResponseCode = executeStop(server, developerServer, username);
                                        s_logger.info("stop(destroy) command finished with response code: "
                                                + stopResponseCode);
                                        success = (stopResponseCode == 200);
                                    }

                                } else {
                                    // Just stop but don't destroy the
                                    // VMs/Routers
                                    s_logger.info("SSH test failed for account " + _account.get()
                                            + "with reason '" + reason + "', stopping VMs");
                                    int stopResponseCode = executeStop(server, developerServer, username);
                                    s_logger.info(
                                            "stop command finished with response code: " + stopResponseCode);
                                    success = false; // since the SSH test
                                    // failed, mark the
                                    // whole test as
                                    // failure
                                }
                            } else {
                                // Just stop but don't destroy the
                                // VMs/Routers
                                s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs");
                                int stopResponseCode = executeStop(server, developerServer, username);
                                s_logger.info("stop command finished with response code: " + stopResponseCode);
                                success = false; // since the deploy test
                                // failed, mark the
                                // whole test as failure
                            }

                            if (success) {
                                s_logger.info("***** Completed test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L) + " seconds");

                            } else {
                                s_logger.info("##### FAILED test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L)
                                        + " seconds with reason : " + reason);
                            }
                            s_logger.info("Sleeping for " + wait + " seconds before starting next iteration");
                            Thread.sleep(wait);
                        } catch (Exception e) {
                            s_logger.warn("Error in thread", e);
                            try {
                                int stopResponseCode = executeStop(server, developerServer, username);
                                s_logger.info("stop response code: " + stopResponseCode);
                            } catch (Exception e1) {
                            }
                        } finally {
                            NDC.clear();
                        }
                    } while (repeat);
                }
            }).start();
        }
    } catch (Exception e) {
        s_logger.error(e);
    }
}

From source file:com.serena.rlc.provider.servicenow.client.ServiceNowClient.java

static public void main(String[] args) {
    ServiceNowClient snow = new ServiceNowClient(null, "http://localhost:9999", "v1", "itil", "itil");

    ChangeRequest firstChangeRequest = null;
    ChangeTask firstChangeTask = null;/*from w ww  .  ja  v  a 2s.c om*/
    Incident firstIncident = null;
    String titleFilter = "Java";
    String query = "short_descriptionLIKE" + titleFilter + "^ORdescriptionLIKE" + titleFilter + "^ORnumberLIKE"
            + titleFilter;

    System.out.println("Retrieving ServiceNow Change Requests...");
    List<ChangeRequest> changeRequests = null;
    try {
        changeRequests = snow.getChangeRequests(query, "New", 1);
        System.out.println("Found " + changeRequests.size() + " Change Requests");
        for (ChangeRequest cr : changeRequests) {
            if (firstChangeRequest == null)
                firstChangeRequest = cr;
            System.out.println("Found Change Request: " + cr.getNumber());
            System.out.println("Title: " + cr.getTitle());
            System.out.println("Description: " + cr.getDescription());
            System.out.println("State: " + cr.getState());
            System.out.println("URL: " + cr.getUrl());
        }
    } catch (ServiceNowClientException e) {
        System.out.print(e.toString());
    }

    try {
        ChangeRequest cr = snow.getChangeRequestById(firstChangeRequest.getId());
        System.out.println("Found Change Request: " + cr.getNumber());
        System.out.println("Title: " + cr.getTitle());
    } catch (ServiceNowClientException e) {
        System.out.print(e.toString());
    }

    try {
        ChangeRequest cr = snow.getChangeRequestByNumber(firstChangeRequest.getNumber());
        System.out.println("Found Change Request: " + cr.getNumber());
        System.out.println("Title: " + cr.getTitle());
    } catch (ServiceNowClientException e) {
        System.out.print(e.toString());
    }

    System.out.println("Retrieving ServiceNow Change Tasks...");
    titleFilter = "Install";
    query = "short_descriptionLIKE" + titleFilter + "^ORdescriptionLIKE" + titleFilter + "^ORnumberLIKE"
            + titleFilter;
    List<ChangeTask> changeTasks = null;
    try {
        changeTasks = snow.getChangeTasks(query, firstChangeRequest.getNumber(), "Open", 10);
        System.out.println("Found " + changeTasks.size() + " Change Tasks");
        for (ChangeTask ct : changeTasks) {
            if (firstChangeTask == null)
                firstChangeTask = ct;
            System.out.println("Found Change Task: " + ct.getNumber());
            System.out.println("Title: " + ct.getTitle());
            System.out.println("Description: " + ct.getDescription());
            System.out.println("State: " + ct.getState());
            System.out.println("URL: " + ct.getUrl());
        }
    } catch (ServiceNowClientException e) {
        System.out.print(e.toString());
    }

    try {
        ChangeTask ct = snow.getChangeTaskById(firstChangeTask.getId());
        System.out.println("Found Change Task: " + ct.getNumber());
        System.out.println("Title: " + ct.getTitle());
    } catch (ServiceNowClientException e) {
        System.out.print(e.toString());
    }

    try {
        ChangeTask ct = snow.getChangeTaskByNumber(firstChangeTask.getNumber());
        System.out.println("Found Change Task: " + ct.getNumber());
        System.out.println("Title: " + ct.getTitle());
    } catch (ServiceNowClientException e) {
        System.out.print(e.toString());
    }

    System.out.println("Retrieving ServiceNow Incidents...");
    titleFilter = "password";
    query = "short_descriptionLIKE" + titleFilter + "^ORdescriptionLIKE" + titleFilter + "^ORnumberLIKE"
            + titleFilter;
    List<Incident> incidents = null;
    try {
        incidents = snow.getIncidents(query, "Closed", 10);
        System.out.println("Found " + incidents.size() + " Incidents");
        for (Incident i : incidents) {
            if (firstIncident == null)
                firstIncident = i;
            System.out.println("Found Incident: " + i.getNumber());
            System.out.println("Title: " + i.getTitle());
            System.out.println("Description: " + i.getDescription());
            System.out.println("State: " + i.getState());
            System.out.println("Type: " + i.getType());
            System.out.println("URL: " + i.getUrl());
        }
    } catch (ServiceNowClientException e) {
        System.out.print(e.toString());
    }

    try {
        Incident inc = snow.getIncidentById(firstIncident.getId());
        System.out.println("Found Incident: " + inc.getNumber());
        System.out.println("Title: " + inc.getTitle());
    } catch (ServiceNowClientException e) {
        System.out.print(e.toString());
    }

    try {
        Incident inc = snow.getIncidentByNumber(firstIncident.getNumber());
        System.out.println("Found Incident: " + inc.getNumber());
        System.out.println("Title: " + inc.getTitle());
    } catch (ServiceNowClientException e) {
        System.out.print(e.toString());
    }

    System.out.println("Creating Change Request");
    String changeNumber = "";
    String changeId = "";
    try {
        ChangeRequest cr = snow.createChangeRequest("my cr", "its description", "Normal", "Software",
                "3 - Moderate", "High", "3 - Low");
        System.out.println("Created Change Request: " + cr.getNumber());
        System.out.println("Title: " + cr.getTitle());
        System.out.println("Description: " + cr.getDescription());
        System.out.println("State: " + cr.getState());
        System.out.println("URL: " + cr.getUrl());
        changeId = cr.getId();
        changeNumber = cr.getNumber();
    } catch (ServiceNowClientException e) {
        System.out.print(e.toString());
    }

    String approvalStatus = null;
    System.out.println("Checking Approval State of " + changeNumber);
    int pollCount = 0;
    while (pollCount < 100) {
        try {
            approvalStatus = snow.getChangeRequestApproval(changeNumber);
            System.out.println("Approval Status = " + approvalStatus);
        } catch (ServiceNowClientException e) {
            logger.debug("Error checking approval status ({}) - {}", changeNumber, e.getMessage());
        }
        if (approvalStatus != null
                && (approvalStatus.equals("Approved") || approvalStatus.equals("Rejected"))) {
            break;
        } else {
            try {
                Thread.sleep(6000);
            } catch (InterruptedException e) {
            }
        }

        pollCount++;
    }

    if (approvalStatus != null && approvalStatus.equals("Approved")) {
        System.out.println("Change Request " + changeNumber + " has been approved");
    } else {
        System.out.println(
                "Change Request " + changeNumber + " has been rejected or its status cannot be retrieved.");
    }

    System.out.println("Checking State of " + changeNumber);
    try {
        ChangeRequest cr = snow.getChangeRequestByNumber(changeNumber);
        System.out.println("Status = " + cr.getState());
        cr = snow.setChangeRequestStatus(cr.getId(), "Closed");
        System.out.println("Status = " + cr.getState());
    } catch (ServiceNowClientException e) {
        System.out.print(e.toString());
    }

    System.out.println("Creating Change Task");
    String changeTaskNumber = "";
    String changeTaskId = "";
    try {
        ChangeTask ct = snow.createChangeTask(firstChangeRequest.getId(), "my ct", "its description",
                "1 - Critical", "3 - Low");
        System.out.println("Created Change Task: " + ct.getNumber());
        System.out.println("Title: " + ct.getTitle());
        System.out.println("Description: " + ct.getDescription());
        System.out.println("State: " + ct.getState());
        System.out.println("URL: " + ct.getUrl());
        changeTaskId = ct.getId();
        changeTaskNumber = ct.getNumber();
    } catch (ServiceNowClientException e) {
        System.out.print(e.toString());
    }

    System.out.println("Checking State of " + changeTaskNumber);
    try {
        ChangeTask ct = snow.getChangeTaskById(changeTaskId);
        System.out.println("Status = " + ct.getState());
        ct = snow.setChangeTaskStatus(ct.getId(), "Closed Complete");
        System.out.println("Status = " + ct.getState());
    } catch (ServiceNowClientException e) {
        System.out.print(e.toString());
    }

}