Example usage for org.w3c.dom Element removeAttribute

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

Introduction

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

Prototype

public void removeAttribute(String name) throws DOMException;

Source Link

Document

Removes an attribute by name.

Usage

From source file:org.sakaiproject.assignment.impl.BaseAssignmentService.java

/**
 * {@inheritDoc}/*  w w  w.ja v  a2 s  .  c om*/
 */
public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments) {
    // prepare the buffer for the results log
    StringBuilder results = new StringBuilder();

    // String assignRef = assignmentReference(siteId, SiteService.MAIN_CONTAINER);
    results.append("archiving " + getLabel() + " context " + Entity.SEPARATOR + siteId + Entity.SEPARATOR
            + SiteService.MAIN_CONTAINER + ".\n");

    // start with an element with our very own (service) name
    Element element = doc.createElement(AssignmentService.class.getName());
    ((Element) stack.peek()).appendChild(element);
    stack.push(element);

    Iterator assignmentsIterator = getAssignmentsForContext(siteId);

    while (assignmentsIterator.hasNext()) {
        Assignment assignment = (Assignment) assignmentsIterator.next();

        // archive this assignment
        Element el = assignment.toXml(doc, stack);
        element.appendChild(el);

        // in order to make the assignment.xml have a better structure
        // the content id attribute removed from the assignment node
        // the content will be a child of assignment node
        el.removeAttribute("assignmentcontent");

        // then archive the related content
        AssignmentContent content = (AssignmentContent) assignment.getContent();
        if (content != null) {
            Element contentEl = content.toXml(doc, stack);

            // assignment node has already kept the context info
            contentEl.removeAttribute("context");

            // collect attachments
            List atts = content.getAttachments();

            for (int i = 0; i < atts.size(); i++) {
                Reference ref = (Reference) atts.get(i);
                // if it's in the attachment area, and not already in the list
                if ((ref.getReference().startsWith("/content/attachment/")) && (!attachments.contains(ref))) {
                    attachments.add(ref);
                }

                // in order to make assignment.xml has the consistent format with the other xml files
                // move the attachments to be the children of the content, instead of the attributes
                String attributeString = "attachment" + i;
                String attRelUrl = contentEl.getAttribute(attributeString);
                contentEl.removeAttribute(attributeString);
                Element attNode = doc.createElement("attachment");
                attNode.setAttribute("relative-url", attRelUrl);
                contentEl.appendChild(attNode);

            } // for

            // make the content a childnode of the assignment node
            el.appendChild(contentEl);

            Iterator submissionsIterator = getSubmissions(assignment).iterator();
            while (submissionsIterator.hasNext()) {
                AssignmentSubmission submission = (AssignmentSubmission) submissionsIterator.next();

                // archive this assignment
                Element submissionEl = submission.toXml(doc, stack);
                el.appendChild(submissionEl);

            }
        } // if
    } // while

    stack.pop();

    return results.toString();

}

From source file:org.sakaiproject.content.impl.BaseContentService.java

/**
 * Archive a singe resource/*from   ww w  .  j  a  va  2s.  c o m*/
 * 
 * @param resource
 *        The content resource to archive
 * @param doc
 *        The XML document.
 * @param stack
 *        The stack of elements.
 * @param storagePath
 *        The path to the folder where we are writing files.
 * @param siteCollectionId
 *        The resource id of the site collection (optional).
 * @return A log of messages from the archive.
 */
protected String archiveResource(ContentResource resource, Document doc, Stack stack, String storagePath,
        String siteCollectionId) {
    // form the xml
    Element el = resource.toXml(doc, stack);

    // remove the content from the xml
    el.removeAttribute("body");

    // write the content to a file
    String fileName = idManager.createUuid();
    InputStream stream = null;
    FileOutputStream out = null;
    try {
        stream = resource.streamContent();
        out = new FileOutputStream(storagePath + fileName);
        byte[] chunk = new byte[STREAM_BUFFER_SIZE];
        int lenRead;
        while ((lenRead = stream.read(chunk)) != -1) {
            out.write(chunk, 0, lenRead);
        }
    } catch (IOException e) {
        M_log.warn("archiveResource(): while writing body for: " + resource.getId() + " : " + e);
    } catch (ServerOverloadException e) {
        M_log.warn("archiveResource(): while writing body for: " + resource.getId() + " : " + e);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                M_log.error("IOException ", e);
            }
        }

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                M_log.error("IOException ", e);
            }
        }
    }

    // store the file name in the xml
    el.setAttribute("body-location", fileName);

    // store the relative file id in the xml
    if (siteCollectionId != null) {
        el.setAttribute("rel-id", resource.getId().substring(siteCollectionId.length()));
    }

    return "archiving resource: " + resource.getId() + " body in file: " + fileName + "\n";
}

From source file:org.sakaiproject.tool.gradebook.test.GradebookServiceInternalTest.java

public void testGradebookMigrationVersioning() throws Exception {
    setAuthnId(INSTRUCTOR_UID);/*from   w ww.  j  ava  2 s  .c  o m*/
    String gradebookXml = gradebookService.getGradebookDefinitionXml(GRADEBOOK_UID);

    DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = documentBuilder.parse(new InputSource(new StringReader(gradebookXml)));
    Element gradebookElement = document.getDocumentElement();
    String versionXml = gradebookElement.getAttribute(VersionedExternalizable.VERSION_ATTRIBUTE);
    Assert.assertTrue(versionXml.equals(GradebookDefinition.EXTERNALIZABLE_VERSION));

    // Mess with the converter's mind and make sure it's displeased.
    gradebookElement.removeAttribute(VersionedExternalizable.VERSION_ATTRIBUTE);
    gradebookElement.setAttribute(VersionedExternalizable.VERSION_ATTRIBUTE, "Who are you kidding?");
    try {
        String newXml = documentToString(document);
        VersionedExternalizable.fromXml(newXml);
        fail();
    } catch (ConversionException e) {
    }
}

From source file:org.sonatype.nexus.yum.internal.MetadataProcessor.java

/**
 * Processes metadata:/* ww  w  .ja  v a  2  s . c o  m*/
 * - Rewrites locations in primary.xml after a merge. Locations are wrongly written as file urls of merged group
 * repository base dirs, which will be rewritten to be relative to group repository.
 * - Removes sqlite databases from repomd.xml.
 *
 * @param repository                 containing yum repository
 * @param memberRepositoriesBaseDirs list of merged group repository base dirs
 * @return true if primary.xml/repomd.xml was changed
 */
public static boolean processMergedMetadata(final Repository repository,
        final List<File> memberRepositoriesBaseDirs) {
    log.debug("Checking if {}:primary.xml locations should be rewritten after merge", repository.getId());
    return processMetadata(repository, new Processor() {
        @Override
        public boolean process(final Element location) {
            String xmlBase = location.getAttribute("xml:base");
            if (xmlBase != null) {
                String href = location.getAttribute("href");
                if (!xmlBase.endsWith("/")) {
                    xmlBase += "/";
                }
                href = xmlBase + href;
                for (File memberReposBaseDir : memberRepositoriesBaseDirs) {
                    String memberRepoDirPath = memberReposBaseDir.getPath();
                    int pos = href.indexOf(memberRepoDirPath);
                    if (pos > -1) {
                        href = href.substring(pos + memberRepoDirPath.length());
                        if (href.startsWith("/")) {
                            href = href.substring(1);
                        }
                        location.setAttribute("href", href);
                        location.removeAttribute("xml:base");
                        return true;
                    }
                }
            }
            return false;
        }
    });
}

From source file:org.sonatype.nexus.yum.internal.MetadataProcessor.java

/**
 * Processes metadata://from  w  ww . j a  v  a 2 s  .c  om
 * - Rewrites locations in primary.xml after it had been proxied. All locations that have an xml:base + url matching
 * repository url will be changed to be relative to repository.
 * - Removes sqlite databases from repomd.xml.
 *
 * @param repository containing yum repository
 * @return true if primary.xml/repomd.xml was changed
 */
public static boolean processProxiedMetadata(final ProxyRepository repository) {
    log.debug("Checking if {}:primary.xml locations should be rewritten after being proxied",
            repository.getId());
    final String repositoryUrl = repository.getRemoteUrl();
    return processMetadata(repository, new Processor() {
        @Override
        public boolean process(final Element location) {
            String xmlBase = location.getAttribute("xml:base");
            if (xmlBase != null) {
                String href = location.getAttribute("href");
                if (!xmlBase.endsWith("/")) {
                    xmlBase += "/";
                }
                href = xmlBase + href;
                if (href.startsWith(repositoryUrl)) {
                    href = href.substring(repositoryUrl.length());
                    if (href.startsWith("/")) {
                        href = href.substring(1);
                    }
                    location.setAttribute("href", href);
                    location.removeAttribute("xml:base");
                    return true;
                }
            }
            return false;
        }
    });
}

From source file:org.xwiki.officeimporter.internal.filter.ImageFilter.java

/**
 * {@inheritDoc}//  ww w  .  jav a  2  s  .  co m
 */
public void filter(Document htmlDocument, Map<String, String> cleaningParams) {
    String targetDocument = cleaningParams.get("targetDocument");
    DocumentReference targetDocumentReference = null;

    List<Element> images = filterDescendants(htmlDocument.getDocumentElement(), new String[] { TAG_IMG });
    for (Element image : images) {
        if (targetDocumentReference == null && !StringUtils.isBlank(targetDocument)) {
            targetDocumentReference = documentStringReferenceResolver.resolve(targetDocument);
        }
        String src = image.getAttribute(ATTRIBUTE_SRC);
        if (!StringUtils.isBlank(src) && targetDocumentReference != null) {
            // OpenOffice 3.2 server generates relative image paths, extract image name.
            int separator = src.lastIndexOf("/");
            if (-1 != separator) {
                src = src.substring(separator + 1);
            }
            try {
                // We have to decode the image file name in case it contains URL special characters.
                src = URLDecoder.decode(src, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // This should never happen.
            }

            // Set image source attribute relative to the reference document.
            AttachmentReference attachmentReference = new AttachmentReference(src, targetDocumentReference);
            image.setAttribute(ATTRIBUTE_SRC,
                    documentAccessBridge.getAttachmentURL(attachmentReference, false));

            // The 'align' attribute of images creates a lot of problems. First, OO server has a problem with
            // center aligning images (it aligns them to left). Next, OO server uses <br clear"xxx"> for
            // avoiding content wrapping around images which is not valid xhtml. There for, to be consistent and
            // simple we will remove the 'align' attribute of all the images so that they are all left aligned.
            image.removeAttribute(ATTRIBUTE_ALIGN);
        } else if (src.startsWith("file://")) {
            src = "Missing.png";
            image.setAttribute(ATTRIBUTE_SRC, src);
            image.setAttribute(ATTRIBUTE_ALT, src);
        }
        ResourceReference imageReference = new ResourceReference(src, ResourceType.ATTACHMENT);
        imageReference.setTyped(false);
        Comment beforeComment = htmlDocument
                .createComment("startimage:" + this.xhtmlMarkerSerializer.serialize(imageReference));
        Comment afterComment = htmlDocument.createComment("stopimage");
        image.getParentNode().insertBefore(beforeComment, image);
        image.getParentNode().insertBefore(afterComment, image.getNextSibling());
    }
}

From source file:org.yawlfoundation.yawl.util.DOMUtil.java

public static void removeAllAttributes(Element element) {
    Vector<String> names = new Vector<String>();

    int length = element.getAttributes().getLength();
    NamedNodeMap atts = element.getAttributes();

    for (int i = 0; i < length; names.add(atts.item(i).getLocalName()), i++)
        ;/*from w ww.  j  a v  a 2 s  .co  m*/

    for (String name : names)
        element.removeAttribute(name);
}

From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java

/**
 * Does the following:/*from   w  w  w .  j ava 2 s .  co  m*/
 * <ol>
 * <li>Recursively calls this method on all child elements of
 * <code>talist</code> to handle any child lists first
 * <li>Remove the attributes {@link #SERIALIZATION_ATTRIBUTE} and
 * {@link #CLASS_ATTRIBUTE} of <code>talist</code></li>
 * <li>If
 * <code>//[talist.getNodeName()]/org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl/default/size/</code>
 * evaluates to a value >1, indicating elements in this list, call
 * {@link #transformClassNode(Document, Node)} on that element and store to
 * readd</li>
 * <li>Remove all child elements of <code>talist</code></li>
 * <li>Readd list elements calculated and transformed above</li>
 * </ol>
 * 
 * @param document
 *            Root {@link Document}
 * @param xpath
 *            {@link XPath} to use during evaluation
 * @param talist
 *            {@link Element} to process typed array lists on
 * @throws XPathExpressionException
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws InstantiationException
 */
private void handleTypedArrayList(Document document, XPath xpath, Element talist)
        throws XPathExpressionException, ClassNotFoundException, IllegalAccessException,
        InvocationTargetException, InvocationTargetException, NoSuchMethodException, InstantiationException {
    LOGGER.trace("Handling typed array list: " + talist.getNodeName());
    XPathExpression getChildTypedArrayLists = xpath
            .compile(".//*[@class='org.kuali.rice.kns.util.TypedArrayList']");
    NodeList nodeList = (NodeList) getChildTypedArrayLists.evaluate(talist, XPathConstants.NODESET);
    // handle any child lists first
    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node item = nodeList.item(i);
        handleTypedArrayList(document, xpath, (Element) item);
    }

    talist.removeAttribute(SERIALIZATION_ATTRIBUTE);
    talist.removeAttribute(CLASS_ATTRIBUTE);
    XPathExpression listSizeExpression = xpath.compile("//" + talist.getNodeName()
            + "/org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl/default/size/text()");
    String size = (String) listSizeExpression.evaluate(talist, XPathConstants.STRING);
    List<Node> nodesToAdd = new ArrayList<Node>();
    if (StringUtils.isNotBlank(size) && Integer.valueOf(size) > 0) {
        XPathExpression listTypeExpression = xpath.compile("//" + talist.getNodeName()
                + "/org.kuali.rice.kns.util.TypedArrayList/default/listObjectType/text()");
        String listType = (String) listTypeExpression.evaluate(talist, XPathConstants.STRING);
        XPathExpression listContentsExpression = xpath.compile("//" + talist.getNodeName()
                + "/org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl/" + listType);
        NodeList listContents = (NodeList) listContentsExpression.evaluate(talist, XPathConstants.NODESET);
        for (int i = 0; i < listContents.getLength(); i++) {
            Node tempNode = listContents.item(i);
            transformClassNode(document, tempNode);
            nodesToAdd.add(tempNode);
        }
    }
    for (Node removeNode = talist.getFirstChild(); removeNode != null;) {
        Node nextRemoveNode = removeNode.getNextSibling();
        talist.removeChild(removeNode);
        removeNode = nextRemoveNode;
    }
    for (Node nodeToAdd : nodesToAdd) {
        talist.appendChild(nodeToAdd);
    }
}