Example usage for org.w3c.dom NamedNodeMap getNamedItem

List of usage examples for org.w3c.dom NamedNodeMap getNamedItem

Introduction

In this page you can find the example usage for org.w3c.dom NamedNodeMap getNamedItem.

Prototype

public Node getNamedItem(String name);

Source Link

Document

Retrieves a node specified by name.

Usage

From source file:Gen.java

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

    try {/*www  .  j ava  2s. co 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:Main.java

/**
 * Gets the attribute as a string.//from   w w w.j  ava 2s . com
 * @param key the name of the attribute.
 * @param map the named node map with the attribute key/value pairs.
 * @return the attribute value or an empty string if it does not exist.
 */
public static String getAttribute(String key, NamedNodeMap map) {
    Node attr = map.getNamedItem(key);
    return attr != null ? attr.getTextContent() : "";
}

From source file:Main.java

public static String getAttr(NamedNodeMap attributes, String attrName) {
    return attributes.getNamedItem(attrName).getNodeValue();
}

From source file:Main.java

public static void removeValue(NamedNodeMap values, String name) {
    if (values.getNamedItem(name) != null) {
        values.removeNamedItem(name);//w w w.ja  v a  2 s  .com
    }
}

From source file:Main.java

/**
 * @param map//from   w  ww  .  java2 s .  c  om
 * @param string
 * @return
 */
public static String getAtributeValue(NamedNodeMap map, String string) {
    if (map.getNamedItem(string) != null)
        return map.getNamedItem(string).getNodeValue();
    else
        return null;
}

From source file:Main.java

/**
 * @param map/*ww w .  j a va2  s. co m*/
 * @param string
 * @return
 */
public static String getAtributeValue(NamedNodeMap map, String string) {
    if (map.getNamedItem(string) != null) {
        return map.getNamedItem(string).getNodeValue();
    } else {
        return null;
    }
}

From source file:Main.java

/**
 * Parses the value of the given attribute as an boolean.
 * @param attributeName the name of the attribute.
 * @param map the map that contains all the attributes.
 * @return the float value.//from   w  ww.  j  a  v  a 2  s  .  c o m
 */
public static boolean parseBoolean(String attributeName, NamedNodeMap map) {
    org.w3c.dom.Node attr = map.getNamedItem(attributeName);
    return attr != null ? Boolean.parseBoolean(attr.getTextContent()) : false;
}

From source file:Main.java

/**
 * Given a {@link NamedNodeMap} of XML attributes, returns the value for 
 * a particular attribute, or null if no attribute exists with this name.
 * @param attributes The attribute list.
 * @param name The name of the attribute.
 * @return The value of that attribute name, or null if no such attribute exists.
 *///from w  w  w. j a v a2s  .  com
public static String getAttribute(NamedNodeMap attributes, String name) {
    if (attributes.getNamedItem(name) == null) {
        return null;
    }
    return attributes.getNamedItem(name).getNodeValue();
}

From source file:Main.java

/**
 * Parses the value of the given attribute as an float.
 * @param attributeName the name of the attribute.
 * @param map the map that contains all the attributes.
 * @return the float value.//from   w  w  w. jav a2  s.  c o  m
 */
public static int parseInt(String attributeName, NamedNodeMap map) {
    org.w3c.dom.Node attr = map.getNamedItem(attributeName);
    try {
        return attr != null ? Integer.parseInt(attr.getTextContent()) : 0;
    } catch (NumberFormatException ex) {
        return 0;
    }
}

From source file:Main.java

/**
 * Parses the value of the given attribute as a float.
 * @param attributeName the name of the attribute.
 * @param map the map that contains all the attributes.
 * @return the float value./*from w  w w.  ja va2  s . c o m*/
 */
public static float parseFloat(String attributeName, NamedNodeMap map) {
    org.w3c.dom.Node attr = map.getNamedItem(attributeName);
    try {
        return attr != null ? Float.parseFloat(attr.getTextContent()) : 0f;
    } catch (NumberFormatException ex) {
        return 0.0f;
    }
}