Example usage for org.dom4j Element getTextTrim

List of usage examples for org.dom4j Element getTextTrim

Introduction

In this page you can find the example usage for org.dom4j Element getTextTrim.

Prototype

String getTextTrim();

Source Link

Document

DOCUMENT ME!

Usage

From source file:org.onecmdb.ui.gwt.desktop.server.transform.QueryParser.java

License:Open Source License

/**
 * XML helper functions//from w w w.  j  a v a  2 s . c  om
 */
private String getElementValue(Element sel, String elementName, boolean requiered) {

    Element el = sel.element(elementName);
    if (el == null) {
        if (requiered) {
            throw new IllegalArgumentException("Element <" + elementName + "> is missing in <" + sel.getName()
                    + "> [" + sel.getPath() + "]");
        }
        return (null);
    }
    String text = el.getTextTrim();
    if (requiered && (text == null || text.length() == 0)) {
        throw new IllegalArgumentException("Element <" + elementName + "> has no value in <" + sel.getName()
                + "> [" + sel.getPath() + "]");
    }
    text = subsituteAttr(text);
    return (text);
}

From source file:org.onecmdb.utils.xml.XMLUtils.java

License:Open Source License

/**
 * XML helper functions/*from  ww  w  .ja  v a 2  s  . c o m*/
 */
public static String getElementValue(Map<String, String> attrMap, Element sel, String elementName,
        boolean requiered) {

    Element el = sel.element(elementName);
    if (el == null) {
        if (requiered) {
            throw new IllegalArgumentException("Element <" + elementName + "> is missing in <" + sel.getName()
                    + "> [" + sel.getPath() + "]");
        }
        return (null);
    }
    String text = el.getTextTrim();
    if (requiered && (text == null || text.length() == 0)) {
        throw new IllegalArgumentException("Element <" + elementName + "> has no value in <" + sel.getName()
                + "> [" + sel.getPath() + "]");
    }
    text = subsituteAttr(attrMap, text);
    return (text);
}

From source file:org.openadaptor.util.hosting.HostedFile.java

License:Open Source License

private void setFields(Element tr) {
    //Name field/*ww  w .j a  v  a2  s . c  om*/
    Element anchor = (Element) tr.selectSingleNode(NAME_XPATH); // XPath is 1-origin
    setName(anchor.getTextTrim());
    //path field
    String path = anchor.attributeValue(HREF_TAG);
    if ((path != null) && (path.startsWith(PATH_PREFIX))) {
        setPath(path);
    } else {
        HostedConnection.fail("Failed to derive path for file from:" + path);
    }
    setStatus(getTableDataValue(tr, STATUS_INDEX));
    setDescription(getTableDataValue(tr, DESCRIPTION_INDEX));
    setId(extractId((Element) tr.selectSingleNode(LINK_XPATH)));
}

From source file:org.openadaptor.util.hosting.HostedFolder.java

License:Open Source License

public List getSubFolders() {
    Document document = fetchDocument(); //Refresh the document.
    log.debug("Fetching subfolders for " + getName());
    Element current = (Element) document.selectSingleNode(FOLDER_NODE_SELECT_XPATH);
    List subFolders = new ArrayList();
    List currentList = (List) current.selectNodes(SUBFOLDER_LIST_NODES_XPATH);
    Iterator iter = currentList.iterator();
    while (iter.hasNext()) {
        Element anchor = (Element) iter.next();
        String name = anchor.getTextTrim();
        // The current CEE has '(<number of files>)' at the end of each folder
        // so we need to go backwards and find the last '(' and remove everything
        // from there.
        int index = name.lastIndexOf("(");
        if (index != -1)
            name = name.substring(0, index - 1);
        String href = anchor.attributeValue("href");

        int sidx = href.indexOf("?folderID=");
        int eidx = href.indexOf("&expandFolder=");
        if (sidx == -1 || eidx == -1) {
            log.warn("Failed to parse the link " + href);
        }//  w  w w.  jav a2s  .c  o m

        int id = Integer.parseInt(href.substring(sidx + 10, eidx)); // 10 = "?folderID=".length()
        HostedFolder subFolder = new HostedFolder(this, name, null, id);
        subFolders.add(subFolder);
    }
    log.debug("Fetched " + subFolders.size() + " subfolders.");
    return subFolders;
}

From source file:org.opencms.importexport.A_CmsImport.java

License:Open Source License

/**
 * Returns the value of a child element with a specified name for a given parent element.<p>
 *
 * @param parentElement the parent element
 * @param elementName the child element name
 * /*www . j a  v a2 s.  co  m*/
 * @return the value of the child node, or null if something went wrong
 */
public String getChildElementTextValue(Element parentElement, String elementName) {

    try {
        // get the first child element matching the specified name
        Element childElement = (Element) parentElement.selectNodes("./" + elementName).get(0);
        // return the value of the child element
        return childElement.getTextTrim();
    } catch (Exception e) {
        return null;
    }
}

From source file:org.opencms.importexport.CmsImportVersion2.java

License:Open Source License

/**
 * Merges a single page.<p>/* w w  w.j av  a  2s.  c  om*/
 * 
 * @param resourcename the resource name of the page
 * @throws CmsImportExportException if something goes wrong
 * @throws CmsXmlException if the page file could not be unmarshalled 
 */
private void mergePageFile(String resourcename) throws CmsXmlException, CmsImportExportException {

    try {

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_START_MERGING_1, resourcename));
        }

        // in OpenCms versions <5 node names have not been case sensitive. thus, nodes are read both in upper
        // and lower case letters, or have to be tested for equality ignoring upper/lower case...

        // get the header file
        CmsFile pagefile = m_cms.readFile(resourcename, CmsResourceFilter.ALL);
        Document contentXml = CmsXmlUtils.unmarshalHelper(pagefile.getContents(), null);

        // get the <masterTemplate> node to check the content. this node contains the name of the template file.
        String masterTemplateNodeName = "//masterTemplate";
        Node masterTemplateNode = contentXml.selectSingleNode(masterTemplateNodeName);
        if (masterTemplateNode == null) {
            masterTemplateNode = contentXml.selectSingleNode(masterTemplateNodeName.toLowerCase());
        }
        if (masterTemplateNode == null) {
            masterTemplateNode = contentXml.selectSingleNode(masterTemplateNodeName.toUpperCase());
        }

        // there is only one <masterTemplate> allowed
        String mastertemplate = null;
        if (masterTemplateNode != null) {
            // get the name of the mastertemplate
            mastertemplate = masterTemplateNode.getText().trim();
        }

        // get the <ELEMENTDEF> nodes to check the content.
        // this node contains the information for the body element.
        String elementDefNodeName = "//ELEMENTDEF";
        Node bodyNode = contentXml.selectSingleNode(elementDefNodeName);
        if (bodyNode == null) {
            bodyNode = contentXml.selectSingleNode(elementDefNodeName.toLowerCase());
        }

        // there is only one <ELEMENTDEF> allowed
        if (bodyNode != null) {

            String bodyclass = null;
            String bodyname = null;
            Map bodyparams = null;

            List nodes = ((Element) bodyNode).elements();
            for (int i = 0, n = nodes.size(); i < n; i++) {

                Node node = (Node) nodes.get(i);

                if ("CLASS".equalsIgnoreCase(node.getName())) {
                    bodyclass = node.getText().trim();
                } else if ("TEMPLATE".equalsIgnoreCase(node.getName())) {
                    bodyname = node.getText().trim();
                    if (!bodyname.startsWith("/")) {
                        bodyname = CmsResource.getFolderPath(resourcename) + bodyname;
                    }
                } else if ("PARAMETER".equalsIgnoreCase(node.getName())) {
                    Element paramElement = (Element) node;
                    if (bodyparams == null) {
                        bodyparams = new HashMap();
                    }
                    bodyparams.put((paramElement.attribute("name")).getText(), paramElement.getTextTrim());
                }
            }

            if ((mastertemplate == null) || (bodyname == null)) {

                CmsMessageContainer message = Messages.get().container(
                        Messages.ERR_IMPORTEXPORT_ERROR_CANNOT_MERGE_PAGE_FILE_3, resourcename, mastertemplate,
                        bodyname);
                if (LOG.isDebugEnabled()) {
                    LOG.debug(message.key());
                }

                throw new CmsImportExportException(message);
            }

            // lock the resource, so that it can be manipulated
            m_cms.lockResource(resourcename);

            // get all properties                               
            List properties = m_cms.readPropertyObjects(resourcename, false);

            // now get the content of the bodyfile and insert it into the control file                   
            CmsFile bodyfile = m_cms.readFile(bodyname, CmsResourceFilter.IGNORE_EXPIRATION);

            //get the encoding
            String encoding = CmsProperty.get(CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, properties)
                    .getValue();
            if (encoding == null) {
                encoding = OpenCms.getSystemInfo().getDefaultEncoding();
            }

            if (m_convertToXmlPage) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug(Messages.get().getBundle()
                            .key(Messages.LOG_IMPORTEXPORT_START_CONVERTING_TO_XML_0));
                }

                CmsXmlPage xmlPage = CmsXmlPageConverter.convertToXmlPage(m_cms, bodyfile.getContents(),
                        getLocale(resourcename, properties), encoding);

                if (LOG.isDebugEnabled()) {
                    LOG.debug(
                            Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_END_CONVERTING_TO_XML_0));
                }

                if (xmlPage != null) {
                    pagefile.setContents(xmlPage.marshal());

                    // set the type to xml page
                    pagefile.setType(CmsResourceTypeXmlPage.getStaticTypeId());
                }
            }

            // add the template and other required properties
            CmsProperty newProperty = new CmsProperty(CmsPropertyDefinition.PROPERTY_TEMPLATE, mastertemplate,
                    null);
            // property lists must not contain equal properties
            properties.remove(newProperty);
            properties.add(newProperty);

            // if set, add the bodyclass as property
            if (CmsStringUtil.isNotEmpty(bodyclass)) {
                newProperty = new CmsProperty(CmsPropertyDefinition.PROPERTY_TEMPLATE, mastertemplate, null);
                newProperty.setAutoCreatePropertyDefinition(true);
                properties.remove(newProperty);
                properties.add(newProperty);
            }
            // if set, add bodyparams as properties
            if (bodyparams != null) {
                for (Iterator p = bodyparams.entrySet().iterator(); p.hasNext();) {
                    Map.Entry entry = (Map.Entry) p.next();
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    newProperty = new CmsProperty(key, value, null);
                    newProperty.setAutoCreatePropertyDefinition(true);
                    properties.remove(newProperty);
                    properties.add(newProperty);
                }
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_START_IMPORTING_XML_PAGE_0));
            }

            // now import the resource
            m_cms.importResource(resourcename, pagefile, pagefile.getContents(), properties);

            // finally delete the old body file, it is not needed anymore
            m_cms.lockResource(bodyname);
            m_cms.deleteResource(bodyname, CmsResource.DELETE_PRESERVE_SIBLINGS);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_END_IMPORTING_XML_PAGE_0));
            }

            m_report.println(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
                    I_CmsReport.FORMAT_OK);

        } else {

            // there are more than one template nodes in this control file
            // convert the resource into a plain text file
            // lock the resource, so that it can be manipulated
            m_cms.lockResource(resourcename);
            // set the type to plain
            pagefile.setType(CmsResourceTypePlain.getStaticTypeId());
            // write all changes                     
            m_cms.writeFile(pagefile);
            // done, unlock the resource                   
            m_cms.unlockResource(resourcename);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle()
                        .key(Messages.LOG_IMPORTEXPORT_CANNOT_CONVERT_XML_STRUCTURE_1, resourcename));
            }

            m_report.println(Messages.get().container(Messages.RPT_NOT_CONVERTED_0), I_CmsReport.FORMAT_OK);

        }

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_END_MERGING_1, resourcename));
        }
    } catch (CmsXmlException e) {

        throw e;
    } catch (CmsException e) {

        m_report.println(e);

        CmsMessageContainer message = Messages.get()
                .container(Messages.ERR_IMPORTEXPORT_ERROR_MERGING_PAGE_FILE_1, resourcename);
        if (LOG.isDebugEnabled()) {
            LOG.debug(message.key(), e);
        }

        throw new CmsImportExportException(message, e);
    }

}

From source file:org.opencms.importexport.CmsImportVersion6.java

License:Open Source License

/**
 * Imports the OpenCms users.<p>/*from   www.  ja  v a2 s .c  om*/
 * 
 * @throws CmsImportExportException if something goes wrong
 */
@Override
protected void importUsers() throws CmsImportExportException {

    try {
        // getAll user nodes
        List userNodes = m_docXml.selectNodes("//" + A_CmsImport.N_USERDATA);
        // walk threw all groups in manifest
        for (int i = 0; i < userNodes.size(); i++) {
            Element currentElement = (Element) userNodes.get(i);

            String name = getChildElementTextValue(currentElement, A_CmsImport.N_NAME);
            name = OpenCms.getImportExportManager().translateUser(name);

            // decode passwords using base 64 decoder
            String pwd = getChildElementTextValue(currentElement, A_CmsImport.N_PASSWORD);
            String password = new String(Base64.decodeBase64(pwd.trim().getBytes()));

            String flags = getChildElementTextValue(currentElement, A_CmsImport.N_FLAGS);
            String firstname = getChildElementTextValue(currentElement, A_CmsImport.N_FIRSTNAME);
            String lastname = getChildElementTextValue(currentElement, A_CmsImport.N_LASTNAME);
            String email = getChildElementTextValue(currentElement, A_CmsImport.N_EMAIL);
            long dateCreated = Long
                    .parseLong(getChildElementTextValue(currentElement, A_CmsImport.N_DATECREATED));

            // get the userinfo and put it into the additional info map
            Map userInfo = new HashMap();
            Iterator itInfoNodes = currentElement
                    .selectNodes("./" + A_CmsImport.N_USERINFO + "/" + A_CmsImport.N_USERINFO_ENTRY).iterator();
            while (itInfoNodes.hasNext()) {
                Element infoEntryNode = (Element) itInfoNodes.next();
                String key = infoEntryNode.attributeValue(A_CmsImport.A_NAME);
                String type = infoEntryNode.attributeValue(A_CmsImport.A_TYPE);
                String value = infoEntryNode.getTextTrim();
                userInfo.put(key, CmsDataTypeUtil.dataImport(value, type));
            }

            // get the groups of the user and put them into the list
            List groupNodes = currentElement.selectNodes("*/" + A_CmsImport.N_GROUPNAME);
            List userGroups = new ArrayList();
            for (int j = 0; j < groupNodes.size(); j++) {
                Element currentGroup = (Element) groupNodes.get(j);
                String userInGroup = getChildElementTextValue(currentGroup, A_CmsImport.N_NAME);
                userInGroup = OpenCms.getImportExportManager().translateGroup(userInGroup);
                userGroups.add(userInGroup);
            }

            // import this user
            importUser(name, flags, password, firstname, lastname, email, dateCreated, userInfo, userGroups);
        }
    } catch (CmsImportExportException e) {
        throw e;
    } catch (Exception e) {
        m_report.println(e);
        CmsMessageContainer message = Messages.get()
                .container(Messages.ERR_IMPORTEXPORT_ERROR_IMPORTING_USERS_0);
        if (LOG.isDebugEnabled()) {
            LOG.debug(message.key(), e);
        }
        throw new CmsImportExportException(message, e);
    }
}

From source file:org.opencms.xml.containerpage.CmsXmlGroupContainer.java

License:Open Source License

/**
 * @see org.opencms.xml.A_CmsXmlDocument#initDocument(org.dom4j.Document, java.lang.String, org.opencms.xml.CmsXmlContentDefinition)
 *///w  ww.jav  a2s.c o  m
@Override
protected void initDocument(Document document, String encoding, CmsXmlContentDefinition definition) {

    m_document = document;
    m_contentDefinition = definition;
    m_encoding = CmsEncoder.lookupEncoding(encoding, encoding);
    m_elementLocales = new HashMap<String, Set<Locale>>();
    m_elementNames = new HashMap<Locale, Set<String>>();
    m_locales = new HashSet<Locale>();
    m_groupContainers = new HashMap<Locale, CmsGroupContainerBean>();
    clearBookmarks();

    // initialize the bookmarks
    for (Iterator<Element> itGroupContainers = CmsXmlGenericWrapper
            .elementIterator(m_document.getRootElement()); itGroupContainers.hasNext();) {
        Element cntPage = itGroupContainers.next();

        try {
            Locale locale = CmsLocaleManager.getLocale(
                    cntPage.attribute(CmsXmlContentDefinition.XSD_ATTRIBUTE_VALUE_LANGUAGE).getValue());

            addLocale(locale);
            Element groupContainer = cntPage.element(XmlNode.GroupContainers.name());

            // container itself
            int cntIndex = CmsXmlUtils.getXpathIndexInt(groupContainer.getUniquePath(cntPage));
            String cntPath = CmsXmlUtils.createXpathElement(groupContainer.getName(), cntIndex);
            I_CmsXmlSchemaType cntSchemaType = definition.getSchemaType(groupContainer.getName());
            I_CmsXmlContentValue cntValue = cntSchemaType.createValue(this, groupContainer, locale);
            addBookmark(cntPath, locale, true, cntValue);
            CmsXmlContentDefinition cntDef = ((CmsXmlNestedContentDefinition) cntSchemaType)
                    .getNestedContentDefinition();

            //title
            Element title = groupContainer.element(XmlNode.Title.name());
            addBookmarkForElement(title, locale, groupContainer, cntPath, cntDef);

            //description
            Element description = groupContainer.element(XmlNode.Description.name());
            addBookmarkForElement(description, locale, groupContainer, cntPath, cntDef);

            // types
            Set<String> types = new HashSet<String>();
            for (Iterator<Element> itTypes = CmsXmlGenericWrapper.elementIterator(groupContainer,
                    XmlNode.Type.name()); itTypes.hasNext();) {
                Element type = itTypes.next();
                addBookmarkForElement(type, locale, groupContainer, cntPath, cntDef);
                String typeName = type.getTextTrim();
                if (!CmsStringUtil.isEmptyOrWhitespaceOnly(typeName)) {
                    types.add(typeName);
                }
            }

            List<CmsContainerElementBean> elements = new ArrayList<CmsContainerElementBean>();
            // Elements
            for (Iterator<Element> itElems = CmsXmlGenericWrapper.elementIterator(groupContainer,
                    XmlNode.Element.name()); itElems.hasNext();) {
                Element element = itElems.next();

                // element itself
                int elemIndex = CmsXmlUtils.getXpathIndexInt(element.getUniquePath(groupContainer));
                String elemPath = CmsXmlUtils.concatXpath(cntPath,
                        CmsXmlUtils.createXpathElement(element.getName(), elemIndex));
                I_CmsXmlSchemaType elemSchemaType = cntDef.getSchemaType(element.getName());
                I_CmsXmlContentValue elemValue = elemSchemaType.createValue(this, element, locale);
                addBookmark(elemPath, locale, true, elemValue);
                CmsXmlContentDefinition elemDef = ((CmsXmlNestedContentDefinition) elemSchemaType)
                        .getNestedContentDefinition();

                // uri
                Element uri = element.element(XmlNode.Uri.name());
                addBookmarkForElement(uri, locale, element, elemPath, elemDef);
                Element uriLink = uri.element(CmsXmlPage.NODE_LINK);
                CmsUUID elementId = null;
                if (uriLink == null) {
                    // this can happen when adding the elements node to the xml content
                    // it is not dangerous since the link has to be set before saving 
                } else {
                    elementId = new CmsLink(uriLink).getStructureId();
                }

                //                    Element createNewElement = element.element(CmsXmlContainerPage.XmlNode.CreateNew.name());
                //                    boolean createNew = (createNewElement != null)
                //                        && Boolean.parseBoolean(createNewElement.getStringValue());

                // propeties
                Map<String, String> propertiesMap = CmsXmlContentPropertyHelper.readProperties(this, locale,
                        element, elemPath, elemDef);

                if (elementId != null) {
                    elements.add(new CmsContainerElementBean(elementId, null, propertiesMap, false));
                }
            }
            m_groupContainers.put(locale,
                    new CmsGroupContainerBean(title.getText(), description.getText(), elements, types));
        } catch (NullPointerException e) {
            LOG.error(org.opencms.xml.content.Messages.get().getBundle()
                    .key(org.opencms.xml.content.Messages.LOG_XMLCONTENT_INIT_BOOKMARKS_0), e);
        }
    }
}

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

License:Open Source License

/**
 * Initializes the resource bundle to use for localized messages in this content handler.<p>
 * /*from  w w  w  . j  a v a  2s  .  co  m*/
 * @param root the "resourcebundle" element from the appinfo node of the XML content definition
 * @param contentDefinition the content definition the validation rules belong to
 * @param single if <code>true</code> we process the classic sinle line entry, otherwise it's the multiple line setting
 * 
 * @throws CmsXmlException if something goes wrong
 */
protected void initResourceBundle(Element root, CmsXmlContentDefinition contentDefinition, boolean single)
        throws CmsXmlException {

    if (m_messageBundleNames == null) {
        // it's uncommon to have more then one bundle so just initialize an array length of 2
        m_messageBundleNames = new ArrayList<String>(2);
    }

    if (single) {
        // single "resourcebundle" node

        String messageBundleName = root.attributeValue(APPINFO_ATTR_NAME);
        if (messageBundleName == null) {
            throw new CmsXmlException(
                    Messages.get().container(Messages.ERR_XMLCONTENT_MISSING_RESOURCE_BUNDLE_NAME_2,
                            root.getName(), contentDefinition.getSchemaLocation()));
        }
        if (!m_messageBundleNames.contains(messageBundleName)) {
            // avoid duplicates
            m_messageBundleNames.add(messageBundleName);
        }
        // clear the cached resource bundles for this bundle
        CmsResourceBundleLoader.flushBundleCache(messageBundleName);

    } else {
        // multiple "resourcebundles" node

        // get an iterator for all "propertybundle" subnodes
        Iterator<Element> propertybundles = CmsXmlGenericWrapper.elementIterator(root, APPINFO_PROPERTYBUNDLE);
        while (propertybundles.hasNext()) {
            // iterate all "propertybundle" elements in the "resourcebundle" node
            Element propBundle = propertybundles.next();
            String propertyBundleName = propBundle.attributeValue(APPINFO_ATTR_NAME);
            if (!m_messageBundleNames.contains(propertyBundleName)) {
                // avoid duplicates
                m_messageBundleNames.add(propertyBundleName);
            }
            // clear the cached resource bundles for this bundle
            CmsResourceBundleLoader.flushBundleCache(propertyBundleName);
        }

        // get an iterator for all "xmlbundle" subnodes
        Iterator<Element> xmlbundles = CmsXmlGenericWrapper.elementIterator(root, APPINFO_XMLBUNDLE);
        while (xmlbundles.hasNext()) {
            Element xmlbundle = xmlbundles.next();
            String xmlBundleName = xmlbundle.attributeValue(APPINFO_ATTR_NAME);
            // cache the bundle from the XML
            if (!m_messageBundleNames.contains(xmlBundleName)) {
                // avoid duplicates
                m_messageBundleNames.add(xmlBundleName);
            }
            // clear the cached resource bundles for this bundle
            CmsResourceBundleLoader.flushBundleCache(xmlBundleName);
            Iterator<Element> bundles = CmsXmlGenericWrapper.elementIterator(xmlbundle, APPINFO_BUNDLE);
            while (bundles.hasNext()) {
                // iterate all "bundle" elements in the "xmlbundle" node
                Element bundle = bundles.next();
                String localeStr = bundle.attributeValue(APPINFO_ATTR_LOCALE);
                Locale locale;
                if (CmsStringUtil.isEmptyOrWhitespaceOnly(localeStr)) {
                    // no locale set, so use no locale
                    locale = null;
                } else {
                    // use provided locale
                    locale = CmsLocaleManager.getLocale(localeStr);
                }
                if (CmsLocaleManager.getDefaultLocale().equals(locale)) {
                    // in case the default locale is given, we store this as root
                    locale = null;
                }

                CmsListResourceBundle xmlBundle = null;

                Iterator<Element> resources = CmsXmlGenericWrapper.elementIterator(bundle, APPINFO_RESOURCE);
                while (resources.hasNext()) {
                    // now collect all resource bundle keys
                    Element resource = resources.next();
                    String key = resource.attributeValue(APPINFO_ATTR_KEY);
                    String value = resource.attributeValue(APPINFO_ATTR_VALUE);
                    if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) {
                        // read from inside XML tag if value attribute is not set
                        value = resource.getTextTrim();
                    }
                    if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(key)
                            && CmsStringUtil.isNotEmptyOrWhitespaceOnly(value)) {
                        if (xmlBundle == null) {
                            // use lazy initilaizing of the bundle
                            xmlBundle = new CmsListResourceBundle();
                        }
                        xmlBundle.addMessage(key.trim(), value.trim());
                    }
                }
                if (xmlBundle != null) {
                    CmsResourceBundleLoader.addBundleToCache(xmlBundleName, locale, xmlBundle);
                }
            }
        }
    }
}

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

License:Open Source License

/**
 * Reads the properties from property-enabled xml content values.<p>
 * /* ww w  . jav a 2  s .  c o m*/
 * @param xmlContent the xml content
 * @param locale the current locale
 * @param element the xml element
 * @param elemPath the xpath
 * @param elemDef the element definition
 * 
 * @return the read property map
 * 
 * @see org.opencms.xml.containerpage.CmsXmlContainerPage.XmlNode#Elements
 */
public static Map<String, String> readProperties(CmsXmlContent xmlContent, Locale locale, Element element,
        String elemPath, CmsXmlContentDefinition elemDef) {

    Map<String, String> propertiesMap = new HashMap<String, String>();
    // Properties
    for (Iterator<Element> itProps = CmsXmlGenericWrapper.elementIterator(element,
            CmsXmlContentProperty.XmlNode.Properties.name()); itProps.hasNext();) {
        Element property = itProps.next();

        // property itself
        int propIndex = CmsXmlUtils.getXpathIndexInt(property.getUniquePath(element));
        String propPath = CmsXmlUtils.concatXpath(elemPath,
                CmsXmlUtils.createXpathElement(property.getName(), propIndex));
        I_CmsXmlSchemaType propSchemaType = elemDef.getSchemaType(property.getName());
        I_CmsXmlContentValue propValue = propSchemaType.createValue(xmlContent, property, locale);
        xmlContent.addBookmarkForValue(propValue, propPath, locale, true);
        CmsXmlContentDefinition propDef = ((CmsXmlNestedContentDefinition) propSchemaType)
                .getNestedContentDefinition();

        // name
        Element propName = property.element(CmsXmlContentProperty.XmlNode.Name.name());
        xmlContent.addBookmarkForElement(propName, locale, property, propPath, propDef);

        // choice value 
        Element value = property.element(CmsXmlContentProperty.XmlNode.Value.name());
        if (value == null) {
            // this can happen when adding the elements node to the xml content
            continue;
        }
        int valueIndex = CmsXmlUtils.getXpathIndexInt(value.getUniquePath(property));
        String valuePath = CmsXmlUtils.concatXpath(propPath,
                CmsXmlUtils.createXpathElement(value.getName(), valueIndex));
        I_CmsXmlSchemaType valueSchemaType = propDef.getSchemaType(value.getName());
        I_CmsXmlContentValue valueValue = valueSchemaType.createValue(xmlContent, value, locale);
        xmlContent.addBookmarkForValue(valueValue, valuePath, locale, true);
        CmsXmlContentDefinition valueDef = ((CmsXmlNestedContentDefinition) valueSchemaType)
                .getNestedContentDefinition();

        String val = null;
        Element string = value.element(CmsXmlContentProperty.XmlNode.String.name());
        if (string != null) {
            // string value
            xmlContent.addBookmarkForElement(string, locale, value, valuePath, valueDef);
            val = string.getTextTrim();
        } else {
            // file list value
            Element valueFileList = value.element(CmsXmlContentProperty.XmlNode.FileList.name());
            if (valueFileList == null) {
                // this can happen when adding the elements node to the xml content
                continue;
            }
            int valueFileListIndex = CmsXmlUtils.getXpathIndexInt(valueFileList.getUniquePath(value));
            String valueFileListPath = CmsXmlUtils.concatXpath(valuePath,
                    CmsXmlUtils.createXpathElement(valueFileList.getName(), valueFileListIndex));
            I_CmsXmlSchemaType valueFileListSchemaType = valueDef.getSchemaType(valueFileList.getName());
            I_CmsXmlContentValue valueFileListValue = valueFileListSchemaType.createValue(xmlContent,
                    valueFileList, locale);
            xmlContent.addBookmarkForValue(valueFileListValue, valueFileListPath, locale, true);
            CmsXmlContentDefinition valueFileListDef = ((CmsXmlNestedContentDefinition) valueFileListSchemaType)
                    .getNestedContentDefinition();

            List<CmsUUID> idList = new ArrayList<CmsUUID>();
            // files
            for (Iterator<Element> itFiles = CmsXmlGenericWrapper.elementIterator(valueFileList,
                    CmsXmlContentProperty.XmlNode.Uri.name()); itFiles.hasNext();) {

                Element valueUri = itFiles.next();
                xmlContent.addBookmarkForElement(valueUri, locale, valueFileList, valueFileListPath,
                        valueFileListDef);
                Element valueUriLink = valueUri.element(CmsXmlPage.NODE_LINK);
                CmsUUID fileId = null;
                if (valueUriLink == null) {
                    // this can happen when adding the elements node to the xml content
                    // it is not dangerous since the link has to be set before saving 
                } else {
                    fileId = new CmsLink(valueUriLink).getStructureId();
                    idList.add(fileId);
                }
            }
            // comma separated list of UUIDs
            val = CmsStringUtil.listAsString(idList, CmsXmlContentProperty.PROP_SEPARATOR);
        }

        propertiesMap.put(propName.getTextTrim(), val);
    }
    return propertiesMap;
}