Example usage for org.w3c.dom Document getDocumentElement

List of usage examples for org.w3c.dom Document getDocumentElement

Introduction

In this page you can find the example usage for org.w3c.dom Document getDocumentElement.

Prototype

public Element getDocumentElement();

Source Link

Document

This is a convenience attribute that allows direct access to the child node that is the document element of the document.

Usage

From source file:Main.java

public static void main(String args[]) {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true); // Set namespace aware
    builderFactory.setValidating(true); // and validating parser feaures
    builderFactory.setIgnoringElementContentWhitespace(true);

    DocumentBuilder builder = null;
    try {//w  w  w . j ava  2 s. c  om
        builder = builderFactory.newDocumentBuilder(); // Create the parser
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    Document xmlDoc = null;

    try {
        xmlDoc = builder.parse(new InputSource(new StringReader(xmlString)));

    } catch (SAXException e) {
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();
    }
    DocumentType doctype = xmlDoc.getDoctype();
    if (doctype == null) {
        System.out.println("DOCTYPE is null");
    } else {
        System.out.println("DOCTYPE node:\n" + doctype.getInternalSubset());
    }

    System.out.println("\nDocument body contents are:");
    listNodes(xmlDoc.getDocumentElement(), ""); // Root element & children
}

From source file:edu.lternet.pasta.datapackagemanager.LevelOneEMLFactory.java

public static void main(String[] args) {
    String filePath = args[0];//from   ww w.  j  av  a2 s. c  o m
    String newFilePath = String.format("%s_new", filePath);
    File newFile = new File(newFilePath);
    LevelOneEMLFactory loef = new LevelOneEMLFactory();
    File levelZeroEMLFile = new File(filePath);
    //String levelOneEMLString = null;
    //Node documentElement = levelZeroEMLDocument.getDocumentElement();
    //String levelZeroEMLString = XMLUtilities.getDOMTreeAsString(documentElement);
    try {
        Document levelZeroEMLDocument = XmlUtility.xmlFileToDocument(levelZeroEMLFile);
        loef.checkIntellectualRights(levelZeroEMLDocument);
        Node documentElement = levelZeroEMLDocument.getDocumentElement();
        String levelOneEMLString = XMLUtilities.getDOMTreeAsString(documentElement);
        FileUtils.writeStringToFile(newFile, levelOneEMLString, "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:MainClass.java

public static void main(String args[]) {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setValidating(true); // and validating parser feaures
    builderFactory.setIgnoringElementContentWhitespace(true);

    DocumentBuilder builder = null;
    try {// www.  j  a  v a 2 s . com
        builder = builderFactory.newDocumentBuilder(); // Create the parser
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    Document xmlDoc = null;

    try {
        xmlDoc = builder.parse(new InputSource(new StringReader(xmlString)));

    } catch (SAXException e) {
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();
    }
    DocumentType doctype = xmlDoc.getDoctype();
    if (doctype == null) {
        System.out.println("DOCTYPE is null");
    } else {
        System.out.println("DOCTYPE node:\n" + doctype.getInternalSubset());
    }

    System.out.println("\nDocument body contents are:");
    listNodes(xmlDoc.getDocumentElement(), ""); // Root element & children
}

From source file:com.wrmsr.nativity.x86.App.java

public static void main(String[] args) throws Exception {
    logger.info("hi");

    Document doc;
    try (InputStream is = App.class.getClassLoader().getResourceAsStream("x86reference.xml")) {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(is);//from  w  w  w . jav a  2 s  .  c o  m
    }

    //optional, but recommended
    //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    doc.getDocumentElement().normalize();

    List<Ref.Entry> entries = Lists.newArrayList();
    Ref.Parsing.parseRoot(doc, entries);
    ByteTrie<Ref.Entry> trie = DisImpl.buildTrie(entries);

    System.out.println(trie.toDetailedString());
    System.out.println();
    System.out.println();

    // Dis.run(trie);

    Ordering<Pair<Ref.Operand.Type, Ref.Operand.Address>> ord = Ordering.from((o1, o2) -> {
        int c = ObjectUtils.compare(o1.getLeft(), o2.getLeft());
        if (c == 0) {
            c = ObjectUtils.compare(o1.getRight(), o2.getRight());
        }
        return c;
    });

    Set<Pair<Ref.Operand.Type, Ref.Operand.Address>> set = Sets.newHashSet();
    for (Ref.Entry entry : entries) {
        for (Ref.Syntax syntax : entry.getSyntaxes()) {
            for (Ref.Operand operand : syntax.getOperands()) {
                set.add(new ImmutablePair<>(operand.type, operand.address));
            }
        }
    }
    for (Pair<Ref.Operand.Type, Ref.Operand.Address> pair : ord.sortedCopy(set)) {
        System.out.println(pair);
    }
    System.out.println("\n");

    DisImpl.run(trie);
}

From source file:com.occamlab.te.parsers.ImageParser.java

public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        System.err.println("Parameters: xml_url image_url");
        return;//  w  w  w.  j  a v  a2s  . c o m
    }

    java.net.URL xml_url;
    try {
        xml_url = new java.net.URL(args[0]);
    } catch (Exception e) {
        jlogger.log(Level.INFO, "Error building xmlurl, will prefix file://", e);

        xml_url = new java.net.URL("file://" + args[0]);
    }

    java.net.URL image_url;
    try {
        image_url = new java.net.URL(args[1]);
    } catch (Exception e) {
        jlogger.log(Level.INFO, "Error building xmlurl, will prefix file://", e);

        image_url = new java.net.URL("file://" + args[1]);
    }

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(xml_url.openStream());
    // Element instruction = (Element)
    // doc.getElementsByTagNameNS("http://www.occamlab.com/te/parsers",
    // "ImageParser").item(0);
    Element instruction = (Element) doc.getDocumentElement();

    PrintWriter logger = new PrintWriter(System.out);
    InputStream image_is = image_url.openConnection().getInputStream();

    Document result = parse(image_is, instruction, logger);
    logger.flush();

    if (result != null) {
        TransformerFactory tf = TransformerFactory.newInstance();
        try {
            tf.setAttribute("http://saxon.sf.net/feature/strip-whitespace", "all");
        } catch (IllegalArgumentException e) {
            jlogger.log(Level.INFO, "setAttribute(\"http://saxon.sf.net/feature/strip-whitespace\", \"all\");",
                    e);

        }
        Transformer t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.transform(new DOMSource(result), new StreamResult(System.out));
    }

    System.exit(0);
}

From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificatorCommandLineTool.java

/**
 * Main (starting) method of the command line application.
 *
 * @param argv Array of command line arguments that are expected to be
 * filesystem paths to input XML documents with MathML to be unified.
 * @throws ParserConfigurationException If a XML DOM builder cannot be
 * created with the configuration requested.
 *//*w w w.  ja  v  a 2 s.c  om*/
public static void main(String argv[]) throws ParserConfigurationException {

    final Options options = new Options();
    options.addOption("p", "operator-unification", false, "unify operator in addition to other types of nodes");
    options.addOption("h", "help", false, "print help");

    final CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, argv);
    } catch (ParseException ex) {
        printHelp(options);
        System.exit(1);
    }

    if (line != null) {
        if (line.hasOption('h')) {
            printHelp(options);
            System.exit(0);
        }
        operatorUnification = line.hasOption('p');

        final List<String> arguments = Arrays.asList(line.getArgs());
        if (arguments.size() > 0) {

            Document outerDocument = DOMBuilder.getDocumentBuilder().newDocument();
            Node rootNode = outerDocument.createElementNS(UNIFIED_MATHML_NS,
                    UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ROOT_ELEM);
            outerDocument.appendChild(rootNode);

            for (String filepath : arguments) {
                try {

                    Document doc = DOMBuilder.buildDocFromFilepath(filepath);
                    MathMLUnificator.unifyMathML(doc, operatorUnification);
                    if (arguments.size() == 1) {
                        xmlStdoutSerializer(doc);
                    } else {
                        Node itemNode = rootNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS,
                                UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_ELEM);
                        Attr filenameAttr = itemNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS,
                                UNIFIED_MATHML_NS_PREFIX + ":"
                                        + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_FILEPATH_ATTR);
                        filenameAttr.setTextContent(String.valueOf(filepath));
                        ((Element) itemNode).setAttributeNodeNS(filenameAttr);
                        itemNode.appendChild(
                                rootNode.getOwnerDocument().importNode(doc.getDocumentElement(), true));
                        rootNode.appendChild(itemNode);

                    }

                } catch (SAXException | IOException ex) {
                    Logger.getLogger(MathMLUnificatorCommandLineTool.class.getName()).log(Level.SEVERE,
                            "Failed processing of file: " + filepath, ex);
                }
            }

            if (rootNode.getChildNodes().getLength() > 0) {
                xmlStdoutSerializer(rootNode.getOwnerDocument());
            }

        } else {
            printHelp(options);
            System.exit(0);
        }
    }

}

From source file:Gen.java

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

    try {/*from  www. 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:ch.kostceco.tools.kostsimy.KOSTSimy.java

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

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

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

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

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

    File directoryOfLogfile = new File(pathToLogfile);

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

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

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

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

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

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

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

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

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

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

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

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

    File tmpDir = new File(pathToWorkDir);

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

    // Im Pfad keine Sonderzeichen Programme knnen evtl abstrzen

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

    String name = tmpDir.getAbsolutePath();

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

        Matcher matcher = pattern.matcher(element);

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

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

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

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

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

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

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

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

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

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

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

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

            factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

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

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

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

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

                        countVal = countVal + 1;

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

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

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

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

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

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

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

            factory.setExpandEntityReferences(false);

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

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

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

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

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

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

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

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

From source file:edu.kit.dama.util.test.LocalAccessTest.java

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

    IFileTree tree = DataOrganizationUtils.createTreeFromFile("1q2345", new AbstractFile(new File(
            "/Users/jejkal/NetBeansProjects/KITDM/trunk/Docker/KITDM/share/log/cd37731e22d7df46722fa41efe2c5511ee83d3ee")),
            true);// w w w  .  j a  v  a2s.co m
    IDataOrganizationNode generatedNode = Util.getNodeByName(tree.getRootNode(),
            Constants.STAGING_GENERATED_FOLDER_NAME);

    //DataOrganizationUtils.printTree(tree.getRootNode(), true);
    DataOrganizationUtils.printTree((ICollectionNode) generatedNode, true);

    if (generatedNode == null || !(generatedNode instanceof ICollectionNode)
            || ((ICollectionNode) generatedNode).getChildren().isEmpty()) {
        System.out.println(
                "Node for 'generated' content not found or is empty. Skip registering view 'generated'.");
    } else {
        System.out.println("OK!");
    }
    if (true) {
        return;
    }

    //     DigitalObject c = DigitalObject.factoryNewDigitalObject();
    //System.out.println(c.getDigitalObjectIdentifier());
    /*   CustomDigitalObject c = new CustomDigitalObject();
    c.setDigitalObjectId(new DigitalObjectId(UUID.randomUUID().toString()));
    c.setLabel("TEst");
    c.setNote("ee123");
    System.out.println("EDS");
    mdm.save(c);
    System.out.println("ODN");*/
    // mdm.close();
    String accessKey = "admin";
    String accessSecret = "dama14";
    String restBaseUrl = "http://localhost:8080/KITDM";
    SimpleRESTContext context = new SimpleRESTContext(accessKey, accessSecret);
    /*  DigitalObject newDigitalObject= DigitalObject.factoryNewDigitalObject();
    newDigitalObject.setLabel("Sample DigitalObject");
    newDigitalObject.setNote("This is a sample");
    newDigitalObject.setStartDate(new Date());*/
    long s = System.currentTimeMillis();
    BaseMetaDataRestClient client;

    client = new BaseMetaDataRestClient(restBaseUrl + "/rest/basemetadata/", context);

    long t = 0;
    for (int i = 0; i < 100; i++) {

        DigitalObjectWrapper o = client.getDigitalObjectById(57l);
        t += (System.currentTimeMillis() - s);
        s = System.currentTimeMillis();
    }

    System.out.println("T " + (t / 100l));

    /*DigitalObject ob = o.getEntities().get(0);
    System.out.println(ob.getDigitalObjectIdentifier());
    System.out.println(ob.getDigitalObjectId().getStringRepresentation());*/
    /*Study newStudy =  Study.factoryNewStudy();
           newStudy.setTopic("Sample Study");
           newStudy.setNote("This is a sample");
           newStudy.setStartDate(new Date());
       Investigation newInvestigation= Investigation.factoryNewInvestigation();
           newInvestigation.setTopic("Sample Investigation");
           newInvestigation.setNote("This is a sample");
           newInvestigation.setStartDate(new Date());
            client = new BaseMetaDataRestClient(restBaseUrl + "/rest/basemetadata/", context);
            
           //Create a new study. The study will be assigned to the default group whose ID we've obtained above.
           StudyWrapper studyWrapper = client.addStudy(newStudy, Constants.USERS_GROUP_ID);
           //Assign returned study to 'newStudy' as the created entity now contains a valid studyId.
           newStudy = studyWrapper.getEntities().get(0);
            
           //Use the studyId to add a new investigation to the study we've just created.
           InvestigationWrapper investigationWrapper = client.addInvestigationToStudy(newStudy.getStudyId(), newInvestigation, Constants.USERS_GROUP_ID);
           //Assign returned investigation to 'newInvestigation' as the created entity now contains a valid investigationId.
           newInvestigation = investigationWrapper.getEntities().get(0);
            
           //Use the investigationId to add a new digital object to the investigation just created.
                   
           DigitalObjectWrapper digitalObjectWrapper = client.addDigitalObjectToInvestigation(newInvestigation.getInvestigationId(), newDigitalObject, Constants.USERS_GROUP_ID);
           //Assign returned digitalObject to 'newDigitalObject' as the created entity now contains a valid objectId.
           newDigitalObject = digitalObjectWrapper.getEntities().get(0);
           System.out.println("OK");
                   
            */
    /*StagingServiceRESTClient client = new StagingServiceRESTClient("http://localhost:8080/KITDM/rest/staging/", new SimpleRESTContext("admin", "dama14"));
            
           FileTreeImpl f = new FileTreeImpl();
           f.setDigitalObjectId(new DigitalObjectId("f735e33e-8821-460e-9d86-90281e6f91e1"));
           f.setViewName("default");
           CollectionNodeImpl col = new CollectionNodeImpl();
           col.setName("myImage");
           FileNodeImpl fi = new FileNodeImpl(new LFNImpl("file:/Users/jejkal/tmp/2016/5/16/admin/d83bdb349f073714cec972958ab5737e7fe28f27/data/images/StructureAdminMetadata.png"));
           fi.setNodeId(500l);
           col.addChild(fi);
           f.getRootNode().addChild(col);
            
           System.out.println(client.createDownload("f735e33e-8821-460e-9d86-90281e6f91e1", "273f477a-546c-41d7-9037-61723de4dd36", f, "USERS"));
            */

    /*String token = new String(Base64.getDecoder().decode("YWRtaW46ZGFtYTE0"));
    int splitIndex = token.indexOf(":");
    if (splitIndex < 1) {
        throw new UnauthorizedAccessAttemptException("Invalid basic authentication header.");
    }
            
    String user = token.substring(0, splitIndex);
    String secret = token.substring(splitIndex+1);
    System.out.println(user);
    System.out.println(secret);*/
    /* System.out.println(DigestUtils.md5Hex("admin:kitdm:dama14"));
        String md5a1 = DigestUtils.md5Hex("admin:kitdm:dama14");
            
                        String md5a2 = DigestUtils.md5Hex("GET:/KITDM/rest/basemetadata/investigations?groupId=USERS");
          Map<String, Object> custom = new HashMap<>();
           custom.put("repository.context", "empty");
           AdalapiProtocolConfiguration config = AdalapiProtocolConfiguration.factoryConfiguration(new URL("http://dreamatico.com/data_images/kitten/kitten-2.jpg"),SimpleHttp.class.getCanonicalName(), KITDMAuthenticator.class.getCanonicalName(), custom);
            
            
                   
                   
           String clientHash = "602ce28e72c44bf003556f4b0e5b678d";
           String serverDigest = DigestUtils.md5Hex(md5a1 + ":12345:" + md5a2);
                   
           System.out.println(md5a1);
        System.out.println(md5a2);
            
           System.out.println(serverDigest);
        System.out.println(clientHash);
            */
    /* String tokenKey = CryptUtil.stringToSHA1("test12345");
            System.out.println(tokenKey);
            IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
            mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
    ServiceAccessToken accessToken = ServiceAccessUtil.getAccessToken(mdm, tokenKey, "simpleRestToken");
           System.out.println(accessToken);*/
    // AbstractFile fi = new AbstractFile(new URL("http://ipelsdf1.lsdf.kit.edu:8889/webdav/admin/1/data/screen.jpg"));
    //SimpleRESTContext context = new SimpleRESTContext("admin", "dama14");

    /* UserGroupWrapper groupWrapper = client1.getAllGroups(0, Integer.MAX_VALUE);
    System.out.println("The following groups were found:");
    for (UserGroup group : groupWrapper.getEntities()) {
    System.out.println(" Name: " + group.getGroupName());
    UserDataWrapper members = client1.getUsersOfGroup(group.getId(), 0, Integer.MAX_VALUE);
    System.out.println(" The group has the following members:");
    for (UserData user : members.getEntities()) {
        System.out.println("   - " + user.getFullname() + " (" + user.getDistinguishedName() + ")" + user.getUserId());
    }
    }
    //  client1.addGroup("uniqueId", "Another Custom Group", "A custom group created for testing purposes.");
            
    UserDataWrapper userWrapper = client1.getAllUsers(Constants.USERS_GROUP_ID, 0, Integer.MAX_VALUE);
    for (UserData user : userWrapper.getEntities()) {
    System.out.println(" - " + user.getFullname() + " (" + user.getDistinguishedName() + ")");
    }
            
    //distinguished name or id
    int modified = client1.addUserToGroup(3l, "tester").getCount();
            
    System.out.println(client1.removeUserFromGroup(3l, 421l).getCount());
     */
    /* UserDataWrapper newUser = client1.addUser(Constants.USERS_GROUP_ID, "Test", "User", "test@mail.org", newUserIdentifier);
           System.out.println(newUser.getEntities().get(0).getDistinguishedName());
           //distinguished name or id
           int modified = client1.addUserToGroup(3l, newUserIdentifier).getCount();
            */
    /*  UserGroupWrapper groupWrapper = client.getAllGroups(0, Integer.MAX_VALUE);
            
           for (UserGroup group : groupWrapper.getEntities()) {
    System.out.println("GName: " + group.getGroupName());
           }
            
           UserDataWrapper userWrapper = client.getAllUsers("eCod", 0, Integer.MAX_VALUE);
           for (UserData user : userWrapper.getEntities()) {
    System.out.println("UName: " + user.getDistinguishedName());
            
           }*/
    //        AbstractRandomDataProviderStrategy stra = new AbstractRandomDataProviderStrategy() {
    //            @Override
    //            public Long getLong(AttributeMetadata attributeMetadata) {
    //                if (attributeMetadata.getAttributeName().toLowerCase().contains("id")) {
    //                    return 0l;
    //                }
    //                return super.getLong(attributeMetadata); //To change body of generated methods, choose Tools | Templates.
    //            }
    //
    //            @Override
    //            public Object getMemoizedObject(AttributeMetadata attributeMetadata) {
    //                if (attributeMetadata != null && attributeMetadata.getAttributeName() != null) {
    //                    switch (attributeMetadata.getAttributeName()) {
    //                        case "validFrom":
    //                            return new Date(0);
    //                        case "startDate":
    //                            return new Date(0);
    //                        case "validUntil":
    //                            return new Date(System.currentTimeMillis());
    //                        case "endDate":
    //                            return new Date(System.currentTimeMillis());
    //                        case "uploadDate":
    //                            return new Date(System.currentTimeMillis());
    //                    }
    //                }
    //                return super.getMemoizedObject(attributeMetadata);
    //            }
    //
    //        };
    //        stra.setDefaultNumberOfCollectionElements(1);       
    //        PodamFactory factory = new PodamFactoryImpl(stra);
    //
    //        DigitalObject a2 = factory.manufacturePojo(DigitalObject.class);
    //
    //        IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
    //        mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
    //        a2 = mdm.save(a2);
    //
    //        System.out.println(a2);
    if (true) {
        return;
    }

    /*String content = org.apache.commons.io.FileUtils.readFileToString(new File("/Users/jejkal/Software/GenericRestClient-1.2/bin/data/default_view.json"));
    JSONObject viewObject = new JSONObject(content);
    IFileTree tree1 = Util.jsonViewToFileTree(viewObject, true, false);
    DataOrganizationUtils.printTree(tree1.getRootNode(), true);*/
    /*AdalapiProtocolConfiguration config = AdalapiProtocolConfiguration.factoryConfiguration(new URL("http://localhost:8080"), "edu.kit.lsdf.adalapi.protocols.WebDav", "edu.kit.dama.staging.adalapi.authenticator.KITDMAuthenticator", null);
           IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
           mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
           System.out.println("RESULT " + mdm.save(config));
            
           DatabaseProtocolConfigurator config1 = new DatabaseProtocolConfigurator();
           ProtocolSettings.getSingleton().setExternalProtocolConfigurator(config1);
            
           Configuration configuration = config1.getConfiguration(new URL("http://localhost:8080"));
           Iterator keys = configuration.getKeys();
           while (keys.hasNext()) {
    String key = (String) keys.next();
    System.out.println(key + " - " + configuration.getString(key));
           }*/
    //SardineImpl impl = new SardineImpl("webdav", "webdav");
    //impl.enablePreemptiveAuthentication(new URL("http://127.0.0.1:8080/webdav/admin/1/data/index.html"));
    //impl.setCredentials("webdav", "webdav");
    //System.out.println(impl.get("http://webdav@127.0.0.1:8080/webdav/admin/1/data/index.html"));
    //System.out.println(impl.exists("http://webdav@ipesuco1.ipe.kit.edu:10000/"));
    /*Configuration config = new DatabaseProtocolConfigurator().getConfiguration(new URL("http://localhost:8080/webdav/admin/1/data/index.html"));
    config.addProperty("username", "webdav");
    config.addProperty("password", "webdav");
            
    AbstractFile file = new AbstractFile(new URL("http://localhost:8080/webdav/admin/1/data/index.html"));
    System.out.println(file.exists());
            
    /* Configuration config1 = new DatabaseProtocolConfigurator().getConfiguration(new URL("http://localhost:8080/webdav/admin/1/data/index.html"));
    config1.addProperty("username", "webdav1");
    config1.addProperty("password", "webdav1");
     */
    /* AbstractFile file2 = new AbstractFile(new URL("http://localhost:8080/webdav/admin/1/data/index.html"));
           System.out.println(file2.exists());*/
    // createDestination("1", new AuthorizationContext(new UserId("admin"), new GroupId("USERS"), Role.ADMINISTRATOR));
    //  System.out.println(file.exists());
    ///////////
    //          long investigationId = -1l;
    //        int first = 0;
    //        int results = 10;
    //         List<DigitalObject> objects;
    //            if (investigationId <= 0) {
    //                //no investigationId provided...get all objects
    //                mdm.addProperty(MetaDataManagerJpa.JAVAX_PERSISTENCE_FETCHGRAPH, "DigitalObject.simple");
    //                objects = mdm.findResultList("SELECT o FROM DigitalObject o", DigitalObject.class, first, results);
    //            } else {
    //                //first, obtain investigation for id
    //                mdm.addProperty(MetaDataManagerJpa.JAVAX_PERSISTENCE_FETCHGRAPH, "Investigation.simple");
    //                Investigation investigation = mdm.find(Investigation.class, investigationId);
    //                if (investigation == null) {
    //                    LOGGER.error("Investigation for id {} not found.", investigationId);
    //                    throw new WebApplicationException(Response.Status.NOT_FOUND);
    //                }
    //                //try to get objects in investigation
    //                mdm.addProperty(MetaDataManagerJpa.JAVAX_PERSISTENCE_FETCHGRAPH, "DigitalObject.simple");
    //                objects = mdm.findResultList("SELECT o FROM DigitalObject o WHERE o.investigation.investigationId=" + investigationId, DigitalObject.class, first, results);
    //            }
    ////////
    /* BaseMetaDataRestClient cl = new BaseMetaDataRestClient("http://ipesuco1.ipe.kit.edu:8080/KITDM/rest/basemetadata/", new SimpleRESTContext("admin", "dama14"));
    DigitalObjectWrapper w = cl.getAllDigitalObjects(63l, 0, 100, "eCod");
            
    System.out.println("Time2: " + (System.currentTimeMillis() - s));
     */
    //DataOrganizationRestClient doClient = new DataOrganizationRestClient("http://localhost:8080/KITDM/rest/dataorganization/", new SimpleRESTContext("admin", "dama14"));
    /* DataOrganizer org = DataOrganizerFactory.getInstance().getDataOrganizer();
    IFileTree tree1 = org.loadFileTree(new DigitalObjectId("ef16c1e5-d9b3-44b5-ba77-b9877082d02c"), "default");
            
    IFileTree sub = org.loadSubTree(new NodeId(new DigitalObjectId("ef16c1e5-d9b3-44b5-ba77-b9877082d02c"), 400l,1), 0);
            
    DataOrganizationUtils.printTree(sub.getRootNode(), true);*/

    /* FileTreeImpl newTree = new FileTreeImpl();
           newTree.setDigitalObjectId(new DigitalObjectId("ef16c1e5-d9b3-44b5-ba77-b9877082d02c"));
           newTree.setViewName("custom");
           CollectionNodeImpl images = new CollectionNodeImpl();
           images.setNodeId(400l);
            
           CollectionNodeImpl documents = new CollectionNodeImpl();
           documents.setName("documents");
           FileNodeImpl fDocumentation = new FileNodeImpl(null);
           fDocumentation.setNodeId(200l);
           documents.addChild(fDocumentation);
           newTree.getRootNode().addChild(images);
           newTree.getRootNode().addChild(documents);
            
           doClient.postView("USERS", 31l, newTree, Boolean.TRUE, new SimpleRESTContext("admin", "dama14"));
            */
    /* DataOrganizer org = DataOrganizerFactory.getInstance().getDataOrganizer();
           IFileTree tree1 = org.loadFileTree(new DigitalObjectId("ef16c1e5-d9b3-44b5-ba77-b9877082d02c"), "custom");
            
           DataOrganizationUtils.printTree(tree1.getRootNode(), true);*/
    DataOrganizer dor = DataOrganizerFactory.getInstance().getDataOrganizer();
    //dor.configure("http://localhost:7474", "neo4j", "test");
    // edu.kit.dama.mdm.dataorganization.impl.jpa.DataOrganizerImpl dor = new edu.kit.dama.mdm.dataorganization.impl.jpa.DataOrganizerImpl();

    // IFileTree tree = DataOrganizationUtils.createTreeFromFile("Large4", new AbstractFile(new File("/Users/jejkal/NetBeansProjects/KITDM/trunk")), true);
    //edu.kit.dama.mdm.dataorganization.impl.jpa.DataOrganizerImpl dor = new edu.kit.dama.mdm.dataorganization.impl.jpa.DataOrganizerImpl();       
    // System.out.println("Create tree");
    //  dor.createFileTree(tree);
    System.out.println("DONE");
    s = System.currentTimeMillis();

    System.out.println(dor.getViews(new DigitalObjectId("Large4")));
    //dor.createFileTree(tree);
    System.out.println("R " + (System.currentTimeMillis() - s));

    if (true) {
        return;
    }

    //  IMetaDataManager mdm1 = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
    // mdm1.addProperty(MetaDataManagerJpa.JAVAX_PERSISTENCE_FETCHGRAPH, "DigitalObject.simple");
    //   AuthorizationContext ctx1 = new AuthorizationContext(new UserId("admin"), new GroupId("eCod"), Role.ADMINISTRATOR);
    //   mdm1.setAuthorizationContext(ctx1);*/
    /* StringBuilder query = new StringBuilder();
    IMetaDataManager mdm1 = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
    mdm1.setAuthorizationContext(ctx1);
    String domain = SecurableEntityHelper.getSecurableResourceDomain(DigitalObject.class);
    String uniqueField = SecurableEntityHelper.getDomainUniqueFieldName(DigitalObject.class);
            
    query.append("SELECT o FROM FilterHelper f, ").
        append("DigitalObject").append(" o WHERE ");
            
    query.append("f.userId='").append(ctx1.getUserId().getStringRepresentation());
    query.append("' AND ");
            
    query.append("f.groupId='").append(ctx1.getGroupId().getStringRepresentation()).append("' AND ")
        .append("f.domainId='").append(domain).
        append("' AND f.roleAllowed>=").append(Role.GUEST.ordinal()).
        append(" AND f.domainUniqueId=o.").append(uniqueField);
            
    long s1 = System.currentTimeMillis();
            
    List<DigitalObject> result2 = mdm1.findResultList(query.toString(), DigitalObject.class, 0, 100);
    System.out.println("D: " + (System.currentTimeMillis() - s1));*/
    /*for(int i=0;i<100;i++){
       if(result1.get(i).getDigitalObjectId().equals(result2.get(i).getDigitalObjectId())){
           System.out.println("ERROR ");
           System.out.println(result1.get(i));
           System.out.println("=====================");
           System.out.println(result2.get(i));
           System.out.println("===================");
           System.out.println(i);
       }
    }*/
    if (true) {
        return;
    }
    //        IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
    //        AuthorizationContext ctx = new AuthorizationContext(new UserId("admin"), new GroupId("eCod"), Role.ADMINISTRATOR);
    //        mdm.setAuthorizationContext(ctx);
    //        long s = System.currentTimeMillis();
    //        //System.out.println(new DigitalObjectSecureQueryHelper().getReadableResources(mdm, 0, 100, ctx).size());
    //        System.out.println("Time: " + (System.currentTimeMillis() - s));
    //        s = System.currentTimeMillis();
    //        mdm.addProperty(MetaDataManagerJpa.JAVAX_PERSISTENCE_FETCHGRAPH, "DigitalObject.default");
    //        System.out.println(mdm.findResultList("SELECT o FROM DigitalObject o", DigitalObject.class, 0, 100).size());
    //        System.out.println("Time2: " + (System.currentTimeMillis() - s));
    //        if (true) {
    //            return;
    //        }

    //        IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
    //        //mdm.setAuthorizationContext(new AuthorizationContext(new UserId("admin"), new GroupId("eCod"), Role.MANAGER));
    //        mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
    //        mdm.addProperty(MetaDataManagerJpa.JAVAX_PERSISTENCE_FETCHGRAPH, "DigitalObject.default");
    //        long s = System.currentTimeMillis();
    //        DigitalObject result = mdm.find(DigitalObject.class, 1000l);
    //        System.out.println(result.getBaseId());
    //        System.out.println(result.getLabel());
    //        System.out.println(result.getInvestigation().getInvestigationId());
    //        System.out.println(result.getInvestigation().getTopic());
    //        /* System.out.println(result.getStudyId());
    //         System.out.println(result.getTopic());*/
    //        System.out.println("TIME: " + (System.currentTimeMillis() - s));
    //        // System.out.println(result.getInvestigations().size());

    /* System.out.println(result.getBaseId());
     System.out.println(result.getLabel());
     System.out.println(result.getNote());
     System.out.println("--------");
     mdm.addProperty(MetaDataManagerJpa.JAVAX_PERSISTENCE_FETCHGRAPH, "DigitalObject.default");
     result = mdm.save(result);
     System.out.println(result.getBaseId());
     System.out.println(result.getLabel());
     System.out.println(result.getNote());
     System.out.println("--------");
     result = mdm.find(DigitalObject.class).get(0);
     System.out.println(result.getBaseId());
     System.out.println(result.getLabel());
     System.out.println(result.getNote());*/

    /* System.out.println("TOPIC " + result.get(0).getTopic());
            System.out.println("NOT " + result.get(0).getNote());
            System.out.println("INV " + result.get(0).getInvestigations());
            System.out.println("DO " + ((Investigation) result.get(0).getInvestigations().toArray()[0]).getDataSets());*/
    if (true) {
        return;
    }

    //        long t = System.currentTimeMillis();
    //
    //        AbstractRandomDataProviderStrategy stra = new AbstractRandomDataProviderStrategy() {
    //        };
    //        stra.setDefaultNumberOfCollectionElements(1);
    //        PodamFactory factory = new PodamFactoryImpl(stra);
    //        DigitalObject a = factory.manufacturePojo(DigitalObject.class);
    //        DigitalObject a2 = factory.manufacturePojoWithFullData(DigitalObject.class);
    //
    //        //for (int i = 0; i < 10; i++) {
    //        //  long s = System.currentTimeMillis();
    //        Marshaller marshaller = org.eclipse.persistence.jaxb.JAXBContext.newInstance(DigitalObject.class).createMarshaller();
    //        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    //        marshaller.setProperty("eclipselink.media-type", "application/json");
    //        marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, "default");
    //        marshaller.marshal(a, System.out);
    //        marshaller.marshal(a2, System.out);
    //        //  t += System.currentTimeMillis() - s;
    //        // }
    //        System.out.println("D " + (System.currentTimeMillis() - t));
    //        if (true) {
    //            return;
    //        }
    Document docDigitalObject = null;
    String completeXml = null;

    String baseXML = DigitalObject2Xml.getXmlString(DigitalObject.factoryNewDigitalObject());

    try {
        ByteArrayInputStream bin = new ByteArrayInputStream(baseXML.getBytes());
        docDigitalObject = JaxenUtil.getW3CDocument(bin);//XMLTools.parseDOM(baseXML);
    } catch (Exception exc) {
        throw new MetaDataExtractionException("Failed to transform DigitalObject XML.", exc);
    }

    Element digitalObjectElement = docDigitalObject.getDocumentElement();

    Document completeDocument = null;
    try {
        completeDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException ex) {
        throw new MetaDataExtractionException("Failed to generate target document.", ex);
    }
    Element rootElement = completeDocument.createElement("test");

    Element root = completeDocument.createElementNS(BaseMetaDataHelper.DAMA_NAMESPACE_BASEMETADATA,
            BaseMetaDataHelper.DAMA_NAMESPACE_PREFIX);
    root.appendChild(completeDocument.importNode(digitalObjectElement, true));
    Node csmdRoot = root.appendChild(completeDocument.createElementNS(
            BaseMetaDataHelper.DAMA_NAMESPACE_METADATA, BaseMetaDataHelper.CSMD_NAMESPACE_PREFIX));
    csmdRoot.appendChild(completeDocument.importNode(rootElement, true));

    completeDocument.appendChild(root);
    root.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation",
            BaseMetaDataHelper.DAMA_NAMESPACE_METADATA + " " + BaseMetaDataHelper.DAMA_NAMESPACE_BASEMETADATA
                    + "/MetaData.xsd");
    // convert tweaked DOM back to XML string
    try {
        completeXml = getStringFromDocument(completeDocument);//XMLTools.getXML(completeDocument);
    } catch (Exception exc) {
        throw new MetaDataExtractionException("Internal XML conversion error.", exc);
    }
    System.out.println(completeXml);

    //    IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
    //    IAuthorizationContext context = new AuthorizationContext(new UserId("admin"), new GroupId(Constants.USERS_GROUP_ID), Role.ADMINISTRATOR);//AuthorizationContext.factorySystemContext();
    //    mdm.setAuthorizationContext(context);
    //    try {
    //      //TransferClientProperties props = new TransferClientProperties();
    //      //props.setStagingAccessPointId("0000-0000-0000-0000");
    //      //IngestInformationServiceLocal.getSingleton().prepareIngest(new DigitalObjectId("c98408fc-36d0-4cc0-8197-340873d6698e"), props, context);
    //
    //      //System.out.println(StagingService.getSingleton().finalizeIngest(new DigitalObjectId("c98408fc-36d0-4cc0-8197-340873d6698e"), context));
    //      System.out.println(MetadataIndexingHelper.getSingleton().performIndexing("KITDataManager", "dc", new GroupId("USERS"), 10, context));
    //    } finally {
    //      mdm.close();
    //    }
}

From source file:ebay.Ebay.java

/**
 * @param args the command line arguments
 *//*from   ww  w  .j  a v a2 s.c o m*/
public static void main(String[] args) {
    HttpClient client = null;
    HttpResponse response = null;
    BufferedReader rd = null;
    Document doc = null;
    String xml = "";
    EbayDAO<Producto> db = new EbayDAO<>(Producto.class);
    String busqueda;

    while (true) {
        busqueda = JOptionPane.showInputDialog(null, "ingresa una busqueda");
        if (busqueda != null) {
            busqueda = busqueda.replaceAll(" ", "%20");
            try {
                client = new DefaultHttpClient();
                /*
                 peticion GET
                 */
                HttpGet request = new HttpGet("http://open.api.ebay.com/shopping?" + "callname=FindPopularItems"
                        + "&appid=student11-6428-4bd4-ac0d-6ed9d84e345" + "&version=517&QueryKeywords="
                        + busqueda + "&siteid=0" + "&responseencoding=XML");
                /*
                 se ejecuta la peticion GET
                 */
                response = client.execute(request);
                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                /*
                 comienza la lectura de la respuesta a la peticion GET
                 */
                String line;
                while ((line = rd.readLine()) != null) {
                    xml += line + "\n";
                }
            } catch (IOException ex) {
                Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex);
            }

            /*
             creamos nuestro documentBulder(documento constructor) y obtenemos 
             nuestro objeto documento apartir de documentBuilder
             */
            try {
                DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                doc = documentBuilder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));
            } catch (ParserConfigurationException | SAXException | IOException ex) {
                Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex);
            }

            Element raiz = doc.getDocumentElement();
            if (raiz == null) {
                System.exit(0);
            }
            if (raiz.getElementsByTagName("Ack").item(0).getTextContent().equals("Success")) {
                NodeList array = raiz.getElementsByTagName("ItemArray").item(0).getChildNodes();
                for (int i = 0; i < array.getLength(); ++i) {
                    Node n = array.item(i);

                    if (n.getNodeType() != Node.TEXT_NODE) {
                        Producto p = new Producto();
                        if (((Element) n).getElementsByTagName("ItemID").item(0) != null)
                            p.setId(new Long(
                                    ((Element) n).getElementsByTagName("ItemID").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("EndTime").item(0) != null)
                            p.setEndtime(
                                    ((Element) n).getElementsByTagName("EndTime").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch").item(0) != null)
                            p.setViewurl(((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch")
                                    .item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ListingType").item(0) != null)
                            p.setListingtype(
                                    ((Element) n).getElementsByTagName("ListingType").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("GalleryURL").item(0) != null)
                            p.setGalleryurl(
                                    ((Element) n).getElementsByTagName("GalleryURL").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("PrimaryCategoryID").item(0) != null)
                            p.setPrimarycategoryid(new Integer(((Element) n)
                                    .getElementsByTagName("PrimaryCategoryID").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("PrimaryCategoryName").item(0) != null)
                            p.setPrimarycategoryname(((Element) n).getElementsByTagName("PrimaryCategoryName")
                                    .item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("BidCount").item(0) != null)
                            p.setBidcount(new Integer(
                                    ((Element) n).getElementsByTagName("BidCount").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ConvertedCurrentPrice").item(0) != null)
                            p.setConvertedcurrentprice(new Double(((Element) n)
                                    .getElementsByTagName("ConvertedCurrentPrice").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ListingStatus").item(0) != null)
                            p.setListingstatus(((Element) n).getElementsByTagName("ListingStatus").item(0)
                                    .getTextContent());
                        if (((Element) n).getElementsByTagName("TimeLeft").item(0) != null)
                            p.setTimeleft(
                                    ((Element) n).getElementsByTagName("TimeLeft").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("Title").item(0) != null)
                            p.setTitle(((Element) n).getElementsByTagName("Title").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ShippingServiceCost").item(0) != null)
                            p.setShippingservicecost(new Double(((Element) n)
                                    .getElementsByTagName("ShippingServiceCost").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ShippingType").item(0) != null)
                            p.setShippingtype(((Element) n).getElementsByTagName("ShippingType").item(0)
                                    .getTextContent());
                        if (((Element) n).getElementsByTagName("WatchCount").item(0) != null)
                            p.setWatchcount(new Integer(
                                    ((Element) n).getElementsByTagName("WatchCount").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ListedShippingServiceCost").item(0) != null)
                            p.setListedshippingservicecost(
                                    new Double(((Element) n).getElementsByTagName("ListedShippingServiceCost")
                                            .item(0).getTextContent()));
                        try {
                            db.insert(p);
                        } catch (Exception e) {
                            db.update(p);
                        }
                    }
                }
            }
            Ventana.crear(xml);
        } else
            System.exit(0);

    }
}