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:isl.FIMS.utils.Utils.java

public static void updateReferences(XMLEntity xmlE, String database, String xmlId, String xmlType,
        String dbPass, String dbUser) {

    /*String[] references = xmlE.queryString("//*[not (self::ref or self::ref_by) and @sps_type!='' and @sps_id!='' and @sps_id!='0']");
     * exist2.2 error with "no"// w w w  .  j av  a2s . c om
     */
    String[] references = xmlE.queryString(
            "//*[name(.)!= 'ref' and name(.)!='ref_by'  and @sps_type!='' and @sps_id!='' and @sps_id!='0']");

    String[] oldRerences = xmlE.queryString("//admin/refs/ref");
    xmlE.setAdminProperty("refs", "");
    Set<String> afterEditingList = new HashSet();
    Set<String> beforeEditingList = new HashSet();
    for (int i = 0; i < oldRerences.length; i++) {
        Element e = Utils.getElement(oldRerences[i]);
        String sps_type = e.getAttribute("sps_type");
        String sps_id = e.getAttribute("sps_id");
        //h katw pavla xrhsimopoieitai gia na mporesume sth sunexeia na spasume to string
        beforeEditingList.add(sps_type + "_" + sps_id);
    }

    for (String reference : references) {
        Element e = Utils.getElement(reference);
        String sps_type = e.getAttribute("sps_type");
        String sps_id = e.getAttribute("sps_id");
        if (!afterEditingList.contains(sps_type + "_" + sps_id)) {
            xmlE.xAppend("//admin/refs", "<ref sps_id='" + sps_id + "' sps_type='" + sps_type + "'/>");

            try {
                XMLEntity refxml = new XMLEntity(database,
                        ApplicationBasicServlet.systemDbCollection + sps_type, dbUser, dbPass, sps_type,
                        sps_type + sps_id);

                String[] existingRefs_by = refxml.queryString("//admin/refs_by");
                if (existingRefs_by.length == 0) {
                    refxml.setAdminProperty("refs_by", "");
                }
                String property = "";
                if (GetEntityCategory.getEntityCategory(xmlType).equals("primary")) {
                    property = "<ref_by sps_id='" + xmlId + "' sps_type='" + xmlType
                            + "' isUnpublished='true'/>";
                } else {
                    property = "<ref_by sps_id='" + xmlId + "' sps_type='" + xmlType + "'/>";
                }

                if (!refxml.exist(
                        "//admin/refs_by/ref_by[@sps_id='" + xmlId + "' and @sps_type='" + xmlType + "']")) {
                    refxml.xAppend("//admin/refs_by", property);
                }
                existingRefs_by = refxml.queryString("//admin/refs_by/ref_by");
            } catch (DBMSException ex) {
            }

        }
        afterEditingList.add(sps_type + "_" + sps_id);
    }
    Collection notUsedReferences = Utils.Subtract(afterEditingList, beforeEditingList);
    Iterator<String> it = notUsedReferences.iterator();
    //removes references that are not used anymore
    while (it.hasNext()) {
        String removeRef = it.next();
        String removeType = removeRef.split("_")[0];
        String removeId = removeRef.split("_")[1];
        XMLEntity removeXml = new XMLEntity(database, ApplicationBasicServlet.systemDbCollection + removeType,
                dbUser, dbPass, removeType, removeType + removeId);
        removeXml.xRemove("//admin/refs_by/ref_by[@sps_type='" + xmlType + "' and @sps_id='" + xmlId + "' ]");
    }
}

From source file:DomUtils.java

/**
 * Get a boolean attribute from the supplied element.
 * @param element The element.//from   w w  w . jav  a  2s .c  om
 * @param attribName The attribute name.
 * @return True if the attribute value is "true" (case insensitive), otherwise false.
 */
public static boolean getBooleanAttrib(Element element, String attribName) {

    String attribVal = element.getAttribute(attribName);

    return (attribVal != null ? attribVal.equalsIgnoreCase("true") : false);
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

public static String getContentBinding(File file) {
    String stix = "";
    try {/*from  w  w w.  ja  v  a 2 s.c o m*/
        stix = FileUtils.readFileToString(file);
    } catch (IOException e) {
        logger.error("Couldn't get content bindings from file. Ensure the file exists.");
    }

    Document stixDoc = convertStringToDocument(stix);

    Element documentElement = null;
    if (stixDoc != null) {
        documentElement = stixDoc.getDocumentElement();
    } else {
        logger.error("Couldn't convert string to a document when getting content bindings...");
    }

    String version = "";
    if (documentElement != null) {
        version = documentElement.getAttribute("version");
    } else {
        logger.error("Couldn't get document element when getting content bindings...");
    }

    switch (version) {
    case "1.1.1":
        return "urn:stix.mitre.org:xml:1.1.1";
    case "1.1":
        return "urn:stix.mitre.org:xml:1.1";
    case "1.0.1":
        return "urn:stix.mitre.org:xml:1.0.1";
    default:
        return "urn:stix.mitre.org:xml:1.0";
    }
}

From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java

/**
 * TransCellAccessToken????./*from w  w w. j  ava2s . c o  m*/
 * @param token 
 * @return TransCellAccessToken(?)
 * @throws AbstractOAuth2Token.TokenParseException ?
 * @throws AbstractOAuth2Token.TokenDsigException ???
 * @throws AbstractOAuth2Token.TokenRootCrtException CA?
 */
public static TransCellAccessToken parse(final String token) throws AbstractOAuth2Token.TokenParseException,
        AbstractOAuth2Token.TokenDsigException, AbstractOAuth2Token.TokenRootCrtException {
    try {
        byte[] samlBytes = DcCoreUtils.decodeBase64Url(token);
        ByteArrayInputStream bais = new ByteArrayInputStream(samlBytes);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = null;
        try {
            builder = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // ????????????
            throw new RuntimeException(e);
        }

        Document doc = builder.parse(bais);

        Element assertion = doc.getDocumentElement();
        Element issuer = (Element) (doc.getElementsByTagName("Issuer").item(0));
        Element subject = (Element) (assertion.getElementsByTagName("Subject").item(0));
        Element subjectNameID = (Element) (subject.getElementsByTagName("NameID").item(0));
        String id = assertion.getAttribute("ID");
        String issuedAtStr = assertion.getAttribute("IssueInstant");

        DateTime dt = new DateTime(issuedAtStr);

        NodeList audienceList = assertion.getElementsByTagName("Audience");
        Element aud1 = (Element) (audienceList.item(0));
        String target = aud1.getTextContent();
        String schema = null;
        if (audienceList.getLength() > 1) {
            Element aud2 = (Element) (audienceList.item(1));
            schema = aud2.getTextContent();
        }

        List<Role> roles = new ArrayList<Role>();
        NodeList attrList = assertion.getElementsByTagName("AttributeValue");
        for (int i = 0; i < attrList.getLength(); i++) {
            Element attv = (Element) (attrList.item(i));
            roles.add(new Role(new URL(attv.getTextContent())));
        }

        NodeList nl = assertion.getElementsByTagName("Signature");
        if (nl.getLength() == 0) {
            throw new TokenParseException("Cannot find Signature element");
        }
        Element signatureElement = (Element) nl.item(0);

        // ???????TokenDsigException??
        // Create a DOMValidateContext and specify a KeySelector
        // and document context.
        X509KeySelector x509KeySelector = new X509KeySelector(issuer.getTextContent());
        DOMValidateContext valContext = new DOMValidateContext(x509KeySelector, signatureElement);

        // Unmarshal the XMLSignature.
        XMLSignature signature;
        try {
            signature = xmlSignatureFactory.unmarshalXMLSignature(valContext);
        } catch (MarshalException e) {
            throw new TokenDsigException(e.getMessage(), e);
        }

        // CA??
        try {
            x509KeySelector.readRoot(x509RootCertificateFileNames);
        } catch (CertificateException e) {
            // CA????????500
            throw new TokenRootCrtException(e.getMessage(), e);
        }

        // Validate the XMLSignature x509.
        boolean coreValidity;
        try {
            coreValidity = signature.validate(valContext);
        } catch (XMLSignatureException e) {
            if (e.getCause().getClass() == new KeySelectorException().getClass()) {
                throw new TokenDsigException(e.getCause().getMessage(), e.getCause());
            }
            throw new TokenDsigException(e.getMessage(), e);
        }

        // http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation

        // Check core validation status.
        if (!coreValidity) {
            // ??
            boolean isDsigValid;
            try {
                isDsigValid = signature.getSignatureValue().validate(valContext);
            } catch (XMLSignatureException e) {
                throw new TokenDsigException(e.getMessage(), e);
            }
            if (!isDsigValid) {
                throw new TokenDsigException("Failed signature validation");
            }

            // 
            Iterator i = signature.getSignedInfo().getReferences().iterator();
            for (int j = 0; i.hasNext(); j++) {
                boolean refValid;
                try {
                    refValid = ((Reference) i.next()).validate(valContext);
                } catch (XMLSignatureException e) {
                    throw new TokenDsigException(e.getMessage(), e);
                }
                if (!refValid) {
                    throw new TokenDsigException("Failed to validate reference [" + j + "]");
                }
            }
            throw new TokenDsigException("Signature failed core validation. unkwnon reason.");
        }
        return new TransCellAccessToken(id, dt.getMillis(), issuer.getTextContent(),
                subjectNameID.getTextContent(), target, roles, schema);
    } catch (UnsupportedEncodingException e) {
        throw new TokenParseException(e.getMessage(), e);
    } catch (SAXException e) {
        throw new TokenParseException(e.getMessage(), e);
    } catch (IOException e) {
        throw new TokenParseException(e.getMessage(), e);
    }
}

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

/**
 * Parse all the IDs associated with the movie from the XML NFO file
 *
 * @param nlElements//from  w ww .ja v a2s . c  o m
 * @param dto
 * @param isTV
 */
private static void parseIds(NodeList nlElements, InfoDTO dto, boolean isTV) {
    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 movieId = eId.getTextContent();
            if (StringUtils.isNotBlank(movieId)) {
                String movieDb = eId.getAttribute("moviedb");
                if (StringUtils.isBlank(movieDb)) {
                    if ("-1".equals(movieId)) {
                        // skip all scans
                        dto.setSkipAllOnlineScans();
                    } else {
                        // choose default scanner id
                        if (isTV) {
                            movieDb = TheTVDbScanner.SCANNER_ID;
                        } else {
                            movieDb = ImdbScanner.SCANNER_ID;
                        }
                        dto.addId(movieDb, movieId);
                        LOG.debug("Found {} ID: {}", movieDb, movieId);
                    }
                } else {
                    dto.addId(movieDb, movieId);
                    LOG.debug("Found {} ID: {}", movieDb, movieId);
                }
            }

            // process the TMDB id
            movieId = eId.getAttribute("TMDB");
            if (StringUtils.isNotBlank(movieId)) {
                LOG.debug("Found TheMovieDb ID: {}", movieId);
                dto.addId(TheMovieDbScanner.SCANNER_ID, movieId);
            }
        }
    }
}

From source file:com.occamlab.te.parsers.ImageParser.java

private static void processBufferedImage(BufferedImage buffimage, String formatName, NodeList nodes)
        throws Exception {
    HashMap<Object, Object> bandMap = new HashMap<Object, Object>();

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("subimage")) {
                Element e = (Element) node;
                int x = Integer.parseInt(e.getAttribute("x"));
                int y = Integer.parseInt(e.getAttribute("y"));
                int w = Integer.parseInt(e.getAttribute("width"));
                int h = Integer.parseInt(e.getAttribute("height"));
                processBufferedImage(buffimage.getSubimage(x, y, w, h), formatName, e.getChildNodes());
            } else if (node.getLocalName().equals("checksum")) {
                CRC32 checksum = new CRC32();
                Raster raster = buffimage.getRaster();
                DataBufferByte buffer;
                if (node.getParentNode().getLocalName().equals("subimage")) {
                    WritableRaster outRaster = raster.createCompatibleWritableRaster();
                    buffimage.copyData(outRaster);
                    buffer = (DataBufferByte) outRaster.getDataBuffer();
                } else {
                    buffer = (DataBufferByte) raster.getDataBuffer();
                }//  w w w. j av  a 2s.  c om
                int numbanks = buffer.getNumBanks();
                for (int j = 0; j < numbanks; j++) {
                    checksum.update(buffer.getData(j));
                }
                Document doc = node.getOwnerDocument();
                node.appendChild(doc.createTextNode(Long.toString(checksum.getValue())));
            } else if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                if (sample.equals("all")) {
                    bandMap.put(band, null);
                } else {
                    HashMap<Object, Object> sampleMap = (HashMap<Object, Object>) bandMap.get(band);
                    if (sampleMap == null) {
                        if (!bandMap.containsKey(band)) {
                            sampleMap = new HashMap<Object, Object>();
                            bandMap.put(band, sampleMap);
                        }
                    }
                    sampleMap.put(Integer.decode(sample), new Integer(0));
                }
            } else if (node.getLocalName().equals("transparentNodata")) { // 2011-08-24
                                                                          // PwD
                String transparentNodata = checkTransparentNodata(buffimage, node);
                node.setTextContent(transparentNodata);
            }
        }
    }

    Iterator bandIt = bandMap.keySet().iterator();
    while (bandIt.hasNext()) {
        String band_str = (String) bandIt.next();
        int band_indexes[];
        if (buffimage.getType() == BufferedImage.TYPE_BYTE_BINARY
                || buffimage.getType() == BufferedImage.TYPE_BYTE_GRAY) {
            band_indexes = new int[1];
            band_indexes[0] = 0;
        } else {
            band_indexes = new int[band_str.length()];
            for (int i = 0; i < band_str.length(); i++) {
                if (band_str.charAt(i) == 'A')
                    band_indexes[i] = 3;
                if (band_str.charAt(i) == 'B')
                    band_indexes[i] = 2;
                if (band_str.charAt(i) == 'G')
                    band_indexes[i] = 1;
                if (band_str.charAt(i) == 'R')
                    band_indexes[i] = 0;
            }
        }

        Raster raster = buffimage.getRaster();
        java.util.HashMap sampleMap = (java.util.HashMap) bandMap.get(band_str);
        boolean addall = (sampleMap == null);
        if (sampleMap == null) {
            sampleMap = new java.util.HashMap();
            bandMap.put(band_str, sampleMap);
        }

        int minx = raster.getMinX();
        int maxx = minx + raster.getWidth();
        int miny = raster.getMinY();
        int maxy = miny + raster.getHeight();
        int bands[][] = new int[band_indexes.length][raster.getWidth()];

        for (int y = miny; y < maxy; y++) {
            for (int i = 0; i < band_indexes.length; i++) {
                raster.getSamples(minx, y, maxx, 1, band_indexes[i], bands[i]);
            }
            for (int x = minx; x < maxx; x++) {
                int sample = 0;
                for (int i = 0; i < band_indexes.length; i++) {
                    sample |= bands[i][x] << ((band_indexes.length - i - 1) * 8);
                }

                Integer sampleObj = new Integer(sample);

                boolean add = addall;
                if (!addall) {
                    add = sampleMap.containsKey(sampleObj);
                }
                if (add) {
                    Integer count = (Integer) sampleMap.get(sampleObj);
                    if (count == null) {
                        count = new Integer(0);
                    }
                    count = new Integer(count.intValue() + 1);
                    sampleMap.put(sampleObj, count);
                }
            }
        }
    }

    Node node = nodes.item(0);
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                HashMap sampleMap = (HashMap) bandMap.get(band);
                Document doc = node.getOwnerDocument();
                if (sample.equals("all")) {
                    Node parent = node.getParentNode();
                    Node prevSibling = node.getPreviousSibling();
                    Iterator sampleIt = sampleMap.keySet().iterator();
                    Element countnode = null;
                    int digits;
                    String prefix;
                    switch (buffimage.getType()) {
                    case BufferedImage.TYPE_BYTE_BINARY:
                        digits = 1;
                        prefix = "";
                        break;
                    case BufferedImage.TYPE_BYTE_GRAY:
                        digits = 2;
                        prefix = "0x";
                        break;
                    default:
                        prefix = "0x";
                        digits = band.length() * 2;
                    }
                    while (sampleIt.hasNext()) {
                        countnode = doc.createElementNS(node.getNamespaceURI(), "count");
                        Integer sampleInt = (Integer) sampleIt.next();
                        Integer count = (Integer) sampleMap.get(sampleInt);
                        if (band.length() > 0) {
                            countnode.setAttribute("bands", band);
                        }
                        countnode.setAttribute("sample", prefix + HexString(sampleInt.intValue(), digits));
                        Node textnode = doc.createTextNode(count.toString());
                        countnode.appendChild(textnode);
                        parent.insertBefore(countnode, node);
                        if (sampleIt.hasNext()) {
                            if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) {
                                parent.insertBefore(prevSibling.cloneNode(false), node);
                            }
                        }
                    }
                    parent.removeChild(node);
                    node = countnode;
                } else {
                    Integer count = (Integer) sampleMap.get(Integer.decode(sample));
                    if (count == null)
                        count = new Integer(0);
                    Node textnode = doc.createTextNode(count.toString());
                    node.appendChild(textnode);
                }
            }
        }
        node = node.getNextSibling();
    }
}

From source file:io.personium.common.auth.token.TransCellAccessToken.java

/**
 * TransCellAccessToken????./*from w  w w  .j ava2  s  . co  m*/
 * @param token 
 * @return TransCellAccessToken(?)
 * @throws AbstractOAuth2Token.TokenParseException ?
 * @throws AbstractOAuth2Token.TokenDsigException ???
 * @throws AbstractOAuth2Token.TokenRootCrtException CA?
 */
public static TransCellAccessToken parse(final String token) throws AbstractOAuth2Token.TokenParseException,
        AbstractOAuth2Token.TokenDsigException, AbstractOAuth2Token.TokenRootCrtException {
    try {
        byte[] samlBytes = PersoniumCoreUtils.decodeBase64Url(token);
        ByteArrayInputStream bais = new ByteArrayInputStream(samlBytes);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = null;
        try {
            builder = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // ????????????
            throw new RuntimeException(e);
        }

        Document doc = builder.parse(bais);

        Element assertion = doc.getDocumentElement();
        Element issuer = (Element) (doc.getElementsByTagName("Issuer").item(0));
        Element subject = (Element) (assertion.getElementsByTagName("Subject").item(0));
        Element subjectNameID = (Element) (subject.getElementsByTagName("NameID").item(0));
        String id = assertion.getAttribute("ID");
        String issuedAtStr = assertion.getAttribute("IssueInstant");

        DateTime dt = new DateTime(issuedAtStr);

        NodeList audienceList = assertion.getElementsByTagName("Audience");
        Element aud1 = (Element) (audienceList.item(0));
        String target = aud1.getTextContent();
        String schema = null;
        if (audienceList.getLength() > 1) {
            Element aud2 = (Element) (audienceList.item(1));
            schema = aud2.getTextContent();
        }

        List<Role> roles = new ArrayList<Role>();
        NodeList attrList = assertion.getElementsByTagName("AttributeValue");
        for (int i = 0; i < attrList.getLength(); i++) {
            Element attv = (Element) (attrList.item(i));
            roles.add(new Role(new URL(attv.getTextContent())));
        }

        NodeList nl = assertion.getElementsByTagName("Signature");
        if (nl.getLength() == 0) {
            throw new TokenParseException("Cannot find Signature element");
        }
        Element signatureElement = (Element) nl.item(0);

        // ???????TokenDsigException??
        // Create a DOMValidateContext and specify a KeySelector
        // and document context.
        X509KeySelector x509KeySelector = new X509KeySelector(issuer.getTextContent());
        DOMValidateContext valContext = new DOMValidateContext(x509KeySelector, signatureElement);

        // Unmarshal the XMLSignature.
        XMLSignature signature;
        try {
            signature = xmlSignatureFactory.unmarshalXMLSignature(valContext);
        } catch (MarshalException e) {
            throw new TokenDsigException(e.getMessage(), e);
        }

        // CA??
        try {
            x509KeySelector.readRoot(x509RootCertificateFileNames);
        } catch (CertificateException e) {
            // CA????????500
            throw new TokenRootCrtException(e.getMessage(), e);
        }

        // Validate the XMLSignature x509.
        boolean coreValidity;
        try {
            coreValidity = signature.validate(valContext);
        } catch (XMLSignatureException e) {
            if (e.getCause().getClass() == new KeySelectorException().getClass()) {
                throw new TokenDsigException(e.getCause().getMessage(), e.getCause());
            }
            throw new TokenDsigException(e.getMessage(), e);
        }

        // http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation

        // Check core validation status.
        if (!coreValidity) {
            // ??
            boolean isDsigValid;
            try {
                isDsigValid = signature.getSignatureValue().validate(valContext);
            } catch (XMLSignatureException e) {
                throw new TokenDsigException(e.getMessage(), e);
            }
            if (!isDsigValid) {
                throw new TokenDsigException("Failed signature validation");
            }

            // 
            Iterator i = signature.getSignedInfo().getReferences().iterator();
            for (int j = 0; i.hasNext(); j++) {
                boolean refValid;
                try {
                    refValid = ((Reference) i.next()).validate(valContext);
                } catch (XMLSignatureException e) {
                    throw new TokenDsigException(e.getMessage(), e);
                }
                if (!refValid) {
                    throw new TokenDsigException("Failed to validate reference [" + j + "]");
                }
            }
            throw new TokenDsigException("Signature failed core validation. unkwnon reason.");
        }
        return new TransCellAccessToken(id, dt.getMillis(), issuer.getTextContent(),
                subjectNameID.getTextContent(), target, roles, schema);
    } catch (UnsupportedEncodingException e) {
        throw new TokenParseException(e.getMessage(), e);
    } catch (SAXException e) {
        throw new TokenParseException(e.getMessage(), e);
    } catch (IOException e) {
        throw new TokenParseException(e.getMessage(), e);
    }
}

From source file:eu.semaine.util.XMLTool.java

/**
 * Create an XML document from the given XPath expression.
 * The given string is interpreted as a limited subset of XPath expressions and split into parts.
 * Each part except the last one is expected to follow precisely the following form:
 * <code>"/" ( prefix ":" ) ? localname ( "[" "@" attName "=" "'" attValue "'" "]" ) ?</code>
 * The last part must be either//from   w  w  w  .  j  av a2  s  .  co m
 * <code> "/" "text()"</code>
 * or
 * </code> "/" "@" attributeName </code>.
 * @param xpathExpression an xpath expression from which the given document can be created. must not be null.
 * @param value the value to insert at the location identified by the xpath expression. if this is null, the empty string is added.
 * @param namespaceContext the namespace context to use for resolving namespace prefixes.
 *  If this is null, the namespace context returned by {@link #getDefaultNamespaceContext()} will be used.
 * @param document if not null, the xpath expression + value pair will be added to the document. 
 * If null, a new document will be created from the xpathExpression and value pair.
 * @return a document containing the given information
 * @throws NullPointerException if xpathExpression is null.
 * @throws IllegalArgumentException if the xpath expression is not valid, or if the xpath expression is incompatible with the given document (e.g., different root node) 
 */
public static Document xpath2doc(String xpathExpression, String value, NamespaceContext namespaceContext,
        Document document) throws NullPointerException, IllegalArgumentException {
    if (xpathExpression == null) {
        throw new NullPointerException("null argument");
    }
    if (value == null) {
        value = "";
    }
    if (namespaceContext == null) {
        namespaceContext = getDefaultNamespaceContext();
    }
    String[][] parts = splitXPathIntoParts(xpathExpression);
    Element currentElt = null;

    for (int i = 0; i < parts.length - 1; i++) {
        String[] part = parts[i];
        assert part != null;
        assert part.length == 4;
        String prefix = part[0];
        String localName = part[1];
        String attName = part[2];
        String attValue = part[3];
        String namespaceURI = prefix != null ? namespaceContext.getNamespaceURI(prefix) : null;
        if (prefix != null && namespaceURI.equals("")) {
            throw new IllegalArgumentException("Unknown prefix: " + prefix);
        }
        // Now traverse to or create element defined by prefix, localName and namespaceURI
        if (currentElt == null) { // at top level
            if (document == null) { // create a new document
                try {
                    document = XMLTool.newDocument(localName, namespaceURI);
                } catch (DOMException de) {
                    throw new IllegalArgumentException("Cannot create document for localname '" + localName
                            + "' and namespaceURI '" + namespaceURI + "'", de);
                }
                currentElt = document.getDocumentElement();
                currentElt.setPrefix(prefix);
            } else {
                currentElt = document.getDocumentElement();
                if (!currentElt.getLocalName().equals(localName)) {
                    throw new IllegalArgumentException(
                            "Incompatible root node specification: expression requests '" + localName
                                    + "', but document already has '" + currentElt.getLocalName() + "'!");
                }
                String currentNamespaceURI = currentElt.getNamespaceURI();
                if (!(currentNamespaceURI == null && namespaceURI == null
                        || currentNamespaceURI != null && currentNamespaceURI.equals(namespaceURI))) {
                    throw new IllegalArgumentException(
                            "Incompatible root namespace specification: expression requests '" + namespaceURI
                                    + "', but document already has '" + currentNamespaceURI + "'!");
                }
            }
        } else { // somewhere in the tree
            // First check if the requested child already exists
            List<Element> sameNameChildren = XMLTool.getChildrenByLocalNameNS(currentElt, localName,
                    namespaceURI);
            boolean found = false;
            if (attName == null) {
                if (sameNameChildren.size() > 0) {
                    currentElt = sameNameChildren.get(0);
                    found = true;
                }
            } else {
                for (Element c : sameNameChildren) {
                    if (c.hasAttribute(attName)) {
                        if (attValue == null || attValue.equals(c.getAttribute(attName))) {
                            currentElt = c;
                            found = true;
                            break;
                        }
                    }
                }
            }
            if (!found) { // need to create it
                currentElt = XMLTool.appendChildElement(currentElt, localName, namespaceURI);
                if (prefix != null)
                    currentElt.setPrefix(prefix);
                if (attName != null) {
                    currentElt.setAttribute(attName, attValue != null ? attValue : "");
                }
            }
        }

    }
    if (currentElt == null) {
        throw new IllegalArgumentException(
                "No elements or no final part created from XPath expression '" + xpathExpression + "'");
    }
    String[] lastPart = parts[parts.length - 1];
    assert lastPart.length <= 1;
    if (lastPart.length == 0) { // text content of the given node
        currentElt.setTextContent(value);
    } else {
        String attName = lastPart[0];
        currentElt.setAttribute(attName, value);
    }
    return document;
}

From source file:com.rapidminer.gui.OperatorDocLoader.java

/**
 * //from ww  w  . ja v  a 2  s . c o  m
 * @param operatorWikiName
 * @param opDesc
 * @return The parsed <tt>Document</tt> (not finally parsed) of the selected operator.
 * @throws MalformedURLException
 * @throws ParserConfigurationException
 */
private static Document parseDocumentForOperator(String operatorWikiName, OperatorDescription opDesc)
        throws MalformedURLException, ParserConfigurationException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setIgnoringComments(true);
    builderFactory.setIgnoringElementContentWhitespace(true);
    DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
    documentBuilder.setEntityResolver(new XHTMLEntityResolver());

    Document document = null;
    URL url = new URL(WIKI_PREFIX_FOR_OPERATORS + operatorWikiName);
    if (url != null) {
        try {
            document = documentBuilder.parse(WebServiceTools.openStreamFromURL(url));
        } catch (IOException e) {
            logger.warning("Could not open " + url.toExternalForm() + ": " + e.getMessage());
        } catch (SAXException e) {
            logger.warning("Could not parse operator documentation: " + e.getMessage());
        }

        int i = 0;

        if (document != null) {
            Element contentElement = document.getElementById("content");

            // removing content element from document
            if (contentElement != null) {
                contentElement.getParentNode().removeChild(contentElement);
            }

            // removing everything from body
            NodeList bodies = document.getElementsByTagName("body");
            for (int k = 0; k < bodies.getLength(); k++) {
                Node body = bodies.item(k);
                while (body.hasChildNodes()) {
                    body.removeChild(body.getFirstChild());
                }

                // read content element to body
                if (contentElement != null && k == 0) {
                    body.appendChild(contentElement);
                }
            }

            // removing everything from head
            NodeList heads = document.getElementsByTagName("head");
            for (int k = 0; k < heads.getLength(); k++) {
                Node head = heads.item(k);
                while (head.hasChildNodes()) {
                    head.removeChild(head.getFirstChild());
                }
            }
            // removing...<head/> from document
            if (heads != null) {
                while (i < heads.getLength()) {
                    Node head = heads.item(i);
                    head.getParentNode().removeChild(head);
                }
            }

            // removing jump-to-nav element from document
            Element jumpToNavElement = document.getElementById("jump-to-nav");
            if (jumpToNavElement != null) {
                jumpToNavElement.getParentNode().removeChild(jumpToNavElement);
            }

            // removing mw-normal-catlinks element from document
            Element mwNormalCatlinksElement = document.getElementById("mw-normal-catlinks");
            if (mwNormalCatlinksElement != null) {
                mwNormalCatlinksElement.getParentNode().removeChild(mwNormalCatlinksElement);
            }

            // removing complete link navigation
            Element tocElement = document.getElementById("toc");
            if (tocElement != null) {
                tocElement.getParentNode().removeChild(tocElement);
            }

            // removing everything from class printfooter
            NodeList nodeListDiv = document.getElementsByTagName("div");
            for (int k = 0; k < nodeListDiv.getLength(); k++) {
                Element div = (Element) nodeListDiv.item(k);
                if (div.getAttribute("class").equals("printfooter")) {
                    div.getParentNode().removeChild(div);
                }
            }

            // removing everything from class editsection
            NodeList spanList = document.getElementsByTagName("span");
            for (int k = 0; k < spanList.getLength(); k++) {
                Element span = (Element) spanList.item(k);
                if (span.getAttribute("class").equals("editsection")) {
                    span.getParentNode().removeChild(span);
                }
            }

            // Synopsis Header
            boolean doIt = true;
            NodeList pList = document.getElementsByTagName("p");
            for (int k = 0; k < pList.getLength(); k++) {

                if (doIt) {
                    Node p = pList.item(k);
                    NodeList pChildList = p.getChildNodes();

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

                        Node pChild = pChildList.item(j);
                        if (pChild.getNodeType() == Node.TEXT_NODE && pChild.getNodeValue() != null
                                && StringUtils.isNotBlank(pChild.getNodeValue())
                                && StringUtils.isNotEmpty(pChild.getNodeValue())) {

                            String pChildString = pChild.getNodeValue();
                            Element newPWithoutSpaces = document.createElement("p");
                            newPWithoutSpaces.setTextContent(pChildString);

                            Node synopsis = document.createTextNode("Synopsis");

                            Element span = document.createElement("span");
                            span.setAttribute("class", "mw-headline");
                            span.setAttribute("id", "Synopsis");
                            span.appendChild(synopsis);

                            Element h2 = document.createElement("h2");
                            h2.appendChild(span);

                            Element div = document.createElement("div");
                            div.setAttribute("id", "synopsis");
                            div.appendChild(h2);
                            div.appendChild(newPWithoutSpaces);

                            Node pChildParentParent = pChild.getParentNode().getParentNode();
                            Node pChildParent = pChild.getParentNode();

                            pChildParentParent.replaceChild(div, pChildParent);
                            doIt = false;
                            break;
                        }
                    }
                } else {
                    break;
                }
            }

            // removing all <br...>-Tags
            NodeList brList = document.getElementsByTagName("br");

            while (i < brList.getLength()) {
                Node br = brList.item(i);
                Node parentBrNode = br.getParentNode();
                parentBrNode.removeChild(br);
            }

            // removing everything from script
            NodeList scriptList = document.getElementsByTagName("script");
            while (i < scriptList.getLength()) {
                Node scriptNode = scriptList.item(i);
                Node parentNode = scriptNode.getParentNode();
                parentNode.removeChild(scriptNode);
            }

            // removing all empty <p...>-Tags
            NodeList pList2 = document.getElementsByTagName("p");
            int ccc = 0;
            while (ccc < pList2.getLength()) {
                Node p = pList2.item(ccc);
                NodeList pChilds = p.getChildNodes();

                int kk = 0;

                while (kk < pChilds.getLength()) {
                    Node pChild = pChilds.item(kk);
                    if (pChild.getNodeType() == Node.TEXT_NODE) {
                        String pNodeValue = pChild.getNodeValue();
                        if (pNodeValue == null || StringUtils.isBlank(pNodeValue)
                                || StringUtils.isEmpty(pNodeValue)) {
                            kk++;
                        } else {
                            ccc++;
                            break;
                        }
                    } else {
                        ccc++;
                        break;
                    }
                    if (kk == pChilds.getLength()) {
                        Node parentBrNode = p.getParentNode();
                        parentBrNode.removeChild(p);
                    }
                }
            }

            // removing firstHeading element from document
            Element firstHeadingElement = document.getElementById("firstHeading");
            if (firstHeadingElement != null) {
                CURRENT_OPERATOR_NAME_READ_FROM_RAPIDWIKI = firstHeadingElement.getFirstChild().getNodeValue()
                        .replaceFirst(".*:", "");
                firstHeadingElement.getParentNode().removeChild(firstHeadingElement);
            }

            // setting operator plugin name
            if (opDesc != null && opDesc.getProvider() != null) {
                CURRENT_OPERATOR_PLUGIN_NAME = opDesc.getProvider().getName();
            }

            // removing sitesub element from document
            Element siteSubElement = document.getElementById("siteSub");
            if (siteSubElement != null) {
                siteSubElement.getParentNode().removeChild(siteSubElement);
            }

            // removing contentSub element from document
            Element contentSubElement = document.getElementById("contentSub");
            if (contentSubElement != null) {
                contentSubElement.getParentNode().removeChild(contentSubElement);
            }

            // removing catlinks element from document
            Element catlinksElement = document.getElementById("catlinks");
            if (catlinksElement != null) {
                catlinksElement.getParentNode().removeChild(catlinksElement);
            }

            // removing <a...> element from document, if they are empty
            NodeList aList = document.getElementsByTagName("a");
            if (aList != null) {
                int k = 0;
                while (k < aList.getLength()) {
                    Node a = aList.item(k);
                    Element aElement = (Element) a;
                    if (aElement.getAttribute("class").equals("internal")) {
                        a.getParentNode().removeChild(a);
                    } else {
                        Node aChild = a.getFirstChild();
                        if (aChild != null
                                && (aChild.getNodeValue() != null && aChild.getNodeType() == Node.TEXT_NODE
                                        && StringUtils.isNotBlank(aChild.getNodeValue())
                                        && StringUtils.isNotEmpty(aChild.getNodeValue())
                                        || aChild.getNodeName() != null)) {
                            Element aChildElement = null;
                            if (aChild.getNodeName().startsWith("img")) {
                                aChildElement = (Element) aChild;

                                Element imgElement = document.createElement("img");
                                imgElement.setAttribute("alt", aChildElement.getAttribute("alt"));
                                imgElement.setAttribute("class", aChildElement.getAttribute("class"));
                                imgElement.setAttribute("height", aChildElement.getAttribute("height"));
                                imgElement.setAttribute("src",
                                        WIKI_PREFIX_FOR_IMAGES + aChildElement.getAttribute("src"));
                                imgElement.setAttribute("width", aChildElement.getAttribute("width"));
                                imgElement.setAttribute("border", "1");

                                Node aParent = a.getParentNode();
                                aParent.replaceChild(imgElement, a);
                            } else {
                                k++;
                            }
                        } else {
                            a.getParentNode().removeChild(a);
                        }
                    }
                }
            }

        }
    }
    return document;
}

From source file:org.brekka.stillingar.spring.config.ConfigurationServiceBeanDefinitionParser.java

protected static String getName(Element element) {
    // Optional application name, will use the id if not specified.
    String name = element.getAttribute("name");
    if (name == null || name.isEmpty()) {
        name = element.getAttribute("id");
    }//  w  ww  . j  a  v a2  s.  c  om
    return name;
}