Example usage for org.w3c.dom Element getAttribute

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

Introduction

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

Prototype

public String getAttribute(String name);

Source Link

Document

Retrieves an attribute value by name.

Usage

From source file:mondrian.test.DiffRepository.java

/**
 * Returns the <TestCase> element corresponding to the current
 * test case.//w w  w . ja  v a 2 s.co  m
 *
 * @param root Root element of the document
 * @param testCaseName Name of test case
 * @return TestCase element, or null if not found
 */
private static Element getTestCaseElement(final Element root, final String testCaseName) {
    final NodeList childNodes = root.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node child = childNodes.item(i);
        if (child.getNodeName().equals(TestCaseTag)) {
            Element testCase = (Element) child;
            if (testCaseName.equals(testCase.getAttribute(TestCaseNameAttr))) {
                return testCase;
            }
        }
    }
    return null;
}

From source file:com.netsteadfast.greenstep.base.action.BaseSupportAction.java

private static Map<String, String> loadStrutsConstants(InputStream is) throws Exception {
    if (loadStrutsSettingConstatns != null) {
        return loadStrutsSettingConstatns;
    }/* www. j a  va 2 s .  co  m*/
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setFeature("http://xml.org/sax/features/validation", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
    dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    dbf.setValidating(false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("constant");
    loadStrutsSettingConstatns = new HashMap<String, String>();
    for (int i = 0; nodes != null && i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        Element nodeElement = (Element) node;
        loadStrutsSettingConstatns.put(nodeElement.getAttribute("name"), nodeElement.getAttribute("value"));
    }
    return loadStrutsSettingConstatns;
}

From source file:com.impetus.kundera.loader.PersistenceXMLLoader.java

/**
 * Parses the persistence unit./*w  w  w .jav a2s .  c  o  m*/
 * 
 * @param top
 *            the top
 * @return the persistence metadata
 * @throws Exception
 *             the exception
 */
private static PersistenceUnitMetadata parsePersistenceUnit(final URL url, final String[] persistenceUnits,
        Element top, final String versionName) {
    PersistenceUnitMetadata metadata = new PersistenceUnitMetadata(versionName, getPersistenceRootUrl(url),
            url);

    String puName = top.getAttribute("name");

    if (!Arrays.asList(persistenceUnits).contains(puName)) {
        // Returning null because this persistence unit is not intended for
        // creating entity manager factory.
        return null;
    }

    if (!isEmpty(puName)) {
        log.trace("Persistent Unit name from persistence.xml: " + puName);
        metadata.setPersistenceUnitName(puName);
        String transactionType = top.getAttribute("transaction-type");
        if (StringUtils.isEmpty(transactionType)
                || PersistenceUnitTransactionType.RESOURCE_LOCAL.name().equals(transactionType)) {
            metadata.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);
        } else if (PersistenceUnitTransactionType.JTA.name().equals(transactionType)) {
            metadata.setTransactionType(PersistenceUnitTransactionType.JTA);
        }
    }

    NodeList children = top.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) children.item(i);
            String tag = element.getTagName();

            if (tag.equals("provider")) {
                metadata.setProvider(getElementContent(element));
            } else if (tag.equals("properties")) {
                NodeList props = element.getChildNodes();
                for (int j = 0; j < props.getLength(); j++) {
                    if (props.item(j).getNodeType() == Node.ELEMENT_NODE) {
                        Element propElement = (Element) props.item(j);
                        // if element is not "property" then skip
                        if (!"property".equals(propElement.getTagName())) {
                            continue;
                        }

                        String propName = propElement.getAttribute("name").trim();
                        String propValue = propElement.getAttribute("value").trim();
                        if (isEmpty(propValue)) {
                            propValue = getElementContent(propElement, "");
                        }
                        metadata.getProperties().put(propName, propValue);
                    }
                }
            } else if (tag.equals("class")) {
                metadata.getClasses().add(getElementContent(element));
            } else if (tag.equals("jar-file")) {
                metadata.addJarFile(getElementContent(element));
            } else if (tag.equals("exclude-unlisted-classes")) {
                String excludeUnlisted = getElementContent(element);
                metadata.setExcludeUnlistedClasses(Boolean.parseBoolean(excludeUnlisted));
            }
        }
    }
    PersistenceUnitTransactionType transactionType = getTransactionType(top.getAttribute("transaction-type"));
    if (transactionType != null) {
        metadata.setTransactionType(transactionType);
    }

    return metadata;
}

From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java

/**
 * @param zipComponents /* ww  w .j  a va2s. c  o m*/
 * @param logDoc
 * @param documentDom
 * @param commentsDom
 * @param commentTemplate
 * @throws XPathExpressionException
 */
static void addMessagesToDocxXml(Document logDoc, Document documentDom, Document commentsDom,
        Element commentTemplate) throws XPathExpressionException {
    NodeList messagesNl = logDoc.getDocumentElement().getElementsByTagName("message");

    for (int i = 0; i < messagesNl.getLength(); i++) {
        Element message = (Element) messagesNl.item(i);

        NodeList existingComments = commentsDom.getDocumentElement().getElementsByTagNameNS(wNs, "comment");
        String commentId = String.valueOf(existingComments.getLength());
        String messageText = message.getTextContent();

        addCommentToComments(commentsDom, commentTemplate, messageText, commentId);

        String xpath = message.getAttribute("wordParaXPath");
        // System.err.println("xpath=" + xpath);
        if (xpath == null || "".equals(xpath.trim())) {
            xpath = "/w:document/w:body[1]/w:p[1]";
        }

        addCommentRefToParaForXPath(documentDom, commentId, xpath);

    }
}

From source file:com.concursive.connect.web.modules.communications.utils.EmailUpdatesUtils.java

public static String getEmailHTMLMessage(Connection db, ApplicationPrefs prefs, Configuration configuration,
        EmailUpdatesQueue queue, Timestamp min, Timestamp max) throws Exception {
    // User who needs to be sent an email
    User user = UserUtils.loadUser(queue.getEnteredBy());

    Project website = ProjectUtils.loadProject("main-profile");
    int emailUpdatesSchedule = -1;
    String title = "";
    if (queue.getScheduleOften()) {
        emailUpdatesSchedule = TeamMember.EMAIL_OFTEN;
        title = website.getTitle() + " recent updates";
    } else if (queue.getScheduleDaily()) {
        emailUpdatesSchedule = TeamMember.EMAIL_DAILY;
        title = website.getTitle() + " daily update";
    } else if (queue.getScheduleWeekly()) {
        emailUpdatesSchedule = TeamMember.EMAIL_WEEKLY;
        title = website.getTitle() + " weekly update";
    } else if (queue.getScheduleMonthly()) {
        emailUpdatesSchedule = TeamMember.EMAIL_MONTHLY;
        title = website.getTitle() + " monthly update";
    }//from w w w .  j a v a 2  s  .  c o m
    if (emailUpdatesSchedule == -1) {
        //unexpected case; throw exception
        throw new Exception("The queue does not have a valid schedule type!");
    }
    if (URLFactory.createURL(prefs.getPrefs()) == null) {
        throw new Exception(
                "The server URL is not specified. Please contact the system administrator to configure the remote server's URL!");
    }

    // Populate the message template
    freemarker.template.Template template = configuration
            .getTemplate("scheduled_activity_updates_email_body-html.ftl");
    Map bodyMappings = new HashMap();
    bodyMappings.put("title", title);
    bodyMappings.put("link", new HashMap());
    ((Map) bodyMappings.get("link")).put("settings",
            URLFactory.createURL(prefs.getPrefs()) + "/show/" + user.getProfileUniqueId());

    // Load the RSS config file to determine the objects for display
    String fileName = "scheduled_emails_en_US.xml";
    URL resource = EmailUpdatesUtils.class.getResource("/" + fileName);
    LOG.debug("Schedule emails config file: " + resource.toString());
    XMLUtils library = new XMLUtils(resource);

    String purpose = prefs.get(ApplicationPrefs.PURPOSE);
    LOG.debug("Purpose: " + purpose);
    Element emailElement = XMLUtils.getElement(library.getDocumentElement(), "email", "events",
            "site," + purpose);
    if (emailElement == null) {
        emailElement = XMLUtils.getElement(library.getDocumentElement(), "email", "events", "site");
    }
    if (emailElement != null) {
        LinkedHashMap categories = new LinkedHashMap();

        PagedListInfo info = new PagedListInfo();
        String limit = emailElement.getAttribute("limit");
        info.setItemsPerPage(limit);
        int activityCount = 0;

        //Determine the website's site-chatter data to email for this user (if any)
        ProjectHistoryList chatter = new ProjectHistoryList();
        chatter.setProjectId(website.getId());
        chatter.setLinkObject(ProjectHistoryList.SITE_CHATTER_OBJECT);
        chatter.setRangeStart(min);
        chatter.setRangeEnd(max);
        chatter.setPagedListInfo(info);
        chatter.setForMemberEmailUpdates(user.getId(), emailUpdatesSchedule);
        LinkedHashMap map = chatter.getList(db, user.getId(), URLFactory.createURL(prefs.getPrefs()));
        activityCount += map.size();
        if (map.size() != 0) {
            categories.put("Chatter", map);
        }

        // Determine the types of events to display based on the config file
        ArrayList<Element> eventElements = new ArrayList<Element>();
        XMLUtils.getAllChildren(emailElement, "event", eventElements);

        // set all the requested types based on the types we allow for the query..
        ArrayList<String> types = new ArrayList<String>();
        for (Element eventElement : eventElements) {
            String type = XMLUtils.getNodeText(eventElement);
            types.add(type);
        }
        LOG.debug("Event Types: " + types);
        // Load the categories
        ProjectCategoryList categoryList = new ProjectCategoryList();
        categoryList.setTopLevelOnly(true);
        categoryList.setEnabled(Constants.TRUE);
        categoryList.buildList(db);

        for (ProjectCategory category : categoryList) {
            ProjectHistoryList activities = new ProjectHistoryList();
            activities.setProjectCategoryId(category.getId());
            activities.setRangeStart(min);
            activities.setRangeEnd(max);
            activities.setObjectPreferences(types);
            activities.setPagedListInfo(info);
            activities.setForMemberEmailUpdates(user.getId(), emailUpdatesSchedule);
            LinkedHashMap activityMap = activities.getList(db, user.getId(),
                    URLFactory.createURL(prefs.getPrefs()));
            activityCount += activityMap.size();
            if (activityMap.size() != 0) {
                categories.put(category.getLabel(), activityMap);
            }
        }

        if (activityCount == 0) {
            //Don't send an email update
            return null;
        }
        bodyMappings.put("categories", categories);
    }

    // Parse and return
    StringWriter emailBodyTextWriter = new StringWriter();
    template.process(bodyMappings, emailBodyTextWriter);

    return emailBodyTextWriter.toString();
}

From source file:org.yamj.core.service.metadata.nfo.InfoReader.java

/**
 * Parse Sets from the XML NFO file/*from   w  ww .j a  v  a 2  s.c om*/
 *
 * @param nlElements
 * @param dto
 */
private static void parseSets(NodeList nlElements, InfoDTO dto) {
    Node nElements;
    for (int looper = 0; looper < nlElements.getLength(); looper++) {
        nElements = nlElements.item(looper);
        if (nElements.getNodeType() == Node.ELEMENT_NODE) {
            Element eId = (Element) nElements;

            String setOrder = eId.getAttribute("order");
            if (StringUtils.isNumeric(setOrder)) {
                dto.addSetInfo(eId.getTextContent(), Integer.parseInt(setOrder));
            } else {
                dto.addSetInfo(eId.getTextContent());
            }
        }
    }
}

From source file:org.springsource.ide.eclipse.commons.core.SpringCoreUtils.java

public static IFile getDeploymentDescriptor(IProject project) {
    if (SpringCoreUtils.hasProjectFacet(project, "jst.web")) {
        IFile settingsFile = project.getFile(".settings/org.eclipse.wst.common.component");
        if (settingsFile.exists()) {
            try {
                NodeList nodes = (NodeList) EXPRESSION.evaluate(parseDocument(settingsFile),
                        XPathConstants.NODESET);
                for (int i = 0; i < nodes.getLength(); i++) {
                    Element element = (Element) nodes.item(i);
                    if ("/".equals(element.getAttribute(DEPLOY_PATH))) {
                        String path = element.getAttribute(SOURCE_PATH);
                        if (path != null) {
                            IFile deploymentDescriptor = project
                                    .getFile(new Path(path).append("WEB-INF").append("web.xml"));
                            if (deploymentDescriptor.exists()) {
                                return deploymentDescriptor;
                            }/*from  w w w .  j a v  a 2 s. c om*/
                        }
                    }
                }
            } catch (Exception e) {
                StatusHandler.log(new Status(IStatus.WARNING, CorePlugin.PLUGIN_ID, 1, e.getMessage(), e));
            }
        }
    }
    return null;
}

From source file:Main.java

public static String getXPath(Node node) {
    if (null == node)
        return null;

    // declarations
    Node parent = null;/*w ww.j  a v a2  s  .co m*/
    Stack<Node> hierarchy = new Stack<Node>();
    StringBuilder buffer = new StringBuilder();

    // push element on stack
    hierarchy.push(node);

    parent = node.getParentNode();
    while (null != parent && parent.getNodeType() != Node.DOCUMENT_NODE) {
        // push on stack
        hierarchy.push(parent);

        // get parent of parent
        parent = parent.getParentNode();
    }

    // construct xpath
    Object obj = null;
    while (!hierarchy.isEmpty() && null != (obj = hierarchy.pop())) {
        Node n = (Node) obj;
        boolean handled = false;

        // only consider elements
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            Element e = (Element) n;

            // is this the root element?
            if (buffer.length() == 0) {
                // root element - simply append element name
                buffer.append(n.getNodeName());
            } else {
                // child element - append slash and element name
                buffer.append("/");
                buffer.append(n.getNodeName());

                if (n.hasAttributes()) {
                    // see if the element has a name or id attribute
                    if (e.hasAttribute("id")) {
                        // id attribute found - use that
                        buffer.append("[@id='" + e.getAttribute("id") + "']");
                        handled = true;
                    } else if (e.hasAttribute("name")) {
                        // name attribute found - use that
                        buffer.append("[@name='" + e.getAttribute("name") + "']");
                        handled = true;
                    }
                }

                if (!handled) {
                    // no known attribute we could use - get sibling index
                    int prev_siblings = 1;
                    Node prev_sibling = n.getPreviousSibling();
                    while (null != prev_sibling) {
                        if (prev_sibling.getNodeType() == n.getNodeType()) {
                            if (prev_sibling.getNodeName().equalsIgnoreCase(n.getNodeName())) {
                                prev_siblings++;
                            }
                        }
                        prev_sibling = prev_sibling.getPreviousSibling();
                    }
                    buffer.append("[" + prev_siblings + "]");
                }
            }
        }
    }

    // return buffer
    return buffer.toString();
}

From source file:com.iflytek.spider.protocol.httpclient.Http.java

/**
 * Reads authentication configuration file (defined as 'http.auth.file' in
 * Nutch configuration file) and sets the credentials for the configured
 * authentication scopes in the HTTP client object.
 * /*from  w  ww . java2 s. co m*/
 * @throws ParserConfigurationException
 *             If a document builder can not be created.
 * @throws SAXException
 *             If any parsing error occurs.
 * @throws IOException
 *             If any I/O error occurs.
 */
private static synchronized void setCredentials()
        throws ParserConfigurationException, SAXException, IOException {
    if (authFile == null || authFile.equals(""))
        authRulesRead = true;
    if (authRulesRead)
        return;

    authRulesRead = true; // Avoid re-attempting to read

    InputStream is = conf.getConfResourceAsInputStream(authFile);
    if (is != null) {
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);

        Element rootElement = doc.getDocumentElement();
        if (!"auth-configuration".equals(rootElement.getTagName())) {
            if (LOG.isWarnEnabled())
                LOG.warn("Bad auth conf file: root element <" + rootElement.getTagName() + "> found in "
                        + authFile + " - must be <auth-configuration>");
        }

        // For each set of credentials
        NodeList credList = rootElement.getChildNodes();
        for (int i = 0; i < credList.getLength(); i++) {
            Node credNode = credList.item(i);
            if (!(credNode instanceof Element))
                continue;

            Element credElement = (Element) credNode;
            if (!"credentials".equals(credElement.getTagName())) {
                if (LOG.isWarnEnabled())
                    LOG.warn("Bad auth conf file: Element <" + credElement.getTagName() + "> not recognized in "
                            + authFile + " - expected <credentials>");
                continue;
            }

            String username = credElement.getAttribute("username");
            String password = credElement.getAttribute("password");

            // For each authentication scope
            NodeList scopeList = credElement.getChildNodes();
            for (int j = 0; j < scopeList.getLength(); j++) {
                Node scopeNode = scopeList.item(j);
                if (!(scopeNode instanceof Element))
                    continue;

                Element scopeElement = (Element) scopeNode;

                if ("default".equals(scopeElement.getTagName())) {

                    // Determine realm and scheme, if any
                    String realm = scopeElement.getAttribute("realm");
                    String scheme = scopeElement.getAttribute("scheme");

                    // Set default credentials
                    defaultUsername = username;
                    defaultPassword = password;
                    defaultRealm = realm;
                    defaultScheme = scheme;

                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Credentials - username: " + username + "; set as default" + " for realm: "
                                + realm + "; scheme: " + scheme);
                    }

                } else if ("authscope".equals(scopeElement.getTagName())) {

                    // Determine authentication scope details
                    String host = scopeElement.getAttribute("host");
                    int port = -1; // For setting port to AuthScope.ANY_PORT
                    try {
                        port = Integer.parseInt(scopeElement.getAttribute("port"));
                    } catch (Exception ex) {
                        // do nothing, port is already set to any port
                    }
                    String realm = scopeElement.getAttribute("realm");
                    String scheme = scopeElement.getAttribute("scheme");

                    // Set credentials for the determined scope
                    AuthScope authScope = getAuthScope(host, port, realm, scheme);
                    NTCredentials credentials = new NTCredentials(username, password, agentHost, realm);

                    client.getState().setCredentials(authScope, credentials);

                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Credentials - username: " + username + "; set for AuthScope - " + "host: "
                                + host + "; port: " + port + "; realm: " + realm + "; scheme: " + scheme);
                    }

                } else {
                    if (LOG.isWarnEnabled())
                        LOG.warn("Bad auth conf file: Element <" + scopeElement.getTagName()
                                + "> not recognized in " + authFile + " - expected <authscope>");
                }
            }
            is.close();
        }
    }
}

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

public static String readCreatorID(String authtoken) {
    String responseBody = null;//from   w ww  .  j av a 2  s.co m
    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;
}