Example usage for java.io File exists

List of usage examples for java.io File exists

Introduction

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

Prototype

public boolean exists() 

Source Link

Document

Tests whether the file or directory denoted by this abstract pathname exists.

Usage

From source file:de.prozesskraft.pkraft.Manager.java

public static void main(String[] args)
        throws org.apache.commons.cli.ParseException, CloneNotSupportedException {

    //      try/*  w  w  w . j  a va  2s . co m*/
    //      {
    //         if (args.length != 1)
    //         {
    //            System.out.println("Please specify Inputfile and Outputfile (prozessinstanz.lri)");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify procesdefinition.lrd and processinstance.lri\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Manager.class) + "/" + "../etc/pkraft-manager.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
        exit = true;
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option help = new Option("help", "print this message");
    Option v = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option instance = OptionBuilder.withArgName("instance").hasArg()
            .withDescription("[mandatory] process instance file")
            //            .isRequired()
            .create("instance");

    Option stop = OptionBuilder.withArgName("stop")
            //            .hasArg()
            .withDescription("[optional] stops a running manager for given instance")
            //            .isRequired()
            .create("stop");

    Option kill = OptionBuilder.withArgName("kill")
            //            .hasArg()
            .withDescription("[optional] kills all applications that have been started by steps")
            //            .isRequired()
            .create("kill");

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

    options.addOption(help);
    options.addOption(v);
    options.addOption(instance);
    options.addOption(stop);
    options.addOption(kill);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    }
    //      catch ( ParseException exp )
    catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("manager", options);
        exit = true;
        System.exit(0);
    }

    else if (line.hasOption("v")) {
        System.out.println("author:  info@prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        exit = true;
        System.exit(0);
    }

    else if (!(line.hasOption("instance"))) {
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        exit = true;
        System.exit(1);
    }

    /*----------------------------
      business logic
    ----------------------------*/

    Process actualProcess = null;
    try {

        Process p1 = new Process();

        // die dauer des loops festlegen. Dies soll kein standardwert sein, da sonst bei vielen subprozessen die Prozessorlast stark oszilliert
        // zwischen 12 und 17 sekunden
        //         Random rand = new Random(System.currentTimeMillis());
        //         int loop_period_seconds = rand.nextInt((17 - 12) + 1) + 12;
        //         System.err.println("loop period is randomly set to: "+loop_period_seconds);

        fileBinary = new java.io.File(line.getOptionValue("instance"));
        String pathBinary = "";

        if (fileBinary.exists()) {
            pathBinary = fileBinary.getAbsolutePath();
            System.err.println("file does exist: " + pathBinary);
        } else {
            System.err.println("file does not exist: " + fileBinary.getAbsolutePath());
            exiter();
        }

        if (line.hasOption("stop") || line.hasOption("kill")) {
            p1.setInfilebinary(pathBinary);
            Process p2 = p1.readBinary();
            p2.log("debug", "setting new manager-Id (0) to signal actual manager (" + p2.getManagerid()
                    + ") that he is no longer in charge ");
            System.err.println("info: stopping instance");
            System.err.println("debug: setting new manager-Id (0) to signal actual manager ("
                    + p2.getManagerid() + ") that he is no longer in charge ");
            p2.setManagerid(0);
            p2.run = false;
            p2.setOutfilebinary(pathBinary);

            p2.writeBinary();

            if (line.hasOption("kill")) {
                System.err.println("info: killing all steps of instance");
                String returnStringOfKills = p2.kill();
                System.err.println("info: killing returns: " + returnStringOfKills);
            }

            boolean pradar = (!(p2.isWrapper()));

            // pradar checkout
            if (pradar) {
                pradarAttend(p2.getRootdir() + "/process.pmb");
                //               pradarCheckout(p2.getId(), p2.getName(), "0");
            }

            exit = true;
            System.exit(0);
        }

        startZyklischerThread(0);

        // prozessinstanz einlesen
        p1.setInfilebinary(pathBinary);

        managerid = p1.genManagerid();

        Process p2;
        p2 = p1.readBinary();

        // beim aufruf des programms wird erstmal die instanz occupiert
        p2.setManagerid(managerid);

        System.err.println("debug: manager " + managerid + ": occupying instance.");
        p2.log("info", "manager " + managerid + ": occupying instance.");
        p2.log("debug", "manager " + managerid
                + ": setting new manager-id to signal other running managers that they are not longer needed.");

        p2.log("debug", "manager " + managerid + ": setting binary file for input to: " + pathBinary);
        //      System.out.println("setting binary file for input to: "+line.getOptionValue("instance"));

        p2.log("debug", "manager " + managerid + ": reading binary file: " + pathBinary);

        p2.setInfilebinary(pathBinary);
        p2.setOutfilebinary(pathBinary);
        p2.log("debug", "manager " + managerid + ": setting binary file for output: " + pathBinary);

        // instanz auf platte schreiben (um anderen managern zu signalisieren, dass sie nicht mehr gebraucht werden
        //      System.out.println("setting manager-id to: "+managerid);

        p2.log("debug", "manager " + managerid + ": writing process to binary file to occupy instance.");

        // wenn es kein wrapper-prozess ist, dann soll die komunikation mit pradar vom manager uebernommen werden
        boolean pradar = (!(p2.isWrapper()));

        System.err.println("debug: setting instance to run");
        p2.run = true;

        // pradar checkin
        if (pradar && p2.run && p2.touchInMillis == 0) {
            pradarAttend(p2.getRootdir() + "/process.pmb");
            //            p2.log("debug", "pradar-checkin id="+p2.getId()+", process="+p2.getName()+", processversion="+p2.getVersion()+", id2="+p2.getId2()+", parentid="+p2.getParentid()+", resource="+p2.getRootdir()+"/process.pmb");
            //            pradarCheckin(p2.getId(), p2.getName(), p2.getVersion(), p2.getId2(), p2.getParentid(), getPid(), p2.getRootdir()+"/process.pmb");
        }

        System.err.println("debug: writing binary");

        p2.writeBinary();

        // process weiter schubsen
        pushProcessAsFarAsPossible(pathBinary, false);

        //         try
        //         {
        //            // der thread soll so lange schlafen, wie die periode lang ist. die schlafdauer wird mit der anzahl multipliziert, wie oft das loadAverage zu hoch war (max 5)
        //            int faktorForPeriod = Math.min(10, p2.counterLoadAverageTooHigh + 1);
        //
        //            int secondsToSleep = loop_period_seconds * faktorForPeriod;
        //            System.err.println("debug: sleeping for " + secondsToSleep + " seconds");
        //            
        //            int millisecondsToSleep = secondsToSleep*1000;
        //            System.err.println("debug: sleeping for " + millisecondsToSleep + " milliseconds");
        //            
        //            Thread.sleep(millisecondsToSleep);
        //         }
        //         catch (InterruptedException e)
        //         {
        //            // TODO Auto-generated catch block
        //            e.printStackTrace();
        //
        //            // ausgabe in das debugLogFile
        //            exiterException(actualProcess.getOutfilebinary(), e);
        //         }
    } catch (Exception e) {
        if (actualProcess != null) {
            actualProcess.log("fatal", e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
            updateFile(actualProcess);
            e.printStackTrace();

            // ausgabe in das debugLogFile
            exiterException(actualProcess.getOutfilebinary(), e);

        }
        exit = true;

        System.exit(10);
    }
}

From source file:com.sforce.dataset.DatasetUtilMain.java

public static void main(String[] args) {

    printBanner();/* w w  w. java  2  s.c o  m*/

    DatasetUtilParams params = new DatasetUtilParams();

    if (args.length > 0)
        params.server = false;

    System.out.println("");
    System.out.println("DatsetUtils called with {" + args.length + "} Params:");

    for (int i = 0; i < args.length; i++) {
        if ((i & 1) == 0) {
            System.out.print("{" + args[i] + "}");
        } else {
            if (i > 0 && args[i - 1].equalsIgnoreCase("--p"))
                System.out.println(":{*******}");
            else
                System.out.println(":{" + args[i] + "}");
        }

        if (i > 0 && args[i - 1].equalsIgnoreCase("--server")) {
            if (args[i] != null && args[i].trim().equalsIgnoreCase("false"))
                params.server = false;
            else if (args[i] != null && args[i].trim().equalsIgnoreCase("true"))
                params.server = true;
        }
    }
    System.out.println("");

    if (!printlneula(params.server)) {
        System.out.println(
                "You do not have permission to use this software. Please delete it from this computer");
        System.exit(-1);
    }

    String action = null;

    if (args.length >= 2) {
        for (int i = 1; i < args.length; i = i + 2) {
            if (args[i - 1].equalsIgnoreCase("--help") || args[i - 1].equalsIgnoreCase("-help")
                    || args[i - 1].equalsIgnoreCase("help")) {
                printUsage();
            } else if (args[i - 1].equalsIgnoreCase("--u")) {
                params.username = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--p")) {
                params.password = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--sessionId")) {
                params.sessionId = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--token")) {
                params.token = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--endpoint")) {
                params.endpoint = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--action")) {
                action = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--operation")) {
                if (args[i] != null) {
                    if (args[i].equalsIgnoreCase("overwrite")) {
                        params.Operation = args[i];
                    } else if (args[i].equalsIgnoreCase("upsert")) {
                        params.Operation = args[i];
                    } else if (args[i].equalsIgnoreCase("append")) {
                        params.Operation = args[i];
                    } else if (args[i].equalsIgnoreCase("delete")) {
                        params.Operation = args[i];
                    } else {
                        System.out.println("Invalid Operation {" + args[i]
                                + "} Must be Overwrite or Upsert or Append or Delete");
                        System.exit(-1);
                    }
                }
            } else if (args[i - 1].equalsIgnoreCase("--debug")) {
                params.debug = true;
                DatasetUtilConstants.debug = true;
            } else if (args[i - 1].equalsIgnoreCase("--ext")) {
                DatasetUtilConstants.ext = true;
            } else if (args[i - 1].equalsIgnoreCase("--inputFile")) {
                String tmp = args[i];
                if (tmp != null) {
                    File tempFile = new File(tmp);
                    if (tempFile.exists()) {
                        params.inputFile = tempFile.toString();
                    } else {
                        System.out.println("File {" + args[i] + "} does not exist");
                        System.exit(-1);
                    }
                }
            } else if (args[i - 1].equalsIgnoreCase("--dataset")) {
                params.dataset = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--datasetLabel")) {
                params.datasetLabel = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--app")) {
                params.app = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--useBulkAPI")) {
                if (args[i] != null && args[i].trim().equalsIgnoreCase("true"))
                    params.useBulkAPI = true;
            } else if (args[i - 1].equalsIgnoreCase("--uploadFormat")) {
                if (args[i] != null && args[i].trim().equalsIgnoreCase("csv"))
                    params.uploadFormat = "csv";
                else if (args[i] != null && args[i].trim().equalsIgnoreCase("binary"))
                    params.uploadFormat = "binary";
            } else if (args[i - 1].equalsIgnoreCase("--rowLimit")) {
                if (args[i] != null && !args[i].trim().isEmpty())
                    params.rowLimit = (new BigDecimal(args[i].trim())).intValue();
            } else if (args[i - 1].equalsIgnoreCase("--rootObject")) {
                params.rootObject = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--fileEncoding")) {
                params.fileEncoding = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--server")) {
                if (args[i] != null && args[i].trim().equalsIgnoreCase("true"))
                    params.server = true;
                else if (args[i] != null && args[i].trim().equalsIgnoreCase("false"))
                    params.server = false;
            } else if (args[i - 1].equalsIgnoreCase("--codingErrorAction")) {
                if (args[i] != null) {
                    if (args[i].equalsIgnoreCase("IGNORE")) {
                        params.codingErrorAction = CodingErrorAction.IGNORE;
                    } else if (args[i].equalsIgnoreCase("REPORT")) {
                        params.codingErrorAction = CodingErrorAction.REPORT;
                    } else if (args[i].equalsIgnoreCase("REPLACE")) {
                        params.codingErrorAction = CodingErrorAction.REPLACE;
                    }
                }
            } else {
                printUsage();
                System.out.println("\nERROR: Invalid argument: " + args[i - 1]);
                System.exit(-1);
            }
        } //end for

        if (params.username != null) {
            if (params.endpoint == null || params.endpoint.isEmpty()) {
                params.endpoint = DatasetUtilConstants.defaultEndpoint;
            }
        }
    }

    if (params.server) {
        System.out.println();
        System.out.println("\n*******************************************************************************");
        try {
            DatasetUtilServer datasetUtilServer = new DatasetUtilServer();
            datasetUtilServer.init(args, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Server ended, exiting JVM.....");
        System.out.println("*******************************************************************************\n");
        System.out.println("QUITAPP");
        System.exit(0);
    }

    if (params.sessionId == null) {
        if (params.username == null || params.username.trim().isEmpty()) {
            params.username = getInputFromUser("Enter salesforce username: ", true, false);
        }

        if (params.username.equals("-1")) {
            params.sessionId = getInputFromUser("Enter salesforce sessionId: ", true, false);
            params.username = null;
            params.password = null;
        } else {
            if (params.password == null || params.password.trim().isEmpty()) {
                params.password = getInputFromUser("Enter salesforce password: ", true, true);
            }
        }
    }

    if (params.sessionId != null && !params.sessionId.isEmpty()) {
        while (params.endpoint == null || params.endpoint.trim().isEmpty()) {
            params.endpoint = getInputFromUser("Enter salesforce instance url: ", true, false);
            if (params.endpoint == null || params.endpoint.trim().isEmpty())
                System.out.println("\nERROR: endpoint must be specified when sessionId is specified");
        }

        while (params.endpoint.toLowerCase().contains("login.salesforce.com")
                || params.endpoint.toLowerCase().contains("test.salesforce.com")
                || params.endpoint.toLowerCase().contains("test")
                || params.endpoint.toLowerCase().contains("prod")
                || params.endpoint.toLowerCase().contains("sandbox")) {
            System.out.println("\nERROR: endpoint must be the actual serviceURL and not the login url");
            params.endpoint = getInputFromUser("Enter salesforce instance url: ", true, false);
        }
    } else {
        if (params.endpoint == null || params.endpoint.isEmpty()) {
            params.endpoint = getInputFromUser("Enter salesforce instance url (default=prod): ", false, false);
            if (params.endpoint == null || params.endpoint.trim().isEmpty()) {
                params.endpoint = DatasetUtilConstants.defaultEndpoint;
            }
        }
    }

    try {
        if (params.endpoint.equalsIgnoreCase("PROD") || params.endpoint.equalsIgnoreCase("PRODUCTION")) {
            params.endpoint = DatasetUtilConstants.defaultEndpoint;
        } else if (params.endpoint.equalsIgnoreCase("TEST") || params.endpoint.equalsIgnoreCase("SANDBOX")) {
            params.endpoint = DatasetUtilConstants.defaultEndpoint.replace("login", "test");
        }

        URL uri = new URL(params.endpoint);
        String protocol = uri.getProtocol();
        String host = uri.getHost();
        if (protocol == null || !protocol.equalsIgnoreCase("https")) {
            if (host == null || !(host.toLowerCase().endsWith("internal.salesforce.com")
                    || host.toLowerCase().endsWith("localhost"))) {
                System.out.println("\nERROR: Invalid endpoint. UNSUPPORTED_CLIENT: HTTPS Required in endpoint");
                System.exit(-1);
            }
        }

        if (uri.getPath() == null || uri.getPath().isEmpty() || uri.getPath().equals("/")) {
            uri = new URL(uri.getProtocol(), uri.getHost(), uri.getPort(),
                    DatasetUtilConstants.defaultSoapEndPointPath);
        }
        params.endpoint = uri.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
        System.out.println("\nERROR: endpoint is not a valid URL");
        System.exit(-1);
    }

    PartnerConnection partnerConnection = null;
    if (params.username != null || params.sessionId != null) {
        try {
            partnerConnection = DatasetUtils.login(0, params.username, params.password, params.token,
                    params.endpoint, params.sessionId, params.debug);
        } catch (ConnectionException e) {
            e.printStackTrace();
            System.exit(-1);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    if (args.length == 0 || action == null) {
        //         System.out.println("\n*******************************************************************************");               
        ////         FileListenerUtil.startAllListener(partnerConnection);
        //         try {
        //            Thread.sleep(1000);
        //         } catch (InterruptedException e) {
        //         }
        //         System.out.println("*******************************************************************************\n");   
        //         System.out.println();         

        //         System.out.println("\n*******************************************************************************");               
        //           try {
        //              DatasetUtilServer datasetUtilServer = new DatasetUtilServer();
        //            datasetUtilServer.init(args, false);
        //         } catch (Exception e) {
        //            e.printStackTrace();
        //         }
        //         System.out.println("*******************************************************************************\n");   
        //         System.out.println();         

        while (true) {
            action = getActionFromUser();
            if (action == null || action.isEmpty()) {
                System.exit(-1);
            }
            params = new DatasetUtilParams();
            getRequiredParams(action, partnerConnection, params);
            @SuppressWarnings("unused")
            boolean status = doAction(action, partnerConnection, params);
            //            if(status)
            //            {
            //               if(action.equalsIgnoreCase("load") && params.debug)
            //                  createListener(partnerConnection, params);
            //            }
        }
    } else {
        doAction(action, partnerConnection, params);
    }

}

From source file:examples.mail.IMAPExportMbox.java

public static void main(String[] args) throws IOException {
    int connect_timeout = CONNECT_TIMEOUT;
    int read_timeout = READ_TIMEOUT;

    int argIdx = 0;
    String eol = EOL_DEFAULT;//from  ww w.j a  v a2  s  .  c  o  m
    boolean printHash = false;
    boolean printMarker = false;
    int retryWaitSecs = 0;

    for (argIdx = 0; argIdx < args.length; argIdx++) {
        if (args[argIdx].equals("-c")) {
            connect_timeout = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-r")) {
            read_timeout = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-R")) {
            retryWaitSecs = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-LF")) {
            eol = LF;
        } else if (args[argIdx].equals("-CRLF")) {
            eol = CRLF;
        } else if (args[argIdx].equals("-.")) {
            printHash = true;
        } else if (args[argIdx].equals("-X")) {
            printMarker = true;
        } else {
            break;
        }
    }

    final int argCount = args.length - argIdx;

    if (argCount < 2) {
        System.err.println("Usage: IMAPExportMbox [-LF|-CRLF] [-c n] [-r n] [-R n] [-.] [-X]"
                + " imap[s]://user:password@host[:port]/folder/path [+|-]<mboxfile> [sequence-set] [itemnames]");
        System.err.println(
                "\t-LF | -CRLF set end-of-line to LF or CRLF (default is the line.separator system property)");
        System.err.println("\t-c connect timeout in seconds (default 10)");
        System.err.println("\t-r read timeout in seconds (default 10)");
        System.err.println("\t-R temporary failure retry wait in seconds (default 0; i.e. disabled)");
        System.err.println("\t-. print a . for each complete message received");
        System.err.println("\t-X print the X-IMAP line for each complete message received");
        System.err.println(
                "\tthe mboxfile is where the messages are stored; use '-' to write to standard output.");
        System.err.println(
                "\tPrefix filename with '+' to append to the file. Prefix with '-' to allow overwrite.");
        System.err.println(
                "\ta sequence-set is a list of numbers/number ranges e.g. 1,2,3-10,20:* - default 1:*");
        System.err
                .println("\titemnames are the message data item name(s) e.g. BODY.PEEK[HEADER.FIELDS (SUBJECT)]"
                        + " or a macro e.g. ALL - default (INTERNALDATE BODY.PEEK[])");
        System.exit(1);
    }

    final URI uri = URI.create(args[argIdx++]);
    final String file = args[argIdx++];
    String sequenceSet = argCount > 2 ? args[argIdx++] : "1:*";
    final String itemNames;
    // Handle 0, 1 or multiple item names
    if (argCount > 3) {
        if (argCount > 4) {
            StringBuilder sb = new StringBuilder();
            sb.append("(");
            for (int i = 4; i <= argCount; i++) {
                if (i > 4) {
                    sb.append(" ");
                }
                sb.append(args[argIdx++]);
            }
            sb.append(")");
            itemNames = sb.toString();
        } else {
            itemNames = args[argIdx++];
        }
    } else {
        itemNames = "(INTERNALDATE BODY.PEEK[])";
    }

    final boolean checkSequence = sequenceSet.matches("\\d+:(\\d+|\\*)"); // are we expecting a sequence?
    final MboxListener chunkListener;
    if (file.equals("-")) {
        chunkListener = null;
    } else if (file.startsWith("+")) {
        final File mbox = new File(file.substring(1));
        System.out.println("Appending to file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, true)), eol, printHash,
                printMarker, checkSequence);
    } else if (file.startsWith("-")) {
        final File mbox = new File(file.substring(1));
        System.out.println("Writing to file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, false)), eol, printHash,
                printMarker, checkSequence);
    } else {
        final File mbox = new File(file);
        if (mbox.exists()) {
            throw new IOException("mailbox file: " + mbox + " already exists!");
        }
        System.out.println("Creating file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox)), eol, printHash, printMarker,
                checkSequence);
    }

    String path = uri.getPath();
    if (path == null || path.length() < 1) {
        throw new IllegalArgumentException("Invalid folderPath: '" + path + "'");
    }
    String folder = path.substring(1); // skip the leading /

    // suppress login details
    final PrintCommandListener listener = new PrintCommandListener(System.out, true) {
        @Override
        public void protocolReplyReceived(ProtocolCommandEvent event) {
            if (event.getReplyCode() != IMAPReply.PARTIAL) { // This is dealt with by the chunk listener
                super.protocolReplyReceived(event);
            }
        }
    };

    // Connect and login
    final IMAPClient imap = IMAPUtils.imapLogin(uri, connect_timeout * 1000, listener);

    String maxIndexInFolder = null;

    try {

        imap.setSoTimeout(read_timeout * 1000);

        if (!imap.select(folder)) {
            throw new IOException("Could not select folder: " + folder);
        }

        for (String line : imap.getReplyStrings()) {
            maxIndexInFolder = matches(line, PATEXISTS, 1);
            if (maxIndexInFolder != null) {
                break;
            }
        }

        if (chunkListener != null) {
            imap.setChunkListener(chunkListener);
        } // else the command listener displays the full output without processing

        while (true) {
            boolean ok = imap.fetch(sequenceSet, itemNames);
            // If the fetch failed, can we retry?
            if (!ok && retryWaitSecs > 0 && chunkListener != null && checkSequence) {
                final String replyString = imap.getReplyString(); //includes EOL
                if (startsWith(replyString, PATTEMPFAIL)) {
                    System.err.println("Temporary error detected, will retry in " + retryWaitSecs + "seconds");
                    sequenceSet = (chunkListener.lastSeq + 1) + ":*";
                    try {
                        Thread.sleep(retryWaitSecs * 1000);
                    } catch (InterruptedException e) {
                        // ignored
                    }
                } else {
                    throw new IOException(
                            "FETCH " + sequenceSet + " " + itemNames + " failed with " + replyString);
                }
            } else {
                break;
            }
        }

    } catch (IOException ioe) {
        String count = chunkListener == null ? "?" : Integer.toString(chunkListener.total);
        System.err.println("FETCH " + sequenceSet + " " + itemNames + " failed after processing " + count
                + " complete messages ");
        if (chunkListener != null) {
            System.err.println("Last complete response seen: " + chunkListener.lastFetched);
        }
        throw ioe;
    } finally {

        if (printHash) {
            System.err.println();
        }

        if (chunkListener != null) {
            chunkListener.close();
            final Iterator<String> missingIds = chunkListener.missingIds.iterator();
            if (missingIds.hasNext()) {
                StringBuilder sb = new StringBuilder();
                for (;;) {
                    sb.append(missingIds.next());
                    if (!missingIds.hasNext()) {
                        break;
                    }
                    sb.append(",");
                }
                System.err.println("*** Missing ids: " + sb.toString());
            }
        }
        imap.logout();
        imap.disconnect();
    }
    if (chunkListener != null) {
        System.out.println("Processed " + chunkListener.total + " messages.");
    }
    if (maxIndexInFolder != null) {
        System.out.println("Folder contained " + maxIndexInFolder + " messages.");
    }
}

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

/** Die Eingabe besteht aus 2 Parameter: [0] Original-Ordner [1] Replica-Ordner
 * //from   w w  w. java 2s.  c  om
 * @param args
 * @throws IOException */

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

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

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

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

    File directoryOfLogfile = new File(pathToLogfile);

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

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

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

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

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

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

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

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

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

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

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

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

    File tmpDir = new File(pathToWorkDir);

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

    // Im Pfad keine Sonderzeichen Programme knnen evtl abstrzen

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

    String name = tmpDir.getAbsolutePath();

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

        Matcher matcher = pattern.matcher(element);

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

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

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

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

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

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

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

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

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

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

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

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

            factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

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

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

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

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

                        countVal = countVal + 1;

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

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

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

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

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

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

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

            factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

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

From source file:com.g2inc.scap.library.domain.SCAPContentManager.java

/**
 * A main method only used for testing//from   w w w.  j a  v a 2 s . co m
 *
 * @param args Command-line arguments
 * 
*/
public static void main(String[] args) throws Exception {
    BasicConfigurator.configure();
    LOG.trace("SchemaParser starting, schemaVersion =" + args[0] + ", xsd File=" + args[1]);
    File xsdFile = new File(args[1]);
    if (!xsdFile.exists()) {
        LOG.error("Usage: java SchemaParser <name of xsd file>");
    }
    SCAPDocumentTypeEnum version = SCAPDocumentTypeEnum.valueOf(args[0]);
    SCAPContentManager mgr = SCAPContentManager.getInstance(new File(args[1]));

    // schema-related data should now be populated
    List<String> platformTypes = mgr.getValidPlatforms(version);
    LOG.trace("STARTING PLATFORMS");
    for (int i = 0; i < platformTypes.size(); i++) {
        LOG.trace(platformTypes.get(i));
    }

    String[] platforms = { "windows", "independent" };

    List<NameDoc> list = null;
    Iterator<NameDoc> iter = null;
    LOG.trace("STARTING TESTS");
    list = mgr.getValidTestTypes(version, platforms);
    iter = list.iterator();
    while (iter.hasNext()) {
        NameDoc testName = iter.next();
        LOG.trace("\t" + testName);
    }
    LOG.trace("STARTING OBJECTS");
    list = mgr.getValidObjectTypes(version, platforms);
    iter = list.iterator();
    while (iter.hasNext()) {
        NameDoc objName = iter.next();
        LOG.trace("\t" + objName);
        LOG.trace("STARTING OBJECT ENTITIES FOR " + objName.getName());
        List<OvalEntity> entityList = mgr.getValidObjectEntityTypes(version, "windows", objName.getName());
        if (entityList != null && entityList.size() > 0) {
            for (int i = 0; i < entityList.size(); i++) {
                LOG.trace("\t\t" + entityList.get(i).toString());
            }
        }
    }

    LOG.trace("STARTING STATES");
    list = mgr.getValidStateTypes(version, platforms);
    iter = list.iterator();
    while (iter.hasNext()) {
        NameDoc stateName = iter.next();
        LOG.trace("\t" + stateName);
        LOG.trace("STARTING STATE ENTITIES FOR " + stateName.getName());
        List<OvalEntity> entityList = mgr.getValidStateEntityTypes(version, "windows", stateName.getName());
        if (entityList != null && entityList.size() > 0) {
            for (int i = 0; i < entityList.size(); i++) {
                LOG.trace("\t\t" + entityList.get(i).toString());
            }
        }
    }
}

From source file:DIA_Umpire_Quant.DIA_Umpire_Quant.java

/**
 * @param args the command line arguments
 *//* www .  ja  va 2  s. co m*/
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println("DIA-Umpire quantitation with targeted re-extraction analysis (version: "
            + UmpireInfo.GetInstance().Version + ")");
    if (args.length != 1) {
        System.out.println(
                "command format error, it should be like: java -jar -Xmx10G DIA_Umpire_Quant.jar diaumpire_quant.params");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_quant.log");
    } catch (Exception e) {
    }

    try {

        Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version);
        Logger.getRootLogger().info("Parameter file:" + args[0]);

        BufferedReader reader = new BufferedReader(new FileReader(args[0]));
        String line = "";
        String WorkFolder = "";
        int NoCPUs = 2;

        String UserMod = "";
        String Combined_Prot = "";
        String InternalLibID = "";
        String ExternalLibPath = "";
        String ExternalLibDecoyTag = "DECOY";
        boolean DefaultProtFiltering = true;
        boolean DataSetLevelPepFDR = false;
        float ProbThreshold = 0.99f;
        float ExtProbThreshold = 0.99f;
        float Freq = 0f;
        int TopNPep = 6;
        int TopNFrag = 6;
        float MinFragMz = 200f;
        String FilterWeight = "GW";
        float MinWeight = 0.9f;
        float RTWindow_Int = -1f;
        float RTWindow_Ext = -1f;

        TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
        HashMap<String, File> AssignFiles = new HashMap<>();
        boolean InternalLibSearch = false;
        boolean ExternalLibSearch = false;

        boolean ExportSaint = false;
        boolean SAINT_MS1 = false;
        boolean SAINT_MS2 = true;

        HashMap<String, String[]> BaitList = new HashMap<>();
        HashMap<String, String> BaitName = new HashMap<>();
        HashMap<String, String[]> ControlList = new HashMap<>();
        HashMap<String, String> ControlName = new HashMap<>();

        //<editor-fold defaultstate="collapsed" desc="Reading parameter file">
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            Logger.getRootLogger().info(line);
            if (!"".equals(line) && !line.startsWith("#")) {
                //System.out.println(line);
                if (line.equals("==File list begin")) {
                    do {
                        line = reader.readLine();
                        line = line.trim();
                        if (line.equals("==File list end")) {
                            continue;
                        } else if (!"".equals(line)) {
                            File newfile = new File(line);
                            if (newfile.exists()) {
                                AssignFiles.put(newfile.getAbsolutePath(), newfile);
                            } else {
                                Logger.getRootLogger().info("File: " + newfile + " does not exist.");
                            }
                        }
                    } while (!line.equals("==File list end"));
                }
                if (line.split("=").length < 2) {
                    continue;
                }
                String type = line.split("=")[0].trim();
                String value = line.split("=")[1].trim();
                switch (type) {
                case "TargetedExtraction": {
                    InternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }
                case "InternalLibSearch": {
                    InternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }
                case "ExternalLibSearch": {
                    ExternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }

                case "Path": {
                    WorkFolder = value;
                    break;
                }
                case "path": {
                    WorkFolder = value;
                    break;
                }
                case "Thread": {
                    NoCPUs = Integer.parseInt(value);
                    break;
                }
                case "Fasta": {
                    tandemPara.FastaPath = value;
                    break;
                }
                case "Combined_Prot": {
                    Combined_Prot = value;
                    break;
                }
                case "DefaultProtFiltering": {
                    DefaultProtFiltering = Boolean.parseBoolean(value);
                    break;
                }
                case "DecoyPrefix": {
                    if (!"".equals(value)) {
                        tandemPara.DecoyPrefix = value;
                    }
                    break;
                }
                case "UserMod": {
                    UserMod = value;
                    break;
                }
                case "ProteinFDR": {
                    tandemPara.ProtFDR = Float.parseFloat(value);
                    break;
                }
                case "PeptideFDR": {
                    tandemPara.PepFDR = Float.parseFloat(value);
                    break;
                }
                case "DataSetLevelPepFDR": {
                    DataSetLevelPepFDR = Boolean.parseBoolean(value);
                    break;
                }
                case "InternalLibID": {
                    InternalLibID = value;
                    break;
                }
                case "ExternalLibPath": {
                    ExternalLibPath = value;
                    break;
                }
                case "ExtProbThreshold": {
                    ExtProbThreshold = Float.parseFloat(value);
                    break;
                }
                case "RTWindow_Int": {
                    RTWindow_Int = Float.parseFloat(value);
                    break;
                }
                case "RTWindow_Ext": {
                    RTWindow_Ext = Float.parseFloat(value);
                    break;
                }
                case "ExternalLibDecoyTag": {
                    ExternalLibDecoyTag = value;
                    if (ExternalLibDecoyTag.endsWith("_")) {
                        ExternalLibDecoyTag = ExternalLibDecoyTag.substring(0,
                                ExternalLibDecoyTag.length() - 1);
                    }
                    break;
                }
                case "ProbThreshold": {
                    ProbThreshold = Float.parseFloat(value);
                    break;
                }
                case "ReSearchProb": {
                    //ReSearchProb = Float.parseFloat(value);
                    break;
                }
                case "FilterWeight": {
                    FilterWeight = value;
                    break;
                }
                case "MinWeight": {
                    MinWeight = Float.parseFloat(value);
                    break;
                }
                case "TopNFrag": {
                    TopNFrag = Integer.parseInt(value);
                    break;
                }
                case "TopNPep": {
                    TopNPep = Integer.parseInt(value);
                    break;
                }
                case "Freq": {
                    Freq = Float.parseFloat(value);
                    break;
                }
                case "MinFragMz": {
                    MinFragMz = Float.parseFloat(value);
                    break;
                }

                //<editor-fold defaultstate="collapsed" desc="SaintOutput">
                case "ExportSaintInput": {
                    ExportSaint = Boolean.parseBoolean(value);
                    break;
                }
                case "QuantitationType": {
                    switch (value) {
                    case "MS1": {
                        SAINT_MS1 = true;
                        SAINT_MS2 = false;
                        break;
                    }
                    case "MS2": {
                        SAINT_MS1 = false;
                        SAINT_MS2 = true;
                        break;
                    }
                    case "BOTH": {
                        SAINT_MS1 = true;
                        SAINT_MS2 = true;
                        break;
                    }
                    }
                    break;
                }
                //                    case "BaitInputFile": {
                //                        SaintBaitFile = value;
                //                        break;
                //                    }
                //                    case "PreyInputFile": {
                //                        SaintPreyFile = value;
                //                        break;
                //                    }
                //                    case "InterationInputFile": {
                //                        SaintInteractionFile = value;
                //                        break;
                //                    }
                default: {
                    if (type.startsWith("BaitName_")) {
                        BaitName.put(type.substring(9), value);
                    }
                    if (type.startsWith("BaitFile_")) {
                        BaitList.put(type.substring(9), value.split("\t"));
                    }
                    if (type.startsWith("ControlName_")) {
                        ControlName.put(type.substring(12), value);
                    }
                    if (type.startsWith("ControlFile_")) {
                        ControlList.put(type.substring(12), value.split("\t"));
                    }
                    break;
                }
                //</editor-fold>                    
                }
            }
        }
        //</editor-fold>

        //Initialize PTM manager using compomics library
        PTMManager.GetInstance();
        if (!UserMod.equals("")) {
            PTMManager.GetInstance().ImportUserMod(UserMod);
        }

        //Check if the fasta file can be found
        if (!new File(tandemPara.FastaPath).exists()) {
            Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath
                    + " cannot be found, the process will be terminated, please check.");
            System.exit(1);
        }

        //Check if the prot.xml file can be found
        if (!new File(Combined_Prot).exists()) {
            Logger.getRootLogger().info("ProtXML file: " + Combined_Prot
                    + " cannot be found, the export protein summary table will be empty.");
        }

        LCMSID protID = null;

        //Parse prot.xml and generate protein master list given an FDR 
        if (Combined_Prot != null && !Combined_Prot.equals("")) {
            protID = LCMSID.ReadLCMSIDSerialization(Combined_Prot);
            if (!"".equals(Combined_Prot) && protID == null) {
                protID = new LCMSID(Combined_Prot, tandemPara.DecoyPrefix, tandemPara.FastaPath);
                ProtXMLParser protxmlparser = new ProtXMLParser(protID, Combined_Prot, 0f);
                //Use DIA-Umpire default protein FDR calculation
                if (DefaultProtFiltering) {
                    protID.RemoveLowLocalPWProtein(0.8f);
                    protID.RemoveLowMaxIniProbProtein(0.9f);
                    protID.FilterByProteinDecoyFDRUsingMaxIniProb(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
                } //Get protein FDR calculation without other filtering
                else {
                    protID.FilterByProteinDecoyFDRUsingLocalPW(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
                }
                protID.LoadSequence();
                protID.WriteLCMSIDSerialization(Combined_Prot);
            }
            Logger.getRootLogger().info("Protein No.:" + protID.ProteinList.size());
        }
        HashMap<String, HashMap<String, FragmentPeak>> IDSummaryFragments = new HashMap<>();

        //Generate DIA file list
        ArrayList<DIAPack> FileList = new ArrayList<>();

        File folder = new File(WorkFolder);
        if (!folder.exists()) {
            Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found.");
            System.exit(1);
        }
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isFile()
                    && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                            | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
            }
            if (fileEntry.isDirectory()) {
                for (final File fileEntry2 : fileEntry.listFiles()) {
                    if (fileEntry2.isFile()
                            && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                                    | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                        AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                    }
                }
            }
        }

        Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
        for (File fileEntry : AssignFiles.values()) {
            Logger.getRootLogger().info(fileEntry.getAbsolutePath());
            String mzXMLFile = fileEntry.getAbsolutePath();
            if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
                DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
                FileList.add(DiaFile);
                HashMap<String, FragmentPeak> FragMap = new HashMap<>();
                IDSummaryFragments.put(FilenameUtils.getBaseName(mzXMLFile), FragMap);
                Logger.getRootLogger().info(
                        "=================================================================================================");
                Logger.getRootLogger().info("Processing " + mzXMLFile);
                if (!DiaFile.LoadDIASetting()) {
                    Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete");
                    System.exit(1);
                }
                if (!DiaFile.LoadParams()) {
                    Logger.getRootLogger().info("Loading parameters failed, job is incomplete");
                    System.exit(1);
                }
            }
        }

        LCMSID combinePepID = null;
        if (DataSetLevelPepFDR) {
            combinePepID = LCMSID.ReadLCMSIDSerialization(WorkFolder + "combinePepID.SerFS");
            if (combinePepID == null) {
                FDR_DataSetLevel fdr = new FDR_DataSetLevel();
                fdr.GeneratePepIonList(FileList, tandemPara, WorkFolder + "combinePepID.SerFS");
                combinePepID = fdr.combineID;
                combinePepID.WriteLCMSIDSerialization(WorkFolder + "combinePepID.SerFS");
            }
        }

        //process each DIA file for quantification based on untargeted identifications
        for (DIAPack DiaFile : FileList) {
            long time = System.currentTimeMillis();
            Logger.getRootLogger().info("Loading identification results " + DiaFile.Filename + "....");

            //If the LCMSID serialization is found
            if (!DiaFile.ReadSerializedLCMSID()) {
                DiaFile.ParsePepXML(tandemPara, combinePepID);
                DiaFile.BuildStructure();
                if (!DiaFile.MS1FeatureMap.ReadPeakCluster()) {
                    Logger.getRootLogger().info("Loading peak and structure failed, job is incomplete");
                    System.exit(1);
                }
                DiaFile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster();
                //Generate mapping between index of precursor feature and pseudo MS/MS scan index 
                DiaFile.GenerateClusterScanNomapping();
                //Doing quantification
                DiaFile.AssignQuant();
                DiaFile.ClearStructure();
            }
            DiaFile.IDsummary.ReduceMemoryUsage();
            time = System.currentTimeMillis() - time;
            Logger.getRootLogger().info(DiaFile.Filename + " processed time:"
                    + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time),
                            TimeUnit.MILLISECONDS.toMinutes(time)
                                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)),
                            TimeUnit.MILLISECONDS.toSeconds(time)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))));
        }

        //<editor-fold defaultstate="collapsed" desc="Targete re-extraction using internal library">            
        Logger.getRootLogger().info(
                "=================================================================================================");
        if (InternalLibSearch && FileList.size() > 1) {
            Logger.getRootLogger().info("Module C: Targeted extraction using internal library");

            FragmentLibManager libManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder,
                    InternalLibID);
            if (libManager == null) {
                Logger.getRootLogger().info("Building internal spectral library");
                libManager = new FragmentLibManager(InternalLibID);
                ArrayList<LCMSID> LCMSIDList = new ArrayList<>();
                for (DIAPack dia : FileList) {
                    LCMSIDList.add(dia.IDsummary);
                }
                libManager.ImportFragLibTopFrag(LCMSIDList, Freq, TopNFrag);
                libManager.WriteFragmentLibSerialization(WorkFolder);
            }
            libManager.ReduceMemoryUsage();

            Logger.getRootLogger()
                    .info("Building retention time prediction model and generate candidate peptide list");
            for (int i = 0; i < FileList.size(); i++) {
                FileList.get(i).IDsummary.ClearMappedPep();
            }
            for (int i = 0; i < FileList.size(); i++) {
                for (int j = i + 1; j < FileList.size(); j++) {
                    RTAlignedPepIonMapping alignment = new RTAlignedPepIonMapping(WorkFolder,
                            FileList.get(i).GetParameter(), FileList.get(i).IDsummary,
                            FileList.get(j).IDsummary);
                    alignment.GenerateModel();
                    alignment.GenerateMappedPepIon();
                }
                FileList.get(i).ExportID();
                FileList.get(i).IDsummary = null;
            }

            Logger.getRootLogger().info("Targeted matching........");
            for (DIAPack diafile : FileList) {
                if (diafile.IDsummary == null) {
                    diafile.ReadSerializedLCMSID();
                }
                if (!diafile.IDsummary.GetMappedPepIonList().isEmpty()) {
                    diafile.UseMappedIon = true;
                    diafile.FilterMappedIonByProb = false;
                    diafile.BuildStructure();
                    diafile.MS1FeatureMap.ReadPeakCluster();
                    diafile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster();
                    diafile.GenerateMassCalibrationRTMap();
                    diafile.TargetedExtractionQuant(false, libManager, 1.1f, RTWindow_Int);
                    diafile.MS1FeatureMap.ClearAllPeaks();
                    diafile.IDsummary.ReduceMemoryUsage();
                    diafile.IDsummary.RemoveLowProbMappedIon(ProbThreshold);
                    diafile.ExportID();
                    Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size()
                            + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size());
                    diafile.ClearStructure();
                }
                diafile.IDsummary = null;
                System.gc();
            }
            Logger.getRootLogger().info(
                    "=================================================================================================");
        }
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Targeted re-extraction using external library">
        //External library search
        if (ExternalLibSearch) {
            Logger.getRootLogger().info("Module C: Targeted extraction using external library");

            //Read exteranl library
            FragmentLibManager ExlibManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder,
                    FilenameUtils.getBaseName(ExternalLibPath));
            if (ExlibManager == null) {
                ExlibManager = new FragmentLibManager(FilenameUtils.getBaseName(ExternalLibPath));

                //Import traML file
                ExlibManager.ImportFragLibByTraML(ExternalLibPath, ExternalLibDecoyTag);
                //Check if there are decoy spectra
                ExlibManager.CheckDecoys();
                //ExlibManager.ImportFragLibBySPTXT(ExternalLibPath);
                ExlibManager.WriteFragmentLibSerialization(WorkFolder);
            }
            Logger.getRootLogger()
                    .info("No. of peptide ions in external lib:" + ExlibManager.PeptideFragmentLib.size());
            for (DIAPack diafile : FileList) {
                if (diafile.IDsummary == null) {
                    diafile.ReadSerializedLCMSID();
                }
                //Generate RT mapping
                RTMappingExtLib RTmap = new RTMappingExtLib(diafile.IDsummary, ExlibManager,
                        diafile.GetParameter());
                RTmap.GenerateModel();
                RTmap.GenerateMappedPepIon();

                diafile.BuildStructure();
                diafile.MS1FeatureMap.ReadPeakCluster();
                diafile.GenerateMassCalibrationRTMap();
                //Perform targeted re-extraction
                diafile.TargetedExtractionQuant(false, ExlibManager, ProbThreshold, RTWindow_Ext);
                diafile.MS1FeatureMap.ClearAllPeaks();
                diafile.IDsummary.ReduceMemoryUsage();
                //Remove target IDs below the defined probability threshold
                diafile.IDsummary.RemoveLowProbMappedIon(ExtProbThreshold);
                diafile.ExportID();
                diafile.ClearStructure();
                Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size()
                        + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size());
            }
        }
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Peptide and fragment selection">
        Logger.getRootLogger().info("Peptide and fragment selection across the whole dataset");
        ArrayList<LCMSID> SummaryList = new ArrayList<>();
        for (DIAPack diafile : FileList) {
            if (diafile.IDsummary == null) {
                diafile.ReadSerializedLCMSID();
                diafile.IDsummary.ClearAssignPeakCluster();
                //diafile.IDsummary.ClearPSMs();                    
            }
            if (protID != null) {
                //Generate protein list according to mapping of peptide ions for each DIA file to the master protein list
                diafile.IDsummary.GenerateProteinByRefIDByPepSeq(protID, true);
                diafile.IDsummary.ReMapProPep();
            }
            if ("GW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByGroupWeight();
            } else if ("PepW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByWeight();
            }
            SummaryList.add(diafile.IDsummary);
        }
        FragmentSelection fragselection = new FragmentSelection(SummaryList);
        fragselection.freqPercent = Freq;
        fragselection.MinFragMZ = MinFragMz;
        fragselection.GeneratePepFragScoreMap();
        fragselection.GenerateTopFragMap(TopNFrag);
        fragselection.GenerateProtPepScoreMap(MinWeight);
        fragselection.GenerateTopPepMap(TopNPep);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Writing general reports">                 
        ExportTable export = new ExportTable(WorkFolder, SummaryList, IDSummaryFragments, protID,
                fragselection);
        export.Export(TopNPep, TopNFrag, Freq);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="//<editor-fold defaultstate="collapsed" desc="Generate SAINT input files">
        if (ExportSaint && protID != null) {
            HashMap<String, DIAPack> Filemap = new HashMap<>();
            for (DIAPack DIAfile : FileList) {
                Filemap.put(DIAfile.GetBaseName(), DIAfile);
            }

            FileWriter baitfile = new FileWriter(WorkFolder + "SAINT_Bait_" + DateTimeTag.GetTag() + ".txt");
            FileWriter preyfile = new FileWriter(WorkFolder + "SAINT_Prey_" + DateTimeTag.GetTag() + ".txt");
            FileWriter interactionfileMS1 = null;
            FileWriter interactionfileMS2 = null;
            if (SAINT_MS1) {
                interactionfileMS1 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS1_" + DateTimeTag.GetTag() + ".txt");
            }
            if (SAINT_MS2) {
                interactionfileMS2 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS2_" + DateTimeTag.GetTag() + ".txt");
            }
            HashMap<String, String> PreyID = new HashMap<>();

            for (String samplekey : ControlName.keySet()) {
                String name = ControlName.get(samplekey);
                for (String file : ControlList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "C\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            for (String samplekey : BaitName.keySet()) {
                String name = BaitName.get(samplekey);
                for (String file : BaitList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "T\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            baitfile.close();
            if (SAINT_MS1) {
                interactionfileMS1.close();
            }
            if (SAINT_MS2) {
                interactionfileMS2.close();
            }
            for (String AccNo : PreyID.keySet()) {
                preyfile.write(AccNo + "\t" + PreyID.get(AccNo) + "\n");
            }
            preyfile.close();
        }

        //</editor-fold>

        Logger.getRootLogger().info("Job done");
        Logger.getRootLogger().info(
                "=================================================================================================");

    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:au.org.ala.delta.key.Key.java

/**
 * @param args//from w w  w  .j a  v a2s.  c o  m
 *            specifies the name of the input file to use.
 */
public static void main(String[] args) throws Exception {

    System.out.println(generateCreditsString());

    File f = handleArgs(args);
    if (!f.exists()) {
        Logger.log("File %s does not exist!", f.getName());
        return;
    }

    new Key(f).calculateKey();
}

From source file:gr.omadak.leviathan.asp.AspParser.java

public static void main(String[] args) {
    File bDir = null;/*from ww w  . j av a  2s .  c  o  m*/
    File oDir = null;
    File sDir = null;
    boolean gSource = true;
    boolean defaultVB = true;
    int i = 0;
    int argCount = args.length;
    while (i < argCount) {
        if (i < argCount - 1) {
            if (args[i].equals("-o")) {
                oDir = new File(args[++i]);
            } else if (args[i].equals("-b")) {
                bDir = new File(args[++i]);
            } else if (args[i].equals("-s")) {
                sDir = new File(args[++i]);
            }
        }
        if (args[i].equals("-ng")) {
            gSource = false;
        } else if (args[i].equals("-js")) {
            defaultVB = false;
        }
        i++;
    }
    boolean oDirValid = oDir != null && (!oDir.exists() || oDir.isDirectory());
    boolean bDirValid = bDir != null && bDir.isDirectory();
    boolean isValid = oDirValid && bDirValid;
    if (isValid && sDir == null) {
        sDir = bDir;
    }
    if (!isValid) {
        System.err.println("Usage:AspParser -b <base directory> "
                + "-o <output directory> [-s <source directory> -g -ng -vb -js]\n"
                + "base directory: the directory where virtual root exists.\n"
                + "eg <!--#include virtual=\"/someFile.asp\"-->\noutput directory"
                + ": the directory where generated files will be placed in\n"
                + "source directory: the root directory where sources are\nIf not "
                + "defined then the base directory is used\n" + "-ng disables source production\n"
                + "-js if an asp page has not defined the langugae asume is js");
        if (!oDirValid) {
            if (oDir == null) {
                System.err.println("Output directory is not defined");
            } else {
                System.err.println("Output directory:" + oDir + " can not be used");
            }
        }
        if (!bDirValid) {
            if (bDir == null) {
                System.err.println("Base directory is not defined");
            } else {
                System.err.println("Base directory:" + bDir + " does not exist or is not a directory");
            }
        }
        System.exit(1);
    }
    AspParser parser = new AspParser(bDir, oDir);
    parser.setGenerateCode(gSource);
    parser.parseDir(sDir, defaultVB);
    System.exit(0);
}

From source file:com.seanmadden.fast.ldap.main.Main.java

/**
 * The Main Event.//from   www .j  a va  2  s  . com
 * 
 * @param args
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    BasicConfigurator.configure();
    log.debug("System initializing");
    try {
        Logger.getRootLogger().addAppender(
                new FileAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), "log.log"));
    } catch (IOException e1) {
        log.error("Unable to open the log file..?");
    }

    /*
     * Initialize the configuration engine.
     */
    XMLConfiguration config = new XMLConfiguration();
    config.setListDelimiter('|');

    /*
     * Initialize the Command-Line parsing engine.
     */
    CommandLineParser parser = new PosixParser();
    Options opts = new Options();
    opts.addOption(OptionBuilder.withLongOpt("config-file").hasArg()
            .withDescription("The configuration file to load").withArgName("config.xml").create("c"));

    opts.addOption(OptionBuilder.withLongOpt("profile").hasArg().withDescription("The profile to use")
            .withArgName("Default").create("p"));

    opts.addOption(OptionBuilder.withLongOpt("password").hasArg().withDescription("Password to connect with")
            .withArgName("password").create("P"));

    opts.addOption(OptionBuilder.withLongOpt("debug").hasArg(false).create('d'));

    opts.addOption(OptionBuilder.withLongOpt("verbose").hasArg(false).create('v'));

    File configurationFile = new File("config.xml");

    try {
        // Parse the command-line options
        CommandLine cmds = parser.parse(opts, args);

        if (!cmds.hasOption('p')) {
            Logger.getRootLogger().addAppender(new GuiErrorAlerter(Level.ERROR));
        }

        Logger.getRootLogger().setLevel(Level.ERROR);
        if (cmds.hasOption('v')) {
            Logger.getRootLogger().setLevel(Level.INFO);
        }
        if (cmds.hasOption('d')) {
            Logger.getRootLogger().setLevel(Level.DEBUG);
        }

        log.debug("Enabling configuration file parsing");
        // The user has given us a file to parse.
        if (cmds.hasOption("c")) {
            configurationFile = new File(cmds.getOptionValue("c"));
        }
        log.debug("Config file: " + configurationFile);

        // Load the configuration file
        if (configurationFile.exists()) {
            config.load(configurationFile);
        } else {
            log.error("Cannot find config file");
        }

        /*
         * Convert the profiles into memory
         */
        Vector<ConnectionProfile> profs = new Vector<ConnectionProfile>();
        List<?> profList = config.configurationAt("Profiles").configurationsAt("Profile");
        for (Object p : profList) {
            SubnodeConfiguration profile = (SubnodeConfiguration) p;
            String name = profile.getString("[@name]");
            String auth = profile.getString("LdapAuthString");
            String server = profile.getString("LdapServerString");
            String group = profile.getString("LdapGroupsLocation");
            ConnectionProfile prof = new ConnectionProfile(name, server, auth, group);
            profs.add(prof);
        }
        ConnectionProfile prof = null;
        if (!cmds.hasOption('p')) {
            /*
             * Deploy the profile selector, to select a profile
             */
            ProfileSelector profSel = new ProfileSelector(profs);
            prof = profSel.getSelection();
            if (prof == null) {
                return;
            }
            /*
             * Empty the profiles and load a clean copy - then save it back
             * to the file
             */
            config.clearTree("Profiles");
            for (ConnectionProfile p : profSel.getProfiles()) {
                config.addProperty("Profiles.Profile(-1)[@name]", p.getName());
                config.addProperty("Profiles.Profile.LdapAuthString", p.getLdapAuthString());
                config.addProperty("Profiles.Profile.LdapServerString", p.getLdapServerString());
                config.addProperty("Profiles.Profile.LdapGroupsLocation", p.getLdapGroupsString());
            }
            config.save(configurationFile);
        } else {
            for (ConnectionProfile p : profs) {
                if (p.getName().equals(cmds.getOptionValue('p'))) {
                    prof = p;
                    break;
                }
            }
        }

        log.info("User selected " + prof);

        String password = "";
        if (cmds.hasOption('P')) {
            password = cmds.getOptionValue('P');
        } else {
            password = PasswordPrompter.promptForPassword("Password?");
        }

        if (password.equals("")) {
            return;
        }

        LdapInterface ldap = new LdapInterface(prof.getLdapServerString(), prof.getLdapAuthString(),
                prof.getLdapGroupsString(), password);

        /*
         * Gather options information from the configuration engine for the
         * specified report.
         */
        Hashtable<String, Hashtable<String, ReportOption>> reportDataStructure = new Hashtable<String, Hashtable<String, ReportOption>>();
        List<?> repConfig = config.configurationAt("Reports").configurationsAt("Report");
        for (Object p : repConfig) {
            SubnodeConfiguration repNode = (SubnodeConfiguration) p;

            // TODO Do something with the report profile.
            // Allowing the user to deploy "profiles" is a nice feature
            // String profile = repNode.getString("[@profile]");

            String reportName = repNode.getString("[@report]");
            Hashtable<String, ReportOption> reportOptions = new Hashtable<String, ReportOption>();
            reportDataStructure.put(reportName, reportOptions);
            // Loop through the options and add each to the table.
            for (Object o : repNode.configurationsAt("option")) {
                SubnodeConfiguration option = (SubnodeConfiguration) o;
                String name = option.getString("[@name]");
                String type = option.getString("[@type]");
                String value = option.getString("[@value]");

                ReportOption ro = new ReportOption();
                ro.setName(name);

                if (type.toLowerCase().equals("boolean")) {
                    ro.setBoolValue(Boolean.parseBoolean(value));
                } else if (type.toLowerCase().equals("integer")) {
                    ro.setIntValue(Integer.valueOf(value));
                } else {
                    // Assume a string type here then.
                    ro.setStrValue(value);
                }
                reportOptions.put(name, ro);
                log.debug(ro);
            }
        }
        System.out.println(reportDataStructure);

        /*
         * At this point, we now need to deploy the reports window to have
         * the user pick a report and select some happy options to allow
         * that report to work. Let's go.
         */
        /*
         * Deploy the Reports selector, to select a report
         */
        Reports.getInstance().setLdapConnection(ldap);
        ReportsWindow reports = new ReportsWindow(Reports.getInstance().getAllReports(), reportDataStructure);
        Report report = reports.getSelection();
        if (report == null) {
            return;
        }
        /*
         * Empty the profiles and load a clean copy - then save it back to
         * the file
         */
        config.clearTree("Reports");
        for (Report r : Reports.getInstance().getAllReports()) {
            config.addProperty("Reports.Report(-1)[@report]", r.getClass().getCanonicalName());
            config.addProperty("Reports.Report[@name]", "Standard");
            for (ReportOption ro : r.getOptions().values()) {
                config.addProperty("Reports.Report.option(-1)[@name]", ro.getName());
                config.addProperty("Reports.Report.option[@type]", ro.getType());
                config.addProperty("Reports.Report.option[@value]", ro.getStrValue());
            }
        }
        config.save(configurationFile);
        ProgressBar bar = new ProgressBar();
        bar.start();
        report.execute();
        ASCIIFormatter format = new ASCIIFormatter();
        ReportResult res = report.getResult();
        format.format(res, new File(res.getForName() + "_" + res.getReportName() + ".txt"));
        bar.stop();

        JOptionPane.showMessageDialog(null,
                "The report is at " + res.getForName() + "_" + res.getReportName() + ".txt", "Success",
                JOptionPane.INFORMATION_MESSAGE);

    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FAST Ldap Searcher", opts);
    } catch (ConfigurationException e) {
        e.printStackTrace();
        log.fatal("OH EM GEES!  Configuration errors.");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.maxl.java.aips2xml.Aips2Xml.java

public static void main(String[] args) {
    Options options = new Options();
    addOption(options, "help", "print this message", false, false);
    addOption(options, "version", "print the version information and exit", false, false);
    addOption(options, "quiet", "be extra quiet", false, false);
    addOption(options, "verbose", "be extra verbose", false, false);
    addOption(options, "zip", "generate zip file", false, false);
    addOption(options, "lang", "use given language", true, false);
    addOption(options, "alpha", "only include titles which start with option value", true, false);
    addOption(options, "nodown", "no download, parse only", false, false);

    commandLineParse(options, args);// w  ww  .ja va2s  . c  o  m

    // Download all files and save them in appropriate directories
    if (DOWNLOAD_ALL) {
        System.out.println("");
        allDown();
    }

    DateFormat df = new SimpleDateFormat("ddMMyy");
    String date_str = df.format(new Date());

    System.out.println("");
    if (!DB_LANGUAGE.isEmpty()) {
        extractPackageInfo();

        List<MedicalInformations.MedicalInformation> med_list = readAipsFile();

        if (SHOW_LOGS) {
            System.out.println("");
            System.out.println("- Generating xml and html files ... ");
        }
        long startTime = System.currentTimeMillis();
        int counter = 0;
        String fi_complete_xml = "";
        for (MedicalInformations.MedicalInformation m : med_list) {
            if (m.getLang().equals(DB_LANGUAGE) && m.getType().equals("fi")) {
                if (m.getTitle().startsWith(MED_TITLE)) {
                    if (SHOW_LOGS)
                        System.out.println(++counter + ": " + m.getTitle());
                    String[] html_str = extractHtmlSection(m);
                    // html_str[0] -> registration numbers
                    // html_str[1] -> content string
                    String xml_str = convertHtmlToXml(m.getTitle(), html_str[1], html_str[0]);
                    if (DB_LANGUAGE.equals("de")) {
                        if (!html_str[0].isEmpty()) {
                            String name = m.getTitle();
                            // Replace all "Sonderzeichen"
                            name = name.replaceAll("[/%:]", "_");
                            writeToFile(html_str[1], "./fis/fi_de_html/", name + "_fi_de.html");
                            writeToFile(xml_str, "./fis/fi_de_xml/", name + "_fi_de.xml");
                            fi_complete_xml += (xml_str + "\n");
                        }
                    } else if (DB_LANGUAGE.equals("fr")) {
                        if (!html_str[0].isEmpty()) {
                            String name = m.getTitle();
                            // Replace all "Sonderzeichen"
                            name = name.replaceAll("[/%:]", "_");
                            writeToFile(html_str[1], "./fis/fi_fr_html/", name + "_fi_fr.html");
                            writeToFile(xml_str, "./fis/fi_fr_xml/", name + "_fi_fr.xml");
                            fi_complete_xml += (xml_str + "\n");
                        }
                    }
                }
            }
        }

        // Add header to huge xml
        fi_complete_xml = addHeaderToXml(fi_complete_xml);
        // Dump to file
        if (DB_LANGUAGE.equals("de")) {
            writeToFile(fi_complete_xml, "./fis/", "fi_de.xml");
            if (ZIP_XML)
                zipToFile("./fis/", "fi_de.xml");
        } else if (DB_LANGUAGE.equals("fr")) {
            writeToFile(fi_complete_xml, "./fis/", "fi_fr.xml");
            if (ZIP_XML)
                zipToFile("./fis/", "fi_fr.xml");
        }

        // Move stylesheet file to ./fis/ folders
        try {
            File src = new File("./css/amiko_stylesheet.css");
            File dst_de = new File("./fis/fi_de_html/");
            File dst_fr = new File("./fis/fi_fr_html/");
            if (src.exists()) {
                if (dst_de.exists())
                    FileUtils.copyFileToDirectory(src, dst_de);
                if (dst_fr.exists())
                    FileUtils.copyFileToDirectory(src, dst_fr);
            }
        } catch (IOException e) {
            // Unhandled!
        }

        if (SHOW_LOGS) {
            long stopTime = System.currentTimeMillis();
            System.out.println("- Generated " + counter + " xml and html files in "
                    + (stopTime - startTime) / 1000.0f + " sec");
        }
    }

    System.exit(0);
}