Example usage for org.w3c.dom Element getElementsByTagName

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

Introduction

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

Prototype

public NodeList getElementsByTagName(String name);

Source Link

Document

Returns a NodeList of all descendant Elements with a given tag name, in document order.

Usage

From source file:org.openremote.android.console.net.ORControllerServerSwitcher.java

/**
 * Detect the groupmembers of current server url
 *//*from  www  .  j a  v  a 2  s .co m*/
public static boolean detectGroupMembers(Context context) {
    Log.i(LOG_CATEGORY, "Detecting group members with current controller server url "
            + AppSettingsModel.getCurrentServer(context));

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
    HttpConnectionParams.setSoTimeout(params, 5 * 1000);
    HttpClient httpClient = new DefaultHttpClient(params);
    String url = AppSettingsModel.getSecuredServer(context);
    HttpGet httpGet = new HttpGet(url + "/rest/servers");

    if (httpGet == null) {
        Log.e(LOG_CATEGORY, "Create HttpRequest fail.");

        return false;
    }

    SecurityUtil.addCredentialToHttpRequest(context, httpGet);

    // TODO : fix the exception handling in this method -- it is ridiculous.

    try {
        URL uri = new URL(url);

        if ("https".equals(uri.getProtocol())) {
            Scheme sch = new Scheme(uri.getProtocol(), new SelfCertificateSSLSocketFactory(context),
                    uri.getPort());
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
        }

        HttpResponse httpResponse = httpClient.execute(httpGet);

        try {
            if (httpResponse.getStatusLine().getStatusCode() == Constants.HTTP_SUCCESS) {
                InputStream data = httpResponse.getEntity().getContent();

                try {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document dom = builder.parse(data);
                    Element root = dom.getDocumentElement();

                    NodeList nodeList = root.getElementsByTagName("server");
                    int nodeNums = nodeList.getLength();
                    List<String> groupMembers = new ArrayList<String>();

                    for (int i = 0; i < nodeNums; i++) {
                        groupMembers.add(nodeList.item(i).getAttributes().getNamedItem("url").getNodeValue());
                    }

                    Log.i(LOG_CATEGORY, "Detected groupmembers. Groupmembers are " + groupMembers);

                    return saveGroupMembersToFile(context, groupMembers);
                } catch (IOException e) {
                    Log.e(LOG_CATEGORY, "The data is from ORConnection is bad", e);
                } catch (ParserConfigurationException e) {
                    Log.e(LOG_CATEGORY, "Cant build new Document builder", e);
                } catch (SAXException e) {
                    Log.e(LOG_CATEGORY, "Parse data error", e);
                }
            }

            else {
                Log.e(LOG_CATEGORY, "detectGroupMembers Parse data error");
            }
        }

        catch (IllegalStateException e) {
            Log.e(LOG_CATEGORY, "detectGroupMembers Parse data error", e);
        }

        catch (IOException e) {
            Log.e(LOG_CATEGORY, "detectGroupMembers Parse data error", e);
        }

    }

    catch (MalformedURLException e) {
        Log.e(LOG_CATEGORY, "Create URL fail:" + url);
    }

    catch (ConnectException e) {
        Log.e(LOG_CATEGORY, "Connection refused: " + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (ClientProtocolException e) {
        Log.e(LOG_CATEGORY, "Can't Detect groupmembers with current controller server "
                + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (SocketTimeoutException e) {
        Log.e(LOG_CATEGORY, "Can't Detect groupmembers with current controller server "
                + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (IOException e) {
        Log.e(LOG_CATEGORY, "Can't Detect groupmembers with current controller server "
                + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (IllegalArgumentException e) {
        Log.e(LOG_CATEGORY, "Host name can be null :" + AppSettingsModel.getCurrentServer(context), e);
    }

    return false;
}

From source file:eu.serco.dhus.xml.parser.TaskTableParser.java

public static TaskTable parseTaskTable(String filename)
        throws ParserConfigurationException, SAXException, IOException {

    TaskTable taskTable = new TaskTable();

    if (filename == null || filename.isEmpty())
        throw new RuntimeException("The name of the XML file is required!");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    // Load the input XML document, parse it and return an instance of the
    // Document class.
    Document document = builder.parse(new File(filename));
    document.getDocumentElement().normalize();
    NodeList list = document.getElementsByTagName("Processor_Name");
    logger.info(" NodeList list size----: " + list.getLength());
    if (list != null && list.item(0) != null && list.item(0).getFirstChild() != null) {
        taskTable.setProcessorName(list.item(0).getFirstChild().getNodeValue());
    }//from  w  w w. j  av a2  s.com

    NodeList nodeList = document.getElementsByTagName("Task");
    Node node;
    Element elem;
    List<Task> tasks = new ArrayList<Task>();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Task task = new Task();
        node = nodeList.item(i);

        if (node.getNodeType() == Node.ELEMENT_NODE) {
            elem = (Element) node;

            task.setName(elem.getElementsByTagName("Name").item(0).getChildNodes().item(0).getNodeValue());
            logger.info("taskname:  " + task.getName());

            List<Input> task_inputs = new ArrayList<Input>();
            NodeList inputs = elem.getElementsByTagName("Input");

            for (int j = 0; j < inputs.getLength(); j++) {

                Input input = new Input();
                node = inputs.item(j);

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    elem = (Element) node;

                    input.setMode(
                            elem.getElementsByTagName("Mode").item(0).getChildNodes().item(0).getNodeValue());
                    logger.info("==== mode:  " + input.getMode());
                    input.setMandatory(elem.getElementsByTagName("Mandatory").item(0).getChildNodes().item(0)
                            .getNodeValue());
                    logger.info("==== mandatory:  " + input.getMandatory());

                    List<Alternative> input_alternatives = new ArrayList<Alternative>();
                    NodeList alternatives = elem.getElementsByTagName("Alternative");

                    for (int k = 0; k < alternatives.getLength(); k++) {

                        Alternative alternative = new Alternative();
                        node = alternatives.item(k);

                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                            elem = (Element) node;

                            alternative.setOrder(Integer.parseInt(elem.getElementsByTagName("Order").item(0)
                                    .getChildNodes().item(0).getNodeValue()));
                            logger.info("==== order:  " + alternative.getOrder());
                            alternative.setRetrievalMode(elem.getElementsByTagName("Retrieval_Mode").item(0)
                                    .getChildNodes().item(0).getNodeValue());
                            logger.info("==== retrievalMode:  " + alternative.getRetrievalMode());
                            alternative.setT0(Double.parseDouble(elem.getElementsByTagName("T0").item(0)
                                    .getChildNodes().item(0).getNodeValue()));
                            logger.info("==== t0:  " + alternative.getT0());
                            alternative.setT1(Double.parseDouble(elem.getElementsByTagName("T1").item(0)
                                    .getChildNodes().item(0).getNodeValue()));
                            logger.info("==== t1:  " + alternative.getT1());
                            alternative.setFileType(elem.getElementsByTagName("File_Type").item(0)
                                    .getChildNodes().item(0).getNodeValue());
                            logger.info("==== fileType:  " + alternative.getFileType());
                            alternative.setFileNameType(elem.getElementsByTagName("File_Name_Type").item(0)
                                    .getChildNodes().item(0).getNodeValue());
                            logger.info("==== fileNameType:  " + alternative.getFileNameType());
                        }
                        input_alternatives.add(alternative);
                    }
                    input.setAlternatives(input_alternatives);
                }
                task_inputs.add(input);
            }
            task.setInputs(task_inputs);
        }
        tasks.add(task);
    }
    taskTable.setTasks(tasks);
    return taskTable;
}

From source file:edu.stanford.muse.webapp.Sessions.java

public static boolean parseArchivesXml(String xmlFile) {
    if (!(new File(xmlFile)).exists())
        return false;

    if (archivesMap != null) // can't reload (any other) archives.xml
        return true;

    boolean result = true;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    org.w3c.dom.Document dom;/*  w w  w  . jav  a  2s.c o  m*/

    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        dom = db.parse(xmlFile);
        Element e_root = dom.getDocumentElement();

        // get a nodelist of <item> elements
        NodeList nl = e_root.getElementsByTagName("item");
        assert (nl != null);

        archivesMap = new LinkedHashMap<String, Map<String, String>>();

        for (int i = 0; i < nl.getLength(); i++) {
            // get an <item> elemment
            Element e = (Element) nl.item(i);
            Map<String, String> map = new LinkedHashMap<String, String>();

            // extract following tags
            addXmlTagToMap(map, e, "name");
            addXmlTagToMap(map, e, "number");
            addXmlTagToMap(map, e, "description");
            addXmlTagToMap(map, e, "file");
            addXmlOptionalTagToMap(map, e, "lexicon");
            addXmlOptionalTagToMap(map, e, "findingaids");
            addXmlOptionalTagToMap(map, e, "searchworks");

            log.info("Added archive " + map);
            archivesMap.put(map.get("number"), map);
        }
    } catch (Exception e) {
        e.printStackTrace();
        result = false;
    }

    return result;
}

From source file:com.msopentech.odatajclient.engine.data.Deserializer.java

private static ServiceDocumentResource toServiceDocumentFromXML(final InputStream input) {
    final Element service = toDOM(input);

    final XMLServiceDocument serviceDoc = new XMLServiceDocument();
    serviceDoc.setBaseURI(URI.create(service.getAttribute(ODataConstants.ATTR_XMLBASE)));

    final NodeList collections = service.getElementsByTagName(ODataConstants.ELEM_COLLECTION);
    for (int i = 0; i < collections.getLength(); i++) {
        final Element collection = (Element) collections.item(i);

        final NodeList title = collection.getElementsByTagName(ODataConstants.ATOM_ATTR_TITLE);
        if (title.getLength() != 1) {
            throw new IllegalArgumentException("Invalid collection element found");
        }/*www.j  a  va  2s  . c om*/

        serviceDoc.addToplevelEntitySet(title.item(0).getTextContent(),
                collection.getAttribute(ODataConstants.ATTR_HREF));
    }

    return serviceDoc;
}

From source file:com.osafe.services.MelissaDataHelper.java

private static AddressVerificationResponse buildVerificationResponse(Document doc) {
    AddressVerificationResponse avResponse = new AddressVerificationResponse();
    NodeList nodeList = doc.getElementsByTagName("Results").item(0).getChildNodes();
    Node nValue = (Node) nodeList.item(0);
    if (nValue.getNodeValue().equals(" ")) {
        List<AddressDocument> responseAddresseList = FastList.newInstance();
        NodeList recordList = doc.getElementsByTagName("Record");
        for (int temp = 0; temp < recordList.getLength(); temp++) {
            AddressDocument responseAddresse = new AddressDocument();
            Node nNode = recordList.item(temp);
            Element eElement = (Element) nNode;
            //check result success, changed or error
            nodeList = eElement.getElementsByTagName("Results").item(0).getChildNodes();
            String results = nodeList.item(0).getNodeValue();
            setResponseCode(avResponse, results);
            if (UtilValidate.isEmpty(avResponse.getResponseCode())) {
                avResponse.setResponseCode(AddressVerificationResponse.AS);
            }//from www. j a va 2  s. co m
            //get address1
            nodeList = eElement.getElementsByTagName("Address1").item(0).getChildNodes();
            responseAddresse.setAddress1(nodeList.item(0).getNodeValue());
            //get address2
            nodeList = eElement.getElementsByTagName("Address2").item(0).getChildNodes();
            responseAddresse.setAddress2(nodeList.item(0).getNodeValue());
            //get City
            nodeList = eElement.getElementsByTagName("City").item(0).getChildNodes();
            responseAddresse.setCity(nodeList.item(0).getChildNodes().item(0).getNodeValue());
            //get State
            nodeList = eElement.getElementsByTagName("State").item(0).getChildNodes();
            responseAddresse.setStateProvinceGeoId(nodeList.item(1).getChildNodes().item(0).getNodeValue());
            //get Country
            nodeList = eElement.getElementsByTagName("Country").item(0).getChildNodes();
            responseAddresse.setCountryGeoId(nodeList.item(0).getChildNodes().item(0).getNodeValue());
            //get Zip
            nodeList = eElement.getElementsByTagName("Zip").item(0).getChildNodes();
            responseAddresse.setPostalCode(nodeList.item(0).getNodeValue());
            //get Plus4
            nodeList = eElement.getElementsByTagName("Plus4").item(0).getChildNodes();
            responseAddresse.setPostalCodeExt(nodeList.item(0).getNodeValue());
            responseAddresseList.add(responseAddresse);
        }
        avResponse.setAlternateAddresses(responseAddresseList);
    } else {
        avResponse.setResponseCode(AddressVerificationResponse.GE);
    }
    return avResponse;
}

From source file:eu.europeana.uim.sugarcrmclient.internal.helpers.ClientUtils.java

/**
 * Returns a Map containing SUgarCRM identifiers
 * /*from w  w w . j  ava 2s . c om*/
 * @param el
 * @return the populated map
 */
public static Map<String, String> mapFromElement(Element el) {
    HashMap<String, String> retMap = new HashMap<String, String>();
    NodeList nl = el.getElementsByTagName("item");
    for (int i = 0; i < nl.getLength(); i++) {
        Node nd = nl.item(i);
        String id = nd.getChildNodes().item(0).getTextContent();
        String content = nd.getChildNodes().item(1).getTextContent();
        retMap.put(id, content);
    }
    return retMap;
}

From source file:org.apache.lens.regression.util.Util.java

public static void changeConfig(HashMap<String, String> map, String remotePath) throws Exception {

    Path p = Paths.get(remotePath);
    String fileName = p.getFileName().toString();
    backupFile = localFilePath + "backup-" + fileName;
    localFile = localFilePath + fileName;
    log.info("Copying " + remotePath + " to " + localFile);
    remoteFile("get", remotePath, localFile);
    Files.copy(new File(localFile).toPath(), new File(backupFile).toPath(), REPLACE_EXISTING);

    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = docBuilder.parse(new FileInputStream(localFile));
    doc.normalize();/*from www . j  a v a2  s. c  om*/

    NodeList rootNodes = doc.getElementsByTagName("configuration");
    Node root = rootNodes.item(0);
    Element rootElement = (Element) root;
    NodeList property = rootElement.getElementsByTagName("property");

    for (int i = 0; i < property.getLength(); i++) { //Deleting redundant properties from the document
        Node prop = property.item(i);
        Element propElement = (Element) prop;
        Node propChild = propElement.getElementsByTagName("name").item(0);

        Element nameElement = (Element) propChild;
        if (map.containsKey(nameElement.getTextContent())) {
            rootElement.removeChild(prop);
            i--;
        }
    }

    Iterator<Entry<String, String>> ab = map.entrySet().iterator();
    while (ab.hasNext()) {
        Entry<String, String> entry = ab.next();
        String propertyName = entry.getKey();
        String propertyValue = entry.getValue();
        System.out.println(propertyName + " " + propertyValue + "\n");
        Node newNode = doc.createElement("property");
        rootElement.appendChild(newNode);
        Node newName = doc.createElement("name");
        Element newNodeElement = (Element) newNode;

        newName.setTextContent(propertyName);
        newNodeElement.appendChild(newName);

        Node newValue = doc.createElement("value");
        newValue.setTextContent(propertyValue);
        newNodeElement.appendChild(newValue);
    }
    prettyPrint(doc);
    remoteFile("put", remotePath, localFile);
}

From source file:com.linkedin.drelephant.util.Utils.java

/**
 * Given a configuration element, extract the params map.
 *
 * @param confElem the configuration element
 * @return the params map or an empty map if one can't be found
 *///w ww . ja v a2  s. co  m
public static Map<String, String> getConfigurationParameters(Element confElem) {
    Map<String, String> paramsMap = new HashMap<String, String>();
    Node paramsNode = confElem.getElementsByTagName("params").item(0);
    if (paramsNode != null) {
        NodeList paramsList = paramsNode.getChildNodes();
        for (int j = 0; j < paramsList.getLength(); j++) {
            Node paramNode = paramsList.item(j);
            if (paramNode != null && !paramsMap.containsKey(paramNode.getNodeName())) {
                paramsMap.put(paramNode.getNodeName(), paramNode.getTextContent());
            }
        }
    }
    return paramsMap;
}

From source file:com.github.fcannizzaro.resourcer.Resourcer.java

/**
 * Parse values xml files//from  ww  w . j  a  va 2 s .c  o  m
 */
private static void findValues() {

    values = new HashMap<>();

    File dir = new File(PATH_BASE + VALUES_DIR);

    if (!dir.isDirectory())
        return;

    File[] files = dir.listFiles();

    if (files == null)
        return;

    for (File file : files)

        // only *.xml files
        if (file.getName().matches(".*\\.xml$")) {

            Document doc = FileUtils.readXML(file.getAbsolutePath());

            if (doc == null)
                return;

            Element ele = doc.getDocumentElement();

            for (String element : elements) {

                NodeList list = ele.getElementsByTagName(element);

                if (values.get(element) == null)
                    values.put(element, new HashMap<>());

                for (int j = 0; j < list.getLength(); j++) {

                    Element node = (Element) list.item(j);
                    String value = node.getFirstChild().getNodeValue();
                    Object valueDefined = value;

                    switch (element) {
                    case INTEGER:
                        valueDefined = Integer.valueOf(value);
                        break;
                    case DOUBLE:
                        valueDefined = Double.valueOf(value);
                        break;
                    case FLOAT:
                        valueDefined = Float.valueOf(value);
                        break;
                    case BOOLEAN:
                        valueDefined = Boolean.valueOf(value);
                        break;
                    case LONG:
                        valueDefined = Long.valueOf(value);
                        break;
                    case COLOR:

                        if (value.matches("@color/.*")) {

                            try {
                                Class<?> c = Class.forName("com.github.fcannizzaro.material.Colors");
                                Object colors = c.getDeclaredField(value.replace("@color/", "")).get(c);
                                Method asColor = c.getMethod("asColor");
                                valueDefined = asColor.invoke(colors);

                            } catch (Exception e) {
                                System.out.println("ERROR Resourcer - Cannot bind " + value);
                            }

                        } else
                            valueDefined = Color.decode(value);
                        break;
                    }

                    values.get(node.getNodeName()).put(node.getAttribute("name"), valueDefined);

                }

            }
        }
}

From source file:com.zimbra.cs.service.AutoDiscoverServlet.java

private static String getTagValue(String tag, Element element) {
    NodeList nlList = element.getElementsByTagName(tag).item(0).getChildNodes();
    Node nValue = nlList.item(0);

    return nValue.getNodeValue();
}