Example usage for org.dom4j Node detach

List of usage examples for org.dom4j Node detach

Introduction

In this page you can find the example usage for org.dom4j Node detach.

Prototype

Node detach();

Source Link

Document

Removes this node from its parent if there is one.

Usage

From source file:org.collectionspace.chain.util.xtmpl.XTmplDocument.java

License:Educational Community License

@SuppressWarnings("unchecked")
public void setTexts(String key, String[] texts) {
    Node basis = document.selectSingleNode(attach.get(key));
    Element parent = basis.getParent();
    int pos = parent.indexOf(basis);
    List<Node> nodes = (List<Node>) parent.content();
    List<Node> after = new ArrayList(nodes.subList(pos + 1, nodes.size()));
    basis.detach();
    if (texts.length > 0) {
        for (Node n : after)
            n.detach();/*  w ww  . j a  v a 2 s .c  om*/
        for (String text : texts) {
            Node renewed = (Node) basis.clone();
            renewed.setText(text);
            parent.add(renewed);
        }
        for (Node n : after)
            parent.add(n);
    }
}

From source file:org.collectionspace.chain.util.xtmpl.XTmplDocument.java

License:Educational Community License

public Document getDocument() {
    if (squash_empty && !stripped) {
        for (String path : attach.values()) {
            Node n = document.selectSingleNode(path);
            if (n == null || !(n instanceof Element))
                continue;
            if (!("".equals(((Element) n).getText())))
                continue;
            // Empty!
            n.detach();
        }/*from w ww. j a v a2  s.  c  om*/
        stripped = true;
    }
    return document;
}

From source file:org.ednovo.gooru.application.util.ClassplanFormatUtil.java

License:Open Source License

public boolean convertXML(String classplanXml, String classplanId) throws Exception {
    boolean updateInfo = false;

    Document classplanDoc;// w  w w. java2  s . c  o m

    classplanDoc = StringUtil.convertString2Document(classplanXml);

    Node suggestedreading = classplanDoc.selectSingleNode("//suggestedreading");

    if (suggestedreading != null) {

        // Create a new Segment for assessment
        String studySegId = insertSegment(classplanId, SUGGESTEDSTUDY, SUGGESTED_STUDY);
        if (!((Element) suggestedreading).getData().toString().equals("")) {
            String data = ((Element) suggestedreading).getData().toString();
            data = data.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&apos;",
                    "'");
            data = "<suggestedreading>" + data + "</suggestedreading>";

            Document anchorTagsInSS = StringUtil.convertString2Document(data); // StringUtil.convertString2Document("<ul><li><a href=\"http://quiz.thefullwiki.org/Mammal\">http://quiz.thefullwiki.org/Mammal</a></li></ul>");

            List<Node> atSS = anchorTagsInSS.selectNodes("//a");
            Map<String, String> suggestedStudyMap = new HashMap<String, String>();
            for (Node node : atSS) {
                Element newele = (Element) node;
                suggestedStudyMap.put(newele.getText(), newele.attributeValue(HREF));
                insertResource(classplanId, studySegId, ResourceType.Type.RESOURCE.getType(),
                        newele.attributeValue(HREF), newele.getText());
            }
        }
        // Delete the suggested study node from info element
        suggestedreading.detach();
        updateInfo = true;
    }

    Node homework = classplanDoc.selectSingleNode("//homework");

    if (homework != null) {

        // create a new segment for homework
        String homeworkSegId = insertSegment(classplanId, "homework", "Homework");

        if (!((Element) homework).getData().toString().equals("")) {

            String data = ((Element) homework).getData().toString();
            data = data.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&apos;",
                    "'");
            data = "<homework>" + data + "</homework>";

            Document anchorTagsInhomework = StringUtil.convertString2Document(data); // StringUtil.convertString2Document("<ul><li><a href=\"http://quiz.thefullwiki.org/Mammal\">http://quiz.thefullwiki.org/Mammal</a></li></ul>");

            List<Node> ath = anchorTagsInhomework.selectNodes("//a");
            Map<String, String> homwworkMap = new HashMap<String, String>();
            for (Node node : ath) {
                Element newele = (Element) node;
                homwworkMap.put(newele.getText(), newele.attributeValue(HREF));
                insertResource(classplanId, homeworkSegId, ResourceType.Type.RESOURCE.getType(),
                        newele.attributeValue(HREF), newele.getText());
            }
        }
        // Delete the homework node from info element
        homework.detach();
        updateInfo = true;
    }

    Node assessment = classplanDoc.selectSingleNode("//assessment");

    if (assessment != null) {

        // Create a new Segment for assessment
        String assessmentSegId = insertSegment(classplanId, ASSESSMENT, ASSESSMENTS);

        if (!((Element) assessment).getData().toString().equals("")) {
            String data = ((Element) assessment).getData().toString();
            data = data.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&apos;",
                    "'");
            data = "<assessment>" + data + "</assessment>";
            Document anchorTagsInassessment = StringUtil.convertString2Document(data); // StringUtil.convertString2Document("<ul><li><a href=\"http://quiz.thefullwiki.org/Mammal\">http://quiz.thefullwiki.org/Mammal</a></li></ul>");

            List<Node> ata = anchorTagsInassessment.selectNodes("//a");
            Map<String, String> assesmentMap = new HashMap<String, String>();
            for (Node node : ata) {
                Element newele = (Element) node;
                assesmentMap.put(newele.getText(), newele.attributeValue(HREF));

                insertResource(classplanId, assessmentSegId, ResourceType.Type.RESOURCE.getType(),
                        newele.attributeValue(HREF), newele.getText());
            }
        }

        // Delete the assessment node from info element
        assessment.detach();
        updateInfo = true;
    }

    if (updateInfo) {
        // FIXME
        // this.getClassplanRepository().updateClasplanInfoXml(classplanDoc.selectSingleNode("//info").asXML()
        // , classplanId);
        System.out.println("Success: " + classplanId);
    }

    return false;
}

From source file:org.gbif.harvest.digir.DigirMetadataHandler.java

License:Open Source License

/**
 * Parse the response file and write the parsed values to their
 * appropriate file./*from   w w w .j ava 2 s  .com*/
 *
 * @param inputStream representing harvested xml response
 *
 * @throws DocumentException thrown if parsing error occurred
 * @throws IOException       thrown
 */
private void parseResponseFile(ByteArrayInputStream inputStream) throws DocumentException, IOException {

    // create a DOM4J tree, reading a Document from the given File
    SAXReader reader = new SAXReader();
    reader.setEncoding("UTF-8");
    Document document = reader.read(inputStream);
    document.setXMLEncoding("UTF-8");

    // get all resource Elements
    List<Node> resourceEntities = (metadataRepeatingElementsXpath.get(resourceEntityRepeatingElementName))
            .selectNodes(document);
    // iterate over resource Elements
    for (Node resourceEntity : resourceEntities) {

        // Detatch resource Element and create new Document with it
        DefaultDocument doc1 = new DefaultDocument();
        doc1.setRootElement((Element) resourceEntity.detach());

        // get all resource contact Elements
        List<Node> resourceContacts = (metadataRepeatingElementsXpath.get(contactEntityRepeatingElementName))
                .selectNodes(doc1);
        // iterate over contact Elements
        for (Node resourceContact : resourceContacts) {

            // Detatch relatedEntity Element and create new Document with it
            DefaultDocument doc2 = new DefaultDocument();
            doc2.setRootElement((Element) resourceContact.detach());

            // write hasContact elements-of-interest to file
            fileUtils.writeValuesToFile(resourceContactsBW, metadataResourceContactElementsOfInterest.values(),
                    doc2, namespaceMap, String.valueOf(getLineNumber()));
        }
        // write relatedEntity elements-of-interest to file
        fileUtils.writeValuesToFile(resourcesBW, metadataElementsOfInterest.values(), doc1, namespaceMap,
                String.valueOf(getLineNumber()));

        setLineNumber(getLineNumber() + 1);
    }
}

From source file:org.gbif.harvest.tapir.TapirMetadataHandler.java

License:Open Source License

/**
 * Parse the response file and write the parsed values to their
 * appropriate file.//from w  ww .  j a va2 s. co  m
 *
 * @param stream file representing harvested xml response as ByteArrayInputStream
 *
 * @throws DocumentException thrown if parsing errors occur
 * @throws IOException       thrown
 */
private void parseResponseFile(ByteArrayInputStream stream) throws DocumentException, IOException {

    // create a DOM4J tree, reading a Document from the given File
    SAXReader reader = new SAXReader();
    reader.setEncoding("UTF-8");
    Document document = reader.read(stream);
    document.setXMLEncoding("UTF-8");

    // get all relatedEntity Elements
    List<Node> relatedEntities = (metadataRepeatingElementsXpath.get(RELATEDENTITY_REPEATING_ELEMENT_NAME))
            .selectNodes(document);
    // iterate over dataset Elements
    for (Node relatedEntity : relatedEntities) {

        // Detatch relatedEntity Element and create new Document with it
        DefaultDocument doc1 = new DefaultDocument();
        doc1.setRootElement((Element) relatedEntity.detach());

        // get all hasContact Elements
        List<Node> hasContacts = (metadataRepeatingElementsXpath.get(HASCONTACT_REPEATING_ELEMENT_NAME))
                .selectNodes(doc1);
        // iterate over hasContact Elements
        for (Node hasContact : hasContacts) {

            // Detatch relatedEntity Element and create new Document with it
            DefaultDocument doc2 = new DefaultDocument();
            doc2.setRootElement((Element) hasContact.detach());

            // write hasContact elements-of-interest to file
            fileUtils.writeValuesToFile(hasContactBW, harvestedHasContactElementsOfInterest.values(), doc2,
                    namespaceMap, String.valueOf(getLineNumber()));
        }
        // write relatedEntity elements-of-interest to file
        fileUtils.writeValuesToFile(relatedEntityBW, harvestedRelatedEntityElementsOfInterest.values(), doc1,
                namespaceMap, String.valueOf(getLineNumber()));

        setLineNumber(getLineNumber() + 1);
    }
}

From source file:org.gbif.portal.util.mhf.message.impl.xml.XMLMessageFactory.java

License:Open Source License

/**
 * Creates a new Message based on the node that is passed in
 *
 * @param node   To copy or detach/*from  w w w. j  a  v  a 2s .com*/
 * @param detach If the node may be detached from the parent document
 * @return A new message
 */
public XMLMessage build(Node node, boolean detach) {
    Document document = DocumentFactory.getInstance().createDocument();
    if (detach) {
        document.add(node.detach());
    } else {
        Node cloned = (Node) node.clone();
        document.add(cloned);
    }
    return new XMLMessage(document);
}

From source file:org.olat.ims.qti.render.ResultsBuilder.java

License:Apache License

private static void detachNodes(final String xPath, final Document doc) {
    final List xpathres = doc.selectNodes(xPath);
    for (final Iterator iter = xpathres.iterator(); iter.hasNext();) {
        final Node element = (Node) iter.next();
        element.detach();
    }// w ww . jav  a 2 s .com
}

From source file:org.openadaptor.thirdparty.dom4j.Dom4jSimpleRecordAccessor.java

License:Open Source License

/**
 * Remove and return an attribute from the document, given it's key.
 * <p>//from   w  ww.j  a  va2s .  c  om
 * If the node isn't found, then no action is taken.
 * @param key corresponding to the object being searched for.
 * @return The Object which has been removed, or null if not found.
 * @throws RecordException if the operation cannot be completed.
 */
public Object remove(Object key) throws RecordException {
    Object value = null;
    Node node = document.selectSingleNode(key.toString());
    if (node instanceof Element) {
        Element element = (Element) node;
        value = Dom4jUtils.getTypedValue(element, valueTypeAttributeName, !element.elements().isEmpty());

        // remove only works if the node is a child, otherwise we need to use
        // the detatch() call
        //            document.remove(node);
        node.detach();
    } else { //Don't know how to proceed. //ToDo: Perhaps we should allow it anyway.
        throw new RecordException("selected node is not an Element instance: " + node.toString());
    }
    return value;
}

From source file:org.opencms.setup.xml.v8.CmsXmlAddADESearch.java

License:Open Source License

/**
 * Initializes the map of XML update actions.<p>
 *///from   w w w.  java2s  .  c  o  m
private void initActions() {

    m_actions = new LinkedHashMap<String, CmsXmlUpdateAction>();
    StringBuffer xp;
    CmsXmlUpdateAction action0 = new CmsXmlUpdateAction() {

        @SuppressWarnings("unchecked")
        @Override
        public boolean executeUpdate(Document doc, String xpath, boolean forReal) {

            Node node = doc.selectSingleNode(xpath);
            org.dom4j.Element parent = node.getParent();
            int position = parent.indexOf(node);
            parent.remove(node);
            try {
                parent.elements().add(position, createElementFromXml("      <documenttypes>     \n"
                        + "            <documenttype>\n" + "                <name>generic</name>\n"
                        + "                <class>org.opencms.search.documents.CmsDocumentGeneric</class>\n"
                        + "                <mimetypes/>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>*</resourcetype>\n"
                        + "                </resourcetypes>\n" + "            </documenttype> \n"
                        + "            <documenttype>\n" + "                <name>html</name>\n"
                        + "                <class>org.opencms.search.documents.CmsDocumentHtml</class>\n"
                        + "                <mimetypes>\n"
                        + "                    <mimetype>text/html</mimetype>\n"
                        + "                </mimetypes>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>plain</resourcetype>\n"
                        + "                </resourcetypes>\n" + "            </documenttype>\n"
                        + "            <documenttype>\n" + "                <name>image</name>\n"
                        + "                <class>org.opencms.search.documents.CmsDocumentGeneric</class>\n"
                        + "                <mimetypes/>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>image</resourcetype>\n"
                        + "                </resourcetypes>\n" + "            </documenttype>     \n"
                        + "            <documenttype>\n" + "                <name>jsp</name>\n"
                        + "                <class>org.opencms.search.documents.CmsDocumentPlainText</class>\n"
                        + "                <mimetypes/>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>jsp</resourcetype>\n"
                        + "                </resourcetypes>\n" + "            </documenttype>     \n"
                        + "            <documenttype>\n" + "                <name>pdf</name>\n"
                        + "                <class>org.opencms.search.documents.CmsDocumentPdf</class>\n"
                        + "                <mimetypes>\n"
                        + "                    <mimetype>application/pdf</mimetype>\n"
                        + "                </mimetypes>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>binary</resourcetype>\n"
                        + "                    <resourcetype>plain</resourcetype>\n"
                        + "                </resourcetypes>\n" + "            </documenttype>\n"
                        + "            <documenttype>\n" + "                <name>rtf</name>\n"
                        + "                <class>org.opencms.search.documents.CmsDocumentRtf</class>\n"
                        + "                <mimetypes>\n"
                        + "                    <mimetype>text/rtf</mimetype>\n"
                        + "                    <mimetype>application/rtf</mimetype>\n"
                        + "                </mimetypes>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>binary</resourcetype>\n"
                        + "                    <resourcetype>plain</resourcetype>\n"
                        + "                </resourcetypes>\n" + "            </documenttype>     \n"
                        + "            <documenttype>\n" + "                <name>text</name>\n"
                        + "                <class>org.opencms.search.documents.CmsDocumentPlainText</class>\n"
                        + "                <mimetypes>\n"
                        + "                    <mimetype>text/html</mimetype>\n"
                        + "                    <mimetype>text/plain</mimetype>\n"
                        + "                </mimetypes>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>plain</resourcetype>\n"
                        + "                </resourcetypes>\n" + "            </documenttype> \n"
                        + "            <documenttype>\n" + "                <name>xmlcontent</name>\n"
                        + "                <class>org.opencms.search.documents.CmsDocumentXmlContent</class>\n"
                        + "                <mimetypes/>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>*</resourcetype>\n"
                        + "                </resourcetypes>\n" + "            </documenttype>\n"
                        + "            <documenttype>\n" + "                <name>containerpage</name>\n"
                        + "                <class>org.opencms.search.documents.CmsDocumentContainerPage</class>\n"
                        + "                <mimetypes>\n"
                        + "                    <mimetype>text/html</mimetype>\n"
                        + "                </mimetypes>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>containerpage</resourcetype>\n"
                        + "                </resourcetypes>\n"
                        + "            </documenttype>                 \n" + "            <documenttype>\n"
                        + "                <name>xmlpage</name>\n"
                        + "                <class>org.opencms.search.documents.CmsDocumentXmlPage</class>\n"
                        + "                <mimetypes>\n"
                        + "                    <mimetype>text/html</mimetype>\n"
                        + "                </mimetypes>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>xmlpage</resourcetype>\n"
                        + "                </resourcetypes>\n" + "            </documenttype>\n"
                        + "            <documenttype>\n" + "                <name>xmlcontent-galleries</name>\n"
                        + "                <class>org.opencms.search.galleries.CmsGalleryDocumentXmlContent</class>\n"
                        + "                <mimetypes/>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>xmlcontent-galleries</resourcetype>\n"
                        + "                </resourcetypes>\n" + "            </documenttype> \n"
                        + "            <documenttype>\n" + "                <name>xmlpage-galleries</name>\n"
                        + "                <class>org.opencms.search.galleries.CmsGalleryDocumentXmlPage</class>\n"
                        + "                <mimetypes />\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>xmlpage-galleries</resourcetype>\n"
                        + "                </resourcetypes>\n" + "            </documenttype>     \n"
                        + "            <documenttype>\n" + "                <name>msoffice-ole2</name>\n"
                        + "                <class>org.opencms.search.documents.CmsDocumentMsOfficeOLE2</class>\n"
                        + "                <mimetypes>\n"
                        + "                    <mimetype>application/vnd.ms-powerpoint</mimetype>\n"
                        + "                    <mimetype>application/msword</mimetype>     \n"
                        + "                    <mimetype>application/vnd.ms-excel</mimetype>\n"
                        + "                </mimetypes>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>binary</resourcetype>\n"
                        + "                    <resourcetype>plain</resourcetype>\n"
                        + "                </resourcetypes>\n"
                        + "            </documenttype>                 \n" + "            <documenttype>\n"
                        + "                <name>msoffice-ooxml</name>\n"
                        + "                <class>org.opencms.search.documents.CmsDocumentMsOfficeOOXML</class>\n"
                        + "                <mimetypes>             \n"
                        + "                    <mimetype>application/vnd.openxmlformats-officedocument.wordprocessingml.document</mimetype>\n"
                        + "                    <mimetype>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mimetype>\n"
                        + "                    <mimetype>application/vnd.openxmlformats-officedocument.presentationml.presentation</mimetype>\n"
                        + "                </mimetypes>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>binary</resourcetype>\n"
                        + "                    <resourcetype>plain</resourcetype>\n"
                        + "                </resourcetypes>\n"
                        + "            </documenttype>                 \n" + "            <documenttype>\n"
                        + "                <name>openoffice</name>\n"
                        + "                <class>org.opencms.search.documents.CmsDocumentOpenOffice</class>\n"
                        + "                <mimetypes>\n"
                        + "                    <mimetype>application/vnd.oasis.opendocument.text</mimetype>\n"
                        + "                    <mimetype>application/vnd.oasis.opendocument.spreadsheet</mimetype>\n"
                        + "                </mimetypes>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>binary</resourcetype>\n"
                        + "                    <resourcetype>plain</resourcetype>\n"
                        + "                </resourcetypes>\n" + "            </documenttype>\n"
                        + "        </documenttypes>\n"));
            } catch (DocumentException e) {
                System.out.println("failed to update document types.");
            }
            return true;

        }
    };
    m_actions.put(buildXpathForDoctypes(), action0);
    //
    //=============================================================================================================
    //
    CmsXmlUpdateAction action1 = new CmsXmlUpdateAction() {

        @SuppressWarnings("synthetic-access")
        @Override
        public boolean executeUpdate(Document doc, String xpath, boolean forReal) {

            Node node = doc.selectSingleNode(xpath);
            if (node == null) {
                createAnalyzer(doc, xpath, CmsGallerySearchAnalyzer.class, "all");
                return true;
            }
            return false;
        }
    };
    xp = new StringBuffer(256);
    xp.append(getCommonPath());
    xp.append("/");
    xp.append(CmsSearchConfiguration.N_ANALYZERS);
    xp.append("/");
    xp.append(CmsSearchConfiguration.N_ANALYZER);
    xp.append("[");
    xp.append(CmsSearchConfiguration.N_CLASS);
    xp.append("='").append(CmsGallerySearchAnalyzer.class.getName()).append("']");
    m_actions.put(xp.toString(), action1);
    //
    //=============================================================================================================
    //
    CmsXmlUpdateAction action2 = new CmsXmlUpdateAction() {

        @SuppressWarnings("synthetic-access")
        @Override
        public boolean executeUpdate(Document doc, String xpath, boolean forReal) {

            Node node = doc.selectSingleNode(xpath);
            if (node != null) {
                node.detach();
            }
            createIndex(doc, xpath, CmsGallerySearchIndex.class, CmsGallerySearchIndex.GALLERY_INDEX_NAME,
                    "offline", "Offline", "all", "gallery_fields",
                    new String[] { "gallery_source", "gallery_modules_source" });
            return true;
        }
    };
    xp = new StringBuffer(256);
    xp.append(getCommonPath());
    xp.append("/");
    xp.append(CmsSearchConfiguration.N_INDEXES);
    xp.append("/");
    xp.append(CmsSearchConfiguration.N_INDEX);
    xp.append("[");
    xp.append(I_CmsXmlConfiguration.N_NAME);
    xp.append("='").append(CmsGallerySearchIndex.GALLERY_INDEX_NAME).append("']");
    m_actions.put(xp.toString(), action2);
    //
    //=============================================================================================================
    //
    CmsXmlUpdateAction action3 = new CmsXmlUpdateAction() {

        @SuppressWarnings("synthetic-access")
        @Override
        public boolean executeUpdate(Document doc, String xpath, boolean forReal) {

            Node node = doc.selectSingleNode(xpath);
            if (node != null) {
                return false;
            }
            // create doc type
            createIndexSource(doc, xpath, "gallery_source", CmsVfsIndexer.class,
                    new String[] { "/sites/", "/shared/", "/system/galleries/" },
                    new String[] { "xmlpage-galleries", "xmlcontent-galleries", "jsp", "text", "pdf", "rtf",
                            "html", "image", "generic", "openoffice", "msoffice-ole2", "msoffice-ooxml" });
            return true;

        }
    };
    xp = new StringBuffer(256);
    xp.append(getCommonPath());
    xp.append("/");
    xp.append(CmsSearchConfiguration.N_INDEXSOURCES);
    xp.append("/");
    xp.append(CmsSearchConfiguration.N_INDEXSOURCE);
    xp.append("[");
    xp.append(I_CmsXmlConfiguration.N_NAME);
    xp.append("='gallery_source']");
    m_actions.put(xp.toString(), action3);
    //
    //=============================================================================================================
    //
    CmsXmlUpdateAction action4 = new CmsXmlUpdateAction() {

        @Override
        public boolean executeUpdate(Document document, String xpath, boolean forReal) {

            Node node = document.selectSingleNode(xpath);

            if (node != null) {
                node.detach();
            }
            // create field config
            CmsSearchFieldConfiguration fieldConf = new CmsSearchFieldConfiguration();
            fieldConf.setName("gallery_fields");
            fieldConf.setDescription("The standard OpenCms search index field configuration.");
            CmsSearchField field = new CmsSearchField();
            // <field name="content" store="compress" index="true" excerpt="true">
            field.setName("content");
            field.setStored("compress");
            field.setIndexed("true");
            field.setInExcerpt("true");
            field.setDisplayNameForConfiguration("%(key.field.content)");
            // <mapping type="content" />
            CmsSearchFieldMapping mapping = new CmsSearchFieldMapping();
            mapping.setType("content");
            field.addMapping(mapping);
            fieldConf.addField(field);
            // <field name="title-key" store="true" index="untokenized" boost="0.0">
            field = new CmsSearchField();
            field.setName("title-key");
            field.setStored("true");
            field.setIndexed("untokenized");
            field.setBoost("0.0");
            // <mapping type="property">Title</mapping>
            mapping = new CmsSearchFieldMapping();
            mapping.setType("property");
            mapping.setParam("Title");
            field.addMapping(mapping);
            fieldConf.addField(field);
            // <field name="title" store="false" index="true">
            field = new CmsSearchField();
            field.setName("title");
            field.setStored("false");
            field.setIndexed("true");
            field.setDisplayNameForConfiguration("%(key.field.title)");
            // <mapping type="property">Title</mapping>
            mapping = new CmsSearchFieldMapping();
            mapping.setType("property");
            mapping.setParam("Title");
            field.addMapping(mapping);
            fieldConf.addField(field);
            // <field name="description" store="true" index="true">
            field = new CmsSearchField();
            field.setName("description");
            field.setStored("true");
            field.setIndexed("true");
            field.setDisplayNameForConfiguration("%(key.field.description)");
            // <mapping type="property">Description</mapping>
            mapping = new CmsSearchFieldMapping();
            mapping.setType("property");
            mapping.setParam("Description");
            field.addMapping(mapping);
            fieldConf.addField(field);
            // <field name="meta" store="false" index="true">
            field = new CmsSearchField();
            field.setName("meta");
            field.setStored("false");
            field.setIndexed("true");
            // <mapping type="property">Title</mapping>
            mapping = new CmsSearchFieldMapping();
            mapping.setType("property");
            mapping.setParam("Title");
            field.addMapping(mapping);
            // <mapping type="property">Description</mapping>
            mapping = new CmsSearchFieldMapping();
            mapping.setType("property");
            mapping.setParam("Description");
            field.addMapping(mapping);
            fieldConf.addField(field);
            // <field name="res_dateExpired" store="true" index="untokenized">
            field = new CmsSearchField();
            field.setName("res_dateExpired");
            field.setStored("true");
            field.setIndexed("untokenized");
            // <mapping type="attribute">dateExpired</mapping>
            mapping = new CmsSearchFieldMapping();
            mapping.setType("attribute");
            mapping.setParam("dateExpired");
            field.addMapping(mapping);
            fieldConf.addField(field);
            // <field name="res_dateReleased" store="true" index="untokenized">
            field = new CmsSearchField();
            field.setName("res_dateReleased");
            field.setStored("true");
            field.setIndexed("untokenized");
            // <mapping type="attribute">dateReleased</mapping>
            mapping = new CmsSearchFieldMapping();
            mapping.setType("attribute");
            mapping.setParam("dateReleased");
            field.addMapping(mapping);
            fieldConf.addField(field);
            // <field name="res_length" store="true" index="untokenized">
            field = new CmsSearchField();
            field.setName("res_length");
            field.setStored("true");
            field.setIndexed("untokenized");
            // <mapping type="attribute">length</mapping>
            mapping = new CmsSearchFieldMapping();
            mapping.setType("attribute");
            mapping.setParam("length");
            field.addMapping(mapping);
            fieldConf.addField(field);
            // <field name="res_state" store="true" index="untokenized">
            field = new CmsSearchField();
            field.setName("res_state");
            field.setStored("true");
            field.setIndexed("untokenized");
            // <mapping type="attribute">state</mapping>
            mapping = new CmsSearchFieldMapping();
            mapping.setType("attribute");
            mapping.setParam("state");
            field.addMapping(mapping);
            fieldConf.addField(field);
            // <field name="res_structureId" store="true" index="false">
            field = new CmsSearchField();
            field.setName("res_structureId");
            field.setStored("true");
            field.setIndexed("untokenized");
            // <mapping type="attribute">structureId</mapping>
            mapping = new CmsSearchFieldMapping();
            mapping.setType("attribute");
            mapping.setParam("structureId");
            field.addMapping(mapping);
            fieldConf.addField(field);
            // <field name="res_userCreated" store="true" index="untokenized">
            field = new CmsSearchField();
            field.setName("res_userCreated");
            field.setStored("true");
            field.setIndexed("untokenized");
            // <mapping type="attribute">userCreated</mapping>
            mapping = new CmsSearchFieldMapping();
            mapping.setType("attribute");
            mapping.setParam("userCreated");
            field.addMapping(mapping);
            fieldConf.addField(field);
            // <field name="res_userLastModified" store="true" index="untokenized">
            field = new CmsSearchField();
            field.setName("res_userLastModified");
            field.setStored("true");
            field.setIndexed("untokenized");
            // <mapping type="attribute">userLastModified</mapping>
            mapping = new CmsSearchFieldMapping();
            mapping.setType("attribute");
            mapping.setParam("userLastModified");
            field.addMapping(mapping);
            fieldConf.addField(field);
            // <field name="res_locales" store="true" index="true" analyzer="WhitespaceAnalyzer">
            field = new CmsSearchField();
            field.setName("res_locales");
            field.setStored("true");
            field.setIndexed("true");
            try {
                field.setAnalyzer("WhitespaceAnalyzer");
            } catch (Exception e) {
                // ignore
                e.printStackTrace();
            }
            // <mapping type="dynamic" class="org.opencms.search.galleries.CmsGallerySearchFieldMapping">res_locales</mapping>
            mapping = new CmsGallerySearchFieldMapping();
            mapping.setType("dynamic");
            mapping.setParam("res_locales");
            field.addMapping(mapping);
            fieldConf.addField(field);
            // <field name="additional_info" store="true" index="false">
            field = new CmsSearchField();
            field.setName("additional_info");
            field.setStored("true");
            field.setIndexed("false");
            // <mapping type="dynamic" class="org.opencms.search.galleries.CmsGallerySearchFieldMapping">additional_info</mapping>
            mapping = new CmsGallerySearchFieldMapping();
            mapping.setType("dynamic");
            mapping.setParam("additional_info");
            field.addMapping(mapping);
            fieldConf.addField(field);
            // <field name="container_types" store="true" index="true" analyzer="WhitespaceAnalyzer">
            field = new CmsSearchField();
            field.setName("container_types");
            field.setStored("true");
            field.setIndexed("true");
            try {
                field.setAnalyzer("WhitespaceAnalyzer");
            } catch (Exception e) {
                // ignore
                e.printStackTrace();
            }
            // <mapping type="dynamic" class="org.opencms.search.galleries.CmsGallerySearchFieldMapping">container_types</mapping>
            mapping = new CmsGallerySearchFieldMapping();
            mapping.setType("dynamic");
            mapping.setParam("container_types");
            field.addMapping(mapping);
            fieldConf.addField(field);
            createFieldConfig(document, xpath, fieldConf, CmsGallerySearchFieldConfiguration.class);
            return true;
        }
    };

    xp = new StringBuffer(256);
    xp.append(getCommonPath());
    xp.append("/");
    xp.append(CmsSearchConfiguration.N_FIELDCONFIGURATIONS);
    xp.append("/");
    xp.append(CmsSearchConfiguration.N_FIELDCONFIGURATION);
    xp.append("[");
    xp.append(I_CmsXmlConfiguration.N_NAME);
    xp.append("='gallery_fields']");
    m_actions.put(xp.toString(), action4);
    //
    //=============================================================================================================
    //

    m_actions.put("/opencms/search/indexsources", new CmsIndexSourceTypeUpdateAction());

    // use dummy check [1=1] to make the xpaths unique 
    m_actions.put("/opencms/search/indexsources[1=1]", new CmsAddGalleryModuleIndexSourceAction());
    m_actions.put(buildXpathForIndexedDocumentType("source1", "containerpage"),
            createIndexedTypeAction("containerpage"));

    //=============================================================================================================

    String analyzerEnPath = "/opencms/search/analyzers/analyzer[class='org.apache.lucene.analysis.standard.StandardAnalyzer'][locale='en']";
    m_actions.put(analyzerEnPath,
            new ElementReplaceAction(analyzerEnPath,
                    "<analyzer>\n"
                            + "                <class>org.apache.lucene.analysis.en.EnglishAnalyzer</class>\n"
                            + "                <locale>en</locale>\n" + "            </analyzer>"));

    String analyzerItPath = "/opencms/search/analyzers/analyzer[class='org.apache.lucene.analysis.snowball.SnowballAnalyzer'][stemmer='Italian']";
    m_actions.put(analyzerItPath,
            new ElementReplaceAction(analyzerItPath,
                    "<analyzer>\n"
                            + "                <class>org.apache.lucene.analysis.it.ItalianAnalyzer</class>\n"
                            + "                <locale>it</locale>\n" + "            </analyzer>"));

    m_actions.put(
            "/opencms/search/indexsources/indexsource[name='gallery_source']/resources['systemgalleries'='systemgalleries']",
            new CmsAddIndexSourceResourceAction());
}

From source file:org.opencms.xml.content.CmsXmlContent.java

License:Open Source License

/**
 * Processes a document node and extracts the values of the node according to the provided XML
 * content definition.<p> /*  w ww.j  a  v a 2 s  . com*/
 * 
 * @param root the root node element to process
 * @param rootPath the Xpath of the root node in the document
 * @param locale the locale 
 * @param definition the XML content definition to use for processing the values
 */
protected void processSchemaNode(Element root, String rootPath, Locale locale,
        CmsXmlContentDefinition definition) {

    // iterate all XML nodes 
    List<Node> content = CmsXmlGenericWrapper.content(root);
    for (int i = content.size() - 1; i >= 0; i--) {
        Node node = content.get(i);
        if (!(node instanceof Element)) {
            // this node is not an element, so it must be a white space text node, remove it
            node.detach();
        } else {
            // node must be an element 
            Element element = (Element) node;
            String name = element.getName();
            int xpathIndex = CmsXmlUtils.getXpathIndexInt(element.getUniquePath(root));

            // build the Xpath expression for the current node
            String path;
            if (rootPath != null) {
                StringBuffer b = new StringBuffer(rootPath.length() + name.length() + 6);
                b.append(rootPath);
                b.append('/');
                b.append(CmsXmlUtils.createXpathElement(name, xpathIndex));
                path = b.toString();
            } else {
                path = CmsXmlUtils.createXpathElement(name, xpathIndex);
            }

            // create a XML content value element
            I_CmsXmlSchemaType schemaType = definition.getSchemaType(name);

            if (schemaType != null) {
                // directly add simple type to schema
                I_CmsXmlContentValue value = schemaType.createValue(this, element, locale);
                addBookmark(path, locale, true, value);

                if (!schemaType.isSimpleType()) {
                    // recurse for nested schema
                    CmsXmlNestedContentDefinition nestedSchema = (CmsXmlNestedContentDefinition) schemaType;
                    processSchemaNode(element, path, locale, nestedSchema.getNestedContentDefinition());
                }
            } else {
                // unknown XML node name according to schema
                if (LOG.isWarnEnabled()) {
                    LOG.warn(Messages.get().getBundle().key(Messages.LOG_XMLCONTENT_INVALID_ELEM_2, name,
                            definition.getSchemaLocation()));
                }
            }
        }
    }
}