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:bamboo.openhash.fileshare.FileShare.java

public static void main(String[] args) throws Exception {
    PatternLayout pl = new PatternLayout("%d{ISO8601} %-5p %c: %m\n");
    ConsoleAppender ca = new ConsoleAppender(pl);
    Logger.getRoot().addAppender(ca);
    Logger.getRoot().setLevel(Level.INFO);

    // create Options object
    Options options = new Options();

    // add t option
    options.addOption("r", "read", false, "read a file from the DHT");
    options.addOption("w", "write", false, "write a file to the DHT");
    options.addOption("g", "gateway", true, "the gateway IP:port");
    options.addOption("k", "key", true, "the key to read a file from");
    options.addOption("f", "file", true, "the file to read or write");
    options.addOption("s", "secret", true, "the secret used to hide data");
    options.addOption("t", "ttl", true, "how long in seconds data should persist");

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

    String gw = null;/*  w ww.j ava 2 s  . c o  m*/
    String mode = null;
    String secret = null;
    String ttl = null;
    String key = null;
    String file = null;

    if (cmd.hasOption("r")) {
        mode = "read";
    }
    if (cmd.hasOption("w")) {
        mode = "write";
    }
    if (cmd.hasOption("g")) {
        gw = cmd.getOptionValue("g");
    }
    if (cmd.hasOption("k")) {
        key = cmd.getOptionValue("k");
    }
    if (cmd.hasOption("f")) {
        file = cmd.getOptionValue("f");
    }
    if (cmd.hasOption("s")) {
        secret = cmd.getOptionValue("s");
    }
    if (cmd.hasOption("t")) {
        ttl = cmd.getOptionValue("t");
    }

    if (mode == null) {
        System.err.println("ERROR: either --read or --write is required");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fileshare", options);
        System.exit(1);
    }

    if (gw == null) {
        System.err.println("ERROR: --gateway is required");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fileshare", options);
        System.exit(1);
    }

    if (file == null) {
        System.err.println("ERROR: --file is required");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fileshare", options);
        System.exit(1);
    }

    if (secret == null) {
        System.err.println("ERROR: --secret is required");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fileshare", options);
        System.exit(1);
    }

    StringBuffer sbuf = new StringBuffer(1000);
    sbuf.append("<sandstorm>\n");
    sbuf.append("<global>\n");
    sbuf.append("<initargs>\n");
    sbuf.append("node_id localhost:3630\n");
    sbuf.append("</initargs>\n");
    sbuf.append("</global>\n");
    sbuf.append("<stages>\n");
    sbuf.append("<GatewayClient>\n");
    sbuf.append("class bamboo.dht.GatewayClient\n");
    sbuf.append("<initargs>\n");
    sbuf.append("debug_level 0\n");
    sbuf.append("gateway " + gw + "\n");
    sbuf.append("</initargs>\n");
    sbuf.append("</GatewayClient>\n");
    sbuf.append("\n");
    sbuf.append("<FileShare>\n");
    sbuf.append("class bamboo.openhash.fileshare.FileShare\n");
    sbuf.append("<initargs>\n");
    sbuf.append("debug_level 0\n");
    sbuf.append("secret " + secret + "\n");
    sbuf.append("mode " + mode + "\n");
    if (mode.equals("write")) {
        if (ttl == null) {
            System.err.println("ERROR: --ttl is required for write mode");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("fileshare", options);
            System.exit(1);
        }

        sbuf.append("ttl " + ttl + "\n");
        sbuf.append("file " + file + "\n");
    } else {
        if (key == null) {
            System.err.println("ERROR: --key is required for write mode");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("fileshare", options);
            System.exit(1);
        }

        sbuf.append("key " + key + "\n");
        sbuf.append("file " + file + "\n");
    }
    sbuf.append("client_stage_name GatewayClient\n");
    sbuf.append("</initargs>\n");
    sbuf.append("</FileShare>\n");
    sbuf.append("</stages>\n");
    sbuf.append("</sandstorm>\n");
    ASyncCore acore = new bamboo.lss.ASyncCoreImpl();
    DustDevil dd = new DustDevil();
    dd.set_acore_instance(acore);
    dd.main(new CharArrayReader(sbuf.toString().toCharArray()));
    acore.async_main();
}

From source file:com.linkedin.mlease.regression.liblinearfunc.LibLinear.java

/**
 * Command-line tool//ww w .java 2  s .  co m
 * 
 * <pre>
 * java -cp target/regression-0.1-uber.jar com.linkedin.lab.regression.LibLinear
 * </pre>
 * 
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    String cmd = "Input parameters (separated by space): \n"
            + "   run:<command>      (required) train or predict\n"
            + "   ftype:<file_type>  (required) libsvm or json\n"
            + "   data:<file_name>   (required) Input data file of the specified type\n"
            + "   out:<file_name>    (required) Output file\n"
            + "   bias:<bias>        (optional) Set to 0 if you do not want to add an\n"
            + "                                 bias/intercept term\n"
            + "                                 Set to 1 if you want to add a feature with\n"
            + "                                 value 1 to every instance\n"
            + "                                 Default: 0\n"
            + "   param:<file_name>  (optional) for run:train, it specifies the prior mean\n"
            + "                      (required) for run:predict, it specifies the model\n"
            + "                                 File format: <featureName>=<value> per line\n"
            + "   priorVar:<var>     (required) for run:train, <var> is the a number\n"
            + "                      (not used) for run:predict\n"
            + "   init:<file_name>   (optional) for run:train, it specifies the initial value\n"
            + "                                 File format: <featureName>=<value> per line\n"
            + "   posteriorVar:1/0   (optional) Whether to compute posterior variances\n"
            + "                                 Default: 1\n"
            + "   posteriorCov:1/0   (optional) Whether to compute posterior covariances\n"
            + "                                 Default: 0\n"
            + "   binaryFeature:1/0  (optional) Whether all of the input features are binary\n"
            + "   useShort:1/0       (optional) Whether to use short to store feature indices\n"
            + "   option:<options>   (optional) Comma-separated list of options\n"
            + "                                 No space is allowed in <options>\n"
            + "                                 Eg: max_iter=5,epsilon=0.01,positive_weight=2\n"
            + "                      (not used) for run:predict\n";

    if (args.length < 3) {
        System.out.println("\n" + cmd);
        System.exit(0);
    }

    // Read the input parameters
    String run = null;
    String ftype = null;
    File dataFile = null;
    File outFile = null;
    double bias = 0;
    File paramFile = null;
    File initFile = null;
    double priorVar = Double.NaN;
    String option = null;
    boolean binaryFeature = false;
    boolean useShort = false;
    boolean computePostVar = true;
    boolean computePostCov = false;

    for (int i = 0; i < args.length; i++) {
        if (args[i] == null)
            continue;
        String[] token = args[i].split(":");
        if (token.length < 2)
            cmd_line_error("'" + args[i] + "' is not a valid input parameter string!", cmd);
        for (int k = 2; k < token.length; k++)
            token[1] += ":" + token[k];
        if (token[0].equals("run")) {
            run = token[1];
        } else if (token[0].equals("ftype")) {
            ftype = token[1];
        } else if (token[0].equals("data")) {
            dataFile = new File(token[1]);
        } else if (token[0].equals("out")) {
            outFile = new File(token[1]);
        } else if (token[0].equals("bias")) {
            bias = Double.parseDouble(token[1]);
        } else if (token[0].equals("param")) {
            paramFile = new File(token[1]);
        } else if (token[0].equals("init")) {
            initFile = new File(token[1]);
        } else if (token[0].equals("priorVar")) {
            priorVar = Double.parseDouble(token[1]);
        } else if (token[0].equals("option")) {
            option = token[1];
        } else if (token[0].equals("binaryFeature")) {
            binaryFeature = Util.atob(token[1]);
        } else if (token[0].equals("useShort")) {
            useShort = Util.atob(token[1]);
        } else if (token[0].equals("posteriorVar")) {
            computePostVar = Util.atob(token[1]);
        } else if (token[0].equals("posteriorCov")) {
            computePostCov = Util.atob(token[1]);
        } else
            cmd_line_error("'" + args[i] + "' is not a valid input parameter string!", cmd);
    }

    if (run == null)
        cmd_line_error("Please specify run:<command>", cmd);
    if (ftype == null)
        cmd_line_error("Please specify ftype:<file_type>", cmd);
    if (dataFile == null)
        cmd_line_error("Please specify data:<file_name>", cmd);
    if (outFile == null)
        cmd_line_error("Please specify out:<file_name>", cmd);

    if (run.equals(RUN_TRAIN)) {

        Map<String, Double> priorMean = null;
        Map<String, Double> initParam = null;
        if (paramFile != null) {
            if (!paramFile.exists())
                cmd_line_error("Param File '" + paramFile.getPath() + "' does not exist", cmd);
            priorMean = Util.readStringDoubleMap(paramFile, "=");
        }
        if (initFile != null) {
            if (!initFile.exists())
                cmd_line_error("Init File '" + initFile.getPath() + "' does not exist", cmd);
            initParam = Util.readStringDoubleMap(initFile, "=");
        }

        if (priorVar == Double.NaN)
            cmd_line_error("Please specify priorVar:<var>", cmd);

        if (!dataFile.exists())
            cmd_line_error("Data File '" + dataFile.getPath() + "' does not exist", cmd);

        LibLinearDataset dataset;
        if (binaryFeature) {
            dataset = new LibLinearBinaryDataset(bias, useShort);
        } else {
            dataset = new LibLinearDataset(bias);
        }

        if ("libsvm".equals(ftype)) {
            dataset.readFromLibSVM(dataFile);
        }
        //else if ("json".equals(ftype))
        //{
        //  dataset.readFromJSON(dataFile);
        //}
        else
            cmd_line_error("Unknown file type 'ftype:" + ftype + "'", cmd);

        if (computePostCov == true && computePostVar == false)
            cmd_line_error("Cannot compute posterior covariances with posteriorVar:0", cmd);

        LibLinear liblinear = new LibLinear();
        liblinear.setComputeFullPostVar(computePostCov);

        liblinear.train(dataset, initParam, priorMean, null, 0.0, priorVar, option, computePostVar);

        PrintStream out = new PrintStream(outFile);
        Util.printStringDoubleMap(out, liblinear.getParamMap(), "=", true);
        out.close();

        if (computePostVar) {
            out = new PrintStream(outFile + ".var");
            Util.printStringDoubleMap(out, liblinear.getPostVarMap(), "=", true);
            out.close();
            if (computePostCov) {
                out = new PrintStream(outFile + ".cov");
                Util.printStringListDoubleMap(out, liblinear.getPostVarMatrixMap(), "=");
                out.close();
            }
        }
    } else if (run.equals(RUN_PREDICT)) {

        throw new Exception("run:predict is not supported yet :(");

    } else
        cmd_line_error("Unknown run:" + run, cmd);
}

From source file:edu.msu.cme.rdp.multicompare.Main.java

public static void main(String[] args) throws Exception {
    PrintStream hier_out = null;//ww w  .j  av a 2s .com
    PrintWriter assign_out = new PrintWriter(new NullWriter());
    PrintStream bootstrap_out = null;
    File hier_out_filename = null;
    String propFile = null;
    File biomFile = null;
    File metadataFile = null;
    PrintWriter shortseq_out = null;
    List<MCSample> samples = new ArrayList();
    ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank;
    float conf = CmdOptions.DEFAULT_CONF;
    String gene = null;
    int min_bootstrap_words = Classifier.MIN_BOOTSTRSP_WORDS;

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) {
            assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT));
        } else {
            throw new IllegalArgumentException("Require the output file for classification assignment");
        }
        if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) {
            hier_out_filename = new File(line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT));
            hier_out = new PrintStream(hier_out_filename);
        }
        if (line.hasOption(CmdOptions.BIOMFILE_SHORT_OPT)) {
            biomFile = new File(line.getOptionValue(CmdOptions.BIOMFILE_SHORT_OPT));
        }
        if (line.hasOption(CmdOptions.METADATA_SHORT_OPT)) {
            metadataFile = new File(line.getOptionValue(CmdOptions.METADATA_SHORT_OPT));
        }

        if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) {
            if (gene != null) {
                throw new IllegalArgumentException(
                        "Already specified the gene from the default location. Can not specify train_propfile");
            } else {
                propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT);
            }
        }
        if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) {
            String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT);
            if (f.equalsIgnoreCase("allrank")) {
                format = ClassificationResultFormatter.FORMAT.allRank;
            } else if (f.equalsIgnoreCase("fixrank")) {
                format = ClassificationResultFormatter.FORMAT.fixRank;
            } else if (f.equalsIgnoreCase("filterbyconf")) {
                format = ClassificationResultFormatter.FORMAT.filterbyconf;
            } else if (f.equalsIgnoreCase("db")) {
                format = ClassificationResultFormatter.FORMAT.dbformat;
            } else if (f.equalsIgnoreCase("biom")) {
                format = ClassificationResultFormatter.FORMAT.biom;
            } else {
                throw new IllegalArgumentException(
                        "Not an valid output format, only allrank, fixrank, biom, filterbyconf and db allowed");
            }
        }
        if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) {
            if (propFile != null) {
                throw new IllegalArgumentException(
                        "Already specified train_propfile. Can not specify gene any more");
            }
            gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase();

            if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) {
                throw new IllegalArgumentException(gene + " not found, choose from"
                        + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", "
                        + ClassifierFactory.FUNGALITS_warcup_GENE + ", "
                        + ClassifierFactory.FUNGALITS_unite_GENE);
            }
        }
        if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) {
            min_bootstrap_words = Integer
                    .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT));
            if (min_bootstrap_words < Classifier.MIN_BOOTSTRSP_WORDS) {
                throw new IllegalArgumentException(CmdOptions.MIN_BOOTSTRAP_WORDS_LONG_OPT
                        + " must be at least " + Classifier.MIN_BOOTSTRSP_WORDS);
            }
        }
        if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) {
            String confString = line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT);
            try {
                conf = Float.valueOf(confString);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("Confidence must be a decimal number");
            }

            if (conf < 0 || conf > 1) {
                throw new IllegalArgumentException("Confidence must be in the range [0,1]");
            }
        }
        if (line.hasOption(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)) {
            shortseq_out = new PrintWriter(line.getOptionValue(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT));
        }
        if (line.hasOption(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)) {
            bootstrap_out = new PrintStream(line.getOptionValue(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT));
        }

        if (format.equals(ClassificationResultFormatter.FORMAT.biom) && biomFile == null) {
            throw new IllegalArgumentException("biom format requires an input biom file");
        }
        if (biomFile != null) { // if input biom file provided, use biom format
            format = ClassificationResultFormatter.FORMAT.biom;
        }

        args = line.getArgs();
        for (String arg : args) {
            String[] inFileNames = arg.split(",");
            File inputFile = new File(inFileNames[0]);
            File idmappingFile = null;
            if (!inputFile.exists()) {
                throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[0] + "\"");
            }
            if (inFileNames.length == 2) {
                idmappingFile = new File(inFileNames[1]);
                if (!idmappingFile.exists()) {
                    throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[1] + "\"");
                }
            }

            MCSample nextSample = new MCSample(inputFile, idmappingFile);
            samples.add(nextSample);
        }
        if (propFile == null && gene == null) {
            gene = CmdOptions.DEFAULT_GENE;
        }
        if (samples.size() < 1) {
            throw new IllegalArgumentException("Require at least one sample files");
        }
    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(80, " [options] <samplefile>[,idmappingfile] ...", "", options, "");
        return;
    }

    MultiClassifier multiClassifier = new MultiClassifier(propFile, gene, biomFile, metadataFile);
    MultiClassifierResult result = multiClassifier.multiCompare(samples, conf, assign_out, format,
            min_bootstrap_words);
    assign_out.close();
    if (hier_out != null) {
        DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(hier_out, samples);
        result.getRoot().topDownVisit(printVisitor);
        hier_out.close();
        if (multiClassifier.hasCopyNumber()) {
            // print copy number corrected counts
            File cn_corrected_s = new File(hier_out_filename.getParentFile(),
                    "cnadjusted_" + hier_out_filename.getName());
            PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s);
            printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true);
            result.getRoot().topDownVisit(printVisitor);
            cn_corrected_hier_out.close();
        }
    }

    if (bootstrap_out != null) {
        for (MCSample sample : samples) {
            MCSamplePrintUtil.printBootstrapCountTable(bootstrap_out, sample);
        }
        bootstrap_out.close();
    }

    if (shortseq_out != null) {
        for (String id : result.getBadSequences()) {
            shortseq_out.write(id + "\n");
        }
        shortseq_out.close();
    }

}

From source file:MainServer.java

public static void main(String[] args) {
    int port = 1234;
    String filepath = "";
    String complete_path = "";
    String connection_type = "";
    String ip_address = "";
    int port_out = 0;
    int delay = 20; //20 by default

    //parse commands using getOpt (cli)
    //add Options
    Options options = new Options();

    options.addOption("p", true, "port_to_listen_on");
    options.addOption("d", true, "directory");
    options.addOption("T", false, "TCP mode");
    options.addOption("U", false, "UDP mode");
    options.addOption("s", true, "iPAddress");
    options.addOption("P", true, "port_to_connect_to");
    options.addOption("D", true, "delay");

    CommandLineParser clp = new DefaultParser();
    try {/* w ww  . j  a  va 2s  .  c  o  m*/
        CommandLine cl = clp.parse(options, args);

        //options for the server
        if (cl.hasOption("p")) {
            port = Integer.parseInt(cl.getOptionValue("p"));
        } else {
            System.err.println("No valid port selected.");
            return;
        }

        if (cl.hasOption("d")) {
            filepath = cl.getOptionValue("d");
            //if there a '/' in front, remove it to make it a valid directory
            if (filepath.substring(0, 1).equalsIgnoreCase("/")) {
                filepath = filepath.substring(1);
            }
        } else {
            System.err.println("No valid directory given.");
            return;
        }

        if (cl.hasOption("D")) {
            delay = Integer.parseInt(cl.getOptionValue("D"));
        }

        //options for the client
        if (cl.hasOption("T")) {
            connection_type = "T";
        } else if (cl.hasOption("U")) {
            connection_type = "U";
        }

        if (cl.hasOption("s")) {
            ip_address = cl.getOptionValue("s");
        }

        if (cl.hasOption("P")) {
            port_out = Integer.parseInt(cl.getOptionValue("P"));
        }

    } catch (ParseException e) {
        //TODO: handle exception
    }

    //create directory (if it doesn't already exist)
    try {
        Files.createDirectories(Paths.get(filepath));
    } catch (Exception e) {
        //TODO: handle exception
        System.err.println("Couldn't create directory");
        System.err.println(filepath);
    }

    //read in required files (create them if they dont already exist)
    try {
        Files.createFile(Paths.get(filepath + "/gossip.txt"));
        Files.createFile(Paths.get(filepath + "/peers.txt"));
    } catch (Exception e) {
        //TODO: handle exception
    }
    WriteToFiles.readFiles(filepath);

    //start the servers
    TCPServerSock tcpServer = new TCPServerSock(port, filepath, delay);
    UDPServer udpServer = new UDPServer(port, filepath);

    Thread tcpThread = new Thread(tcpServer);
    Thread udpThread = new Thread(udpServer);

    tcpThread.start();
    udpThread.start();

    //start the client
    if (!connection_type.equals("") && port_out != 0 && !ip_address.equals("")) {
        Client client = new Client(ip_address, port_out, connection_type);
        Thread clientThread = new Thread(client);
        clientThread.start();
    }

    //Start thread to forget peers
    ForgetPeer forgetPeer = new ForgetPeer(filepath + "/peers.txt", delay);
    Thread forgetPeerThread = new Thread(forgetPeer);
    forgetPeerThread.start();
}

From source file:SimpleRecorder.java

public static void main(String[] args) {

    //////////////////////////////////////////////////////
    // Object to handle the processing and sinking of the
    // data captured from the device.
    //////////////////////////////////////////////////////
    Location2Location capture;

    /////////////////////////////////////
    // Audio and video capture devices.
    ////////////////////////////////////
    CaptureDeviceInfo audioDevice = null;
    CaptureDeviceInfo videoDevice = null;

    /////////////////////////////////////////////////////////////
    // Capture device's "location" plus the name and location of
    // the destination.
    /////////////////////////////////////////////////////////////
    MediaLocator captureLocation = null;
    MediaLocator destinationLocation;/*from   w w w  .ja  va 2s  . com*/
    String destinationName = null;

    ////////////////////////////////////////////////////////////
    // Formats the Processor (in Location2Location) must match.
    ////////////////////////////////////////////////////////////
    Format[] formats = new Format[1];

    ///////////////////////////////////////////////
    // Content type for an audio or video capture.
    //////////////////////////////////////////////
    ContentDescriptor audioContainer = new ContentDescriptor(FileTypeDescriptor.WAVE);
    ContentDescriptor videoContainer = new ContentDescriptor(FileTypeDescriptor.MSVIDEO);
    ContentDescriptor container = null;

    ////////////////////////////////////////////////////////////////////
    // Duration of recording (in seconds) and period to wait afterwards
    ///////////////////////////////////////////////////////////////////
    double duration = 10;
    int waitFor = 0;

    //////////////////////////
    // Audio or video capture?
    //////////////////////////
    String selected = AUDIO;

    ////////////////////////////////////////////////////////
    // All devices that support the format in question.
    // A means of "ensuring" the program works on different
    // machines with different capture devices.
    ////////////////////////////////////////////////////////
    Vector devices;

    //////////////////////////////////////////////////////////
    // Whether to search for capture devices that support the
    // format or use the devices whos names are already
    // known to the application.
    //////////////////////////////////////////////////////////
    boolean useKnownDevices = false;

    /////////////////////////////////////////////////////////
    // Process the command-line options as to audio or video,
    // duration, and file to save to.
    /////////////////////////////////////////////////////////
    for (int i = 0; i < args.length; i++) {
        if (args[i].equals("-d")) {
            try {
                duration = (new Double(args[++i])).doubleValue();
            } catch (NumberFormatException e) {
            }
        } else if (args[i].equals("-w")) {
            try {
                waitFor = Integer.parseInt(args[++i]);
            } catch (NumberFormatException e) {
            }
        } else if (args[i].equals("-a")) {
            selected = AUDIO;
        } else if (args[i].equals("-v")) {
            selected = VIDEO;
        } else if (args[i].equals("-b")) {
            selected = BOTH;
        } else if (args[i].equals("-f")) {
            destinationName = args[++i];
        } else if (args[i].equals("-k")) {
            useKnownDevices = true;
        } else if (args[i].equals("-h")) {
            System.out.println(
                    "Call as java SimpleRecorder [-a | -v | -b] [-d duration] [-f file] [-k] [-w wait]");
            System.out.println("\t-a\tAudio\n\t-v\tVideo\n\t-b\tBoth audio and video (system dependent)");
            System.out.println("\t-d\trecording Duration (seconds)");
            System.out
                    .println("\t-f\tFile to save to\n\t-k\tuse Known device names (don't search for devices)");
            System.out.println("\t-w\tWait the specified time (seconds) before abandoning capture");
            System.out.println(
                    "Defaults: 10 seconds, audio, and captured.wav or captured.avi, 4x recording duration wait");
            System.exit(0);
        }
    }

    /////////////////////////////////////////////////////////////////
    // Perform setup for audio capture. Includes finding a suitable
    // device, obatining its MediaLocator and setting the content
    // type.
    ////////////////////////////////////////////////////////////////
    if (selected.equals(AUDIO)) {
        devices = CaptureDeviceManager.getDeviceList(AUDIO_FORMAT);
        if (devices.size() > 0 && !useKnownDevices) {
            audioDevice = (CaptureDeviceInfo) devices.elementAt(0);
        } else
            audioDevice = CaptureDeviceManager.getDevice(AUDIO_DEVICE_NAME);
        if (audioDevice == null) {
            System.out.println("Can't find suitable audio device. Exiting");
            System.exit(1);
        }
        captureLocation = audioDevice.getLocator();
        formats[0] = AUDIO_FORMAT;
        if (destinationName == null)
            destinationName = DEFAULT_AUDIO_NAME;
        container = audioContainer;
    }
    /////////////////////////////////////////////////////////////////
    // Perform setup for video capture. Includes finding a suitable
    // device, obatining its MediaLocator and setting the content
    // type.
    ////////////////////////////////////////////////////////////////
    else if (selected.equals(VIDEO)) {
        devices = CaptureDeviceManager.getDeviceList(VIDEO_FORMAT);
        if (devices.size() > 0 && !useKnownDevices)
            videoDevice = (CaptureDeviceInfo) devices.elementAt(0);
        else
            videoDevice = CaptureDeviceManager.getDevice(VIDEO_DEVICE_NAME);
        if (videoDevice == null) {
            System.out.println("Can't find suitable video device. Exiting");
            System.exit(1);
        }
        captureLocation = videoDevice.getLocator();
        formats[0] = VIDEO_FORMAT;
        if (destinationName == null)
            destinationName = DEFAULT_VIDEO_NAME;
        container = videoContainer;
    } else if (selected.equals(BOTH)) {
        captureLocation = null;
        formats = new Format[2];
        formats[0] = AUDIO_FORMAT;
        formats[1] = VIDEO_FORMAT;
        container = videoContainer;
        if (destinationName == null)
            destinationName = DEFAULT_VIDEO_NAME;
    }

    ////////////////////////////////////////////////////////////////////
    // Perform all the necessary Processor and DataSink preparation via
    // the Location2Location class.
    ////////////////////////////////////////////////////////////////////
    destinationLocation = new MediaLocator(destinationName);
    System.out.println("Configuring for capture. Please wait.");
    capture = new Location2Location(captureLocation, destinationLocation, formats, container, 1.0);

    /////////////////////////////////////////////////////////////////////////////
    // Start the recording and tell the user. Specify the length of the
    // recording. Then wait around for up to 4-times the duration of
    // recording
    // (can take longer to sink/write the data so should wait a bit incase).
    /////////////////////////////////////////////////////////////////////////////
    System.out.println("Started recording " + duration + " seconds of " + selected + " ...");
    capture.setStopTime(new Time(duration));
    if (waitFor == 0)
        waitFor = (int) (4000 * duration);
    else
        waitFor *= 1000;
    int waited = capture.transfer(waitFor);

    /////////////////////////////////////////////////////////
    // Report on the success (or otherwise) of the recording.
    /////////////////////////////////////////////////////////
    int state = capture.getState();
    if (state == Location2Location.FINISHED)
        System.out.println(selected + " capture successful in approximately " + ((int) ((waited + 500) / 1000))
                + " seconds. Data written to " + destinationName);
    else if (state == Location2Location.FAILED)
        System.out.println(selected + " capture failed after approximately " + ((int) ((waited + 500) / 1000))
                + " seconds");
    else {
        System.out.println(selected + " capture still ongoing after approximately "
                + ((int) ((waited + 500) / 1000)) + " seconds");
        System.out.println("Process likely to have failed");
    }

    System.exit(0);
}

From source file:edu.msu.cme.rdp.classifier.comparison.ComparisonCmd.java

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

    String queryFile1 = null;/*from   ww  w .j  av  a2s . c o  m*/
    String queryFile2 = null;
    String class_outputFile = null;
    String compare_outputFile = null;
    String propFile = null;
    ClassificationResultFormatter.FORMAT format = CmdOptions.DEFAULT_FORMAT;
    float conf_cutoff = CmdOptions.DEFAULT_CONF;
    String gene = null;

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption(QUERYFILE1_SHORT_OPT)) {
            queryFile1 = line.getOptionValue(QUERYFILE1_SHORT_OPT);
        } else {
            throw new Exception("queryFile1 must be specified");
        }
        if (line.hasOption(QUERYFILE2_SHORT_OPT)) {
            queryFile2 = line.getOptionValue(QUERYFILE2_SHORT_OPT);
        } else {
            throw new Exception("queryFile2 must be specified");
        }

        if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) {
            class_outputFile = line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT);
        } else {
            throw new Exception("outputFile for classification results must be specified");
        }

        if (line.hasOption(COMPARE_OUTFILE_SHORT_OPT)) {
            compare_outputFile = line.getOptionValue(COMPARE_OUTFILE_SHORT_OPT);
        } else {
            throw new Exception("outputFile for comparsion results must be specified");
        }

        if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) {
            if (gene != null) {
                throw new IllegalArgumentException(
                        "Already specified the gene from the default location. Can not specify train_propfile");
            } else {
                propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT);
            }
        }
        if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) {
            conf_cutoff = Float.parseFloat(line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT));
        }
        if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) {
            String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT);
            if (f.equalsIgnoreCase("allrank")) {
                format = ClassificationResultFormatter.FORMAT.allRank;
            } else if (f.equalsIgnoreCase("fixrank")) {
                format = ClassificationResultFormatter.FORMAT.fixRank;
            } else if (f.equalsIgnoreCase("filterbyconf")) {
                format = ClassificationResultFormatter.FORMAT.filterbyconf;
            } else if (f.equalsIgnoreCase("db")) {
                format = ClassificationResultFormatter.FORMAT.dbformat;
            } else {
                throw new IllegalArgumentException(
                        "Not valid output format, only allrank, fixrank, filterbyconf and db allowed");
            }

        }
        if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) {
            if (propFile != null) {
                throw new IllegalArgumentException(
                        "Already specified train_propfile. Can not specify gene any more");
            }
            gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase();

            if (!gene.equals(ClassifierFactory.RRNA_16S_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALLSU_GENE)) {
                throw new IllegalArgumentException(gene + " is NOT valid, only allows "
                        + ClassifierFactory.RRNA_16S_GENE + " and " + ClassifierFactory.FUNGALLSU_GENE);
            }
        }
    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(120, "ComparisonCmd", "", options, "", true);
        return;
    }

    if (propFile == null && gene == null) {
        gene = ClassifierFactory.RRNA_16S_GENE;
    }

    ComparisonCmd cmd = new ComparisonCmd(propFile, gene);
    cmd.setConfidenceCutoff(conf_cutoff);
    printLicense();

    cmd.doClassify(queryFile1, queryFile2, class_outputFile, compare_outputFile, format);

}

From source file:edu.msu.cme.rdp.multicompare.Reprocess.java

/**
 * This class reprocesses the classification results (allrank output) and print out hierarchy output file, based on the confidence cutoff;
 * and print out only the detail classification results with assignment at certain rank with confidence above the cutoff or/and matching a given taxon.
 * @param args/*from w w  w.j  av  a 2 s  .  com*/
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {

    PrintWriter assign_out = new PrintWriter(new NullWriter());
    float conf = 0.8f;
    PrintStream heir_out = null;
    String hier_out_filename = null;
    ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank;
    String rank = null;
    String taxonFilterFile = null;
    String train_propfile = null;
    String gene = null;
    List<MCSample> samples = new ArrayList();

    try {
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) {
            hier_out_filename = line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT);
            heir_out = new PrintStream(hier_out_filename);
        } else {
            throw new Exception(
                    "It make sense to provide output filename for " + CmdOptions.HIER_OUTFILE_LONG_OPT);
        }
        if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) {
            assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT));
        }

        if (line.hasOption(CmdOptions.RANK_SHORT_OPT)) {
            rank = line.getOptionValue(CmdOptions.RANK_SHORT_OPT);
        }
        if (line.hasOption(CmdOptions.TAXON_SHORT_OPT)) {
            taxonFilterFile = line.getOptionValue(CmdOptions.TAXON_SHORT_OPT);
        }

        if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) {
            conf = Float.parseFloat(line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT));
            if (conf < 0 || conf > 1) {
                throw new IllegalArgumentException("Confidence must be in the range [0,1]");
            }
        }
        if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) {
            String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT);
            if (f.equalsIgnoreCase("allrank")) {
                format = ClassificationResultFormatter.FORMAT.allRank;
            } else if (f.equalsIgnoreCase("fixrank")) {
                format = ClassificationResultFormatter.FORMAT.fixRank;
            } else if (f.equalsIgnoreCase("db")) {
                format = ClassificationResultFormatter.FORMAT.dbformat;
            } else if (f.equalsIgnoreCase("filterbyconf")) {
                format = ClassificationResultFormatter.FORMAT.filterbyconf;
            } else {
                throw new IllegalArgumentException(
                        "Not valid output format, only allrank, fixrank, filterbyconf and db allowed");
            }
        }
        if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) {
            if (gene != null) {
                throw new IllegalArgumentException(
                        "Already specified the gene from the default location. Can not specify train_propfile");
            } else {
                train_propfile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT);
            }
        }
        if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) {
            if (train_propfile != null) {
                throw new IllegalArgumentException(
                        "Already specified train_propfile. Can not specify gene any more");
            }
            gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase();

            if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) {
                throw new IllegalArgumentException(gene + " is NOT valid, only allows "
                        + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", "
                        + ClassifierFactory.FUNGALITS_warcup_GENE + " and "
                        + ClassifierFactory.FUNGALITS_unite_GENE);
            }
        }
        args = line.getArgs();
        if (args.length < 1) {
            throw new Exception("Incorrect number of command line arguments");
        }

        for (String arg : args) {
            String[] inFileNames = arg.split(",");
            String inputFile = inFileNames[0];
            File idmappingFile = null;

            if (inFileNames.length == 2) {
                idmappingFile = new File(inFileNames[1]);
                if (!idmappingFile.exists()) {
                    System.err.println("Failed to find input file \"" + inFileNames[1] + "\"");
                    return;
                }
            }

            MCSample nextSample = new MCSampleResult(inputFile, idmappingFile);
            samples.add(nextSample);

        }
    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(120,
                "Reprocess [options] <Classification_allrank_result>[,idmappingfile] ...", "", options, "");
        return;
    }

    if (train_propfile == null && gene == null) {
        gene = ClassifierFactory.RRNA_16S_GENE;
    }

    HashSet<String> taxonFilter = null;
    if (taxonFilterFile != null) {
        taxonFilter = readTaxonFilterFile(taxonFilterFile);
    }

    MultiClassifier multiClassifier = new MultiClassifier(train_propfile, gene);
    DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(heir_out, samples);
    MultiClassifierResult result = multiClassifier.multiClassificationParser(samples, conf, assign_out, format,
            rank, taxonFilter);

    result.getRoot().topDownVisit(printVisitor);

    assign_out.close();
    heir_out.close();
    if (multiClassifier.hasCopyNumber()) {
        // print copy number corrected counts
        File cn_corrected_s = new File(new File(hier_out_filename).getParentFile(),
                "cncorrected_" + hier_out_filename);
        PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s);
        printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true);
        result.getRoot().topDownVisit(printVisitor);
        cn_corrected_hier_out.close();
    }

}

From source file:com.netscape.cmstools.CRMFPopClient.java

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

    Options options = createOptions();/*from w  w w .  j  a v  a 2  s  .  c  o m*/
    CommandLine cmd = null;

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

    } catch (Exception e) {
        printError(e.getMessage());
        System.exit(1);
    }

    if (cmd.hasOption("help")) {
        printHelp();
        System.exit(0);
    }

    boolean verbose = cmd.hasOption("v");

    String databaseDir = cmd.getOptionValue("d", ".");
    String tokenPassword = cmd.getOptionValue("p");
    String tokenName = cmd.getOptionValue("h");

    String algorithm = cmd.getOptionValue("a", "rsa");
    int keySize = Integer.parseInt(cmd.getOptionValue("l", "2048"));

    String profileID = cmd.getOptionValue("f");
    String subjectDN = cmd.getOptionValue("n");
    boolean encodingEnabled = Boolean.parseBoolean(cmd.getOptionValue("k", "false"));

    // if transportCertFilename is not specified then assume no key archival
    String transportCertFilename = cmd.getOptionValue("b");

    String popOption = cmd.getOptionValue("q", "POP_SUCCESS");

    String curve = cmd.getOptionValue("c", "nistp256");
    boolean sslECDH = Boolean.parseBoolean(cmd.getOptionValue("x", "false"));
    boolean temporary = Boolean.parseBoolean(cmd.getOptionValue("t", "true"));
    int sensitive = Integer.parseInt(cmd.getOptionValue("s", "-1"));
    int extractable = Integer.parseInt(cmd.getOptionValue("e", "-1"));

    boolean self_sign = cmd.hasOption("y");

    // get the keywrap algorithm
    KeyWrapAlgorithm keyWrapAlgorithm = null;
    String kwAlg = KeyWrapAlgorithm.AES_KEY_WRAP_PAD.toString();
    if (cmd.hasOption("w")) {
        kwAlg = cmd.getOptionValue("w");
    } else {
        String alg = System.getenv("KEY_ARCHIVAL_KEYWRAP_ALGORITHM");
        if (alg != null) {
            kwAlg = alg;
        }
    }

    String output = cmd.getOptionValue("o");

    String hostPort = cmd.getOptionValue("m");
    String username = cmd.getOptionValue("u");
    String requestor = cmd.getOptionValue("r");

    if (hostPort != null) {
        if (cmd.hasOption("w")) {
            printError("Any value specified for the key wrap parameter (-w) "
                    + "will be overriden.  CRMFPopClient will contact the "
                    + "CA to determine the supported algorithm when " + "hostport is specified");
        }
    }

    if (subjectDN == null) {
        printError("Missing subject DN");
        System.exit(1);
    }

    if (tokenPassword == null) {
        printError("Missing token password");
        System.exit(1);
    }

    if (algorithm.equals("rsa")) {
        if (cmd.hasOption("c")) {
            printError("Illegal parameter for RSA: -c");
            System.exit(1);
        }

        if (cmd.hasOption("t")) {
            printError("Illegal parameter for RSA: -t");
            System.exit(1);
        }

        if (cmd.hasOption("s")) {
            printError("Illegal parameter for RSA: -s");
            System.exit(1);
        }

        if (cmd.hasOption("e")) {
            printError("Illegal parameter for RSA: -e");
            System.exit(1);
        }

        if (cmd.hasOption("x")) {
            printError("Illegal parameter for RSA: -x");
            System.exit(1);
        }

    } else if (algorithm.equals("ec")) {
        if (cmd.hasOption("l")) {
            printError("Illegal parameter for ECC: -l");
            System.exit(1);
        }

        if (sensitive != 0 && sensitive != 1 && sensitive != -1) {
            printError("Illegal input parameters for -s: " + sensitive);
            System.exit(1);
        }

        if (extractable != 0 && extractable != 1 && extractable != -1) {
            printError("Illegal input parameters for -e: " + extractable);
            System.exit(1);
        }

    } else {
        printError("Invalid algorithm: " + algorithm);
        System.exit(1);
    }

    if (!popOption.equals("POP_SUCCESS") && !popOption.equals("POP_FAIL") && !popOption.equals("POP_NONE")) {
        printError("Invalid POP option: " + popOption);
        System.exit(1);
    }

    if (profileID == null) {
        if (algorithm.equals("rsa")) {
            profileID = "caEncUserCert";

        } else if (algorithm.equals("ec")) {
            profileID = "caEncECUserCert";

        } else {
            throw new Exception("Unknown algorithm: " + algorithm);
        }
    }

    try {
        if (verbose)
            System.out.println("Initializing security database: " + databaseDir);
        CryptoManager.initialize(databaseDir);

        CryptoManager manager = CryptoManager.getInstance();

        CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName);
        tokenName = token.getName();
        manager.setThreadToken(token);

        Password password = new Password(tokenPassword.toCharArray());
        try {
            token.login(password);
        } catch (Exception e) {
            throw new Exception("Unable to login: " + e, e);
        }

        CRMFPopClient client = new CRMFPopClient();
        client.setVerbose(verbose);

        String encoded = null;
        X509Certificate transportCert = null;
        if (transportCertFilename != null) {
            if (verbose)
                System.out.println("archival option enabled");
            if (verbose)
                System.out.println("Loading transport certificate");
            encoded = new String(Files.readAllBytes(Paths.get(transportCertFilename)));
            byte[] transportCertData = Cert.parseCertificate(encoded);
            transportCert = manager.importCACertPackage(transportCertData);
        } else {
            if (verbose)
                System.out.println("archival option not enabled");
        }

        if (verbose)
            System.out.println("Parsing subject DN");
        Name subject = client.createName(subjectDN, encodingEnabled);

        if (subject == null) {
            subject = new Name();
            subject.addCommonName("Me");
            subject.addCountryName("US");
            subject.addElement(
                    new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString("MyUid")));
        }

        if (verbose)
            System.out.println("Generating key pair");
        KeyPair keyPair;
        if (algorithm.equals("rsa")) {
            keyPair = CryptoUtil.generateRSAKeyPair(token, keySize);
        } else if (algorithm.equals("ec")) {
            keyPair = client.generateECCKeyPair(token, curve, sslECDH, temporary, sensitive, extractable);

        } else {
            throw new Exception("Unknown algorithm: " + algorithm);
        }

        // print out keyid to be used in cmc decryptPOP
        PrivateKey privateKey = (PrivateKey) keyPair.getPrivate();
        @SuppressWarnings("deprecation")
        byte id[] = privateKey.getUniqueID();
        String kid = CryptoUtil.encodeKeyID(id);
        System.out.println("Keypair private key id: " + kid);

        if ((transportCert != null) && (hostPort != null)) {
            // check the CA for the required key wrap algorithm
            // if found, override whatever has been set by the command line
            // options for the key wrap algorithm

            ClientConfig config = new ClientConfig();
            String host = hostPort.substring(0, hostPort.indexOf(':'));
            int port = Integer.parseInt(hostPort.substring(hostPort.indexOf(':') + 1));
            config.setServerURL("http", host, port);

            PKIClient pkiclient = new PKIClient(config);
            kwAlg = getKeyWrapAlgotihm(pkiclient);
        }

        if (verbose && (transportCert != null))
            System.out.println("Using key wrap algorithm: " + kwAlg);
        if (transportCert != null) {
            keyWrapAlgorithm = KeyWrapAlgorithm.fromString(kwAlg);
        }

        if (verbose)
            System.out.println("Creating certificate request");
        CertRequest certRequest = client.createCertRequest(self_sign, token, transportCert, algorithm, keyPair,
                subject, keyWrapAlgorithm);

        ProofOfPossession pop = null;

        if (!popOption.equals("POP_NONE")) {

            if (verbose)
                System.out.println("Creating signer");
            Signature signer = client.createSigner(token, algorithm, keyPair);

            if (popOption.equals("POP_SUCCESS")) {

                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                certRequest.encode(bo);
                signer.update(bo.toByteArray());

            } else if (popOption.equals("POP_FAIL")) {

                byte[] data = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };

                signer.update(data);
            }

            byte[] signature = signer.sign();

            if (verbose)
                System.out.println("Creating POP");
            pop = client.createPop(algorithm, signature);
        }

        if (verbose)
            System.out.println("Creating CRMF request");
        String request = client.createCRMFRequest(certRequest, pop);

        StringWriter sw = new StringWriter();
        try (PrintWriter out = new PrintWriter(sw)) {
            out.println(Cert.REQUEST_HEADER);
            out.print(request);
            out.println(Cert.REQUEST_FOOTER);
        }
        String csr = sw.toString();

        if (hostPort != null) {
            System.out.println("Submitting CRMF request to " + hostPort);
            client.submitRequest(request, hostPort, username, profileID, requestor);

        } else if (output != null) {
            System.out.println("Storing CRMF request into " + output);
            try (FileWriter out = new FileWriter(output)) {
                out.write(csr);
            }

        } else {
            System.out.println(csr);
        }

    } catch (Exception e) {
        if (verbose)
            e.printStackTrace();
        printError(e.getMessage());
        System.exit(1);
    }
}

From source file:com.act.lcms.db.io.PrintConstructInfo.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//from  w w  w.jav  a 2 s  . c  o  m
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        System.out.print("Loading/updating LCMS scan files into DB\n");
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);

        String construct = cl.getOptionValue(OPTION_CONSTRUCT);
        List<LCMSWell> lcmsWells = LCMSWell.getInstance().getByConstructID(db, construct);
        Collections.sort(lcmsWells, new Comparator<LCMSWell>() {
            @Override
            public int compare(LCMSWell o1, LCMSWell o2) {
                return o1.getId().compareTo(o2.getId());
            }
        });

        Set<String> uniqueMSIDs = new HashSet<>();
        Map<Integer, Plate> platesById = new HashMap<>();

        System.out.format("\n\n-- Construct %s --\n\n", construct);

        List<ChemicalAssociatedWithPathway> pathwayChems = ChemicalAssociatedWithPathway.getInstance()
                .getChemicalsAssociatedWithPathwayByConstructId(db, construct);
        System.out.print("Chemicals associated with pathway:\n");
        System.out.format("  %-8s%-15s%-45s\n", "index", "kind", "chemical");
        for (ChemicalAssociatedWithPathway chem : pathwayChems) {
            System.out.format("  %-8d%-15s%-45s\n", chem.getIndex(), chem.getKind(), chem.getChemical());
        }

        System.out.print("\nLCMS wells:\n");
        System.out.format("  %-15s%-6s%-15s%-15s%-15s\n", "barcode", "well", "msid", "fed", "lcms_count");
        for (LCMSWell well : lcmsWells) {
            uniqueMSIDs.add(well.getMsid());

            Plate p = platesById.get(well.getPlateId());
            if (p == null) {
                // TODO: migrate Plate to be a subclass of BaseDBModel.
                p = Plate.getPlateById(db, well.getPlateId());
                platesById.put(p.getId(), p);
            }

            String chem = well.getChemical();
            List<ScanFile> scanFiles = ScanFile.getScanFileByPlateIDRowAndColumn(db, p.getId(),
                    well.getPlateRow(), well.getPlateColumn());

            System.out.format("  %-15s%-6s%-15s%-15s%-15d\n", p.getBarcode(), well.getCoordinatesString(),
                    well.getMsid(), chem == null || chem.isEmpty() ? "--" : chem, scanFiles.size());
            System.out.flush();
        }

        List<Integer> plateIds = Arrays.asList(platesById.keySet().toArray(new Integer[platesById.size()]));
        Collections.sort(plateIds);
        System.out.print("\nAppears in plates:\n");
        for (Integer id : plateIds) {
            Plate p = platesById.get(id);
            System.out.format("  %s: %s\n", p.getBarcode(), p.getName());
        }

        List<String> msids = Arrays.asList(uniqueMSIDs.toArray(new String[uniqueMSIDs.size()]));
        Collections.sort(msids);
        System.out.format("\nMSIDS: %s\n", StringUtils.join(msids, ", "));

        Set<String> availableNegativeControls = new HashSet<>();
        for (Map.Entry<Integer, Plate> entry : platesById.entrySet()) {
            List<LCMSWell> wells = LCMSWell.getInstance().getByPlateId(db, entry.getKey());
            for (LCMSWell well : wells) {
                if (!construct.equals(well.getComposition())) {
                    availableNegativeControls.add(well.getComposition());
                }
            }
        }

        // Print available standards for each step w/ plate barcodes and coordinates.
        System.out.format("\nAvailable Standards:\n");
        Map<Integer, Plate> plateCache = new HashMap<>();
        for (ChemicalAssociatedWithPathway chem : pathwayChems) {
            List<StandardWell> matchingWells = StandardWell.getInstance().getStandardWellsByChemical(db,
                    chem.getChemical());
            for (StandardWell well : matchingWells) {
                if (!plateCache.containsKey(well.getPlateId())) {
                    Plate p = Plate.getPlateById(db, well.getPlateId());
                    plateCache.put(p.getId(), p);
                }
            }
            Map<Integer, List<StandardWell>> standardWellsByPlateId = new HashMap<>();
            for (StandardWell well : matchingWells) {
                List<StandardWell> plateWells = standardWellsByPlateId.get(well.getPlateId());
                if (plateWells == null) {
                    plateWells = new ArrayList<>();
                    standardWellsByPlateId.put(well.getPlateId(), plateWells);
                }
                plateWells.add(well);
            }
            List<Pair<String, Integer>> plateBarcodes = new ArrayList<>(plateCache.size());
            for (Plate p : plateCache.values()) {
                if (p.getBarcode() == null) {
                    plateBarcodes.add(Pair.of("(no barcode)", p.getId()));
                } else {
                    plateBarcodes.add(Pair.of(p.getBarcode(), p.getId()));
                }
            }
            Collections.sort(plateBarcodes);
            System.out.format("  %s:\n", chem.getChemical());
            for (Pair<String, Integer> barcodePair : plateBarcodes) {
                // TODO: hoist this whole sorting/translation step into a utility class.
                List<StandardWell> wells = standardWellsByPlateId.get(barcodePair.getRight());
                if (wells == null) {
                    // Don't print plates that don't apply to this chemical, which can happen because we're caching the plates.
                    continue;
                }
                Collections.sort(wells, new Comparator<StandardWell>() {
                    @Override
                    public int compare(StandardWell o1, StandardWell o2) {
                        int c = o1.getPlateRow().compareTo(o2.getPlateRow());
                        if (c != 0)
                            return c;
                        return o1.getPlateColumn().compareTo(o2.getPlateColumn());
                    }
                });
                List<String> descriptions = new ArrayList<>(wells.size());
                for (StandardWell well : wells) {
                    descriptions.add(String.format("%s in %s%s", well.getCoordinatesString(), well.getMedia(),
                            well.getConcentration() == null ? ""
                                    : String.format(" c. %f", well.getConcentration())));
                }
                System.out.format("    %s: %s\n", barcodePair.getLeft(), StringUtils.join(descriptions, ", "));
            }
        }

        List<String> negativeControlStrains = Arrays
                .asList(availableNegativeControls.toArray(new String[availableNegativeControls.size()]));
        Collections.sort(negativeControlStrains);
        System.out.format("\nAvailable negative controls: %s\n", StringUtils.join(negativeControlStrains, ","));
        System.out.print("\n----------\n");
        System.out.print("\n\n");
    }
}

From source file:ch.kostceco.tools.kostval.KOSTVal.java

/** Die Eingabe besteht aus 2 oder 3 Parameter: [0] Validierungstyp [1] Pfad zur Val-File [2]
 * option: Verbose/*from  ww w. j  a v  a  2  s  . c  om*/
 * 
 * @param args
 * @throws IOException */

@SuppressWarnings("unused")
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);

    /* TODO: siehe Bemerkung im applicationContext-services.xml bezglich Injection in der
     * Superklasse aller Impl-Klassen ValidationModuleImpl validationModuleImpl =
     * (ValidationModuleImpl) context.getBean("validationmoduleimpl"); */

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

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

    File directoryOfLogfile = new File(pathToLogfile);

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

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

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

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

    File valDatei = new File(args[1]);
    File logDatei = null;
    logDatei = valDatei;

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

    // Informationen holen, welche Formate validiert werden sollen
    String pdfaValidation = kostval.getConfigurationService().pdfaValidation();
    String siardValidation = kostval.getConfigurationService().siardValidation();
    String tiffValidation = kostval.getConfigurationService().tiffValidation();
    String jp2Validation = kostval.getConfigurationService().jp2Validation();

    // 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...

    String formatValOn = "";
    // ermitteln welche Formate validiert werden knnen respektive eingeschaltet sind
    if (pdfaValidation.equals("yes")) {
        formatValOn = "PDF/A";
        if (tiffValidation.equals("yes")) {
            formatValOn = formatValOn + ", TIFF";
        }
        if (jp2Validation.equals("yes")) {
            formatValOn = formatValOn + ", JP2";
        }
        if (siardValidation.equals("yes")) {
            formatValOn = formatValOn + ", SIARD";
        }
    } else if (tiffValidation.equals("yes")) {
        formatValOn = "TIFF";
        if (jp2Validation.equals("yes")) {
            formatValOn = formatValOn + ", JP2";
        }
        if (siardValidation.equals("yes")) {
            formatValOn = formatValOn + ", SIARD";
        }
    } else if (jp2Validation.equals("yes")) {
        formatValOn = "JP2";
        if (siardValidation.equals("yes")) {
            formatValOn = formatValOn + ", SIARD";
        }
    } else if (siardValidation.equals("yes")) {
        formatValOn = "SIARD";
    }

    LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_HEADER));
    LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_START, ausgabeStart));
    LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_END));
    LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMATON, formatValOn));
    LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_INFO));
    System.out.println("KOST-Val");
    System.out.println("");

    if (args[0].equals("--format") && formatValOn.equals("")) {
        // Formatvalidierung aber alle Formate ausgeschlossen
        LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                kostval.getTextResourceService().getText(ERROR_NOFILEENDINGS)));
        System.out.println(kostval.getTextResourceService().getText(ERROR_NOFILEENDINGS));
        System.exit(1);
    }

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

    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(kostval.getTextResourceService().getText(ERROR_IOE,
                        kostval.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS, pathToWorkDir)));
                System.out.println(
                        kostval.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS, pathToWorkDir));
                System.exit(1);
            }
        }
    }

    // Im Pfad keine Sonderzeichen xml-Validierung SIP 1d und SIARD C strzen ab

    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(kostval.getTextResourceService().getText(ERROR_IOE,
                    kostval.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)));
            System.out.println(kostval.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(kostval.getTextResourceService().getText(ERROR_IOE,
                kostval.getTextResourceService().getText(ERROR_WRONG_JRE)));
        System.out.println(kostval.getTextResourceService().getText(ERROR_WRONG_JRE));
        System.exit(1);
    }

    // bestehendes Workverzeichnis wieder anlegen
    if (!tmpDir.exists()) {
        tmpDir.mkdir();
    }

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

    /* Vorberitung fr eine allfllige Festhaltung bei unterschiedlichen PDFA-Validierungsresultaten
     * in einer PDF_Diagnosedatei sowie Zhler der SIP-Dateiformate */
    String diaPath = kostval.getConfigurationService().getPathToDiagnose();

    // Im diaverzeichnis besteht kein Schreibrecht
    File diaDir = new File(diaPath);

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

    if (!diaDir.canWrite()) {
        LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                kostval.getTextResourceService().getText(ERROR_DIADIRECTORY_NOTWRITABLE, diaDir)));
        System.out.println(kostval.getTextResourceService().getText(ERROR_DIADIRECTORY_NOTWRITABLE, diaDir));
        System.exit(1);
    }

    File xmlDiaOrig = new File("resources" + File.separator + "KaD-Diagnosedaten.kost-val.xml");
    File xmlDiaCopy = new File(diaPath + File.separator + "KaD-Diagnosedaten.kost-val.xml");
    if (!xmlDiaCopy.exists()) {
        Util.copyFile(xmlDiaOrig, xmlDiaCopy);
    }
    File xslDiaOrig = new File("resources" + File.separator + "kost-val_KaDdia.xsl");
    File xslDiaCopy = new File(diaPath + File.separator + "kost-val_KaDdia.xsl");
    if (!xslDiaCopy.exists()) {
        Util.copyFile(xslDiaOrig, xslDiaCopy);
    }

    /* Ueberprfung des optionalen Parameters (2 -v --> im Verbose-mode werden die originalen Logs
     * nicht gelscht (PDFTron, Jhove & Co.) */
    boolean verbose = false;
    if (args.length > 2) {
        if (!(args[2].equals("-v"))) {
            LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                    kostval.getTextResourceService().getText(ERROR_PARAMETER_OPTIONAL_1)));
            System.out.println(kostval.getTextResourceService().getText(ERROR_PARAMETER_OPTIONAL_1));
            System.exit(1);
        } else {
            verbose = true;
        }
    }

    /* Initialisierung TIFF-Modul B (JHove-Validierung) berprfen der Konfiguration: existiert die
     * jhove.conf am angebenen Ort? */
    String jhoveConf = kostval.getConfigurationService().getPathToJhoveConfiguration();
    File fJhoveConf = new File(jhoveConf);
    if (!fJhoveConf.exists() || !fJhoveConf.getName().equals("jhove.conf")) {

        LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                kostval.getTextResourceService().getText(ERROR_JHOVECONF_MISSING)));
        System.out.println(kostval.getTextResourceService().getText(ERROR_JHOVECONF_MISSING));
        System.exit(1);
    }

    // Im Pfad keine Sonderzeichen xml-Validierung SIP 1d und SIARD C strzen ab

    name = valDatei.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(kostval.getTextResourceService().getText(ERROR_IOE,
                    kostval.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)));
            System.out.println(kostval.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name));
            System.exit(1);
        }
    }

    // Ueberprfung des Parameters (Val-Datei): existiert die Datei?
    if (!valDatei.exists()) {
        LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                kostval.getTextResourceService().getText(ERROR_VALFILE_FILENOTEXISTING)));
        System.out.println(kostval.getTextResourceService().getText(ERROR_VALFILE_FILENOTEXISTING));
        System.exit(1);
    }

    if (args[0].equals("--format")) {
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT1));
        Integer countNio = 0;
        Integer countSummaryNio = 0;
        Integer count = 0;
        Integer pdfaCountIo = 0;
        Integer pdfaCountNio = 0;
        Integer siardCountIo = 0;
        Integer siardCountNio = 0;
        Integer tiffCountIo = 0;
        Integer tiffCountNio = 0;
        Integer jp2CountIo = 0;
        Integer jp2CountNio = 0;

        // TODO: Formatvalidierung an einer Datei --> erledigt --> nur Marker
        if (!valDatei.isDirectory()) {

            boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

            LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2));

            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }

            LOGGER.logError(kostval.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 = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER);
                String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>";
                Util.oldnewstring(oldstring, newstring, logFile);

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

            if (valFile) {
                // 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: Formatvalidierung ber ein Ordner --> erledigt --> nur Marker
            Map<String, File> fileMap = Util.getFileMap(valDatei, false);
            Set<String> fileMapKeys = fileMap.keySet();

            for (Iterator<String> iterator = fileMapKeys.iterator(); iterator.hasNext();) {
                String entryName = iterator.next();
                File newFile = fileMap.get(entryName);
                if (!newFile.isDirectory()) {
                    valDatei = newFile;
                    count = count + 1;

                    // Ausgabe Dateizhler Ersichtlich das KOST-Val Dateien durchsucht
                    System.out.print(count + "   ");
                    System.out.print("\r");

                    if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".jp2")))
                            && jp2Validation.equals("yes")) {

                        boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                        // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                        if (tmpDir.exists()) {
                            Util.deleteDir(tmpDir);
                        }
                        if (valFile) {
                            jp2CountIo = jp2CountIo + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        } else {
                            jp2CountNio = jp2CountNio + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        }
                    } else if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".tiff")
                            || valDatei.getAbsolutePath().toLowerCase().endsWith(".tif")))
                            && tiffValidation.equals("yes")) {

                        boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                        // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                        if (tmpDir.exists()) {
                            Util.deleteDir(tmpDir);
                        }
                        if (valFile) {
                            tiffCountIo = tiffCountIo + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        } else {
                            tiffCountNio = tiffCountNio + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        }
                    } else if ((valDatei.getAbsolutePath().toLowerCase().endsWith(".siard"))
                            && siardValidation.equals("yes")) {

                        boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                        // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                        if (tmpDir.exists()) {
                            Util.deleteDir(tmpDir);
                        }
                        if (valFile) {
                            siardCountIo = siardCountIo + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        } else {
                            siardCountNio = siardCountNio + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        }

                    } else if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".pdf")
                            || valDatei.getAbsolutePath().toLowerCase().endsWith(".pdfa")))
                            && pdfaValidation.equals("yes")) {

                        boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                        // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                        if (tmpDir.exists()) {
                            Util.deleteDir(tmpDir);
                        }
                        if (valFile) {
                            pdfaCountIo = pdfaCountIo + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        } else {
                            pdfaCountNio = pdfaCountNio + 1;
                            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
                            if (tmpDir.exists()) {
                                Util.deleteDir(tmpDir);
                            }
                        }

                    } else {
                        countNio = countNio + 1;
                    }
                }
            }

            System.out.print("                   ");
            System.out.print("\r");

            if (countNio.equals(count)) {
                // keine Dateien Validiert
                LOGGER.logError(
                        kostval.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS, formatValOn));
                System.out.println(
                        kostval.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS, formatValOn));
            }

            LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2));

            LOGGER.logError(kostval.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 = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER);
                String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>";
                Util.oldnewstring(oldstring, newstring, logFile);

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

            countSummaryNio = pdfaCountNio + siardCountNio + tiffCountNio + jp2CountNio;

            if (countNio.equals(count)) {
                // keine Dateien Validiert bestehendes Workverzeichnis ggf. lschen
                if (tmpDir.exists()) {
                    Util.deleteDir(tmpDir);
                }
                System.exit(1);
            } else if (countSummaryNio == 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();
            }
        }
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2));

    } else if (args[0].equals("--sip")) {
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT1));

        // TODO: Sipvalidierung --> erledigt --> nur Marker
        boolean validFormat = false;
        File originalSipFile = valDatei;
        File unSipFile = valDatei;
        File outputFile3c = null;
        String fileName3c = null;
        File tmpDirZip = null;

        // zuerst eine Formatvalidierung ber den Content dies ist analog aufgebaut wie --format
        Integer countNio = 0;
        Integer countSummaryNio = 0;
        Integer countSummaryIo = 0;
        Integer count = 0;
        Integer pdfaCountIo = 0;
        Integer pdfaCountNio = 0;
        Integer siardCountIo = 0;
        Integer siardCountNio = 0;
        Integer tiffCountIo = 0;
        Integer tiffCountNio = 0;
        Integer jp2CountIo = 0;
        Integer jp2CountNio = 0;

        if (!valDatei.isDirectory()) {
            Boolean zip = false;
            // Eine ZIP Datei muss mit PK.. beginnen
            if ((valDatei.getAbsolutePath().toLowerCase().endsWith(".zip")
                    || valDatei.getAbsolutePath().toLowerCase().endsWith(".zip64"))) {

                FileReader fr = null;

                try {
                    fr = new FileReader(valDatei);
                    BufferedReader read = new BufferedReader(fr);

                    // Hex 03 in Char umwandeln
                    String str3 = "03";
                    int i3 = Integer.parseInt(str3, 16);
                    char c3 = (char) i3;
                    // Hex 04 in Char umwandeln
                    String str4 = "04";
                    int i4 = Integer.parseInt(str4, 16);
                    char c4 = (char) i4;

                    // auslesen der ersten 4 Zeichen der Datei
                    int length;
                    int i;
                    char[] buffer = new char[4];
                    length = read.read(buffer);
                    for (i = 0; i != length; i++)
                        ;

                    // die beiden charArrays (soll und ist) mit einander vergleichen
                    char[] charArray1 = buffer;
                    char[] charArray2 = new char[] { 'P', 'K', c3, c4 };

                    if (Arrays.equals(charArray1, charArray2)) {
                        // hchstwahrscheinlich ein ZIP da es mit 504B0304 respektive PK.. beginnt
                        zip = true;
                    }
                } catch (Exception e) {
                    LOGGER.logError("<Error>"
                            + kostval.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                    System.out.println("Exception: " + e.getMessage());
                }
            }

            // wenn die Datei kein Directory ist, muss sie mit zip oder zip64 enden
            if ((!(valDatei.getAbsolutePath().toLowerCase().endsWith(".zip")
                    || valDatei.getAbsolutePath().toLowerCase().endsWith(".zip64"))) || zip == false) {
                // Abbruch! D.h. Sip message beginnen, Meldung und Beenden ab hier bis System.exit( 1 );
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2));
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP1));
                valDatei = originalSipFile;
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS));
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALTYPE,
                        kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION)));
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALFILE,
                        valDatei.getAbsolutePath()));
                System.out.println(kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION));
                System.out.println(valDatei.getAbsolutePath());

                // die eigentliche Fehlermeldung
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_MODUL_Aa_SIP)
                        + kostval.getTextResourceService().getText(ERROR_XML_AA_INCORRECTFILEENDING));
                System.out.println(kostval.getTextResourceService().getText(ERROR_XML_AA_INCORRECTFILEENDING));

                // Fehler im Validierten SIP --> invalide & Abbruch
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_INVALID));
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE));
                System.out.println("Invalid");
                System.out.println("");
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP2));
                LOGGER.logError(kostval.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 = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER);
                    String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>";
                    Util.oldnewstring(oldstring, newstring, logFile);

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

                // bestehendes Workverzeichnis ggf. lschen
                if (tmpDir.exists()) {
                    Util.deleteDir(tmpDir);
                }
                System.exit(1);

            } else {
                // geziptes SIP --> in temp dir entzipen
                String toplevelDir = valDatei.getName();
                int lastDotIdx = toplevelDir.lastIndexOf(".");
                toplevelDir = toplevelDir.substring(0, lastDotIdx);
                tmpDirZip = new File(
                        tmpDir.getAbsolutePath() + File.separator + "ZIP" + File.separator + toplevelDir);
                try {
                    Zip64Archiver.unzip(valDatei.getAbsolutePath(), tmpDirZip.getAbsolutePath());
                } catch (Exception e) {
                    try {
                        Zip64Archiver.unzip64(valDatei, tmpDirZip);
                    } catch (Exception e1) {
                        // Abbruch! D.h. Sip message beginnen, Meldung und Beenden ab hier bis System.exit
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2));
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP1));
                        valDatei = originalSipFile;
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS));
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALTYPE,
                                kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION)));
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALFILE,
                                valDatei.getAbsolutePath()));
                        System.out.println(kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION));
                        System.out.println(valDatei.getAbsolutePath());

                        // die eigentliche Fehlermeldung
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_MODUL_Aa_SIP)
                                + kostval.getTextResourceService().getText(ERROR_XML_AA_CANNOTEXTRACTZIP));
                        System.out.println(
                                kostval.getTextResourceService().getText(ERROR_XML_AA_CANNOTEXTRACTZIP));

                        // Fehler im Validierten SIP --> invalide & Abbruch
                        LOGGER.logError(
                                kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_INVALID));
                        LOGGER.logError(
                                kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE));
                        System.out.println("Invalid");
                        System.out.println("");
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP2));
                        LOGGER.logError(kostval.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 = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER);
                            String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>";
                            Util.oldnewstring(oldstring, newstring, logFile);

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

                        // bestehendes Workverzeichnis ggf. lschen
                        if (tmpDir.exists()) {
                            Util.deleteDir(tmpDir);
                        }
                        System.exit(1);
                    }
                }
                valDatei = tmpDirZip;

                File toplevelfolder = new File(
                        valDatei.getAbsolutePath() + File.separator + valDatei.getName());
                if (toplevelfolder.exists()) {
                    valDatei = toplevelfolder;
                }
                unSipFile = valDatei;
            }
        } else {
            // SIP ist ein Ordner valDatei bleibt unverndert
        }

        // Vorgngige Formatvalidierung (Schritt 3c)
        Map<String, File> fileMap = Util.getFileMap(valDatei, false);
        Set<String> fileMapKeys = fileMap.keySet();

        int pdf = 0;
        int tiff = 0;
        int siard = 0;
        int txt = 0;
        int csv = 0;
        int xml = 0;
        int xsd = 0;
        int wave = 0;
        int mp3 = 0;
        int jp2 = 0;
        int jpx = 0;
        int jpeg = 0;
        int png = 0;
        int dng = 0;
        int svg = 0;
        int mpeg2 = 0;
        int mp4 = 0;
        int xls = 0;
        int odt = 0;
        int ods = 0;
        int odp = 0;
        int other = 0;

        for (Iterator<String> iterator = fileMapKeys.iterator(); iterator.hasNext();) {
            String entryName = iterator.next();
            File newFile = fileMap.get(entryName);

            if (!newFile.isDirectory()
                    && newFile.getAbsolutePath().contains(File.separator + "content" + File.separator)) {
                valDatei = newFile;
                count = count + 1;

                // Ausgabe Dateizhler Ersichtlich das KOST-Val Dateien durchsucht
                System.out.print(count + "   ");
                System.out.print("\r");

                String extension = valDatei.getName();
                int lastIndexOf = extension.lastIndexOf(".");
                if (lastIndexOf == -1) {
                    // empty extension
                    extension = "other";
                } else {
                    extension = extension.substring(lastIndexOf);
                }

                if (extension.equalsIgnoreCase(".pdf") || extension.equalsIgnoreCase(".pdfa")) {
                    pdf = pdf + 1;
                } else if (extension.equalsIgnoreCase(".tiff") || extension.equalsIgnoreCase(".tif")) {
                    tiff = tiff + 1;
                } else if (extension.equalsIgnoreCase(".siard")) {
                    siard = siard + 1;
                } else if (extension.equalsIgnoreCase(".txt")) {
                    txt = txt + 1;
                } else if (extension.equalsIgnoreCase(".csv")) {
                    csv = csv + 1;
                } else if (extension.equalsIgnoreCase(".xml")) {
                    xml = xml + 1;
                } else if (extension.equalsIgnoreCase(".xsd")) {
                    xsd = xsd + 1;
                } else if (extension.equalsIgnoreCase(".wav")) {
                    wave = wave + 1;
                } else if (extension.equalsIgnoreCase(".mp3")) {
                    mp3 = mp3 + 1;
                } else if (extension.equalsIgnoreCase(".jp2")) {
                    jp2 = jp2 + 1;
                } else if (extension.equalsIgnoreCase(".jpx") || extension.equalsIgnoreCase(".jpf")) {
                    jpx = jpx + 1;
                } else if (extension.equalsIgnoreCase(".jpe") || extension.equalsIgnoreCase(".jpeg")
                        || extension.equalsIgnoreCase(".jpg")) {
                    jpeg = jpeg + 1;
                } else if (extension.equalsIgnoreCase(".png")) {
                    png = png + 1;
                } else if (extension.equalsIgnoreCase(".dng")) {
                    dng = dng + 1;
                } else if (extension.equalsIgnoreCase(".svg")) {
                    svg = svg + 1;
                } else if (extension.equalsIgnoreCase(".mpeg") || extension.equalsIgnoreCase(".mpg")) {
                    mpeg2 = mpeg2 + 1;
                } else if (extension.equalsIgnoreCase(".f4a") || extension.equalsIgnoreCase(".f4v")
                        || extension.equalsIgnoreCase(".m4a") || extension.equalsIgnoreCase(".m4v")
                        || extension.equalsIgnoreCase(".mp4")) {
                    mp4 = mp4 + 1;
                } else if (extension.equalsIgnoreCase(".xls") || extension.equalsIgnoreCase(".xlw")
                        || extension.equalsIgnoreCase(".xlsx")) {
                    xls = xls + 1;
                } else if (extension.equalsIgnoreCase(".odt") || extension.equalsIgnoreCase(".ott")) {
                    odt = odt + 1;
                } else if (extension.equalsIgnoreCase(".ods") || extension.equalsIgnoreCase(".ots")) {
                    ods = ods + 1;
                } else if (extension.equalsIgnoreCase(".odp") || extension.equalsIgnoreCase(".otp")) {
                    odp = odp + 1;
                } else {
                    other = other + 1;
                }

                if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".jp2")))
                        && jp2Validation.equals("yes")) {

                    boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                    if (valFile) {
                        jp2CountIo = jp2CountIo + 1;
                    } else {
                        jp2CountNio = jp2CountNio + 1;
                    }

                } else if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".tiff")
                        || valDatei.getAbsolutePath().toLowerCase().endsWith(".tif")))
                        && tiffValidation.equals("yes")) {

                    boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                    if (valFile) {
                        tiffCountIo = tiffCountIo + 1;
                    } else {
                        tiffCountNio = tiffCountNio + 1;
                    }

                } else if ((valDatei.getAbsolutePath().toLowerCase().endsWith(".siard"))
                        && siardValidation.equals("yes")) {

                    // Arbeitsverzeichnis zum Entpacken des Archivs erstellen
                    String pathToWorkDirSiard = kostval.getConfigurationService().getPathToWorkDir();
                    File tmpDirSiard = new File(pathToWorkDirSiard + File.separator + "SIARD");
                    if (tmpDirSiard.exists()) {
                        Util.deleteDir(tmpDirSiard);
                    }
                    if (!tmpDirSiard.exists()) {
                        tmpDirSiard.mkdir();
                    }

                    boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                    if (valFile) {
                        siardCountIo = siardCountIo + 1;
                    } else {
                        siardCountNio = siardCountNio + 1;
                    }

                } else if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".pdf")
                        || valDatei.getAbsolutePath().toLowerCase().endsWith(".pdfa")))
                        && pdfaValidation.equals("yes")) {

                    boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose);

                    if (valFile) {
                        pdfaCountIo = pdfaCountIo + 1;
                    } else {
                        pdfaCountNio = pdfaCountNio + 1;
                    }

                } else {
                    countNio = countNio + 1;
                }
            }
        }

        countSummaryNio = pdfaCountNio + siardCountNio + tiffCountNio + jp2CountNio;
        countSummaryIo = pdfaCountIo + siardCountIo + tiffCountIo + jp2CountIo;
        int countSummaryIoP = 100 / count * countSummaryIo;
        int countSummaryNioP = 100 / count * countSummaryNio;
        int countNioP = 100 / count * countNio;
        String summary3c = kostval.getTextResourceService().getText(MESSAGE_XML_SUMMARY_3C, count,
                countSummaryIo, countSummaryNio, countNio, countSummaryIoP, countSummaryNioP, countNioP);

        if (countSummaryNio == 0) {
            // alle Validierten Dateien valide
            validFormat = true;
            fileName3c = "3c_Valide.txt";
        } else {
            // Fehler in Validierten Dateien --> invalide
            validFormat = false;
            fileName3c = "3c_Invalide.txt";
        }
        // outputFile3c = new File( directoryOfLogfile + fileName3c );
        outputFile3c = new File(pathToWorkDir + File.separator + fileName3c);
        try {
            outputFile3c.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (countNio == count) {
            // keine Dateien Validiert
            LOGGER.logError(kostval.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS, formatValOn));
            System.out
                    .println(kostval.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS, formatValOn));
        }

        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2));

        // Start Normale SIP-Validierung mit auswertung Format-Val. im 3c

        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP1));
        valDatei = unSipFile;
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS));
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALTYPE,
                kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION)));
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALFILE,
                originalSipFile.getAbsolutePath()));
        System.out.println(kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION));
        System.out.println(originalSipFile.getAbsolutePath());

        Controllersip controller = (Controllersip) context.getBean("controllersip");
        boolean okMandatory = false;
        okMandatory = controller.executeMandatory(valDatei, directoryOfLogfile);
        boolean ok = false;

        /* die Validierungen 1a - 1d sind obligatorisch, wenn sie bestanden wurden, knnen die
         * restlichen Validierungen, welche nicht zum Abbruch der Applikation fhren, ausgefhrt
         * werden.
         * 
         * 1a wurde bereits getestet (vor der Formatvalidierung entsprechend fngt der Controller mit
         * 1b an */
        if (okMandatory) {
            ok = controller.executeOptional(valDatei, directoryOfLogfile);
        }
        // Formatvalidierung validFormat
        ok = (ok && okMandatory && validFormat);

        if (ok) {
            // Validiertes SIP valide
            LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_VALID));
            LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE));
            System.out.println("Valid");
            System.out.println("");
        } else {
            // Fehler im Validierten SIP --> invalide
            LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_INVALID));
            LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE));
            System.out.println("Invalid");
            System.out.println("");

        }

        // ggf. Fehlermeldung 3c ergnzen Util.val3c(summary3c, logFile );

        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP2));

        LOGGER.logError(kostval.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.val3c(summary3c, 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 = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER);
            String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>";
            Util.oldnewstring(oldstring, newstring, logFile);

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

        // bestehendes Workverzeichnis ggf. lschen
        if (tmpDir.exists()) {
            Util.deleteDir(tmpDir);
        }
        StringBuffer command = new StringBuffer("rd " + tmpDir.getAbsolutePath() + " /s /q");

        try {
            // KaD-Diagnose-Datei mit den neusten Anzahl Dateien pro KaD-Format Updaten
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlDiaCopy);

            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("KOSTVal_FFCounter");

            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;

                    if (pdf > 0) {
                        String pdfNodeString = eElement.getElementsByTagName("pdf").item(0).getTextContent();
                        int pdfNodeValue = Integer.parseInt(pdfNodeString);
                        pdf = pdf + pdfNodeValue;
                        Util.kadDia("<pdf>" + pdfNodeValue + "</pdf>", "<pdf>" + pdf + "</pdf>", xmlDiaCopy);
                    }
                    if (tiff > 0) {
                        String tiffNodeString = eElement.getElementsByTagName("tiff").item(0).getTextContent();
                        int tiffNodeValue = Integer.parseInt(tiffNodeString);
                        tiff = tiff + tiffNodeValue;
                        Util.kadDia("<tiff>" + tiffNodeValue + "</tiff>", "<tiff>" + tiff + "</tiff>",
                                xmlDiaCopy);
                    }
                    if (siard > 0) {
                        String siardNodeString = eElement.getElementsByTagName("siard").item(0)
                                .getTextContent();
                        int siardNodeValue = Integer.parseInt(siardNodeString);
                        siard = siard + siardNodeValue;
                        Util.kadDia("<siard>" + siardNodeValue + "</siard>", "<siard>" + siard + "</siard>",
                                xmlDiaCopy);
                    }
                    if (txt > 0) {
                        String txtNodeString = eElement.getElementsByTagName("txt").item(0).getTextContent();
                        int txtNodeValue = Integer.parseInt(txtNodeString);
                        txt = txt + txtNodeValue;
                        Util.kadDia("<txt>" + txtNodeValue + "</txt>", "<txt>" + txt + "</txt>", xmlDiaCopy);
                    }
                    if (csv > 0) {
                        String csvNodeString = eElement.getElementsByTagName("csv").item(0).getTextContent();
                        int csvNodeValue = Integer.parseInt(csvNodeString);
                        csv = csv + csvNodeValue;
                        Util.kadDia("<csv>" + csvNodeValue + "</csv>", "<csv>" + csv + "</csv>", xmlDiaCopy);
                    }
                    if (xml > 0) {
                        String xmlNodeString = eElement.getElementsByTagName("xml").item(0).getTextContent();
                        int xmlNodeValue = Integer.parseInt(xmlNodeString);
                        xml = xml + xmlNodeValue;
                        Util.kadDia("<xml>" + xmlNodeValue + "</xml>", "<xml>" + xml + "</xml>", xmlDiaCopy);
                    }
                    if (xsd > 0) {
                        String xsdNodeString = eElement.getElementsByTagName("xsd").item(0).getTextContent();
                        int xsdNodeValue = Integer.parseInt(xsdNodeString);
                        xsd = xsd + xsdNodeValue;
                        Util.kadDia("<xsd>" + xsdNodeValue + "</xsd>", "<xsd>" + xsd + "</xsd>", xmlDiaCopy);
                    }
                    if (wave > 0) {
                        String waveNodeString = eElement.getElementsByTagName("wave").item(0).getTextContent();
                        int waveNodeValue = Integer.parseInt(waveNodeString);
                        wave = wave + waveNodeValue;
                        Util.kadDia("<wave>" + waveNodeValue + "</wave>", "<wave>" + wave + "</wave>",
                                xmlDiaCopy);
                    }
                    if (mp3 > 0) {
                        String mp3NodeString = eElement.getElementsByTagName("mp3").item(0).getTextContent();
                        int mp3NodeValue = Integer.parseInt(mp3NodeString);
                        mp3 = mp3 + mp3NodeValue;
                        Util.kadDia("<mp3>" + mp3NodeValue + "</mp3>", "<mp3>" + mp3 + "</mp3>", xmlDiaCopy);
                    }
                    if (jp2 > 0) {
                        String jp2NodeString = eElement.getElementsByTagName("jp2").item(0).getTextContent();
                        int jp2NodeValue = Integer.parseInt(jp2NodeString);
                        jp2 = jp2 + jp2NodeValue;
                        Util.kadDia("<jp2>" + jp2NodeValue + "</jp2>", "<jp2>" + jp2 + "</jp2>", xmlDiaCopy);
                    }
                    if (jpx > 0) {
                        String jpxNodeString = eElement.getElementsByTagName("jpx").item(0).getTextContent();
                        int jpxNodeValue = Integer.parseInt(jpxNodeString);
                        jpx = jpx + jpxNodeValue;
                        Util.kadDia("<jpx>" + jpxNodeValue + "</jpx>", "<jpx>" + jpx + "</jpx>", xmlDiaCopy);
                    }
                    if (jpeg > 0) {
                        String jpegNodeString = eElement.getElementsByTagName("jpeg").item(0).getTextContent();
                        int jpegNodeValue = Integer.parseInt(jpegNodeString);
                        jpeg = jpeg + jpegNodeValue;
                        Util.kadDia("<jpeg>" + jpegNodeValue + "</jpeg>", "<jpeg>" + jpeg + "</jpeg>",
                                xmlDiaCopy);
                    }
                    if (png > 0) {
                        String pngNodeString = eElement.getElementsByTagName("png").item(0).getTextContent();
                        int pngNodeValue = Integer.parseInt(pngNodeString);
                        png = png + pngNodeValue;
                        Util.kadDia("<png>" + pngNodeValue + "</png>", "<png>" + png + "</png>", xmlDiaCopy);
                    }
                    if (dng > 0) {
                        String dngNodeString = eElement.getElementsByTagName("dng").item(0).getTextContent();
                        int dngNodeValue = Integer.parseInt(dngNodeString);
                        dng = dng + dngNodeValue;
                        Util.kadDia("<dng>" + dngNodeValue + "</dng>", "<dng>" + dng + "</dng>", xmlDiaCopy);
                    }
                    if (svg > 0) {
                        String svgNodeString = eElement.getElementsByTagName("svg").item(0).getTextContent();
                        int svgNodeValue = Integer.parseInt(svgNodeString);
                        svg = svg + svgNodeValue;
                        Util.kadDia("<svg>" + svgNodeValue + "</svg>", "<svg>" + svg + "</svg>", xmlDiaCopy);
                    }
                    if (mpeg2 > 0) {
                        String mpeg2NodeString = eElement.getElementsByTagName("mpeg2").item(0)
                                .getTextContent();
                        int mpeg2NodeValue = Integer.parseInt(mpeg2NodeString);
                        mpeg2 = mpeg2 + mpeg2NodeValue;
                        Util.kadDia("<mpeg2>" + mpeg2NodeValue + "</mpeg2>", "<mpeg2>" + mpeg2 + "</mpeg2>",
                                xmlDiaCopy);
                    }
                    if (mp4 > 0) {
                        String mp4NodeString = eElement.getElementsByTagName("mp4").item(0).getTextContent();
                        int mp4NodeValue = Integer.parseInt(mp4NodeString);
                        mp4 = mp4 + mp4NodeValue;
                        Util.kadDia("<mp4>" + mp4NodeValue + "</mp4>", "<mp4>" + mp4 + "</mp4>", xmlDiaCopy);
                    }
                    if (xls > 0) {
                        String xlsNodeString = eElement.getElementsByTagName("xls").item(0).getTextContent();
                        int xlsNodeValue = Integer.parseInt(xlsNodeString);
                        xls = xls + xlsNodeValue;
                        Util.kadDia("<xls>" + xlsNodeValue + "</xls>", "<xls>" + xls + "</xls>", xmlDiaCopy);
                    }
                    if (odt > 0) {
                        String odtNodeString = eElement.getElementsByTagName("odt").item(0).getTextContent();
                        int odtNodeValue = Integer.parseInt(odtNodeString);
                        odt = odt + odtNodeValue;
                        Util.kadDia("<odt>" + odtNodeValue + "</odt>", "<odt>" + odt + "</odt>", xmlDiaCopy);
                    }
                    if (ods > 0) {
                        String odsNodeString = eElement.getElementsByTagName("ods").item(0).getTextContent();
                        int odsNodeValue = Integer.parseInt(odsNodeString);
                        ods = ods + odsNodeValue;
                        Util.kadDia("<ods>" + odsNodeValue + "</ods>", "<ods>" + ods + "</ods>", xmlDiaCopy);
                    }
                    if (odp > 0) {
                        String odpNodeString = eElement.getElementsByTagName("odp").item(0).getTextContent();
                        int odpNodeValue = Integer.parseInt(odpNodeString);
                        odp = odp + odpNodeValue;
                        Util.kadDia("<odp>" + odpNodeValue + "</odp>", "<odp>" + odp + "</odp>", xmlDiaCopy);
                    }
                    if (other > 0) {
                        String otherNodeString = eElement.getElementsByTagName("other").item(0)
                                .getTextContent();
                        int otherNodeValue = Integer.parseInt(otherNodeString);
                        other = other + otherNodeValue;
                        Util.kadDia("<other>" + otherNodeValue + "</other>", "<other>" + other + "</other>",
                                xmlDiaCopy);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (ok) {
            // bestehendes Workverzeichnis ggf. lschen
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            if (tmpDir.exists()) {
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec(command.toString());
            }
            System.exit(0);
        } else {
            // bestehendes Workverzeichnis ggf. lschen
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            if (tmpDir.exists()) {
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec(command.toString());
            }
            System.exit(2);
        }
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP2));

    } else {
        /* Ueberprfung des Parameters (Val-Typ): format / sip args[0] ist nicht "--format" oder
         * "--sip" --> INVALIDE */
        LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE,
                kostval.getTextResourceService().getText(ERROR_PARAMETER_USAGE)));
        System.out.println(kostval.getTextResourceService().getText(ERROR_PARAMETER_USAGE));
        if (tmpDir.exists()) {
            Util.deleteDir(tmpDir);
            tmpDir.deleteOnExit();
        }
        System.exit(1);
    }
}