Replaces structure ids of resources in the source subtree with the structure ids of the corresponding
resources in the target subtree inside a content string.<p>

@param originalContent the original content

@return the content with the new structure ids
196778
protected String rewriteContentString(String originalContent) {

        Pattern uuidPattern = Pattern.compile(CmsUUID.UUID_REGEX);
        I_CmsRegexSubstitution substitution = new I_CmsRegexSubstitution() {

            public String substituteMatch(String text, Matcher matcher) {

                String uuidString = text.substring(matcher.start(), matcher.end());
                CmsUUID uuid = new CmsUUID(uuidString);
                String result = uuidString;
                if (m_translationsById.containsKey(uuid)) {
                    result = m_translationsById.get(uuid).getStructureId().toString();
                }
                return result;
            }
        };
        return CmsStringUtil.substitute(uuidPattern, originalContent, substitution);
    }
513046
private List<Content> rewriteAnchor(Element element) {

    // detect empty anchor elements and insert at least an empty string to avoid "self-closing" elements
    // that are not handled correctly by most browsers
    if (element.getContent().isEmpty()) {
      element.setText("");
    }

    // resolve link metadata from DOM element
    Link link = getAnchorLink(element);

    // build anchor for link metadata
    Element anchorElement = buildAnchorElement(link, element);

    // Replace anchor tag or remove anchor tag if invalid - add any sub-content in every case
    List<Content> content = new ArrayList<Content>();
    if (anchorElement != null) {
      anchorElement.addContent(element.cloneContent());
      content.add(anchorElement);
    }
    else {
      content.addAll(element.getContent());
    }
    return content;
  }
797148
public void upgradeContent(CmsObject cms) throws CmsException {

        if (m_content == null) {
            m_content = cms.readFile(m_resource).getContents();
        }
    }
1131842
@PUT
    public Response putContent(@PathParam("spaceID") String spaceID,
                               @PathParam("contentID") String contentID,
                               @QueryParam("storeID") String storeID,
                               @HeaderParam(COPY_SOURCE_HEADER) String copySource,
                               @HeaderParam(COPY_SOURCE_STORE_HEADER) String sourceStoreID) {
        if (null != copySource) {
            return copyContent(spaceID, contentID, storeID, sourceStoreID, copySource);

        } else {
            return addContent(spaceID, contentID, storeID);
        }
    }
510113
private void copyMembers(CmsClientSitemapEntry source) {

        setId(source.getId());
        setName(source.getName());
        setOwnProperties(new HashMap<String, CmsClientProperty>(source.getOwnProperties()));
        setDefaultFileId(source.getDefaultFileId());
        setDefaultFileType(source.getDefaultFileType());
        Map<String, CmsClientProperty> defaultFileProperties = source.getDefaultFileProperties();
        if (defaultFileProperties == null) {
            defaultFileProperties = new HashMap<String, CmsClientProperty>();
        }
        setDefaultFileProperties(new HashMap<String, CmsClientProperty>(defaultFileProperties));
        if (source.getDetailpageTypeName() != null) {
            // do not copy the detail page type name unless it is not null, otherwise newly created detail pages
            // are not displayed correctly in the sitemap editor.
            setDetailpageTypeName(source.getDetailpageTypeName());
        }
        setSitePath(source.getSitePath());
        setVfsPath(source.getVfsPath());
        setLock(source.getLock());
        setEntryType(source.getEntryType());
        setInNavigation(source.isInNavigation());
        setHasForeignFolderLock(source.hasForeignFolderLock());
        setBlockingLockedChildren(source.hasBlockingLockedChildren());
        setFolderDefaultPage(source.isFolderDefaultPage());
        setResourceTypeName(source.getResourceTypeName());
        setChildrenLoadedInitially(source.getChildrenLoadedInitially());
        setFolderDefaultPage(source.isFolderDefaultPage());
        setDateExpired(source.getDateExpired());
        setDateReleased(source.getDateReleased());
        setResleasedAndNotExpired(source.isResleasedAndNotExpired());
        setDefaultFileReleased(source.isDefaultFileReleased());
        setAliases(source.getAliases());
        setRedirectTarget(source.getRedirectTarget());
        setResourceState(source.getResourceState());
        setPermissionInfo(source.m_permissionInfo);
    }
1098738
public void setStructureId(String structureId) {

        try {
            m_resourceBuilder.setStructureId(new CmsUUID(structureId));
            m_hasStructureId = true;

        } catch (Throwable e) {
            setThrowable(e);
        }

    }
135846
public CmsHistoryResourceCollection getResourceHistoryInternal(CmsUUID structureId) throws CmsException {

        CmsHistoryResourceCollection result = new CmsHistoryResourceCollection();
        CmsObject cms = getCmsObject();
        CmsResource resource = cms.readResource(structureId, CmsResourceFilter.ALL);
        List<I_CmsHistoryResource> versions = cms.readAllAvailableVersions(resource);
        if (!resource.getState().isUnchanged()) {
            result.add(createHistoryResourceBean(cms, resource, true, -1));
        }
        int maxVersion = 0;

        if (versions.isEmpty()) {
            try {
                CmsProject online = cms.readProject(CmsProject.ONLINE_PROJECT_ID);
                CmsObject onlineCms = OpenCms.initCmsObject(cms);
                onlineCms.getRequestContext().setCurrentProject(online);
                CmsResource onlineResource = onlineCms.readResource(structureId, CmsResourceFilter.ALL);
                CmsHistoryResourceBean onlineResBean = createHistoryResourceBean(onlineCms, onlineResource, false, 0);
                result.add(onlineResBean);
            } catch (CmsVfsResourceNotFoundException e) {
                LOG.info(e.getLocalizedMessage(), e);
            } catch (Exception e) {
                LOG.error(e.getLocalizedMessage(), e);
            }
        } else {
            for (I_CmsHistoryResource historyRes : versions) {
                maxVersion = Math.max(maxVersion, historyRes.getVersion());
            }
            for (I_CmsHistoryResource historyRes : versions) {
                CmsHistoryResourceBean historyBean = createHistoryResourceBean(
                    cms,
                    (CmsResource)historyRes,
                    false,
                    maxVersion);
                result.add(historyBean);
            }
        }
        return result;
    }
130063
protected I_CmsFormatterBean readFormatter(CmsUUID structureId) {

        I_CmsFormatterBean formatterBean = null;
        CmsResource formatterRes = null;
        try {
            formatterRes = m_cms.readResource(structureId);
            CmsFile formatterFile = m_cms.readFile(formatterRes);
            CmsFormatterBeanParser parser = new CmsFormatterBeanParser(m_cms, m_settingConfigs);
            CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, formatterFile);
            formatterBean = parser.parse(content, formatterRes.getRootPath(), "" + formatterRes.getStructureId());
        } catch (Exception e) {

            if (formatterRes == null) {
                // normal case if resources get deleted, should not be written to the error channel
                LOG.info("Could not read formatter with id " + structureId);
            } else {
                LOG.error(
                    "Error while trying to read formatter configuration "
                        + formatterRes.getRootPath()
                        + ":    "
                        + e.getLocalizedMessage(),
                    e);
            }
        }
        return formatterBean;
    }
1107392
private CmsValidationResult validateContent(CmsObject cms, CmsUUID structureId, CmsXmlContent content) {

        return validateContent(cms, structureId, content, null);
    }
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;
    }
1085262
public static CmsEditExternalLinkDialog loadAndShowDialog(final CmsUUID structureId) {

        final CmsEditExternalLinkDialog dialog = new CmsEditExternalLinkDialog(structureId);
        CmsRpcAction<CmsExternalLinkInfoBean> action = new CmsRpcAction<CmsExternalLinkInfoBean>() {

            @Override
            public void execute() {

                CmsCoreProvider.getVfsService().loadLinkInfo(structureId, this);
            }

            @Override
            protected void onResponse(CmsExternalLinkInfoBean result) {

                dialog.initContent(result);
            }
        };
        action.execute();
        dialog.center();
        return dialog;
    }
686742
public String replaceText(String originalStr, String oldStr,
            String newStr) {
        if (oldStr == null || newStr == null || oldStr.equals(newStr)) {
            return originalStr;
        }
        return originalStr.replace(oldStr, newStr);
    }
648570
@Override
    public String addContent(String spaceID,
                             String contentID,
                             InputStream content,
                             String contentMimeType,
                             Map<String, String> userProperties,
                             long contentSize,
                             String checksum,
                             String storeID)
        throws ResourceException, InvalidIdException, ResourcePropertiesInvalidException {

        IdUtil.validateContentId(contentID);
        validateProperties(userProperties, "add content", spaceID, contentID);

        try {
            StorageProvider storage =
                storageProviderFactory.getStorageProvider(storeID);

            try {
                // overlay new properties on top of older extended properties
                // so that old tags and custom properties are preserved.
                // c.f. https://jira.duraspace.org/browse/DURACLOUD-757
                Map<String, String> oldUserProperties =
                    storage.getContentProperties(spaceID, contentID);
                //remove all non extended properties
                if (userProperties != null) {
                    oldUserProperties.putAll(userProperties);
                    //use old mimetype if none specified.
                    String oldMimetype =
                        oldUserProperties.remove(StorageProvider.PROPERTIES_CONTENT_MIMETYPE);
                    if (contentMimeType == null || contentMimeType.trim() == "") {
                        contentMimeType = oldMimetype;
                    }

                    oldUserProperties = StorageProviderUtil.removeCalculatedProperties(oldUserProperties);
                }

                userProperties = oldUserProperties;
            } catch (NotFoundException ex) {
                // do nothing - no properties to update
                // since file did not previous exist.
            }

            return storage.addContent(spaceID,
                                      contentID,
                                      contentMimeType,
                                      userProperties,
                                      contentSize,
                                      checksum,
                                      content);
        } catch (NotFoundException e) {
            throw new ResourceNotFoundException("add content",
                                                spaceID,
                                                contentID,
                                                e);
        } catch (ChecksumMismatchException e) {
            throw new ResourceChecksumException("add content",
                                                spaceID,
                                                contentID,
                                                e);
        } catch (Exception e) {
            storageProviderFactory.expireStorageProvider(storeID);
            throw new ResourceException("add content", spaceID, contentID, e);
        }
    }
1024923
Set<CmsUUID> getOpenElementIds() {

        Set<CmsUUID> ids = new HashSet<CmsUUID>();
        for (CmsLazyTreeItem item : m_treeItems) {
            CmsVfsEntryBean entry = item.getData();
            if (item.isOpen()) {
                ids.add(entry.getStructureId());
            }
        }
        return ids;
    }
430334
public I_CmsExtractionResult extractContent(CmsObject cms, CmsResource resource, I_CmsSearchIndex index)
    throws CmsException {

        logContentExtraction(resource, index);
        try {
            CmsFile file = readFile(cms, resource);
            CmsXmlPage page = CmsXmlPageFactory.unmarshal(cms, file);
            Locale locale = index.getLocaleForResource(cms, resource, page.getLocales());

            List<String> elements = page.getNames(locale);
            StringBuffer content = new StringBuffer();
            LinkedHashMap<String, String> items = new LinkedHashMap<String, String>();
            for (Iterator<String> i = elements.iterator(); i.hasNext();) {
                String elementName = i.next();
                String value = page.getStringValue(cms, elementName, locale);
                String extracted = CmsHtmlExtractor.extractText(value, page.getEncoding());
                if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(extracted)) {
                    items.put(elementName, extracted);
                    content.append(extracted);
                    content.append('\n');
                }
            }

            return new CmsExtractionResult(content.toString(), items);

        } catch (Exception e) {
            throw new CmsIndexException(
                Messages.get().container(Messages.ERR_TEXT_EXTRACTION_1, resource.getRootPath()),
                e);
        }
    }
119755
@Override
    public void replaceProperties(final IdentifierConverter<Resource, FedoraResource> idTranslator,
        final Model inputModel, final RdfStream originalTriples) throws MalformedRdfException {

        final Resource selfResource = idTranslator.reverse().convert(this);
        ensureInteractionModelDefaults(selfResource.toString(), inputModel);

        // remove any statements that update "relaxed" server-managed triples so they can be updated separately
        final List<Statement> filteredStatements = new ArrayList<>();
        final StmtIterator it = inputModel.listStatements();
        final Optional<String> resourceInteractionModel = getResourceInteraction();
        final boolean hasInteractionModel = resourceInteractionModel.isPresent();
        while (it.hasNext()) {
            final Statement next = it.next();
            if (RdfLexicon.isRelaxed.test(next.getPredicate())) {
                filteredStatements.add(next);
                it.remove();
            } else {
                if (hasInteractionModel) {
                    checkInteractionModel(next.asTriple(), resourceInteractionModel);
                }
            }
        }
        // remove any "relaxed" server-managed triples from the existing triples
        final RdfStream filteredTriples = new DefaultRdfStream(originalTriples.topic(),
                originalTriples.filter(triple -> !isRelaxed.test(createProperty(triple.getPredicate().getURI()))));



        try (final RdfStream replacementStream =
                new DefaultRdfStream(selfResource.asNode())) {

            final GraphDifferencer differencer =
                new GraphDifferencer(inputModel, filteredTriples);

            final StringBuilder exceptions = new StringBuilder();
            try (final DefaultRdfStream diffStream =
                    new DefaultRdfStream(replacementStream.topic(), differencer.difference())) {
                new RdfRemover(idTranslator, getSession(), diffStream).consume();
            } catch (final MalformedRdfException e) {
                exceptions.append(e.getMessage());
                exceptions.append("\n");
            } catch (final ConstraintViolationException e) {
                throw e;
            }

            try (
                final DefaultRdfStream notCommonStream =
                        new DefaultRdfStream(replacementStream.topic(), differencer.notCommon());
                final DefaultRdfStream testStream =
                        new DefaultRdfStream(replacementStream.topic(), differencer.notCommon())) {

                // do some very basic validation to catch invalid RDF
                // this uses the same checks that updateProperties() uses
                final Collection<ConstraintViolationException> errors = testStream
                        .flatMap(FedoraResourceImpl::validateTriple)
                        .filter(x -> x != null)
                        .collect(Collectors.toList());

                throwConstraintErrorsIfPresent(errors);

                new RdfAdder(idTranslator, getSession(), notCommonStream, inputModel.getNsPrefixMap()).consume();
            } catch (final MalformedRdfException e) {
                exceptions.append(e.getMessage());
            } catch (final ConstraintViolationException e) {
                throw e;
            }

            // If this resource's structural parent is an IndirectContainer, check whether the
            // ldp:insertedContentRelation property is present in the stream of changed triples.
            // If so, set the propertyChanged value to true.
            final AtomicBoolean propertyChanged = new AtomicBoolean();
            ldpInsertedContentProperty(getNode()).ifPresent(resource -> {
                propertyChanged.set(differencer.notCommon().map(Triple::getPredicate).anyMatch(resource::equals));
            });

            removeEmptyFragments();

            if (exceptions.length() > 0) {
                throw new MalformedRdfException(exceptions.toString());
            }

            try {
                touch(propertyChanged.get(), RelaxedPropertiesHelper.getCreatedDate(filteredStatements),
                        RelaxedPropertiesHelper.getCreatedBy(filteredStatements),
                        RelaxedPropertiesHelper.getModifiedDate(filteredStatements),
                        RelaxedPropertiesHelper.getModifiedBy(filteredStatements));
            } catch (final RepositoryException e) {
                throw new RuntimeException(e);
            }
        }
    }
622124
private Response copyContent(String spaceID,
                                 String contentID,
                                 String storeID,
                                 String sourceStoreID,
                                 String copySource) {
        StringBuilder msg = new StringBuilder("copying content from (");
        msg.append(copySource);
        msg.append(") to (");
        msg.append(spaceID);
        msg.append(" / ");
        msg.append(contentID);
        msg.append(", ");
        msg.append(storeID);
        msg.append(")");
        log.info(msg.toString());

        try {
            return doCopyContent(spaceID, contentID, storeID, sourceStoreID, copySource);

        } catch (InvalidIdException e) {
            return responseBad(msg.toString(), e, BAD_REQUEST);

        } catch (InvalidRequestException e) {
            return responseBad(msg.toString(), e, BAD_REQUEST);

        } catch (ResourceNotFoundException e) {
            return responseNotFound(msg.toString(), e, NOT_FOUND);

        } catch (ResourceStateException e) {
            return responseBad(msg.toString(), e, CONFLICT);

        } catch (ResourceException e) {
            return responseBad(msg.toString(), e, INTERNAL_SERVER_ERROR);

        } catch (Exception e) {
            return responseBad(msg.toString(), e, INTERNAL_SERVER_ERROR);
        }
    }