Example usage for org.w3c.dom Element getNodeName

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

Introduction

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

Prototype

public String getNodeName();

Source Link

Document

The name of this node, depending on its type; see the table above.

Usage

From source file:org.etudes.mneme.impl.ImportQti2ServiceImpl.java

/**
 * Find all interaction to check explain reason. If more than one kind of interaction like inlinechoice and textEntry then textEntry shows explain reason.
 * /*from   w  w  w.j av  a 2 s. c  o m*/
 * @param contentsDOM
 * @return
 * @throws Exception
 */
private Set<String> findAllInteraction(Document contentsDOM) throws Exception {
    List<Element> interactionElements = new ArrayList<Element>();
    Set<String> allTypesInteraction = new HashSet<String>();

    XPath interactionTypePath = new DOMXPath(
            "/assessmentItem/itemBody//*[contains(local-name(),'Interaction')]");
    interactionElements = interactionTypePath.selectNodes(contentsDOM);

    for (Element i : interactionElements)
        allTypesInteraction.add(i.getNodeName());
    return allTypesInteraction;
}

From source file:org.etudes.mneme.impl.ImportQti2ServiceImpl.java

/**
 * Find embed media from question text and bring it in 
 * @param itemBodyElement//from   w w w  .ja  v  a2 s. co m
 * @param unzipBackUpLocation
 * @param context
 * @param embedMedia
 * @throws Exception
 */
private void processEmbedMedia(Element itemBodyElement, String unzipBackUpLocation, String context,
        List<String> embedMedia) throws Exception {
    List<Element> objects = new ArrayList<Element>();

    if (itemBodyElement.getNodeName().equals("object") || itemBodyElement.getNodeName().equals("img")
            || itemBodyElement.getNodeName().equals("a")) {
        objects.add(itemBodyElement);
    } else {
        XPath objectPath = new DOMXPath(".//object|.//img|.//a");
        objects = objectPath.selectNodes(itemBodyElement);
    }

    if (objects == null || objects.size() == 0)
        return;

    for (Element obj : objects) {
        // find fileName
        String fileName = null;
        if (obj.getNodeName().equals("object"))
            fileName = obj.getAttribute("data");
        else if (obj.getNodeName().equals("img"))
            fileName = obj.getAttribute("src");
        else if (obj.getNodeName().equals("a"))
            fileName = obj.getAttribute("href");

        // add to collection
        Reference ref = transferEmbeddedData(unzipBackUpLocation + File.separator + fileName, fileName,
                context);
        if (ref == null)
            continue;

        // replace with collection Url
        String ref_id = attachmentService.processMnemeUrls(ref.getId());
        if (ref_id != null && obj.getNodeName().equals("object"))
            obj.setAttribute("data", ref_id);
        else if (ref_id != null && obj.getNodeName().equals("img"))
            obj.setAttribute("src", ref_id);
        else if (ref_id != null && obj.getNodeName().equals("a"))
            obj.setAttribute("href", ref_id);

        if (embedMedia != null)
            embedMedia.add(fileName);
    }

}

From source file:org.etudes.mneme.impl.ImportQtiServiceImpl.java

/**
 * Process this item if it is recognized as a Respondous Matching question.
 * /*from   w ww.  ja  v  a2s .  c  om*/
 * @param item
 *        The QTI item from the QTI file DOM.
 * @param pool
 *        The pool to add the question to.
 * @param pointsAverage
 *        A running average to contribute the question's point value to for the pool.
 * @return true if successfully recognized and processed, false if not.
 */
protected boolean processRespondousMatching(Element item, Pool pool, Average pointsAverage)
        throws AssessmentPermissionException {
    String externalId = null;
    String presentation = null;
    String feedback = null;
    float points = 0.0f;

    try {
        // identifier
        externalId = StringUtil.trimToNull(item.getAttribute("ident"));

        // presentation text
        // Respondous is using the format - presentation/material/mattext
        XPath presentationTextPath = new DOMXPath("presentation/material/mattext");
        List presentationMaterialTexts = presentationTextPath.selectNodes(item);
        StringBuilder presentationTextBuilder = new StringBuilder();
        for (Object presentationMaterialText : presentationMaterialTexts) {
            Element presentationTextElement = (Element) presentationMaterialText;
            XPath matTextPath = new DOMXPath(".");
            String matText = StringUtil.trimToNull(matTextPath.stringValueOf(presentationTextElement));

            if (matText != null)
                presentationTextBuilder.append(matText);
        }
        presentation = presentationTextBuilder.toString();

        if (presentation == null) {
            // QTI format - presentation/flow/material/mattext
            presentationTextPath = new DOMXPath("presentation/flow/material/mattext");
            presentation = StringUtil.trimToNull(presentationTextPath.stringValueOf(item));
        }

        if (presentation == null)
            return false;

        // reponse_lid
        XPath reponseLidPath = new DOMXPath("presentation//response_lid");
        List responseLids = reponseLidPath.selectNodes(item);

        if (responseLids.size() == 0)
            return false;

        Map<String, String> matchPresentations = new LinkedHashMap<String, String>();
        Map<String, Object> matchChoices = new HashMap<String, Object>();

        for (Object responseLid : responseLids) {
            Element responseLidElement = (Element) responseLid;

            String identifier = responseLidElement.getAttribute("ident");

            if (StringUtil.trimToNull(identifier) == null)
                continue;

            XPath matchPresentationPath = new DOMXPath("material/mattext");
            String matchPresentationText = StringUtil
                    .trimToNull(matchPresentationPath.stringValueOf(responseLidElement));

            matchPresentations.put(identifier, matchPresentationText);

            // response_label
            XPath reponseChoicePath = new DOMXPath("render_choice/response_label");
            List reponseChoices = reponseChoicePath.selectNodes(responseLidElement);

            Map<String, String> answerChoices = new HashMap<String, String>();
            for (Object reponseChoice : reponseChoices) {
                Element reponseChoiceElement = (Element) reponseChoice;

                String responseChoiceId = reponseChoiceElement.getAttribute("ident");

                if (StringUtil.trimToNull(responseChoiceId) == null)
                    continue;

                XPath choicePresentation = new DOMXPath("material/mattext");
                String matchChoicesText = StringUtil
                        .trimToNull(choicePresentation.stringValueOf(reponseChoiceElement));

                if (StringUtil.trimToNull(matchChoicesText) == null)
                    continue;

                answerChoices.put(responseChoiceId, matchChoicesText);
            }
            matchChoices.put(identifier, answerChoices);
        }

        Map<String, String> matchAnswers = new HashMap<String, String>();

        for (String matchPresId : matchPresentations.keySet()) {
            // resprocessing
            XPath reponseAnswerPath = new DOMXPath(
                    "resprocessing//conditionvar/varequal[@respident='" + matchPresId + "']");
            List reponseAnswers = reponseAnswerPath.selectNodes(item);

            for (Object answer : reponseAnswers) {
                Element answerElement = (Element) answer;

                if (answerElement == null)
                    continue;

                XPath setvarPath = new DOMXPath("../../setvar");
                Element setvarElement = (Element) setvarPath.selectSingleNode(answerElement);

                if (setvarElement == null)
                    continue;

                if (!"setvar".equalsIgnoreCase(setvarElement.getNodeName()))
                    continue;

                if (!"Respondus_Correct".equalsIgnoreCase(setvarElement.getAttribute("varname")))
                    continue;

                matchAnswers.put(matchPresId, answerElement.getTextContent());
            }
        }

        XPath pointsPath = new DOMXPath(
                "resprocessing/outcomes/decvar[@varname='Respondus_Correct']/@maxvalue");
        String pointsValue = StringUtil.trimToNull(pointsPath.stringValueOf(item));

        try {
            if (pointsValue != null)
                points = Float.valueOf(pointsValue);
        } catch (NumberFormatException e) {
            pointsValue = "1.0";
        }

        if (matchAnswers.size() != matchPresentations.size())
            return false;

        // create the question
        Question question = this.questionService.newQuestion(pool, "mneme:Match");
        MatchQuestionImpl m = (MatchQuestionImpl) (question.getTypeSpecificQuestion());

        String clean = HtmlHelper.cleanAndAssureAnchorTarget(presentation, true);

        question.getPresentation().setText(clean);

        m.consolidate("INIT:" + matchPresentations.size());

        // set the pair values
        List<MatchQuestionImpl.MatchQuestionPair> pairs = m.getPairs();
        String value;
        int index = 0;
        for (String key : matchPresentations.keySet()) {
            clean = HtmlHelper.cleanAndAssureAnchorTarget(matchPresentations.get(key), true);
            pairs.get(index).setMatch(clean);

            Map choices = (Map) matchChoices.get(key);
            value = (String) choices.get(matchAnswers.get(key));

            if (StringUtil.trimToNull(value) == null)
                return false;

            clean = HtmlHelper.cleanAndAssureAnchorTarget(value, true);
            pairs.get(index).setChoice(clean);

            index++;
        }

        XPath itemfeedbackPath = new DOMXPath("itemfeedback/material/mattext");
        feedback = StringUtil.trimToNull(itemfeedbackPath.stringValueOf(item));

        if (feedback != null) {
            question.setFeedback(HtmlHelper.cleanAndAssureAnchorTarget(feedback, true));
        }

        // save
        question.getTypeSpecificQuestion().consolidate("");
        this.questionService.saveQuestion(question);

        // add to the points average
        pointsAverage.add(points);

        return true;
    } catch (JaxenException e) {
        return false;
    }
}

From source file:org.exist.xquery.modules.compression.AbstractCompressFunction.java

/**
* Adds a element to a archive/*from ww  w  . j a v  a2  s  .c o  m*/
* 
* @param os
*            The Output Stream to add the element to
* @param element
*            The element to add to the archive
* @param useHierarchy
*            Whether to use a folder hierarchy in the archive file that
*            reflects the collection hierarchy
*/
private void compressElement(OutputStream os, Element element, boolean useHierarchy, String stripOffset)
        throws XPathException {

    if (!(element.getNodeName().equals("entry") || element.getNamespaceURI().length() > 0))
        throw new XPathException(this, "Item must be type of xs:anyURI or element entry.");

    if (element.getChildNodes().getLength() > 1)
        throw new XPathException(this, "Entry content is not valid XML fragment.");

    String name = element.getAttribute("name");
    //            if(name == null)
    //                throw new XPathException(this, "Entry must have name attribute.");

    String type = element.getAttribute("type");

    if ("uri".equals(type)) {
        compressFromUri(os, URI.create(element.getFirstChild().getNodeValue()), useHierarchy, stripOffset,
                element.getAttribute("method"), name);
        return;
    }

    if (useHierarchy) {
        name = removeLeadingOffset(name, stripOffset);
    } else {
        name = name.substring(name.lastIndexOf("/") + 1);
    }

    if ("collection".equals(type))
        name += "/";

    Object entry = null;

    try {

        entry = newEntry(name);

        if (!"collection".equals(type)) {
            byte[] value;
            CRC32 chksum = new CRC32();
            Node content = element.getFirstChild();

            if (content == null) {
                value = new byte[0];
            } else {
                if (content.getNodeType() == Node.TEXT_NODE) {
                    String text = content.getNodeValue();
                    Base64Decoder dec = new Base64Decoder();
                    if ("binary".equals(type)) {
                        //base64 binary
                        dec.translate(text);
                        value = dec.getByteArray();
                    } else {
                        //text
                        value = text.getBytes();
                    }
                } else {
                    //xml
                    Serializer serializer = context.getBroker().getSerializer();
                    serializer.setUser(context.getUser());
                    serializer.setProperty("omit-xml-declaration", "no");
                    getDynamicSerializerOptions(serializer);
                    value = serializer.serialize((NodeValue) content).getBytes();
                }
            }

            if (entry instanceof ZipEntry && "store".equals(element.getAttribute("method"))) {
                ((ZipEntry) entry).setMethod(ZipOutputStream.STORED);
                chksum.update(value);
                ((ZipEntry) entry).setCrc(chksum.getValue());
                ((ZipEntry) entry).setSize(value.length);
            }
            putEntry(os, entry);

            os.write(value);
        }
    } catch (IOException ioe) {
        throw new XPathException(this, ioe.getMessage(), ioe);
    } catch (SAXException saxe) {
        throw new XPathException(this, saxe.getMessage(), saxe);
    } finally {
        if (entry != null)
            try {
                closeEntry(os);
            } catch (IOException ioe) {
                throw new XPathException(this, ioe.getMessage(), ioe);
            }
    }
}

From source file:org.exoplatform.wcm.connector.authoring.TestLifecycleConnector.java

/**
 * Test method LifecycleConnector.byDate()
 * Input: /authoring/bydate?fromstate=staged&date=2&lang=en&workspace=collaboration
 * Expect:a collection of nodes in XML type that contains 2 nodes:
 *         Node 1: name is Mock node1//from   w w w  . j a  va 2s. c  om
 *                 path is /node1
 *         Node 2: name is Mock node2
 *                 path is /node2
 *                 title is Mock node 2
 *                 publication:startPublishedDate is 03/18/2012
 * @throws Exception
 */
public void testByDate() throws Exception {
    String restPath = "/authoring/bydate?fromstate=staged&date=2&lang=en&workspace=collaboration";
    ContainerResponse response = service(HTTPMethods.GET.toString(), restPath, StringUtils.EMPTY, null, null);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    DOMSource object = (DOMSource) response.getEntity();
    Document document = (Document) object.getNode();
    Element element = (Element) document.getChildNodes().item(0);
    assertEquals("contents", element.getNodeName());
    NodeList nodes = element.getChildNodes();
    Node firstNode = nodes.item(0);
    Node secondNode = nodes.item(1);
    assertEquals("content", firstNode.getNodeName());
    assertEquals("Mock node1", firstNode.getAttributes().getNamedItem("name").getNodeValue());
    assertEquals("/node1", firstNode.getAttributes().getNamedItem("path").getNodeValue());
    assertEquals("content", secondNode.getNodeName());
    assertEquals("Mock node2", secondNode.getAttributes().getNamedItem("name").getNodeValue());
    assertEquals("/node2", secondNode.getAttributes().getNamedItem("path").getNodeValue());
    assertEquals("Mock node2", secondNode.getAttributes().getNamedItem("title").getNodeValue());
    assertEquals("03/18/2012", secondNode.getAttributes().getNamedItem("publishedDate").getNodeValue());
}

From source file:org.exoplatform.wcm.connector.fckeditor.TestPortalLinkConnector.java

/**
 * Test method PortalLinkConnector.getPageURI()
 * Input 1: /portalLinks/getFoldersAndFiles/
 * Expect 1: Connector return data in XML format as: 
 * <Connector command="" resourceType="PortalPageURI">
 *   <CurrentFolder path="" url="">
 *   </CurrentFolder>//ww w  . j a  va  2s.com
 *   <Folders>
 *     <Folder name="classic" url="" path="/">
 *     </Folder>
 *   </Folders>
 * </Connector> 
 * 
 * Input 2: /portalLinks/getFoldersAndFiles?currentFolder=/classic/
 * Expect 2: Connector return data in XML format OK
 * 
 * Input 3: /portalLinks/getFoldersAndFiles?currentFolder=/classic/home
 * Expect 3: Connector return data in XML format as:
 * <Connector command="" resourceType="PortalPageURI">
 *   <CurrentFolder path="/classic/home" url="">
 *   </CurrentFolder>
 *   <Folders>
 *     <Folder name="classic" url="" path="/">
 *     </Folder>
 *   </Folders>
 *   <Files>
 *   </Files>
 * </Connector>
 * @throws Exception
 */
public void testGetPageURI() throws Exception {
    ConversationState.setCurrent(new ConversationState(new Identity("root")));
    String restPath = "/portalLinks/getFoldersAndFiles/";
    ContainerResponse response = service(HTTPMethods.GET.toString(), restPath, StringUtils.EMPTY, null, null);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    DOMSource object = (DOMSource) response.getEntity();
    Document node = (Document) object.getNode();
    Element connector = (Element) node.getChildNodes().item(0);
    NodeList ConnectorChildren = connector.getChildNodes();
    assertEquals("Connector", connector.getNodeName());
    assertEquals("", connector.getAttribute("command"));
    assertEquals("PortalPageURI", connector.getAttribute("resourceType"));
    assertEquals(2, ConnectorChildren.getLength());
    Element currentFolder = (Element) ConnectorChildren.item(0);
    assertEquals("CurrentFolder", currentFolder.getNodeName());
    assertEquals("/", currentFolder.getAttribute("path"));
    assertEquals("", currentFolder.getAttribute("url"));

    Node folders = ConnectorChildren.item(1);
    assertEquals("Folders", folders.getNodeName());
    Element firstFolder = (Element) folders.getChildNodes().item(0);
    assertNotNull(firstFolder);
    assertEquals("classic", firstFolder.getAttribute("name"));
    assertEquals("", firstFolder.getAttribute("url"));
    assertEquals("", firstFolder.getAttribute("folderType"));

    restPath = "/portalLinks/getFoldersAndFiles?currentFolder=/classic/";
    response = service(HTTPMethods.GET.toString(), restPath, StringUtils.EMPTY, null, null);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

    restPath = "/portalLinks/getFoldersAndFiles?currentFolder=/classic/home";
    response = service(HTTPMethods.GET.toString(), restPath, StringUtils.EMPTY, null, null);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    object = (DOMSource) response.getEntity();
    node = (Document) object.getNode();
    connector = (Element) node.getChildNodes().item(0);
    ConnectorChildren = connector.getChildNodes();
    assertEquals("Connector", connector.getNodeName());
    assertEquals("", connector.getAttribute("command"));
    assertEquals("PortalPageURI", connector.getAttribute("resourceType"));
    assertEquals(3, ConnectorChildren.getLength());
    currentFolder = (Element) ConnectorChildren.item(0);
    assertEquals("CurrentFolder", currentFolder.getNodeName());
    assertEquals("/classic/home", currentFolder.getAttribute("path"));
    assertEquals("", currentFolder.getAttribute("url"));
    folders = ConnectorChildren.item(1);
    assertEquals("Folders", folders.getNodeName());
    Node files = ConnectorChildren.item(2);
    assertEquals("Files", files.getNodeName());
}

From source file:org.fao.geonet.api.records.formatters.ImageReplacedElementFactory.java

@Override
public ReplacedElement createReplacedElement(LayoutContext layoutContext, BlockBox box,
        UserAgentCallback userAgentCallback, int cssWidth, int cssHeight) {
    org.w3c.dom.Element element = box.getElement();
    if (element == null) {
        return null;
    }//from   www  .j  av  a  2  s.  c om

    String nodeName = element.getNodeName();
    String src = element.getAttribute("src");
    if ("img".equals(nodeName) && src.contains("region.getmap.png")) {
        StringBuilder builder = new StringBuilder(baseURL);
        try {
            if (StringUtils.startsWith(src, "http")) {
                builder = new StringBuilder();
            }
            String[] parts = src.split("\\?|&");
            builder.append(parts[0]);
            builder.append('?');
            for (int i = 1; i < parts.length; i++) {
                if (i > 1) {
                    builder.append('&');
                }
                String[] param = parts[i].split("=");
                builder.append(param[0]);
                builder.append('=');
                builder.append(URLEncoder.encode(param[1], "UTF-8"));
            }
        } catch (Exception e) {
            Log.warning(Geonet.GEONETWORK, "Error writing metadata to PDF", e);
        }
        float factor = layoutContext.getDotsPerPixel();
        return loadImage(layoutContext, box, userAgentCallback, cssWidth, cssHeight, builder.toString(),
                factor);
    } else if ("img".equals(nodeName) && isSupportedImageFormat(src)) {
        float factor = layoutContext.getDotsPerPixel();
        return loadImage(layoutContext, box, userAgentCallback, cssWidth, cssHeight, src, factor);
    }

    try {
        return superFactory.createReplacedElement(layoutContext, box, userAgentCallback, cssWidth, cssHeight);
    } catch (Throwable e) {
        return new EmptyReplacedElement(cssWidth, cssHeight);
    }
}

From source file:org.geoserver.test.GeoServerAbstractTestSupport.java

/**
 * Performs basic checks on an OWS 1.0 exception, to ensure it's well formed
 * and ensuring that a particular exceptionCode is used.
 *//*w w w  .  j  a va 2 s  .  c o  m*/
protected void checkOws10Exception(Document dom, String exceptionCode, String locator) throws Exception {
    Element root = dom.getDocumentElement();
    assertEquals("ows:ExceptionReport", root.getNodeName());
    assertEquals("1.0.0", root.getAttribute("version"));
    assertEquals("http://www.opengis.net/ows", root.getAttribute("xmlns:ows"));
    assertEquals(1, dom.getElementsByTagName("ows:Exception").getLength());

    Element ex = (Element) dom.getElementsByTagName("ows:Exception").item(0);
    if (exceptionCode != null) {
        assertEquals(exceptionCode, ex.getAttribute("exceptionCode"));
    }
    if (locator != null) {
        assertEquals(locator, ex.getAttribute("locator"));
    }
}

From source file:org.geoserver.test.GeoServerAbstractTestSupport.java

/**
 * Performs basic checks on an OWS 1.1 exception, to ensure it's well formed
 * and ensuring that a particular exceptionCode is used.
 *///w  ww .  j  a  va  2 s . c o m
protected void checkOws11Exception(Document dom, String exceptionCode) throws Exception {
    Element root = dom.getDocumentElement();
    assertEquals("ows:ExceptionReport", root.getNodeName());
    assertEquals("1.1.0", root.getAttribute("version"));
    assertEquals("http://www.opengis.net/ows/1.1", root.getAttribute("xmlns:ows"));

    if (exceptionCode != null) {
        assertEquals(1, dom.getElementsByTagName("ows:Exception").getLength());
        Element ex = (Element) dom.getElementsByTagName("ows:Exception").item(0);
        assertEquals(exceptionCode, ex.getAttribute("exceptionCode"));
    }
}

From source file:org.geoserver.test.GeoServerSystemTestSupport.java

/**
 * Performs basic checks on an OWS 2.0 exception. The check for status, exception code and locator
 * is optional, leave null if you don't want to check it. 
 * @returns Returns the message of the inner exception.
 *///w  w w . jav  a 2s.c o m
protected String checkOws20Exception(MockHttpServletResponse response, Integer status, String exceptionCode,
        String locator) throws Exception {
    // check the http level
    assertEquals("application/xml", response.getContentType());
    if (status != null) {
        assertEquals(status.intValue(), response.getStatusCode());
    }

    // check the returned xml
    Document dom = dom(new ByteArrayInputStream(response.getOutputStreamContent().getBytes()));
    Element root = dom.getDocumentElement();
    assertEquals("ows:ExceptionReport", root.getNodeName());
    assertEquals("2.0.0", root.getAttribute("version"));
    assertEquals("http://www.opengis.net/ows/2.0", root.getAttribute("xmlns:ows"));

    // look into exception code and locator
    assertEquals(1, dom.getElementsByTagName("ows:Exception").getLength());
    Element ex = (Element) dom.getElementsByTagName("ows:Exception").item(0);
    if (exceptionCode != null) {
        assertEquals(exceptionCode, ex.getAttribute("exceptionCode"));
    }
    if (locator != null) {
        assertEquals(locator, ex.getAttribute("locator"));
    }

    assertEquals(1, dom.getElementsByTagName("ows:ExceptionText").getLength());
    return dom.getElementsByTagName("ows:ExceptionText").item(0).getTextContent();
}