Example usage for org.w3c.dom Document getElementsByTagName

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

Introduction

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

Prototype

public NodeList getElementsByTagName(String tagname);

Source Link

Document

Returns a NodeList of all the Elements in document order with a given tag name and are contained in the document.

Usage

From source file:moskitt4me.repositoryClient.core.util.RepositoryClientUtil.java

public static void setInitialLocationType(RepositoryLocation location) {

    FTPClient client = RepositoryClientUtil.connect(location, false);

    if (client != null) {

        String tempDir = "";

        try {//w  ww.ja va2  s .  c  o  m
            String eclipseInstallationDirectory = Platform.getInstallLocation().getURL().getPath();
            tempDir = RepositoryClientUtil.createFolder(eclipseInstallationDirectory + "tmp", 0);

            FTPFile[] files = client.listFiles();

            if (files.length > 0) {
                String fileName = files[0].getName();
                String destination = tempDir + "/" + fileName;
                FileOutputStream fos = new FileOutputStream(destination);
                client.retrieveFile(fileName, fos);
                fos.close();

                extractZipFile(tempDir, fileName);

                Document doc = getDocument(tempDir + "/rasset.xml");
                if (doc != null) {
                    Node ntype = doc.getElementsByTagName("type").item(0);
                    String type = ntype.getAttributes().getNamedItem("value").getNodeValue();
                    if (type != null) {
                        if (isTechnicalFragment(type)) {
                            location.setType("Technical");
                        } else {
                            location.setType("Conceptual");
                        }
                    }
                }
            } else {
                location.setType("Empty");
            }
        } catch (Exception e) {

        } finally {
            RepositoryClientUtil.disconnect(client);
            if (location.getType().equals("")) {
                location.setType("Empty");
            }
            if (!tempDir.equals("")) {
                RepositoryClientUtil.removeFolder(new File(tempDir));
            }
        }
    }
}

From source file:eu.eidas.configuration.ConfigurationReader.java

/**
 * Read configuration./*from w w w  .  j  av  a 2s .  co  m*/
 *
 * @return the map< string, instance engine>
 *
 * @throws SAMLEngineException the EIDASSAML engine runtime
 *             exception
 */
public static Map<String, InstanceEngine> readConfiguration() throws SAMLEngineException {

    LOGGER.debug("Init reader: " + ENGINE_CONF_FILE);
    final Map<String, InstanceEngine> instanceConfs = new HashMap<String, InstanceEngine>();

    Document document = null;
    // Load configuration file
    final DocumentBuilderFactory factory = EIDASSAMLEngine.newDocumentBuilderFactory();
    DocumentBuilder builder;

    InputStream engineConf = null;
    try {

        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        builder = factory.newDocumentBuilder();

        engineConf = ConfigurationReader.class.getResourceAsStream("/" + ENGINE_CONF_FILE);

        document = builder.parse(engineConf);

        // Read instance
        final NodeList list = document.getElementsByTagName(NODE_INSTANCE);

        for (int indexElem = 0; indexElem < list.getLength(); ++indexElem) {
            final Element element = (Element) list.item(indexElem);

            final InstanceEngine instanceConf = new InstanceEngine();

            // read every configuration.
            final String instanceName = element.getAttribute(NODE_INST_NAME);

            if (StringUtils.isBlank(instanceName)) {
                throw new EIDASSAMLEngineRuntimeException("Error reader instance name.");
            }
            instanceConf.setName(instanceName.trim());

            final NodeList confNodes = element.getElementsByTagName(NODE_CONF);

            for (int indexNode = 0; indexNode < confNodes.getLength(); ++indexNode) {

                final Element configurationNode = (Element) confNodes.item(indexNode);

                final String configurationName = configurationNode.getAttribute(NODE_CONF_NAME);

                if (StringUtils.isBlank(configurationName)) {
                    throw new EIDASSAMLEngineRuntimeException("Error reader configuration name.");
                }

                final ConfigurationEngine confSamlEngine = new ConfigurationEngine();

                // Set configuration name.
                confSamlEngine.setName(configurationName.trim());

                // Read every parameter for this configuration.
                final Map<String, String> parameters = generateParam(configurationNode);

                // Set parameters
                confSamlEngine.setParameters(parameters);

                // Add parameters to the configuration.
                instanceConf.getConfiguration().add(confSamlEngine);
            }

            // Add to the list of configurations.
            instanceConfs.put(element.getAttribute(NODE_INST_NAME), instanceConf);
        }

    } catch (SAXException e) {
        LOGGER.warn("ERROR : init library parser.", e.getMessage());
        LOGGER.debug("ERROR : init library parser.", e);
        throw new SAMLEngineException(e);
    } catch (ParserConfigurationException e) {
        LOGGER.warn("ERROR : parser configuration file xml.");
        LOGGER.debug("ERROR : parser configuration file xml.", e);
        throw new SAMLEngineException(e);
    } catch (IOException e) {
        LOGGER.warn("ERROR : read configuration file.", e.getMessage());
        LOGGER.debug("ERROR : read configuration file.", e);
        throw new SAMLEngineException(e);
    } finally {
        IOUtils.closeQuietly(engineConf);
    }

    return instanceConfs;
}

From source file:com.meltmedia.cadmium.core.util.WarUtils.java

/**
 * Adds vHost and context-root mappings to a jboss-web.xml file contained withing a zip/war file.
 * @param inZip The zip file that the original jboss-web.xml file is in.
 * @param outZip The zip output stream to write the updated jboss-web.xml file to.
 * @param jbossWeb The zip element that represents the jboss-web.xml file.
 * @param domain The domain to add a vHost for.
 * @param context The context to add a context-root for.
 * @throws Exception// w  w w.  ja  v  a2s .c  o m
 */
public static void updateDomain(ZipFile inZip, ZipOutputStream outZip, ZipEntry jbossWeb, String domain,
        String context) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(inZip.getInputStream(jbossWeb));

    Element rootNode = null;
    NodeList nodes = doc.getElementsByTagName("jboss-web");
    if (nodes.getLength() == 1) {
        rootNode = (Element) nodes.item(0);
    }

    if (domain != null && domain.length() > 0) {
        Element vHost = doc.createElement("virtual-host");
        removeNodesByTagName(rootNode, "virtual-host");
        vHost.appendChild(doc.createTextNode(domain));
        rootNode.appendChild(vHost);
    }

    if (context != null && context.length() > 0) {
        Element cRoot = doc.createElement("context-root");
        removeNodesByTagName(rootNode, "context-root");
        cRoot.appendChild(doc.createTextNode(context));
        rootNode.appendChild(cRoot);
    }

    storeXmlDocument(outZip, jbossWeb, doc);
}

From source file:edu.stanford.muse.slant.CustomSearchHelper.java

public static String readCreatorID(String authtoken) {
    String responseBody = null;// w  w w  . java2s  .  c  om
    try {
        HttpClient client = new HttpClient();
        GetMethod annotation_post = new GetMethod("http://www.google.com/cse/api/default/cse/");

        annotation_post.addRequestHeader("Content-type", "text/xml");
        annotation_post.addRequestHeader("Authorization", "GoogleLogin auth=" + authtoken);

        int astatusCode = client.executeMethod(annotation_post);
        if (astatusCode == HttpStatus.SC_OK) {
            responseBody = IOUtils.toString(annotation_post.getResponseBodyAsStream(), "UTF-8");
            log.info("Result request for creator id: " + responseBody);
        } else {
            responseBody = IOUtils.toString(annotation_post.getResponseBodyAsStream(), "UTF-8");
            log.warn("Search id failed: Result request: " + responseBody);
        }
    } catch (Exception e) {
        log.warn("Exception reading xml for creator id: " + e + " " + Util.stackTrace(e));
    }

    try {
        Document doc = loadXMLFromString(responseBody);
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName("CustomSearchEngine");
        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;
                String creator = eElement.getAttribute("creator"); // eElement is not HttpSession
                if (creator != null) {
                    log.info("creator id:" + creator);
                    return creator;
                }
            }
        }
    } catch (Exception e) {
        log.warn("Invalid xml from google while reading creator id: " + e + " " + Util.stackTrace(e));
    }

    return null;
}

From source file:edu.stanford.muse.slant.CustomSearchHelper.java

public static List<CSEDetails> getExistingCSEs(String authtoken) throws HttpException, IOException {
    HttpClient client = new HttpClient();

    GetMethod get = new GetMethod("http://www.google.com/cse/api/default/cse/");
    get.addRequestHeader("Content-type", "text/xml");
    get.addRequestHeader("Authorization", "GoogleLogin auth=" + authtoken);

    int astatusCode = client.executeMethod(get);

    List<CSEDetails> cses = new ArrayList<CSEDetails>();

    if (astatusCode == HttpStatus.SC_OK) {
        //If successful, the CSE annotation is displayed in the response.
        String s = get.getResponseBodyAsString();
        try {/*from w ww  .jav a2s .  co  m*/
            Document doc = loadXMLFromString(s);
            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("CustomSearchEngine");
            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    CSEDetails cse = new CSEDetails();

                    Element eElement = (Element) nNode;
                    String creator = eElement.getAttribute("creator"); // eElement is not HttpSession
                    if (creator != null)
                        cse.creator = creator;
                    eElement = (Element) nNode;
                    String title = eElement.getAttribute("title"); // eElement is not HttpSession
                    if (creator != null)
                        cse.title = title;
                    eElement = (Element) nNode;
                    String description = eElement.getAttribute("description"); // eElement is not HttpSession
                    if (creator != null)
                        cse.description = description;
                    cses.add(cse);
                }
            }
        } catch (Exception e) {
            Util.print_exception(e);
            return cses;
        }
        log.info("Existing CSEs: " + s);
    } else
        log.warn("get existing CSEs failed");
    return cses;
}

From source file:com.idynin.ftbutils.ModPack.java

/**
 * Lightly modified from FTB net.ftb.workers.ModpackLoader
 * /*ww  w  .  j ava 2  s  . c om*/
 * @param modPackFilter
 */
public static void populateModpacks(String server, String modpackMetaPath, ModPackFilter modPackFilter) {
    InputStream modPackStream = null;
    if (modPackStream == null) {
        try {
            modPackStream = new URL("http://" + server + modpackMetaPath).openStream();
        } catch (IOException e) {
            System.err.println("Completely unable to download the modpack file - check your connection");
            e.printStackTrace();
        }
    }
    if (modPackStream != null) {
        Document doc;
        try {
            doc = getXML(modPackStream);
        } catch (Exception e) {
            System.err.println("Exception reading modpack file");
            e.printStackTrace();
            return;
        }
        if (doc == null) {
            System.err.println("Error: could not load modpack data!");
            return;
        }
        NodeList modPacks = doc.getElementsByTagName("modpack");
        ModPack mp;
        for (int i = 0; i < modPacks.getLength(); i++) {
            Node modPackNode = modPacks.item(i);
            NamedNodeMap modPackAttr = modPackNode.getAttributes();
            try {
                mp = new ModPack(modPackAttr.getNamedItem("name").getTextContent(),
                        modPackAttr.getNamedItem("author").getTextContent(),
                        modPackAttr.getNamedItem("version").getTextContent(),
                        modPackAttr.getNamedItem("logo").getTextContent(),
                        modPackAttr.getNamedItem("url").getTextContent(),
                        modPackAttr.getNamedItem("image").getTextContent(),
                        modPackAttr.getNamedItem("dir").getTextContent(),
                        modPackAttr.getNamedItem("mcVersion").getTextContent(),
                        modPackAttr.getNamedItem("serverPack").getTextContent(),
                        modPackAttr.getNamedItem("description").getTextContent(),
                        modPackAttr.getNamedItem("mods") != null
                                ? modPackAttr.getNamedItem("mods").getTextContent()
                                : "",
                        modPackAttr.getNamedItem("oldVersions") != null
                                ? modPackAttr.getNamedItem("oldVersions").getTextContent()
                                : "",
                        modPackAttr.getNamedItem("animation") != null
                                ? modPackAttr.getNamedItem("animation").getTextContent()
                                : "",
                        modPackAttr.getNamedItem("maxPermSize") != null
                                ? modPackAttr.getNamedItem("maxPermSize").getTextContent()
                                : "",
                        (ModPack.getPackArray().isEmpty() ? 0 : ModPack.getPackArray().size()), false,
                        "modpacks.xml",
                        modPackAttr.getNamedItem("bundledMap") != null
                                ? modPackAttr.getNamedItem("bundledMap").getTextContent()
                                : "",
                        modPackAttr.getNamedItem("customTP") != null ? true : false);
                if (modPackFilter == null || modPackFilter.accept(mp)) {
                    ModPack.addPack(mp);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        IOUtils.closeQuietly(modPackStream);
    }
}

From source file:com.amalto.webapp.core.util.Util.java

public static String getDefaultLanguage() throws Exception {
    String defaultLanguage = ""; //$NON-NLS-1$
    String userName = LocalUser.getLocalUser().getUsername();
    WSItemPK itemPK = new WSItemPK(new WSDataClusterPK(DATACLUSTER_PK), PROVISIONING_CONCEPT,
            new String[] { userName });
    if (userName != null && userName.length() > 0) {
        Document doc = XMLUtils.parse(Util.getPort().getItem(new WSGetItem(itemPK)).getContent());
        if (doc.getElementsByTagName("language") != null) { //$NON-NLS-1$
            Node language = doc.getElementsByTagName("language").item(0); //$NON-NLS-1$
            if (language != null) {
                return language.getTextContent();
            }/*from  w w w  . j  a v a  2  s.c  o m*/
        }
    }
    return defaultLanguage;
}

From source file:eu.stork.peps.configuration.ConfigurationReader.java

/**
 * Read configuration./*w w  w  . j  a  v a 2 s.  c  om*/
 * 
 * @return the map< string, instance engine>
 * 
 * @throws SAMLEngineException the STORKSAML engine runtime
 *             exception
 */
public static Map<String, InstanceEngine> readConfiguration() throws SAMLEngineException {

    // fetch base from system properties, give a default if there is nothing configured
    String base = System.getProperty("eu.stork.samlengine.config.location");
    if (null != base)
        if (!base.endsWith("/"))
            base += "/";

    LOGGER.info("Init reader: " + base + ENGINE_CONF_FILE);
    final Map<String, InstanceEngine> instanceConfs = new HashMap<String, InstanceEngine>();

    Document document = null;
    // Load configuration file
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    InputStream engineConf = null;
    try {

        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        builder = factory.newDocumentBuilder();

        if (null != base)
            engineConf = new FileInputStream(base + ENGINE_CONF_FILE);
        else
            engineConf = ConfigurationReader.class.getResourceAsStream("/" + ENGINE_CONF_FILE);

        document = builder.parse(engineConf);

        // Read instance
        final NodeList list = document.getElementsByTagName(NODE_INSTANCE);

        for (int indexElem = 0; indexElem < list.getLength(); ++indexElem) {
            final Element element = (Element) list.item(indexElem);

            final InstanceEngine instanceConf = new InstanceEngine();

            // read every configuration.
            final String instanceName = element.getAttribute(NODE_INST_NAME);

            if (StringUtils.isBlank(instanceName)) {
                throw new STORKSAMLEngineRuntimeException("Error reader instance name.");
            }
            instanceConf.setName(instanceName.trim());

            final NodeList confNodes = element.getElementsByTagName(NODE_CONF);

            for (int indexNode = 0; indexNode < confNodes.getLength(); ++indexNode) {

                final Element configurationNode = (Element) confNodes.item(indexNode);

                final String configurationName = configurationNode.getAttribute(NODE_CONF_NAME);

                if (StringUtils.isBlank(configurationName)) {
                    throw new STORKSAMLEngineRuntimeException("Error reader configuration name.");
                }

                final ConfigurationEngine confSamlEngine = new ConfigurationEngine();

                // Set configuration name.
                confSamlEngine.setName(configurationName.trim());

                // Read every parameter for this configuration.
                final Map<String, String> parameters = generateParam(configurationNode);

                // Set parameters
                confSamlEngine.setParameters(parameters);

                // Add parameters to the configuration.
                instanceConf.getConfiguration().add(confSamlEngine);
            }

            // Add to the list of configurations.
            instanceConfs.put(element.getAttribute(NODE_INST_NAME), instanceConf);
        }

    } catch (SAXException e) {
        LOGGER.error("Error: init library parser.");
        throw new SAMLEngineException(e);
    } catch (ParserConfigurationException e) {
        LOGGER.error("Error: parser configuration file xml.");
        throw new SAMLEngineException(e);
    } catch (IOException e) {
        LOGGER.error("Error: read configuration file.");
        throw new SAMLEngineException(e);
    } finally {
        IOUtils.closeQuietly(engineConf);
    }

    return instanceConfs;
}

From source file:com.krawler.esp.handlers.basecampHandler.java

public static String importUserFromBaseCamp(javax.servlet.http.HttpServletRequest request) {
    String result = "";
    JSONObject res = new JSONObject();
    String errorString = "";
    try {//  w  w w.  j  a  v  a2s.  c om
        res.put("error", "%s");
        String docid = java.util.UUID.randomUUID().toString();
        File f1 = getfile(request, docid);

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        //                Document doc = docBuilder.parse (new File("/home/mosin/krawlercom-20081201125009.xml"));
        Document doc = docBuilder.parse(f1);
        doc.getDocumentElement().normalize();
        NodeList firmInfo = doc.getElementsByTagName("firm");
        NodeList peopel = (getElementFromNodeList(firmInfo)).getElementsByTagName("people");
        NodeList personList = (getElementFromNodeList(peopel)).getElementsByTagName("person");
        int len = personList.getLength();
        for (int i = 0; i < len; i++) {
            if (checkNodeType(personList.item(i))) {
                Element person = (Element) personList.item(i);
                JSONObject temp = new JSONObject();
                temp.put("firstName", person.getElementsByTagName("first-name").item(0).getChildNodes().item(0)
                        .getNodeValue());
                temp.put("lastName", person.getElementsByTagName("last-name").item(0).getChildNodes().item(0)
                        .getNodeValue());
                temp.put("id",
                        person.getElementsByTagName("id").item(0).getChildNodes().item(0).getNodeValue());
                try {
                    temp.put("username", person.getElementsByTagName("user-name").item(0).getChildNodes()
                            .item(0).getNodeValue());
                } catch (Exception e) {
                    temp.put("username", person.getElementsByTagName("first-name").item(0).getChildNodes()
                            .item(0).getNodeValue());
                }
                temp.put("email", person.getElementsByTagName("email-address").item(0).getChildNodes().item(0)
                        .getNodeValue());
                res.append("data", temp);
            }
        }

        NodeList projects = doc.getElementsByTagName("projects");
        NodeList projectList = (getElementFromNodeList(projects)).getElementsByTagName("project");
        len = projectList.getLength();
        for (int j = 0; j < len; j++) {
            if (checkNodeType(projectList.item(j))) {
                Element project = (Element) projectList.item(j);
                JSONObject temp = new JSONObject();
                temp.put("projectname",
                        project.getElementsByTagName("name").item(0).getChildNodes().item(0).getNodeValue());
                temp.put("projectid",
                        project.getElementsByTagName("id").item(0).getChildNodes().item(0).getNodeValue());
                temp.put("status",
                        project.getElementsByTagName("status").item(0).getChildNodes().item(0).getNodeValue());
                res.append("projdata", temp);
            }
        }
        res.put("docid", docid);
        result = res.toString();
    } catch (Exception ex) {
        errorString = MessageSourceProxy.getMessage("", null, request);
        result = res.toString();
        KrawlerLog.op.warn("Problem Occured while importing project from base camp from " + ex.toString());
    } finally {

        result = String.format(result, errorString);
        return result;
    }
}

From source file:forge.quest.io.QuestDataIO.java

@SuppressWarnings("unchecked")
private static <T> T readAsset(final XStream xs, final Document doc, final String tagName,
        final Class<T> clasz) {
    final NodeList nn = doc.getElementsByTagName(tagName);
    final Node n = nn.item(0);

    final Attr att = doc.createAttribute("resolves-to");
    att.setValue(clasz.getCanonicalName());
    n.getAttributes().setNamedItem(att);

    final String xmlData = XmlUtil.nodeToString(n);
    return (T) xs.fromXML(xmlData);
}