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:ambit.data.qmrf.QMRFConverter.java

protected String findAttributeValue(String name_node, String name_attribute, org.w3c.dom.Document source) {

    source.getDocumentElement();/*ww w.  j  av a 2s  . co  m*/
    NodeList objCatNodes = source.getElementsByTagName(name_node);
    Node objNode = objCatNodes.item(0);
    if (objNode == null)
        return null;
    NamedNodeMap objAttributes = objNode.getAttributes();
    Node attribute = objAttributes.getNamedItem(name_attribute);
    if (attribute != null)
        return org.apache.commons.lang.StringEscapeUtils
                .unescapeXml(replaceTags(attribute.getNodeValue()).trim());
    else
        return null;
}

From source file:de.escidoc.core.test.om.container.ContainerWithdrawTest.java

@Override
public String getTheLastModificationParam(boolean includeWithdrawComment, String id) throws Exception {
    String lastModificationDate = null;
    try {/*from  w  w w  .ja  v  a  2s .  c om*/
        Document container = EscidocRestSoapTestBase.getDocument(retrieve(id));

        // get last-modification-date
        NamedNodeMap atts = container.getDocumentElement().getAttributes();
        Node lastModificationDateNode = atts.getNamedItem("last-modification-date");
        lastModificationDate = lastModificationDateNode.getNodeValue();
    } catch (final ContainerNotFoundException e) {
        // nothing to do
    }
    if (lastModificationDate == null) {
        Object result = getItemClient().retrieve(id);
        String xmlResult = null;
        if (result instanceof HttpResponse) {
            HttpResponse httpRes = (HttpResponse) result;
            assertHttpStatusOfMethod("", httpRes);
            xmlResult = EntityUtils.toString(httpRes.getEntity(), HTTP.UTF_8);

        } else if (result instanceof String) {
            xmlResult = (String) result;
        }
        Document item = EscidocRestSoapTestBase.getDocument(xmlResult);
        // get last-modification-date
        NamedNodeMap atts = item.getDocumentElement().getAttributes();
        Node lastModificationDateNode = atts.getNamedItem("last-modification-date");
        lastModificationDate = lastModificationDateNode.getNodeValue();
    }
    String param = "<param last-modification-date=\"" + lastModificationDate + "\" ";
    param += ">";
    if (includeWithdrawComment) {
        param += "<withdraw-comment>" + WITHDRAW_COMMENT + "</withdraw-comment>";
        // param += "withdraw-comment=\"" + WITHDRAW_COMMENT + "\"";
    }
    param += "</param>";

    return param;
}

From source file:com.ironiacorp.persistence.datasource.HibernateConfigurationUtil.java

/**
 * Load the current hibernate.cfg.xml./*from w  ww  .j a v  a  2 s.co m*/
 */
public void load() {
    File configFile = new File(contextPath + configFileSufix);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = null;

    log.debug("Loading configuration from file " + configFile.getAbsolutePath());
    try {
        factory.setValidating(true);
        factory.setNamespaceAware(false);
        // BUG 1: It try to validate.
        // BUG 2: 'null', following the specification, is a valid value.
        // Unfortunately,
        // the current implementation fails on it.
        // factory.setSchema( null );
        parser = factory.newDocumentBuilder();
        //         parser.setEntityResolver(new DTDEntityResolver());
        config = parser.parse(configFile);
    } catch (Exception e) {
        log.debug("Error loading the configuration: ", e);
    }
    NodeList propertiesNodes = config.getElementsByTagName("property");
    for (int i = 0; i < propertiesNodes.getLength(); i++) {
        Node propertyNode = propertiesNodes.item(i);

        // Get the property name
        NamedNodeMap attributesNodes = propertyNode.getAttributes();
        Node attributeNode = attributesNodes.getNamedItem("name");
        String property = attributeNode.getNodeValue();

        // Get the property value
        NodeList childrenNodes = propertyNode.getChildNodes();
        String value = null;
        for (int j = 0; j < childrenNodes.getLength(); j++) {
            Node childNode = childrenNodes.item(j);
            if (childNode.getNodeType() == Node.TEXT_NODE) {
                value = childNode.getNodeValue();
                break;
            }
        }

        if (property.equals("connection.driver_class") || property.equals("connection.url")
                || property.equals("connection.username") || property.equals("connection.password")
                || property.equals("dialect") || property.equals("hibernate.connection.datasource")
                || property.equals("hibernate.connection.username")
                || property.equals("hibernate.connection.password")) {
            preferences.put(property, value);
        }
    }
}

From source file:com.limegroup.gnutella.licenses.CCLicense.java

/**
 * Adds a single permission to the list.
 *//*  w w w. j a v  a  2 s  . c om*/
private void addPermission(List<String> permissions, Node node) {
    NamedNodeMap attributes = node.getAttributes();
    Node resource = attributes.getNamedItem("rdf:resource");
    if (resource != null) {
        String value = resource.getNodeValue();
        int slash = value.lastIndexOf('/');
        if (slash != -1 && slash != value.length() - 1) {
            String permission = value.substring(slash + 1);
            if (!permissions.contains(permission)) {
                permissions.add(permission);
                if (LOG.isDebugEnabled())
                    LOG.debug("Added permission: " + permission);
            } else {
                if (LOG.isWarnEnabled())
                    LOG.warn("Duplicate permission: " + permission + "!");
            }
        } else if (LOG.isWarnEnabled()) {
            LOG.trace("Unable to find permission name: " + value);
        }
    } else if (LOG.isWarnEnabled()) {
        LOG.warn("No resource item for permission.");
    }
}

From source file:org.openmrs.module.sdmxhddataexport.web.controller.dataelement.DataElementController.java

@RequestMapping(value = "/module/sdmxhddataexport/listDataElement.form", method = RequestMethod.POST)
public String deleteDataElement(@RequestParam(value = "ids", required = false) String[] ids,
        @RequestParam(value = "files", required = false) MultipartFile uploadItem, HttpServletRequest request,
        @RequestParam(value = "upload", required = false) String upload,
        @RequestParam(value = "IncludeQueries", required = false) String IncludeQueries, Object command,
        SessionStatus status) {/*w w w.j a  va 2  s. co  m*/
    String temp = "";
    HttpSession httpSession = request.getSession();
    Integer dataElementId = null;
    System.out.println(" done " + upload);
    if (upload != null) {
        System.out.println("1st part truly done");
        //FileUpload file = uploadItem;
        String fileName = "";
        if (uploadItem != null) {
            fileName = uploadItem.getOriginalFilename();
            System.out.println("2nd part truly done " + fileName);

            byte[] byteArray = null;
            try {
                byteArray = uploadItem.getBytes();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out.println("Bad file name");

                e.printStackTrace();
            }

            String data = new String(byteArray);
            System.out.println("3rd part truly done " + data);
            XPath xpath = XPathFactory.newInstance().newXPath();
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            DocumentBuilder builder = null;
            try {
                builder = domFactory.newDocumentBuilder();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();

            }
            Document doc = null;
            try {
                doc = builder.parse(uploadItem.getInputStream());
            } catch (SAXException e1) {
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "Unsupported Document type is uploaded ");

                //or we can use httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "sdmxhddataexport.UploadedFile.Wrong" );

                return "redirect:/module/sdmxhddataexport/listDataElement.form";

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "error in reading Document type  ");

                //e1.printStackTrace();

            }
            XPathExpression expr = null;
            XPathExpression exprDesc = null;
            XPathExpression exprQuery = null;
            try {
                expr = xpath.compile(
                        "//*[local-name(.)='CodeList' and @id='CL_DATAELEMENT']/*[local-name(.)='Code']");
                exprDesc = xpath.compile("//[local-name(.)='Description']");

                exprQuery = xpath.compile("//[local-name(.)='Query']");
            } catch (XPathExpressionException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Error parsing document ");

            }
            Object result = null;
            try {
                result = expr.evaluate(doc, XPathConstants.NODESET);
            } catch (XPathExpressionException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Error parsing document ");

                // e.printStackTrace();
            }
            NodeList nodes = (NodeList) result;
            ArrayList<DataElement> dataElements = new ArrayList<DataElement>();
            for (int i = 0; i < nodes.getLength(); i++) {
                boolean putItIn = false;
                DataElement de = new DataElement();
                System.out.println(nodes.item(i).getLocalName());

                NamedNodeMap nmp = nodes.item(i).getAttributes();
                System.out.println(nmp.getNamedItem("value").getNodeValue() + "  hellooo..");
                de.setCode(nmp.getNamedItem("value").getNodeValue());
                //Node tempNode = (Node)nodes.item(i); 
                NodeList innerNodeList = nodes.item(i).getChildNodes();
                System.out.println("length: " + innerNodeList.getLength());
                for (int j = 0; j < innerNodeList.getLength(); j++) {
                    if (innerNodeList.item(j).getLocalName() != null) {
                        System.out.println("hehe " + innerNodeList.item(j).getLocalName());
                        if (innerNodeList.item(j).getLocalName().equals(new String("Description"))) {
                            System.out.println("Description: " + innerNodeList.item(j).getTextContent());
                            de.setName(innerNodeList.item(j).getTextContent());

                            putItIn = true;
                        }

                        if (innerNodeList.item(j).getLocalName().equals(new String("Query"))
                                && IncludeQueries != null) {
                            System.out.println("Query: " + innerNodeList.item(j).getTextContent());
                            de.setSqlQuery(innerNodeList.item(j).getTextContent());
                        }
                    }
                }
                if (putItIn) {

                    boolean bool;
                    DataElementValidator valid = new DataElementValidator();
                    bool = valid.fileValidate(de);
                    if (bool == true)
                        dataElements.add(de);

                }
            }
            ListIterator<DataElement> li = dataElements.listIterator();
            DataElement de;
            while (li.hasNext()) {
                de = (DataElement) li.next();
                System.out.println("Element 1 = " + de.getName());
                de.setCreatedOn(new java.util.Date());
                de.setCreatedBy(Context.getAuthenticatedUser().getGivenName());
                SDMXHDDataExportService sDMXHDDataExportService = Context
                        .getService(SDMXHDDataExportService.class);

                sDMXHDDataExportService.saveDataElement(de);

            }

            status.setComplete();
        }

        return "redirect:/module/sdmxhddataexport/listDataElement.form";
    }
    try {
        SDMXHDDataExportService sDMXHDDataExportService = Context.getService(SDMXHDDataExportService.class);
        if (ids != null && ids.length > 0) {
            for (String sId : ids) {
                dataElementId = Integer.parseInt(sId);
                if (dataElementId != null && dataElementId > 0 && CollectionUtils.isEmpty(
                        sDMXHDDataExportService.listReportDataElement(null, dataElementId, null, 0, 1))) {
                    sDMXHDDataExportService
                            .deleteDataElement(sDMXHDDataExportService.getDataElementById(dataElementId));
                } else {
                    //temp += "We can't delete store="+store.getName()+" because that store is using please check <br/>";
                    temp = "This dataElement cannot be deleted as it is in use";
                }
            }
        }
    } catch (Exception e) {
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Can not delete dataElement ");
        log.error(e);
    }
    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
            StringUtils.isBlank(temp) ? "sdmxhddataexport.dataElement.deleted" : temp);

    return "redirect:/module/sdmxhddataexport/listDataElement.form";
}

From source file:com.cloudbees.sdk.Bees.java

private void initialize(boolean force) throws Exception {
    LocalRepository localRepository = new LocalRepository();

    String beesRepoPath = localRepository.getRepositoryPath();
    File lastCheckFile = new File(beesRepoPath, CHECK_FILE);
    boolean checkVersion = true;
    Properties p = new Properties();
    if (!force && Helper.loadProperties(lastCheckFile, p)) {
        String str = p.getProperty("last");
        if (str != null) {
            long interval = System.currentTimeMillis() - Long.parseLong(str);
            if (interval < CHECK_INTERVAL)
                checkVersion = false;// ww w.j a v  a2  s. c o  m
        }
    }

    if (checkVersion) {
        // Check SDK version
        File sdkConfig = getURLAsFile(localRepository, app_template_xml_url + app_template_xml_name,
                app_template_xml_name, app_template_xml_desc);
        Document doc = XmlHelper.readXMLFromFile(sdkConfig.getCanonicalPath());
        Element e = doc.getDocumentElement();
        String availVersion = e.getAttribute("version");
        String minVersion = e.getAttribute("min-version");

        VersionNumber currentVersion = new VersionNumber(BOOTSTRAP_VERSION);
        VersionNumber availableVersion = new VersionNumber(availVersion);
        VersionNumber minimumVersion = new VersionNumber(minVersion);

        if (currentVersion.compareTo(availableVersion) < 0) {
            System.out.println();
            if (currentVersion.compareTo(minimumVersion) < 0) {
                throw new AbortException("ERROR - This version of the CloudBees SDK is no longer supported,"
                        + "" + " please install the latest version (" + availVersion + ").");
            } else if (currentVersion.compareTo(availableVersion) < 0) {
                System.out.println(
                        "WARNING - A new version of the CloudBees SDK is available, please install the latest version ("
                                + availVersion + ").");
            }

            String hRef = e.getAttribute("href");

            String homeRef = "www.cloudbees.com";
            NodeList nodeList = e.getElementsByTagName("link");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                NamedNodeMap nodeMap = node.getAttributes();
                Node rel = nodeMap.getNamedItem("rel");
                Node href = nodeMap.getNamedItem("href");
                if (rel != null && rel.getTextContent().trim().equalsIgnoreCase("alternate") && href != null) {
                    homeRef = href.getTextContent();
                }
            }

            NodeList libsNL = e.getElementsByTagName("libraries");
            Node libsNode = null;
            if (libsNL.getLength() > 0) {
                libsNode = libsNL.item(0);
            }
            if (libsNode != null) {
                NodeList libNL = e.getElementsByTagName("library");
                for (int i = 0; i < libNL.getLength(); i++) {
                    Node node = libNL.item(i);
                    NamedNodeMap nodeMap = node.getAttributes();
                    Node nameNode = nodeMap.getNamedItem("name");
                    Node refNode = nodeMap.getNamedItem("href");
                    if (nameNode != null && refNode != null) {
                        String libName = nameNode.getTextContent();
                        String libUrlString = refNode.getTextContent().trim();
                        int idx = libUrlString.lastIndexOf('/');
                        String libFileName = libUrlString.substring(idx);
                        localRepository.getURLAsFile(libUrlString, "lib1" + libFileName, libName);
                    }
                }
            }

            System.out.println("  SDK home:     " + homeRef);
            System.out.println("  SDK download: " + hRef);
            System.out.println();
        }

        // Check plugins version
        NodeList pluginsNL = e.getElementsByTagName("plugins");
        Node pluginsNode = null;
        if (pluginsNL.getLength() > 0) {
            pluginsNode = pluginsNL.item(0);
        }
        if (pluginsNode != null) {
            NodeList pluginNL = e.getElementsByTagName("plugin");
            CommandServiceImpl service = (CommandServiceImpl) commandService;
            for (int i = 0; i < pluginNL.getLength(); i++) {
                Node node = pluginNL.item(i);
                NamedNodeMap nodeMap = node.getAttributes();
                Node nameNode = nodeMap.getNamedItem("artifact");
                if (nameNode != null) {
                    Node n = nodeMap.getNamedItem("required");
                    boolean forceInstall = (n != null && Boolean.parseBoolean(n.getTextContent()));

                    String pluginArtifact = nameNode.getTextContent();
                    GAV gav = new GAV(pluginArtifact);
                    VersionNumber pluginVersion = new VersionNumber(gav.version);
                    Plugin plugin = service.getPlugin(gav.artifactId);
                    if (plugin != null) {
                        forceInstall = false;
                        GAV pgav = new GAV(plugin.getArtifact());
                        VersionNumber currentPluginVersion = new VersionNumber(pgav.version);
                        if (currentPluginVersion.compareTo(pluginVersion) < 0) {
                            Node nf = nodeMap.getNamedItem("force-upgrade");
                            boolean forced = (nf != null && Boolean.parseBoolean(nf.getTextContent()));
                            if (forced) {
                                forceInstall = true;
                            } else {
                                System.out.println();
                                System.out.println("WARNING - A newer version of the [" + gav.artifactId
                                        + "] plugin is available, please update with:");
                                System.out.println(" > bees plugin:update " + gav.artifactId);
                                System.out.println();
                            }
                        }
                    }
                    if (forceInstall)
                        pluginsToInstallList.put(gav.artifactId, gav);

                }
            }
        }

        // Update last check
        p.setProperty("last", "" + System.currentTimeMillis());
        lastCheckFile.getParentFile().mkdirs();
        FileOutputStream fos = new FileOutputStream(lastCheckFile);
        p.store(fos, "CloudBees SDK check");
        fos.close();
    }
}

From source file:com.limegroup.gnutella.licenses.CCLicense.java

/**
 * Parses the 'Work' item.//from  w  w  w .  j  a  v  a 2  s  .c om
 */
protected void parseWorkItem(Node work) {
    if (LOG.isTraceEnabled())
        LOG.trace("Parsing work item.");

    // Get the URN of this Work item.   
    NamedNodeMap attributes = work.getAttributes();
    Node about = attributes.getNamedItem("rdf:about");
    URN expectedURN = null;
    if (about != null) {
        // attempt to create a SHA1 urn out of it.
        try {
            expectedURN = URN.createSHA1Urn(about.getNodeValue());
        } catch (IOException ioe) {
        }
    }

    // Get the license child element.
    NodeList children = work.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child.getNodeName().equals("license")) {
            attributes = child.getAttributes();
            Node resource = attributes.getNamedItem("rdf:resource");
            // if we found a resource, attempt to add the Work.
            if (resource != null)
                addWork(expectedURN, resource.getNodeValue());
        }
    }

    // other than it existing, nothing else needs to happen.
    return;
}

From source file:org.gvnix.dynamic.configuration.roo.addon.ConfigurationsImpl.java

/**
 * {@inheritDoc}/*  w  w w.ja v a 2  s . c o m*/
 */
public DynComponent parseComponent(Element comp, String name) {

    // If property name specified, only it be considered
    List<Element> props;
    if (name == null) {

        props = XmlUtils.findElements("*", comp);
    } else {
        props = XmlUtils.findElements(
                PROPERTY_ELEMENT_NAME + "/" + KEY_ELEMENT_NAME + "[text()='" + name + "']/..", comp);
    }

    // Iterate all child property elements from the component element
    DynPropertyList dynProps = new DynPropertyList();
    for (Element prop : props) {

        dynProps.add(parseProperty(prop));
    }

    if (dynProps.size() == 0) {
        return null;
    }

    // Add new dynamic component
    NamedNodeMap attributes = comp.getAttributes();
    return new DynComponent(attributes.getNamedItem(ID_ATTRIBUTE_NAME).getNodeValue(),
            attributes.getNamedItem(NAME_ATTRIBUTE_NAME).getNodeValue(), dynProps);
}

From source file:com.avlesh.web.filter.responseheaderfilter.ConfigProcessor.java

/**
 * <code>configFile</code> processor: Processes the file according to these rules:
 * <ol>/*from w  w w .ja va2s  .c o  m*/
 * <li>The file <b>should</b> have <code>response-header-mapper</code> as the root node.</li>
 * <li>Each node (in the xml) with the name <code>mapping</code> is identified as mapping rule and
 * gets converted into a {@link Mapping}.<br/><code>url</code> is a mandatory attribute in the <code>mapping</code> node;
 * mappings without a <code>url</code> are rejected.
 * </li>
 * <li>Subsequent mappings for the same <code>url</code> will <b>OVERRIDE</b> the previous {@link Mapping}.
 * <i>Last <code>Rule</code> wins</i>.
 * </li>
 * <li>Each mapping can have only <b>one <code>default</code></b> <code>response-header</code> list.
 * In cases of multiple such declarations, the <i>Last &lt;default&gt; declaration wins</i>.
 * </li>
 * <li>Each mapping can have any number of <code>conditional</code> mappings.
 * All these rules are treated as mutually exclusive.
 * </li>
 * <li>Both, <code>default</code> and <code>conditional</code> nodes <b>should</b> have a &lt;response-headers&gt;
 * node. In case of multiple such nodes, <i>Last &lt;response-headers&gt; declaration wins</i>.
 * </li>
 * <li>Each &lt;response-headers&gt; node may contain one or more &lt;header&gt; nodes. Each such node has to have two mandatory
 * attributes, <code>key</code> and <code>value</code>.</li>
 * <li>Both, <code>queryParamName</code> and <code>queryParamValue</code>, are required attributes in a <code>conditional</code> tag.
 * They <b>can't</b> be left blank or undeclared.
 * </li>
 * <li>Values inside the <code>queryParamValue</code> attribute are parsed as a <code>Pattern</code>.</li>
 * </ol>
 *
 * For rules on the implementation of the filter, go here -
 * {@link ResponseHeaderFilter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)}
 * @see #getCondition(org.w3c.dom.Node)
 * @see #getResponseHeader(org.w3c.dom.Node)
 */
protected void processConfig() {
    if (logger.isDebugEnabled()) {
        logger.debug("Processing the response header manager filter's config file: " + configFile.getName());
    }
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    Document doc;
    try {
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        doc = docBuilder.parse(configFile);
    } catch (Exception ex) {
        //Parse exception in the xml, not expected
        throw new RuntimeException(
                "Check " + configFile.getName() + " for errors. The file might have some unbalanced nodes");
    }

    doc.getDocumentElement().normalize();
    String rootElementName = doc.getDocumentElement().getNodeName();
    //expecting <response-header-mapper> as the root node
    if (Constants.RESPONSE_HEADER_MAPPER.equalsIgnoreCase(rootElementName)) {
        String processorClassName = doc.getDocumentElement().getAttribute("processorClass");
        MappingProcessor processorClassInstance = getProcessorClass(processorClassName);
        //the user has not configured any ProcessorClass, lets use our default one
        if (processorClassInstance == null) {
            processorClassInstance = new DefaultMappingProcessor();
        }

        NodeList allMappingNodes = doc.getDocumentElement().getElementsByTagName(Constants.MAPPING);
        if (allMappingNodes != null && allMappingNodes.getLength() > 0) {
            for (int i = 0; i < allMappingNodes.getLength(); i++) {
                MappingProcessor mappingProcessorForThisRule = null;
                String urlStr = null;
                List<Mapping.ResponseHeader> defaultResponseHeaders = new ArrayList<Mapping.ResponseHeader>();
                Map<Mapping.Condition, List<Mapping.ResponseHeader>> conditionalResponseHeaders = new LinkedHashMap<Mapping.Condition, List<Mapping.ResponseHeader>>();

                Node mappingNode = allMappingNodes.item(i);
                NamedNodeMap mappingNodeAttributes = mappingNode.getAttributes();
                if (mappingNodeAttributes != null) {
                    Node urlAttributeNode = mappingNodeAttributes.getNamedItem("url");
                    if (urlAttributeNode != null) {
                        urlStr = urlAttributeNode.getNodeValue();
                    }

                    Node processorClassNode = mappingNodeAttributes.getNamedItem("processorClass");
                    if (processorClassNode != null) {
                        mappingProcessorForThisRule = getProcessorClass(processorClassNode.getNodeValue());
                    }
                }

                //no url specified in this mappingNode, skip and continue ...
                if (StringUtils.isEmpty(urlStr)) {
                    logger.warn("Encountered a mapping without a mandatory url attribute. Skipping ...");
                    continue;
                }

                if (mappingProcessorForThisRule == null) {
                    mappingProcessorForThisRule = processorClassInstance;
                }

                Pattern url = Pattern.compile(urlStr);
                NodeList mappingChildNodes = mappingNode.getChildNodes();
                for (int j = 0; j < mappingChildNodes.getLength(); j++) {
                    Node node = mappingChildNodes.item(j);
                    String nodeName = node.getNodeName();

                    //if the node is of type <default>, just parse the list of response headers
                    if (Constants.DEFAULT.equalsIgnoreCase(nodeName)) {
                        defaultResponseHeaders = getResponseHeader(node);
                    }
                    //if the node is <conditional>, parse the <code>Condition</code> and then the corresponding
                    //list of response headers
                    else if (Constants.CONDITIONAL.equalsIgnoreCase(nodeName)) {
                        Mapping.Condition condition = getCondition(node);
                        //add the list of headers against this condition, only when both of them are "valid" (read not null)
                        if (condition != null) {
                            List<Mapping.ResponseHeader> responseHeaders = getResponseHeader(node);
                            if (CollectionUtils.isNotEmpty(responseHeaders)) {
                                conditionalResponseHeaders.put(condition, responseHeaders);
                            }
                        } else {
                            logger.warn("Both queryParamName and queryParamValue have to be set for the <"
                                    + Constants.CONDITIONAL + "> tag");
                            continue;
                        }
                    }

                    //if this mappingNode has "valid" allMappingNodes, add it as a rule in the mapper
                    if (CollectionUtils.isNotEmpty(defaultResponseHeaders)
                            || !conditionalResponseHeaders.isEmpty()) {
                        Mapping newMapping = new Mapping();
                        newMapping.setProcessorClass(mappingProcessorForThisRule);
                        newMapping.setUrl(url);
                        newMapping.setDefaultResponseHeaders(defaultResponseHeaders);
                        newMapping.setConditionalResponseHeaders(conditionalResponseHeaders);
                        this.mappings.add(newMapping);
                    }
                }
            }
        } else {
            //the filter is useless, no valid allMappingNodes found in the config file
            if (logger.isInfoEnabled()) {
                logger.info("No valid mappings found. Huh!");
            }
        }
    } else {
        //absense of <response-header-mapper> node not expected, throwing a runtime exception
        throw new RuntimeException(
                "Root node <" + Constants.RESPONSE_HEADER_MAPPER + "> missing from the file");
    }
}

From source file:com.limegroup.gnutella.licenses.CCLicense.java

/**
 * Parses the 'license' item.//from ww w. j  av a 2s .  c o m
 */
protected void parseLicenseItem(Node license) {
    if (LOG.isTraceEnabled())
        LOG.trace("Parsing license item.");

    // Get the license URL. 
    NamedNodeMap attributes = license.getAttributes();
    Node about = attributes.getNamedItem("rdf:about");
    List<Details> details = Collections.emptyList();
    if (about != null) {
        String value = about.getNodeValue();
        try {
            details = getDetailsForLicenseURL(new URL(value));
        } catch (MalformedURLException murl) {
            LOG.warn("Unable to create license URL for: " + value, murl);
        }
    }

    // Optimization:  If no details, exit early.
    if (!details.iterator().hasNext())
        return;

    List<String> required = null;
    List<String> prohibited = null;
    List<String> permitted = null;

    // Get the 'permit', 'requires', and 'prohibits' values.
    NodeList children = license.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        String name = child.getNodeName();
        if (name.equalsIgnoreCase("requires")) {
            if (required == null)
                required = new LinkedList<String>();
            addPermission(required, child);
        } else if (name.equalsIgnoreCase("permits")) {
            if (permitted == null)
                permitted = new LinkedList<String>();
            addPermission(permitted, child);
        } else if (name.equalsIgnoreCase("prohibits")) {
            if (prohibited == null)
                prohibited = new LinkedList<String>();
            addPermission(prohibited, child);
        }
    }

    // Okay, now iterate through each details and set the lists.
    for (Details detail : details) {
        if (LOG.isDebugEnabled())
            LOG.debug("Setting license details for " + details);
        detail.required = required;
        detail.prohibited = prohibited;
        detail.permitted = permitted;
    }

    return;
}