nu.xom.Element Java Examples

The following examples show how to use nu.xom.Element. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReplaceEmbeddedStylesheetExtension.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void addTo(ConcordionExtender concordionExtender) {
  if (styleToReplace != null) {
    concordionExtender.withLinkedCSS(styleToReplace, new Resource("/concordion.css"));
  }
  concordionExtender.withDocumentParsingListener(document -> {
    Element html = document.getRootElement();
    Element head = html.getFirstChildElement("head");
    if (head != null) {
      Elements styles = head.getChildElements("style");
      for (int i = 0; i < styles.size(); i++) {
        Element style = styles.get(i);
        if (styleToRemove.equals(style.getValue())) {
          head.removeChild(style);
        }
      }
    }
  });
}
 
Example #2
Source File: XOMTreeBuilder.java    From caja with Apache License 2.0 6 votes vote down vote up
@Override
protected void addAttributesToElement(Element element, HtmlAttributes attributes)
        throws SAXException {
    try {
        for (int i = 0; i < attributes.getLength(); i++) {
            String localName = attributes.getLocalName(i);
            String uri = attributes.getURI(i);
            if (element.getAttribute(localName, uri) == null) {
                element.addAttribute(nodeFactory.makeAttribute(localName,
                        uri, attributes.getValue(i),
                        attributes.getType(i) == "ID" ? Attribute.Type.ID
                                : Attribute.Type.CDATA));
            }
        }
    } catch (XMLException e) {
        fatal(e);
    }
}
 
Example #3
Source File: XOMTreeBuilder.java    From caja with Apache License 2.0 6 votes vote down vote up
@Override
protected Element createElement(String ns, String name, HtmlAttributes attributes)
        throws SAXException {
    try {
        Element rv = nodeFactory.makeElement(name,
                ns);
        for (int i = 0; i < attributes.getLength(); i++) {
            rv.addAttribute(nodeFactory.makeAttribute(
                    attributes.getLocalName(i), attributes.getURI(i),
                    attributes.getValue(i),
                    attributes.getType(i) == "ID" ? Attribute.Type.ID
                            : Attribute.Type.CDATA));
        }
        return rv;
    } catch (XMLException e) {
        fatal(e);
        throw new RuntimeException("Unreachable");
    }
}
 
Example #4
Source File: XOMTreeBuilder.java    From caja with Apache License 2.0 6 votes vote down vote up
@Override
protected Element createHtmlElementSetAsRoot(HtmlAttributes attributes)
        throws SAXException {
    try {
        Element rv = nodeFactory.makeElement("html",
                "http://www.w3.org/1999/xhtml");
        for (int i = 0; i < attributes.getLength(); i++) {
            rv.addAttribute(nodeFactory.makeAttribute(
                    attributes.getLocalName(i), attributes.getURI(i),
                    attributes.getValue(i),
                    attributes.getType(i) == "ID" ? Attribute.Type.ID
                            : Attribute.Type.CDATA));
        }
        document.setRootElement(rv);
        return rv;
    } catch (XMLException e) {
        fatal(e);
        throw new RuntimeException("Unreachable");
    }
}
 
Example #5
Source File: XOMTreeBuilder.java    From caja with Apache License 2.0 6 votes vote down vote up
@Override
protected Element shallowClone(Element element) throws SAXException {
    try {
        Element rv = nodeFactory.makeElement(element.getLocalName(),
                element.getNamespaceURI());
        for (int i = 0; i < element.getAttributeCount(); i++) {
            Attribute attribute = element.getAttribute(i);
            rv.addAttribute(nodeFactory.makeAttribute(
                    attribute.getLocalName(), attribute.getNamespaceURI(),
                    attribute.getValue(), attribute.getType()));
        }
        return rv;
    } catch (XMLException e) {
        fatal(e);
        throw new RuntimeException("Unreachable");
    }
}
 
Example #6
Source File: XOMTreeBuilder.java    From caja with Apache License 2.0 6 votes vote down vote up
/**
 * @see nu.validator.htmlparser.impl.TreeBuilder#createElement(String,
 *      java.lang.String, org.xml.sax.Attributes, java.lang.Object)
 */
@Override
protected Element createElement(String ns, String name,
        HtmlAttributes attributes, Element form) throws SAXException {
    try {
        Element rv = nodeFactory.makeElement(name,
                ns, form);
        for (int i = 0; i < attributes.getLength(); i++) {
            rv.addAttribute(nodeFactory.makeAttribute(
                    attributes.getLocalName(i), attributes.getURI(i),
                    attributes.getValue(i),
                    attributes.getType(i) == "ID" ? Attribute.Type.ID
                            : Attribute.Type.CDATA));
        }
        return rv;
    } catch (XMLException e) {
        fatal(e);
        throw new RuntimeException("Unreachable");
    }
}
 
Example #7
Source File: XmlPersistenceRead.java    From rest-client with Apache License 2.0 6 votes vote down vote up
private List<HttpCookie> getCookiesFromCookiesNode(final Element node) 
        throws XMLException {
    List<HttpCookie> out = new ArrayList<>();
    
    for (int i = 0; i < node.getChildElements().size(); i++) {
        Element e = node.getChildElements().get(i);
        if(!"cookie".equals(e.getQualifiedName())) {
            throw new XMLException("<cookies> element should contain only <cookie> elements");
        }
        
        HttpCookie cookie = new HttpCookie(e.getAttributeValue("name"),
                e.getAttributeValue("value"));
        final String cookieVerStr = e.getAttributeValue("version");
        if(StringUtil.isNotEmpty(cookieVerStr)) {
            cookie.setVersion(Integer.parseInt(cookieVerStr));
        }
        else {
            cookie.setVersion(CookieVersion.DEFAULT_VERSION.getIntValue());
        }
        out.add(cookie);
    }
    
    return out;
}
 
Example #8
Source File: XmlAuthUtil.java    From rest-client with Apache License 2.0 6 votes vote down vote up
static Element getAuthElement(Auth auth) {
    Element eAuth = new Element("auth");
    
    if(auth instanceof BasicAuth) {
        eAuth.appendChild(getBasicAuthElement((BasicAuth)auth));
    }
    else if(auth instanceof DigestAuth) {
        eAuth.appendChild(getDigestAuthElement((DigestAuth)auth));
    }
    else if(auth instanceof NtlmAuth) {
        eAuth.appendChild(getNtlmAuthElement((NtlmAuth)auth));
    }
    else if(auth instanceof OAuth2BearerAuth) {
        eAuth.appendChild(getOAuth2BearerElement((OAuth2BearerAuth)auth));
    }
    
    return eAuth;
}
 
Example #9
Source File: XmlAuthUtil.java    From rest-client with Apache License 2.0 6 votes vote down vote up
static Element getNtlmAuthElement(NtlmAuth auth) {
    Element e = new Element("ntlm");
    
    if(StringUtil.isNotEmpty(auth.getDomain())) {
        Element eDomain = new Element("domain");
        eDomain.appendChild(auth.getDomain());
        e.appendChild(eDomain);
    }
    
    if(StringUtil.isNotEmpty(auth.getWorkstation())) {
        Element eWorkstation = new Element("workstation");
        eWorkstation.appendChild(auth.getWorkstation());
        e.appendChild(eWorkstation);
    }
    
    populateUsernamePasswordElement(e, auth);
    
    return e;
}
 
Example #10
Source File: XmlAuthUtil.java    From rest-client with Apache License 2.0 6 votes vote down vote up
static void populateBasicDigestElement(Element eParent, BasicDigestAuth auth) {
    if(StringUtil.isNotEmpty(auth.getHost())) {
        Element eHost = new Element("host");
        eHost.appendChild(auth.getHost());
        eParent.appendChild(eHost);
    }
    
    if(StringUtil.isNotEmpty(auth.getRealm())) {
        Element eRealm = new Element("realm");
        eRealm.appendChild(auth.getRealm());
        eParent.appendChild(eRealm);
    }
    
    if(auth.isPreemptive()) {
        Element ePreemptive = new Element("preemptive");
        eParent.appendChild(ePreemptive);
    }
    
    populateUsernamePasswordElement(eParent, auth);
}
 
Example #11
Source File: XmlAuthUtil.java    From rest-client with Apache License 2.0 6 votes vote down vote up
static Auth getAuth(Element eAuth) {
    Elements eChildren = eAuth.getChildElements();
    for(int i=0; i<eChildren.size(); i++) {
        Element e = eChildren.get(i);
        final String name = e.getLocalName();
        if(name.equals("basic")) {
            return getBasicAuth(e);
        }
        else if(name.equals("digest")) {
            return getDigestAuth(e);
        }
        else if(name.equals("ntlm")) {
            return getNtlmAuth(e);
        }
        else if(name.equals("oauth2-bearer")) {
            return getOAuth2BearerAuth(e);
        }
        else {
            throw new XMLException("Invalid auth element encountered: " + name);
        }
    }
    return null;
}
 
Example #12
Source File: XmlAuthUtil.java    From rest-client with Apache License 2.0 6 votes vote down vote up
static void populateBasicDigestAuth(BasicDigestAuthBaseBean bean, Element eAuth) {
    Elements eChildren = eAuth.getChildElements();
    for(int i=0; i<eChildren.size(); i++) {
        Element e = eChildren.get(i);
        final String name = e.getLocalName();
        if(name.equals("host")) {
            bean.setHost(e.getValue());
        }
        else if(name.equals("realm")) {
            bean.setRealm(e.getValue());
        }
        else if(name.equals("username")) {
            bean.setUsername(e.getValue());
        }
        else if(name.equals("password")) {
            bean.setPassword(getPassword(e));
        }
        else if(name.equals("preemptive")) {
            bean.setPreemptive(true);
        }
        else {
            throw new XMLException("Unknown element in basic/digest auth: " + name);
        }
    }
}
 
Example #13
Source File: XmlAuthUtil.java    From rest-client with Apache License 2.0 6 votes vote down vote up
static NtlmAuth getNtlmAuth(Element eNtlmAuth) {
    NtlmAuthBean out = new NtlmAuthBean();
    
    Elements eChildren = eNtlmAuth.getChildElements();
    for(int i=0; i<eChildren.size(); i++) {
        Element e = eChildren.get(i);
        final String name = e.getLocalName();
        if(name.equals("domain")) {
            out.setDomain(e.getValue());
        }
        else if(name.equals("workstation")) {
            out.setWorkstation(e.getValue());
        }
        else if(name.equals("username")) {
            out.setUsername(e.getValue());
        }
        else if(name.equals("password")) {
            out.setPassword(getPassword(e));
        }
        else {
            throw new XMLException("Unknown element in ntlm auth: " + name);
        }
    }
    
    return out;
}
 
Example #14
Source File: SettingsManager.java    From ciscorouter with MIT License 6 votes vote down vote up
/**
 * Constructs the class. Requires settings.xml to be present to run
 */
public SettingsManager() {
    String currentDir = System.getProperty("user.dir");
    String settingDir = currentDir + "/settings/";
    File f = new File(settingDir + "settings.xml");
    if (f.exists() && !f.isDirectory()) {
        try {
            Builder parser = new Builder();
            Document doc   = parser.build(f);
            Element root   = doc.getRootElement();

            Element eUsername = root.getFirstChildElement("Username");
            username = eUsername.getValue();

            Element ePassword = root.getFirstChildElement("Password");
            password = ePassword.getValue();

            requiresAuth = true;
        } catch (ParsingException|IOException e) {
            e.printStackTrace();
        }
    }
    else {
        requiresAuth = false;
    }
}
 
Example #15
Source File: XomCreateXML.java    From maven-framework-project with MIT License 6 votes vote down vote up
/**
 * 多個節點
 */
@Test
public void test02() {
	BigInteger low = BigInteger.ONE;
	BigInteger high = BigInteger.ONE;
	Element root = new Element("Fibonacci_Numbers");
	for (int i = 1; i <= 10; i++) {
		Element fibonacci = new Element("fibonacci");
		fibonacci.appendChild(low.toString());
		root.appendChild(fibonacci);

		BigInteger temp = high;
		high = high.add(low);
		low = temp;
	}
	Document doc = new Document(root);
	System.out.println(doc.toXML()); 
}
 
Example #16
Source File: XomCreateXML.java    From maven-framework-project with MIT License 6 votes vote down vote up
/**
 * Create Document Type
 */
@Test
public void test06() throws Exception{
	Element greeting = new Element("greeting");
	Document doc = new Document(greeting);
	String temp = "<!DOCTYPE element [\n" 
	  + "<!ELEMENT greeting (#PCDATA)>\n"
	  + "]>\n"
	  + "<root />";
	Builder builder = new Builder();
	Document tempDoc = builder.build(temp, null);
	DocType doctype = tempDoc.getDocType();
	doctype.detach();
	doc.setDocType(doctype);
	
	System.out.println(doc.toXML()); 
	
}
 
Example #17
Source File: XmlAuthUtil.java    From rest-client with Apache License 2.0 6 votes vote down vote up
static OAuth2BearerAuth getOAuth2BearerAuth(Element eAuth) {
    OAuth2BearerAuthBean out = new OAuth2BearerAuthBean();
    
    Elements eChildren = eAuth.getChildElements();
    for(int i=0; i<eChildren.size(); i++) {
        Element e = eChildren.get(i);
        final String name = e.getLocalName();
        if(name.equals("token")) {
            out.setOAuth2BearerToken(e.getValue());
        }
        else {
            throw new XMLException("Unknown element in oauth2-bearer auth: " + name);
        }
    }
    
    return out;
}
 
Example #18
Source File: XmlPersistenceRead.java    From rest-client with Apache License 2.0 6 votes vote down vote up
private Map<String, String> getHeadersFromHeaderNode(final Element node)
        throws XMLException {
    Map<String, String> m = new LinkedHashMap<>();

    for (int i = 0; i < node.getChildElements().size(); i++) {
        Element headerElement = node.getChildElements().get(i);
        if (!"header".equals(headerElement.getQualifiedName())) {
            throw new XMLException("<headers> element should contain only <header> elements");
        }

        m.put(headerElement.getAttributeValue("key"),
                headerElement.getAttributeValue("value"));

    }
    return m;
}
 
Example #19
Source File: XmlAuthUtil.java    From rest-client with Apache License 2.0 5 votes vote down vote up
static void populateUsernamePasswordElement(Element eParent, UsernamePasswordAuth auth) {
    if(StringUtil.isNotEmpty(auth.getUsername())) {
        Element eUsername = new Element("username");
        eUsername.appendChild(auth.getUsername());
        eParent.appendChild(eUsername);
    }
    
    if(auth.getPassword() != null && auth.getPassword().length > 0) {
        Element ePassword = new Element("password");
        ePassword.appendChild(Util.base64encode(new String(auth.getPassword())));
        eParent.appendChild(ePassword);
    }
}
 
Example #20
Source File: XmlAuthUtil.java    From rest-client with Apache License 2.0 5 votes vote down vote up
static Element getOAuth2BearerElement(OAuth2BearerAuth auth) {
    Element e = new Element("oauth2-bearer");
    
    if(StringUtil.isNotEmpty(auth.getOAuth2BearerToken())) {
        Element eToken = new Element("token");
        eToken.appendChild(auth.getOAuth2BearerToken());
        e.appendChild(eToken);
    }
    
    return e;
}
 
Example #21
Source File: PermissionUtils.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static byte[] createPermissionsXml(Permission... permissions) {
    final Element permissionsElement = new Element("permissions");
    permissionsElement.setNamespaceURI("http://xmlns.jcp.org/xml/ns/javaee");
    permissionsElement.addAttribute(new Attribute("version", "7"));
    for (Permission permission : permissions) {
        final Element permissionElement = new Element("permission");

        final Element classNameElement = new Element("class-name");
        final Element nameElement = new Element("name");
        classNameElement.appendChild(permission.getClass().getName());
        nameElement.appendChild(permission.getName());
        permissionElement.appendChild(classNameElement);
        permissionElement.appendChild(nameElement);

        final String actions = permission.getActions();
        if (actions != null && ! actions.isEmpty()) {
            final Element actionsElement = new Element("actions");
            actionsElement.appendChild(actions);
            permissionElement.appendChild(actionsElement);
        }
        permissionsElement.appendChild(permissionElement);
    }
    Document document = new Document(permissionsElement);
    try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
        final NiceSerializer serializer = new NiceSerializer(stream);
        serializer.setIndent(4);
        serializer.setLineSeparator("\n");
        serializer.write(document);
        serializer.flush();
        return stream.toByteArray();
    } catch (IOException e) {
        throw new IllegalStateException("Generating permissions.xml failed", e);
    }
}
 
Example #22
Source File: XMLCollectionUtil.java    From rest-client with Apache License 2.0 5 votes vote down vote up
public static void writeRequestCollectionXML(final List<Request> requests, final File f)
        throws IOException, XMLException {
    XmlPersistenceWrite xUtl = new XmlPersistenceWrite();
    
    Element eRoot = new Element("request-collection");
    eRoot.addAttribute(new Attribute("version", Versions.CURRENT));
    for(Request req: requests) {
        Element e = xUtl.getRequestElement(req);
        eRoot.appendChild(e);
    }
    Document doc = new Document(eRoot);
    xUtl.writeXML(doc, f);
}
 
Example #23
Source File: XmlPersistenceRead.java    From rest-client with Apache License 2.0 5 votes vote down vote up
protected Request xml2Request(final Document doc)
        throws MalformedURLException, XMLException {
    // get the rootNode
    Element rootNode = doc.getRootElement();

    if (!"rest-client".equals(rootNode.getQualifiedName())) {
        throw new XMLException("Root node is not <rest-client>");
    }

    // checking correct rest version
    final String rcVersion = rootNode.getAttributeValue("version");
    try {
        Versions.versionValidCheck(rcVersion);
    }
    catch(Versions.VersionValidationException ex) {
        throw new XMLException(ex);
    }
    
    readVersion = rcVersion;

    // if more than two request element is present then throw the exception 
    if (rootNode.getChildElements().size() != 1) {
        throw new XMLException("There can be only one child node for root node: <request>");
    }
    // minimum one request element is present in xml 
    if (rootNode.getFirstChildElement("request") == null) {
        throw new XMLException("The child node of <rest-client> should be <request>");
    }
    Element requestNode = rootNode.getFirstChildElement("request");
    
    return getRequestBean(requestNode);
}
 
Example #24
Source File: XMLCollectionUtil.java    From rest-client with Apache License 2.0 5 votes vote down vote up
public static List<Request> getRequestCollectionFromXMLFile(final File f)
        throws IOException, XMLException {
    XmlPersistenceRead xUtlRead = new XmlPersistenceRead();
    
    List<Request> out = new ArrayList<>();
    Document doc = xUtlRead.getDocumentFromFile(f);
    Element eRoot = doc.getRootElement();
    if(!"request-collection".equals(eRoot.getLocalName())) {
        throw new XMLException("Expecting root element <request-collection>, but found: "
                + eRoot.getLocalName());
    }
    final String version = eRoot.getAttributeValue("version");
    try {
        Versions.versionValidCheck(version);
    }
    catch(Versions.VersionValidationException ex) {
        throw new XMLException(ex);
    }
    xUtlRead.setReadVersion(version);
    
    Elements eRequests = doc.getRootElement().getChildElements();
    for(int i=0; i<eRequests.size(); i++) {
        Element eRequest = eRequests.get(i);
        Request req = xUtlRead.getRequestBean(eRequest);
        out.add(req);
    }
    return out;
}
 
Example #25
Source File: XmlBodyRead.java    From rest-client with Apache License 2.0 5 votes vote down vote up
private ReqEntityMultipartBean getMultipart(Element e) {
    final String subTypeStr = e.getAttributeValue("subtype");
    final MultipartSubtype subType = subTypeStr!=null?
            MultipartSubtype.valueOf(subTypeStr): MultipartSubtype.FORM_DATA;
    final String mode = e.getAttributeValue("mode");
    MultipartMode format = StringUtil.isNotEmpty(mode)?
            MultipartMode.valueOf(mode): null;
    List<ReqEntityPart> parts = getMultipartParts(e);
    return new ReqEntityMultipartBean(parts, format, subType);
}
 
Example #26
Source File: XmlBodyRead.java    From rest-client with Apache License 2.0 5 votes vote down vote up
private List<ReqEntityPart> getMultipartParts(Element e) {
    List<ReqEntityPart> parts = new ArrayList<>();
    Elements children = e.getChildElements();
    for(int i=0; i<children.size(); i++) {
        ReqEntityPart part = getMultipartPart(children.get(i));
        parts.add(part);
    }
    return parts;
}
 
Example #27
Source File: XmlBodyRead.java    From rest-client with Apache License 2.0 5 votes vote down vote up
private String getPartValue(Element e) {
    if(readVersion.isLessThan(VERSION_SINCE_PART_CONTENT)) {
        return e.getValue();
    }
    else {
        Element eContent = e.getChildElements("content").get(0);
        return eContent.getValue();
    }
}
 
Example #28
Source File: XmlBodyRead.java    From rest-client with Apache License 2.0 5 votes vote down vote up
private ReqEntityPart getMultipartPart(Element e) {
    final String name = e.getLocalName();
    
    final String partName = e.getAttributeValue("name");
    final ContentType ct = getContentType(e);
    
    Elements eFields = null;
    if(e.getChildElements("fields").size() > 0) {
        eFields = e.getChildElements("fields").get(0).getChildElements("field");
    }
    
    if("string".equals(name)) {
        String partBody = getPartValue(e);
        ReqEntityStringPartBean out = new ReqEntityStringPartBean(partName, ct, partBody);
        addFields(eFields, out);
        return out;
    }
    else if("file".equals(name)) {
        File file = new File(getPartValue(e));
        String fileName = e.getAttributeValue("filename");
        
        // filename: backward-compatibility:
        fileName = StringUtil.isEmpty(fileName)? file.getName(): fileName;
        
        return new ReqEntityFilePartBean(partName, fileName, ct, file);
    }
    else {
        throw new XMLException("Unsupported element encountered inside <multipart>: " + name);
    }
}
 
Example #29
Source File: XmlBodyRead.java    From rest-client with Apache License 2.0 5 votes vote down vote up
private void addFields(Elements eFields, ReqEntityBasePart part) {
    if(eFields == null) {
        return;
    }
    
    for(int i=0; i<eFields.size(); i++) {
        Element eField = eFields.get(i);
        
        String name = eField.getChildElements("name").get(0).getValue();
        String value = eField.getChildElements("value").get(0).getValue();
        
        part.addField(name, value);
    }
}
 
Example #30
Source File: XomWriter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected Object createNode(final String name) {
    final Element newNode = new Element(encodeNode(name));
    final Element top = top();
    if (top != null){
        top().appendChild(newNode);
    }
    return newNode;
}