Saves the editor content to the temporary file.<p>

@param body the body name to write
@param locale the body locale to write
@throws CmsException if writing the file fails
492127
protected void performSaveContent(String body, Locale locale) throws CmsException {

        // prepare the content for saving
        String content = prepareContent(true);

        String contentConversion = m_page.getConversion();
        // check if cleanup was selected in the editor, we have to add the cleanup parameter
        if (EDITOR_CLEANUP.equals(getParamAction())) {
            if ((contentConversion == null) || (contentConversion.equals(CmsHtmlConverter.PARAM_DISABLED))) {
                // if the current conversion mode is "false" only, we have to remove the "false" value and set it to "cleanup", as "false" will be stronger than all other values
                contentConversion = CmsHtmlConverter.PARAM_WORD;
            } else {
                // add "cleanup" to the already existing values
                contentConversion += ";" + CmsHtmlConverter.PARAM_WORD;
            }
        }
        m_page.setConversion(contentConversion);

        // create the element if necessary and if content is present
        if (!m_page.hasValue(body, locale) && !"".equals(content)) {
            m_page.addValue(body, locale);
        }

        // get the enabled state of the element
        boolean enabled = m_page.isEnabled(body, locale);

        // set the element data
        if (m_page.hasValue(body, locale)) {
            m_page.setStringValue(getCms(), body, locale, content);
        }

        // write the file
        m_file.setContents(m_page.marshal());
        m_file = getCms().writeFile(m_file);

        // content might have been modified during write operation
        m_page = CmsXmlPageFactory.unmarshal(getCms(), m_file);
        if (m_page.hasValue(body, locale)) {
            getCms().getRequestContext().setAttribute(CmsRequestContext.ATTRIBUTE_EDITOR, Boolean.TRUE);
            content = m_page.getStringValue(getCms(), body, locale);
            if (content == null) {
                content = "";
            }
            setParamContent(content);
            prepareContent(false);
            m_page.setEnabled(body, locale, enabled);
        }
    }
903396
private void addMessagesToVfsBundle(Map<String, String> messages, CmsFile vfsBundleFile) throws CmsException {

        lockTemporary(vfsBundleFile);
        CmsObject cms = m_cms;
        CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, vfsBundleFile);
        Locale locale = CmsLocaleManager.getDefaultLocale();
        if (!content.hasLocale(locale)) {
            content.addLocale(cms, locale);
        }
        Element root = content.getLocaleNode(locale);
        for (Entry<String, String> entry : messages.entrySet()) {
            Element message = root.addElement(CmsVfsBundleLoaderXml.N_MESSAGE);
            Element key = message.addElement(CmsVfsBundleLoaderXml.N_KEY);
            key.setText(entry.getKey());
            Element value = message.addElement(CmsVfsBundleLoaderXml.N_VALUE);
            value.setText(entry.getValue());
        }
        content.initDocument();
        vfsBundleFile.setContents(content.marshal());
        cms.writeFile(vfsBundleFile);
    }
1092486
public CmsResource createResource() throws CmsException {

        String path = OpenCms.getResourceManager().getNameGenerator().getNewFileName(
            m_cms,
            m_pathWithPattern,
            5,
            m_explorerNameGeneration);
        Locale contentLocale = OpenCms.getLocaleManager().getDefaultLocale(m_cms, CmsResource.getFolderPath(path));
        CmsRequestContext context = m_cms.getRequestContext();
        if (m_modelResource != null) {
            context.setAttribute(CmsRequestContext.ATTRIBUTE_MODEL, m_modelResource.getRootPath());
        }
        context.setAttribute(CmsRequestContext.ATTRIBUTE_NEW_RESOURCE_LOCALE, contentLocale);
        CmsResource res = m_cms.createResource(
            path,
            OpenCms.getResourceManager().getResourceType(m_type),
            null,
            new ArrayList<CmsProperty>());
        if (m_propChanges != null) {
            CmsPropertyEditorHelper helper = new CmsPropertyEditorHelper(m_cms);
            helper.overrideStructureId(res.getStructureId());
            helper.saveProperties(m_propChanges);
        }
        // Path or other metadata may have changed
        m_createdResource = m_cms.readResource(res.getStructureId(), CmsResourceFilter.IGNORE_EXPIRATION);
        try {
            m_cms.unlockResource(m_createdResource);
        } catch (CmsException e) {
            LOG.info(e.getLocalizedMessage(), e);
        }
        for (I_Callback callback : m_callbacks) {
            callback.onResourceCreated(this);
        }
        return m_createdResource;
    }
115657
protected void addContentValue(CmsXmlContent content, Locale locale, String path, String value) {

        boolean hasValue = content.hasValue(path, locale);
        if (!hasValue) {
            String[] pathElements = path.split("/");
            String currentPath = pathElements[0];
            for (int i = 0; i < pathElements.length; i++) {
                if (i > 0) {
                    currentPath = CmsStringUtil.joinPaths(currentPath, pathElements[i]);
                }
                while (!content.hasValue(currentPath, locale)) {
                    content.addValue(m_cms, currentPath, locale, CmsXmlUtils.getXpathIndexInt(currentPath) - 1);
                }
            }
        }
        content.getValue(path, locale).setStringValue(m_cms, value);

    }
1281779
void switchLocale(final String locale) {

        if (locale.equals(m_locale)) {
            return;
        }
        m_locale = locale;
        m_basePanel.clear();
        destroyForm(false);
        final CmsEntity entity = m_entityBackend.getEntity(m_entityId);
        m_entityId = getIdForLocale(locale);
        // if the content does not contain the requested locale yet, a new node will be created
        final boolean addedNewLocale = !m_contentLocales.contains(locale);
        if (m_registeredEntities.contains(m_entityId)) {
            unregistereEntity(m_entityId);
        }
        if (addedNewLocale) {
            loadNewDefinition(m_entityId, entity, new I_CmsSimpleCallback<CmsContentDefinition>() {

                public void execute(final CmsContentDefinition contentDefinition) {

                    setContentDefinition(contentDefinition);
                    renderFormContent();
                    setChanged();

                }
            });
        } else {
            loadDefinition(m_entityId, entity, new I_CmsSimpleCallback<CmsContentDefinition>() {

                public void execute(CmsContentDefinition contentDefinition) {

                    setContentDefinition(contentDefinition);
                    renderFormContent();
                }
            });
        }
    }
102284
@Override
    public void actionSave() throws JspException {

        CmsFile editFile = null;
        try {
            editFile = getCms().readFile(getParamResource(), CmsResourceFilter.ALL);
            String decodedContent = decodeContentParameter(getParamContent(), getFileEncoding(), editFile);
            try {
                editFile.setContents(decodedContent.getBytes(getFileEncoding()));
            } catch (UnsupportedEncodingException e) {
                throw new CmsException(
                    Messages.get().container(Messages.ERR_INVALID_CONTENT_ENC_1, getParamResource()),
                    e);
            }
            if (OpenCms.getWorkplaceManager().isXmlContentAutoCorrect()
                && (CmsResourceTypeXmlContent.isXmlContent(editFile))) {
                // enable auto correction in case of XML content (if configured)
                getCms().getRequestContext().setAttribute(CmsXmlContent.AUTO_CORRECTION_ATTRIBUTE, Boolean.TRUE);
            }
            // the file content might have been modified during the write operation
            CmsFile writtenFile = getCms().writeFile(editFile);
            decodedContent = CmsEncoder.createString(writtenFile.getContents(), getFileEncoding());
            setParamContent(encodeContent(decodedContent));
            // set the modified parameter
            setParamModified(Boolean.TRUE.toString());
        } catch (CmsException e) {
            showErrorPage(e);
        }

        if (getAction() != ACTION_CANCEL) {
            // save successful, set save action
            setAction(ACTION_SAVE);
        }
    }
363755
public void setContentLocale(Locale locale) {

        m_contentLocale = locale;
        m_dateFieldKey = CmsSearchField.FIELD_INSTANCEDATE + "_" + m_contentLocale.toString() + "_dt";
    }
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());
        }
    }
431170
@Override
    public boolean save(String content, String location) {
        return save(content, Charsets.UTF_8, location);
    }
468891
protected void commitTempFile() throws CmsException {

        CmsObject cms = getCms();
        CmsFile tempFile;
        List<CmsProperty> properties;
        try {
            switchToTempProject();
            tempFile = cms.readFile(getParamTempfile(), CmsResourceFilter.ALL);
            properties = cms.readPropertyObjects(getParamTempfile(), false);
        } finally {
            // make sure the project is reset in case of any exception
            switchToCurrentProject();
        }
        if (cms.existsResource(getParamResource(), CmsResourceFilter.ALL)) {
            // update properties of original file first (required if change in encoding occurred)
            cms.writePropertyObjects(getParamResource(), properties);
            // now replace the content of the original file
            CmsFile orgFile = cms.readFile(getParamResource(), CmsResourceFilter.ALL);
            orgFile.setContents(tempFile.getContents());
            getCloneCms().writeFile(orgFile);
        } else {
            // original file does not exist, remove visibility permission entries and copy temporary file

            // switch to the temporary file project
            try {
                switchToTempProject();
                // lock the temporary file
                cms.changeLock(getParamTempfile());
                // remove visibility permissions for everybody on temporary file if possible
                if (cms.hasPermissions(tempFile, CmsPermissionSet.ACCESS_CONTROL)) {
                    cms.rmacc(
                        getParamTempfile(),
                        I_CmsPrincipal.PRINCIPAL_GROUP,
                        OpenCms.getDefaultUsers().getGroupUsers());
                }
            } finally {
                // make sure the project is reset in case of any exception
                switchToCurrentProject();
            }

            cms.copyResource(getParamTempfile(), getParamResource(), CmsResource.COPY_AS_NEW);
            // ensure the content handler is called
            CmsFile orgFile = cms.readFile(getParamResource(), CmsResourceFilter.ALL);
            getCloneCms().writeFile(orgFile);

        }
        // remove the temporary file flag
        int flags = cms.readResource(getParamResource(), CmsResourceFilter.ALL).getFlags();
        if ((flags & CmsResource.FLAG_TEMPFILE) == CmsResource.FLAG_TEMPFILE) {
            flags ^= CmsResource.FLAG_TEMPFILE;
            cms.chflags(getParamResource(), flags);
        }
    }
224131
private void writeCategories(CmsFile file, CmsXmlContent content, CmsEntity lastEditedEntity) {

        // do nothing if one of the arguments is empty.
        if ((null == content) || (null == file)) {
            return;
        }

        CmsObject cms = getCmsObject();
        if (!content.getLocales().isEmpty()) {
            Locale locale = content.getLocales().iterator().next();
            CmsEntity entity = lastEditedEntity;
            List<I_CmsXmlContentValue> values = content.getValues(locale);
            for (I_CmsXmlContentValue value : values) {
                if (value.getTypeName().equals(CmsXmlDynamicCategoryValue.TYPE_NAME)) {
                    I_CmsWidget widget = CmsWidgetUtil.collectWidgetInfo(value).getWidget();
                    List<CmsCategory> categories = new ArrayList<CmsCategory>(0);
                    try {
                        categories = CmsCategoryService.getInstance().readResourceCategories(cms, file);
                    } catch (CmsException e) {
                        LOG.error(Messages.get().getBundle().key(Messages.ERROR_FAILED_READING_CATEGORIES_1), e);
                    }
                    if ((null != widget) && (widget instanceof CmsCategoryWidget)) {
                        String mainCategoryPath = ((CmsCategoryWidget)widget).getStartingCategory(
                            cms,
                            cms.getSitePath(file));
                        for (CmsCategory category : categories) {
                            if (category.getPath().startsWith(mainCategoryPath)) {
                                try {
                                    CmsCategoryService.getInstance().removeResourceFromCategory(
                                        cms,
                                        cms.getSitePath(file),
                                        category);
                                } catch (CmsException e) {
                                    LOG.error(e.getLocalizedMessage(), e);
                                }
                            }
                        }
                        if (null == entity) {
                            try {
                                CmsContentDefinition definition = readContentDefinition(
                                    file,
                                    content,
                                    "dummy",
                                    null,
                                    locale,
                                    false,
                                    null,
                                    null,
                                    Collections.emptyMap());
                                entity = definition.getEntity();
                            } catch (CmsException e) {
                                LOG.error(e.getLocalizedMessage(), e);
                            }
                        }
                        String checkedCategories = "";
                        if (null != entity) {
                            checkedCategories = CmsEntity.getValueForPath(entity, new String[] {value.getPath()});
                        }
                        List<String> checkedCategoryList = Arrays.asList(checkedCategories.split(","));
                        for (String category : checkedCategoryList) {
                            try {
                                CmsCategoryService.getInstance().addResourceToCategory(
                                    cms,
                                    cms.getSitePath(file),
                                    CmsCategoryService.getInstance().getCategory(cms, category));
                            } catch (CmsException e) {
                                if (LOG.isWarnEnabled()) {
                                    LOG.warn(e.getLocalizedMessage(), e);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
760146
private void saveInheritanceGroup(CmsResource resource, CmsInheritanceContainer inheritanceContainer)
    throws CmsException {

        CmsObject cms = getCmsObject();
        CmsFile file = cms.readFile(resource);
        CmsXmlContent document = CmsXmlContentFactory.unmarshal(cms, file);

        for (Locale docLocale : document.getLocales()) {
            document.removeLocale(docLocale);
        }
        Locale locale = Locale.ENGLISH;
        document.addLocale(cms, locale);
        document.getValue("Title", locale).setStringValue(cms, inheritanceContainer.getTitle());
        document.getValue("Description", locale).setStringValue(cms, inheritanceContainer.getDescription());
        document.getValue("ConfigName", locale).setStringValue(cms, inheritanceContainer.getName());
        byte[] content = document.marshal();
        file.setContents(content);
        cms.writeFile(file);
    }
1102655
private void writeHttpImportDir(FileItem fi) throws CmsException {

        try {

            if ((fi != null) && CmsStringUtil.isNotEmptyOrWhitespaceOnly(fi.getName())) {
                //write the file in the tmp-directory of the system
                byte[] content = fi.get();
                File importFile = File.createTempFile("import_html", ".zip");
                //write the content in the tmp file
                FileOutputStream fileOutput = new FileOutputStream(importFile.getAbsolutePath());
                fileOutput.write(content);
                fileOutput.close();
                fi.delete();
                m_htmlimport.setHttpDir(importFile.getAbsolutePath());
            }
        } catch (Exception e) {
            throw new CmsException(Messages.get().container(Messages.ERR_ACTION_ZIPFILE_UPLOAD_0));
        }
    }
306695
public void initialize(CmsObject cms) throws CmsException {

        CmsUUID id = m_entry.getId();
        CmsResource resource = cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION);
        m_resource = resource;
        CmsResource defaultFile = resource;
        if (resource.isFolder()) {
            defaultFile = cms.readDefaultFile(resource, CmsResourceFilter.IGNORE_EXPIRATION);
        }
        CmsLocaleGroup localeGroup = cms.getLocaleGroupService().readLocaleGroup(defaultFile);
        CmsResource primary = localeGroup.getPrimaryResource();
        CmsProperty noTranslationProp = cms.readPropertyObject(
            primary,
            CmsPropertyDefinition.PROPERTY_LOCALE_NOTRANSLATION,
            false);
        m_noTranslation = noTranslationProp.getValue();
        CmsUUID defaultFileId = (defaultFile != null) ? defaultFile.getStructureId() : null;
        m_isCopyable = (defaultFile != null) && CmsResourceTypeXmlContainerPage.isContainerPage(defaultFile);
        Collection<CmsResource> resourcesForTargetLocale = localeGroup.getResourcesForLocale(m_otherLocale);
        if (!resourcesForTargetLocale.isEmpty()) {
            m_linkedResource = resourcesForTargetLocale.iterator().next();
            if (primary.getStructureId().equals(m_resource.getStructureId())
                || primary.getStructureId().equals(defaultFileId)
                || primary.getStructureId().equals(m_linkedResource.getStructureId())) {
                m_isDirectLink = true;
            }
        }
    }
493253
public I_CmsSearchDocument createDocument(CmsObject cms, CmsResource resource, I_CmsSearchIndex index)
    throws CmsException {

        // extract the content from the resource
        I_CmsExtractionResult content = null;

        if (index.isExtractingContent()) {
            // do full text content extraction only if required

            // check if caching is enabled for this document type
            CmsExtractionResultCache cache = getCache();
            String cacheName = null;
            if ((cache != null) && (resource.getSiblingCount() > 1)) {
                // hard drive based caching only makes sense for resources that have siblings,
                // because the index will also store the content as a blob
                cacheName = cache.getCacheName(
                    resource,
                    isLocaleDependend() ? index.getLocaleForResource(cms, resource, null) : null,
                    getName());
                content = cache.getCacheObject(cacheName);
            }

            if (content == null) {
                // extraction result has not been found in the cache
                // use the currently indexed content, if it is still up to date.
                content = index.getContentIfUnchanged(resource);
            }

            if (content == null) {
                // extraction result has not been attached to the resource
                try {
                    content = extractContent(cms, resource, index);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Extracting content for '" + resource.getRootPath() + "' successful.");
                    }
                    if ((cache != null) && (resource.getSiblingCount() > 1)) {
                        // save extracted content to the cache
                        cache.saveCacheObject(cacheName, content);
                    }
                } catch (CmsIndexNoContentException e) {
                    // there was no content found for the resource
                    LOG.info(
                        Messages.get().getBundle().key(Messages.ERR_TEXT_EXTRACTION_1, resource.getRootPath())
                            + " "
                            + e.getMessage());
                } catch (Throwable e) {
                    // text extraction failed for document - continue indexing meta information only
                    LOG.error(
                        Messages.get().getBundle().key(Messages.ERR_TEXT_EXTRACTION_1, resource.getRootPath()),
                        e);
                }
            }
        }

        // create the Lucene document according to the index field configuration
        return index.getFieldConfiguration().createDocument(cms, resource, index, content);
    }
986666
public void actionPreview() throws IOException, JspException {

        try {
            // save content of the editor to the temporary file
            performSaveContent(getParamElementname(), getElementLocale());
        } catch (CmsException e) {
            // show error page
            showErrorPage(this, e);
        }

        // redirect to the temporary file with current active element language
        String param = "?" + org.opencms.i18n.CmsLocaleManager.PARAMETER_LOCALE + "=" + getParamElementlanguage();
        sendCmsRedirect(getParamTempfile() + param);
    }
76633
public void switchToLocale(Locale locale) throws CmsException {

        CmsObject cms = A_CmsUI.getCmsObject();
        CmsLocaleGroupService groupService = cms.getLocaleGroupService();
        CmsLocaleGroup localeGroup = groupService.readDefaultFileLocaleGroup(m_currentRoot);
        Collection<CmsResource> resources = localeGroup.getResourcesForLocale(locale);
        if (resources.isEmpty()) {
            LOG.error(
                "Can not switch to locale "
                    + locale
                    + ": no page found in locale group of "
                    + m_currentRoot.getRootPath());
        }
        CmsResource localeVariant = resources.iterator().next();
        if (!localeVariant.isFolder()) {
            CmsResource parentFolder = cms.readParentFolder(localeVariant.getStructureId());
            if (m_comparisonLocale.equals(locale)) {
                m_comparisonLocale = m_rootLocale;
                m_rootLocale = locale;
            } else {
                m_rootLocale = locale;
            }
            updateLocaleWidgets();
            initTree(parentFolder);
        } else {
            LOG.error("locale variant should not be a folder: " + localeVariant.getRootPath());
        }
    }