Example usage for javax.xml.parsers DocumentBuilder parse

List of usage examples for javax.xml.parsers DocumentBuilder parse

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder parse.

Prototype


public abstract Document parse(InputSource is) throws SAXException, IOException;

Source Link

Document

Parse the content of the given input source as an XML document and return a new DOM Document object.

Usage

From source file:InlineSchemaValidator.java

/** Main program entry point. */
public static void main(String[] argv) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();/* www. j  a  v a 2 s. c o m*/
        System.exit(1);
    }

    // variables
    Vector schemas = null;
    Vector instances = null;
    HashMap prefixMappings = null;
    HashMap uriMappings = null;
    String docURI = argv[argv.length - 1];
    String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE;
    int repetition = DEFAULT_REPETITION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
    boolean memoryUsage = DEFAULT_MEMORY_USAGE;

    // process arguments
    for (int i = 0; i < argv.length - 1; ++i) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("l")) {
                // get schema language name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -l option.");
                } else {
                    schemaLanguage = argv[i];
                }
                continue;
            }
            if (option.equals("x")) {
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -x option.");
                    continue;
                }
                String number = argv[i];
                try {
                    int value = Integer.parseInt(number);
                    if (value < 1) {
                        System.err.println("error: Repetition must be at least 1.");
                        continue;
                    }
                    repetition = value;
                } catch (NumberFormatException e) {
                    System.err.println("error: invalid number (" + number + ").");
                }
                continue;
            }
            if (arg.equals("-a")) {
                // process -a: xpath expressions for schemas
                if (schemas == null) {
                    schemas = new Vector();
                }
                while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) {
                    schemas.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-i")) {
                // process -i: xpath expressions for instance documents
                if (instances == null) {
                    instances = new Vector();
                }
                while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) {
                    instances.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-nm")) {
                String prefix;
                String uri;
                while (i + 2 < argv.length - 1 && !(prefix = argv[i + 1]).startsWith("-")
                        && !(uri = argv[i + 2]).startsWith("-")) {
                    if (prefixMappings == null) {
                        prefixMappings = new HashMap();
                        uriMappings = new HashMap();
                    }
                    prefixMappings.put(prefix, uri);
                    HashSet prefixes = (HashSet) uriMappings.get(uri);
                    if (prefixes == null) {
                        prefixes = new HashSet();
                        uriMappings.put(uri, prefixes);
                    }
                    prefixes.add(prefix);
                    i += 2;
                }
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                continue;
            }
            if (option.equalsIgnoreCase("m")) {
                memoryUsage = option.equals("m");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
            System.err.println("error: unknown option (" + option + ").");
            continue;
        }
    }

    try {
        // Create new instance of inline schema validator.
        InlineSchemaValidator inlineSchemaValidator = new InlineSchemaValidator(prefixMappings, uriMappings);

        // Parse document containing schemas and validation roots
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(inlineSchemaValidator);
        Document doc = db.parse(docURI);

        // Create XPath factory for selecting schema and validation roots
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        xpath.setNamespaceContext(inlineSchemaValidator);

        // Select schema roots from the DOM
        NodeList[] schemaNodes = new NodeList[schemas != null ? schemas.size() : 0];
        for (int i = 0; i < schemaNodes.length; ++i) {
            XPathExpression xpathSchema = xpath.compile((String) schemas.elementAt(i));
            schemaNodes[i] = (NodeList) xpathSchema.evaluate(doc, XPathConstants.NODESET);
        }

        // Select validation roots from the DOM
        NodeList[] instanceNodes = new NodeList[instances != null ? instances.size() : 0];
        for (int i = 0; i < instanceNodes.length; ++i) {
            XPathExpression xpathInstance = xpath.compile((String) instances.elementAt(i));
            instanceNodes[i] = (NodeList) xpathInstance.evaluate(doc, XPathConstants.NODESET);
        }

        // Create SchemaFactory and configure
        SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage);
        factory.setErrorHandler(inlineSchemaValidator);

        try {
            factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Build Schema from sources
        Schema schema;
        {
            DOMSource[] sources;
            int size = 0;
            for (int i = 0; i < schemaNodes.length; ++i) {
                size += schemaNodes[i].getLength();
            }
            sources = new DOMSource[size];
            if (size == 0) {
                schema = factory.newSchema();
            } else {
                int count = 0;
                for (int i = 0; i < schemaNodes.length; ++i) {
                    NodeList nodeList = schemaNodes[i];
                    int nodeListLength = nodeList.getLength();
                    for (int j = 0; j < nodeListLength; ++j) {
                        sources[count++] = new DOMSource(nodeList.item(j));
                    }
                }
                schema = factory.newSchema(sources);
            }
        }

        // Setup validator and input source.
        Validator validator = schema.newValidator();
        validator.setErrorHandler(inlineSchemaValidator);

        try {
            validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err
                    .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Validator does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Validate instance documents
        for (int i = 0; i < instanceNodes.length; ++i) {
            NodeList nodeList = instanceNodes[i];
            int nodeListLength = nodeList.getLength();
            for (int j = 0; j < nodeListLength; ++j) {
                DOMSource source = new DOMSource(nodeList.item(j));
                source.setSystemId(docURI);
                inlineSchemaValidator.validate(validator, source, docURI, repetition, memoryUsage);
            }
        }
    } catch (SAXParseException e) {
        // ignore
    } catch (Exception e) {
        System.err.println("error: Parse error occurred - " + e.getMessage());
        if (e instanceof SAXException) {
            Exception nested = ((SAXException) e).getException();
            if (nested != null) {
                e = nested;
            }
        }
        e.printStackTrace(System.err);
    }
}

From source file:com.adobe.aem.demomachine.gui.AemDemo.java

public static void main(String[] args) {

    String demoMachineRootFolder = null;

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Path to Demo Machine root folder");
    CommandLineParser parser = new BasicParser();
    try {/*from  w w  w  .j a v a  2s  . c  o m*/
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("f")) {
            demoMachineRootFolder = cmd.getOptionValue("f");
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    // Let's grab the version number for the core Maven file
    String mavenFilePath = (demoMachineRootFolder != null ? demoMachineRootFolder
            : System.getProperty("user.dir")) + File.separator + "java" + File.separator + "core"
            + File.separator + "pom.xml";
    File mavenFile = new File(mavenFilePath);
    if (mavenFile.exists() && !mavenFile.isDirectory()) {

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document;
            document = builder.parse(mavenFile);
            NodeList list = document.getElementsByTagName("version");
            if (list != null && list.getLength() > 0) {
                aemDemoMachineVersion = list.item(0).getFirstChild().getNodeValue();
            }

        } catch (Exception e) {
            logger.error("Can't parse Maven pom.xml file");
        }

    }

    // Let's check if we have a valid build.xml file to work with...
    String buildFilePath = (demoMachineRootFolder != null ? demoMachineRootFolder
            : System.getProperty("user.dir")) + File.separator + "build.xml";
    logger.debug("Trying to load build file from " + buildFilePath);
    buildFile = new File(buildFilePath);
    if (buildFile.exists() && !buildFile.isDirectory()) {

        // Launching the main window
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {

                    UIManager.getLookAndFeelDefaults().put("defaultFont", new Font("Arial", Font.BOLD, 14));
                    AemDemo window = new AemDemo();
                    window.frameMain.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    } else {

        logger.error("No valid build.xml file to work with");
        System.exit(-1);

    }
}

From source file:Gen.java

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

    try {//from  w w w .j a  v a 2  s  .  c o  m

        File[] files = null;
        if (System.getProperty("dir") != null && !System.getProperty("dir").equals("")) {
            files = new File(System.getProperty("dir")).listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.toUpperCase().endsWith(".XML");
                };
            });
        } else {
            String fileName = System.getProperty("file") != null && !System.getProperty("file").equals("")
                    ? System.getProperty("file")
                    : "rjmap.xml";
            files = new File[] { new File(fileName) };
        }

        log.info("files : " + Arrays.toString(files));

        if (files == null || files.length == 0) {
            log.info("no files to parse");
            System.exit(0);
        }

        boolean formatsource = true;
        if (System.getProperty("formatsource") != null && !System.getProperty("formatsource").equals("")
                && System.getProperty("formatsource").equalsIgnoreCase("false")) {
            formatsource = false;
        }

        GEN_ROOT = System.getProperty("outputdir");

        if (GEN_ROOT == null || GEN_ROOT.equals("")) {
            GEN_ROOT = new File(files[0].getAbsolutePath()).getParent() + FILE_SEPARATOR + "distrib";
        }

        GEN_ROOT = new File(GEN_ROOT).getAbsolutePath().replace('\\', '/');
        if (GEN_ROOT.endsWith("/"))
            GEN_ROOT = GEN_ROOT.substring(0, GEN_ROOT.length() - 1);

        System.out.println("GEN ROOT:" + GEN_ROOT);

        MAPPING_JAR_NAME = System.getProperty("mappingjar") != null
                && !System.getProperty("mappingjar").equals("") ? System.getProperty("mappingjar")
                        : "mapping.jar";
        if (!MAPPING_JAR_NAME.endsWith(".jar"))
            MAPPING_JAR_NAME += ".jar";

        GEN_ROOT_SRC = GEN_ROOT + FILE_SEPARATOR + "src";
        GEN_ROOT_LIB = GEN_ROOT + FILE_SEPARATOR + "";

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        domFactory.setValidating(false);
        DocumentBuilder documentBuilder = domFactory.newDocumentBuilder();

        for (int f = 0; f < files.length; ++f) {
            log.info("parsing file : " + files[f]);
            Document document = documentBuilder.parse(files[f]);

            Vector<Node> initNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "initScript",
                    initNodes);
            for (int i = 0; i < initNodes.size(); ++i) {
                NamedNodeMap attrs = initNodes.elementAt(i).getAttributes();
                boolean embed = attrs.getNamedItem("embed") != null
                        && attrs.getNamedItem("embed").getNodeValue().equalsIgnoreCase("true");
                StringBuffer vbuffer = new StringBuffer();
                if (attrs.getNamedItem("inline") != null) {
                    vbuffer.append(attrs.getNamedItem("inline").getNodeValue());
                    vbuffer.append('\n');
                } else {
                    String fname = attrs.getNamedItem("name").getNodeValue();
                    if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') {
                        String path = files[f].getAbsolutePath();
                        path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR));
                        fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath();
                    }
                    vbuffer.append(Utils.getFileAsStringBuffer(fname));
                }
                initScriptBuffer.append(vbuffer);
                if (embed)
                    embedScriptBuffer.append(vbuffer);
            }

            Vector<Node> packageInitNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "packageScript",
                    packageInitNodes);
            for (int i = 0; i < packageInitNodes.size(); ++i) {
                NamedNodeMap attrs = packageInitNodes.elementAt(i).getAttributes();
                String packageName = attrs.getNamedItem("package").getNodeValue();

                if (packageName.equals(""))
                    packageName = "rGlobalEnv";

                if (!packageName.endsWith("Function"))
                    packageName += "Function";
                if (packageEmbedScriptHashMap.get(packageName) == null) {
                    packageEmbedScriptHashMap.put(packageName, new StringBuffer());
                }
                StringBuffer vbuffer = packageEmbedScriptHashMap.get(packageName);

                // if (!packageName.equals("rGlobalEnvFunction")) {
                // vbuffer.append("library("+packageName.substring(0,packageName.lastIndexOf("Function"))+")\n");
                // }

                if (attrs.getNamedItem("inline") != null) {
                    vbuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n");
                    initScriptBuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n");
                } else {
                    String fname = attrs.getNamedItem("name").getNodeValue();
                    if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') {
                        String path = files[f].getAbsolutePath();
                        path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR));
                        fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath();
                    }
                    StringBuffer fileBuffer = Utils.getFileAsStringBuffer(fname);
                    vbuffer.append(fileBuffer);
                    initScriptBuffer.append(fileBuffer);
                }
            }

            Vector<Node> functionsNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "functions"), "function",
                    functionsNodes);
            for (int i = 0; i < functionsNodes.size(); ++i) {
                NamedNodeMap attrs = functionsNodes.elementAt(i).getAttributes();
                String functionName = attrs.getNamedItem("name").getNodeValue();

                boolean forWeb = attrs.getNamedItem("forWeb") != null
                        && attrs.getNamedItem("forWeb").getNodeValue().equalsIgnoreCase("true");

                String signature = (attrs.getNamedItem("signature") == null ? ""
                        : attrs.getNamedItem("signature").getNodeValue() + ",");
                String renameTo = (attrs.getNamedItem("renameTo") == null ? null
                        : attrs.getNamedItem("renameTo").getNodeValue());

                HashMap<String, FAttributes> sigMap = Globals._functionsToPublish.get(functionName);

                if (sigMap == null) {
                    sigMap = new HashMap<String, FAttributes>();
                    Globals._functionsToPublish.put(functionName, sigMap);

                    if (attrs.getNamedItem("returnType") == null) {
                        _functionsVector.add(new String[] { functionName });
                    } else {
                        _functionsVector.add(
                                new String[] { functionName, attrs.getNamedItem("returnType").getNodeValue() });
                    }

                }

                sigMap.put(signature, new FAttributes(renameTo, forWeb));

                if (forWeb)
                    _webPublishingEnabled = true;

            }

            if (System.getProperty("targetjdk") != null && !System.getProperty("targetjdk").equals("")
                    && System.getProperty("targetjdk").compareTo("1.5") < 0) {
                if (_webPublishingEnabled || (System.getProperty("ws.r.api") != null
                        && System.getProperty("ws.r.api").equalsIgnoreCase("true"))) {
                    log.info("be careful, web publishing disabled beacuse target JDK<1.5");
                }
                _webPublishingEnabled = false;
            } else {

                if (System.getProperty("ws.r.api") == null || System.getProperty("ws.r.api").equals("")
                        || !System.getProperty("ws.r.api").equalsIgnoreCase("false")) {
                    _webPublishingEnabled = true;
                }

                if (_webPublishingEnabled && System.getProperty("java.version").compareTo("1.5") < 0) {
                    log.info("be careful, web publishing disabled beacuse a JDK<1.5 is in use");
                    _webPublishingEnabled = false;
                }
            }

            Vector<Node> s4Nodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "s4classes"), "class", s4Nodes);

            if (s4Nodes.size() > 0) {
                String formalArgs = "";
                String signature = "";
                for (int i = 0; i < s4Nodes.size(); ++i) {
                    NamedNodeMap attrs = s4Nodes.elementAt(i).getAttributes();
                    String s4Name = attrs.getNamedItem("name").getNodeValue();
                    formalArgs += "p" + i + (i == s4Nodes.size() - 1 ? "" : ",");
                    signature += "'" + s4Name + "'" + (i == s4Nodes.size() - 1 ? "" : ",");
                }
                String genBeansScriptlet = "setGeneric('" + PUBLISH_S4_HEADER + "', function(" + formalArgs
                        + ") standardGeneric('" + PUBLISH_S4_HEADER + "'));" + "setMethod('" + PUBLISH_S4_HEADER
                        + "', signature(" + signature + ") , function(" + formalArgs + ") {   })";
                initScriptBuffer.append(genBeansScriptlet);
                _functionsVector.add(new String[] { PUBLISH_S4_HEADER, "numeric" });
            }

        }

        if (!new File(GEN_ROOT_LIB).exists())
            regenerateDir(GEN_ROOT_LIB);
        else {
            clean(GEN_ROOT_LIB, true);
        }

        for (int i = 0; i < rwebservicesScripts.length; ++i)
            DirectJNI.getInstance().getRServices().sourceFromResource(rwebservicesScripts[i]);

        String lastStatus = DirectJNI.getInstance().runR(new ExecutionUnit() {
            public void run(Rengine e) {
                DirectJNI.getInstance().toggleMarker();
                DirectJNI.getInstance().sourceFromBuffer(initScriptBuffer.toString());
                log.info(" init  script status : " + DirectJNI.getInstance().cutStatusSinceMarker());

                for (int i = 0; i < _functionsVector.size(); ++i) {

                    String[] functionPair = _functionsVector.elementAt(i);
                    log.info("dealing with : " + functionPair[0]);

                    regenerateDir(GEN_ROOT_SRC);

                    String createMapStr = "createMap(";
                    boolean isGeneric = e.rniGetBoolArrayI(
                            e.rniEval(e.rniParse("isGeneric(\"" + functionPair[0] + "\")", 1), 0))[0] == 1;

                    log.info("is Generic : " + isGeneric);
                    if (isGeneric) {
                        createMapStr += functionPair[0];
                    } else {
                        createMapStr += "\"" + functionPair[0] + "\"";
                    }
                    createMapStr += ", outputDirectory=\"" + GEN_ROOT_SRC
                            .substring(0, GEN_ROOT_SRC.length() - "/src".length()).replace('\\', '/') + "\"";
                    createMapStr += ", typeMode=\"robject\"";
                    createMapStr += (functionPair.length == 1 || functionPair[1] == null
                            || functionPair[1].trim().equals("") ? ""
                                    : ", S4DefaultTypedSig=TypedSignature(returnType=\"" + functionPair[1]
                                            + "\")");
                    createMapStr += ")";

                    log.info("------------------------------------------");
                    log.info("-- createMapStr=" + createMapStr);
                    DirectJNI.getInstance().toggleMarker();
                    e.rniEval(e.rniParse(createMapStr, 1), 0);
                    String createMapStatus = DirectJNI.getInstance().cutStatusSinceMarker();
                    log.info(" createMap status : " + createMapStatus);
                    log.info("------------------------------------------");

                    deleteDir(GEN_ROOT_SRC + "/org/kchine/r/rserviceJms");
                    compile(GEN_ROOT_SRC);
                    jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", null);

                    URL url = null;
                    try {
                        url = new URL(
                                "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar")
                                        .replace('\\', '/') + "!/");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    DirectJNI.generateMaps(url, true);
                }

            }
        });

        log.info(lastStatus);

        log.info(DirectJNI._rPackageInterfacesHash);
        regenerateDir(GEN_ROOT_SRC);
        for (int i = 0; i < _functionsVector.size(); ++i) {
            unjar(GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", GEN_ROOT_SRC);
        }

        regenerateRPackageClass(true);

        generateS4BeanRef();

        if (formatsource)
            applyJalopy(GEN_ROOT_SRC);

        compile(GEN_ROOT_SRC);

        for (String k : DirectJNI._rPackageInterfacesHash.keySet()) {
            Rmic rmicTask = new Rmic();
            rmicTask.setProject(_project);
            rmicTask.setTaskName("rmic_packages");
            rmicTask.setClasspath(new Path(_project, GEN_ROOT_SRC));
            rmicTask.setBase(new File(GEN_ROOT_SRC));
            rmicTask.setClassname(k + "ImplRemote");
            rmicTask.init();
            rmicTask.execute();
        }

        // DirectJNI._rPackageInterfacesHash=new HashMap<String,
        // Vector<Class<?>>>();
        // DirectJNI._rPackageInterfacesHash.put("org.bioconductor.packages.rGlobalEnv.rGlobalEnvFunction",new
        // Vector<Class<?>>());

        if (_webPublishingEnabled) {

            jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar", null);
            URL url = new URL(
                    "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").replace('\\', '/') + "!/");
            ClassLoader cl = new URLClassLoader(new URL[] { url }, Globals.class.getClassLoader());

            for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
                if (cl.loadClass(className + "Web").getDeclaredMethods().length == 0)
                    continue;
                log.info("######## " + className);

                WsGen wsgenTask = new WsGen();
                wsgenTask.setProject(_project);
                wsgenTask.setTaskName("wsgen");

                FileSet rjb_fileSet = new FileSet();
                rjb_fileSet.setProject(_project);
                rjb_fileSet.setDir(new File("."));
                rjb_fileSet.setIncludes("RJB.jar");

                DirSet src_dirSet = new DirSet();
                src_dirSet.setDir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                Path classPath = new Path(_project);
                classPath.addFileset(rjb_fileSet);
                classPath.addDirset(src_dirSet);
                wsgenTask.setClasspath(classPath);
                wsgenTask.setKeep(true);
                wsgenTask.setDestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                wsgenTask.setResourcedestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                wsgenTask.setSei(className + "Web");

                wsgenTask.init();
                wsgenTask.execute();
            }

            new File(GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").delete();

        }

        embedRScripts();

        HashMap<String, String> marker = new HashMap<String, String>();
        marker.put("RJBMAPPINGJAR", "TRUE");

        Properties props = new Properties();
        props.put("PACKAGE_NAMES", PoolUtils.objectToHex(DirectJNI._packageNames));
        props.put("S4BEANS_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMapping));
        props.put("S4BEANS_REVERT_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMappingRevert));
        props.put("FACTORIES_MAPPING", PoolUtils.objectToHex(DirectJNI._factoriesMapping));
        props.put("S4BEANS_HASH", PoolUtils.objectToHex(DirectJNI._s4BeansHash));
        props.put("R_PACKAGE_INTERFACES_HASH", PoolUtils.objectToHex(DirectJNI._rPackageInterfacesHash));
        props.put("ABSTRACT_FACTORIES", PoolUtils.objectToHex(DirectJNI._abstractFactories));
        new File(GEN_ROOT_SRC + "/" + "maps").mkdirs();
        FileOutputStream fos = new FileOutputStream(GEN_ROOT_SRC + "/" + "maps/rjbmaps.xml");
        props.storeToXML(fos, null);
        fos.close();

        jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + MAPPING_JAR_NAME, marker);

        if (_webPublishingEnabled)
            genWeb();

        DirectJNI._mappingClassLoader = null;

    } finally {

        System.exit(0);

    }
}

From source file:client.QueryLastFm.java

License:asdf

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

    // isAlreadyInserted("asdfs","jas,jnjkah");

    // FileWriter fw = new FileWriter(".\\tracks.csv");
    OutputStream track_os = new FileOutputStream(".\\tracks.csv");
    PrintWriter out = new PrintWriter(new OutputStreamWriter(track_os, "UTF-8"));

    OutputStream track_id_os = new FileOutputStream(".\\track_id_sim_track_id.csv");
    PrintWriter track_id_out = new PrintWriter(new OutputStreamWriter(track_id_os, "UTF-8"));

    track_id_out.print("");

    ByteArrayInputStream input;//from w  w  w . jav  a  2 s  .c  o m
    Document doc = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();

    String trackName = "";
    String artistName = "";
    String sourceMbid = "";
    out.print("ID");// first row first column
    out.print(",");
    out.print("TrackName");// first row second column
    out.print(",");
    out.println("Artist");// first row third column

    track_id_out.print("source");// first row second column
    track_id_out.print(",");
    track_id_out.println("target");// first row third column
    // track_id_out.print(",");
    // track_id_out.println("type");// first row third column

    // out.flush();

    // out.close();

    // fw.close();

    // os.close();

    try {
        URI uri = new URIBuilder().setScheme("http").setHost("ws.audioscrobbler.com").setPath("/2.0/")
                .setParameter("method", "track.getsimilar").setParameter("artist", "cher")
                .setParameter("track", "believe").setParameter("limit", "100")
                .setParameter("api_key", "88858618961414f8bec919bddd057044").build();

        // new URIBuilder().
        HttpGet request = new HttpGet(uri);

        // request.
        // This is useful for last.fm logging and preventing them from blocking this client
        request.setHeader(HttpHeaders.USER_AGENT,
                "nileshmore@gatech.edu - ClassAssignment at GeorgiaTech Non-commercial use");

        HttpGet httpGet = new HttpGet(
                "http://ws.audioscrobbler.com/2.0/?method=track.getsimilar&artist=cher&track=believe&limit=4&api_key=88858618961414f8bec919bddd057044");
        CloseableHttpResponse response = httpclient.execute(request);

        int statusCode = response.getStatusLine().getStatusCode();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            if (statusCode == 200) {
                HttpEntity entity1 = response.getEntity();
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));
                Document document = builder.parse((response.getEntity().getContent()));
                Element root = document.getDocumentElement();
                root.normalize();
                // Need to focus and resolve this part
                NodeList nodes;
                nodes = root.getChildNodes();

                nodes = root.getElementsByTagName("track");
                if (nodes.getLength() == 0) {
                    // System.out.println("empty");
                    return;
                }
                Node trackNode;
                for (int k = 0; k < nodes.getLength(); k++) // can access all tracks now
                {
                    trackNode = nodes.item(k);
                    NodeList trackAttributes = trackNode.getChildNodes();

                    // check if mbid is present in track attributes
                    // System.out.println("Length  " + (trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0));

                    if ((trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0)) {
                        if (((Element) trackAttributes.item(5)).hasChildNodes())
                            ;// System.out.println("Go aHead");
                        else
                            continue;
                    } else
                        continue;

                    for (int n = 0; n < trackAttributes.getLength(); n++) {
                        Node attribute = trackAttributes.item(n);
                        if ((attribute.getNodeName().compareToIgnoreCase("name")) == 0) {
                            // System.out.println(((Element)attribute).getFirstChild().getNodeValue());
                            trackName = ((Element) attribute).getFirstChild().getNodeValue(); // make string encoding as UTF-8 ************ 

                        }

                        if ((attribute.getNodeName().compareToIgnoreCase("mbid")) == 0) {
                            // System.out.println(n +  "   " +  ((Element)attribute).getFirstChild().getNodeValue());
                            sourceMbid = attribute.getFirstChild().getNodeValue();

                        }

                        if ((attribute.getNodeName().compareToIgnoreCase("artist")) == 0) {
                            NodeList ArtistNodeList = attribute.getChildNodes();
                            for (int j = 0; j < ArtistNodeList.getLength(); j++) {
                                Node Artistnode = ArtistNodeList.item(j);
                                if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) {
                                    // System.out.println(((Element)Artistnode).getFirstChild().getNodeValue());
                                    artistName = ((Element) Artistnode).getFirstChild().getNodeValue();
                                }
                            }
                        }
                    }
                    out.print(sourceMbid);
                    out.print(",");
                    out.print(trackName);
                    out.print(",");
                    out.println(artistName);
                    // out.print(",");
                    findSimilarTracks(track_id_out, sourceMbid, trackName, artistName);

                }
                track_id_out.flush();

                out.flush();
                out.close();
                track_id_out.close();
                track_os.close();

                // fw.close();
                Element trac = (Element) nodes.item(0);
                // trac.normalize();
                nodes = trac.getChildNodes();
                // System.out.println(nodes.getLength());

                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    // System.out.println(node.getNodeName());
                    if ((node.getNodeName().compareToIgnoreCase("name")) == 0) {
                        // System.out.println(((Element)node).getFirstChild().getNodeValue());
                    }

                    if ((node.getNodeName().compareToIgnoreCase("mbid")) == 0) {
                        // System.out.println(((Element)node).getFirstChild().getNodeValue());
                    }

                    if ((node.getNodeName().compareToIgnoreCase("artist")) == 0) {

                        // System.out.println("Well");
                        NodeList ArtistNodeList = node.getChildNodes();
                        for (int j = 0; j < ArtistNodeList.getLength(); j++) {
                            Node Artistnode = ArtistNodeList.item(j);
                            if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) {
                                /* System.out.println(((Element)Artistnode).getFirstChild().getNodeValue());*/
                            }
                            /*System.out.println(Artistnode.getNodeName());*/
                        }
                    }

                }
                /*if(node instanceof Element){
                  //a child element to process
                  Element child = (Element) node;
                  String attribute = child.getAttribute("width");
                }*/

                // System.out.println(root.getAttribute("status"));
                NodeList tracks = root.getElementsByTagName("track");
                Element track = (Element) tracks.item(0);
                // System.out.println(track.getTagName());
                track.getChildNodes();

            } else {
                System.out.println("failed with status" + response.getStatusLine());
            }
            // input = (ByteArrayInputStream)entity1.getContent();
            // do something useful with the response body
            // and ensure it is fully consumed
        } finally {
            response.close();
        }
    }

    finally {
        System.out.println("Exited succesfully.");
        httpclient.close();

    }
}

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 av a2 s . co m
 * 
 * @param args
 * @throws IOException */

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

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

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

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

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

    File directoryOfLogfile = new File(pathToLogfile);

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

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

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

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

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

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

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

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

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

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

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

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

    File tmpDir = new File(pathToWorkDir);

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

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

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

    String name = tmpDir.getAbsolutePath();

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

        Matcher matcher = pattern.matcher(element);

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

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

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

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

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

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

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

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

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

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

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

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

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

    name = valDatei.getAbsolutePath();

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

        Matcher matcher = pattern.matcher(element);

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

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

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

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

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

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

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

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

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

                factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

            countSummaryNio = pdfaCountNio + siardCountNio + tiffCountNio + jp2CountNio;

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

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

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

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

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

                FileReader fr = null;

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

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

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

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

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

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

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

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

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

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

                    factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

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

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

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

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

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

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

                            factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        }

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

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

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

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

            factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

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

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

            doc.getDocumentElement().normalize();

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

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

                Node nNode = nList.item(temp);

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

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

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

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

From source file:Main.java

public static Document stringToDom(String xmlSource)
        throws SAXException, ParserConfigurationException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(new InputSource(new StringReader(xmlSource)));
}

From source file:JAXPTransformNode.java

public static Document buildDoc(String document) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    DocumentBuilder db = dbf.newDocumentBuilder();

    Document theDocument = db.parse(new File(document));

    return theDocument;

}

From source file:Main.java

private static Document getCurrentstudents() throws Exception {
    DocumentBuilder builder = dbFactory.newDocumentBuilder();
    Document docstudent = builder.parse(new StringBufferInputStream(studentData));
    return docstudent;
}

From source file:Main.java

public static boolean validateXmlByDtd(String xmlPath)
        throws FileNotFoundException, SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);//from ww w. ja v  a2s  .c o m
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.parse(new File(xmlPath));
    return true;
}

From source file:Main.java

static void formatXMLFile(String file) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new InputStreamReader(new FileInputStream(file))));

    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.setOutputProperty(OutputKeys.METHOD, "xml");
    xformer.setOutputProperty(OutputKeys.INDENT, "yes");
    xformer.setOutputProperty("b;http://xml.apache.org/xsltd;indent-amount", "4");
    xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    Source source = new DOMSource(document);
    Result result = new StreamResult(new File(file));
    xformer.transform(source, result);/* ww w.  j  av a  2  s . c om*/
}