Example usage for org.w3c.dom Element getElementsByTagNameNS

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

Introduction

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

Prototype

public NodeList getElementsByTagNameNS(String namespaceURI, String localName) throws DOMException;

Source Link

Document

Returns a NodeList of all the descendant Elements with a given local name and namespace URI in document order.

Usage

From source file:eu.elf.license.LicenseParser.java

/**
 * Creates List of LicenseModelGroup objects
 *
 * @param productGroupElementList - List of <ns:productGroup> elements
 * @return list of LicenseModelGroup objects
 *//*from w ww  .  j  a v a2s . com*/
private static List<LicenseModelGroup> createLicenseModelGroupList(NodeList productGroupElementList) {
    List<LicenseModelGroup> lmgList = new ArrayList<LicenseModelGroup>();

    for (int i = 0; i < productGroupElementList.getLength(); i++) {
        LicenseModelGroup tempLMG = new LicenseModelGroup();
        Boolean isAccountGroup = false;

        Element productGroupElement = (Element) productGroupElementList.item(i);

        NamedNodeMap productGroupElementAttributeMap = productGroupElement.getAttributes();

        for (int j = 0; j < productGroupElementAttributeMap.getLength(); j++) {
            Attr attrs = (Attr) productGroupElementAttributeMap.item(j);

            if (attrs.getNodeName().equals("id")) {

                if (attrs.getNodeValue().equals("ACCOUNTING_SUMMARY_GROUP")) { // Skip element with id="ACCOUNTING_SUMMARY_GROUP" -  do not add to the list
                    isAccountGroup = true;
                }

                if (attrs.getNodeName() != null) {
                    tempLMG.setId(attrs.getNodeValue());
                }
            }
            if (attrs.getNodeName().equals("name")) {
                if (attrs.getNodeName() != null) {
                    tempLMG.setUrl(attrs.getNodeValue());
                }
            }
        }

        if (isAccountGroup == true) {
            continue; // Skip element with id="ACCOUNTING_SUMMARY_GROUP" -  do not add to the list
        }

        Element abstractElement = (Element) productGroupElement
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "abstract").item(0);
        if (abstractElement != null) {
            tempLMG.setDescription(abstractElement.getTextContent());
        }

        Element titleElement = (Element) productGroupElement
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "title").item(0);
        if (titleElement != null) {
            tempLMG.setName(titleElement.getTextContent());
        }

        NodeList productElementList = productGroupElement
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "product");
        tempLMG.setLicenseModels(createLicenseModelList(productElementList));

        lmgList.add(tempLMG);
    }

    return lmgList;
}

From source file:kml.feature.Placemark.java

public void setPlacemarkElement(Element element) {
    try {//from   w w  w.ja  v  a  2  s  .  c  o  m
        this.setParent(element.getParentNode().getNodeName());
    } catch (Exception ex) {
        this.setParent("UNKNOWN");
    }

    // id attribute
    if (element.getAttribute("id").length() > 0) {
        String id = element.getAttribute("id");
        this.setId(id);
    } // id
      // name element
    if (element.getElementsByTagNameNS("*", "name").getLength() > 0) {
        String name = element.getElementsByTagNameNS("*", "name").item(0).getTextContent();
        this.setName(name);
    } // name
    if (element.getElementsByTagNameNS("*", "description").getLength() > 0) {
        String description = element.getElementsByTagNameNS("*", "description").item(0).getTextContent();
        this.setDescription(description);
    } // description     
    if (element.getElementsByTagNameNS("*", "Style").getLength() > 0) {
        this.style.setStyleElement(element);
    } // Style   
    if (element.getElementsByTagNameNS("*", "StyleMap").getLength() > 0) {
        this.styleMap.setElement(element);
    } // StyleMap        
    int suKnt = element.getElementsByTagNameNS("*", "styleUrl").getLength();
    if (element.getElementsByTagNameNS("*", "styleUrl").getLength() > 0) {
        //String styleUrl = element.getElementsByTagNameNS("*","styleUrl").item(0).getTextContent();
        //pm.append("styleUrl: ").append(styleUrl).append("\n");
        for (int knt = 0; knt < suKnt; knt++) {
            String styleUrl = element.getElementsByTagNameNS("*", "styleUrl").item(knt).getTextContent();
            this.setStyleUrl(styleUrl);
        }
        //System.out.println("element styleUrl : " + element.getElementsByTagNameNS("*","styleUrl").item(0).getTextContent());
    } // styleUrl    

    // IGNORE MultiGeometry because the child elements are geometris that are parsed anyway
    //                if (element.getElementsByTagNameNS("*","MultiGeometry").getLength() > 0) {
    //                    //TODO
    //                }// MultiGeometry    
    int polyKnt = element.getElementsByTagNameNS("*", "Polygon").getLength();
    if (polyKnt > 0) {
        NodeList polyNodes = element.getElementsByTagNameNS("*", "Polygon"); //NodeList
        if (polyNodes != null) {
            for (int i = 0; i < polyNodes.getLength(); i++) {
                if (polyNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
                    Element polyElement = (Element) polyNodes.item(i);
                    Polygon polygon = new Polygon(polyElement);
                    //System.out.println("Adding Polygon[" + i + "] id:" + polygon.getId());
                    this.addGeometry(polygon.getId(), polygon);
                }
            }
        }
        //            for (int knt = 0; knt < polyKnt; knt++) {
        //                Element polyElement = (Element) element.getElementsByTagNameNS("*","Polygon").item(knt);
        //                Polygon polygon = new Polygon(polyElement);
        //                System.out.println("Adding Polygon[" + knt + "] id:" + polygon.getId() + " " + polygon.toString());
        //                this.addGeometry(polygon.getId(), polygon);
        //
        //            }
    } // Polygon ====================================================
      //System.out.println("      Placemark.setPlacemarkElement element.getTagName() " + element.getTagName());
    if (element.getTagName().equals("Polygon")) {
        Polygon polygon = new Polygon(element);
        System.out.println("Adding Polygon[ORPHAN] id:" + polygon.getId());
        this.addGeometry(polygon.getId(), polygon);
    } // Polygon Orphan ====================================================
    int pointKnt = element.getElementsByTagNameNS("*", "Point").getLength();
    if (pointKnt > 0) {
        for (int knt = 0; knt < pointKnt; knt++) {
            Point point = new Point(element);
            //System.out.println("Adding LineString[" + knt + "] id:" + lineString.getId() + "\n" + lineString.getCoordinates());
            this.addGeometry(point.getId(), point);
        }
    } // Point ====================================================== 
    if (element.getTagName().equals("Point")) {
        Point point = new Point(element);
        System.out.println("Adding Point[ORPHAN] id:" + point.getId());
        this.addGeometry(point.getId(), point);
    } // Point Orphan ====================================================        
    int lsKnt = element.getElementsByTagNameNS("*", "LineString").getLength();
    if (lsKnt > 0) {
        for (int knt = 0; knt < lsKnt; knt++) {
            LineString lineString = new LineString(element);
            //System.out.println("Adding LineString[" + knt + "] id:" + lineString.getId() + "\n" + lineString.getCoordinates());
            this.addGeometry(lineString.getId(), lineString);
        }
    } // LineString =================================================
    //            if (lsKnt > 0) {
    //                NodeList lsNodes = element.getElementsByTagNameNS("*","LineString"); //NodeList
    //                if (lsNodes != null) {
    //                    for (int knt = 0; knt < lsKnt; knt++) {
    //                        if (lsNodes.item(knt).getNodeType() == Node.ELEMENT_NODE) {
    //                            LineString lineString = new LineString((Element) lsNodes.item(knt));
    //                            //System.out.println("Adding LineString[" + knt + "] id:" + lineString.getId() + "\n" + lineString.getCoordinates());
    //                            this.addGeometry(lineString.getId(), lineString);
    //                        }
    //                    }
    //                }
    //            }        
    if (element.getTagName().equals("LineString")) {
        LineString lineString = new LineString(element);
        System.out.println("Adding LineString[ORPHAN] id:" + lineString.getId());
        this.addGeometry(lineString.getId(), lineString);
    } // LineString Orphan ====================================================         
      // Is this necessary since it is part of a Polygon?
      //                int lrKnt = element.getElementsByTagNameNS("*","LinearRing").getLength();
      //                if (element.getElementsByTagNameNS("*","LinearRing").getLength() > 0) {
      //                    for (int knt = 0; knt < lrKnt; knt++) {
      //                        System.out.println("Adding LinearRing[" + knt + "] ");
      //                        LinearRing linearRing = new LinearRing(element);
      //                        this.addGeometry(linearRing.getId(), linearRing);
      //                    }
      //                }// LinearRing ================================================= 
}

From source file:de.mpg.escidoc.services.exportmanager.Export.java

/**
 * Walk around the itemList XML, fetch all files from components via URIs
 * and put them into the archive {@link OutputStream} aos
 * /*from   www  .java 2 s .com*/
 * @param aos
 *            - array {@link OutputStream}
 * @param itemList
 *            - XML with the files to be fetched, see NS:
 *            http://www.escidoc.de/schemas/components/0.7
 * @throws ExportManagerException
 */
private void fetchComponentsDo(OutputStream aos, String itemList) throws ExportManagerException {
    Document doc = parseDocument(itemList);
    NodeIterator ni = getFilteredNodes(new ComponentNodeFilter(), doc);

    // login only once
    String userHandle;
    try {
        userHandle = AdminHelper.loginUser(USER_ID, PASSWORD);
    } catch (Exception e) {
        throw new ExportManagerException("Cannot login", e);
    }

    String fileName;
    Node n;
    while ((n = ni.nextNode()) != null) {

        Element componentElement = (Element) n;
        NodeList nl = componentElement.getElementsByTagNameNS(COMPONENTS_NS, "content");
        Element contentElement = (Element) nl.item(0);
        if (contentElement == null) {
            throw new ExportManagerException(
                    "Wrong item XML: {" + COMPONENTS_NS + "}component element doesn't contain content element. "
                            + "Component id: " + componentElement.getAttributeNS(XLINK_NS, "href"));
        }
        String href = contentElement.getAttributeNS(XLINK_NS, "href");
        String storageStatus = contentElement.getAttribute("storage");

        // get file name
        if ("internal-managed".equals(storageStatus)) {
            NodeIterator nif = ((DocumentTraversal) doc).createNodeIterator(componentElement,
                    NodeFilter.SHOW_ELEMENT, new FileNameNodeFilter(), true);
            Node nf;

            if ((nf = nif.nextNode()) != null) {
                fileName = ((Element) nf).getTextContent();

                // names of files for
                Matcher m = Pattern.compile("^([\\w.]+?)(\\s+|$)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL)
                        .matcher(fileName);
                m.find();
                fileName = m.group(1);
            } else {
                throw new ExportManagerException("Missed file property: {" + COMPONENTS_NS
                        + "}component element doesn't contain file-name element (md-records/md-record/file:file/dc:title). "
                        + "Component id: " + componentElement.getAttributeNS(XLINK_NS, "href"));
            }
        }
        // TODO: the external-managed will be processed later
        else {
            throw new ExportManagerException("Missed internal-managed file in {" + COMPONENTS_NS
                    + "}component: components/component/content[@storage=\"internal-managed\"]"
                    + "Component id: " + componentElement.getAttributeNS(XLINK_NS, "href"));
        }

        logger.info("link to the content: " + href);
        logger.info("storage status: " + storageStatus);
        logger.info("fileName: " + fileName);

        // get file via URI
        String url;
        try {
            url = ServiceLocator.getFrameworkUrl() + href;
        } catch (Exception e) {
            throw new ExportManagerException("Cannot get framework url", e);
        }

        logger.info("url=" + url);
        GetMethod method = new GetMethod(url);

        method.setFollowRedirects(false);
        method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);

        // Execute the method with HttpClient.
        HttpClient client = new HttpClient();
        try {
            ProxyHelper.executeMethod(client, method);
        } catch (Exception e) {
            throw new ExportManagerException("Cannot execute HttpMethod", e);
        }

        int status = method.getStatusCode();
        logger.info("Status=" + status);

        if (status != 200)
            fileName += ".error" + status;

        byte[] responseBody;
        try {
            responseBody = method.getResponseBody();
        } catch (Exception e) {

            throw new ExportManagerException("Cannot get Response Body", e);

        }
        InputStream bis = new BufferedInputStream(new ByteArrayInputStream(responseBody));

        if (aos instanceof ZipOutputStream) {
            ZipEntry ze = new ZipEntry(fileName);
            ze.setSize(responseBody.length);
            try {
                ((ZipOutputStream) aos).putNextEntry(ze);
                writeFromStreamToStream(bis, aos);
                ((ZipOutputStream) aos).closeEntry();
            } catch (Exception e) {
                throw new ExportManagerException("zip2stream generation problem", e);
            }

        } else if (aos instanceof TarOutputStream) {
            TarEntry te = new TarEntry(fileName);
            te.setSize(responseBody.length);
            try {
                ((TarOutputStream) aos).putNextEntry(te);
                writeFromStreamToStream(bis, aos);
                ((TarOutputStream) aos).closeEntry();
            } catch (Exception e) {
                throw new ExportManagerException("tar2stream generation problem", e);
            }
        } else {
            throw new ExportManagerException("Unsupported archive output stream: " + aos.getClass());
        }
        try {
            bis.close();
        } catch (Exception e) {
            throw new ExportManagerException("Cannot close InputStream", e);
        }
    }

}

From source file:it.pronetics.madstore.crawler.publisher.impl.AtomPublisherImpl.java

@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void publish(Page page) {
    try {/* w ww . ja v a  2 s .com*/
        if (LOG.isDebugEnabled()) {
            LOG.debug("Publishing feed:\n{}.", page.getData());
        }
        Element feed = DomHelper.getDomFeedFromString(page.getData());
        String collectionKey = getOrGenerateCollectionKey(page, feed);
        String collectionTitle = getOrGenerateCollectionTitle(page, feed);
        String collectionHref = collectionKey;
        Element collectionElement = createCollectionElement(collectionKey, collectionHref, collectionTitle);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Publishing collection:\n{}.", DomHelper.getStringFromDomElement(collectionElement));
        }
        String newCollectionKey = collectionRepository.putIfAbsent(collectionElement);
        if (newCollectionKey != null) {
            LOG.info("Inserted collection with key {}.", collectionKey);
        } else {
            LOG.info("Collection {} already existent.", collectionKey);
        }
        NodeList entryNodes = feed.getElementsByTagNameNS(AtomConstants.ATOM_NS, AtomConstants.ATOM_ENTRY);
        if (entryNodes != null && entryNodes.getLength() > 0) {
            for (int i = 0; i < entryNodes.getLength(); i++) {
                Element entry = (Element) entryNodes.item(i);
                String entryKey = getOrGenerateEntryKey(entry);
                setUpdatedDateTimeIfNecessary(entry);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Publishing entry:\n{}.", DomHelper.getStringFromDomElement(entry));
                }
                String newEntryKey = entryRepository.putIfAbsent(collectionKey, entry);
                if (newEntryKey != null) {
                    LOG.info("Entry with key {} inserted in collection {}.", entryKey, collectionKey);
                } else {
                    LOG.info("Entry with key {} already existent in collection {}.", entryKey, collectionKey);
                    String updatedEntryKey = entryRepository.updateIfNewer(collectionKey, entry);
                    if (updatedEntryKey != null) {
                        LOG.info("Entry with key {} in collection {} was updated.", entryKey, collectionKey);
                    } else {
                        LOG.info("Entry with key {} wasn't updated because is older.", entryKey);
                    }
                }
            }
        } else {
            LOG.info("No entries for {}", page.getLink());
        }
    } catch (Exception e) {
        LOG.info("Publishing abnormally terminated: {}", page.getLink());
        LOG.warn(e.getMessage());
        LOG.debug(e.getMessage(), e);
    }
}

From source file:javax.microedition.ims.core.xdm.XDMServiceImpl.java

private List<DocumentBean> handleFolderNode(Node node) {
    List<DocumentBean> retValue = new ArrayList<DocumentBean>();

    if (node != null) {

        if (!"Folder".equalsIgnoreCase(node.getNodeName())) {
            throw new IllegalArgumentException("Must be 'Folder' node");
        }//w w w.j a va 2s.  c  o m

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

            NodeList nameNode = element.getElementsByTagNameNS("*", "entry");

            for (int entrIndex = 0; entrIndex < nameNode.getLength(); entrIndex++) {
                if (nameNode.item(entrIndex).getNodeType() == Node.ELEMENT_NODE) {
                    Element entryElement = (Element) nameNode.item(entrIndex);
                    // "<entry
                    // uri=\"http://siptest.dummy.com:8080/services/resource-lists/users/sip%3Amovial11%40dummy.com/index\"
                    // etag=\"W/'437-1271417541984'\" last-modified=\"2010-04-16T13:32:21.000+02:00\" size=\"437\"/>\n"
                    // +

                    String uriAttrValue = entryElement.getAttribute("uri");
                    String etagAttrValue = entryElement.getAttribute("etag");
                    String lmAttrValue = entryElement.getAttribute("last-modified");
                    String sizeAttrValue = entryElement.getAttribute("size");

                    DocumentBean documentBean = new DocumentDataBean(uriAttrValue, etagAttrValue, lmAttrValue,
                            sizeAttrValue);

                    retValue.add(documentBean);
                }
            }
        }
    }

    return retValue.size() != 0 ? retValue : Collections.<DocumentBean>emptyList();
}

From source file:eu.elf.license.LicenseQueryHandler.java

/**
 * Gets the price of the License Model// w  w  w.ja  v a  2  s  .co m
 *
 * @param lm     - LicenseModel object
 * @param userId - UserId
 * @throws Exception
 * @return         - ProductPriceSum as String
 */
public String getLicenseModelPrice(LicenseModel lm, String userId) throws Exception {
    StringBuffer buf = null;
    String productPriceSum = "";
    List<LicenseParam> lpList = lm.getParams();

    String productPriceQuery = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
            + "<wpos:WPOSRequest xmlns:wpos=\"http://www.conterra.de/wpos/1.1\" version=\"1.1.0\">"
            + "<wpos:GetPrice collapse=\"true\">" + "<wpos:Product id=\""
            + StringEscapeUtils.escapeXml10(lm.getId()) + "\">" + "<wpos:ConfigParams>";

    for (int i = 0; i < lpList.size(); i++) {
        if (lpList.get(i).getParameterClass().equals("configurationParameter")) {

            LicenseParam lp = (LicenseParam) lpList.get(i);

            String priceQuery = "<wpos:Parameter name=\"" + StringEscapeUtils.escapeXml10(lp.getName()) + "\">";

            if (lp instanceof LicenseParamInt) {
                LicenseParamInt lpi = (LicenseParamInt) lp;

                priceQuery += "<wpos:Value selected=\"true\">" + lpi.getValue() + "</wpos:Value>"
                        + "</wpos:Parameter>";
            } else if (lp instanceof LicenseParamBln) {
                LicenseParamBln lpBln = (LicenseParamBln) lp;

                priceQuery += "<wpos:Value selected=\"true\">" + lpBln.getValue() + "</wpos:Value>"
                        + "</wpos:Parameter>";
            } else if (lp instanceof LicenseParamDisplay) {
                LicenseParamDisplay lpd = (LicenseParamDisplay) lp;
                List<String> values = lpd.getValues();

                if (lp.getName().equals("LICENSE_USER_GROUP")) {
                    priceQuery += "<wpos:Value>Users</wpos:Value>";

                } else if (lp.getName().equals("LICENSE_USER_ID")) {
                    priceQuery += "<wpos:Value>" + userId + "</wpos:Value>";

                } else {
                    for (int l = 0; l < values.size(); l++) {
                        priceQuery += "<wpos:Value selected=\"true\">"
                                + StringEscapeUtils.escapeXml10(values.get(l)) + "</wpos:Value>";
                    }
                }

                priceQuery += "</wpos:Parameter>";
            } else if (lp instanceof LicenseParamEnum) {
                LicenseParamEnum lpEnum = (LicenseParamEnum) lp;

                List<String> tempOptions = lpEnum.getOptions();
                List<String> tempSelections = lpEnum.getSelections();

                if (tempSelections.size() == 0) {
                    priceQuery = "";
                } else {
                    String selectionsString = "";

                    for (int j = 0; j < tempSelections.size(); j++) {
                        if (j == 0) {
                            selectionsString = tempSelections.get(j);
                        } else {
                            selectionsString += ", " + tempSelections.get(j);
                        }
                    }

                    priceQuery += "<wpos:Value selected=\"true\">"
                            + StringEscapeUtils.escapeXml10(selectionsString) + "</wpos:Value>"
                            + "</wpos:Parameter>";
                }
            } else if (lp instanceof LicenseParamText) {
                LicenseParamText lpText = (LicenseParamText) lp;
                List<String> values = lpText.getValues();

                for (int k = 0; k < values.size(); k++) {
                    priceQuery += "<wpos:Value selected=\"true\">" + lpText.getValues() + "</wpos:Value>";
                }
                priceQuery += "</wpos:Parameter>";
            }

            productPriceQuery += priceQuery;
        }

    }

    productPriceQuery += "</wpos:ConfigParams>" + "</wpos:Product>" + "</wpos:GetPrice>"
            + "</wpos:WPOSRequest>";

    //System.out.println("query: "+productPriceQuery.toString());

    try {
        buf = doHTTPQuery(this.wposURL, "post", productPriceQuery, false);
        //System.out.println("response: "+buf.toString());

        // Get productPriceInfo from the response
        Document xmlDoc = LicenseParser.createXMLDocumentFromString(buf.toString());
        Element catalogElement = (Element) xmlDoc
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "catalog").item(0);
        NodeList productGroupElementList = catalogElement
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "productGroup");

        for (int m = 0; m < productGroupElementList.getLength(); m++) {
            Element productGroupElement = (Element) productGroupElementList.item(m);
            Element calculationElement = (Element) productGroupElement
                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "calculation").item(0);
            Element declarationListElement = (Element) calculationElement
                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "declarationList").item(0);
            Element referencedParametersElement = (Element) declarationListElement
                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "referencedParameters").item(0);
            NodeList referencedParametersParameterList = referencedParametersElement
                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "parameter");

            for (int n = 0; n < referencedParametersParameterList.getLength(); n++) {
                Element referencedParametersParameterElement = (Element) referencedParametersParameterList
                        .item(n);

                NamedNodeMap referencedParametersParameterAttributeMap = referencedParametersParameterElement
                        .getAttributes();

                for (int o = 0; o < referencedParametersParameterAttributeMap.getLength(); o++) {
                    Attr attrs = (Attr) referencedParametersParameterAttributeMap.item(o);

                    if (attrs.getNodeName().equals("name")) {
                        if (attrs.getNodeValue().equals("productPriceSum")) {
                            Element valueElement = (Element) referencedParametersParameterElement
                                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "value").item(0);

                            productPriceSum = valueElement.getTextContent();
                        }
                    }
                }

            }

        }

    } catch (Exception e) {
        throw e;
    }

    return productPriceSum;
}

From source file:org.springjutsu.validation.namespace.ValidationConfigurationDefinitionParser.java

/**
 * Do actual parsing.//from   www  .java 2s .  co m
 */
public BeanDefinition parse(Element configNode, ParserContext context) {

    BeanDefinitionBuilder validationManagerBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(ValidationManager.class);
    BeanDefinitionBuilder validationErrorMessageHandlerBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(ValidationErrorMessageHandler.class);
    BeanDefinitionBuilder ruleExecutorContainerBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(RuleExecutorContainer.class);
    BeanDefinitionBuilder contextHandlerContainerBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(ValidationContextHandlerContainer.class);
    BeanDefinitionBuilder validationRulesContainerBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(ValidationRulesContainer.class);

    // Parse message configuration...
    Element messageConfig = (Element) configNode
            .getElementsByTagNameNS(configNode.getNamespaceURI(), "message-config").item(0);
    if (messageConfig != null) {
        validationErrorMessageHandlerBuilder.addPropertyValue("errorMessagePrefix",
                messageConfig.getAttribute("errorMessagePrefix"));
        validationErrorMessageHandlerBuilder.addPropertyValue("fieldLabelPrefix",
                messageConfig.getAttribute("fieldLabelPrefix"));
        validationErrorMessageHandlerBuilder.addPropertyValue("enableSuperclassFieldLabelLookup",
                messageConfig.getAttribute("enableSuperclassFieldLabelLookup"));
    }

    // Parse rules configuration...
    Element rulesConfig = (Element) configNode
            .getElementsByTagNameNS(configNode.getNamespaceURI(), "rules-config").item(0);
    if (rulesConfig != null) {
        boolean addDefaultRules = Boolean.valueOf(rulesConfig.getAttribute("addDefaultRuleExecutors"));
        ruleExecutorContainerBuilder.addPropertyValue("addDefaultRuleExecutors", addDefaultRules);

        List<KeyedBeanRegistrant> ruleExecutors = new ArrayList<KeyedBeanRegistrant>();
        NodeList ruleExecutorNodes = rulesConfig.getElementsByTagNameNS(rulesConfig.getNamespaceURI(),
                "rule-executor");
        for (int executorNbr = 0; executorNbr < ruleExecutorNodes.getLength(); executorNbr++) {
            Element ruleExecutorNode = (Element) ruleExecutorNodes.item(executorNbr);
            BeanDefinitionBuilder executorBuilder = BeanDefinitionBuilder
                    .genericBeanDefinition(ruleExecutorNode.getAttribute("class"));
            String ruleExecutorBeanName = registerInfrastructureBean(context, executorBuilder);
            ruleExecutors
                    .add(new KeyedBeanRegistrant(ruleExecutorBeanName, ruleExecutorNode.getAttribute("name")));
        }
        ruleExecutorContainerBuilder.addPropertyValue("ruleExecutorBeanRegistrants", ruleExecutors);

        List<Class<?>> excludeAnnotations = new ArrayList<Class<?>>();
        excludeAnnotations.add(RecursiveValidationExclude.class);

        NodeList excludeAnnotationNodes = rulesConfig.getElementsByTagNameNS(rulesConfig.getNamespaceURI(),
                "recursion-exclude-annotation");
        for (int excludeNbr = 0; excludeNbr < excludeAnnotationNodes.getLength(); excludeNbr++) {
            Element excludeNode = (Element) excludeAnnotationNodes.item(excludeNbr);
            String excludeAnnotationClass = excludeNode.getAttribute("class");
            try {
                excludeAnnotations.add(Class.forName(excludeAnnotationClass));
            } catch (ClassNotFoundException cnfe) {
                throw new IllegalArgumentException(
                        "Invalid exclude annotation class: " + excludeAnnotationClass, cnfe);
            }
        }
        validationRulesContainerBuilder.addPropertyValue("excludeAnnotations", excludeAnnotations);

        List<Class<?>> includeAnnotations = new ArrayList<Class<?>>();
        includeAnnotations.add(RecursiveValidationInclude.class);

        NodeList includeAnnotationNodes = rulesConfig.getElementsByTagNameNS(rulesConfig.getNamespaceURI(),
                "recursion-include-annotation");
        for (int includeNbr = 0; includeNbr < includeAnnotationNodes.getLength(); includeNbr++) {
            Element includeNode = (Element) includeAnnotationNodes.item(includeNbr);
            String includeAnnotationClass = includeNode.getAttribute("class");
            try {
                includeAnnotations.add(Class.forName(includeAnnotationClass));
            } catch (ClassNotFoundException cnfe) {
                throw new IllegalArgumentException(
                        "Invalid include annotation class: " + includeAnnotationClass, cnfe);
            }
        }
        validationRulesContainerBuilder.addPropertyValue("includeAnnotations", includeAnnotations);
    }

    // Parse context configuration...
    Element contextConfig = (Element) configNode
            .getElementsByTagNameNS(configNode.getNamespaceURI(), "context-config").item(0);
    if (contextConfig != null) {
        boolean addDefaultContextHandlers = Boolean
                .valueOf(contextConfig.getAttribute("addDefaultContextHandlers"));
        contextHandlerContainerBuilder.addPropertyValue("addDefaultContextHandlers", addDefaultContextHandlers);

        List<KeyedBeanRegistrant> contextHandlers = new ArrayList<KeyedBeanRegistrant>();
        NodeList contextHandlerNodes = contextConfig.getElementsByTagNameNS(contextConfig.getNamespaceURI(),
                "context-handler");
        for (int handlerNbr = 0; handlerNbr < contextHandlerNodes.getLength(); handlerNbr++) {
            Element contextHandlerNode = (Element) contextHandlerNodes.item(handlerNbr);
            BeanDefinitionBuilder handlerBuilder = BeanDefinitionBuilder
                    .genericBeanDefinition(contextHandlerNode.getAttribute("class"));
            String ruleExecutorBeanName = registerInfrastructureBean(context, handlerBuilder);
            contextHandlers.add(
                    new KeyedBeanRegistrant(ruleExecutorBeanName, contextHandlerNode.getAttribute("type")));
        }
        contextHandlerContainerBuilder.addPropertyValue("contextHandlerBeanRegistrants", contextHandlers);
    }

    // Register them beans.
    registerInfrastructureBean(context, validationRulesContainerBuilder);
    registerInfrastructureBean(context, ruleExecutorContainerBuilder);
    registerInfrastructureBean(context, contextHandlerContainerBuilder);
    registerInfrastructureBean(context, validationErrorMessageHandlerBuilder);
    context.registerBeanComponent(new BeanComponentDefinition(validationManagerBuilder.getBeanDefinition(),
            configNode.getAttribute("validatorName")));

    return null;
}

From source file:gov.nih.nci.cacis.common.util.ExtractSchematron.java

private void processDatatypeAnnotation(XSAnnotation annotation, TypeUsage typeUsage, Writer out)
        throws IOException {
    try {/*from  w  w w .  j  ava  2  s .  co  m*/
        final Document doc = this.dfactory.newDocumentBuilder().newDocument();
        annotation.writeAnnotation(doc, XSAnnotation.W3C_DOM_DOCUMENT);

        final NodeList result = (NodeList) this.patternExpr.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < result.getLength(); i++) {
            final Element patternElt = (Element) result.item(i);
            // the included schematron rules do not have text content in the assert,
            // which should be the human-readable version of the test. we will use
            // the pattern name instead, as it's the most descriptive thing we have
            final String name = patternElt.getAttribute("name");
            // we know each pattern has a single rule and a single assert
            final Element assertElt = (Element) patternElt.getElementsByTagNameNS(SCH_NS, "assert").item(0);
            assertElt.setTextContent(name);
            final String test = assertElt.getAttribute("test");
            final String test2 = test.replaceAll(ELEMENT_REGEXP, "$1hl7:$2");
            assertElt.setAttribute("test", test2);
            final Element ruleElt = (Element) patternElt.getElementsByTagNameNS(SCH_NS, "rule").item(0);
            typeUsage.getRuleIds().add(ruleElt.getAttribute("id"));
            writeNode(ruleElt, out);
            out.write("\n");
        }
    } catch (final XPathExpressionException e) {
        LOG.error("Could not extract rules", e);
    } catch (final ParserConfigurationException e) {
        LOG.error("Could not extract rules", e);
    } catch (final TransformerException e) {
        LOG.error("Could not extract rules", e);
    }
}

From source file:be.fedict.eid.applet.service.signer.AbstractXmlSignatureService.java

public void postSign(byte[] signatureValue, List<X509Certificate> signingCertificateChain) {
    LOG.debug("postSign");

    /*//from ww w  . j  a  va2s . co m
     * Retrieve the intermediate XML signature document from the temporary
     * data storage.
     */
    TemporaryDataStorage temporaryDataStorage = getTemporaryDataStorage();
    InputStream documentInputStream = temporaryDataStorage.getTempInputStream();
    String signatureId = (String) temporaryDataStorage.getAttribute(SIGNATURE_ID_ATTRIBUTE);
    LOG.debug("signature Id: " + signatureId);

    /*
     * Load the signature DOM document.
     */
    Document document;
    try {
        document = loadDocument(documentInputStream);
    } catch (Exception e) {
        throw new RuntimeException("DOM error: " + e.getMessage(), e);
    }

    /*
     * Locate the correct ds:Signature node.
     */
    Element nsElement = document.createElement("ns");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);
    Element signatureElement;
    try {
        signatureElement = (Element) XPathAPI.selectSingleNode(document,
                "//ds:Signature[@Id='" + signatureId + "']", nsElement);
    } catch (TransformerException e) {
        throw new RuntimeException("XPATH error: " + e.getMessage(), e);
    }
    if (null == signatureElement) {
        throw new RuntimeException("ds:Signature not found for @Id: " + signatureId);
    }

    /*
     * Insert signature value into the ds:SignatureValue element
     */
    NodeList signatureValueNodeList = signatureElement
            .getElementsByTagNameNS(javax.xml.crypto.dsig.XMLSignature.XMLNS, "SignatureValue");
    Element signatureValueElement = (Element) signatureValueNodeList.item(0);
    signatureValueElement.setTextContent(Base64.encode(signatureValue));

    //LOG.debug("signatureValue: "+Base64.encode(signatureValue));
    /*
     * Allow signature facets to inject their own stuff.
     */
    for (SignatureFacet signatureFacet : this.signatureFacets) {
        signatureFacet.postSign(signatureElement, signingCertificateChain);
    }

    OutputStream signedDocumentOutputStream = getSignedDocumentOutputStream();
    if (null == signedDocumentOutputStream) {
        throw new IllegalArgumentException("signed document output stream is null");
    }
    try {
        writeDocument(document, signedDocumentOutputStream);
    } catch (Exception e) {
        LOG.debug("error writing the signed XML document: " + e.getMessage(), e);
        throw new RuntimeException("error writing the signed XML document: " + e.getMessage(), e);
    }
}

From source file:javax.microedition.ims.core.xdm.XDMServiceImpl.java

private URIListData handleListNode(Node listNode) {

    URIListDataBean retValue;//from   w  w  w . j  ava2  s  . co  m

    if (listNode != null) {

        if (!LIST_NODE_NAME.equalsIgnoreCase(listNode.getLocalName())) {
            throw new IllegalArgumentException("Must be 'list' listNode");
        }

        if (listNode.getNodeType() == Node.ELEMENT_NODE) {
            Element listElement = (Element) listNode;

            NodeList displayNameNode = listElement.getElementsByTagNameNS("*", "display-name");
            String displayName = /* "" */null;

            for (int entrIndex = 0; entrIndex < displayNameNode.getLength(); entrIndex++) {
                if (displayNameNode.item(entrIndex).getNodeType() == Node.ELEMENT_NODE) {

                    Element entryElement = (Element) displayNameNode.item(entrIndex);
                    if (LIST_NODE_NAME.equalsIgnoreCase(entryElement.getParentNode().getLocalName())) {

                        final Node firstChildNode = entryElement.getFirstChild();
                        if (firstChildNode != null) {
                            displayName = firstChildNode.getNodeValue();
                        }
                        break;
                    }
                }
            }

            String name = listElement.getAttribute("name");

            List<ListEntryData> listEntryData = new ArrayList<ListEntryData>();

            // extracts single user URI
            {
                NodeList entryNode = listElement.getElementsByTagNameNS("*", "entry");
                for (int entrIndex = 0; entrIndex < entryNode.getLength(); entrIndex++) {
                    if (entryNode.item(entrIndex).getNodeType() == Node.ELEMENT_NODE) {
                        Element entryElement = (Element) entryNode.item(entrIndex);
                        if (LIST_NODE_NAME.equalsIgnoreCase(entryElement.getParentNode().getLocalName())) {
                            String entryURI = entryElement.getAttribute("uri");
                            NodeList entryDisplayNameNode = entryElement.getElementsByTagNameNS("*",
                                    "display-name");
                            String entryDisplayName = null/* "" */;
                            if (entryDisplayNameNode.getLength() > 0) {
                                Node node = entryDisplayNameNode.item(0);
                                final Node firstChildNode = node.getFirstChild();
                                if (firstChildNode != null) {
                                    entryDisplayName = firstChildNode.getNodeValue();
                                }
                            }

                            listEntryData.add(
                                    new ListEntryDataBean(ListEntryData.URI_ENTRY, entryDisplayName, entryURI));
                        }
                    }
                }
            }

            // extracts references to an already existing URI list
            {
                NodeList externalsNode = listElement.getElementsByTagNameNS("*", "external");
                for (int entrIndex = 0; entrIndex < externalsNode.getLength(); entrIndex++) {
                    if (externalsNode.item(entrIndex).getNodeType() == Node.ELEMENT_NODE) {
                        Element externalElement = (Element) externalsNode.item(entrIndex);
                        if (LIST_NODE_NAME.equalsIgnoreCase(externalElement.getParentNode().getLocalName())) {
                            String anchorURI = externalElement.getAttribute("anchor");
                            NodeList anchorDisplayNameNode = externalElement.getElementsByTagNameNS("*",
                                    "display-name");
                            String anchorDisplayName = null/* "" */;
                            if (anchorDisplayNameNode.getLength() > 0) {
                                Node node = anchorDisplayNameNode.item(0);
                                final Node firstChildNode = node.getFirstChild();
                                if (firstChildNode != null) {
                                    anchorDisplayName = firstChildNode.getNodeValue();
                                }
                            }

                            listEntryData.add(new ListEntryDataBean(ListEntryData.URI_LIST_ENTRY,
                                    anchorDisplayName, anchorURI));
                        }
                    }
                }
            }

            retValue = new URIListDataBean(displayName, name, listEntryData);

        } else {
            throw new IllegalArgumentException(
                    "only " + Node.ELEMENT_NODE + " is allowed as parameter. Passed " + listNode.getNodeType());
        }
    } else {
        throw new NullPointerException("listNode is null. Null is not allowed here.");
    }

    return retValue;
}