Example usage for java.io File separator

List of usage examples for java.io File separator

Introduction

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

Prototype

String separator

To view the source code for java.io File separator.

Click Source Link

Document

The system-dependent default name-separator character, represented as a string for convenience.

Usage

From source file:eu.edisonproject.training.execute.Main.java

public static void main(String args[]) {
    Options options = new Options();
    Option operation = new Option("op", "operation", true,
            "type of operation to perform. " + "For term extraction use 'x'.\n"
                    + "Example: -op x -i E-COCO/documentation/sampleTextFiles/databases.txt "
                    + "-o E-COCO/documentation/sampleTextFiles/databaseTerms.csv"
                    + "For word sense disambiguation use 'w'.\n"
                    + "Example: -op w -i E-COCO/documentation/sampleTextFiles/databaseTerms.csv "
                    + "-o E-COCO/documentation/sampleTextFiles/databse.avro\n"
                    + "For tf-idf vector extraction use 't'.\n" + "For running the apriori algorithm use 'a'");
    operation.setRequired(true);/*from   w w  w.  ja v  a2 s.  c om*/
    options.addOption(operation);

    Option input = new Option("i", "input", true, "input file path");
    input.setRequired(true);
    options.addOption(input);

    Option output = new Option("o", "output", true, "output file");
    output.setRequired(true);
    options.addOption(output);

    Option popertiesFile = new Option("p", "properties", true, "path for a properties file");
    popertiesFile.setRequired(false);
    options.addOption(popertiesFile);

    Option termsFile = new Option("t", "terms", true, "terms file");
    termsFile.setRequired(false);
    options.addOption(termsFile);

    String helpmasg = "Usage: \n";
    for (Object obj : options.getOptions()) {
        Option op = (Option) obj;
        helpmasg += op.getOpt() + ", " + op.getLongOpt() + "\t Required: " + op.isRequired() + "\t\t"
                + op.getDescription() + "\n";
    }

    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);

        String propPath = cmd.getOptionValue("properties");
        if (propPath == null) {
            prop = ConfigHelper
                    .getProperties(".." + File.separator + "etc" + File.separator + "configure.properties");
        } else {
            prop = ConfigHelper.getProperties(propPath);
        }
        //            ${user.home}

        switch (cmd.getOptionValue("operation")) {
        case "x":
            termExtraction(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        case "w":
            wsd(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        case "t":
            calculateTFIDF(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        //                case "tt":
        //                    calculateTermTFIDF(cmd.getOptionValue("input"), cmd.getOptionValue("terms"), cmd.getOptionValue("output"));
        //                    break;
        case "a":
            apriori(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        default:
            System.out.println(helpmasg);
        }

    } catch (Exception ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, helpmasg, ex);
    }
}

From source file:de.dfki.dmas.owls2wsdl.core.OWLS2WSDL.java

public static void main(String[] args) {
    // http://jakarta.apache.org/commons/cli/usage.html
    System.out.println("ARG COUNT: " + args.length);

    OWLS2WSDLSettings.getInstance();// w  ww  .  j  a va 2  s .  c  om

    Options options = new Options();
    Option help = new Option("help", "print help message");
    options.addOption(help);

    // create the parser
    CommandLineParser parser = new GnuParser();
    CommandLine cmdLine = null;

    for (int i = 0; i < args.length; i++) {
        System.out.println("ARG: " + args[i].toString());
    }

    if (args.length > 0) {
        if (args[args.length - 1].toString().endsWith(".owl")) {
            // -kbdir d:\tmp\KB http://127.0.0.1/ontology/ActorDefault.owl
            Option test = new Option("test", "parse only, don't save");
            @SuppressWarnings("static-access")
            Option kbdir = OptionBuilder.withArgName("dir").hasArg()
                    .withDescription("knowledgebase directory; necessary").create("kbdir");
            options.addOption(test);
            options.addOption(kbdir);

            try {
                cmdLine = parser.parse(options, args);
                if (cmdLine.hasOption("help")) {
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.printHelp("owls2wsdl [options] FILE.owl", options);
                    System.exit(0);
                }
            } catch (ParseException exp) {
                // oops, something went wrong
                System.out.println("Error: Parsing failed, reason: " + exp.getMessage());
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("owls2wsdl", options, true);
            }

            if (args.length == 1) {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("owls2wsdl [options] FILE.owl", options);
                System.out.println("Error: Option -kbdir is missing.");
                System.exit(0);
            } else {
                String ontURI = args[args.length - 1].toString();
                String persistentName = "KB_"
                        + ontURI.substring(ontURI.lastIndexOf("/") + 1, ontURI.lastIndexOf(".")) + "-MAP.xml";

                try {
                    if (cmdLine.hasOption("kbdir")) {
                        String kbdirValue = cmdLine.getOptionValue("kbdir");
                        if (new File(kbdirValue).isDirectory()) {
                            DatatypeParser p = new DatatypeParser();
                            p.parse(args[args.length - 1].toString());
                            p.getAbstractDatatypeKBData();
                            if (!cmdLine.hasOption("test")) {
                                System.out.println("AUSGABE: " + kbdirValue + File.separator + persistentName);
                                FileOutputStream ausgabeStream = new FileOutputStream(
                                        kbdirValue + File.separator + persistentName);
                                AbstractDatatypeKB.getInstance().marshallAsXML(ausgabeStream, true); // System.out);
                            }
                        }
                    }
                } catch (java.net.MalformedURLException murle) {
                    System.err.println("MalformedURLException: " + murle.getMessage());
                    System.err.println("Try something like: http://127.0.0.1/ontology/my_ontology.owl");
                } catch (Exception e) {
                    System.err.println("Exception: " + e.toString());
                }
            }
        } else if (args[args.length - 1].toString().endsWith(".xml")) {
            // -owlclass http://127.0.0.1/ontology/Student.owl#HTWStudent
            // -xsd -d 1 -h D:\tmp\KB\KB_Student-MAP.xml
            Option xsd = new Option("xsd", "generate XML Schema");
            Option info = new Option("info", "print datatype information");
            @SuppressWarnings("static-access")
            Option owlclass = OptionBuilder.withArgName("class").hasArg()
                    .withDescription("owl class to translate; necessary").create("owlclass");
            Option keys = new Option("keys", "list all owlclass keys");
            options.addOption(keys);
            options.addOption(owlclass);
            options.addOption(info);
            options.addOption(xsd);
            options.addOption("h", "hierarchy", false, "use hierarchy pattern");
            options.addOption("d", "depth", true, "set recursion depth");
            options.addOption("b", "behavior", true, "set inheritance bevavior");
            options.addOption("p", "primitive", true, "set default primitive type");

            try {
                cmdLine = parser.parse(options, args);
                if (cmdLine.hasOption("help")) {
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.printHelp("owls2wsdl [options] FILE.xml", options);
                    System.exit(0);
                }
            } catch (ParseException exp) {
                // oops, something went wrong
                System.out.println("Error: Parsing failed, reason: " + exp.getMessage());
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("owls2wsdl", options, true);
            }

            if (args.length == 1) {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("owls2wsdl [options] FILE.xml", options);
                System.exit(0);
            } else if (cmdLine.hasOption("keys")) {
                File f = new File(args[args.length - 1].toString());
                try {
                    AbstractDatatypeMapper.getInstance().loadAbstractDatatypeKB(f);
                } catch (Exception e) {
                    System.err.println("Error: " + e.getMessage());
                    System.exit(1);
                }
                AbstractDatatypeKB.getInstance().getAbstractDatatypeKBData().printRegisteredDatatypes();
                System.exit(0);
            } else if (!cmdLine.hasOption("owlclass")) {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("owls2wsdl [options] FILE.xml", "", options,
                        "Info: owl class not set.\n e.g. -owlclass http://127.0.0.1/ontology/Student.owl#Student");
                System.exit(0);
            } else {
                File f = new File(args[args.length - 1].toString());
                try {
                    AbstractDatatypeMapper.getInstance().loadAbstractDatatypeKB(f);
                } catch (Exception e) {
                    System.err.println("Error: " + e.getMessage());
                    System.exit(1);
                }

                String owlclassString = cmdLine.getOptionValue("owlclass");
                if (!AbstractDatatypeKB.getInstance().getAbstractDatatypeKBData().containsKey(owlclassString)) {
                    System.err.println("Error: Key " + owlclassString + " not in knowledgebase.");
                    System.exit(1);
                }

                if (cmdLine.hasOption("info")) {
                    AbstractDatatypeKB.getInstance().getAbstractDatatypeKBData().get(owlclassString)
                            .printDatatype();
                }
                if (cmdLine.hasOption("xsd")) {
                    boolean hierachy = false;
                    int depth = 0;
                    String inheritanceBehavior = AbstractDatatype.InheritanceByNone;
                    String defaultPrimitiveType = "http://www.w3.org/2001/XMLSchema#string";

                    if (cmdLine.hasOption("h")) {
                        hierachy = true;
                    }
                    if (cmdLine.hasOption("d")) {
                        depth = Integer.parseInt(cmdLine.getOptionValue("d"));
                    }
                    if (cmdLine.hasOption("b")) {
                        System.out.print("Set inheritance behaviour to: ");
                        if (cmdLine.getOptionValue("b")
                                .equals(AbstractDatatype.InheritanceByParentsFirstRDFTypeSecond)) {
                            System.out.println(AbstractDatatype.InheritanceByParentsFirstRDFTypeSecond);
                            inheritanceBehavior = AbstractDatatype.InheritanceByNone;
                        } else if (cmdLine.getOptionValue("b")
                                .equals(AbstractDatatype.InheritanceByRDFTypeFirstParentsSecond)) {
                            System.out.println(AbstractDatatype.InheritanceByRDFTypeFirstParentsSecond);
                            inheritanceBehavior = AbstractDatatype.InheritanceByRDFTypeFirstParentsSecond;
                        } else if (cmdLine.getOptionValue("b")
                                .equals(AbstractDatatype.InheritanceByRDFTypeOnly)) {
                            System.out.println(AbstractDatatype.InheritanceByRDFTypeOnly);
                            inheritanceBehavior = AbstractDatatype.InheritanceByRDFTypeOnly;
                        } else if (cmdLine.getOptionValue("b")
                                .equals(AbstractDatatype.InheritanceBySuperClassOnly)) {
                            System.out.println(AbstractDatatype.InheritanceBySuperClassOnly);
                            inheritanceBehavior = AbstractDatatype.InheritanceBySuperClassOnly;
                        } else {
                            System.out.println(AbstractDatatype.InheritanceByNone);
                            inheritanceBehavior = AbstractDatatype.InheritanceByNone;
                        }
                    }
                    if (cmdLine.hasOption("p")) {
                        defaultPrimitiveType = cmdLine.getOptionValue("p");
                        if (defaultPrimitiveType.split("#")[0].equals("http://www.w3.org/2001/XMLSchema")) {
                            System.err.println("Error: Primitive Type not valid: " + defaultPrimitiveType);
                            System.exit(1);
                        }
                    }
                    XsdSchemaGenerator xsdgen = new XsdSchemaGenerator("SCHEMATYPE", hierachy, depth,
                            inheritanceBehavior, defaultPrimitiveType);

                    try {
                        AbstractDatatypeKB.getInstance().toXSD(owlclassString, xsdgen, System.out);
                    } catch (Exception e) {
                        System.err.println("Error: " + e.getMessage());
                    }
                }

            }
        } else {
            try {
                cmdLine = parser.parse(options, args);
                if (cmdLine.hasOption("help")) {
                    printDefaultHelpMessage();
                }
            } catch (ParseException exp) {
                // oops, something went wrong
                System.out.println("Error: Parsing failed, reason: " + exp.getMessage());
                printDefaultHelpMessage();
            }
        }
    } else {
        OWLS2WSDLGui.createAndShowGUI();
    }

    // for(Iterator it=options.getOptions().iterator(); it.hasNext(); ) {
    // String optString = ((Option)it.next()).getOpt();
    // if(cmdLine.hasOption(optString)) {
    // System.out.println("Option set: "+optString);
    // }
    // }

}

From source file:com.jbrisbin.groovy.mqdsl.RabbitMQDsl.java

public static void main(String[] argv) {

    // Parse command line arguments
    CommandLine args = null;/*from w  w w.j  a  v a2s .c  om*/
    try {
        Parser p = new BasicParser();
        args = p.parse(cliOpts, argv);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    }

    // Check for help
    if (args.hasOption('?')) {
        printUsage();
        return;
    }

    // Runtime properties
    Properties props = System.getProperties();

    // Check for ~/.rabbitmqrc
    File userSettings = new File(System.getProperty("user.home"), ".rabbitmqrc");
    if (userSettings.exists()) {
        try {
            props.load(new FileInputStream(userSettings));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    // Load Groovy builder file
    StringBuffer script = new StringBuffer();
    BufferedInputStream in = null;
    String filename = "<STDIN>";
    if (args.hasOption("f")) {
        filename = args.getOptionValue("f");
        try {
            in = new BufferedInputStream(new FileInputStream(filename));
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        in = new BufferedInputStream(System.in);
    }

    // Read script
    if (null != in) {
        byte[] buff = new byte[4096];
        try {
            for (int read = in.read(buff); read > -1;) {
                script.append(new String(buff, 0, read));
                read = in.read(buff);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        System.err.println("No script file to evaluate...");
    }

    PrintStream stdout = System.out;
    PrintStream out = null;
    if (args.hasOption("o")) {
        try {
            out = new PrintStream(new FileOutputStream(args.getOptionValue("o")), true);
            System.setOut(out);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    }

    String[] includes = (System.getenv().containsKey("MQDSL_INCLUDE")
            ? System.getenv("MQDSL_INCLUDE").split(String.valueOf(File.pathSeparatorChar))
            : new String[] { System.getenv("HOME") + File.separator + ".mqdsl.d" });

    try {
        // Setup RabbitMQ
        String username = (args.hasOption("U") ? args.getOptionValue("U")
                : props.getProperty("mq.user", "guest"));
        String password = (args.hasOption("P") ? args.getOptionValue("P")
                : props.getProperty("mq.password", "guest"));
        String virtualHost = (args.hasOption("v") ? args.getOptionValue("v")
                : props.getProperty("mq.virtualhost", "/"));
        String host = (args.hasOption("h") ? args.getOptionValue("h")
                : props.getProperty("mq.host", "localhost"));
        int port = Integer.parseInt(
                args.hasOption("p") ? args.getOptionValue("p") : props.getProperty("mq.port", "5672"));

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        if (null != virtualHost) {
            connectionFactory.setVirtualHost(virtualHost);
        }

        // The DSL builder
        RabbitMQBuilder builder = new RabbitMQBuilder();
        builder.setConnectionFactory(connectionFactory);
        // Our execution environment
        Binding binding = new Binding(args.getArgs());
        binding.setVariable("mq", builder);
        String fileBaseName = filename.replaceAll("\\.groovy$", "");
        binding.setVariable("log",
                LoggerFactory.getLogger(fileBaseName.substring(fileBaseName.lastIndexOf("/") + 1)));
        if (null != out) {
            binding.setVariable("out", out);
        }

        // Include helper files
        GroovyShell shell = new GroovyShell(binding);
        for (String inc : includes) {
            File f = new File(inc);
            if (f.isDirectory()) {
                File[] files = f.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File file, String s) {
                        return s.endsWith(".groovy");
                    }
                });
                for (File incFile : files) {
                    run(incFile, shell, binding);
                }
            } else {
                run(f, shell, binding);
            }
        }

        run(script.toString(), shell, binding);

        while (builder.isActive()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }

        if (null != out) {
            out.close();
            System.setOut(stdout);
        }

    } finally {
        System.exit(0);
    }
}

From source file:org.cbio.portal.pipelines.FoundationPipeline.java

public static void main(String[] args) throws Exception {
    Options gnuOptions = FoundationPipeline.getOptions(args);
    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = parser.parse(gnuOptions, args);
    if (commandLine.hasOption("h") || !commandLine.hasOption("source") || !commandLine.hasOption("output")
            || !commandLine.hasOption("cancer_study_id")) {
        help(gnuOptions, 0);//from w  ww .j a  va2  s . c  o  m
    }
    for (String v : commandLine.getArgList()) {
        System.out.println(v);
    }

    // light pre-processing for source directory and output directory paths
    String sourceDirectory = commandLine.getOptionValue("source");
    String outputDirectory = commandLine.getOptionValue("output");
    String cancerStudyId = commandLine.getOptionValue("cancer_study_id");
    if (!sourceDirectory.endsWith(File.separator))
        sourceDirectory += File.separator;
    if (!outputDirectory.endsWith(File.separator))
        outputDirectory += File.separator;

    // determine whether to run xml document generator job or not
    boolean generateXmlDocument = commandLine.hasOption("generate_xml");

    launchJob(args, sourceDirectory, outputDirectory, cancerStudyId, generateXmlDocument);
}

From source file:PinotResponseTime.java

public static void main(String[] args) throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost("http://localhost:8099/query");
        CloseableHttpResponse res;// ww  w  . j a  v  a2s . co  m

        if (STORE_RESULT) {
            File dir = new File(RESULT_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }

        int length;

        // Make sure all segments online
        System.out.println("Test if number of records is " + RECORD_NUMBER);
        post.setEntity(new StringEntity("{\"pql\":\"select count(*) from tpch_lineitem\"}"));
        while (true) {
            System.out.print('*');
            res = client.execute(post);
            boolean valid;
            try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent())) {
                length = in.read(BUFFER);
                valid = new String(BUFFER, 0, length, "UTF-8").contains("\"value\":\"" + RECORD_NUMBER + "\"");
            }
            res.close();
            if (valid) {
                break;
            } else {
                Thread.sleep(5000);
            }
        }
        System.out.println("Number of Records Test Passed");

        // Start Benchmark
        for (int i = 0; i < QUERIES.length; i++) {
            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Start running query: " + QUERIES[i]);
            post.setEntity(new StringEntity("{\"pql\":\"" + QUERIES[i] + "\"}"));

            // Warm-up Rounds
            System.out.println("Run " + WARMUP_ROUND + " times to warm up cache...");
            for (int j = 0; j < WARMUP_ROUND; j++) {
                res = client.execute(post);
                if (!isValid(res, null)) {
                    System.out.println("\nInvalid Response, Sleep 20 Seconds...");
                    Thread.sleep(20000);
                }
                res.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            int[] time = new int[TEST_ROUND];
            int totalTime = 0;
            int validIdx = 0;
            System.out.println("Run " + TEST_ROUND + " times to get average time...");
            while (validIdx < TEST_ROUND) {
                long startTime = System.currentTimeMillis();
                res = client.execute(post);
                long endTime = System.currentTimeMillis();
                boolean valid;
                if (STORE_RESULT && validIdx == 0) {
                    valid = isValid(res, RESULT_DIR + File.separator + i + ".json");
                } else {
                    valid = isValid(res, null);
                }
                if (!valid) {
                    System.out.println("\nInvalid Response, Sleep 20 Seconds...");
                    Thread.sleep(20000);
                    res.close();
                    continue;
                }
                res.close();
                time[validIdx] = (int) (endTime - startTime);
                totalTime += time[validIdx];
                System.out.print(time[validIdx] + "ms ");
                validIdx++;
            }
            System.out.println();

            // Process Results
            double avgTime = (double) totalTime / TEST_ROUND;
            double stdDev = 0;
            for (int temp : time) {
                stdDev += (temp - avgTime) * (temp - avgTime) / TEST_ROUND;
            }
            stdDev = Math.sqrt(stdDev);
            System.out.println("The average response time for the query is: " + avgTime + "ms");
            System.out.println("The standard deviation is: " + stdDev);
        }
    }
}

From source file:com.linkedin.restli.tools.data.FilterSchemaGenerator.java

public static void main(String[] args) {
    CommandLine cl = null;//  www  . j av  a2 s  .com
    try {
        final CommandLineParser parser = new GnuParser();
        cl = parser.parse(_options, args);
    } catch (ParseException e) {
        _log.error("Invalid arguments: " + e.getMessage());
        reportInvalidArguments();
    }

    final String[] directoryArgs = cl.getArgs();
    if (directoryArgs.length != 2) {
        reportInvalidArguments();
    }

    final File sourceDirectory = new File(directoryArgs[0]);
    if (!sourceDirectory.exists()) {
        _log.error(sourceDirectory.getPath() + " does not exist");
        System.exit(1);
    }
    if (!sourceDirectory.isDirectory()) {
        _log.error(sourceDirectory.getPath() + " is not a directory");
        System.exit(1);
    }
    final URI sourceDirectoryURI = sourceDirectory.toURI();

    final File outputDirectory = new File(directoryArgs[1]);
    if (outputDirectory.exists() && !sourceDirectory.isDirectory()) {
        _log.error(outputDirectory.getPath() + " is not a directory");
        System.exit(1);
    }

    final boolean isAvroMode = cl.hasOption('a');
    final String predicateExpression = cl.getOptionValue('e');
    final Predicate predicate = PredicateExpressionParser.parse(predicateExpression);

    final Collection<File> sourceFiles = FileUtil.listFiles(sourceDirectory, null);
    int exitCode = 0;
    for (File sourceFile : sourceFiles) {
        try {
            final ValidationOptions val = new ValidationOptions();
            val.setAvroUnionMode(isAvroMode);

            final SchemaParser schemaParser = new SchemaParser();
            schemaParser.setValidationOptions(val);

            schemaParser.parse(new FileInputStream(sourceFile));
            if (schemaParser.hasError()) {
                _log.error("Error parsing " + sourceFile.getPath() + ": " + schemaParser.errorMessageBuilder());
                exitCode = 1;
                continue;
            }

            final DataSchema originalSchema = schemaParser.topLevelDataSchemas().get(0);
            if (!(originalSchema instanceof NamedDataSchema)) {
                _log.error(sourceFile.getPath() + " does not contain valid NamedDataSchema");
                exitCode = 1;
                continue;
            }

            final SchemaParser filterParser = new SchemaParser();
            filterParser.setValidationOptions(val);

            final NamedDataSchema filteredSchema = Filters.removeByPredicate((NamedDataSchema) originalSchema,
                    predicate, filterParser);
            if (filterParser.hasError()) {
                _log.error("Error applying predicate: " + filterParser.errorMessageBuilder());
                exitCode = 1;
                continue;
            }

            final String relativePath = sourceDirectoryURI.relativize(sourceFile.toURI()).getPath();
            final String outputFilePath = outputDirectory.getPath() + File.separator + relativePath;
            final File outputFile = new File(outputFilePath);
            final File outputFileParent = outputFile.getParentFile();
            outputFileParent.mkdirs();
            if (!outputFileParent.exists()) {
                _log.error("Unable to write filtered schema to " + outputFileParent.getPath());
                exitCode = 1;
                continue;
            }

            FileOutputStream fout = new FileOutputStream(outputFile);
            String schemaJson = SchemaToJsonEncoder.schemaToJson(filteredSchema, JsonBuilder.Pretty.INDENTED);
            fout.write(schemaJson.getBytes(RestConstants.DEFAULT_CHARSET));
            fout.close();
        } catch (IOException e) {
            _log.error(e.getMessage());
            exitCode = 1;
        }
    }

    System.exit(exitCode);
}

From source file:com.flagleader.builder.FlagLeader.java

public static void main(String[] paramArrayOfString) {
    Shell localShell = new Shell(16777216);
    localShell.setLocation(new Point(300, 200));
    localShell.setLayout(new FillLayout());
    Composite localComposite = new Composite(localShell, 0);
    localComposite.setLayout(new FillLayout());
    Label localLabel = new Label(localComposite, 0);
    Image localImage = ImageDescriptor
            .createFromURL(localShell.getClass().getClassLoader().getResource("icons/start.jpg")).createImage();
    localLabel.setImage(localImage);//from ww w. j a v a  2 s . com
    localShell.setSize(400, 300);
    localShell.setText("Visual Rules Solution");
    localShell.open();
    Init.a();
    String str = null;
    if (BuilderConfig.getInstance().isLoadDefault())
        str = RuleRepository.DEFAULTEXT;
    if (paramArrayOfString.length > 0)
        str = "";
    for (int i = 0; i < paramArrayOfString.length; i++)
        str = str + paramArrayOfString[i] + " ";
    Logger localLogger = Logger.getLogger("ruleengine");
    Object localObject;
    try {
        new File(SystemUtils.USER_HOME + File.separator + ".visualrules" + File.separator + "logs").mkdirs();
        FileHandler localFileHandler = new FileHandler(SystemUtils.USER_HOME + File.separator + ".visualrules"
                + File.separator + "logs" + File.separator + "logfile%u.%g.txt", 0, 10);
        localFileHandler.setFormatter(new com.flagleader.server.c());
        localFileHandler.setLevel(Level.ALL);
        Logger.getLogger("flagleader").addHandler(localFileHandler);
        localLogger.addHandler(localFileHandler);
    } catch (Exception localException1) {
        if (!b) {
            localObject = new ConsoleHandler();
            ((ConsoleHandler) localObject).setFormatter(new com.flagleader.server.c());
            ((ConsoleHandler) localObject).setLevel(Level.ALL);
            Logger.getLogger("flagleader").addHandler((Handler) localObject);
            localLogger.addHandler((Handler) localObject);
        }
    }
    if (!BuilderManager.checkLicense()) {
        localImage.dispose();
        localShell.dispose();
        return;
    }
    Property.getInstance().setEngineImplement("com.flagleader.engine.impl.SingleRuleEngineFactory");
    FlagLeader localFlagLeader = new FlagLeader();
    Property.getInstance().setUpdateInternateTime(0L);
    localFlagLeader.setBlockOnOpen(true);
    localFlagLeader.builderManager = new BuilderManager(localFlagLeader);
    if ((com.flagleader.manager.d.c.a("needLogin", false)) || (BuilderConfig.getInstance().isFirstLogin()))
        try {
            localObject = localFlagLeader.builderManager.getUserServer();
            if ((localObject == null) || (((String) localObject).length() == 0)
                    || (localFlagLeader.builderManager.getUserType() == 0)
                    || (localFlagLeader.builderManager.getUserid() == 0)) {
                localImage.dispose();
                localShell.dispose();
                return;
            }
        } catch (Exception localException2) {
            MessageDialog.openError(null, "",
                    ResourceTools.getMessage("loginserver.error") + localException2.getLocalizedMessage());
            localImage.dispose();
            localShell.dispose();
            return;
        }
    if ((str != null) && (new File(str).exists()))
        localFlagLeader.builderManager.getRulesManager().a(new File(str));
    localFlagLeader.initWindow();
    if (new File(SystemUtils.JAVA_IO_TMPDIR, "engine.jar").exists())
        new File(SystemUtils.JAVA_IO_TMPDIR, "engine.jar").delete();
    if (new File(SystemUtils.JAVA_IO_TMPDIR, "export.jar").exists())
        new File(SystemUtils.JAVA_IO_TMPDIR, "export.jar").delete();
    if (BuilderConfig.getInstance().isAutosave())
        new com.flagleader.builder.d.c(localFlagLeader.builderManager).b();
    if (BuilderConfig.getInstance().isAutoCheckVersion())
        new a(localFlagLeader.builderManager).b();
    new e().b();
    localImage.dispose();
    localShell.dispose();
    localFlagLeader.open();
    BuilderManager localBuilderManager = localFlagLeader.builderManager;
    localFlagLeader.getShell().addShellListener(new d(localBuilderManager));
}

From source file:com.ctriposs.rest4j.tools.data.FilterSchemaGenerator.java

public static void main(String[] args) {
    final CommandLineParser parser = new GnuParser();
    CommandLine cl = null;/*from w ww  .  java  2 s .c  om*/
    try {
        cl = parser.parse(_options, args);
    } catch (ParseException e) {
        _log.error("Invalid arguments: " + e.getMessage());
        reportInvalidArguments();
    }

    final String[] directoryArgs = cl.getArgs();
    if (directoryArgs.length != 2) {
        reportInvalidArguments();
    }

    final File sourceDirectory = new File(directoryArgs[0]);
    if (!sourceDirectory.exists()) {
        _log.error(sourceDirectory.getPath() + " does not exist");
        System.exit(1);
    }
    if (!sourceDirectory.isDirectory()) {
        _log.error(sourceDirectory.getPath() + " is not a directory");
        System.exit(1);
    }
    final URI sourceDirectoryURI = sourceDirectory.toURI();

    final File outputDirectory = new File(directoryArgs[1]);
    if (outputDirectory.exists() && !sourceDirectory.isDirectory()) {
        _log.error(outputDirectory.getPath() + " is not a directory");
        System.exit(1);
    }

    final boolean isAvroMode = cl.hasOption('a');
    final String predicateExpression = cl.getOptionValue('e');
    final Predicate predicate = PredicateExpressionParser.parse(predicateExpression);

    final Collection<File> sourceFiles = FileUtil.listFiles(sourceDirectory, null);
    int exitCode = 0;
    for (File sourceFile : sourceFiles) {
        try {
            final ValidationOptions val = new ValidationOptions();
            val.setAvroUnionMode(isAvroMode);

            final SchemaParser schemaParser = new SchemaParser();
            schemaParser.setValidationOptions(val);

            schemaParser.parse(new FileInputStream(sourceFile));
            if (schemaParser.hasError()) {
                _log.error("Error parsing " + sourceFile.getPath() + ": "
                        + schemaParser.errorMessageBuilder().toString());
                exitCode = 1;
                continue;
            }

            final DataSchema originalSchema = schemaParser.topLevelDataSchemas().get(0);
            if (!(originalSchema instanceof NamedDataSchema)) {
                _log.error(sourceFile.getPath() + " does not contain valid NamedDataSchema");
                exitCode = 1;
                continue;
            }

            final SchemaParser filterParser = new SchemaParser();
            filterParser.setValidationOptions(val);

            final NamedDataSchema filteredSchema = Filters.removeByPredicate((NamedDataSchema) originalSchema,
                    predicate, filterParser);
            if (filterParser.hasError()) {
                _log.error("Error applying predicate: " + filterParser.errorMessageBuilder().toString());
                exitCode = 1;
                continue;
            }

            final String relativePath = sourceDirectoryURI.relativize(sourceFile.toURI()).getPath();
            final String outputFilePath = outputDirectory.getPath() + File.separator + relativePath;
            final File outputFile = new File(outputFilePath);
            final File outputFileParent = outputFile.getParentFile();
            outputFileParent.mkdirs();
            if (!outputFileParent.exists()) {
                _log.error("Unable to write filtered schema to " + outputFileParent.getPath());
                exitCode = 1;
                continue;
            }

            FileOutputStream fout = new FileOutputStream(outputFile);
            fout.write(filteredSchema.toString().getBytes(RestConstants.DEFAULT_CHARSET));
            fout.close();
        } catch (IOException e) {
            _log.error(e.getMessage());
            exitCode = 1;
        }
    }

    System.exit(exitCode);
}

From source file:ch.kostceco.tools.kostsimy.KOSTSimy.java

/** Die Eingabe besteht aus 2 Parameter: [0] Original-Ordner [1] Replica-Ordner
 * //  w ww .j  a  va 2  s.co m
 * @param args
 * @throws IOException */

public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:config/applicationContext.xml");

    // Zeitstempel Start
    java.util.Date nowStart = new java.util.Date();
    java.text.SimpleDateFormat sdfStart = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
    String ausgabeStart = sdfStart.format(nowStart);

    KOSTSimy kostsimy = (KOSTSimy) context.getBean("kostsimy");
    File configFile = new File("configuration" + File.separator + "kostsimy.conf.xml");

    // Ueberprfung des Parameters (Log-Verzeichnis)
    String pathToLogfile = kostsimy.getConfigurationService().getPathToLogfile();

    File directoryOfLogfile = new File(pathToLogfile);

    if (!directoryOfLogfile.exists()) {
        directoryOfLogfile.mkdir();
    }

    // Im Logverzeichnis besteht kein Schreibrecht
    if (!directoryOfLogfile.canWrite()) {
        System.out.println(
                kostsimy.getTextResourceService().getText(ERROR_LOGDIRECTORY_NOTWRITABLE, directoryOfLogfile));
        System.exit(1);
    }

    if (!directoryOfLogfile.isDirectory()) {
        System.out.println(kostsimy.getTextResourceService().getText(ERROR_LOGDIRECTORY_NODIRECTORY));
        System.exit(1);
    }

    // Ist die Anzahl Parameter (2) korrekt?
    if (args.length > 3) {
        System.out.println(kostsimy.getTextResourceService().getText(ERROR_PARAMETER_USAGE));
        System.exit(1);
    }

    File origDir = new File(args[0]);
    File repDir = new File(args[1]);
    File logDatei = null;
    logDatei = origDir;

    // Informationen zum Arbeitsverzeichnis holen
    String pathToWorkDir = kostsimy.getConfigurationService().getPathToWorkDir();
    /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
     * entsprechenden Modul die property anzugeben: <property name="configurationService"
     * ref="configurationService" /> */

    // Konfiguration des Loggings, ein File Logger wird zustzlich erstellt
    LogConfigurator logConfigurator = (LogConfigurator) context.getBean("logconfigurator");
    String logFileName = logConfigurator.configure(directoryOfLogfile.getAbsolutePath(), logDatei.getName());
    File logFile = new File(logFileName);
    // Ab hier kann ins log geschrieben werden...

    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_HEADER));
    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_START, ausgabeStart));
    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_END));
    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_INFO));
    System.out.println("KOST-Simy");
    System.out.println("");

    if (!origDir.exists()) {
        // Das Original-Verzeichnis existiert nicht
        LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                kostsimy.getTextResourceService().getText(ERROR_NOORIGDIR, origDir.getAbsolutePath())));
        System.out
                .println(kostsimy.getTextResourceService().getText(ERROR_NOORIGDIR, origDir.getAbsolutePath()));
        System.exit(1);
    }

    if (!repDir.exists()) {
        // Das Replica-Verzeichnis existiert nicht
        LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                kostsimy.getTextResourceService().getText(ERROR_NOREPDIR1, repDir.getAbsolutePath())));
        System.out
                .println(kostsimy.getTextResourceService().getText(ERROR_NOREPDIR1, repDir.getAbsolutePath()));
        System.exit(1);
    }

    File xslOrig = new File("resources" + File.separator + "kost-simy.xsl");
    File xslCopy = new File(directoryOfLogfile.getAbsolutePath() + File.separator + "kost-simy.xsl");
    if (!xslCopy.exists()) {
        Util.copyFile(xslOrig, xslCopy);
    }

    // Informationen zur prozentualen Stichprobe holen
    String randomTest = kostsimy.getConfigurationService().getRandomTest();
    /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
     * entsprechenden Modul die property anzugeben: <property name="configurationService"
     * ref="configurationService" /> */
    int iRandomTest = 100;
    try {
        iRandomTest = Integer.parseInt(randomTest);
    } catch (Exception ex) {
        // unzulaessige Eingabe --> 50 wird gesetzt
        iRandomTest = 50;
    }
    if (iRandomTest > 100 || iRandomTest < 1) {
        // unzulaessige Eingabe --> 50 wird gesetzt
        iRandomTest = 50;
    }

    File tmpDir = new File(pathToWorkDir);

    /* bestehendes Workverzeichnis Abbruch wenn nicht leer, da am Schluss das Workverzeichnis
     * gelscht wird und entsprechend bestehende Dateien gelscht werden knnen */
    if (tmpDir.exists()) {
        if (tmpDir.isDirectory()) {
            // Get list of file in the directory. When its length is not zero the folder is not empty.
            String[] files = tmpDir.list();
            if (files.length > 0) {
                LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                        kostsimy.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS, pathToWorkDir)));
                System.out.println(
                        kostsimy.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS, pathToWorkDir));
                System.exit(1);
            }
        }
    }

    // Im Pfad keine Sonderzeichen Programme knnen evtl abstrzen

    String patternStr = "[^!#\\$%\\(\\)\\+,\\-_\\.=@\\[\\]\\{\\}\\~:\\\\a-zA-Z0-9 ]";
    Pattern pattern = Pattern.compile(patternStr);

    String name = tmpDir.getAbsolutePath();

    String[] pathElements = name.split("/");
    for (int i = 0; i < pathElements.length; i++) {
        String element = pathElements[i];

        Matcher matcher = pattern.matcher(element);

        boolean matchFound = matcher.find();
        if (matchFound) {
            LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                    kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)));
            System.out.println(kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name));
            System.exit(1);
        }
    }

    // die Anwendung muss mindestens unter Java 6 laufen
    String javaRuntimeVersion = System.getProperty("java.vm.version");
    if (javaRuntimeVersion.compareTo("1.6.0") < 0) {
        LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                kostsimy.getTextResourceService().getText(ERROR_WRONG_JRE)));
        System.out.println(kostsimy.getTextResourceService().getText(ERROR_WRONG_JRE));
        System.exit(1);
    }

    // bestehendes Workverzeichnis wieder anlegen
    if (!tmpDir.exists()) {
        tmpDir.mkdir();
        File origDirTmp = new File(tmpDir.getAbsolutePath() + File.separator + "orig");
        File repDirTmp = new File(tmpDir.getAbsolutePath() + File.separator + "rep");
        origDirTmp.mkdir();
        repDirTmp.mkdir();
    }

    // Im workverzeichnis besteht kein Schreibrecht
    if (!tmpDir.canWrite()) {
        LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                kostsimy.getTextResourceService().getText(ERROR_WORKDIRECTORY_NOTWRITABLE, tmpDir)));
        System.out.println(kostsimy.getTextResourceService().getText(ERROR_WORKDIRECTORY_NOTWRITABLE, tmpDir));
        System.exit(1);
    }

    // Im Pfad keine Sonderzeichen --> Absturzgefahr
    name = origDir.getAbsolutePath();
    pathElements = name.split("/");
    for (int i = 0; i < pathElements.length; i++) {
        String element = pathElements[i];
        Matcher matcher = pattern.matcher(element);
        boolean matchFound = matcher.find();
        if (matchFound) {
            LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                    kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)));
            System.out.println(kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name));
            System.exit(1);
        }
    }
    name = repDir.getAbsolutePath();
    pathElements = name.split("/");
    for (int i = 0; i < pathElements.length; i++) {
        String element = pathElements[i];
        Matcher matcher = pattern.matcher(element);
        boolean matchFound = matcher.find();
        if (matchFound) {
            LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                    kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)));
            System.out.println(kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name));
            System.exit(1);
        }
    }

    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_IMAGE1));
    float count = 0;
    int countNio = 0;
    int countIo = 0;
    float countVal = 0;
    int countNotVal = 0;
    float percentage = (float) 0.0;

    if (!origDir.isDirectory()) {
        // TODO: Bildervergleich zweier Dateien --> erledigt --> nur Marker

        if (repDir.isDirectory()) {
            // Das Replica-ist ein Verzeichnis, aber Original eine Datei
            LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                    kostsimy.getTextResourceService().getText(ERROR_NOREPDIR2, repDir.getAbsolutePath())));
            System.out.println(
                    kostsimy.getTextResourceService().getText(ERROR_NOREPDIR2, repDir.getAbsolutePath()));
            System.exit(1);
        }
        boolean compFile = compFile(origDir, logFileName, directoryOfLogfile, repDir, tmpDir);

        float statIo = 0;
        int statNio = 0;
        float statUn = 0;
        if (compFile) {
            statIo = 100;
        } else {
            statNio = 100;
        }

        LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_IMAGE2));
        LOGGER.logError(
                kostsimy.getTextResourceService().getText(MESSAGE_XML_STATISTICS, statIo, statNio, statUn));

        LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_LOGEND));
        // Zeitstempel End
        java.util.Date nowEnd = new java.util.Date();
        java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
        String ausgabeEnd = sdfEnd.format(nowEnd);
        ausgabeEnd = "<End>" + ausgabeEnd + "</End>";
        Util.valEnd(ausgabeEnd, logFile);
        Util.amp(logFile);

        // Die Konfiguration hereinkopieren
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);

            factory.setExpandEntityReferences(false);

            Document docConfig = factory.newDocumentBuilder().parse(configFile);
            NodeList list = docConfig.getElementsByTagName("configuration");
            Element element = (Element) list.item(0);

            Document docLog = factory.newDocumentBuilder().parse(logFile);

            Node dup = docLog.importNode(element, true);

            docLog.getDocumentElement().appendChild(dup);
            FileWriter writer = new FileWriter(logFile);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ElementToStream(docLog.getDocumentElement(), baos);
            String stringDoc2 = new String(baos.toByteArray());
            writer.write(stringDoc2);
            writer.close();

            // Der Header wird dabei leider verschossen, wieder zurck ndern
            String newstring = kostsimy.getTextResourceService().getText(MESSAGE_XML_HEADER);
            String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTSimyLog>";
            Util.oldnewstring(oldstring, newstring, logFile);

        } catch (Exception e) {
            LOGGER.logError(
                    "<Error>" + kostsimy.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
            System.out.println("Exception: " + e.getMessage());
        }

        if (compFile) {
            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            // Validierte Datei valide
            System.exit(0);
        } else {
            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            // Fehler in Validierte Datei --> invalide
            System.exit(2);

        }
    } else {
        // TODO: Bildervergleich zweier Verzeichnisse --> in Arbeit --> nur Marker
        if (!repDir.isDirectory()) {
            // Das Replica-ist eine Datei, aber Original ein Ordner
            LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                    kostsimy.getTextResourceService().getText(ERROR_NOREPDIR3, repDir.getAbsolutePath())));
            System.out.println(
                    kostsimy.getTextResourceService().getText(ERROR_NOREPDIR3, repDir.getAbsolutePath()));
            System.exit(1);
        }

        Map<String, File> fileMap = Util.getFileMap(origDir, false);
        Set<String> fileMapKeys = fileMap.keySet();
        boolean other = false;

        for (Iterator<String> iterator = fileMapKeys.iterator(); iterator.hasNext();) {
            String entryName = iterator.next();
            File newFile = fileMap.get(entryName);
            if (!newFile.isDirectory()) {
                origDir = newFile;
                count = count + 1;
                if ((origDir.getAbsolutePath().toLowerCase().endsWith(".pdf")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".pdfa")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".tif")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".tiff")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".jpeg")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".jpg")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".jpe")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".jp2")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".gif")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".png")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".bmp"))) {
                    percentage = 100 / count * countVal;
                    if (percentage < iRandomTest) {
                        // if ( 100 / count * (countVal + 1) <= iRandomTest ) {

                        countVal = countVal + 1;

                        String origWithOutExt = FilenameUtils.removeExtension(origDir.getName());

                        File repFile = new File(
                                repDir.getAbsolutePath() + File.separator + origWithOutExt + ".pdf");
                        if (!repFile.exists()) {
                            repFile = new File(
                                    repDir.getAbsolutePath() + File.separator + origWithOutExt + ".pdfa");
                            if (!repFile.exists()) {
                                repFile = new File(
                                        repDir.getAbsolutePath() + File.separator + origWithOutExt + ".tif");
                                if (!repFile.exists()) {
                                    repFile = new File(repDir.getAbsolutePath() + File.separator
                                            + origWithOutExt + ".tiff");
                                    if (!repFile.exists()) {
                                        repFile = new File(repDir.getAbsolutePath() + File.separator
                                                + origWithOutExt + ".jpeg");
                                        if (!repFile.exists()) {
                                            repFile = new File(repDir.getAbsolutePath() + File.separator
                                                    + origWithOutExt + ".jpg");
                                            if (!repFile.exists()) {
                                                repFile = new File(repDir.getAbsolutePath() + File.separator
                                                        + origWithOutExt + ".jpe");
                                                if (!repFile.exists()) {
                                                    repFile = new File(repDir.getAbsolutePath() + File.separator
                                                            + origWithOutExt + ".jp2");
                                                    if (!repFile.exists()) {
                                                        repFile = new File(repDir.getAbsolutePath()
                                                                + File.separator + origWithOutExt + ".gif");
                                                        if (!repFile.exists()) {
                                                            repFile = new File(repDir.getAbsolutePath()
                                                                    + File.separator + origWithOutExt + ".png");
                                                            if (!repFile.exists()) {
                                                                repFile = new File(repDir.getAbsolutePath()
                                                                        + File.separator + origWithOutExt
                                                                        + ".bmp");
                                                                if (!repFile.exists()) {
                                                                    other = true;
                                                                    LOGGER.logError(kostsimy
                                                                            .getTextResourceService()
                                                                            .getText(MESSAGE_XML_VALERGEBNIS));
                                                                    LOGGER.logError(kostsimy
                                                                            .getTextResourceService()
                                                                            .getText(MESSAGE_XML_COMPFILE,
                                                                                    origDir));
                                                                    LOGGER.logError(kostsimy
                                                                            .getTextResourceService().getText(
                                                                                    MESSAGE_XML_VALERGEBNIS_NOTVALIDATED));
                                                                    LOGGER.logError(
                                                                            kostsimy.getTextResourceService()
                                                                                    .getText(ERROR_NOREP,
                                                                                            origDir.getName()));
                                                                    LOGGER.logError(kostsimy
                                                                            .getTextResourceService().getText(
                                                                                    MESSAGE_XML_VALERGEBNIS_CLOSE));
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (!other) {
                            boolean compFile = compFile(origDir, logFileName, directoryOfLogfile, repFile,
                                    tmpDir);
                            if (compFile) {
                                // Vergleich bestanden
                                countIo = countIo + 1;
                            } else {
                                // Vergleich nicht bestanden
                                countNio = countNio + 1;
                            }
                        }
                    } else {
                        countNotVal = countNotVal + 1;
                        LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS));
                        LOGGER.logError(
                                kostsimy.getTextResourceService().getText(MESSAGE_XML_COMPFILE, origDir));
                        LOGGER.logError(kostsimy.getTextResourceService()
                                .getText(MESSAGE_XML_VALERGEBNIS_NOTVALIDATED));
                        LOGGER.logError(
                                kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE));
                    }
                } else {
                    countNotVal = countNotVal + 1;
                    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS));
                    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_COMPFILE, origDir));
                    LOGGER.logError(
                            kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_NOTVALIDATED));
                    LOGGER.logError(
                            kostsimy.getTextResourceService().getText(ERROR_INCORRECTFILEENDING, origDir));
                    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE));
                }
            }
        }

        if (countNio == 0 && countIo == 0) {
            // keine Dateien verglichen
            LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS));
            System.out.println(kostsimy.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS));
        }

        float statIo = 100 / (float) count * (float) countIo;
        float statNio = 100 / (float) count * (float) countNio;
        float statUn = 100 - statIo - statNio;

        LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_IMAGE2));
        LOGGER.logError(
                kostsimy.getTextResourceService().getText(MESSAGE_XML_STATISTICS, statIo, statNio, statUn));
        LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_LOGEND));
        // Zeitstempel End
        java.util.Date nowEnd = new java.util.Date();
        java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
        String ausgabeEnd = sdfEnd.format(nowEnd);
        ausgabeEnd = "<End>" + ausgabeEnd + "</End>";
        Util.valEnd(ausgabeEnd, logFile);
        Util.amp(logFile);

        // Die Konfiguration hereinkopieren
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);

            factory.setExpandEntityReferences(false);

            Document docConfig = factory.newDocumentBuilder().parse(configFile);
            NodeList list = docConfig.getElementsByTagName("configuration");
            Element element = (Element) list.item(0);

            Document docLog = factory.newDocumentBuilder().parse(logFile);

            Node dup = docLog.importNode(element, true);

            docLog.getDocumentElement().appendChild(dup);
            FileWriter writer = new FileWriter(logFile);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ElementToStream(docLog.getDocumentElement(), baos);
            String stringDoc2 = new String(baos.toByteArray());
            writer.write(stringDoc2);
            writer.close();

            // Der Header wird dabei leider verschossen, wieder zurck ndern
            String newstring = kostsimy.getTextResourceService().getText(MESSAGE_XML_HEADER);
            String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTSimyLog>";
            Util.oldnewstring(oldstring, newstring, logFile);

        } catch (Exception e) {
            LOGGER.logError(
                    "<Error>" + kostsimy.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
            System.out.println("Exception: " + e.getMessage());
        }

        if (countNio == 0 && countIo == 0) {
            // keine Dateien verglichen bestehendes Workverzeichnis ggf. lschen
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            System.exit(1);
        } else if (countNio == 0) {
            // bestehendes Workverzeichnis ggf. lschen
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            // alle Validierten Dateien valide
            System.exit(0);
        } else {
            // bestehendes Workverzeichnis ggf. lschen
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            // Fehler in Validierten Dateien --> invalide
            System.exit(2);
        }
        if (tmpDir.exists()) {
            Util.deleteDir(tmpDir);
            tmpDir.deleteOnExit();
        }
    }
}

From source file:com.ms.commons.test.tool.GenerateTestCase.java

public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("Usage:\r\n.frameworktest_maketests antx|maven fileter");
        System.exit(-1);/*  w  ww . j  a v a  2  s .  co  m*/
    }

    final com.ms.commons.test.runner.filter.expression.internal.Expression filterExpression;
    try {
        System.out.println("Filter: " + args[1]);
        filterExpression = ExpressionParseUtil.parse(args[1], new SimpleExpressionBuiler() {

            public AbstractSimpleExpression build(String value) {
                return new StringExpressionImpl(value);
            }
        });
    } catch (ParseException e) {
        throw ExceptionUtil.wrapToRuntimeException(e);
    }
    final FullClassNameFilter fullClassNameFilter = new FullClassNameFilter() {

        public boolean accept(String fullClassName) {

            return ((Boolean) filterExpression.evaluate(fullClassName)).booleanValue();
        }
    };

    String userDir = System.getProperty("user.dir");

    ProjectPath pp = getProjectPath(args[0]);

    final String mainSource = userDir + File.separator + pp.getMainSource();
    final String testSource = userDir + File.separator + pp.getTestSource();

    FileUtil.listFiles(null, new File(mainSource), new FileFilter() {

        public boolean accept(File pathname) {
            if (pathname.isDirectory()) {
                return !pathname.toString().contains(".svn");
            }
            if (pathname.toString().contains(".svn")) {
                return false;
            }
            if (!pathname.toString().toLowerCase().endsWith(".java")) {
                return false;
            }
            try {
                processJavaFile(pathname, testSource, fullClassNameFilter);
            } catch (Exception e) {
                System.err.println("Parse java file failed:" + pathname);
                e.printStackTrace();
            }
            return false;
        }
    });
}