Example usage for java.io File exists

List of usage examples for java.io File exists

Introduction

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

Prototype

public boolean exists() 

Source Link

Document

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

Usage

From source file:com.cws.esolutions.security.main.PasswordUtility.java

public static void main(final String[] args) {
    final String methodName = PasswordUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {//from w ww . j  a v  a2  s. co  m
        DEBUGGER.debug("Value: {}", methodName);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(PasswordUtility.CNAME, options, true);

        System.exit(1);
    }

    BufferedReader bReader = null;
    BufferedWriter bWriter = null;

    try {
        // load service config first !!
        SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG,
                false);

        if (DEBUG) {
            DEBUGGER.debug("Options options: {}", options);

            for (String arg : args) {
                DEBUGGER.debug("Value: {}", arg);
            }
        }

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

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();
        final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo();
        final SystemConfig systemConfig = secConfigData.getSystemConfig();

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig);
            DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig);
        }

        if (commandLine.hasOption("encrypt")) {
            if ((StringUtils.isBlank(repoConfig.getPasswordFile()))
                    || (StringUtils.isBlank(repoConfig.getSaltFile()))) {
                System.err.println("The password/salt files are not configured. Entries will not be stored!");
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            final String entryName = commandLine.getOptionValue("entry");
            final String username = commandLine.getOptionValue("username");
            final String password = commandLine.getOptionValue("password");
            final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
                DEBUGGER.debug("String password: {}", password);
                DEBUGGER.debug("String salt: {}", salt);
            }

            final String encodedSalt = PasswordUtils.base64Encode(salt);
            final String encodedUserName = PasswordUtils.base64Encode(username);
            final String encryptedPassword = PasswordUtils.encryptText(password, salt,
                    secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                    systemConfig.getEncoding());
            final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword);

            if (DEBUG) {
                DEBUGGER.debug("String encodedSalt: {}", encodedSalt);
                DEBUGGER.debug("String encodedUserName: {}", encodedUserName);
                DEBUGGER.debug("String encodedPassword: {}", encodedPassword);
            }

            if (commandLine.hasOption("store")) {
                try {
                    new File(passwordFile.getParent()).mkdirs();
                    new File(saltFile.getParent()).mkdirs();

                    boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile();

                    if (DEBUG) {
                        DEBUGGER.debug("saltFileExists: {}", saltFileExists);
                    }

                    // write the salt out first
                    if (!(saltFileExists)) {
                        throw new IOException("Unable to create salt file");
                    }

                    boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile();

                    if (!(passwordFileExists)) {
                        throw new IOException("Unable to create password file");
                    }

                    if (commandLine.hasOption("replace")) {
                        File[] files = new File[] { saltFile, passwordFile };

                        if (DEBUG) {
                            DEBUGGER.debug("File[] files: {}", (Object) files);
                        }

                        for (File file : files) {
                            if (DEBUG) {
                                DEBUGGER.debug("File: {}", file);
                            }

                            String currentLine = null;
                            File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile");

                            if (DEBUG) {
                                DEBUGGER.debug("File tmpFile: {}", tmpFile);
                            }

                            bReader = new BufferedReader(new FileReader(file));
                            bWriter = new BufferedWriter(new FileWriter(tmpFile));

                            while ((currentLine = bReader.readLine()) != null) {
                                if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) {
                                    bWriter.write(currentLine + System.getProperty("line.separator"));
                                    bWriter.flush();
                                }
                            }

                            bWriter.close();

                            FileUtils.deleteQuietly(file);
                            FileUtils.copyFile(tmpFile, file);
                            FileUtils.deleteQuietly(tmpFile);
                        }
                    }

                    FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt
                            + System.getProperty("line.separator"), true);
                    FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + ","
                            + encodedPassword + System.getProperty("line.separator"), true);
                } catch (IOException iox) {
                    ERROR_RECORDER.error(iox.getMessage(), iox);
                }
            }

            System.out.println("Entry Name " + entryName + " stored.");
        }

        if (commandLine.hasOption("decrypt")) {
            String saltEntryName = null;
            String saltEntryValue = null;
            String decryptedPassword = null;
            String passwordEntryName = null;

            if ((StringUtils.isEmpty(commandLine.getOptionValue("entry"))
                    && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) {
                throw new ParseException("No entry or username was provided to decrypt.");
            }

            if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) {
                throw new ParseException("no entry provided to decrypt");
            }

            String entryName = commandLine.getOptionValue("entry");
            String username = commandLine.getOptionValue("username");

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) {
                throw new IOException(
                        "Unable to read configured password/salt file. Please check configuration and/or permissions.");
            }

            for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) {
                saltEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String saltEntryName: {}", saltEntryName);
                }

                if (StringUtils.equals(saltEntryName, entryName)) {
                    saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    break;
                }
            }

            if (StringUtils.isEmpty(saltEntryValue)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) {
                passwordEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName);
                }

                if (StringUtils.equals(passwordEntryName, saltEntryName)) {
                    String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue,
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            systemConfig.getEncoding());

                    break;
                }
            }

            if (StringUtils.isEmpty(decryptedPassword)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            System.out.println(decryptedPassword);
        } else if (commandLine.hasOption("encode")) {
            System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0)));
        } else if (commandLine.hasOption("decode")) {
            System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0)));
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        System.err.println("An error occurred during processing: " + iox.getMessage());
        System.exit(1);
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
        System.exit(1);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
        System.exit(1);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
        System.exit(1);
    } finally {
        try {
            if (bReader != null) {
                bReader.close();
            }

            if (bWriter != null) {
                bReader.close();
            }
        } catch (IOException iox) {
        }
    }

    System.exit(0);
}

From source file:net.sf.extjwnl.cli.ewn.java

public static void main(String[] args) throws IOException, JWNLException {
    if (args.length < 1) {
        System.out.println(USAGE);
        System.exit(0);/*from   w ww  .  ja  va2  s  . c  om*/
    }
    //find dictionary
    Dictionary d = null;
    File config = new File(defaultConfig);
    if (!config.exists()) {
        if (System.getenv().containsKey("WNHOME")) {
            String wnHomePath = System.getenv().get("WNHOME");
            File wnHome = new File(wnHomePath);
            if (wnHome.exists()) {
                d = Dictionary.getFileBackedInstance(wnHomePath);
            } else {
                log.error("Cannot find dictionary. Make sure " + defaultConfig
                        + " is available or WNHOME variable is set.");
            }
        }
    } else {
        d = Dictionary.getInstance(new FileInputStream(config));
    }

    if (null != d) {
        //parse and execute command line
        if ((-1 < args[0].indexOf('%') && -1 < args[0].indexOf(':')) || "-script".equals(args[0])
                || (-1 < args[0].indexOf('#'))) {
            d.edit();
            //edit
            if ("-script".equals(args[0])) {
                if (args.length < 2) {
                    log.error("Filename missing for -script command");
                    System.exit(1);
                } else {
                    File script = new File(args[1]);
                    if (script.exists()) {
                        //load into args
                        ArrayList<String> newArgs = new ArrayList<String>();
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(new FileInputStream(script), "UTF-8"));
                        try {
                            String str;
                            while ((str = in.readLine()) != null) {
                                String[] bits = str.split(" ");
                                StringBuilder tempArg = null;
                                for (String bit : bits) {
                                    int quoteCnt = 0;
                                    for (int j = 0; j < bit.length(); j++) {
                                        if ('"' == bit.charAt(j)) {
                                            quoteCnt++;
                                        }
                                    }
                                    if (null != tempArg) {
                                        if (0 == quoteCnt) {
                                            tempArg.append(" ").append(bit);
                                        } else {
                                            tempArg.append(" ").append(bit.replaceAll("\"\"", "\""));
                                            if (1 == (quoteCnt % 2)) {
                                                newArgs.add(
                                                        tempArg.toString().substring(1, tempArg.length() - 1));
                                                tempArg = null;
                                            }
                                        }
                                    } else {
                                        if (0 == quoteCnt) {
                                            newArgs.add(bit);
                                        } else {
                                            if (1 == (quoteCnt % 2)) {
                                                tempArg = new StringBuilder(bit.replaceAll("\"\"", "\""));
                                            } else {
                                                newArgs.add(bit.replaceAll("\"\"", "\""));
                                            }
                                        }
                                    }
                                }
                                if (null != tempArg) {
                                    newArgs.add(tempArg.toString());
                                }
                            }
                        } finally {
                            try {
                                in.close();
                            } catch (IOException e) {
                                //nop
                            }
                        }
                        args = newArgs.toArray(args);
                    }
                }
            }

            Word workWord = null;
            String key = null;
            String lemma = null;
            int lexFileNum = -1;
            int lexId = -1;
            //                String headLemma = null;
            //                int headLexId = -1;
            POS pos = null;
            String derivation = null;

            for (int i = 0; i < args.length; i++) {
                if (null == key && '-' != args[i].charAt(0)
                        && ((-1 < args[i].indexOf('%') && -1 < args[i].indexOf(':')))) {
                    key = args[i];
                    log.info("Searching " + key + "...");
                    if (null != key) {
                        workWord = d.getWordBySenseKey(key);
                    }
                    if (null == workWord) {
                        //parse sensekey
                        lemma = key.substring(0, key.indexOf('%')).replace('_', ' ');
                        String posId = key.substring(key.indexOf('%') + 1, key.indexOf(':'));
                        if ("1".equals(posId) || "2".equals(posId) || "3".equals(posId) || "4".equals(posId)
                                || "5".equals(posId)) {
                            pos = POS.getPOSForId(Integer.parseInt(posId));
                            String lexFileString = key.substring(key.indexOf(':') + 1);
                            if (-1 < lexFileString.indexOf(':')) {
                                lexFileNum = Integer
                                        .parseInt(lexFileString.substring(0, lexFileString.indexOf(':')));
                                if (lexFileString.indexOf(':') + 1 < lexFileString.length()) {
                                    String lexIdString = lexFileString
                                            .substring(lexFileString.indexOf(':') + 1);
                                    if (-1 < lexIdString.indexOf(':')) {
                                        lexId = Integer
                                                .parseInt(lexIdString.substring(0, lexIdString.indexOf(':')));
                                        //                                            if (lexIdString.indexOf(':') + 1 < lexIdString.length()) {
                                        //                                                headLemma = lexIdString.substring(lexIdString.indexOf(':') + 1);
                                        //                                                if (-1 < headLemma.indexOf(':')) {
                                        //                                                    headLemma = headLemma.substring(0, headLemma.indexOf(':'));
                                        //                                                    if (null != headLemma && !"".equals(headLemma) && lexIdString.lastIndexOf(':') + 1 < lexIdString.length()) {
                                        //                                                        headLexId = Integer.parseInt(lexIdString.substring(lexIdString.lastIndexOf(':') + 1));
                                        //                                                    }
                                        //                                                } else {
                                        //                                                    log.error("Malformed sensekey " + key);
                                        //                                                    System.exit(1);
                                        //                                                }
                                        //                                            }
                                    } else {
                                        log.error("Malformed sensekey " + key);
                                        System.exit(1);
                                    }
                                } else {
                                    log.error("Malformed sensekey " + key);
                                    System.exit(1);
                                }
                            } else {
                                log.error("Malformed sensekey " + key);
                                System.exit(1);
                            }
                        } else {
                            log.error("Malformed sensekey " + key);
                            System.exit(1);
                        }
                    }
                } else if (-1 < args[i].indexOf('#')) {
                    if (2 < args[i].length()) {
                        derivation = args[i].substring(2);
                        if (null == derivation) {
                            log.error("Missing derivation");
                            System.exit(1);
                        } else {
                            pos = POS.getPOSForKey(args[i].substring(0, 1));
                            if (null == pos) {
                                log.error("POS " + args[i] + " is not recognized for derivation " + derivation);
                                System.exit(1);
                            }
                        }
                    }
                }

                if ("-add".equals(args[i])) {
                    if (null == key) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    }
                    if (null != workWord) {
                        log.error("Duplicate sensekey " + workWord.getSenseKey());
                        System.exit(1);
                    }
                    log.info("Creating " + pos.getLabel() + " synset...");
                    Synset tempSynset = d.createSynset(pos);
                    log.info("Creating word " + lemma + "...");
                    workWord = new Word(d, tempSynset, 1, lemma);
                    workWord.setLexId(lexId);
                    tempSynset.getWords().add(workWord);
                    tempSynset.setLexFileNum(lexFileNum);
                    key = null;
                }

                if ("-remove".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        d.removeSynset(workWord.getSynset());
                        workWord = null;
                        key = null;
                    }
                }

                if ("-addword".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            Word tempWord = new Word(d, workWord.getSynset(),
                                    workWord.getSynset().getWords().size() + 1, args[i]);
                            workWord.getSynset().getWords().add(tempWord);
                            key = null;
                        } else {
                            log.error(
                                    "Missing word for addword command for sensekey " + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-removeword".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        workWord.getSynset().getWords().remove(workWord);
                        key = null;
                    }
                }

                if ("-setgloss".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            workWord.getSynset().setGloss(args[i]);
                            key = null;
                        } else {
                            log.error("Missing gloss for setgloss command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setadjclus".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            workWord.getSynset().setIsAdjectiveCluster(Boolean.parseBoolean(args[i]));
                            key = null;
                        } else {
                            log.error("Missing flag for setadjclus command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setverbframe".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length) {
                            if (workWord instanceof Verb) {
                                Verb verb = (Verb) workWord;
                                if ('-' == args[i].charAt(0)) {
                                    verb.getVerbFrameFlags().clear(Integer.parseInt(args[i].substring(1)));
                                } else {
                                    verb.getVerbFrameFlags().set(Integer.parseInt(args[i]));
                                }
                            } else {
                                log.error("Word at " + workWord.getSenseKey() + " should be verb");
                                System.exit(1);
                            }
                            key = null;
                        } else {
                            log.error("Missing index for setverbframe command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setverbframeall".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length) {
                            if (workWord.getSynset() instanceof VerbSynset) {
                                if ('-' == args[i].charAt(0)) {
                                    workWord.getSynset().getVerbFrameFlags()
                                            .clear(Integer.parseInt(args[i].substring(1)));
                                } else {
                                    workWord.getSynset().getVerbFrameFlags().set(Integer.parseInt(args[i]));
                                }
                            } else {
                                log.error("Synset at " + workWord.getSenseKey() + " should be verb");
                                System.exit(1);
                            }
                            key = null;
                        } else {
                            log.error("Missing index for setverbframeall command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setlexfile".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            if (-1 < args[i].indexOf('.')) {
                                workWord.getSynset()
                                        .setLexFileNum(LexFileNameLexFileIdMap.getMap().get(args[i]));
                            } else {
                                workWord.getSynset().setLexFileNum(Integer.parseInt(args[i]));
                            }
                        } else {
                            log.error("Missing file number or name for setlexfile command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-addptr".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length) {
                            Word targetWord = d.getWordBySenseKey(args[i]);
                            if (null != targetWord) {
                                i++;
                                if (i < args.length) {
                                    PointerType pt = PointerType.getPointerTypeForKey(args[i]);
                                    if (null != pt) {
                                        Pointer p;
                                        if (pt.isLexical()) {
                                            p = new Pointer(pt, workWord, targetWord);
                                        } else {
                                            p = new Pointer(pt, workWord.getSynset(), targetWord.getSynset());
                                        }
                                        if (!workWord.getSynset().getPointers().contains(p)) {
                                            workWord.getSynset().getPointers().add(p);
                                        } else {
                                            log.error("Duplicate pointer of type " + pt + " to "
                                                    + targetWord.getSenseKey()
                                                    + " in addptr command for sensekey "
                                                    + workWord.getSenseKey());
                                            System.exit(1);
                                        }
                                    } else {
                                        log.error("Invalid pointer type at " + args[i]
                                                + " in addptr command for sensekey " + workWord.getSenseKey());
                                        System.exit(1);
                                    }
                                } else {
                                    log.error("Missing pointer type at " + args[i]
                                            + " in addptr command for sensekey " + workWord.getSenseKey());
                                    System.exit(1);
                                }
                            } else {
                                log.error("Missing target at " + args[i] + " in addptr command for sensekey "
                                        + workWord.getSenseKey());
                                System.exit(1);
                            }
                            key = null;
                        } else {
                            log.error("Missing sensekey for addptr command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-removeptr".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length) {
                            Word targetWord = d.getWordBySenseKey(args[i]);
                            if (null != targetWord) {
                                i++;
                                if (i < args.length) {
                                    PointerType pt = PointerType.getPointerTypeForKey(args[i]);
                                    if (null != pt) {
                                        Pointer p;
                                        if (pt.isLexical()) {
                                            p = new Pointer(pt, workWord, targetWord);
                                        } else {
                                            p = new Pointer(pt, workWord.getSynset(), targetWord.getSynset());
                                        }
                                        if (workWord.getSynset().getPointers().contains(p)) {
                                            workWord.getSynset().getPointers().remove(p);
                                        } else {
                                            log.error("Missing pointer of type " + pt + " to "
                                                    + targetWord.getSenseKey()
                                                    + " in removeptr command for sensekey "
                                                    + workWord.getSenseKey());
                                            System.exit(1);
                                        }
                                    } else {
                                        log.error("Invalid pointer type at " + args[i]
                                                + " in removeptr command for sensekey "
                                                + workWord.getSenseKey());
                                        System.exit(1);
                                    }
                                } else {
                                    log.error("Missing pointer type at " + args[i]
                                            + " in removeptr command for sensekey " + workWord.getSenseKey());
                                    System.exit(1);
                                }
                            } else {
                                log.error("Missing target at " + args[i] + " in removeptr command for sensekey "
                                        + workWord.getSenseKey());
                                System.exit(1);
                            }
                            key = null;
                        } else {
                            log.error("Missing sensekey for removeptr command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setlexid".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            workWord.setLexId(Integer.parseInt(args[i]));
                            key = null;
                        } else {
                            log.error("Missing lexid for setlexid command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setusecount".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            workWord.setUseCount(Integer.parseInt(args[i]));
                            key = null;
                        } else {
                            log.error("Missing count for setusecount command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-addexc".equals(args[i])) {
                    i++;
                    if (i < args.length && '-' != args[i].charAt(0)) {
                        String baseform = args[i];
                        Exc e = d.getException(pos, derivation);
                        if (null != e) {
                            if (null != e.getExceptions()) {
                                if (!e.getExceptions().contains(baseform)) {
                                    e.getExceptions().add(baseform);
                                }
                            }
                        } else {
                            ArrayList<String> list = new ArrayList<String>(1);
                            list.add(baseform);
                            d.createException(pos, derivation, list);
                        }
                        derivation = null;
                    } else {
                        log.error("Missing baseform for addexc command for derivation " + derivation);
                        System.exit(1);
                    }
                }

                if ("-removeexc".equals(args[i])) {
                    Exc e = d.getException(pos, derivation);
                    if (null != e) {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            String baseform = args[i];
                            if (null != e.getExceptions()) {
                                if (e.getExceptions().contains(baseform)) {
                                    e.getExceptions().remove(baseform);
                                }
                                if (0 == e.getExceptions().size()) {
                                    d.removeException(e);
                                }
                            }
                        } else {
                            d.removeException(e);
                        }
                    } else {
                        log.error("Missing derivation " + derivation);
                        System.exit(1);
                    }
                    derivation = null;
                }
            }

            d.save();
        } else {
            //browse
            String key = args[0];
            if (1 == args.length) {
                for (POS pos : POS.getAllPOS()) {
                    IndexWord iw = d.getIndexWord(pos, key);
                    if (null == iw) {
                        System.out.println("\nNo information available for " + pos.getLabel() + " " + key);
                    } else {
                        System.out.println(
                                "\nInformation available for " + iw.getPOS().getLabel() + " " + iw.getLemma());
                        printAvailableInfo(iw);
                    }
                    if (null != d.getMorphologicalProcessor()) {
                        List<String> forms = d.getMorphologicalProcessor().lookupAllBaseForms(pos, key);
                        if (null != forms) {
                            for (String form : forms) {
                                if (!key.equals(form)) {
                                    iw = d.getIndexWord(pos, form);
                                    if (null != iw) {
                                        System.out.println("\nInformation available for "
                                                + iw.getPOS().getLabel() + " " + iw.getLemma());
                                        printAvailableInfo(iw);
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                boolean needHelp = false;
                boolean needGloss = false;
                boolean needLex = false;
                boolean needOffset = false;
                boolean needSenseNum = false;
                boolean needSenseKeys = false;
                int needSense = 0;
                for (String arg : args) {
                    if ("-h".equals(arg)) {
                        needHelp = true;
                    }
                    if ("-g".equals(arg)) {
                        needGloss = true;
                    }
                    if ("-a".equals(arg)) {
                        needLex = true;
                    }
                    if ("-o".equals(arg)) {
                        needOffset = true;
                    }
                    if ("-s".equals(arg)) {
                        needSenseNum = true;
                    }
                    if ("-k".equals(arg)) {
                        needSenseKeys = true;
                    }
                    if (arg.startsWith("-n") && 2 < arg.length()) {
                        needSense = Integer.parseInt(arg.substring(2));
                    }
                }

                for (String arg : args) {
                    if (arg.startsWith("-ants") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display synsets containing direct antonyms of the search string.\n" + "\n"
                                            + "Direct antonyms are a pair of words between which there is an\n"
                                            + "associative bond built up by co-occurrences.\n" + "\n"
                                            + "Antonym synsets are preceded by \"=>\".");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nAntonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.ANTONYM, 1, needSense, needGloss, needLex, needOffset,
                                    needSenseNum, needSenseKeys);
                        }
                    } //ants

                    if (arg.startsWith("-hype") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Recursively display hypernym (superordinate) tree for the search\n"
                                            + "string.\n" + "\n"
                                            + "Hypernym is the generic term used to designate a whole class of\n"
                                            + "specific instances.  Y is a hypernym of X if X is a (kind of) Y.\n"
                                            + "\n"
                                            + "Hypernym synsets are preceded by \"=>\", and are indented from\n"
                                            + "the left according to their level in the hierarchy.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHypernyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.HYPERNYM, PointerUtils.INFINITY, needSense, needGloss,
                                    needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //hype

                    if (arg.startsWith("-hypo") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display immediate hyponyms (subordinates) for the search string.\n" + "\n"
                                            + "Hyponym is the generic term used to designate a member of a class.\n"
                                            + "X is a hyponym of Y if X is a (kind of) Y.\n" + "\n"
                                            + "Hyponym synsets are preceded by \"=>\".");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHyponyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.HYPONYM, 1, needSense, needGloss, needLex, needOffset,
                                    needSenseNum, needSenseKeys);
                        }
                    } //hypo

                    if (arg.startsWith("-tree") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display hyponym (subordinate) tree for the search string.  This is\n"
                                            + "a recursive search that finds the hyponyms of each hyponym. \n"
                                            + "\n"
                                            + "Hyponym is the generic term used to designate a member of a class.\n"
                                            + "X is a hyponym of Y if X is a (kind of) Y. \n" + "\n"
                                            + "Hyponym synsets are preceded by \"=>\", and are indented from the left\n"
                                            + "according to their level in the hierarchy.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHyponyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.HYPONYM, PointerUtils.INFINITY, needSense, needGloss,
                                    needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //tree

                    if (arg.startsWith("-enta") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Recursively display entailment relations of the search string.\n" + "\n"
                                            + "The action represented by the verb X entails Y if X cannot be done\n"
                                            + "unless Y is, or has been, done.\n" + "\n"
                                            + "Entailment synsets are preceded by \"=>\", and are indented from the left\n"
                                            + "according to their level in the hierarchy.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nEntailment of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.ENTAILMENT, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //enta

                    if (arg.startsWith("-syns") && 6 == arg.length()) {
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nSynonyms of " + p.getLabel() + " " + iw.getLemma());
                            if (POS.ADJECTIVE == p) {
                                if (needHelp) {
                                    System.out.println(
                                            "Display synonyms and synsets related to synsets containing\n"
                                                    + "the search string.  If the search string is in a head synset\n"
                                                    + "the 'cluster's' satellite synsets are displayed.  If the search\n"
                                                    + "string is in a satellite synset, its head synset is displayed.\n"
                                                    + "If the search string is a pertainym the word or synset that it\n"
                                                    + "pertains to is displayed.\n" + "\n"
                                                    + "A cluster is a group of adjective synsets that are organized around\n"
                                                    + "antonymous pairs or triplets.  An adjective cluster contains two or more\n"
                                                    + "head synsets that contan antonyms.  Each head synset has one or more\n"
                                                    + "satellite synsets.\n" + "\n"
                                                    + "A head synset contains at least one word that has a direct antonym\n"
                                                    + "in another head synset of the same cluster.\n" + "\n"
                                                    + "A satellite synset represents a concept that is similar in meaning to\n"
                                                    + "the concept represented by its head synset.\n" + "\n"
                                                    + "Direct antonyms are a pair of words between which there is an\n"
                                                    + "associative bond built up by co-occurrences.\n" + "\n"
                                                    + "Direct antonyms are printed in parentheses following the adjective.\n"
                                                    + "The position of an adjective in relation to the noun may be restricted\n"
                                                    + "to the prenominal, postnominal or predicative position.  Where present\n"
                                                    + "these restrictions are noted in parentheses.\n" + "\n"
                                                    + "A pertainym is a relational adjective, usually defined by such phrases\n"
                                                    + "as \"of or pertaining to\" and that does not have an antonym.  It pertains\n"
                                                    + "to a noun or another pertainym.\n" + "\n"
                                                    + "Senses contained in head synsets are displayed above the satellites,\n"
                                                    + "which are indented and preceded by \"=>\".  Senses contained in\n"
                                                    + "satellite synsets are displayed with the head synset below.  The head\n"
                                                    + "synset is preceded by \"=>\".\n" + "\n"
                                                    + "Pertainym senses display the word or synsets that the search string\n"
                                                    + "pertains to.");
                                }
                                tracePointers(iw, PointerType.SIMILAR_TO, 1, needSense, needGloss, needLex,
                                        needOffset, needSenseNum, needSenseKeys);
                                tracePointers(iw, PointerType.PARTICIPLE_OF, 1, needSense, needGloss, needLex,
                                        needOffset, needSenseNum, needSenseKeys);
                            }

                            if (POS.ADVERB == p) {
                                if (needHelp) {
                                    System.out.println(
                                            "Display synonyms and synsets related to synsets containing\n"
                                                    + "the search string.  If the search string is a pertainym the word\n"
                                                    + "or synset that it pertains to is displayed.\n" + "\n"
                                                    + "A pertainym is a relational adverb that is derived from an adjective.\n"
                                                    + "\n"
                                                    + "Pertainym senses display the word that the search string is derived from\n"
                                                    + "and the adjective synset that contains the word.  If the adjective synset\n"
                                                    + "is a satellite synset, its head synset is also displayed.");
                                }
                                tracePointers(iw, PointerType.PERTAINYM, 1, needSense, needGloss, needLex,
                                        needOffset, needSenseNum, needSenseKeys);
                            }

                            if (POS.NOUN == p || POS.VERB == p) {
                                if (needHelp) {
                                    System.out.println(
                                            "Recursively display hypernym (superordinate) tree for the search\n"
                                                    + "string.\n" + "\n"
                                                    + "Hypernym is the generic term used to designate a whole class of\n"
                                                    + "specific instances.  Y is a hypernym of X if X is a (kind of) Y.\n"
                                                    + "\n"
                                                    + "Hypernym synsets are preceded by \"=>\", and are indented from\n"
                                                    + "the left according to their level in the hierarchy.");
                                }
                                tracePointers(iw, PointerType.HYPERNYM, PointerUtils.INFINITY, needSense,
                                        needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            }
                        }
                    } //syns

                    if (arg.startsWith("-smem") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all holonyms of the search string.\n" + "\n"
                                    + "A holonym is the name of the whole of which the 'meronym' names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.\n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMember Holonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //smem

                    if (arg.startsWith("-ssub") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all holonyms of the search string.\n" + "\n"
                                    + "A holonym is the name of the whole of which the 'meronym' names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.\n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nSubstance Holonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //ssub

                    if (arg.startsWith("-sprt") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all holonyms of the search string.\n" + "\n"
                                    + "A holonym is the name of the whole of which the 'meronym' names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.\n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nPart Holonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.PART_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //sprt

                    if (arg.startsWith("-memb") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMember Meronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //memb

                    if (arg.startsWith("-subs") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nSubstance Meronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //subs

                    if (arg.startsWith("-part") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nPart Meronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //part

                    if (arg.startsWith("-mero") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //mero

                    if (arg.startsWith("-holo") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all holonyms of the search string.\n" + "\n"
                                    + "A holonym is the name of the whole of which the 'meronym' names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.\n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHolonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //holo

                    if (arg.startsWith("-caus") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Recursively display CAUSE TO relations of the search string.\n"
                                    + "\n"
                                    + "The action represented by the verb X causes the action represented by\n"
                                    + "the verb Y.\n" + "\n"
                                    + "CAUSE TO synsets are preceded by \"=>\", and are indented from the left\n"
                                    + "according to their level in the hierarchy.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\n'Cause to' of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.CAUSE, PointerUtils.INFINITY, needSense, needGloss,
                                    needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //caus

                    if (arg.startsWith("-pert") && 6 == arg.length()) {
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nPertainyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.PERTAINYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //pert

                    if (arg.startsWith("-attr") && 6 == arg.length()) {
                        POS p = POS.getPOSForKey(arg.substring(5));
                        if (needHelp) {
                            if (POS.NOUN == p) {
                                System.out
                                        .println("Display adjectives for which search string is an attribute.");
                            }
                            if (POS.ADJECTIVE == p) {
                                System.out.println("Display nouns that are attributes of search string.");
                            }
                        }
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nAttributes of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.ATTRIBUTE, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //attr

                    if (arg.startsWith("-deri") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display derived forms - nouns and verbs that are related morphologically.\n"
                                            + "Each related synset is preceeded by its part of speech. Each word in the\n"
                                            + "synset is followed by its sense number.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nDerived forms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.NOMINALIZATION, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //deri

                    if (arg.startsWith("-domn") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display domain to which this synset belongs.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nDomain of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.CATEGORY, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.USAGE, 1, needSense, needGloss, needLex, needOffset,
                                    needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.REGION, 1, needSense, needGloss, needLex, needOffset,
                                    needSenseNum, needSenseKeys);
                        }
                    } //domn

                    if (arg.startsWith("-domt") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all synsets belonging to the domain.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nDomain of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.CATEGORY_MEMBER, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.USAGE_MEMBER, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.REGION_MEMBER, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //domt

                    if (arg.startsWith("-faml") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display familiarity and polysemy information for the search string.\n"
                                            + "The polysemy count is the number of senses in WordNet.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            String[] freqs = { "extremely rare", "very rare", "rare", "uncommon", "common",
                                    "familiar", "very familiar", "extremely familiar" };
                            String[] pos = { "a noun", "a verb", "an adjective", "an adverb" };
                            int cnt = iw.getSenses().size();
                            int familiar = 0;
                            if (cnt == 0) {
                                familiar = 0;
                            }
                            if (cnt == 1) {
                                familiar = 1;
                            }
                            if (cnt == 2) {
                                familiar = 2;
                            }
                            if (cnt >= 3 && cnt <= 4) {
                                familiar = 3;
                            }
                            if (cnt >= 5 && cnt <= 8) {
                                familiar = 4;
                            }
                            if (cnt >= 9 && cnt <= 16) {
                                familiar = 5;
                            }
                            if (cnt >= 17 && cnt <= 32) {
                                familiar = 6;
                            }
                            if (cnt > 32) {
                                familiar = 7;
                            }
                            System.out.println("\n" + iw.getLemma() + " used as " + pos[p.getId() - 1] + " is "
                                    + freqs[familiar] + " (polysemy count = " + cnt + ")");
                        }
                    } //faml

                    if (arg.startsWith("-fram") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display applicable verb sentence frames for the search string.\n" + "\n"
                                            + "A frame is a sentence template illustrating the usage of a verb.\n"
                                            + "\n"
                                            + "Verb sentence frames are preceded with the string \"*>\" if a sentence\n"
                                            + "frame is acceptable for all of the words in the synset, and with \"=>\"\n"
                                            + "if a sentence frame is acceptable for the search string only.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nVerb frames of " + p.getLabel() + " " + iw.getLemma());
                            for (int i = 0; i < iw.getSenses().size(); i++) {
                                Synset synset = iw.getSenses().get(i);
                                for (String vf : synset.getVerbFrames()) {
                                    System.out.println("\t*> " + vf);
                                }
                                for (Word word : synset.getWords()) {
                                    if (iw.getLemma().equalsIgnoreCase(word.getLemma())) {
                                        if (word instanceof Verb) {
                                            Verb verb = (Verb) word;
                                            for (String vf : verb.getVerbFrames()) {
                                                System.out.println("\t=> " + vf);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } //fram

                    if (arg.startsWith("-hmer") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display meronyms for search string tree.  This is a recursive search\n"
                                            + "the prints all the meronyms of the search string and all of its\n"
                                            + "hypernyms. \n" + "\n"
                                            + "A meronym is the name of a constituent part, the substance of, or a\n"
                                            + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_MERONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_MERONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_MERONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //hmer

                    if (arg.startsWith("-hhol") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "\"Display holonyms for search string tree.  This is a recursive search\n"
                                            + "that prints all the holonyms of the search string and all of the\n"
                                            + "holonym's holonyms.\n" + "\n"
                                            + "A holonym is the name of the whole of which the meronym names a part.\n"
                                            + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHolonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_HOLONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_HOLONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //hhol

                    if (arg.startsWith("-mero") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //mero

                    if (arg.startsWith("-grep") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out
                                    .println("Print all strings in the database containing the search string\n"
                                            + "as an individual word, or as the first or last string in a word or\n"
                                            + "collocation.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        System.out.println("\nGrep of " + p.getLabel() + " " + key);
                        Iterator<IndexWord> ii = d.getIndexWordIterator(p, key);
                        while (ii.hasNext()) {
                            System.out.println(ii.next().getLemma());
                        }
                    } //grep

                    if ("-over".equals(arg)) {
                        for (POS pos : POS.getAllPOS()) {
                            if (null != d.getMorphologicalProcessor()) {
                                IndexWord iw = d.getIndexWord(pos, key);
                                //for plurals like species, glasses
                                if (null != iw && key.equals(iw.getLemma())) {
                                    printOverview(pos, iw, needGloss, needLex, needOffset, needSenseNum,
                                            needSenseKeys);
                                }

                                List<String> forms = d.getMorphologicalProcessor().lookupAllBaseForms(pos, key);
                                if (null != forms) {
                                    for (String form : forms) {
                                        if (!form.equals(key)) {
                                            iw = d.getIndexWord(pos, form);
                                            if (null != iw) {
                                                printOverview(pos, iw, needGloss, needLex, needOffset,
                                                        needSenseNum, needSenseKeys);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } //over
                }
            }
        }
    }
}

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 a v a  2 s  .com*/
 * 
 * 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:fmiquerytest.Coordinates.java

public static void main(String[] args) {
    df_short.setTimeZone(tz);
    df_iso.setTimeZone(tz);/*from   w  ww .  ja  v  a 2 s .c  o m*/
    df_daycode.setTimeZone(tz);
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols();
    otherSymbols.setDecimalSeparator('.');
    df_fiveDecimal.setDecimalFormatSymbols(otherSymbols);
    String startTime = df_short.format(new Date(startTimeMillis));
    System.out.println("startTime: " + startTime);

    //Clean up old weather data 
    //**********************************************************************
    FileSystemTools.cleanupOldWeatherData(daysToStoreWeatherData);

    //Google query
    //**********************************************************************
    if (gShare.equals("")) {
        Scanner input = new Scanner(System.in);
        System.out.println("Paste Google Directions Share:");
        gShare = input.nextLine();
    }
    String gQuery = Parser.getQueryFromShare(gShare);
    System.out.println("Google query URL: " + gQuery);

    //Check if we already have this route
    //Valid only if the route option is 0 (default)
    //Because otherwise we cannot be sure we already have the optional route
    List<routeStep> gSteps = new ArrayList<>();
    if (FileSystemTools.isSavedRoute(gQuery) && gRouteOption == 0) {
        System.out.println("Route found from saved list. Loading.");
        gSteps = FileSystemTools.loadSavedRoute(gQuery);
    } else {
        gSteps = Parser.getSteps(gQuery);
        if (gRouteOption == 0) {
            System.out.println("Saving new route to list.");
            FileSystemTools.saveRoute(gQuery, gSteps);
        }
    }

    //Compile route table with current settings
    //**********************************************************************
    List<routeStep> routeData = RouteTools.compileRoute(gSteps, refreshInterval);
    String endTime = df_short.format(new Date(startTimeMillis + routeDur * 1000));
    System.out.println("endTime: " + endTime);
    //Forecast from FMI is only for 48h - warning if we are going over
    //Or is it 54h? http://ilmatieteenlaitos.fi/avoin-data-saaennustedata-hirlam
    if (((startTimeMillis + routeDur * 1000) - System.currentTimeMillis()) / (1000 * 60 * 60) > 48) {
        System.out.println("**************************************************" + newLine + "WARNING:" + newLine
                + "Weather forecast available only for 48 hours" + newLine
                + "**************************************************");
    }

    //Prepare time and file variables
    //**********************************************************************
    String nowAsISO = df_iso.format(new Date());
    System.out.println("Start ISO time: " + nowAsISO);
    double timeMarginal = routeDur * 1.2 + 3600;
    String endTimeForFmi = df_iso.format(new Date(startTimeMillis + (intValue(timeMarginal)) * 1000));
    String endTimeForFile = df_iso.format(new Date(startTimeMillis + (intValue(routeDur + 3600)) * 1000));
    System.out.println("End ISO time:   " + endTimeForFmi);
    String fmiParam = new StringBuilder("&starttime=").append(nowAsISO).append("&endtime=")
            .append(endTimeForFmi).toString();
    File weatherDataFileNameFirst = new File("weather" + nowAsISO.replaceAll("[^A-Za-z0-9 ]", "") + ".txt");
    File weatherDataFileNameLast = new File("weather" + endTimeForFmi.replaceAll("[^A-Za-z0-9 ]", "") + ".txt");
    File weatherDataFileNameStart = new File(
            "weather" + (df_iso.format(new Date(startTimeMillis))).replaceAll("[^A-Za-z0-9 ]", "") + ".txt");
    File weatherDataFileNameEnd = new File("weather" + endTimeForFile.replaceAll("[^A-Za-z0-9 ]", "") + ".txt");
    List<stationData> allStations = new ArrayList<>();
    List<stationData> fmiData = new ArrayList<>();
    List<String> savedFileTimes = new ArrayList<>();

    //**********************************************************************
    //Check if we already have the weather data
    //**********************************************************************
    if (!weatherDataFileNameStart.exists() || !weatherDataFileNameEnd.exists()) {
        //FMI query
        //**********************************************************************
        String fmiCities = new StringBuilder(fmiBase).append(fmiKey).append(fmiMiddle).append(fmiQueryCities)
                .append(fmiParam).toString();
        String fmiObsStations = new StringBuilder(fmiBase).append(fmiKey).append(fmiMiddle)
                .append(fmiQueryObsStations).append(fmiParam).toString();
        //System.out.println("FMI cities URL: "+fmiCities);
        //System.out.println("FMI obsstations URL: "+fmiObsStations);

        //Collect weather data from FMI
        //**********************************************************************
        System.out.print("FMI data:" + newLine + fmiCities + newLine + "Loading and processing...");
        fmiData.addAll(Parser.getStations(fmiCities));
        System.out.println("SUCCESS.");
        System.out.print("FMI data:" + newLine + fmiObsStations + newLine + "Loading and processing...");
        fmiData.addAll(Parser.getStations(fmiObsStations));
        System.out.println("SUCCESS.");

        //Get unique stations
        //**********************************************************************
        List<stationData> uniqueStations = ToolBox.getUniqueStations(fmiData);
        System.out.println("Parsed stations count: " + uniqueStations.size());

        //Save or load stations
        //**********************************************************************
        List<stationData> savedStations = new ArrayList<>();
        if (!stationFileName.exists()) {
            //Save current parsed stations to file
            FileSystemTools.saveObjectToFile(uniqueStations, stationFileName);
        } else {
            //Or if the stations were already saved, load them
            System.out.println("Station information file found: " + stationFileName);
            System.out.print("Loading...");
            savedStations = FileSystemTools.loadStationsFromFile(stationFileName);
            System.out.println("DONE.");
            System.out.println("Loaded stations count: " + savedStations.size());
        }

        //Merge station information
        //**********************************************************************
        System.out.println("Merging station information.");
        savedStations.addAll(uniqueStations);
        allStations = ToolBox.getUniqueStations(savedStations);
        System.out.println("Merged stations count: " + allStations.size());

        //Find names for stations
        //**********************************************************************
        String gMapsGeoCode = "https://maps.googleapis.com/maps/api/geocode/xml?latlng=";
        //for (stationData station : allStations){
        for (int i = 0; i < allStations.size(); i++) {
            if (allStations.get(i).stationName.equals("")) {
                gQuery = new StringBuilder(gMapsGeoCode).append(allStations.get(i).stationLocation.Lat)
                        .append(",").append(allStations.get(i).stationLocation.Lon).append("&key=").append(gKey)
                        .toString();
                System.out.println("Google query URL: " + gQuery);

                allStations.get(i).stationName = Parser.getStationName(gQuery);
            }
        }
        //System.out.println("Station names parsed.");
        Collections.sort(allStations);

        //Print stations and separate them for saving
        //**********************************************************************
        List<stationData> onlyStations = new ArrayList<>();
        //int indeksi = 0;
        List<weatherData> weatherPoint = new ArrayList<>();
        weatherPoint.add(0, new weatherData("", "", ""));
        for (stationData station : allStations) {
            //System.out.format("%-4s%-30s%-10s%-10s%n",
            //                    indeksi,station.stationName,station.stationLocation.Lat,station.stationLocation.Lon);
            //++indeksi;
            onlyStations.add(new stationData(station.stationLocation, station.stationName, weatherPoint));
        }

        //Save station names
        //**********************************************************************
        System.out.println("Saving station names.");
        FileSystemTools.saveObjectToFile(onlyStations, stationFileName);

        //Save weather dataset
        //**********************************************************************
        //Compute file names between start and end
        System.out.println("Saving weather data...");
        long currentTimeAsDouble = System.currentTimeMillis();
        int hoursPassed = intValue(Math.floor(currentTimeAsDouble - startTimeMillis) / 1000 / 60 / 60);
        File weatherDataFileNameTemp = weatherDataFileNameFirst;
        while (!weatherDataFileNameTemp.equals(weatherDataFileNameLast)) {
            String savedFileTime = df_iso.format(new Date(startTimeMillis + ((hoursPassed * 3600) * 1000)));
            savedFileTimes.add(savedFileTime);
            weatherDataFileNameTemp = new File(
                    "weather" + savedFileTime.replaceAll("[^A-Za-z0-9 ]", "") + ".txt");
            //System.out.println("Weather data file: "+weatherDataFileNameTemp);
            //This if we don't actually maybe want
            //if (!weatherDataFileNameTemp.exists()){
            List<stationData> thisHourWeather = FileSystemTools.extractHourOfWeatherData(savedFileTime,
                    fmiData);
            //System.out.println("Saving: "+weatherDataFileNameTemp);
            FileSystemTools.saveObjectToFile(thisHourWeather, weatherDataFileNameTemp);
            //}
            ++hoursPassed;
        }
    }
    //If we have weather data saved, definitely we have the stations also
    //**********************************************************************
    else {
        System.out.println("Loading weather data...");
        File weatherDataFileNameTemp = weatherDataFileNameStart;
        int hoursPassed = 0;
        while (!weatherDataFileNameTemp.equals(weatherDataFileNameEnd)) {
            String savedFileTime = df_iso.format(new Date(startTimeMillis + ((hoursPassed * 3600) * 1000)));
            savedFileTimes.add(savedFileTime);
            weatherDataFileNameTemp = new File(
                    "weather" + savedFileTime.replaceAll("[^A-Za-z0-9 ]", "") + ".txt");
            System.out.println("Weather data file: " + weatherDataFileNameTemp);
            if (weatherDataFileNameTemp.exists()) {
                fmiData.addAll(FileSystemTools.loadStationsFromFile(weatherDataFileNameTemp));
            }
            ++hoursPassed;
        }
        allStations = FileSystemTools.loadStationsFromFile(stationFileName);
        System.out.println("DONE.");
    }

    //Find closest weather stations in route points and extract their data
    //**********************************************************************
    System.out.println("Calculating nearest stations in route points:");
    List<Integer> neededStations = new ArrayList<>();
    for (routeStep step : routeData) {
        distance[] stationDistances = RouteTools.calculateStationDistances(step.StartLocation, allStations);
        System.out.format("%-6s%.5f, %.5f  ", "Step: ", step.StartLocation.Lat, step.StartLocation.Lon);
        for (int i = 0; i < 1; i++) {
            System.out.format("%-9s%-5s%-20s%.5f%n", "Station: ", stationDistances[i].stationNum,
                    allStations.get(stationDistances[i].stationNum).stationName,
                    stationDistances[i].stationDistance);
        }
        neededStations.add(stationDistances[0].stationNum);
    }
    System.out.println("Needed stations: " + neededStations.toString().trim());
    //Remove duplicates from needed stations list
    Set<Integer> uniqueEntries = new HashSet<Integer>(neededStations);
    //Extract weather data from needed stations
    Map routeWeather = Collections.synchronizedMap(new HashMap());
    routeWeather = WeatherTools.extractNeededStations(uniqueEntries, fmiData, allStations);

    //Find what fields we have
    List<String> allParameters = new ArrayList<>();
    for (int i = 0; i < fmiData.size(); ++i) {
        allParameters.add(fmiData.get(i).weatherData.get(0).parameterName);
    }
    Set<String> uniqueParameters = new HashSet<String>(allParameters);
    for (String par : uniqueParameters) {
        for (Integer num : uniqueEntries) {
            for (String time : savedFileTimes) {
                //System.out.format("%-5s%-25s%-35s%s%n",num,time,par,routeWeather.get(num+"-"+time+"-"+par));
            }
        }
    }

    // Build the final data table
    //**********************************************************************
    List<stepWeather> stepDataBase = new ArrayList<>();
    stepDataBase = RouteTools.combineRouteDatabase(routeData, neededStations, allStations);

    //Find sunrise and sunset times during the route
    //**********************************************************************
    List<String> sunEvents = DayLightTime.calculateSunEvents(stepDataBase);
    for (String s : sunEvents) {
        System.out.println(s.replaceAll(",", "."));
    }

    //Make a webpage to show the weather data
    //**********************************************************************
    WeatherTools.makeResultHtml(stepDataBase, allStations, routeWeather, sunEvents);
}

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

/**
 * Launches this application/*from  ww  w . j  a v a  2s. c  om*/
 */
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:edu.ku.brc.dbsupport.ImportExportDB.java

public static void main(String[] args) {
        Pair<String, String> usernamePassword = UserAndMasterPasswordMgr.getInstance().getUserNamePasswordForDB();
        UIHelper.tryLogin("com.mysql.jdbc.Driver", "org.hibernate.dialect.MySQLDialect", //$NON-NLS-1$ //$NON-NLS-2$
                "testfish", "jdbc:mysql://localhost/testfish", //$NON-NLS-1$ //$NON-NLS-2$
                usernamePassword.first, usernamePassword.second);

        Session testSession = HibernateUtil.getCurrentSession();
        String workingFolder = "Specify6ImportExport"; //$NON-NLS-1$
        File wf = new File(workingFolder);
        if (!wf.exists()) {
            wf.mkdirs();//from   w  ww  .  ja va  2s.c o  m
        }
        //String dbTable = "Division"; //$NON-NLS-1$

        ImportExportDB impexp = new ImportExportDB(testSession, workingFolder + File.separator);

        try {
            // record set
            // impexp.importSingleDBObject(dbTable, 1, false);
            // impexp.printRecordSet(dbTable);
            // impexp.printSingleRecordXML(dbTable, 3);
            // impexp.writeRecordSet(dbTable, 1);
            // impexp.writeSingleRecordXML(dbTable, 1);
            // impexp.exportTables();
            // List<String> temp = new ArrayList();
            // impexp.getImmediateParentTables(dbTable,temp , false);
            // impexp.getRequiredFields("Geography");

            // import
            System.out.println("importing..."); //$NON-NLS-1$
            // impexp.importTable(dbTable);
            // impexp.importTable("LoanAgent");
            // print results
            System.out.println("printing..."); //$NON-NLS-1$
            //impexp.printXML(dbTable);
            // impexp.printXML("Geography");
            // impexp.printXML("LoanAgent");
            // impexp.printXML("CollectionObject");
            // impexp.printXML("LoanReturnPreparation");
            // impexp.printXML("CollectionObject");
            // impexp.printXML("Collector");

            // export
            // impexp.writeSingleRecordXML(dbTable,1);
            //impexp.exportTables();

            impexp.writeXMLfile("PrepType"); //$NON-NLS-1$

        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex);
            ex.printStackTrace();
        } finally {
            impexp.close();
            System.out.println("...done"); //$NON-NLS-1$
        }
    }

From source file:com.moviejukebox.MovieJukebox.java

public static void main(String[] args) throws Throwable {
    JukeboxStatistics.setTimeStart(System.currentTimeMillis());

    // Create the log file name here, so we can change it later (because it's locked
    System.setProperty("file.name", LOG_FILENAME);
    PropertyConfigurator.configure("properties/log4j.properties");

    LOG.info("Yet Another Movie Jukebox {}", GitRepositoryState.getVersion());
    LOG.info("~~~ ~~~~~~~ ~~~~~ ~~~~~~~ {}", StringUtils.repeat("~", GitRepositoryState.getVersion().length()));
    LOG.info("https://github.com/YAMJ/yamj-v2");
    LOG.info("Copyright (c) 2004-2016 YAMJ Members");
    LOG.info("");
    LOG.info("This software is licensed under the GNU General Public License v3+");
    LOG.info("See this page: https://github.com/YAMJ/yamj-v2/wiki/License");
    LOG.info("");
    LOG.info(" Revision SHA: {} {}", GIT.getCommitId(), GIT.getDirty() ? "(Custom Build)" : "");
    LOG.info("  Commit Date: {}", GIT.getCommitTime());
    LOG.info("   Build Date: {}", GIT.getBuildTime());
    LOG.info("");
    LOG.info(" Java Version: {}", GitRepositoryState.getJavaVersion());
    LOG.info("");

    if (!SystemTools.validateInstallation()) {
        LOG.info("ABORTING.");
        return;/*  w  w w. j ava 2 s  .com*/
    }

    String movieLibraryRoot = null;
    String jukeboxRoot = null;
    Map<String, String> cmdLineProps = new LinkedHashMap<>();

    try {
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if ("-v".equalsIgnoreCase(arg)) {
                // We've printed the version, so quit now
                return;
            } else if ("-t".equalsIgnoreCase(arg)) {
                String pin = args[++i];

                // load the apikeys.properties file
                if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) {
                    return;
                }

                // authorize to Trakt.TV
                TraktTV.getInstance().initialize().authorizeWithPin(pin);

                // We've authorized access to Trakt.TV, so quit now
                return;
            } else if ("-o".equalsIgnoreCase(arg)) {
                jukeboxRoot = args[++i];
                PropertiesUtil.setProperty("mjb.jukeboxRoot", jukeboxRoot);
            } else if ("-c".equalsIgnoreCase(arg)) {
                jukeboxClean = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.jukeboxClean", TRUE);
            } else if ("-k".equalsIgnoreCase(arg)) {
                setJukeboxPreserve(Boolean.TRUE);
            } else if ("-p".equalsIgnoreCase(arg)) {
                userPropertiesName = args[++i];
            } else if ("-i".equalsIgnoreCase(arg)) {
                skipIndexGeneration = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.skipIndexGeneration", TRUE);
            } else if ("-h".equalsIgnoreCase(arg)) {
                skipHtmlGeneration = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.skipHtmlGeneration", Boolean.TRUE);
            } else if ("-dump".equalsIgnoreCase(arg)) {
                dumpLibraryStructure = Boolean.TRUE;
            } else if ("-memory".equalsIgnoreCase(arg)) {
                showMemory = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.showMemory", Boolean.TRUE);
            } else if (arg.startsWith("-D")) {
                String propLine = arg.length() > 2 ? arg.substring(2) : args[++i];
                int propDiv = propLine.indexOf('=');
                if (-1 != propDiv) {
                    cmdLineProps.put(propLine.substring(0, propDiv), propLine.substring(propDiv + 1));
                }
            } else if (arg.startsWith("-")) {
                help();
                return;
            } else {
                movieLibraryRoot = args[i];
            }
        }
    } catch (Exception error) {
        LOG.error("Wrong arguments specified");
        help();
        return;
    }

    // Save the name of the properties file for use later
    setProperty("userPropertiesName", userPropertiesName);

    LOG.info("Processing started at {}", new Date());
    LOG.info("");

    // Load the moviejukebox-default.properties file
    if (!setPropertiesStreamName("./properties/moviejukebox-default.properties", Boolean.TRUE)) {
        return;
    }

    // Load the user properties file "moviejukebox.properties"
    // No need to abort if we don't find this file
    // Must be read before the skin, because this may contain an override skin
    setPropertiesStreamName(userPropertiesName, Boolean.FALSE);

    // Grab the skin from the command-line properties
    if (cmdLineProps.containsKey(SKIN_DIR)) {
        setProperty(SKIN_DIR, cmdLineProps.get(SKIN_DIR));
    }

    // Load the skin.properties file
    if (!setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin.properties", Boolean.TRUE)) {
        return;
    }

    // Load the skin-user.properties file (ignore the error)
    setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin-user.properties", Boolean.FALSE);

    // Load the overlay.properties file (ignore the error)
    String overlayRoot = getProperty("mjb.overlay.dir", Movie.UNKNOWN);
    overlayRoot = (PropertiesUtil.getBooleanProperty("mjb.overlay.skinroot", Boolean.TRUE)
            ? (getProperty(SKIN_DIR, SKIN_DEFAULT) + File.separator)
            : "") + (StringTools.isValidString(overlayRoot) ? (overlayRoot + File.separator) : "");
    setPropertiesStreamName(overlayRoot + "overlay.properties", Boolean.FALSE);

    // Load the apikeys.properties file
    if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) {
        return;
    }

    // This is needed to update the static reference for the API Keys in the pattern formatter
    // because the formatter is initialised before the properties files are read
    FilteringLayout.addApiKeys();

    // Load the rest of the command-line properties
    for (Map.Entry<String, String> propEntry : cmdLineProps.entrySet()) {
        setProperty(propEntry.getKey(), propEntry.getValue());
    }

    // Read the information about the skin
    SkinProperties.readSkinVersion();
    // Display the information about the skin
    SkinProperties.printSkinVersion();

    StringBuilder properties = new StringBuilder("{");
    for (Map.Entry<Object, Object> propEntry : PropertiesUtil.getEntrySet()) {
        properties.append(propEntry.getKey());
        properties.append("=");
        properties.append(propEntry.getValue());
        properties.append(",");
    }
    properties.replace(properties.length() - 1, properties.length(), "}");

    // Print out the properties to the log file.
    LOG.debug("Properties: {}", properties.toString());

    // Check for mjb.skipIndexGeneration and set as necessary
    // This duplicates the "-i" functionality, but allows you to have it in the property file
    skipIndexGeneration = PropertiesUtil.getBooleanProperty("mjb.skipIndexGeneration", Boolean.FALSE);

    if (PropertiesUtil.getBooleanProperty("mjb.people", Boolean.FALSE)) {
        peopleScan = Boolean.TRUE;
        peopleScrape = PropertiesUtil.getBooleanProperty("mjb.people.scrape", Boolean.TRUE);
        peopleMax = PropertiesUtil.getIntProperty("mjb.people.maxCount", 10);
        popularity = PropertiesUtil.getIntProperty("mjb.people.popularity", 5);

        // Issue 1947: Cast enhancement - option to save all related files to a specific folder
        peopleFolder = PropertiesUtil.getProperty("mjb.people.folder", "");
        if (isNotValidString(peopleFolder)) {
            peopleFolder = "";
        } else if (!peopleFolder.endsWith(File.separator)) {
            peopleFolder += File.separator;
        }
        StringTokenizer st = new StringTokenizer(
                PropertiesUtil.getProperty("photo.scanner.photoExtensions", "jpg,jpeg,gif,bmp,png"), ",;| ");
        while (st.hasMoreTokens()) {
            PHOTO_EXTENSIONS.add(st.nextToken());
        }
    }

    // Check for mjb.skipHtmlGeneration and set as necessary
    // This duplicates the "-h" functionality, but allows you to have it in the property file
    skipHtmlGeneration = PropertiesUtil.getBooleanProperty("mjb.skipHtmlGeneration", Boolean.FALSE);

    // Look for the parameter in the properties file if it's not been set on the command line
    // This way we don't overwrite the setting if it's not found and defaults to FALSE
    showMemory = PropertiesUtil.getBooleanProperty("mjb.showMemory", Boolean.FALSE);

    // This duplicates the "-c" functionality, but allows you to have it in the property file
    jukeboxClean = PropertiesUtil.getBooleanProperty("mjb.jukeboxClean", Boolean.FALSE);

    MovieFilenameScanner.setSkipKeywords(
            tokenizeToArray(getProperty("filename.scanner.skip.keywords", ""), ",;| "),
            PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive", Boolean.TRUE));
    MovieFilenameScanner.setSkipRegexKeywords(
            tokenizeToArray(getProperty("filename.scanner.skip.keywords.regex", ""), ","),
            PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive.regex", Boolean.TRUE));
    MovieFilenameScanner.setExtrasKeywords(
            tokenizeToArray(getProperty("filename.extras.keywords", "trailer,extra,bonus"), ",;| "));
    MovieFilenameScanner.setMovieVersionKeywords(tokenizeToArray(
            getProperty("filename.movie.versions.keywords", "remastered,directors cut,extended cut,final cut"),
            ",;|"));
    MovieFilenameScanner.setLanguageDetection(
            PropertiesUtil.getBooleanProperty("filename.scanner.language.detection", Boolean.TRUE));
    final KeywordMap languages = PropertiesUtil.getKeywordMap("filename.scanner.language.keywords", null);
    if (!languages.isEmpty()) {
        MovieFilenameScanner.clearLanguages();
        for (String lang : languages.getKeywords()) {
            String values = languages.get(lang);
            if (values != null) {
                MovieFilenameScanner.addLanguage(lang, values, values);
            } else {
                LOG.info("No values found for language code '{}'", lang);
            }
        }
    }
    final KeywordMap sourceKeywords = PropertiesUtil.getKeywordMap("filename.scanner.source.keywords",
            "HDTV,PDTV,DVDRip,DVDSCR,DSRip,CAM,R5,LINE,HD2DVD,DVD,DVD5,DVD9,HRHDTV,MVCD,VCD,TS,VHSRip,BluRay,HDDVD,D-THEATER,SDTV");
    MovieFilenameScanner.setSourceKeywords(sourceKeywords.getKeywords(), sourceKeywords);

    String temp = getProperty("sorting.strip.prefixes");
    if (temp != null) {
        StringTokenizer st = new StringTokenizer(temp, ",");
        while (st.hasMoreTokens()) {
            String token = st.nextToken().trim();
            if (token.startsWith("\"") && token.endsWith("\"")) {
                token = token.substring(1, token.length() - 1);
            }
            Movie.addSortIgnorePrefixes(token.toLowerCase());
        }
    }

    enableWatchScanner = PropertiesUtil.getBooleanProperty("watched.scanner.enable", Boolean.TRUE);
    enableWatchTraktTv = PropertiesUtil.getBooleanProperty("watched.trakttv.enable", Boolean.FALSE);
    enableCompleteMovies = PropertiesUtil.getBooleanProperty("complete.movies.enable", Boolean.TRUE);

    // Check to see if don't have a root, check the property file
    if (StringTools.isNotValidString(movieLibraryRoot)) {
        movieLibraryRoot = getProperty("mjb.libraryRoot");
        if (StringTools.isValidString(movieLibraryRoot)) {
            LOG.info("Got libraryRoot from properties file: {}", movieLibraryRoot);
        } else {
            LOG.error("No library root found!");
            help();
            return;
        }
    }

    if (jukeboxRoot == null) {
        jukeboxRoot = getProperty("mjb.jukeboxRoot");
        if (jukeboxRoot == null) {
            LOG.info("jukeboxRoot is null in properties file. Please fix this as it may cause errors.");
        } else {
            LOG.info("Got jukeboxRoot from properties file: {}", jukeboxRoot);
        }
    }

    File f = new File(movieLibraryRoot);
    if (f.exists() && f.isDirectory() && jukeboxRoot == null) {
        jukeboxRoot = movieLibraryRoot;
    }

    if (movieLibraryRoot == null) {
        help();
        return;
    }

    if (jukeboxRoot == null) {
        LOG.info("Wrong arguments specified: you must define the jukeboxRoot property (-o) !");
        help();
        return;
    }

    if (!f.exists()) {
        LOG.error("Directory or library configuration file '{}', not found.", movieLibraryRoot);
        return;
    }

    FileTools.initUnsafeChars();
    FileTools.initSubtitleExtensions();

    // make canonical names
    jukeboxRoot = FileTools.getCanonicalPath(jukeboxRoot);
    movieLibraryRoot = FileTools.getCanonicalPath(movieLibraryRoot);
    MovieJukebox ml = new MovieJukebox(movieLibraryRoot, jukeboxRoot);
    if (dumpLibraryStructure) {
        LOG.warn(
                "WARNING !!! A dump of your library directory structure will be generated for debug purpose. !!! Library won't be built or updated");
        ml.makeDumpStructure();
    } else {
        ml.generateLibrary();
    }

    // Now rename the log files
    renameLogFile();

    if (ScanningLimit.isLimitReached()) {
        LOG.warn("Scanning limit of {} was reached, please re-run to complete processing.",
                ScanningLimit.getLimit());
        System.exit(EXIT_SCAN_LIMIT);
    } else {
        System.exit(EXIT_NORMAL);
    }
}

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  . j  a v  a2s . 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:ca.uqac.info.trace.execution.BabelTrace.java

/**
 * Main program loop//w  w w . j a  v  a 2s.  c  o  m
 * @param args
 */
public static void main(String[] args) {
    String trace_type = "", tool_name = "";
    String trace_in_filename = "", formula_in_filename = "";
    String out_formula = "", out_trace = "", out_signature = "", output_dir = "";
    File formula_in, trace_in;
    trace_in = null;
    Operator op = null;
    EventTrace trace = null;
    boolean run_tool = false, show_command = false;

    // Parse command line arguments
    Options options = setupOptions();
    CommandLine c_line = setupCommandLine(args, options);
    assert c_line != null;
    if (c_line.hasOption("version")) {
        System.out.println("\nBabelTrace build " + BUILD_STRING);
        System.out.println("(C) 2012-2013 Sylvain Hall et al., Universit du Qubec  Chicoutimi");
        System.out.println("This program comes with ABSOLUTELY NO WARRANTY.");
        System.out.println("This is a free software, and you are welcome to redistribute it");
        System.out.println("under certain conditions. See the file COPYING for details.\n");
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("t"))
        trace_in_filename = c_line.getOptionValue("t");
    else {
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    if (c_line.hasOption("f"))
        formula_in_filename = c_line.getOptionValue("f");
    else {
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    if (c_line.hasOption("i"))
        trace_type = c_line.getOptionValue("i");
    else {
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    if (c_line.hasOption("c"))
        tool_name = c_line.getOptionValue("c");
    else {
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    if (c_line.hasOption("o"))
        output_dir = c_line.getOptionValue("o");
    else {
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    if (c_line.hasOption("b")) {
        run_tool = false;
        show_command = true;
    }
    if (c_line.hasOption("r")) {
        run_tool = true;
        show_command = false;
    }

    // Read input formula
    formula_in = new File(formula_in_filename);
    if (!formula_in.exists()) {
        System.err.println("Error reading " + formula_in_filename);
        System.exit(ERR_IO);
    }
    try {
        out_formula = ca.uqac.info.util.FileReadWrite.readFile(formula_in_filename);
    } catch (java.io.FileNotFoundException e) {
        System.err.println("File not found: " + formula_in_filename);
        System.exit(ERR_IO);
    } catch (java.io.IOException e) {
        System.err.println("IO Exception: " + formula_in_filename);
        e.printStackTrace();
        System.exit(ERR_IO);
    }

    // Get trace file
    trace_in = new File(trace_in_filename);

    // Get execution
    Execution ex = getExecution(tool_name);

    // Get filenames for each part
    String base_filename = FileReadWrite.baseName(trace_in) + "." + FileReadWrite.baseName(formula_in);
    String trace_filename = output_dir + "/" + base_filename + "." + ex.getTraceExtension();
    String formula_filename = output_dir + "/" + base_filename + "." + ex.getFormulaExtension();
    String signature_filename = output_dir + "/" + base_filename + "." + ex.getSignatureExtension();

    // Setup execution environment
    ex.setProperty(formula_filename);
    ex.setSignature(signature_filename);
    ex.setTrace(trace_filename);

    // Show command lines and leave
    if (show_command) {
        String[] cl = ex.getCommandLines();
        for (String c : cl) {
            System.out.println(c);
        }
        System.exit(ERR_OK);
    }

    // Initialize the translator
    Translator tt = getTraceTranslator(tool_name);
    if (tt == null) {
        System.err.println("Error: unrecognized conversion format \"" + tool_name + "\"");
        System.exit(ERR_NO_SUCH_TOOL);
    }
    tt.setTrace(trace);

    // Parse the trace
    TraceReader t_read = getTraceReader(trace_type);
    try {
        trace = t_read.parseEventTrace(new FileInputStream(trace_in));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        System.exit(ERR_IO);
    }

    // Get the formula as an operator
    try {
        op = Operator.parseFromString(out_formula);
    } catch (ParseException e) {
        System.err.println("Error parsing the input formula");
        System.exit(ERR_PARSE);
    }
    assert op != null;

    // Does the formula require flat messages and formulas?
    if (tt.requiresFlat()) {
        // Convert the first-order formula to a propositional one
        FlatTranslator pt = new FlatTranslator();
        pt.setFormula(op);
        pt.setTrace(trace);
        // Flatten the trace
        String tr_trans = pt.translateTrace();
        TraceReader xtr = new XmlTraceReader();
        trace = xtr.parseEventTrace(new ByteArrayInputStream(tr_trans.getBytes()));
        // Flatten the formula
        String op_trans = pt.translateFormula();
        try {
            op = Operator.parseFromString(op_trans);
        } catch (ParseException e) {
            System.err.println("Error parsing the formula once translated to propositional");
            System.exit(ERR_PARSE);
        }
    }

    // Is the formula first-order while the tool requires propositional?
    if (tt.requiresPropositional() && FirstOrderDetector.isFirstOrder(op)) {
        // Convert the first-order formula to a propositional one
        PropositionalTranslator pt = new PropositionalTranslator();
        pt.setFormula(op);
        pt.setTrace(trace);
        String op_trans = pt.translateFormula();
        try {
            op = Operator.parseFromString(op_trans);
        } catch (ParseException e) {
            System.err.println("Error parsing the formula once translated to propositional");
            System.exit(ERR_PARSE);
        }
        // We also convert equalities between constants produced by the translator
        // into Booleans
        ConstantConverter cc = new ConstantConverter();
        op.accept(cc);
        op = cc.getFormula();
        // And then propagate those constants
        UnitPropagator up = new UnitPropagator();
        op.accept(up);
        op = up.getFormula();
    }

    // Convert
    tt.setTrace(trace);
    tt.setFormula(op);
    tt.translateAll();
    out_trace = tt.getTraceFile();
    out_formula = tt.getFormulaFile();
    out_signature = tt.getSignatureFile();

    // Save conversions to files
    try {
        if (!out_trace.isEmpty()) {
            ca.uqac.info.util.FileReadWrite.writeToFile(trace_filename, out_trace);
        }
        if (!out_formula.isEmpty()) {
            ca.uqac.info.util.FileReadWrite.writeToFile(formula_filename, out_formula);
        }
        if (!out_signature.isEmpty()) {
            ca.uqac.info.util.FileReadWrite.writeToFile(signature_filename, out_signature);
        }
    } catch (java.io.IOException e) {
        System.err.println("Error writing to file");
        System.err.println(e.getMessage());
        System.exit(ERR_IO);
    }

    // Now that all conversions have been made, run the tool
    if (run_tool) {
        try {
            ex.run();
        } catch (Execution.CommandLineException e) {
            System.err.println("Error running command");
            System.exit(ERR_TOOL_EXECUTION);
        }

        // Print results
        ReturnVerdict ex_retval = ex.getReturnVerdict();
        float ex_time = (float) ex.getTime() / (float) 1000000000; // We show seconds, not s
        float ex_memory = (float) ex.getMemory() / (float) 1024; // We show megabytes, not bytes
        System.out.printf("%s,%.2f,%.2f\n", ex_retval, ex_time, ex_memory);

        // If an error occurred, dump it
        if (ex_retval == ReturnVerdict.ERROR) {
            System.err.println("Error while executing " + tool_name);
            System.err.println("Command line(s):");
            for (String cl : ex.getCommandLines()) {
                System.err.println(cl);
            }
            System.err.println("Below is the string returned by the tool\n");
            System.err.println(ex.getErrorString());
            System.exit(ERR_TOOL_EXECUTION);
        }
    }

    // Quit
    System.exit(ERR_OK);
}