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:com.omertron.thetvdbapi.tools.TvdbParser.java

/**
 * Get a list of the actors from the URL
 *
 * @param urlString/*from   w w w.  ja  v a2 s. c  om*/
 * @param bannerMirror
 * @return
 */
public static List<Actor> getActors(String urlString, String bannerMirror) {
    List<Actor> results = new ArrayList<Actor>();
    Actor actor;
    Document doc;
    NodeList nlActor;
    Node nActor;
    Element eActor;

    try {
        doc = DOMHelper.getEventDocFromUrl(urlString);
        if (doc == null) {
            return results;
        }
    } catch (WebServiceException ex) {
        LOG.trace(ERROR_GET_XML, ex);
        return results;
    }

    nlActor = doc.getElementsByTagName("Actor");

    for (int loop = 0; loop < nlActor.getLength(); loop++) {
        nActor = nlActor.item(loop);

        if (nActor.getNodeType() == Node.ELEMENT_NODE) {
            eActor = (Element) nActor;
            actor = new Actor();

            actor.setId(DOMHelper.getValueFromElement(eActor, "id"));
            String image = DOMHelper.getValueFromElement(eActor, "Image");
            if (!image.isEmpty()) {
                actor.setImage(bannerMirror + image);
            }
            actor.setName(DOMHelper.getValueFromElement(eActor, "Name"));
            actor.setRole(DOMHelper.getValueFromElement(eActor, "Role"));
            actor.setSortOrder(DOMHelper.getValueFromElement(eActor, "SortOrder"));

            results.add(actor);
        }
    }

    Collections.sort(results);

    return results;
}

From source file:fr.afcepf.atod.wine.data.parser.XmlParser.java

public static ArrayList<ProductWine> parseSampleXml(String fileName) throws WineException {
    ArrayList<ProductWine> wineList = new ArrayList<ProductWine>();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from w  w w.  ja  v  a2  s .  c o  m
    Document xml = null;
    try {
        xml = dbf.newDocumentBuilder()
                .parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName));
    } catch (Exception e) {
        e.printStackTrace();
    }
    NodeList subNodes = xml.getElementsByTagName("Product");
    for (int i = 0; i < subNodes.getLength(); i++) {
        Node node = subNodes.item(i);
        Element tag = (Element) node;
        ProductWine w = setWine(tag);
        if (Files.exists(Paths.get(getResourcePath() + "wine_pictures/" + w.getApiId() + "/" + w.getApiId()
                + "_front.jpg")) == true) {
            wineList.add(w);
        }
    }
    return wineList;
}

From source file:isl.FIMS.utils.Utils.java

public static void copySchemaReferences(String schemaPath, String destination) {
    Document contents = ParseXMLFile.parseFile(schemaPath);
    String prefix = contents.getDocumentElement().getTagName().split(":")[0];
    NodeList includes = contents.getElementsByTagName(prefix + ":include");
    for (int i = 0; i < includes.getLength(); i++) {
        try {//from  w  w  w.j  a v a  2 s  .  c o  m
            Node include = includes.item(i);
            String schemaLocation = include.getAttributes().getNamedItem("schemaLocation").getNodeValue();
            if (schemaLocation != "") {
                File schemaFile = new File(Utils.schemaFolder + schemaLocation);
                FileUtils.copyFile(schemaFile,
                        new File(destination + System.getProperty("file.separator") + schemaLocation));
                copySchemaReferences(schemaFile.getAbsolutePath(), destination);
            }
        } catch (IOException ex) {
        }

    }

}

From source file:com.risevision.ui.server.rpc.CompanyServiceImpl.java

public static CompanyInfo DocToCompany(Document doc) {
    try {/*from  ww  w . j ava2 s. c  o  m*/
        doc.getDocumentElement().normalize();

        NodeList nodeList = doc.getElementsByTagName(Entity.COMPANY);

        Node fstNode = nodeList.item(0);

        CompanyInfo company = new CompanyInfo();

        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

            Element fstElmnt = (Element) fstNode;

            company.setId(ServerUtils.getNode(fstElmnt, CompanyAttribute.ID));
            company.setName(ServerUtils.getNode(fstElmnt, CompanyAttribute.NAME));

            company.setStreet(ServerUtils.getNode(fstElmnt, CompanyAttribute.STREET));
            company.setUnit(ServerUtils.getNode(fstElmnt, CompanyAttribute.UNIT));
            company.setCity(ServerUtils.getNode(fstElmnt, CompanyAttribute.CITY));
            company.setProvince(ServerUtils.getNode(fstElmnt, CompanyAttribute.PROVINCE));
            company.setCountry(ServerUtils.getNode(fstElmnt, CompanyAttribute.COUNTRY));
            company.setPostalCode(ServerUtils.getNode(fstElmnt, CompanyAttribute.POSTAL));
            company.setTimeZone(
                    ServerUtils.getNode(fstElmnt, CompanyAttribute.TIMEZONE, company.getTimeZone()));

            // Added the address field for the getCompanyByAuthKey API
            company.setAddress(ServerUtils.getNode(fstElmnt, CompanyAttribute.ADDRESS));

            company.setTelephone(ServerUtils.getNode(fstElmnt, CompanyAttribute.TELEPHONE));
            company.setFax(ServerUtils.getNode(fstElmnt, CompanyAttribute.FAX));

            company.setParentId(ServerUtils.getNode(fstElmnt, CompanyAttribute.PARENT));

            company.setPnoStatus(
                    RiseUtils.strToInt(ServerUtils.getNode(fstElmnt, CompanyAttribute.NETWORK_OPERATOR_STATUS),
                            CompanyNetworkOperatorStatus.NO));
            company.setCustomerStatus(RiseUtils.strToInt(
                    ServerUtils.getNode(fstElmnt, CompanyAttribute.COMPANY_STATUS), CompanyStatus.ACTIVE));
            company.setCustomerStatusChangeDate(ServerUtils.strToDate(
                    ServerUtils.getNode(fstElmnt, CompanyAttribute.COMPANY_STATUS_CHANGE_DATE), null));

            company.setDisplayMonitorEmailRecipients(ServerUtils
                    .getNodeListElements(fstElmnt.getElementsByTagName(CompanyAttribute.NOTIFICATION_EMAIL)));

            String settingsString = ServerUtils.getNode(fstElmnt, CompanyAttribute.SETTINGS);
            company.setSettings(parsePnoSettings(settingsString));

            String parentSettingsString = ServerUtils.getNode(fstElmnt, "parentSettings");
            company.setParentSettings(parsePnoSettings(parentSettingsString));

            // if non-PNO inherit parent settings; now in UiControlBinder
            //            if (company.getSettings() == null) {
            //               company.setSettings(company.getParentSettings());
            //            }

            company.setAuthKey(ServerUtils.getNode(fstElmnt, CompanyAttribute.AUTH_KEY));
            company.setClaimId(ServerUtils.getNode(fstElmnt, CompanyAttribute.CLAIM_ID));

            company.setCreationDate(
                    ServerUtils.strToDate(ServerUtils.getNode(fstElmnt, CompanyAttribute.CREATION_DATE)));

            company.setChangedBy(ServerUtils.getNode(fstElmnt, CommonAttribute.CHANGED_BY));
            company.setChangeDate(
                    ServerUtils.strToDate(ServerUtils.getNode(fstElmnt, CommonAttribute.CHANGE_DATE), null));

            AlertsInfo alertsSettings = new AlertsInfo();

            alertsSettings.setAllowAlerts(
                    ServerUtils.StrToBoolean(ServerUtils.getNode(fstElmnt, CompanyAttribute.ALLOW_ALERTS)));
            alertsSettings.setAlertURL(ServerUtils.getNode(fstElmnt, CompanyAttribute.ALERT_URL));
            alertsSettings.setAlertUserName(ServerUtils.getNode(fstElmnt, CompanyAttribute.ALERT_USERNAME));
            alertsSettings.setAlertPassword(ServerUtils.getNode(fstElmnt, CompanyAttribute.ALERT_PASSWORD));

            alertsSettings.setAlertSenders(ServerUtils
                    .getNodeListElements(fstElmnt.getElementsByTagName(CompanyAttribute.ALERT_SENDER)));
            alertsSettings.setAlertStatuses(ServerUtils
                    .getNodeListElements(fstElmnt.getElementsByTagName(CompanyAttribute.ALERT_STATUS)));
            alertsSettings.setAlertHandlingCodes(ServerUtils
                    .getNodeListElements(fstElmnt.getElementsByTagName(CompanyAttribute.ALERT_HANDLING_CODE)));
            alertsSettings.setAlertCategories(ServerUtils
                    .getNodeListElements(fstElmnt.getElementsByTagName(CompanyAttribute.ALERT_CATEGORY)));
            alertsSettings.setAlertUrgencies(ServerUtils
                    .getNodeListElements(fstElmnt.getElementsByTagName(CompanyAttribute.ALERT_URGENCY)));
            alertsSettings.setAlertSeverities(ServerUtils
                    .getNodeListElements(fstElmnt.getElementsByTagName(CompanyAttribute.ALERT_SEVERITY)));
            alertsSettings.setAlertCertainties(ServerUtils
                    .getNodeListElements(fstElmnt.getElementsByTagName(CompanyAttribute.ALERT_CERTAINTY)));
            alertsSettings.setAlertEventCodes(ServerUtils
                    .getNodeListElements(fstElmnt.getElementsByTagName(CompanyAttribute.ALERT_EVENT_CODE)));
            alertsSettings.setAlertTextFields(ServerUtils
                    .getNodeListElements(fstElmnt.getElementsByTagName(CompanyAttribute.ALERT_TEXT_FIELD)));

            alertsSettings.setAlertPresentationId(
                    ServerUtils.getNode(fstElmnt, CompanyAttribute.ALERT_PRESENTATION_ID));
            alertsSettings.setAlertDistribution(ServerUtils
                    .getNodeListElements(fstElmnt.getElementsByTagName(CompanyAttribute.DISPLAY_ID)));
            alertsSettings.setAlertExpiry(
                    RiseUtils.strToInt(ServerUtils.getNode(fstElmnt, CompanyAttribute.ALERT_EXPIRY), 60));

            company.setAlertsSettings(alertsSettings);

            DemographicsInfo demographicsInfo = new DemographicsInfo();

            demographicsInfo.setCompanyType(ServerUtils.getNode(fstElmnt, CompanyAttribute.COMPANY_TYPE));
            demographicsInfo.setServicesProvided(ServerUtils
                    .getNodeListElements(fstElmnt.getElementsByTagName(CompanyAttribute.SERVICE_PROVIDED)));
            demographicsInfo.setMarketSegments(ServerUtils
                    .getNodeListElements(fstElmnt.getElementsByTagName(CompanyAttribute.MARKET_SEGMENT)));
            demographicsInfo.setTargetGroups(ServerUtils
                    .getNodeListElements(fstElmnt.getElementsByTagName(CompanyAttribute.TARGET_GROUP)));
            //            demographicsInfo.setViewsPerDisplay(ServerUtils.getNode(fstElmnt, CompanyAttribute.VIEWS_PER_DISPLAY));
            demographicsInfo.setAdvertisingRevenueEarn(ServerUtils
                    .StrToBoolean(ServerUtils.getNode(fstElmnt, CompanyAttribute.ADVERTISING_REVENUE_EARN)));
            demographicsInfo.setAdvertisingRevenueInterested(ServerUtils.StrToBoolean(
                    ServerUtils.getNode(fstElmnt, CompanyAttribute.ADVERTISING_REVENUE_INTERESTED)));

            company.setDemographicsInfo(demographicsInfo);

        }
        return company;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.microfocus.application.automation.tools.srf.run.RunFromSrfBuilder.java

public static JSONObject getSrfConnectionData(AbstractBuild<?, ?> build, PrintStream logger) {
    try {/* w w  w. j a va2  s .  c  o m*/
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        String path = build.getProject().getParent().getRootDir().toString();
        path = path.concat(
                "/com.microfocus.application.automation.tools.srf.settings.SrfServerSettingsBuilder.xml");
        File file = new File(path);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(file);
        // This also shows how you can consult the global configuration of the builder
        JSONObject connectionData = new JSONObject();

        String credentialsId = document.getElementsByTagName("credentialsId").item(0).getTextContent();
        UsernamePasswordCredentials credentials = CredentialsProvider.findCredentialById(credentialsId,
                StandardUsernamePasswordCredentials.class, build, URIRequirementBuilder.create().build());

        String app = credentials.getUsername();
        String tenant = app.substring(1, app.indexOf('_'));
        String secret = credentials.getPassword().getPlainText();
        String server = document.getElementsByTagName("srfServerName").item(0).getTextContent();

        // Normalize SRF server URL string if needed
        if (server.substring(server.length() - 1).equals("/")) {
            server = server.substring(0, server.length() - 1);
        }

        boolean https = true;
        if (!server.startsWith("https://")) {
            if (!server.startsWith("http://")) {
                String tmp = server;
                server = "https://";
                server = server.concat(tmp);
            } else
                https = false;
        }
        URL urlTmp = new URL(server);
        if (urlTmp.getPort() == -1) {
            if (https)
                server = server.concat(":443");
            else
                server = server.concat(":80");
        }
        String srfProxy = "";
        String srfTunnel = "";
        try {
            srfProxy = document.getElementsByTagName("srfProxyName").item(0) != null
                    ? document.getElementsByTagName("srfProxyName").item(0).getTextContent().trim()
                    : null;
            srfTunnel = document.getElementsByTagName("srfTunnelPath").item(0) != null
                    ? document.getElementsByTagName("srfTunnelPath").item(0).getTextContent()
                    : null;
        } catch (Exception e) {
            throw e;
        }
        connectionData.put("app", app);
        connectionData.put("tunnel", srfTunnel);
        connectionData.put("secret", secret);
        connectionData.put("server", server);
        connectionData.put("https", (https) ? "True" : "False");
        connectionData.put("proxy", srfProxy);
        connectionData.put("tenant", tenant);
        return connectionData;
    } catch (ParserConfigurationException e) {
        logger.print(e.getMessage());
        logger.print("\n\r");
    } catch (SAXException | IOException e) {
        logger.print(e.getMessage());
    }
    return null;
}

From source file:org.jboss.as.test.integration.logging.formatters.XmlFormatterTestCase.java

private static void validateDefault(final Document doc, final Collection<String> expectedKeys,
        final String expectedMessage) {
    final Set<String> remainingKeys = new HashSet<>(expectedKeys);

    String loggerClassName = null;
    String loggerName = null;// www . j ava2s  . co  m
    String level = null;
    String message = null;

    // Check all the expected keys
    final Iterator<String> iterator = remainingKeys.iterator();
    while (iterator.hasNext()) {
        final String key = iterator.next();
        final NodeList children = doc.getElementsByTagName(key);
        Assert.assertTrue(String.format("Key %s was not found in the document: %s", key, doc),
                children.getLength() > 0);
        final Node child = children.item(0);
        if ("loggerClassName".equals(child.getNodeName())) {
            loggerClassName = child.getTextContent();
        } else if ("loggerName".equals(child.getNodeName())) {
            loggerName = child.getTextContent();
        } else if ("level".equals(child.getNodeName())) {
            level = child.getTextContent();
        } else if ("message".equals(child.getNodeName())) {
            message = child.getTextContent();
        }
        iterator.remove();
    }

    // Should have no more remaining keys
    Assert.assertTrue("There are remaining keys that were not validated: " + remainingKeys,
            remainingKeys.isEmpty());

    Assert.assertEquals("org.jboss.logging.Logger", loggerClassName);
    Assert.assertEquals(LoggingServiceActivator.LOGGER.getName(), loggerName);
    Assert.assertTrue("Invalid level found in " + level, isValidLevel(level));
    Assert.assertEquals(expectedMessage, message);
}

From source file:com.fujitsu.dc.test.utils.DavResourceUtils.java

/**
 * PROPFIND???OData?????????. <br />
 * dc:odata?????? OData ??????.//  ww  w .  jav  a  2 s  .  c  om
 * @param res PROPFIND?
 */
public static void assertIsODataCol(TResponse res) {
    Document propfind = res.bodyAsXml();
    NodeList list;
    list = propfind.getElementsByTagName("dc:odata");
    assertThat(list.getLength()).isGreaterThanOrEqualTo(1);
}

From source file:com.fujitsu.dc.test.utils.DavResourceUtils.java

/**
 * PROPFIND???Service?????????. <br />
 * dc:path?????? Service ??????.// ww  w  . j a v  a 2 s  . co  m
 * @param res PROPFIND?
 */
public static void assertIsServiceCol(TResponse res) {
    Document propfind = res.bodyAsXml();
    NodeList list;
    list = propfind.getElementsByTagName("dc:path");
    assertThat(list.getLength()).isGreaterThanOrEqualTo(1);
}

From source file:com.fujitsu.dc.test.utils.DavResourceUtils.java

/**
 * XML??????????????./*  ww w .  j a  v  a 2s  .com*/
 * @param res PROPFIND?
 * @param tagName ?????
 */
public static void assertContainsNodeInResXml(TResponse res, String tagName) {
    Document propfind = res.bodyAsXml();
    NodeList list;
    list = propfind.getElementsByTagName(tagName);
    assertThat(list.getLength()).isGreaterThan(0);
}

From source file:com.fujitsu.dc.test.utils.DavResourceUtils.java

/**
 * XML????????????????.//from w w  w. j a va 2s.  c o  m
 * @param res PROPFIND?
 * @param tagName ?????
 */
public static void assertNotContainsNodeInResXml(TResponse res, String tagName) {
    Document propfind = res.bodyAsXml();
    NodeList list;
    list = propfind.getElementsByTagName(tagName);
    assertThat(list.getLength()).isEqualTo(0);
}