Example usage for java.io File getAbsolutePath

List of usage examples for java.io File getAbsolutePath

Introduction

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

Prototype

public String getAbsolutePath() 

Source Link

Document

Returns the absolute pathname string of this abstract pathname.

Usage

From source file:net.jradius.client.gui.JRadiusSimulator.java

/**
 * Launches this application/*from   ww w . j  av  a 2  s  . c  o m*/
 */
public static void main(String[] args) {
    System.setProperty("org.apache.commons.logging.LogFactory", "net.jradius.client.gui.LogFactory");
    if (args.length > 0) {
        String url = args[0];
        File file = new File(url);
        if (file.exists())
            url = "file:///" + file.getAbsolutePath();
        JRadiusSimulator.setConfigFileUrl(url);
    }
    JRadiusSimulator application = new JRadiusSimulator();
    application.setVisible(true);
}

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

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

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

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

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

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

    File directoryOfLogfile = new File(pathToLogfile);

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

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

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

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

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

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

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

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

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

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

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

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

    File tmpDir = new File(pathToWorkDir);

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

    // Im Pfad keine Sonderzeichen Programme knnen evtl abstrzen

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

    String name = tmpDir.getAbsolutePath();

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

        Matcher matcher = pattern.matcher(element);

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

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

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

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

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

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

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

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

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

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

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

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

            factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

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

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

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

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

                        countVal = countVal + 1;

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

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

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

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

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

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

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

            factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

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

From source file:ch.kostceco.tools.siardexcerpt.SIARDexcerpt.java

/** Die Eingabe besteht aus mind 3 Parameter: [0] Pfad zur SIARD-Datei oder Verzeichnis [1]
 * configfile [2] Modul//from  w w  w  .  j av  a  2 s.  co m
 * 
 * bersicht der Module: --init --search --extract sowie --finish
 * 
 * bei --search kommen danach noch die Suchtexte und bei --extract die Schlssel
 * 
 * @param args
 * @throws IOException */

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

    /** SIARDexcerpt: Aufbau des Tools
     * 
     * 1) init: Config Kopieren und ggf SIARD-Datei ins Workverzeichnis entpacken
     * 
     * 2) search: gemss config die Tabelle mit Suchtext befragen und Ausgabe des Resultates
     * 
     * 3) extract: mit den Keys anhand der config einen Records herausziehen und anzeigen
     * 
     * 4) finish: Config-Kopie sowie Workverzeichnis lschen */

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

    SIARDexcerpt siardexcerpt = (SIARDexcerpt) context.getBean("siardexcerpt");

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

    String module = new String(args[2]);
    File siardDatei = new File(args[0]);
    File configFile = new File(args[1]);

    /* arg 1 gibt den Pfad zur configdatei an. Da dieser in ConfigurationServiceImpl hartcodiert
     * ist, wird diese nach "configuration/SIARDexcerpt.conf.xml" kopiert. */
    File configFileHard = new File("configuration" + File.separator + "SIARDexcerpt.conf.xml");

    // excerpt ist der Standardwert wird aber anhand der config dann gesetzt
    File directoryOfOutput = new File("excerpt");

    // temp_SIARDexcerpt ist der Standardwert wird aber anhand der config dann gesetzt
    File tmpDir = new File("temp_SIARDexcerpt");

    boolean okA = false;
    boolean okB = false;
    boolean okC = false;

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

    if (module.equalsIgnoreCase("--init")) {

        /** 1) init: Config Kopieren und ggf SIARD-Datei ins Workverzeichnis entpacken
         * 
         * a) config muss existieren und SIARDexcerpt.conf.xml noch nicht
         * 
         * b) Excerptverzeichnis mit schreibrechte und ggf anlegen
         * 
         * c) Workverzeichnis muss leer sein und mit schreibrechte
         * 
         * d) SIARD-Datei entpacken
         * 
         * e) Struktur-Check SIARD-Verzeichnis
         * 
         * TODO: Erledigt */

        System.out.println("SIARDexcerpt: init");

        /** a) config muss existieren und SIARDexcerpt.conf.xml noch nicht */
        if (!configFile.exists()) {
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_CONFIGFILE_FILENOTEXISTING,
                    configFile.getAbsolutePath()));
            System.exit(1);
        }

        if (configFileHard.exists()) {
            System.out
                    .println(siardexcerpt.getTextResourceService().getText(ERROR_CONFIGFILEHARD_FILEEXISTING));
            System.exit(1);
        }
        Util.copyFile(configFile, configFileHard);

        /** b) Excerptverzeichnis mit schreibrechte und ggf anlegen */
        String pathToOutput = siardexcerpt.getConfigurationService().getPathToOutput();

        directoryOfOutput = new File(pathToOutput);

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

        // Im Logverzeichnis besteht kein Schreibrecht
        if (!directoryOfOutput.canWrite()) {
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_LOGDIRECTORY_NOTWRITABLE,
                    directoryOfOutput));
            // Lschen des configFileHard, falls eines angelegt wurde
            if (configFileHard.exists()) {
                Util.deleteDir(configFileHard);
            }
            System.exit(1);
        }

        if (!directoryOfOutput.isDirectory()) {
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_LOGDIRECTORY_NODIRECTORY));
            // Lschen des configFileHard, falls eines angelegt wurde
            if (configFileHard.exists()) {
                Util.deleteDir(configFileHard);
            }
            System.exit(1);
        }

        /** c) Workverzeichnis muss leer sein und mit schreibrechte */
        String pathToWorkDir = siardexcerpt.getConfigurationService().getPathToWorkDir();

        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) {
                    System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS,
                            pathToWorkDir));
                    // Lschen des configFileHard, falls eines angelegt wurde
                    if (configFileHard.exists()) {
                        Util.deleteDir(configFileHard);
                    }
                    System.exit(1);
                }
            }
        }
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }

        // Im Workverzeichnis besteht kein Schreibrecht
        if (!tmpDir.canWrite()) {
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_WORKDIRECTORY_NOTWRITABLE,
                    pathToWorkDir));
            // Lschen des configFileHard, falls eines angelegt wurde
            if (configFileHard.exists()) {
                Util.deleteDir(configFileHard);
            }
            System.exit(1);
        }

        /** d) SIARD-Datei entpacken */
        if (!siardDatei.exists()) {
            // SIARD-Datei existiert nicht
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_SIARDFILE_FILENOTEXISTING,
                    siardDatei.getAbsolutePath()));
            // Lschen des configFileHard, falls eines angelegt wurde
            if (configFileHard.exists()) {
                Util.deleteDir(configFileHard);
            }
            System.exit(1);
        }

        if (!siardDatei.isDirectory()) {

            /* SIARD-Datei ist eine Datei
             * 
             * Die Datei muss ins Workverzeichnis extrahiert werden. Dies erfolgt im Modul A.
             * 
             * danach der Pfad zu SIARD-Datei dorthin zeigen lassen */

            Controllerexcerpt controllerexcerpt = (Controllerexcerpt) context.getBean("controllerexcerpt");
            File siardDateiNew = new File(pathToWorkDir + File.separator + siardDatei.getName());
            okA = controllerexcerpt.executeA(siardDatei, siardDateiNew, "");

            if (!okA) {
                // SIARD Datei konte nicht entpackt werden
                System.out.println(MESSAGE_XML_MODUL_A);
                System.out.println(ERROR_XML_A_CANNOTEXTRACTZIP);

                // Lschen des Arbeitsverzeichnisses und configFileHard, falls eines angelegt wurde
                if (tmpDir.exists()) {
                    Util.deleteDir(tmpDir);
                }
                if (configFileHard.exists()) {
                    Util.deleteDir(configFileHard);
                }
                // Fehler Extraktion --> invalide
                System.exit(2);
            } else {
                @SuppressWarnings("unused")
                File siardDateiOld = siardDatei;
                siardDatei = siardDateiNew;
            }

        } else {
            /* SIARD-Datei entpackt oder Datei war bereits ein Verzeichnis.
             * 
             * Gerade bei grsseren SIARD-Dateien ist es sinnvoll an einer Stelle das ausgepackte SIARD
             * zu haben, damit diese nicht immer noch extrahiert werden muss */
        }

        /** e) Struktur-Check SIARD-Verzeichnis */
        File content = new File(siardDatei.getAbsolutePath() + File.separator + "content");
        File header = new File(siardDatei.getAbsolutePath() + File.separator + "header");
        File xsd = new File(
                siardDatei.getAbsolutePath() + File.separator + "header" + File.separator + "metadata.xsd");
        File metadata = new File(
                siardDatei.getAbsolutePath() + File.separator + "header" + File.separator + "metadata.xml");

        if (!content.exists() || !header.exists() || !xsd.exists() || !metadata.exists()) {
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_XML_B_STRUCTURE));
            // Lschen des Arbeitsverzeichnisses und configFileHard, falls eines angelegt wurde
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            if (configFileHard.exists()) {
                Util.deleteDir(configFileHard);
            }
            // Fehler Extraktion --> invalide
            System.exit(2);
        } else {
            // Struktur sieht plausibel aus, extraktion kann starten
        }

    } // End init

    if (module.equalsIgnoreCase("--search")) {

        /** 2) search: gemss config die Tabelle mit Suchtext befragen und Ausgabe des Resultates
         * 
         * a) Ist die Anzahl Parameter (mind 4) korrekt? arg4 = Suchtext
         * 
         * b) Suchtext einlesen
         * 
         * c) search.xml vorbereiten (Header) und xsl in Output kopieren
         * 
         * d) grep ausfhren
         * 
         * e) Suchergebnis speichern und anzeigen (via GUI)
         * 
         * TODO: Noch offen */

        System.out.println("SIARDexcerpt: search");

        String pathToOutput = siardexcerpt.getConfigurationService().getPathToOutput();

        directoryOfOutput = new File(pathToOutput);

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

        /** a) Ist die Anzahl Parameter (mind 4) korrekt? arg4 = Suchtext */
        if (args.length < 4) {
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_PARAMETER_USAGE));
            System.exit(1);
        }

        if (!siardDatei.isDirectory()) {
            File siardDateiNew = new File(tmpDir.getAbsolutePath() + File.separator + siardDatei.getName());
            if (!siardDateiNew.exists()) {
                System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_NOINIT));
                System.exit(1);
            } else {
                siardDatei = siardDateiNew;
            }
        }

        /** b) Suchtext einlesen */
        String searchString = new String(args[3]);

        /** c) search.xml vorbereiten (Header) und xsl in Output kopieren */
        // Zeitstempel der Datenextraktion
        java.util.Date nowStartS = new java.util.Date();
        java.text.SimpleDateFormat sdfStartS = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
        String ausgabeStartS = sdfStartS.format(nowStartS);

        /* Der SearchString kann zeichen enthalten, welche nicht im Dateinamen vorkommen drfen.
         * Entsprechend werden diese normalisiert */
        String searchStringFilename = searchString.replaceAll("/", "_");
        searchStringFilename = searchStringFilename.replaceAll(">", "_");
        searchStringFilename = searchStringFilename.replaceAll("<", "_");
        searchStringFilename = searchStringFilename.replace(".*", "_");
        searchStringFilename = searchStringFilename.replaceAll("___", "_");
        searchStringFilename = searchStringFilename.replaceAll("__", "_");

        String outDateiNameS = siardDatei.getName() + "_" + searchStringFilename + "_SIARDsearch.xml";
        outDateiNameS = outDateiNameS.replaceAll("__", "_");

        // Informationen zum Archiv holen
        String archiveS = siardexcerpt.getConfigurationService().getArchive();

        // Konfiguration des Outputs, ein File Logger wird zustzlich erstellt
        LogConfigurator logConfiguratorS = (LogConfigurator) context.getBean("logconfigurator");
        String outFileNameS = logConfiguratorS.configure(directoryOfOutput.getAbsolutePath(), outDateiNameS);
        File outFileSearch = new File(outFileNameS);
        // Ab hier kann ins Output geschrieben werden...

        // Informationen zum XSL holen
        String pathToXSLS = siardexcerpt.getConfigurationService().getPathToXSLsearch();

        File xslOrigS = new File(pathToXSLS);
        File xslCopyS = new File(directoryOfOutput.getAbsolutePath() + File.separator + xslOrigS.getName());
        if (!xslCopyS.exists()) {
            Util.copyFile(xslOrigS, xslCopyS);
        }

        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_HEADER, xslCopyS.getName()));
        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_START, ausgabeStartS));
        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_ARCHIVE, archiveS));
        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_INFO));

        /** d) search: dies ist in einem eigenen Modul realisiert */
        Controllerexcerpt controllerexcerptS = (Controllerexcerpt) context.getBean("controllerexcerpt");

        okB = controllerexcerptS.executeB(siardDatei, outFileSearch, searchString);

        /** e) Ausgabe und exitcode */
        if (!okB) {
            // Suche konnte nicht erfolgen
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_MODUL_B));
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(ERROR_XML_B_CANNOTSEARCHRECORD));
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_LOGEND));
            System.out.println(MESSAGE_XML_MODUL_B);
            System.out.println(ERROR_XML_B_CANNOTSEARCHRECORD);
            System.out.println("");

            // Lschen des Arbeitsverzeichnisses und configFileHard erfolgt erst bei schritt 4 finish

            // Fehler Extraktion --> invalide
            System.exit(2);
        } else {
            // Suche konnte durchgefhrt werden
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_LOGEND));
            // Lschen des Arbeitsverzeichnisses und configFileHard erfolgt erst bei schritt 4 finish

            // Record konnte extrahiert werden
            System.exit(0);
        }

    } // End search

    if (module.equalsIgnoreCase("--excerpt")) {

        /** 3) extract: mit den Keys anhand der config einen Records herausziehen und anzeigen
         * 
         * a) Ist die Anzahl Parameter (mind 4) korrekt? arg4 = Suchtext
         * 
         * b) extract.xml vorbereiten (Header) und xsl in Output kopieren
         * 
         * c) extraktion: dies ist in einem eigenen Modul realisiert
         * 
         * d) Ausgabe und exitcode
         * 
         * TODO: Erledigt */

        System.out.println("SIARDexcerpt: extract");

        String pathToOutput = siardexcerpt.getConfigurationService().getPathToOutput();

        directoryOfOutput = new File(pathToOutput);

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

        /** a) Ist die Anzahl Parameter (mind 4) korrekt? arg4 = Suchtext */
        if (args.length < 4) {
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_PARAMETER_USAGE));
            System.exit(1);
        }

        if (!siardDatei.isDirectory()) {
            File siardDateiNew = new File(tmpDir.getAbsolutePath() + File.separator + siardDatei.getName());
            if (!siardDateiNew.exists()) {
                System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_NOINIT));
                System.exit(1);
            } else {
                siardDatei = siardDateiNew;
            }
        }

        /** b) extract.xml vorbereiten (Header) und xsl in Output kopieren */
        // Zeitstempel der Datenextraktion
        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);

        String excerptString = new String(args[3]);
        String outDateiName = siardDatei.getName() + "_" + excerptString + "_SIARDexcerpt.xml";

        // Informationen zum Archiv holen
        String archive = siardexcerpt.getConfigurationService().getArchive();

        // Konfiguration des Outputs, ein File Logger wird zustzlich erstellt
        LogConfigurator logConfigurator = (LogConfigurator) context.getBean("logconfigurator");
        String outFileName = logConfigurator.configure(directoryOfOutput.getAbsolutePath(), outDateiName);
        File outFile = new File(outFileName);
        // Ab hier kann ins Output geschrieben werden...

        // Informationen zum XSL holen
        String pathToXSL = siardexcerpt.getConfigurationService().getPathToXSL();

        File xslOrig = new File(pathToXSL);
        File xslCopy = new File(directoryOfOutput.getAbsolutePath() + File.separator + xslOrig.getName());
        if (!xslCopy.exists()) {
            Util.copyFile(xslOrig, xslCopy);
        }

        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_HEADER, xslCopy.getName()));
        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_START, ausgabeStart));
        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_ARCHIVE, archive));
        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_INFO));

        /** c) extraktion: dies ist in einem eigenen Modul realisiert */
        Controllerexcerpt controllerexcerpt = (Controllerexcerpt) context.getBean("controllerexcerpt");

        okC = controllerexcerpt.executeC(siardDatei, outFile, excerptString);

        /** d) Ausgabe und exitcode */
        if (!okC) {
            // Record konnte nicht extrahiert werden
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_MODUL_C));
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(ERROR_XML_C_CANNOTEXTRACTRECORD));
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_LOGEND));
            System.out.println(MESSAGE_XML_MODUL_C);
            System.out.println(ERROR_XML_C_CANNOTEXTRACTRECORD);
            System.out.println("");

            // Lschen des Arbeitsverzeichnisses und configFileHard erfolgt erst bei schritt 4 finish

            // Fehler Extraktion --> invalide
            System.exit(2);
        } else {
            // Record konnte extrahiert werden
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_LOGEND));
            // Lschen des Arbeitsverzeichnisses und configFileHard erfolgt erst bei schritt 4 finish

            // Record konnte extrahiert werden
            System.exit(0);

        }

    } // End extract

    if (module.equalsIgnoreCase("--finish")) {

        /** 4) finish: Config-Kopie sowie Workverzeichnis lschen
         * 
         * TODO: Erledigt */

        System.out.println("SIARDexcerpt: finish");

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

    } // End finish

}

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

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

    Createdoc tmp = new Createdoc();
    /*----------------------------
      get options from ini-file/*from   w ww  .  j  a va  2  s  .  c om*/
    ----------------------------*/
    File installDir = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Createdoc.class) + "/..");

    File inifile = new java.io.File(installDir.getAbsolutePath() + "/etc/pkraft-createdoc.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);
    }

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

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

    Option oformat = OptionBuilder.withArgName("format").hasArg()
            .withDescription("[mandatory, default=pdf] output format (pdf|pptx) ").create("format");

    Option ooutput = OptionBuilder.withArgName("output").hasArg().withDescription(
            "[mandatory, default=out.<format>] output file with full documentation of process definition")
            //            .isRequired()
            .create("output");

    ////      Option property = OptionBuilder.withArgName( "property=value" )
    ////            .hasArgs(2)
    ////            .withValueSeparator()
    ////            .withDescription( "use value for given property" )
    ////            .create("D");
    //      
    //      /*----------------------------
    //        create options object
    //      ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(odefinition);
    options.addOption(oformat);
    options.addOption(ooutput);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    line = parser.parse(options, args);

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

    if (line.hasOption("v")) {
        System.out.println("web:     www.prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }

    /*----------------------------
      die variablen festlegen
    ----------------------------*/
    int error = 0;
    String definition = null;
    String format = null;
    String output = null;

    // festlegen von definition
    if (line.hasOption("definition")) {
        definition = line.getOptionValue("definition");
        if (!(new java.io.File(definition).exists())) {
            System.err.println("file does not exist " + definition);
        }
    } else {
        System.err.println("parameter -definition is mandatory");
        error++;
    }

    // festlegen von format
    if (line.hasOption("format")) {
        if (line.getOptionValue("format").matches("pdf|pptx")) {
            format = line.getOptionValue("format");
        } else {
            System.err.println("for -format use only pdf|pptx");
            error++;
        }
    } else {
        format = "pdf";
    }

    // festlegen von output
    if (line.hasOption("output")) {
        output = line.getOptionValue("output");
    } else {
        output = "out." + format;
    }

    // feststellen ob output bereits existiert
    if (new java.io.File(output).exists()) {
        System.err.println("output already exists: " + output);
        error++;
    }

    // aussteigen, falls fehler aufgetaucht sind
    if (error > 0) {
        System.err.println("error(s) occured. try -help for help.");
        System.exit(1);
    }

    /*----------------------------
      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()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    Process process = new Process();
    Reporter report;

    process.setInfilexml(definition);

    System.out.println("info: reading process definition " + definition);

    try {
        process.readXml();
        process.setStepRanks();
    }

    catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //festlegen des temporaeren verzeichnisses fuer die Daten und Pfade erzeugen
    long jetztMillis = System.currentTimeMillis();
    String randomPathJasperFilled = "/tmp/" + jetztMillis + "_jasperFilled";
    String randomPathPng = "/tmp/" + jetztMillis + "_png";
    String randomPathPdf = "/tmp/" + jetztMillis + "_pdf";
    String randomPathPptx = "/tmp/" + jetztMillis + "_pptx";

    new File(randomPathJasperFilled).mkdirs();
    new File(randomPathPng).mkdirs();
    new File(randomPathPdf).mkdirs();
    new File(randomPathPptx).mkdirs();

    //////////////////////////////////////////

    // erstellen der Bilder

    // konfigurieren der processing ansicht
    //      PmodelViewPage page = new PmodelViewPage(process);
    PmodelViewPage page = new PmodelViewPage();
    page.einstellungen.getProcess().setStepRanks();
    page.einstellungen.setSize(100);
    page.einstellungen.setZoom(100);
    //      page.einstellungen.setZoom(8 * 100/process.getMaxLevel());
    page.einstellungen.setTextsize(0);
    page.einstellungen.setRanksize(7);
    page.einstellungen.setWidth(2500);
    page.einstellungen.setHeight(750);
    page.einstellungen.setGravx(10);
    page.einstellungen.setGravy(0);
    page.einstellungen.setRootpositionratiox((float) 0.05);
    page.einstellungen.setRootpositionratioy((float) 0.5);
    page.einstellungen.setProcess(process);

    createContents(page);

    // mit open kann die page angezeigt werden
    if (!(produktiv)) {
        open();
    }

    //      // warten
    //      System.out.println("stabilisierung ansicht: 5 sekunden warten gravitation = "+page.einstellungen.getGravx());
    //      long jetzt5 = System.currentTimeMillis();
    //      while (System.currentTimeMillis() < jetzt5 + 5000)
    //      {
    //         
    //      }
    //
    //      page.einstellungen.setGravx(10);
    //
    // warten
    int wartezeitSeconds = 1;
    if (produktiv) {
        wartezeitSeconds = page.einstellungen.getProcess().getStep().size() * 2;
    }
    System.out.println("stabilisierung ansicht: " + wartezeitSeconds + " sekunden warten gravitation = "
            + page.einstellungen.getGravx());
    long jetzt6 = System.currentTimeMillis();
    while (System.currentTimeMillis() < jetzt6 + (wartezeitSeconds * 1000)) {

    }

    page.einstellungen.setFix(true);

    // VORBEREITUNG) bild speichern
    processTopologyImagePath = randomPathPng + "/processTopology.png";
    page.savePic(processTopologyImagePath);
    // zuerst 1 sekunde warten, dann autocrop
    long jetzt = System.currentTimeMillis();
    while (System.currentTimeMillis() < jetzt + 1000) {

    }
    new AutoCropBorder(processTopologyImagePath);

    // VORBEREITUNG) fuer jeden step ein bild speichern
    for (Step actualStep : process.getStep()) {

        // root ueberspringen
        //         if (actualStep.isRoot());

        String stepImagePath = randomPathPng + "/step_" + actualStep.getName() + "_Topology.png";

        // Farbe des Steps auf finished (gruen) aendern
        page.einstellungen.getProcess().getRootStep().setStatusOverwrite("waiting");
        actualStep.setStatusOverwrite("finished");

        // etwas warten, bis die farbe bezeichnet wurde
        long jetzt4 = System.currentTimeMillis();
        while (System.currentTimeMillis() < jetzt4 + 500) {

        }

        page.savePic(stepImagePath);
        // zuerst 1 sekunde warten, dann autocrop
        long jetzt3 = System.currentTimeMillis();
        while (System.currentTimeMillis() < jetzt3 + 1000) {

        }
        new AutoCropBorder(stepImagePath);

        stepTopologyImagePath.put(actualStep.getName(), stepImagePath);

        // farbe wieder auf grau aendern
        actualStep.setStatusOverwrite(null);

        System.out.println("erstelle bild fuer step: " + actualStep.getName());

        long jetzt2 = System.currentTimeMillis();
        while (System.currentTimeMillis() < jetzt2 + 1000) {

        }
    }

    page.destroy();

    //////////////////////////////////////////
    report = new Reporter();

    // P03) erstellen des p03
    System.out.println("info: generating p03.");

    String pdfPathP03 = null;
    String pptxPathP03 = null;
    String jasperPathP03 = null;
    String jasperFilledPathP03 = null;

    // P03) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p03") != null) {
        pdfPathP03 = randomPathPdf + "/p03.pdf";
        pptxPathP03 = randomPathPptx + "/p03.pptx";
        jasperPathP03 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p03");
        jasperFilledPathP03 = (randomPathJasperFilled + "/p03.jasperFilled");

        pdfRankFiles.put("0.0.03", pdfPathP03);
        pptxRankFiles.put("0.0.03", pptxPathP03);
    } else {
        System.err.println("no entry 'p03' found in ini file");
        System.exit(1);
    }

    DateFormat dateFormat = new SimpleDateFormat("dd. MM. yyyy");
    Date date = new Date();

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processDatum", dateFormat.format(date));
    report.setParameter("processArchitectLogoImagePath",
            installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "logo"));
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    try {
        report.fillReportFileToFile(jasperPathP03, jasperFilledPathP03);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP03, pdfPathP03);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP03, pptxPathP03);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //System.exit(0);

    //////////////////////////////////////////
    report = new Reporter();

    // P05) erstellen des p05
    System.out.println("info: generating p05.");

    String pdfPathP05 = null;
    String pptxPathP05 = null;
    String jasperPathP05 = null;
    String jasperFilledPathP05 = null;

    // P05) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p05") != null) {
        pdfPathP05 = randomPathPdf + "/p05.pdf";
        pptxPathP05 = randomPathPptx + "/p05.pptx";
        jasperPathP05 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p05");
        jasperFilledPathP05 = (randomPathJasperFilled + "/p05.jasperFilled");

        pdfRankFiles.put("0.0.05", pdfPathP05);
        pptxRankFiles.put("0.0.05", pptxPathP05);
    }

    else {
        System.err.println("no entry 'p05' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    try {
        report.fillReportFileToFile(jasperPathP05, jasperFilledPathP05);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP05, pdfPathP05);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP05, pptxPathP05);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //System.exit(0);

    //////////////////////////////////////////
    report = new Reporter();

    // P08) erstellen des p08
    System.out.println("info: generating p08.");

    String pdfPathP08 = null;
    String pptxPathP08 = null;
    String jasperPathP08 = null;
    String jasperFilledPathP08 = null;

    // P08) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p08") != null) {
        pdfPathP08 = randomPathPdf + "/p08.pdf";
        pptxPathP08 = randomPathPptx + "/p08.pptx";
        jasperPathP08 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p08");
        jasperFilledPathP08 = (randomPathJasperFilled + "/p08.jasperFilled");

        pdfRankFiles.put("0.0.08", pdfPathP08);
        pptxRankFiles.put("0.0.08", pptxPathP08);
    } else {
        System.err.println("no entry 'p08' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());
    report.setParameter("processDescription", process.getDescription());

    try {
        report.fillReportFileToFile(jasperPathP08, jasperFilledPathP08);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP08, pdfPathP08);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP08, pptxPathP08);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //System.exit(0);

    //////////////////////////////////////////

    report = new Reporter();

    // P10) erstellen des p10
    System.out.println("info: generating p10.");

    String pdfPathP10 = null;
    String pptxPathP10 = null;
    String jasperPathP10 = null;
    String jasperFilledPathP10 = null;

    // P10) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p10") != null) {
        pdfPathP10 = randomPathPdf + "/p10.pdf";
        pptxPathP10 = randomPathPptx + "/p10.pptx";
        jasperPathP10 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p10");
        jasperFilledPathP10 = (randomPathJasperFilled + "/p10.jasperFilled");

        pdfRankFiles.put("0.0.10", pdfPathP10);
        pptxRankFiles.put("0.0.10", pptxPathP10);
    } else {
        System.err.println("no entry 'p10' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    // rootstep holen
    Step rootStep = process.getStep(process.getRootstepname());

    // ueber alle commit iterieren
    for (Commit actualCommit : rootStep.getCommit()) {

        // ueber alle files iterieren
        for (de.prozesskraft.pkraft.File actualFile : actualCommit.getFile()) {
            HashMap<String, Object> row = new HashMap<String, Object>();

            // Spalte 'origin'
            row.put("origin", "user/cb2");

            // Spalte 'objectType'
            row.put("objectType", "file");

            // Spalte 'minOccur'
            row.put("minOccur", "" + actualFile.getMinoccur());

            // Spalte 'maxOccur'
            row.put("maxOccur", "" + actualFile.getMaxoccur());

            // Spalte 'objectKey'
            row.put("objectKey", actualFile.getKey());

            // die steps herausfinden, die dieses file benoetigen
            ArrayList<Step> allStepsThatNeedThisFileFromRoot = process.getStepWhichNeedFromRoot("file",
                    actualFile.getKey());
            String stepnameListe = "";
            for (Step actStep : allStepsThatNeedThisFileFromRoot) {
                stepnameListe += "\n=> " + actStep.getName();
            }

            // Spalte 'objectDescription'
            row.put("objectDescription", actualFile.getDescription() + stepnameListe);

            // Datensatz dem report hinzufuegen
            report.addField(row);
        }

        // ueber alle variablen iterieren
        for (de.prozesskraft.pkraft.Variable actualVariable : actualCommit.getVariable()) {
            HashMap<String, Object> row = new HashMap<String, Object>();

            // Spalte 'origin'
            row.put("origin", "user/cb2");

            // Spalte 'objectType'
            row.put("objectType", "variable");

            // Spalte 'minOccur'
            row.put("minOccur", "" + actualVariable.getMinoccur());

            // Spalte 'maxOccur'
            row.put("maxOccur", "" + actualVariable.getMaxoccur());

            // Spalte 'objectKey'
            row.put("objectKey", actualVariable.getKey());

            // die steps herausfinden, die dieses file benoetigen
            ArrayList<Step> allStepsThatNeedThisObjectFromRoot = process.getStepWhichNeedFromRoot("variable",
                    actualVariable.getKey());
            String stepnameListe = "";
            for (Step actStep : allStepsThatNeedThisObjectFromRoot) {
                stepnameListe += "\n=> " + actStep.getName();
            }

            // Spalte 'objectDescription'
            row.put("objectDescription", actualVariable.getDescription() + stepnameListe);

            // Datensatz dem report hinzufuegen
            report.addField(row);
        }

    }

    try {
        report.fillReportFileToFile(jasperPathP10, jasperFilledPathP10);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP10, pdfPathP10);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP10, pptxPathP10);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //////////////////////////////////////////

    report = new Reporter();

    // P20) erstellen des p20
    System.out.println("info: generating p20.");

    String pdfPathP20 = null;
    String pptxPathP20 = null;
    String jasperPathP20 = null;
    String jasperFilledPathP20 = null;

    // P20) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p20") != null) {
        pdfPathP20 = randomPathPdf + "/p20.pdf";
        pptxPathP20 = randomPathPptx + "/p20.pptx";
        jasperPathP20 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p20");
        jasperFilledPathP20 = (randomPathJasperFilled + "/p20.jasperFilled");

        pdfRankFiles.put("0.0.20", pdfPathP20);
        pptxRankFiles.put("0.0.20", pptxPathP20);
    } else {
        System.err.println("no entry 'p20' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    // ueber alle steps iterieren (ausser root)
    for (Step actualStep : (ArrayList<Step>) process.getStep()) {

        // ueberspringen wenn es sich um root handelt
        if (!(actualStep.getName().equals(process.getRootstepname()))) {
            // ueber alle commit iterieren
            for (Commit actualCommit : actualStep.getCommit()) {

                // nur die, die toroot=true ( und spaeter auch tosdm=true)
                if (actualCommit.isTorootPresent()) {
                    // ueber alle files iterieren
                    for (de.prozesskraft.pkraft.File actualFile : actualCommit.getFile()) {

                        HashMap<String, Object> row = new HashMap<String, Object>();

                        // Spalte 'destination'
                        row.put("destination", "user/cb2");

                        // Spalte 'objectType'
                        row.put("objectType", "file");

                        // Spalte 'minOccur'
                        row.put("minOccur", "" + actualFile.getMinoccur());

                        // Spalte 'maxOccur'
                        row.put("maxOccur", "" + actualFile.getMaxoccur());

                        // Spalte 'objectKey'
                        row.put("objectKey", actualFile.getKey());

                        // Spalte 'objectDescription'
                        row.put("objectDescription",
                                actualFile.getDescription() + "\n<= " + actualStep.getName());

                        // Datensatz dem report hinzufuegen
                        report.addField(row);
                    }

                    // ueber alle variablen iterieren
                    for (de.prozesskraft.pkraft.Variable actualVariable : actualCommit.getVariable()) {
                        HashMap<String, Object> row = new HashMap<String, Object>();

                        // Spalte 'objectType'
                        row.put("destination", "user/cb2");

                        // Spalte 'objectType'
                        row.put("objectType", "variable");

                        // Spalte 'minOccur'
                        row.put("minOccur", "" + actualVariable.getMinoccur());

                        // Spalte 'maxOccur'
                        row.put("maxOccur", "" + actualVariable.getMaxoccur());

                        // Spalte 'objectKey'
                        row.put("objectKey", actualVariable.getKey());

                        // Spalte 'objectDescription'
                        row.put("objectDescription",
                                actualVariable.getDescription() + "\n<= " + actualStep.getName());

                        // Datensatz dem report hinzufuegen
                        report.addField(row);
                    }
                }
            }
        }

    }

    try {
        report.fillReportFileToFile(jasperPathP20, jasperFilledPathP20);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP20, pdfPathP20);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP20, pptxPathP20);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //////////////////////////////////////////

    report = new Reporter();

    // P30) erstellen des p30
    System.out.println("info: generating p30.");

    String pdfPathP30 = null;
    String pptxPathP30 = null;
    String jasperPathP30 = null;
    String jasperFilledPathP30 = null;

    // P30) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p30") != null) {
        pdfPathP30 = randomPathPdf + "/p30.pdf";
        pptxPathP30 = randomPathPptx + "/p30.pptx";
        jasperPathP30 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p30");
        jasperFilledPathP30 = (randomPathJasperFilled + "/p30.jasperFilled");

        pdfRankFiles.put("0.0.30", pdfPathP30);
        pptxRankFiles.put("0.0.30", pptxPathP30);
    } else {
        System.err.println("no entry 'p30' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    // P1) bild an report melden
    report.setParameter("processTopologyImagePath", processTopologyImagePath);

    try {
        report.fillReportFileToFile(jasperPathP30, jasperFilledPathP30);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP30, pdfPathP30);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP30, pptxPathP30);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //      System.exit(0);
    //////////////////////////////////////////

    report = new Reporter();

    // P40) erstellen des p40
    System.out.println("info: generating p40.");

    String pdfPathP40 = null;
    String pptxPathP40 = null;
    String jasperPathP40 = null;
    String jasperFilledPathP40 = null;

    // P40) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p40") != null) {
        pdfPathP40 = randomPathPdf + "/p40.pdf";
        pptxPathP40 = randomPathPptx + "/p40.pptx";
        jasperPathP40 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p40");
        jasperFilledPathP40 = (randomPathJasperFilled + "/p40.jasperFilled");

        pdfRankFiles.put("0.0.40", pdfPathP40);
        pptxRankFiles.put("0.0.40", pptxPathP40);
    } else {
        System.err.println("no entry 'p40' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    // P40) bild an report melden
    report.setParameter("processTopologyImagePath", processTopologyImagePath);

    // Tabelle erzeugen

    ArrayList<Step> steps = process.getStep();
    for (int x = 0; x < steps.size(); x++) {
        HashMap<String, Object> row = new HashMap<String, Object>();
        Step actualStep = steps.get(x);

        // erste Spalte ist 'rank'
        // um die korrekte sortierung zu erhalten soll der rank-string auf jeweils 2 Stellen erweitert werden
        String[] rankArray = actualStep.getRank().split("\\.");
        Integer[] rankArrayInt = new Integer[rankArray.length];
        for (int y = 0; y < rankArray.length; y++) {
            rankArrayInt[y] = Integer.parseInt(rankArray[y]);
        }
        String rankFormated = String.format("%02d.%02d", rankArrayInt);
        row.put("stepRank", rankFormated);

        // zweite Spalte ist 'stepname'
        row.put("stepName", actualStep.getName());
        //            System.out.println("stepName: "+actualStep.getName());

        // dritte Spalte ist 'Beschreibung'
        row.put("stepDescription", actualStep.getDescription());
        //            System.out.println("stepRank: "+actualStep.getDescription());

        // wenn nicht der root-step, dann row eintragen
        if (!(actualStep.getName().equals(process.getRootstepname()))) {
            report.addField(row);
        }
    }

    try {
        report.fillReportFileToFile(jasperPathP40, jasperFilledPathP40);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP40, pdfPathP40);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP40, pptxPathP40);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //////////////////////////////////////////

    // fuer jeden Step einen eigenen Input Report erzeugen

    for (Step actualStep : process.getStep()) {
        // root-step ueberspringen
        if (actualStep.getName().equals(process.getRootstepname())) {
            System.out.println("skipping step root");
        }

        // alle anderen auswerten
        else {

            report = new Reporter();

            // P51x) erstellen des p51
            System.out.println(
                    "info: generating p51 for step " + actualStep.getRank() + " => " + actualStep.getName());

            String stepRank = actualStep.getRank();

            String pdfPathP51 = null;
            String pptxPathP51 = null;
            String jasperPathP51 = null;
            String jasperFilledPathP51 = null;

            // P51x) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
            if (ini.get("pkraft-createdoc", "p51") != null) {
                pdfPathP51 = randomPathPdf + "/p5." + stepRank + ".1.pdf";
                pptxPathP51 = randomPathPptx + "/p5." + stepRank + ".1.pptx";
                jasperPathP51 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p51");
                jasperFilledPathP51 = randomPathJasperFilled + "/p5." + stepRank + ".1.jasperFilled";

                String[] rankArray = stepRank.split("\\.");
                Integer[] rankArrayInt = new Integer[rankArray.length];
                for (int x = 0; x < rankArray.length; x++) {
                    rankArrayInt[x] = Integer.parseInt(rankArray[x]);
                }
                String rankFormated = String.format("%03d.%03d", rankArrayInt);

                pdfRankFiles.put(rankFormated + ".1", pdfPathP51);
                pptxRankFiles.put(rankFormated + ".1", pptxPathP51);
            } else {
                System.err.println("no entry 'p51' found in ini file");
                System.exit(1);
            }

            report.setParameter("processName", process.getName());
            report.setParameter("processVersion", process.getVersion());
            report.setParameter("processArchitectCompany", process.getArchitectCompany());
            report.setParameter("processArchitectName", process.getArchitectName());
            report.setParameter("processArchitectMail", process.getArchitectMail());
            report.setParameter("processCustomerCompany", process.getCustomerCompany());
            report.setParameter("processCustomerName", process.getCustomerName());
            report.setParameter("processCustomerMail", process.getCustomerMail());

            report.setParameter("stepName", actualStep.getName());
            report.setParameter("stepRank", stepRank);
            report.setParameter("stepDescription", actualStep.getDescription());

            String aufruf = "";
            if (actualStep.getWork() != null) {
                // zusammensetzen des scriptaufrufs
                String interpreter = "";

                if (actualStep.getWork().getInterpreter() != null) {
                    interpreter = actualStep.getWork().getInterpreter();
                }

                aufruf = interpreter + " " + actualStep.getWork().getCommand();
                for (Callitem actualCallitem : actualStep.getWork().getCallitem()) {
                    aufruf += " " + actualCallitem.getPar();
                    if (!(actualCallitem.getDel() == null)) {
                        aufruf += actualCallitem.getDel();
                    }
                    if (!(actualCallitem.getVal() == null)) {
                        aufruf += actualCallitem.getVal();
                    }
                }
            } else if (actualStep.getSubprocess() != null) {
                aufruf = ini.get("apps", "pkraft-startinstance");
                aufruf += " --pdomain " + actualStep.getSubprocess().getDomain();
                aufruf += " --pname " + actualStep.getSubprocess().getName();
                aufruf += " --pversion " + actualStep.getSubprocess().getVersion();

                for (Commit actCommit : actualStep.getSubprocess().getStep().getCommit()) {
                    for (de.prozesskraft.pkraft.File actFile : actCommit.getFile()) {
                        aufruf += " --commitfile " + actFile.getGlob();
                    }
                    for (Variable actVariable : actCommit.getVariable()) {
                        aufruf += " --commitvariable " + actVariable.getKey() + "=" + actVariable.getValue();
                    }
                }
            }
            report.setParameter("stepWorkCall", aufruf);

            // P51x) bild an report melden
            report.setParameter("stepTopologyImagePath", stepTopologyImagePath.get(actualStep.getName()));

            // ueber alle lists iterieren
            for (List actualList : actualStep.getList()) {
                HashMap<String, Object> row = new HashMap<String, Object>();

                // Spalte 'Woher?'
                row.put("origin", "-");

                // Spalte 'typ'
                row.put("objectType", "wert");

                // Spalte 'minOccur'
                row.put("minOccur", "-");

                // Spalte 'maxOccur'
                row.put("maxOccur", "-");

                // Spalte 'Label'
                row.put("objectKey", actualList.getName());

                // Spalte 'Label'
                String listString = actualList.getItem().toString();
                row.put("objectDescription", listString.substring(1, listString.length() - 1));

                report.addField(row);
            }

            // ueber alle inits iterieren
            for (Init actualInit : actualStep.getInit()) {
                HashMap<String, Object> row = new HashMap<String, Object>();

                // Spalte 'Woher?'
                if (actualInit.getFromstep().equals(process.getRootstepname())) {
                    row.put("origin", "user/cb2");
                } else {
                    row.put("origin", actualInit.getFromstep());
                }

                // Spalte 'typ'
                row.put("objectType", actualInit.getFromobjecttype());

                // Spalte 'minOccur'
                row.put("minOccur", "" + actualInit.getMinoccur());

                // Spalte 'maxOccur'
                row.put("maxOccur", "" + actualInit.getMaxoccur());

                // Spalte 'Label'
                row.put("objectKey", actualInit.getListname());

                // Spalte 'Label'
                row.put("objectDescription", "-");

                report.addField(row);
            }

            try {
                report.fillReportFileToFile(jasperPathP51, jasperFilledPathP51);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // export to pdf
            try {
                report.convertFileToPdf(jasperFilledPathP51, pdfPathP51);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // export to pptx
            try {
                report.convertFileToPptx(jasperFilledPathP51, pptxPathP51);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            report = null;
        }
    }

    //////////////////////////////////////////

    // fuer jeden Step einen eigenen Output Report erzeugen

    for (Step actualStep : process.getStep()) {
        // root-step ueberspringen
        if (actualStep.getName().equals(process.getRootstepname())) {
            System.out.println("skipping step root");
        }

        // alle anderen auswerten
        else {

            report = new Reporter();

            // P52x) erstellen des p52
            System.out.println(
                    "info: generating p52 for step " + actualStep.getRank() + " => " + actualStep.getName());

            String stepRank = actualStep.getRank();

            String pdfPathP52 = null;
            String pptxPathP52 = null;
            String jasperPathP52 = null;
            String jasperFilledPathP52 = null;

            // P52x) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
            if (ini.get("pkraft-createdoc", "p52") != null) {
                pdfPathP52 = randomPathPdf + "/p5." + stepRank + ".2.pdf";
                pptxPathP52 = randomPathPptx + "/p5." + stepRank + ".2.pptx";
                jasperPathP52 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p52");
                jasperFilledPathP52 = randomPathJasperFilled + "/p5." + stepRank + ".1.jasperFilled";

                String[] rankArray = stepRank.split("\\.");
                Integer[] rankArrayInt = new Integer[rankArray.length];
                for (int x = 0; x < rankArray.length; x++) {
                    rankArrayInt[x] = Integer.parseInt(rankArray[x]);
                }
                String rankFormated = String.format("%03d.%03d", rankArrayInt);

                pdfRankFiles.put(rankFormated + ".2", pdfPathP52);
                pptxRankFiles.put(rankFormated + ".2", pptxPathP52);
            } else {
                System.err.println("no entry 'p52' found in ini file");
                System.exit(1);
            }

            report.setParameter("processName", process.getName());
            report.setParameter("processVersion", process.getVersion());
            report.setParameter("processArchitectCompany", process.getArchitectCompany());
            report.setParameter("processArchitectName", process.getArchitectName());
            report.setParameter("processArchitectMail", process.getArchitectMail());
            report.setParameter("processCustomerCompany", process.getCustomerCompany());
            report.setParameter("processCustomerName", process.getCustomerName());
            report.setParameter("processCustomerMail", process.getCustomerMail());

            report.setParameter("stepName", actualStep.getName());
            report.setParameter("stepRank", stepRank);

            // logfile ermitteln
            String logfile = "-";
            if (actualStep.getWork() != null) {
                if (actualStep.getWork().getLogfile() == null || actualStep.getWork().getLogfile().equals("")) {
                    report.setParameter("stepWorkLogfile", actualStep.getWork().getLogfile());
                }
            } else if (actualStep.getSubprocess() != null) {
                logfile = ".log";
            }
            report.setParameter("stepWorkLogfile", logfile);

            // zusammensetzen der return/exitcode informationen
            String exitInfo = "exit 0 = kein fehler aufgetreten";
            exitInfo += "\nexit >0 = ein fehler ist aufgetreten.";
            if (actualStep.getWork() != null) {
                for (Exit actualExit : actualStep.getWork().getExit()) {
                    exitInfo += "\nexit " + actualExit.getValue() + " = " + actualExit.getMsg();
                }
            }
            report.setParameter("stepWorkExit", exitInfo);

            // P52x) bild an report melden
            report.setParameter("stepTopologyImagePath", stepTopologyImagePath.get(actualStep.getName()));

            // ueber alle inits iterieren
            for (Commit actualCommit : actualStep.getCommit()) {

                // ueber alle files iterieren
                for (de.prozesskraft.pkraft.File actualFile : actualCommit.getFile()) {

                    HashMap<String, Object> row = new HashMap<String, Object>();

                    // Spalte 'destination'
                    if (actualCommit.isTorootPresent()) {
                        row.put("destination", "user/cb2");
                    } else {
                        row.put("destination", "prozessintern");
                    }

                    // Spalte 'objectType'
                    row.put("objectType", "file");

                    // Spalte 'minOccur'
                    row.put("minOccur", "" + actualFile.getMinoccur());

                    // Spalte 'maxOccur'
                    row.put("maxOccur", "" + actualFile.getMaxoccur());

                    // Spalte 'objectKey'
                    row.put("objectKey", actualFile.getKey());

                    // Spalte 'objectDescription'
                    row.put("objectDescription", actualFile.getDescription());

                    // Datensatz dem report hinzufuegen
                    report.addField(row);
                }

                // ueber alle variablen iterieren
                for (de.prozesskraft.pkraft.Variable actualVariable : actualCommit.getVariable()) {
                    HashMap<String, Object> row = new HashMap<String, Object>();

                    // Spalte 'destination'
                    if (actualCommit.isTorootPresent()) {
                        row.put("destination", "user/cb2");
                    } else {
                        row.put("destination", "prozessintern");
                    }

                    // Spalte 'objectType'
                    row.put("objectType", "variable");

                    // Spalte 'minOccur'
                    row.put("minOccur", "" + actualVariable.getMinoccur());

                    // Spalte 'maxOccur'
                    row.put("maxOccur", "" + actualVariable.getMaxoccur());

                    // Spalte 'objectKey'
                    row.put("objectKey", actualVariable.getKey());

                    // Spalte 'objectDescription'
                    row.put("objectDescription", actualVariable.getDescription());

                    // Datensatz dem report hinzufuegen
                    report.addField(row);
                }

            }
            try {
                report.fillReportFileToFile(jasperPathP52, jasperFilledPathP52);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // export to pdf
            try {
                report.convertFileToPdf(jasperFilledPathP52, pdfPathP52);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // export to pptx
            try {
                report.convertFileToPptx(jasperFilledPathP52, pptxPathP52);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            report = null;
        }
    }

    // warten bis alles auf platte geschrieben ist
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    // merge and output
    if (format.equals("pdf")) {
        mergePdf(pdfRankFiles, output);
    } else if (format.equals("pptx")) {
        mergePptx(pptxRankFiles, output);
    }

    System.out.println("info: generating process documentation ready.");
    System.exit(0);
}

From source file:de.prozesskraft.pradar.parts.PradarPartUi3.java

/**
 * @param args/* w ww  .j a v  a2  s.c o  m*/
 */
public static void main(String[] args) {
    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(PradarPartUi3.class) + "/" + "../etc/pradar-gui.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);
    }

    /*----------------------------
      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 dbfile = OptionBuilder.withArgName("dbfile").hasArg().withDescription("[optional] dbfile")
            //            .isRequired()
            .create("dbfile");
    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(help);
    options.addOption(v);
    options.addOption(dbfile);

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

    /*----------------------------
      usage/help
    ----------------------------*/
    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        //         formatter.printHelp("checkin --version [% version %]", options);
        formatter.printHelp("pradar-gui", options);
        System.exit(0);
    }

    if (line.hasOption("v")) {
        System.out.println("author:  alexander.vogel@caegroup.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }

    /*----------------------------
      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()) {
        System.exit(1);
    }

    /*----------------------------
      other things
    ----------------------------*/

    // gui
    final Display display = new Display();

    Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
        public void run() {
            try {
                Shell shell = new Shell(display);
                shell.setText("pradar " + "[% version %]");

                // set an icon
                if (this.getClass().getResourceAsStream("/logoSymbol50Transp.png") != null) {
                    shell.setImage(
                            new Image(display, this.getClass().getResourceAsStream("/logoSymbol50Transp.png")));
                } else if ((new java.io.File("logoSymbol50Transp.png")).exists()) {
                    shell.setImage(new Image(display, "logoSymbol50Transp.png"));
                }

                shell.setLayout(new FillLayout());
                //               shell.setSize(1500, 1000);
                shell.setMaximized(true);
                Composite composite = new Composite(shell, SWT.NO_FOCUS);
                GridLayout gl_composite = new GridLayout(2, false);
                gl_composite.marginWidth = 0;
                gl_composite.marginHeight = 0;
                new PradarPartUi3(composite);

                try {
                    shell.open();

                    while (!shell.isDisposed()) {
                        if (!display.readAndDispatch()) {
                            display.sleep();
                        }
                    }

                } finally {
                    if (!shell.isDisposed()) {
                        shell.dispose();
                    }
                }

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

From source file:copi.ScalaEntryPoint.java

public static void main(String[] args) {
    /*//from w w  w.ja v a  2 s .c o m
       * Set lwjgl library path so that LWJGL finds the natives depending on
       * the OS.
       */
    File libDir = new File(path);

    if (!libDir.exists()) {
        // create native lib folder 
        libDir.mkdir();

        // retrieve os type
        String osName = System.getProperty("os.name");

        // try to determine if the system is 64 bit  
        boolean is64bit = false;
        if (System.getProperty("os.name").contains("Windows")) {
            is64bit = (System.getenv("ProgramFiles(x86)") != null);
        } else {
            is64bit = (System.getProperty("os.arch").indexOf("64") != -1);
        }

        // construct name of native lib file 
        String natLibLWJGL = "";
        if (osName.startsWith("Windows")) {
            natLibLWJGL += "lwjgl";
            if (is64bit)
                natLibLWJGL += "64";
            natLibLWJGL += ".dll";
        } else if (osName.startsWith("Linux")) {
            natLibLWJGL += "liblwjgl";
            if (is64bit)
                natLibLWJGL += "64";
            natLibLWJGL += ".so";
        } else if (osName.startsWith("Mac OS X")) {
            natLibLWJGL += "liblwjgl";
            natLibLWJGL += ".jnilib";
        } else {
            System.out.println("Unsupported OS: " + osName + ". Exiting.");
            System.exit(-1);
        }

        // try to establish an input stream on the native lib inside the jar
        InputStream fis = ScalaEntryPoint.class.getResourceAsStream("/" + natLibLWJGL);
        if (fis == null) {
            System.out.println("Native library file " + natLibLWJGL + " was not found inside JAR.");
            System.exit(-1);
        }

        // establish an output stream on the target file 
        File fOut = new File(path + "/" + natLibLWJGL);
        try (FileOutputStream fos = new FileOutputStream(fOut)) {
            // create file at destination if not already existing
            if (!fOut.exists())
                fOut.createNewFile();

            // making buffer for copy operation 
            byte[] buffer = new byte[1024];
            int readBytes;

            // Open output stream and copy data between source file in JAR and the temporary file
            try {
                while ((readBytes = fis.read(buffer)) != -1) {
                    fos.write(buffer, 0, readBytes);
                }
            } finally {
                fos.close();
                fis.close();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
            System.exit(-1);
        }

        // register shutdown hook
        JVMShutdownHook jvmShutdownHook = new JVMShutdownHook();
        Runtime.getRuntime().addShutdownHook(jvmShutdownHook);

    }

    // set lwjgl native library path
    System.setProperty("org.lwjgl.librarypath", libDir.getAbsolutePath());

    // start COPI
    System.out.println("Starting COPI ...");
    (new SICApplicationLogic()).render();
}

From source file:com.milaboratory.mitcr.cli.Main.java

public static void main(String[] args) {
    int o = 0;/*from w  w w .  j a  v a2  s . c  o m*/

    BuildInformation buildInformation = BuildInformationProvider.get();

    final boolean isProduction = "default".equals(buildInformation.scmBranch); // buildInformation.version != null && buildInformation.version.lastIndexOf("SNAPSHOT") < 0;

    orderingMap.put(PARAMETERS_SET_OPTION, o++);
    orderingMap.put(SPECIES_OPTION, o++);
    orderingMap.put(GENE_OPTION, o++);
    orderingMap.put(ERROR_CORECTION_LEVEL_OPTION, o++);
    orderingMap.put(QUALITY_THRESHOLD_OPTION, o++);
    orderingMap.put(AVERAGE_QUALITY_OPTION, o++);
    orderingMap.put(LQ_OPTION, o++);
    orderingMap.put(CLUSTERIZATION_OPTION, o++);
    orderingMap.put(INCLUDE_CYS_PHE_OPTION, o++);
    orderingMap.put(LIMIT_OPTION, o++);
    orderingMap.put(EXPORT_OPTION, o++);
    orderingMap.put(REPORT_OPTION, o++);
    orderingMap.put(REPORTING_LEVEL_OPTION, o++);
    orderingMap.put(PHRED33_OPTION, o++);
    orderingMap.put(PHRED64_OPTION, o++);
    orderingMap.put(THREADS_OPTION, o++);
    orderingMap.put(COMPRESSED_OPTION, o++);
    orderingMap.put(PRINT_HELP_OPTION, o++);
    orderingMap.put(PRINT_VERSION_OPTION, o++);
    orderingMap.put(PRINT_DEBUG_OPTION, o++);

    options.addOption(OptionBuilder.withArgName("preset name").hasArg()
            .withDescription("preset of pipeline parameters to use").create(PARAMETERS_SET_OPTION));

    options.addOption(OptionBuilder.withArgName("species").hasArg()
            .withDescription("overrides species ['hs' for Homo sapiens, 'mm' for us Mus musculus] "
                    + "(default for built-in presets is 'hs')")
            .create(SPECIES_OPTION));

    options.addOption(OptionBuilder.withArgName("gene").hasArg()
            .withDescription("overrides gene: TRB or TRA (default value for built-in parameter sets is TRB)")
            .create(GENE_OPTION));

    options.addOption(OptionBuilder.withArgName("0|1|2").hasArg()
            .withDescription(
                    "overrides error correction level (0 = don't correct errors, 1 = correct sequenecing "
                            + "errors only (see -" + QUALITY_THRESHOLD_OPTION + " and -" + LQ_OPTION
                            + " options for details), " + "2 = also correct PCR errors (see -"
                            + CLUSTERIZATION_OPTION + " option)")
            .create(ERROR_CORECTION_LEVEL_OPTION));

    options.addOption(OptionBuilder.withArgName("value").hasArg().withDescription(
            "overrides quality threshold value for segment alignment and bad quality sequences "
                    + "correction algorithms. 0 tells the program not to process quality information. (default is 25)")
            .create(QUALITY_THRESHOLD_OPTION));

    if (!isProduction)
        options.addOption(OptionBuilder.hasArg(false)
                .withDescription("use this option to output average instead of "
                        + "maximal, quality for CDR3 nucleotide sequences. (Experimental option, use with caution.)")
                .create(AVERAGE_QUALITY_OPTION));

    options.addOption(OptionBuilder.withArgName("map | drop").hasArg()
            .withDescription("overrides low quality CDR3s processing strategy (drop = filter off, "
                    + "map = map onto clonotypes created from the high quality CDR3s). This option makes no difference if "
                    + "quality threshold (-" + QUALITY_THRESHOLD_OPTION
                    + " option) is set to 0, or error correction " + "level (-" + ERROR_CORECTION_LEVEL_OPTION
                    + ") is 0.")
            .create(LQ_OPTION));

    options.addOption(OptionBuilder.withArgName("smd | ete").hasArg()
            .withDescription("overrides the PCR error correction algorithm: smd = \"save my diversity\", "
                    + "ete = \"eliminate these errors\". Default value for built-in parameters is ete.")
            .create(CLUSTERIZATION_OPTION));

    options.addOption(OptionBuilder.withArgName("0|1").hasArg()
            .withDescription("overrides weather include bounding Cys & Phe into CDR3 sequence")
            .create(INCLUDE_CYS_PHE_OPTION));

    options.addOption(
            OptionBuilder.withArgName("# of reads").hasArg()
                    .withDescription("limits the number of input sequencing reads, use this parameter to "
                            + "normalize several datasets or to have a glance at the data")
                    .create(LIMIT_OPTION));

    options.addOption(OptionBuilder.withArgName("new name").hasArg()
            .withDescription("use this option to export presets to a local xml files").create(EXPORT_OPTION));

    options.addOption(OptionBuilder.withArgName("file name").hasArg()
            .withDescription("use this option to write analysis report (summary) to file")
            .create(REPORT_OPTION));

    options.addOption(OptionBuilder.withArgName("1|2|3").hasArg(true)
            .withDescription("output detalization level (1 = simple, 2 = medium, 3 = full, this format "
                    + "could be deserialized using mitcr API). Affects only tab-delimited output. Default value is 3.")
            .create(REPORTING_LEVEL_OPTION));

    options.addOption(OptionBuilder.hasArg(false).withDescription(
            "add this option if input file is in old illumina format with 64 byte offset for quality "
                    + "string (MiTCR will try to automatically detect file format if one of the \"-phredXX\" options is not provided)")
            .create(PHRED64_OPTION));

    options.addOption(OptionBuilder.hasArg(false)
            .withDescription("add this option if input file is in Phred+33 format for quality values "
                    + "(MiTCR will try to automatically detect file format if one of the \"-phredXX\" options is not provided)")
            .create(PHRED33_OPTION));

    options.addOption(OptionBuilder.withArgName("threads").hasArg()
            .withDescription(
                    "specifies the number of CDR3 extraction threads (default = number of available CPU cores)")
            .create(THREADS_OPTION));

    if (!isProduction)
        options.addOption(OptionBuilder.hasArg(false)
                .withDescription("use compressed data structures for storing individual "
                        + "clone segments statistics (from which arises the clone segment information). This option reduces required "
                        + "amount of memory, but introduces small stochastic errors into the algorithm which determines clone "
                        + "segments. (Experimental option, use with caution.)")
                .create(COMPRESSED_OPTION));

    options.addOption(
            OptionBuilder.hasArg(false).withDescription("print this message").create(PRINT_HELP_OPTION));

    options.addOption(OptionBuilder.hasArg(false).withDescription("print version information")
            .create(PRINT_VERSION_OPTION));

    options.addOption(OptionBuilder.hasArg(false)
            .withDescription("print additional information about analysis process").create(PRINT_DEBUG_OPTION));

    PosixParser parser = new PosixParser();

    try {
        long input_limit = -1;
        int threads = Runtime.getRuntime().availableProcessors();
        int reporting_level = 3;
        int ec_level = 2;

        CommandLine cl = parser.parse(options, args, true);
        if (cl.hasOption(PRINT_HELP_OPTION)) {
            printHelp();
            return;
        }

        boolean averageQuality = cl.hasOption(AVERAGE_QUALITY_OPTION),
                compressedAggregators = cl.hasOption(COMPRESSED_OPTION);

        if (cl.hasOption(PRINT_VERSION_OPTION)) {
            System.out.println("MiTCR by MiLaboratory, version: " + buildInformation.version);
            System.out.println("Branch: " + buildInformation.scmBranch);
            System.out.println("Built: " + buildInformation.buildDate + ", " + buildInformation.jdk + " JDK, "
                    + "build machine: " + buildInformation.builtBy);
            System.out.println("SCM changeset: " + buildInformation.scmChangeset + " ("
                    + buildInformation.scmDate.replace("\"", "") + ")");
            return;
        }

        //Normal execution

        String paramName = cl.getOptionValue(PARAMETERS_SET_OPTION);

        if (paramName == null) {
            err.println("No parameters set is specified.");
            return;
        }

        Parameters params = ParametersIO.getParameters(paramName);

        if (params == null) {
            err.println("No parameters set found with name '" + paramName + "'.");
            return;
        }

        String value;

        if ((value = cl.getOptionValue(THREADS_OPTION)) != null)
            threads = Integer.decode(value);

        if ((value = cl.getOptionValue(REPORTING_LEVEL_OPTION)) != null)
            reporting_level = Integer.decode(value);

        if ((value = cl.getOptionValue(LIMIT_OPTION)) != null)
            input_limit = Long.decode(value);

        if ((value = cl.getOptionValue(GENE_OPTION)) != null)
            params.setGene(Gene.fromXML(value));

        if ((value = cl.getOptionValue(SPECIES_OPTION)) != null)
            params.setSpecies(Species.getFromShortName(value));

        if ((value = cl.getOptionValue(INCLUDE_CYS_PHE_OPTION)) != null) {
            if (value.equals("1"))
                params.getCDR3ExtractorParameters().setIncludeCysPhe(true);
            else if (value.equals("0"))
                params.getCDR3ExtractorParameters().setIncludeCysPhe(false);
            else {
                err.println("Illegal value for -" + INCLUDE_CYS_PHE_OPTION + " parameter.");
                return;
            }
        }

        if ((value = cl.getOptionValue(ERROR_CORECTION_LEVEL_OPTION)) != null) {
            int v = Integer.decode(value);
            ec_level = v;
            if (v == 0) {
                params.setCloneGeneratorParameters(new BasicCloneGeneratorParameters());
                params.setClusterizationType(CloneClusterizationType.None);
            } else if (v == 1) {
                params.setCloneGeneratorParameters(new LQMappingCloneGeneratorParameters());
                params.setClusterizationType(CloneClusterizationType.None);
            } else if (v == 2) {
                params.setCloneGeneratorParameters(new LQMappingCloneGeneratorParameters());
                params.setClusterizationType(CloneClusterizationType.OneMismatch, .1f);
            } else
                throw new RuntimeException("This (" + v + ") error correction level is not supported.");
        }

        if ((value = cl.getOptionValue(QUALITY_THRESHOLD_OPTION)) != null) {
            int v = Integer.decode(value);
            if (v == 0)
                params.setQualityInterpretationStrategy(new DummyQualityInterpretationStrategy());
            else
                params.setQualityInterpretationStrategy(new IlluminaQualityInterpretationStrategy((byte) v));
        }

        if ((value = cl.getOptionValue(LQ_OPTION)) != null)
            if (ec_level > 0)
                switch (value) {
                case "map":
                    params.setCloneGeneratorParameters(new LQMappingCloneGeneratorParameters(
                            ((BasicCloneGeneratorParameters) params.getCloneGeneratorParameters())
                                    .getSegmentInformationAggregationFactor(),
                            3, true));
                    break;
                case "drop":
                    params.setCloneGeneratorParameters(new LQFilteringOffCloneGeneratorParameters(
                            ((BasicCloneGeneratorParameters) params.getCloneGeneratorParameters())
                                    .getSegmentInformationAggregationFactor()));
                    break;
                default:
                    throw new RuntimeException("Wrong value for -" + LQ_OPTION + " option.");
                }

        if ((value = cl.getOptionValue(CLUSTERIZATION_OPTION)) != null)
            if (ec_level > 1) // == 2
                switch (value) {
                case "smd":
                    params.setClusterizationType(CloneClusterizationType.V2D1J2T3Explicit);
                    break;
                case "ete":
                    params.setClusterizationType(CloneClusterizationType.OneMismatch);
                    break;
                default:
                    throw new RuntimeException("Wrong value for -" + CLUSTERIZATION_OPTION + " option.");
                }

        ((BasicCloneGeneratorParameters) params.getCloneGeneratorParameters())
                .setAccumulatorType(AccumulatorType.get(compressedAggregators, averageQuality));

        if ((value = cl.getOptionValue(EXPORT_OPTION)) != null) {
            //Exporting parameters
            ParametersIO.exportParameters(params, value);
            return;
        }

        String[] offArgs = cl.getArgs();

        if (offArgs.length == 0) {
            err.println("Input file not specified.");
            return;
        } else if (offArgs.length == 1) {
            err.println("Output file not specified.");
            return;
        } else if (offArgs.length > 2) {
            err.println("Unrecognized argument.");
            return;
        }

        String inputFileName = offArgs[0];
        String outputFileName = offArgs[1];

        File input = new File(inputFileName);

        if (!input.exists()) {
            err.println("Input file not found.");
            return;
        }

        //TODO This also done inside SFastqReader constructor
        CompressionType compressionType = CompressionType.None;
        if (inputFileName.endsWith(".gz"))
            compressionType = CompressionType.GZIP;

        QualityFormat format = null; // If variable remains null file format will be detected automatically
        if (cl.hasOption(PHRED33_OPTION))
            format = QualityFormat.Phred33;
        if (cl.hasOption(PHRED64_OPTION))
            if (format == null)
                format = QualityFormat.Phred64;
            else {
                err.println(
                        "Options: -" + PHRED33_OPTION + " and -" + PHRED64_OPTION + " are mutually exclusive");
                return;
            }

        SFastqReader reads = format == null ? new SFastqReader(input, compressionType)
                : new SFastqReader(input, format, compressionType);

        OutputPort<SSequencingRead> inputToPipeline = reads;
        if (input_limit >= 0)
            inputToPipeline = new CountLimitingOutputPort<>(inputToPipeline, input_limit);

        SegmentLibrary library = DefaultSegmentLibrary.load();

        AnalysisStatisticsAggregator statisticsAggregator = new AnalysisStatisticsAggregator();

        FullPipeline pipeline = new FullPipeline(inputToPipeline, params, false, library);
        pipeline.setThreads(threads);
        pipeline.setAnalysisListener(statisticsAggregator);

        new Thread(new SmartProgressReporter(pipeline, err)).start(); // Printing status to the standard error stream

        pipeline.run();

        if (cl.hasOption(PRINT_DEBUG_OPTION)) {
            err.println("Memory = " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
            err.println("Clusterization: " + pipeline.getQC().getReadsClusterized() + "% of reads, "
                    + pipeline.getQC().getClonesClusterized() + " % clones");
        }

        CloneSetClustered cloneSet = pipeline.getResult();

        if ((value = cl.getOptionValue(REPORT_OPTION)) != null) {
            File file = new File(value);
            TablePrintStreamAdapter table;
            if (file.exists())
                table = new TablePrintStreamAdapter(new FileOutputStream(file, true));
            else {
                table = new TablePrintStreamAdapter(file);
                ReportExporter.printHeader(table);
            }
            //CloneSetQualityControl qc = new CloneSetQualityControl(library, params.getSpecies(), params.getGene(), cloneSet);
            ReportExporter.printRow(table, inputFileName, outputFileName, pipeline.getQC(),
                    statisticsAggregator);
            table.close();
        }

        if (outputFileName.endsWith(".cls"))
            ClsExporter.export(pipeline, outputFileName.replace(".cls", "") + " " + new Date().toString(),
                    input.getName(), outputFileName);
        else {
            //Dry run
            if (outputFileName.startsWith("-"))
                return;

            ExportDetalizationLevel detalization = ExportDetalizationLevel.fromLevel(reporting_level);

            CompressionType compressionType1 = CompressionType.None;
            if (outputFileName.endsWith(".gz"))
                compressionType1 = CompressionType.GZIP;
            CloneSetIO.exportCloneSet(outputFileName, cloneSet, detalization, params, input.getAbsolutePath(),
                    compressionType1);
        }
    } catch (ParseException | RuntimeException | IOException e) {
        err.println("Error occurred in the analysis pipeline.");
        err.println();
        e.printStackTrace();
        //printHelp();
    }
}

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

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

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

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

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

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

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

    File directoryOfLogfile = new File(pathToLogfile);

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

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

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

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

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

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

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

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

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

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

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

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

    File tmpDir = new File(pathToWorkDir);

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

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

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

    String name = tmpDir.getAbsolutePath();

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

        Matcher matcher = pattern.matcher(element);

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

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

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

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

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

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

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

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

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

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

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

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

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

    name = valDatei.getAbsolutePath();

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

        Matcher matcher = pattern.matcher(element);

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

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

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

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

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

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

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

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

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

                factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

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

            }
        } else {
            // TODO: Formatvalidierung ber ein Ordner --> erledigt --> nur Marker
            Map<String, File> fileMap = Util.getFileMap(valDatei, false);
            Set<String> fileMapKeys = fileMap.keySet();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

            countSummaryNio = pdfaCountNio + siardCountNio + tiffCountNio + jp2CountNio;

            if (countNio.equals(count)) {
                // keine Dateien Validiert bestehendes Workverzeichnis ggf. lschen
                if (tmpDir.exists()) {
                    Util.deleteDir(tmpDir);
                }
                System.exit(1);
            } else if (countSummaryNio == 0) {
                // bestehendes Workverzeichnis ggf. lschen
                if (tmpDir.exists()) {
                    Util.deleteDir(tmpDir);
                }
                // alle Validierten Dateien valide
                System.exit(0);
            } else {
                // bestehendes Workverzeichnis ggf. lschen
                if (tmpDir.exists()) {
                    Util.deleteDir(tmpDir);
                }
                // Fehler in Validierten Dateien --> invalide
                System.exit(2);
            }
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
                tmpDir.deleteOnExit();
            }
        }
        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2));

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

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

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

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

                FileReader fr = null;

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

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

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

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

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

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

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

                // Fehler im Validierten SIP --> invalide & Abbruch
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_INVALID));
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE));
                System.out.println("Invalid");
                System.out.println("");
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP2));
                LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_LOGEND));

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

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

                    factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

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

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

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

                        // Fehler im Validierten SIP --> invalide & Abbruch
                        LOGGER.logError(
                                kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_INVALID));
                        LOGGER.logError(
                                kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE));
                        System.out.println("Invalid");
                        System.out.println("");
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP2));
                        LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_LOGEND));

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

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

                            factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        }

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

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

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

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

            factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

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

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

            doc.getDocumentElement().normalize();

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

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

                Node nNode = nList.item(temp);

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

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

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

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

From source file:com.mgreau.jboss.as7.cli.CliLauncher.java

public static void main(String[] args) throws Exception {
    int exitCode = 0;
    CommandContext cmdCtx = null;/*from  w  w  w.  j  a v  a 2 s.  co  m*/
    boolean gui = false;
    String appName = "";
    try {
        String argError = null;
        List<String> commands = null;
        File file = null;
        boolean connect = false;
        String defaultControllerProtocol = "http-remoting";
        String defaultControllerHost = null;
        int defaultControllerPort = -1;
        boolean version = false;
        String username = null;
        char[] password = null;
        int connectionTimeout = -1;

        //App deployment
        boolean isAppDeployment = false;
        final Properties props = new Properties();

        for (String arg : args) {
            if (arg.startsWith("--controller=") || arg.startsWith("controller=")) {
                final String fullValue;
                final String value;
                if (arg.startsWith("--")) {
                    fullValue = arg.substring(13);
                } else {
                    fullValue = arg.substring(11);
                }
                final int protocolEnd = fullValue.lastIndexOf("://");
                if (protocolEnd == -1) {
                    value = fullValue;
                } else {
                    value = fullValue.substring(protocolEnd + 3);
                    defaultControllerProtocol = fullValue.substring(0, protocolEnd);
                }

                String portStr = null;
                int colonIndex = value.lastIndexOf(':');
                if (colonIndex < 0) {
                    // default port
                    defaultControllerHost = value;
                } else if (colonIndex == 0) {
                    // default host
                    portStr = value.substring(1);
                } else {
                    final boolean hasPort;
                    int closeBracket = value.lastIndexOf(']');
                    if (closeBracket != -1) {
                        //possible ip v6
                        if (closeBracket > colonIndex) {
                            hasPort = false;
                        } else {
                            hasPort = true;
                        }
                    } else {
                        //probably ip v4
                        hasPort = true;
                    }
                    if (hasPort) {
                        defaultControllerHost = value.substring(0, colonIndex).trim();
                        portStr = value.substring(colonIndex + 1).trim();
                    } else {
                        defaultControllerHost = value;
                    }
                }

                if (portStr != null) {
                    int port = -1;
                    try {
                        port = Integer.parseInt(portStr);
                        if (port < 0) {
                            argError = "The port must be a valid non-negative integer: '" + args + "'";
                        } else {
                            defaultControllerPort = port;
                        }
                    } catch (NumberFormatException e) {
                        argError = "The port must be a valid non-negative integer: '" + arg + "'";
                    }
                }
            } else if ("--connect".equals(arg) || "-c".equals(arg)) {
                connect = true;
            } else if ("--version".equals(arg)) {
                version = true;
            } else if ("--gui".equals(arg)) {
                gui = true;
            } else if (arg.startsWith("--appDeployment=") || arg.startsWith("appDeployment=")) {
                isAppDeployment = true;
                appName = arg.startsWith("--") ? arg.substring(16) : arg.substring(14);
            } else if (arg.startsWith("--file=") || arg.startsWith("file=")) {
                if (file != null) {
                    argError = "Duplicate argument '--file'.";
                    break;
                }
                if (commands != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }

                final String fileName = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
                if (!fileName.isEmpty()) {
                    file = new File(fileName);
                    if (!file.exists()) {
                        argError = "File " + file.getAbsolutePath() + " doesn't exist.";
                        break;
                    }
                } else {
                    argError = "Argument '--file' is missing value.";
                    break;
                }
            } else if (arg.startsWith("--commands=") || arg.startsWith("commands=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(11) : arg.substring(9);
                commands = Util.splitCommands(value);
            } else if (arg.startsWith("--command=") || arg.startsWith("command=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(10) : arg.substring(8);
                commands = Collections.singletonList(value);
            } else if (arg.startsWith("--user=")) {
                username = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
            } else if (arg.startsWith("--password=")) {
                password = (arg.startsWith("--") ? arg.substring(11) : arg.substring(9)).toCharArray();
            } else if (arg.startsWith("--timeout=")) {
                if (connectionTimeout > 0) {
                    argError = "Duplicate argument '--timeout'";
                    break;
                }
                final String value = arg.substring(10);
                try {
                    connectionTimeout = Integer.parseInt(value);
                } catch (final NumberFormatException e) {
                    //
                }
                if (connectionTimeout <= 0) {
                    argError = "The timeout must be a valid positive integer: '" + value + "'";
                }
            } else if (arg.equals("--help") || arg.equals("-h")) {
                commands = Collections.singletonList("help");
            } else if (arg.startsWith("--properties=")) {
                final String value = arg.substring(13);
                final File propertiesFile = new File(value);
                if (!propertiesFile.exists()) {
                    argError = "File doesn't exist: " + propertiesFile.getAbsolutePath();
                    break;
                }

                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(propertiesFile);
                    props.load(fis);
                } catch (FileNotFoundException e) {
                    argError = e.getLocalizedMessage();
                    break;
                } catch (java.io.IOException e) {
                    argError = "Failed to load properties from " + propertiesFile.getAbsolutePath() + ": "
                            + e.getLocalizedMessage();
                    break;
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (java.io.IOException e) {
                        }
                    }
                }
                for (final Object prop : props.keySet()) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        public Object run() {
                            System.setProperty((String) prop, (String) props.get(prop));
                            return null;
                        }
                    });
                }
            } else if (!(arg.startsWith("-D") || arg.equals("-XX:"))) {// skip system properties and jvm options
                // assume it's commands
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time: "
                            + arg;
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                commands = Util.splitCommands(arg);
            }
        }

        if (argError != null) {
            System.err.println(argError);
            exitCode = 1;
            return;
        }

        if (version) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            VersionHandler.INSTANCE.handle(cmdCtx);
            return;
        }

        if (file != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processFile(file, cmdCtx, isAppDeployment, appName, props);
            return;
        }

        if (commands != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processCommands(commands, cmdCtx);
            return;
        }

        // Interactive mode
        cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                username, password, true, connect, connectionTimeout);
        cmdCtx.interact();
    } catch (Throwable t) {
        t.printStackTrace();
        exitCode = 1;
    } finally {
        if (cmdCtx != null && cmdCtx.getExitCode() != 0) {
            exitCode = cmdCtx.getExitCode();
        }
        if (!gui) {
            System.exit(exitCode);
        }
    }
    System.exit(exitCode);
}

From source file:com.peterbochs.PeterBochsDebugger.java

public static void main(String[] args) {
    WebServiceUtil.log("peter-bochs", "start", null, null, null);
    try {//ww  w.  j  av a2 s .  co m
        UIManager.setLookAndFeel("com.peterswing.white.PeterSwingWhiteLookAndFeel");
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (args.length == 0) {
        String errorMessage = "Wrong number of argument\n\n";
        errorMessage += "\nIn Linux/Mac : java -jar peter-bochs-debugger.jar bochs -f bochsrc.bxrc";
        errorMessage += "\nIn windows : java -jar peter-bochs-debugger.jar c:\\program files\\bochs2.4.3\\bochsdbg.exe -q -f bochsrc.bxrc";
        errorMessage += "\n!!! if using peter-bochs in windows, you need to pass the full path of bochs exe and -q to the parameter. (!!! relative path of bochs exe will not work)";
        errorMessage += "\n!!! to use \"experimental feature\", please add \"-debug\" to the parameter list";
        System.out.println(errorMessage);
        JOptionPane.showMessageDialog(null, errorMessage);
        System.exit(1);
    } else {
        if (args[0].equals("-version") || args[0].equals("-v")) {
            System.out.println(Global.version);
            System.exit(1);
        }
    }

    for (String str : args) {
        if (str.contains("bochsrc") || str.contains(".bxrc")) {
            bochsrc = str;
        }
    }

    String osName = System.getProperty("os.name").toLowerCase();
    if (osName.toLowerCase().contains("windows")) {
        os = OSType.win;
    } else if (osName.toLowerCase().contains("mac")) {
        os = OSType.mac;
    } else {
        os = OSType.linux;
    }
    if (os == OSType.mac) {
        com.apple.eawt.Application macApp = com.apple.eawt.Application.getApplication();
        // System.setProperty("dock:name", "Your Application Name");
        macApp.setDockIconImage(new ImageIcon(
                PeterBochsDebugger.class.getClassLoader().getResource("com/peterbochs/icons/peter.png"))
                        .getImage());
        // java.awt.PopupMenu menu = new java.awt.PopupMenu();
        // menu.add(new MenuItem("test"));
        // macApp.setDockMenu(menu);

        macApp.addApplicationListener(new MacAboutBoxHandler());
    }

    if (ArrayUtils.contains(args, "-debug")) {
        Global.debug = true;
        args = (String[]) ArrayUtils.removeElement(args, "-debug");
    } else {
        Global.debug = false;
    }

    try {
        if (PeterBochsDebugger.class.getProtectionDomain().getCodeSource().getLocation().getFile()
                .endsWith(".jar")) {
            JarFile jarFile = new JarFile(
                    PeterBochsDebugger.class.getProtectionDomain().getCodeSource().getLocation().getFile());
            if (System.getProperty("os.name").toLowerCase().contains("linux")) {
                if (System.getProperty("os.arch").contains("64")) {
                    if (Global.debug) {
                        System.out.println("Loading linux 64 bits jogl");
                    }
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libgluegen-rt.so")),
                            new File("libgluegen-rt.so"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libjogl_awt.so")),
                            new File("libjogl_awt.so"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libjogl_cg.so")),
                            new File("libjogl_cg.so"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libjogl.so")),
                            new File("libjogl.so"));
                } else {
                    if (Global.debug) {
                        System.out.println("Loading linux 32 bits jogl");
                    }
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_i586/libgluegen-rt.so")),
                            new File("libgluegen-rt.so"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_i586/libjogl_awt.so")),
                            new File("libjogl_awt.so"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_i586/libjogl_cg.so")),
                            new File("libjogl_cg.so"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_i586/libjogl.so")),
                            new File("libjogl.so"));
                }
                try {
                    File f = new File(".");
                    Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libjogl.so");
                    System.out.println("Loading " + f.getAbsolutePath() + File.separator + "libjogl.so");
                    Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libjogl_awt.so");
                    Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libjogl_cg.so");
                    Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libgluegen-rt.so");
                } catch (UnsatisfiedLinkError e) {
                    e.printStackTrace();
                    System.err.println("Native code library failed to load.\n" + e);
                    System.err.println(
                            "Solution : Please add \"-Djava.library.path=.\" to start peter-bochs\n" + e);
                }
            } else if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                CommonLib.writeFile(jarFile.getInputStream(new JarEntry("com/peterbochs/exe/PauseBochs.exe")),
                        new File("PauseBochs.exe"));
                CommonLib.writeFile(jarFile.getInputStream(new JarEntry("com/peterbochs/exe/StopBochs.exe")),
                        new File("StopBochs.exe"));
                CommonLib.writeFile(jarFile.getInputStream(new JarEntry("com/peterbochs/exe/ndisasm.exe")),
                        new File("ndisasm.exe"));

                if (System.getProperty("os.arch").contains("64")) {
                    if (Global.debug) {
                        System.out.println("Loading windows 64 bits jogl");
                    }
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_amd64/jogl.dll")),
                            new File("jogl.dll"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_amd64/jogl_awt.dll")),
                            new File("jogl_awt.dll"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_amd64/jogl_cg.dll")),
                            new File("jogl_cg.dll"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_amd64/gluegen-rt.dll")),
                            new File("gluegen-rt.dll"));
                } else {
                    if (Global.debug) {
                        System.out.println("Loading windows 32 bits jogl");
                    }
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_i586/jogl.dll")),
                            new File("jogl.dll"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_i586/jogl_awt.dll")),
                            new File("jogl_awt.dll"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_i586/jogl_cg.dll")),
                            new File("jogl_cg.dll"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_i586/gluegen-rt.dll")),
                            new File("gluegen-rt.dll"));
                }
                try {
                    File f = new File(".");
                    System.load(f.getAbsolutePath() + File.separator + "jogl.dll");
                    System.load(f.getAbsolutePath() + File.separator + "jogl_awt.dll");
                    System.load(f.getAbsolutePath() + File.separator + "jogl_cg.dll");
                    System.load(f.getAbsolutePath() + File.separator + "gluegen-rt.dll");
                } catch (UnsatisfiedLinkError e) {
                    e.printStackTrace();
                    System.err.println("Native code library failed to load.\n" + e);
                    System.err.println(
                            "Solution : Please add \"-Djava.library.path=.\" to start peter-bochs\n" + e);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (ArrayUtils.contains(args, "-loadBreakpoint")) {
        Setting.getInstance().setLoadBreakpointAtStartup(true);
        args = (String[]) ArrayUtils.removeElement(args, "-loadBreakpoint");
    } else if (ArrayUtils.contains(args, "-loadbreakpoint")) {
        Setting.getInstance().setLoadBreakpointAtStartup(true);
        args = (String[]) ArrayUtils.removeElement(args, "-loadbreakpoint");
    }

    for (int x = 0; x < args.length; x++) {
        if (args[x].toLowerCase().startsWith("-osdebug")) {
            Global.osDebug = CommonLib.string2long(args[x].replaceAll("-.*=", ""));
            args = (String[]) ArrayUtils.removeElement(args, args[x]);
            x = -1;
        } else if (args[x].toLowerCase().startsWith("-profilingmemoryport")) {
            Global.profilingMemoryPort = (int) CommonLib.string2long(args[x].replaceAll("-.*=", ""));
            args = (String[]) ArrayUtils.removeElement(args, args[x]);
            x = -1;
        } else if (args[x].toLowerCase().startsWith("-profilingjmpport")) {
            Global.profilingJmpPort = (int) CommonLib.string2long(args[x].replaceAll("-.*=", ""));
            args = (String[]) ArrayUtils.removeElement(args, args[x]);
            x = -1;
        } else if (args[x].toLowerCase().startsWith("-loadelf")) {
            Global.elfPaths = args[x].replaceAll("-loadelf=", "").split(",");
            Setting.getInstance().setLoadSystemMapAtStartup(true);
            args = (String[]) ArrayUtils.removeElement(args, args[x]);
            x = -1;
        } else if (args[x].toLowerCase().startsWith("-loadmap")) {
            System.out.println("-loadmap is not deprecated, please use -loadelf.");
        }
    }

    arguments = args;

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            PeterBochsDebugger inst = new PeterBochsDebugger();
            PeterBochsDebugger.instance = inst;

            new Thread("preventSetVisibleHang thread") {
                public void run() {
                    try {
                        Thread.sleep(10000);
                        if (preventSetVisibleHang) {
                            System.out.println(
                                    "setVisible(true) cause system hang, this probably a swing bug, so force exit, please restart");
                            System.exit(-1);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();

            if (Global.debug) {
                System.out.println("setVisible(true)");
            }
            inst.setVisible(true);

            preventSetVisibleHang = false;
            if (Global.debug) {
                System.out.println("end setVisible(true)");
            }
        }
    });
}