Unmarshals the XML content and adds the file to the bundle files.
@throws CmsException thrown if reading the file or unmarshaling fails.
169971
private void initXmlBundle() throws CmsException {

        CmsFile file = m_cms.readFile(m_resource);
        m_bundleFiles.put(null, m_resource);
        m_xmlBundle = CmsXmlContentFactory.unmarshal(m_cms, file);
        initKeySetForXmlBundle();

    }
646489
protected String getContentAsString(CmsFile file) throws CmsException {

        CmsProperty p = m_cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true);
        String e = p.getValue();
        if (e == null) {
            e = OpenCms.getSystemInfo().getDefaultEncoding();
        }
        return CmsEncoder.createString(file.getContents(), e);
    }
282561
protected void doLoadNextFile() throws CmsException {

        super.doLoadNextResource();
        if (m_resource == null) {
            return;
        }

        // upgrade the resource to a file
        CmsFile file = m_cms.readFile(m_resource);

        // unmarshal the XML content from the resource, don't use unmarshal(CmsObject, CmsResource)
        // as no support for getting the historic version that has been cached by a CmsHistoryResourceHandler
        // will come from there!
        m_content = CmsXmlContentFactory.unmarshal(m_cms, file, pageContext.getRequest());

        // check if locale is available
        m_contentLocale = m_locale;
        if (!m_content.hasLocale(m_contentLocale)) {
            Iterator<Locale> it = OpenCms.getLocaleManager().getDefaultLocales().iterator();
            while (it.hasNext()) {
                Locale locale = it.next();
                if (m_content.hasLocale(locale)) {
                    // found a matching locale
                    m_contentLocale = locale;
                    break;
                }
            }
        }
    }
342711
protected void load() throws FileNotFoundException {
        XMLObjectReader reader = null;
        try {
            reader = XMLObjectReader.newInstance(new FileInputStream(persistFile.toString()));

            reader.setBinding(binding);
            load(reader);
        } catch (XMLStreamException ex) {
            // this.logger.info(
            // "Error while re-creating Linksets from persisted file", ex);
        }
    }
632093
public void write(String xmlFilename) throws CmsXmlException {

        // try to get it from the cache
        Document document = m_cache.get(xmlFilename);

        if (document != null) {
            try {
                CmsXmlUtils.validateXmlStructure(document, CmsEncoder.ENCODING_UTF_8, new CmsXmlEntityResolver(null));
                OutputStream out = null;
                out = new FileOutputStream(getFile(xmlFilename));
                CmsXmlUtils.marshal(document, out, CmsEncoder.ENCODING_UTF_8);
            } catch (FileNotFoundException e) {
                throw new CmsXmlException(new CmsMessageContainer(null, e.toString()));
            } catch (CmsXmlException e) {
                // write invalid config files to the file system with a prefix of "invalid-" so they can be inspected for errors
                try {
                    OutputStream invalidOut = new FileOutputStream(getFile("invalid-" + xmlFilename));
                    CmsXmlUtils.marshal(document, invalidOut, CmsEncoder.ENCODING_UTF_8);
                } catch (IOException e2) {
                    // ignore

                }
                throw e;
            }
        }
    }
825816
protected void saveData() throws CmsException {

        CmsObject cms = m_context.getCms();
        for (CmsResource resource : m_context.getResources()) {
            CmsLockActionRecord actionRecord = null;
            try {
                actionRecord = CmsLockUtil.ensureLock(m_context.getCms(), resource);

                String secureValue = (String)m_secureField.getValue();
                String exportValue = (String)m_exportField.getValue();
                String exportname = m_exportNameField.getValue();
                CmsProperty secureProp = new CmsProperty(CmsPropertyDefinition.PROPERTY_SECURE, secureValue, null);
                CmsProperty exportProp = new CmsProperty(CmsPropertyDefinition.PROPERTY_EXPORT, exportValue, null);
                CmsProperty exportNameProp = new CmsProperty(
                    CmsPropertyDefinition.PROPERTY_EXPORTNAME,
                    exportname,
                    null);
                boolean internal = m_internalField.getValue().booleanValue();

                cms.writePropertyObjects(resource, Arrays.asList(secureProp, exportProp, exportNameProp));
                resource.setInternal(internal);
                cms.writeResource(resource);
            } finally {
                if ((actionRecord != null) && (actionRecord.getChange() == LockChange.locked)) {
                    try {
                        cms.unlockResource(resource);
                    } catch (CmsLockException e) {
                        LOG.warn(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
    }
370675
private void saveToBundleDescriptor() throws CmsException {

        if (null != m_descFile) {
            m_removeDescriptorOnCancel = false;
            updateBundleDescriptorContent();
            m_descFile.getFile().setContents(m_descContent.marshal());
            m_cms.writeFile(m_descFile.getFile());
        }
    }
261092
public CmsFile correctXmlStructure(CmsObject cms) throws CmsXmlException {

        // apply XSD schema translation
        Attribute schema = m_document.getRootElement().attribute(
            I_CmsXmlSchemaType.XSI_NAMESPACE_ATTRIBUTE_NO_SCHEMA_LOCATION);
        if (schema != null) {
            String schemaLocation = schema.getValue();
            String translatedSchema = OpenCms.getResourceManager().getXsdTranslator().translateResource(schemaLocation);
            if (!schemaLocation.equals(translatedSchema)) {
                schema.setValue(translatedSchema);
            }
        }
        updateLocaleNodeSorting();

        // iterate over all locales
        Iterator<Locale> i = m_locales.iterator();
        while (i.hasNext()) {
            Locale locale = i.next();
            List<String> names = getNames(locale);
            List<I_CmsXmlContentValue> validValues = new ArrayList<I_CmsXmlContentValue>();

            // iterate over all nodes per language
            Iterator<String> j = names.iterator();
            while (j.hasNext()) {

                // this step is required for values that need a processing of their content
                // an example for this is the HTML value that does link replacement
                String name = j.next();
                I_CmsXmlContentValue value = getValue(name, locale);
                if (value.isSimpleType()) {
                    String content = value.getStringValue(cms);
                    value.setStringValue(cms, content);
                }

                // save valid elements for later check
                validValues.add(value);
            }

            if (isAutoCorrectionEnabled()) {
                // full correction of XML
                if (validValues.size() < 1) {
                    // no valid element was in the content
                    if (hasLocale(locale)) {
                        // remove the old locale entirely, as there was no valid element
                        removeLocale(locale);
                    }
                    // add a new default locale, this will also generate the default XML as required
                    addLocale(cms, locale);
                } else {
                    // there is at least one valid element in the content

                    List<Element> roots = new ArrayList<Element>();
                    List<CmsXmlContentDefinition> rootCds = new ArrayList<CmsXmlContentDefinition>();
                    List<Element> validElements = new ArrayList<Element>();

                    // gather all XML content definitions and their parent nodes
                    Iterator<I_CmsXmlContentValue> it = validValues.iterator();
                    while (it.hasNext()) {
                        // collect all root elements, also for the nested content definitions
                        I_CmsXmlContentValue value = it.next();
                        Element element = value.getElement();
                        validElements.add(element);
                        if (element.supportsParent()) {
                            // get the parent XML node
                            Element root = element.getParent();
                            if ((root != null) && !roots.contains(root)) {
                                // this is a parent node we do not have already in our storage
                                CmsXmlContentDefinition rcd = value.getContentDefinition();
                                if (rcd != null) {
                                    // this value has a valid XML content definition
                                    roots.add(root);
                                    rootCds.add(rcd);
                                } else {
                                    // no valid content definition for the XML value
                                    throw new CmsXmlException(
                                        Messages.get().container(
                                            Messages.ERR_CORRECT_NO_CONTENT_DEF_3,
                                            value.getName(),
                                            value.getTypeName(),
                                            value.getPath()));
                                }
                            }
                        }
                    }

                    for (int le = 0; le < roots.size(); le++) {
                        // iterate all XML content root nodes and correct each XML subtree

                        Element root = roots.get(le);
                        CmsXmlContentDefinition cd = rootCds.get(le);

                        // step 1: first sort the nodes according to the schema, this takes care of re-ordered elements
                        List<List<Element>> nodeLists = new ArrayList<List<Element>>();
                        boolean isMultipleChoice = cd.getSequenceType() == CmsXmlContentDefinition.SequenceType.MULTIPLE_CHOICE;

                        // if it's a multiple choice element, the child elements must not be sorted into their types,
                        // but must keep their original order
                        if (isMultipleChoice) {
                            List<Element> nodeList = new ArrayList<Element>();
                            List<Element> elements = CmsXmlGenericWrapper.elements(root);
                            Set<String> typeNames = cd.getSchemaTypes();
                            for (Element element : elements) {
                                // check if the node type is still in the definition
                                if (typeNames.contains(element.getName())) {
                                    nodeList.add(element);
                                }
                            }
                            checkMaxOccurs(nodeList, cd.getChoiceMaxOccurs(), cd.getTypeName());
                            nodeLists.add(nodeList);
                        }
                        // if it's a sequence, the children are sorted according to the sequence type definition
                        else {
                            for (I_CmsXmlSchemaType type : cd.getTypeSequence()) {
                                List<Element> elements = CmsXmlGenericWrapper.elements(root, type.getName());
                                checkMaxOccurs(elements, type.getMaxOccurs(), type.getTypeName());
                                nodeLists.add(elements);
                            }
                        }

                        // step 2: clear the list of nodes (this will remove all invalid nodes)
                        List<Element> nodeList = CmsXmlGenericWrapper.elements(root);
                        nodeList.clear();
                        Iterator<List<Element>> in = nodeLists.iterator();
                        while (in.hasNext()) {
                            // now add all valid nodes in the right order
                            List<Element> elements = in.next();
                            nodeList.addAll(elements);
                        }

                        // step 3: now append the missing elements according to the XML content definition
                        cd.addDefaultXml(cms, this, root, locale);
                    }
                }
            }
            initDocument();
        }

        // write the modified XML back to the VFS file
        if (m_file != null) {
            // make sure the file object is available
            m_file.setContents(marshal());
        }
        return m_file;
    }
625246
private byte[] replaceInXml(CmsFile cmsFile) throws Exception {

        Exception e = null;
        CmsXmlContent xmlContent = CmsXmlContentFactory.unmarshal(getCms(), cmsFile);
        Pattern pattern = Pattern.compile(m_settings.getSearchpattern());
        // loop over the locales of the content
        boolean modified = false;
        boolean matched = false;
        String requestedLocale = m_settings.getLocale();
        for (Locale locale : xmlContent.getLocales()) {
            if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(requestedLocale)
                && !locale.toString().equalsIgnoreCase(requestedLocale)) {
                // does not match the requested locale, skip it
                continue;
            }
            // loop over the available element paths of the current content locale
            List<String> paths = xmlContent.getNames(locale);
            for (String xpath : paths) {
                // try to get the value extraction for the current element path
                I_CmsXmlContentValue value = xmlContent.getValue(xpath, locale);
                if (value.isSimpleType()) {
                    try {
                        String currPath = value.getPath();
                        if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_settings.getXpath())
                            || currPath.equals(m_settings.getXpath())
                            || (CmsXmlUtils.removeXpath(currPath).equals(m_settings.getXpath()))) {
                            // xpath match
                            String oldVal = value.getStringValue(getCms());
                            Matcher matcher = pattern.matcher(oldVal);
                            matcher = Pattern.compile(m_settings.getSearchpattern()).matcher(oldVal);
                            if (matcher.find()) {
                                matched = true;
                                m_matchedResources.add(cmsFile);
                                if (m_replace) {
                                    String newVal = matcher.replaceAll(m_settings.getReplacepattern());
                                    if (!oldVal.equals(newVal)) {
                                        value.setStringValue(getCms(), newVal);
                                        modified = true;
                                    }
                                }
                            }
                        }
                    } catch (Exception ex) {
                        // log and go on
                        LOG.error(ex.getMessage(), ex);
                        e = ex;
                    }
                }
            }
        }
        if (e != null) {
            throw e;
        }
        if (matched) {
            getReport().println(Messages.get().container(Messages.RPT_SOURCESEARCH_MATCHED_0), I_CmsReport.FORMAT_OK);
        } else {
            getReport().println(
                Messages.get().container(Messages.RPT_SOURCESEARCH_NOT_MATCHED_0),
                I_CmsReport.FORMAT_NOTE);
        }
        if (modified) {
            return xmlContent.marshal();
        }
        return null;
    }
543943
private void repairXmlContents() throws CmsException {

        // set the resource filter to filter XML contents of the selected type
        CmsResourceFilter filter = CmsResourceFilter.IGNORE_EXPIRATION.addRequireType(m_settings.getResourceTypeId());
        String path = CmsResource.getFolderPath(m_settings.getVfsFolder());
        // get the list of resources to check
        List<CmsResource> resources = getCms().readResources(path, filter, m_settings.isIncludeSubFolders());

        // set the report counters
        int count = 0;
        int resSize = resources.size();

        // create an entity resolver to use
        CmsXmlEntityResolver resolver = new CmsXmlEntityResolver(getCms());

        // iterate the resources
        Iterator<CmsResource> i = resources.iterator();
        while (i.hasNext()) {

            count++;
            CmsResource res = i.next();

            // generate report output
            getReport().print(
                org.opencms.report.Messages.get().container(
                    org.opencms.report.Messages.RPT_SUCCESSION_2,
                    String.valueOf(count),
                    String.valueOf(resSize)),
                I_CmsReport.FORMAT_NOTE);
            getReport().print(Messages.get().container(Messages.RPT_PROCESSING_XMLCONTENT_0), I_CmsReport.FORMAT_NOTE);
            getReport().print(
                org.opencms.report.Messages.get().container(
                    org.opencms.report.Messages.RPT_ARGUMENT_1,
                    getCms().getSitePath(res)));
            getReport().print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));

            try {

                // get the file contents
                CmsFile file = getCms().readFile(res);
                // get the XML content
                CmsXmlContent xmlContent = CmsXmlContentFactory.unmarshal(getCms(), file);

                // check the XML structure
                boolean fixFile = m_settings.isForce();
                if (!fixFile) {
                    try {
                        xmlContent.validateXmlStructure(resolver);
                    } catch (CmsXmlException e) {
                        // XML structure is not valid, this file has to be fixed
                        fixFile = true;
                    }
                }
                if (fixFile) {

                    // check the lock state of the file to repair
                    CmsLock lock = getCms().getLock(res);
                    boolean isLocked = false;
                    boolean canWrite = false;
                    if (lock.isNullLock()) {
                        // file is not locked, lock it
                        getCms().lockResource(getCms().getSitePath(res));
                        isLocked = true;
                        canWrite = true;
                    } else if (lock.isOwnedBy(getCms().getRequestContext().getCurrentUser())) {
                        // file is locked by current user
                        canWrite = true;
                    }

                    if (canWrite) {
                        // enable "auto correction mode" - this is required or the XML structure will not be fully corrected
                        xmlContent.setAutoCorrectionEnabled(true);
                        // now correct the XML
                        xmlContent.correctXmlStructure(getCms());
                        file.setContents(xmlContent.marshal());
                        // write the corrected file
                        getCms().writeFile(file);
                    } else {
                        // no write operation possible
                        getReport().println(
                            Messages.get().container(Messages.RPT_XMLCONTENTREPAIR_NOTLOCKED_0),
                            I_CmsReport.FORMAT_NOTE);
                    }

                    if (isLocked) {
                        // unlock previously locked resource
                        getCms().unlockResource(getCms().getSitePath(res));
                    }

                    if (canWrite) {
                        // successfully repaired XML content, report it
                        getReport().println(
                            Messages.get().container(Messages.RPT_XMLCONTENTREPAIR_REPAIRED_0),
                            I_CmsReport.FORMAT_OK);
                    }

                } else {
                    // nothing to fix, skip this file
                    getReport().println(
                        Messages.get().container(Messages.RPT_XMLCONTENTREPAIR_SKIPFILE_0),
                        I_CmsReport.FORMAT_NOTE);
                }

            } catch (CmsException e) {
                // an error occurred, show exception on report output
                getReport().println(e);
            }
        }
    }
802952
private void replaceModuleName() throws CmsException, UnsupportedEncodingException {

        CmsResourceFilter filter = CmsResourceFilter.ALL.addRequireFile().addExcludeState(
            CmsResource.STATE_DELETED).addRequireTimerange().addRequireVisible();
        List<CmsResource> resources = getCms().readResources(
            CmsWorkplace.VFS_PATH_MODULES + m_cloneInfo.getName() + "/",
            filter);
        for (CmsResource resource : resources) {
            CmsFile file = getCms().readFile(resource);
            if (CmsResourceTypeXmlContent.isXmlContent(file)) {
                CmsXmlContent xmlContent = CmsXmlContentFactory.unmarshal(getCms(), file);
                xmlContent.setAutoCorrectionEnabled(true);
                file = xmlContent.correctXmlStructure(getCms());
            }
            byte[] contents = file.getContents();
            String encoding = CmsLocaleManager.getResourceEncoding(getCms(), file);
            String content = new String(contents, encoding);
            Matcher matcher = Pattern.compile(m_cloneInfo.getSourceModuleName()).matcher(content);
            if (matcher.find()) {
                contents = matcher.replaceAll(m_cloneInfo.getName()).getBytes(encoding);
                if (lockResource(getCms(), file)) {
                    file.setContents(contents);
                    getCms().writeFile(file);
                }
            }
        }
    }
119293
protected void addSubResources(CmsObject cms, Set<CmsResource> resources) throws CmsException {

        List<CmsResource> subResources = new ArrayList<CmsResource>();
        CmsObject rootCms = OpenCms.initCmsObject(cms);
        rootCms.getRequestContext().setSiteRoot("");
        for (CmsResource res : resources) {
            if (res.isFolder()) {
                try {
                    List<CmsResource> childrenOfCurrentResource = rootCms.readResources(
                        res.getRootPath(),
                        CmsResourceFilter.ALL,
                        true);
                    subResources.addAll(childrenOfCurrentResource);
                } catch (CmsException e) {
                    LOG.error(e.getLocalizedMessage(), e);
                }
            }
        }
        resources.addAll(subResources);
    }
1050457
public void initialize(CmsObject cms) throws CmsException {

        m_publishEngine.initialize(cms, m_publishQueuePersistance, m_publishQueueShutdowntime);
        m_frozen = true;
    }
492993
protected CmsXmlContent addContentValues(CmsFile file, Map<String, String> contentValues) throws CmsException {

        CmsXmlContent content = unmarshalXmlContent(file);
        Locale locale = m_cms.getRequestContext().getLocale();

        addContentValues(content, locale, contentValues);
        return content;
    }
310862
private static void updateFile(CmsObject cms, CmsFile file, CmsMacroResolver macroResolver) throws CmsException {

        String encoding = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true).getValue(
            OpenCms.getSystemInfo().getDefaultEncoding());
        String content;
        try {
            content = macroResolver.resolveMacros(new String(file.getContents(), encoding));
        } catch (UnsupportedEncodingException e) {
            try {
                content = macroResolver.resolveMacros(
                    new String(file.getContents(), Charset.defaultCharset().toString()));
            } catch (UnsupportedEncodingException e1) {
                content = macroResolver.resolveMacros(new String(file.getContents()));
            }
        }
        // update the content
        try {
            file.setContents(content.getBytes(encoding));
        } catch (UnsupportedEncodingException e) {
            try {
                file.setContents(content.getBytes(Charset.defaultCharset().toString()));
            } catch (UnsupportedEncodingException e1) {
                file.setContents(content.getBytes());
            }
        }
        // write the target file
        cms.writeFile(file);
    }
29933
public CmsResource createXmlContent() throws CmsUgcException {

        checkNotFinished();
        checkEditResourceNotSet();

        CmsUgcSessionSecurityUtil.checkCreateContent(m_cms, m_configuration);
        try {
            I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(m_configuration.getResourceType());
            m_editResource = m_cms.createResource(getNewContentName(), type);
            return m_editResource;
        } catch (CmsException e) {
            LOG.error(e.getLocalizedMessage(), e);
            throw new CmsUgcException(e, CmsUgcConstants.ErrorCode.errMisc, e.getLocalizedMessage());
        }
    }
402886
private void unmarshalDescriptor() throws CmsXmlException, CmsException {

        if (null != m_desc) {

            // unmarshal descriptor
            m_descContent = CmsXmlContentFactory.unmarshal(m_cms, m_cms.readFile(m_desc));

            // configure messages if wanted
            CmsProperty bundleProp = m_cms.readPropertyObject(m_desc, PROPERTY_BUNDLE_DESCRIPTOR_LOCALIZATION, true);
            if (!(bundleProp.isNullProperty() || bundleProp.getValue().trim().isEmpty())) {
                m_configuredBundle = bundleProp.getValue();
            }
        }

    }