public Document getBinary(GetBinaryParams params) throws Exception { assertMinValue("binaryKey", params.binaryKey, 0); final UserEntity runAsUser = securityService.getImpersonatedPortalUser(); final BinaryDataKey binaryDataKey = new BinaryDataKey(params.binaryKey); final BinaryDataEntity binaryData = binaryDataDao.findByKey(binaryDataKey); if (binaryData == null) { throw AttachmentNotFoundException.notFound(binaryDataKey); } final ContentBinaryDataEntity contentBinaryDataInMainVersion = ContentBinaryDataEntity.resolveContentBinaryDataInMainVersion( contentBinaryDataDao.findAllByBinaryKey(binaryData.getKey())); if (contentBinaryDataInMainVersion == null) { throw AttachmentNotFoundException.notFound(binaryData.getBinaryDataKey()); } final ContentEntity content = contentBinaryDataInMainVersion.getContentVersion().getContent(); if (content == null || content.isDeleted()) { throw AttachmentNotFoundException.notFound(binaryDataKey); } if (!new ContentAccessResolver(groupDao).hasReadContentAccess(runAsUser, content)) { throw AttachmentNotFoundException.noAccess(content.getKey()); } checkContentIsOnline(content); return createBinaryDocument(createBinaryData(contentBinaryDataInMainVersion)); }
@Test public void request_content_image_that_binary_is_on_main_version() throws Exception { // setup: content byte[] bytes = loadImage("Arn.JPG"); ContentKey contentKey = createImageContent( "MyImage.jpg", 2, bytes, "ImageCategory", new DateTime(2011, 6, 27, 10, 0, 0, 0), null); // setup: draft version of content ContentEntity content = fixture.findContentByKey(contentKey); BinaryDataEntity binaryDataOfMainVersion = content.getMainVersion().getBinaryData("source"); // exercise & verify String imageRequestPath = "_image/" + contentKey + "/binary/" + binaryDataOfMainVersion.getKey() + ".jpg"; setPathInfoAndRequestURI(httpServletRequest, imageRequestPath); httpServletRequest.setParameter("_background", "0xffffff"); httpServletRequest.setParameter("_quality", "100"); imageController.handleRequestInternal(httpServletRequest, httpServletResponse); assertEquals(HttpServletResponse.SC_OK, httpServletResponse.getStatus()); assertTrue("Content Length", httpServletResponse.getContentLength() > 0); assertEquals("image/jpg", httpServletResponse.getContentType()); }
@Test public void testUpdateContentWithReplaceNew_WithNullValue() { ContentDataInput cdi = getContentData(true); UpdateContentParams upcd = getUpdateContentParams(cdi); upcd.updateStrategy = ContentDataInputUpdateStrategy.REPLACE_NEW; // update content with all fields set internalClient.updateContent(upcd); // get updated content - make sure all fiels are set String xml = getUpdatedContentXMLWithDao(); assertTrue( "XML inneholder ikke <mytitle>updateTest</mytitle>", xml.contains("<mytitle>updateTest</mytitle>")); assertTrue( "XML inneholder ikke <updatefield>foobar</updatefield>", xml.contains("<updatefield>foobar</updatefield>")); // update content with missing field // update content with missing field cdi = new ContentDataInput("MyContentType"); cdi.add(new TextInput("myTitle", "updateTest")); cdi.add(new TextInput("fieldToUpdate", null)); upcd.contentData = cdi; internalClient.updateContent(upcd); // get updated content ContentEntity entity = contentDao.findByKey(updateContentKey); ContentVersionEntity version = entity.getMainVersion(); CustomContentData customContentData = (CustomContentData) version.getContentData(); TextDataEntry myTitle = (TextDataEntry) customContentData.getEntry("myTitle"); assertEquals("updateTest", myTitle.getValue()); TextDataEntry fieldToUpdate = (TextDataEntry) customContentData.getEntry("fieldToUpdate"); assertFalse(fieldToUpdate.hasValue()); }
private void handleRecentItems( Document verticalDoc, Map<Integer, String> contentTypeKeyHandlerMapping, final ExtendedMap formItems, UserEntity user) { String maximize = formItems.getString("maximize", null); int index = formItems.getInt("index", 0); int count = formItems.getInt("count", maximize != null ? 20 : 10); ContentLogEntrySpecification logSpecification = new ContentLogEntrySpecification(); logSpecification.setUser(user); logSpecification.setTypes( new LogType[] {LogType.ENTITY_OPENED, LogType.ENTITY_CREATED, LogType.ENTITY_UPDATED}); logSpecification.setTableTypes(new Table[] {Table.CONTENT}); logSpecification.setAllowDuplicateEntries(false); logSpecification.setAllowDeletedContent(false); Calendar now = GregorianCalendar.getInstance(); final int monthsInPast = 3; now.add(Calendar.MONTH, -monthsInPast); logSpecification.setDateFilter(now.getTime()); LogEntryResultSet logResult = logService.getLogEntries(logSpecification, "timestamp DESC", count, index); if (logResult.getLength() > 0) { // build contentTypeKey and handler mapping List<ContentKey> contentKeys = new ArrayList<ContentKey>(); for (LogEntryEntity entity : logResult.getLogEntries()) { contentKeys.add(new ContentKey(entity.getKeyValue())); } ContentByContentQuery contentByContentQuery = new ContentByContentQuery(); contentByContentQuery.setContentKeyFilter(contentKeys); contentByContentQuery.setUser(user); contentByContentQuery.setIndex(0); contentByContentQuery.setCount(logResult.getLength()); ContentResultSet contentResultSet = contentService.queryContent(contentByContentQuery); for (ContentEntity entity : contentResultSet.getContents()) { contentTypeKeyHandlerMapping.put( entity.getContentType().getKey(), entity.getContentType().getContentHandlerName().getHandlerClassShortName()); } } ContentLogXMLCreator logXMLCreator = new ContentLogXMLCreator(); logXMLCreator.setIncludeContentData(true); logXMLCreator.setContentDao(contentDao); XMLDocument xmlDocument = logXMLCreator.createLogsDocument(logResult); Document lastModifiedDoc = xmlDocument.getAsDOMDocument(); lastModifiedDoc.getDocumentElement().setAttribute("type", "lastmodified"); XMLTool.mergeDocuments(verticalDoc, lastModifiedDoc, true); }
@Test public void testCreateContentWithBinary() { fixture.createAndStoreNormalUserWithUserGroup("testuser", "Test user", "testuserstore"); fixture.save( factory.createContentHandler( "Custom content", ContentHandlerName.CUSTOM.getHandlerClassShortName())); fixture.save( factory.createContentType( "MyContentType", ContentHandlerName.CUSTOM.getHandlerClassShortName(), standardConfig)); fixture.save(factory.createUnit("MyUnit", "en")); fixture.save( factory.createCategory("MyCategory", "MyContentType", "MyUnit", "testuser", "testuser")); fixture.save(factory.createCategoryAccessForUser("MyCategory", "testuser", "read,create")); fixture.flushAndClearHibernateSesssion(); UserEntity runningUser = fixture.findUserByName("testuser"); PortalSecurityHolder.setImpersonatedUser(runningUser.getKey()); ContentDataInput contentData = new ContentDataInput("MyContentType"); contentData.add(new TextInput("myTitle", "testtitle")); contentData.add(new BinaryInput("myBinaryfile", dummyBinary, "dummyBinary")); CreateContentParams params = new CreateContentParams(); params.categoryKey = fixture.findCategoryByName("MyCategory").getKey().toInt(); params.contentData = contentData; params.publishFrom = new Date(); params.publishTo = null; params.status = ContentStatus.STATUS_DRAFT; int contentKey = internalClient.createContent(params); fixture.flushAndClearHibernateSesssion(); ContentEntity persistedContent = fixture.findContentByKey(new ContentKey(contentKey)); assertNotNull(persistedContent); assertEquals("MyCategory", persistedContent.getCategory().getName()); ContentVersionEntity persistedVersion = persistedContent.getMainVersion(); assertNotNull(persistedVersion); assertEquals("testtitle", persistedVersion.getTitle()); assertEquals( com.enonic.cms.core.content.ContentStatus.DRAFT.getKey(), persistedVersion.getStatus().getKey()); // verify binary was saved Set<ContentBinaryDataEntity> contentBinaryDatas = persistedVersion.getContentBinaryData(); assertEquals(1, contentBinaryDatas.size()); ContentBinaryDataEntity contentBinaryData = contentBinaryDatas.iterator().next(); BinaryDataEntity binaryData = contentBinaryData.getBinaryData(); assertEquals("dummyBinary", binaryData.getName()); CustomContentData customContentData = (CustomContentData) persistedVersion.getContentData(); assertNotNull(customContentData); }
private void validateUpdateContentParams(UpdateContentParams params) { if (params.contentKey == null) { throw new IllegalArgumentException("contentKey must be specified"); } if (params.updateStrategy == null) { throw new IllegalArgumentException("updateStrategy must be specified"); } if (params.publishFrom != null && params.publishTo != null && !params.publishTo.after(params.publishFrom)) { throw new IllegalArgumentException("publishTo must be after publishFrom"); } if (params.createNewVersion && params.contentData == null && params.updateStrategy == ContentDataInputUpdateStrategy.REPLACE_ALL) { throw new IllegalArgumentException( "contentData must be specified if you want to create new version when updateStrategy is " + ContentDataInputUpdateStrategy.REPLACE_ALL); } if (params.contentVersionKey != null && params.createNewVersion) { throw new IllegalArgumentException( "There is no meaning in wanting to both update one specific version and create a new version"); } ContentEntity persistedContent = contentDao.findByKey(new ContentKey(params.contentKey)); if (persistedContent == null) { throw new IllegalArgumentException("No content for given contentKey: " + params.contentKey); } int currentStatus = persistedContent.getMainVersion().getStatus().getKey(); if (!params.createNewVersion && currentStatus != ContentStatus.DRAFT.getKey() && params.contentData != null) { throw new IllegalArgumentException( "Only allowed to overwrite a draft content version - create new version instead"); } if (params.status != null) { boolean currentStatusIsApprovedOrArchived = currentStatus == ContentStatus.APPROVED.getKey() || currentStatus == ContentStatus.ARCHIVED.getKey(); if (currentStatusIsApprovedOrArchived) { boolean statusChangingingToDraft = params.status == ContentStatus.DRAFT.getKey(); boolean statusChangingToSnapshot = params.status == ContentStatus.SNAPSHOT.getKey(); if (!params.createNewVersion && (statusChangingingToDraft || statusChangingToSnapshot)) { throw new IllegalArgumentException( "Not allowed to change status of an approved or archived content version - create new content version instead"); } } } }
private void handleActivation( Document verticalDoc, Map<Integer, String> contentTypeKeyHandlerMapping, final ExtendedMap formItems, UserEntity user) { String maximize = formItems.getString("maximize", null); int index = formItems.getInt("index", 0); int count = formItems.getInt("count", maximize != null ? 20 : 3); ContentBySectionQuery contentBySectionQuery = new ContentBySectionQuery(); contentBySectionQuery.setSectionFilterStatus(SectionFilterStatus.UNAPPROVED_ONLY); contentBySectionQuery.setSearchInAllSections(); contentBySectionQuery.setCount(count); contentBySectionQuery.setUser(user); contentBySectionQuery.setOrderBy("timestamp DESC"); contentBySectionQuery.setIndex(index); contentBySectionQuery.setFilterIncludeOfflineContent(); contentBySectionQuery.setLevels(Integer.MAX_VALUE); List<CategoryAccessType> categoryAccessTypeFilter = new ArrayList<CategoryAccessType>(); categoryAccessTypeFilter.add(CategoryAccessType.ADMINISTRATE); categoryAccessTypeFilter.add(CategoryAccessType.APPROVE); contentBySectionQuery.setCategoryAccessTypeFilter( categoryAccessTypeFilter, CategoryAccessTypeFilterPolicy.OR); ContentResultSet contentResultSet = null; try { contentResultSet = contentService.queryContent(contentBySectionQuery); } catch (Exception e) { throw new VerticalAdminException("Failed to get unapproved content", e); } // build contentTypeKey and handlerName mapping for (ContentEntity entity : contentResultSet.getContents()) { contentTypeKeyHandlerMapping.put( entity.getContentType().getKey(), entity.getContentType().getContentHandlerName().getHandlerClassShortName()); } SectionXmlCreator sectionXmlCreator = new SectionXmlCreator( siteDao, new CategoryAccessResolver(groupDao), new ContentAccessResolver(groupDao)); XMLDocument sectionDocument = sectionXmlCreator.createSectionsDocument(user, contentResultSet, count); Document waitingForActivationDoc = sectionDocument.getAsDOMDocument(); // waitingForActivationDoc.getDocumentElement().setAttribute("type", "activation"); XMLTool.mergeDocuments(verticalDoc, waitingForActivationDoc, true); }
private ContentVersionKey resolveContentVersionKey( boolean createNewVersion, int contentKey, Integer contentVeresionKey) { ContentEntity persistedContent = contentDao.findByKey(new ContentKey(contentKey)); ContentVersionKey contentVersionKey; if (createNewVersion) { contentVersionKey = persistedContent.getMainVersion().getKey(); } else if (contentVeresionKey == null) { contentVersionKey = persistedContent.getMainVersion().getKey(); } else { contentVersionKey = new ContentVersionKey(contentVeresionKey); } return contentVersionKey; }
private void checkContentIsOnline(final ContentEntity content) { if (previewService.isInPreview()) { PreviewContext previewContext = previewService.getPreviewContext(); if (previewContext.isPreviewingContent() && previewContext .getContentPreviewContext() .treatContentAsAvailableEvenIfOffline(content.getKey())) { // when in preview, the content doesn't need to be online return; } } if (!content.isOnline(timeService.getNowAsDateTime())) { throw AttachmentNotFoundException.notFound(content.getKey()); } }
private void removeContentHomeIfThisSectionIs( final ContentEntity content, final MenuItemEntity section) { final ContentHomeEntity contentHome = content.getContentHome(section.getSite().getKey()); if (contentHome != null && contentHome.getMenuItem() == null) { content.removeContentHome(section.getSite().getKey()); contentHomeDao.delete(contentHome); } else if (contentHome != null && section.getKey() == contentHome.getMenuItem().getKey()) { content.removeContentHome(section.getSite().getKey()); contentHomeDao.delete(contentHome); } contentHomeDao .getHibernateTemplate() .getSessionFactory() .evictCollection(ContentEntity.class.getName() + ".contentHomes", content.getKey()); }
private void handleAssignedToMe( Document verticalDoc, Map<Integer, String> contentTypeKeyHandlerMapping, final ExtendedMap formItems, UserEntity user) { String maximize = formItems.getString("maximize", null); int index = formItems.getInt("index", 0); int count = formItems.getInt("count", maximize != null ? 20 : ASSIGNED_TO_COUNT); ContentSpecification contentSpecification = new ContentSpecification(); // contentSpecification.setUser( user ); contentSpecification.setAssignee(user); contentSpecification.setAssignedDraftsOnly(false); ContentResultSet contentResultSet = contentService.getContent( contentSpecification, "c.assignmentDueDate ASC, c.timestamp DESC", count, index); for (ContentEntity content : contentResultSet.getContents()) { contentTypeKeyHandlerMapping.put( content.getContentType().getKey(), content.getContentType().getContentHandlerName().getHandlerClassShortName()); } ContentXMLCreator contentXMLCreator = new ContentXMLCreator(); contentXMLCreator.setResultIndexing(index, count); contentXMLCreator.setIncludeOwnerAndModifierData(true); contentXMLCreator.setIncludeContentData(true); contentXMLCreator.setIncludeCategoryData(true); contentXMLCreator.setIncludeAccessRightsInfo(false); contentXMLCreator.setIncludeRelatedContentsInfo(false); contentXMLCreator.setIncludeRepositoryPathInfo(true); contentXMLCreator.setIncludeVersionsInfoForAdmin(true); contentXMLCreator.setIncludeAssignment(true); contentXMLCreator.setIncludeDraftInfo(true); contentXMLCreator.setIncludeSectionActivationInfo(true); XMLDocument xmlDocument = contentXMLCreator.createContentVersionsDocument( user, contentResultSet, new RelatedContentResultSetImpl()); Document doc = xmlDocument.getAsDOMDocument(); doc.getDocumentElement().setAttribute("type", "assignedto"); XMLTool.mergeDocuments(verticalDoc, doc, true); }
@Test public void request_content_image_that_is_deleted() throws Exception { byte[] bytes = loadImage("Arn.JPG"); ContentKey contentKey = createImageContent( "MyImage.jpg", 2, bytes, "ImageCategory", new DateTime(2011, 6, 27, 10, 0, 0, 0), null); ContentEntity content = fixture.findContentByKey(contentKey); content.setDeleted(true); String imageRequestPath = "_image/" + contentKey + ".jpg"; setPathInfoAndRequestURI(httpServletRequest, imageRequestPath); httpServletRequest.setParameter("_background", "0xffffff"); httpServletRequest.setParameter("_quality", "100"); imageController.handleRequestInternal(httpServletRequest, httpServletResponse); assertEquals(HttpServletResponse.SC_NOT_FOUND, httpServletResponse.getStatus()); assertTrue("Content Length", httpServletResponse.getContentLength() == 0); }
public ContentHomeEntity createContentHome( ContentEntity content, MenuItemEntity menuItem, PageTemplateEntity pageTemplate) { ContentHomeEntity contentHome = new ContentHomeEntity(); contentHome.setKey(new ContentHomeKey(menuItem.getSite().getKey(), content.getKey())); contentHome.setContent(content); contentHome.setMenuItem(menuItem); contentHome.setSite(menuItem.getSite()); contentHome.setPageTemplate(pageTemplate); return contentHome; }
@Test public void response_ok_for_request_to_content_image_that_binary_is_not_on_main_version() throws Exception { // setup: content byte[] bytes = loadImage("Arn.JPG"); ContentKey contentKey = createImageContent( "MyImage.jpg", 2, bytes, "ImageCategory", new DateTime(2011, 6, 27, 10, 0, 0, 0), null); // setup: draft version of content ContentEntity content = fixture.findContentByKey(contentKey); ContentVersionEntity draftVersion = createDraftVersion("Arn.JPG"); draftVersion.setContentDataXml(content.getMainVersion().getContentDataAsXmlString()); content.setDraftVersion(draftVersion); content.addVersion(draftVersion); fixture.save(draftVersion); BinaryDataEntity binaryDataForDraftVersion = factory.createBinaryData("Arn.JPG", bytes.length); binaryDataForDraftVersion.setBlobKey( content.getMainVersion().getBinaryData("source").getBlobKey()); fixture.save(binaryDataForDraftVersion); ContentBinaryDataEntity contentBinaryDataForDraftVersion = factory.createContentBinaryData("source", binaryDataForDraftVersion, draftVersion); draftVersion.addContentBinaryData(contentBinaryDataForDraftVersion); fixture.save(contentBinaryDataForDraftVersion); fixture.flushAndClearHibernateSesssion(); // exercise & verify String imageRequestPath = "_image/" + contentKey + "/label/source.jpg"; setPathInfoAndRequestURI(httpServletRequest, imageRequestPath); httpServletRequest.setParameter("_version", draftVersion.getKey().toString()); httpServletRequest.setParameter("_background", "0xffffff"); httpServletRequest.setParameter("_quality", "100"); imageController.handleRequestInternal(httpServletRequest, httpServletResponse); assertEquals(HttpServletResponse.SC_OK, httpServletResponse.getStatus()); assertTrue("Content Length", httpServletResponse.getContentLength() > 0); assertEquals("image/jpg", httpServletResponse.getContentType()); }
public void deleteContent(DeleteContentParams params) { UserEntity runningUser = securityService.getImpersonatedPortalUser(); ContentEntity content = contentDao.findByKey(new ContentKey(params.contentKey)); if (content != null && !content.isDeleted()) { ContentLocationSpecification contentLocationSpecification = new ContentLocationSpecification(); contentLocationSpecification.setIncludeInactiveLocationsInSection(false); ContentLocations contentLocations = content.getLocations(contentLocationSpecification); contentService.deleteContent( runningUser, content, params.siteKey != null ? new SiteKey(params.siteKey) : null); for (ContentLocation contentLocation : contentLocations.getAllLocations()) { PageCache pageCache = pageCacheService.getPageCacheService(contentLocation.getSiteKey()); pageCache.removeEntriesByMenuItem(contentLocation.getMenuItemKey()); } } }
private UpdateContentCommand updateContentCommand( ContentKey contentKeyToUpdate, ContentData contentData, String updaterUid) { ContentEntity contentToUpdate = fixture.findContentByKey(contentKeyToUpdate); UpdateContentCommand command = UpdateContentCommand.storeNewVersionEvenIfUnchanged( contentToUpdate.getMainVersion().getKey()); command.setUpdateAsMainVersion(true); command.setSyncAccessRights(false); command.setSyncRelatedContent(true); command.setContentKey(contentToUpdate.getKey()); command.setUpdateStrategy(UpdateContentCommand.UpdateStrategy.MODIFY); command.setModifier(fixture.findUserByName(updaterUid).getKey()); command.setPriority(0); command.setLanguage(fixture.findLanguageByCode("en")); command.setStatus(ContentStatus.APPROVED); command.setContentData(contentData); command.setAvailableFrom(DATE_TIME_2010_01_01.toDate()); return command; }
private void doArchiveContent( UserEntity importer, ContentKey contentKey, ImportResult importResult) { final ContentEntity content = contentDao.findByKey(contentKey); if (content == null) { return; } boolean contentArchived = contentStorer.archiveMainVersion(importer, content); if (contentArchived) { importResult.addArchived(content); UnassignContentCommand unassignContentCommand = new UnassignContentCommand(); unassignContentCommand.setContentKey(content.getKey()); unassignContentCommand.setUnassigner(importer.getKey()); contentStorer.unassignContent(unassignContentCommand); } else { importResult.addAlreadyArchived(content); } }
@Test public void testUpdateContentDoNotChangeAssignment() { // exercise: updateContent AssignContentCommand assignContentCommand = new AssignContentCommand(); assignContentCommand.setAssignerKey(fixture.findUserByName("testuser").getKey()); assignContentCommand.setAssigneeKey(fixture.findUserByName("testuser").getKey()); assignContentCommand.setAssignmentDescription("test assignment"); assignContentCommand.setAssignmentDueDate(new DateTime(2010, 6, 6, 10, 0, 0, 0).toDate()); assignContentCommand.setContentKey(contentWithBinaryKey); contentService.assignContent(assignContentCommand); ContentDataInput newContentData = new ContentDataInput("MyContentType"); newContentData.add(new TextInput("myTitle", "changedtitle")); newContentData.add(new BinaryInput("myBinaryfile", dummyBinary, "dummyBinary")); UserEntity runningUser = fixture.findUserByName("testuser"); PortalSecurityHolder.setImpersonatedUser(runningUser.getKey()); UpdateContentParams params = new UpdateContentParams(); params.contentKey = contentWithBinaryKey.toInt(); params.contentData = newContentData; params.publishFrom = new Date(); params.publishTo = null; params.createNewVersion = false; params.status = ContentStatus.STATUS_DRAFT; int contentVersionKey = internalClient.updateContent(params); fixture.flushAndClearHibernateSession(); ContentVersionEntity actualVersion = contentVersionDao.findByKey(new ContentVersionKey(contentVersionKey)); ContentEntity persistedContent = contentDao.findByKey(actualVersion.getContent().getKey()); assertEquals(runningUser, persistedContent.getAssignee()); assertEquals(runningUser, persistedContent.getAssigner()); assertEquals("test assignment", persistedContent.getAssignmentDescription()); assertEquals( new DateTime(2010, 6, 6, 10, 0, 0, 0).toDate(), persistedContent.getAssignmentDueDate()); }
public Document getContentBinary(GetContentBinaryParams params) throws ClientException { assertMinValue("contentKey", params.contentKey, 0); final UserEntity runAsUser = securityService.getImpersonatedPortalUser(); final ContentKey contentKey = new ContentKey(params.contentKey); final ContentEntity content = contentDao.findByKey(contentKey); if (content == null || content.isDeleted()) { throw AttachmentNotFoundException.notFound(contentKey); } if (!new ContentAccessResolver(groupDao).hasReadContentAccess(runAsUser, content)) { throw AttachmentNotFoundException.noAccess(content.getKey()); } if (!params.includeOfflineContent) { checkContentIsOnline(content); } ContentBinaryDataEntity contentBinaryData; if (params.label == null) { contentBinaryData = content.getMainVersion().getContentBinaryData("source"); if (contentBinaryData == null) { contentBinaryData = content.getMainVersion().getOneAndOnlyContentBinaryData(); } } else { contentBinaryData = content.getMainVersion().getContentBinaryData(params.label); } if (contentBinaryData == null) { throw AttachmentNotFoundException.notFound(contentKey); } return createBinaryDocument(createBinaryData(contentBinaryData)); }
private void createUpdateContentWithBinary() { UserEntity runningUser = fixture.findUserByName("testuser"); // prepare: save a new content ContentEntity content = new ContentEntity(); content.setPriority(0); content.setAvailableFrom(null); content.setAvailableTo(null); content.setCategory(fixture.findCategoryByName("MyCategory")); content.setLanguage(fixture.findLanguageByCode("en")); content.setName("testcontentwithbinary"); ContentVersionEntity version = new ContentVersionEntity(); version.setContent(content); version.setModifiedBy(runningUser); version.setStatus(com.enonic.cms.core.content.ContentStatus.DRAFT); version.setContent(content); CustomContentData contentData = new CustomContentData( fixture.findContentTypeByName("MyContentType").getContentTypeConfig()); TextDataEntryConfig titleConfig = (TextDataEntryConfig) contentData.getContentTypeConfig().getForm().getInputConfig("myTitle"); TextDataEntryConfig updateFieldConfig = (TextDataEntryConfig) contentData.getContentTypeConfig().getForm().getInputConfig("fieldToUpdate"); BinaryDataEntryConfig binaryConfig = (BinaryDataEntryConfig) contentData.getContentTypeConfig().getForm().getInputConfig("myBinaryfile"); contentData.add(new TextDataEntry(titleConfig, "testitle")); contentData.add(new TextDataEntry(updateFieldConfig, "foobar")); contentData.add(new BinaryDataEntry(binaryConfig, "%0")); version.setContentData(contentData); version.setTitle(contentData.getTitle()); CreateContentCommand createContentCommand = new CreateContentCommand(); createContentCommand.setCreator(runningUser); createContentCommand.populateCommandWithContentValues(content); createContentCommand.populateCommandWithContentVersionValues(version); List<BinaryDataAndBinary> binaryDatas = new ArrayList<BinaryDataAndBinary>(); binaryDatas.add(factory.createBinaryDataAndBinary("dummyBinary", dummyBinary)); createContentCommand.setBinaryDatas(binaryDatas); createContentCommand.setUseCommandsBinaryDataToAdd(true); contentWithBinaryKey = contentService.createContent(createContentCommand); fixture.flushAndClearHibernateSession(); }
private void doSetContentHome( final ContentEntity content, final MenuItemEntity section, final PageTemplateEntity pageTemplate) { final ContentHomeEntity existingHome = content.getContentHome(section.getSite().getKey()); if (existingHome != null) { existingHome.setMenuItem(section); existingHome.setPageTemplate(pageTemplate); } else { final ContentHomeEntity newContentHome = new ContentHomeEntity(); newContentHome.setKey(new ContentHomeKey(section.getSite().getKey(), content.getKey())); newContentHome.setSite(section.getSite()); newContentHome.setContent(content); newContentHome.setMenuItem(section); newContentHome.setPageTemplate(pageTemplate); contentHomeDao.storeNew(newContentHome); content.addContentHome(newContentHome); } indexTransactionService.registerUpdate(content.getKey(), true); }
private void doExecuteRemoveContentsFromSectionCommand( final RemoveContentsFromSectionCommand command) { Preconditions.checkNotNull(command.getSection(), "section cannot be null"); Preconditions.checkNotNull(command.getRemover(), "remover cannot be null"); Preconditions.checkNotNull(command.getContentsToRemove(), "content to remove cannot be null"); final UserEntity remover = userDao.findByKey(command.getRemover()); final MenuItemEntity section = doResolveSection(command.getSection()); final MenuItemAccessResolver menuItemAccessResolver = new MenuItemAccessResolver(groupDao); for (ContentKey contentKey : command.getContentsToRemove()) { final SectionContentEntity sectionContentToRemove = section.getSectionContent(contentKey); Preconditions.checkNotNull( sectionContentToRemove, "content in section (" + section.getKey() + ") not found: " + contentKey); final boolean contentIsApprovedInSection = sectionContentToRemove.isApproved(); if (contentIsApprovedInSection) { menuItemAccessResolver.checkAccessToUnapproveContentInSection( remover, section, "Cannot remove approved content from section."); } else { menuItemAccessResolver.checkAccessToRemoveUnapprovedContentFromSection( remover, section, "Cannot remove unapproved content from section."); } final ContentEntity content = contentDao.findByKey(contentKey); content.removeSectionContent(command.getSection()); sectionContentDao.getHibernateTemplate().flush(); sectionContentDao .getHibernateTemplate() .getSessionFactory() .evictCollection(MenuItemEntity.class.getName() + ".sectionContents", section.getKey()); removeContentHomeIfThisSectionIs(content, section); indexTransactionService.registerUpdate(content.getKey(), true); } }
public ContentEntity createContent( String contentName, String categoryName, String languageCode, String ownerQualifiedName, String priority, Date created) { ContentEntity content = new ContentEntity(); content.setLanguage(fixture.findLanguageByCode(languageCode)); content.setCategory(fixture.findCategoryByName(categoryName)); content.setOwner(fixture.findUserByName(ownerQualifiedName)); content.setPriority(Integer.valueOf(priority)); content.setCreatedAt(created); // Not-null field in database. content.setDeleted(false); // Not-null field in database. content.setName(contentName); return content; }
private void doExecuteSetContentHomeCommand(final SetContentHomeCommand command) { Preconditions.checkNotNull(command.getSetter(), "setter cannot be null"); Preconditions.checkNotNull(command.getContent(), "content to set home for cannot be null"); Preconditions.checkNotNull(command.getSection(), "section to set home to cannot be null"); final UserEntity setter = doResolveUser(command.getSetter(), "setter"); final ContentEntity content = contentDao.findByKey(command.getContent()); final MenuItemEntity section = doResolveSection(command.getSection()); final CategoryAccessResolver categoryAccessResolver = new CategoryAccessResolver(groupDao); if (!categoryAccessResolver.hasApproveContentAccess(setter, content.getCategory())) { throw new CategoryAccessException( "Cannot set content home", setter.getQualifiedName(), CategoryAccessType.APPROVE, content.getCategory().getKey()); } PageTemplateEntity pageTemplate = null; if (command.getPageTemplate() != null) { pageTemplate = pageTemplateDao.findByKey(command.getPageTemplate().toInt()); } doSetContentHome(content, section, pageTemplate); }
private void createUpdateContent() { UserEntity runningUser = fixture.findUserByName("testuser"); // prepare: save a new content ContentEntity content = new ContentEntity(); content.setPriority(0); content.setAvailableFrom(new Date()); content.setAvailableTo(null); content.setCategory(fixture.findCategoryByName("MyCategory")); content.setLanguage(fixture.findLanguageByCode("en")); content.setName("testcontent"); ContentVersionEntity version = new ContentVersionEntity(); version.setContent(content); version.setModifiedBy(runningUser); version.setStatus(com.enonic.cms.core.content.ContentStatus.APPROVED); version.setContent(content); CustomContentData contentData = new CustomContentData( fixture.findContentTypeByName("MyContentType").getContentTypeConfig()); TextDataEntryConfig titleConfig = (TextDataEntryConfig) contentData.getContentTypeConfig().getForm().getInputConfig("myTitle"); TextDataEntryConfig updateFieldConfig = (TextDataEntryConfig) contentData.getContentTypeConfig().getForm().getInputConfig("fieldToUpdate"); contentData.add(new TextDataEntry(titleConfig, "testitle")); contentData.add(new TextDataEntry(updateFieldConfig, "foobar")); version.setContentData(contentData); version.setTitle(contentData.getTitle()); CreateContentCommand createContentCommand = new CreateContentCommand(); createContentCommand.setCreator(runningUser); createContentCommand.setAccessRightsStrategy(AccessRightsStrategy.USE_GIVEN); createContentCommand.populateCommandWithContentValues(content); createContentCommand.populateCommandWithContentVersionValues(version); updateContentKey = contentService.createContent(createContentCommand); fixture.flushAndClearHibernateSession(); }
private ContentTypeEntity resolveContentType(int contentKey) { ContentEntity persistedContent = contentDao.findByKey(new ContentKey(contentKey)); return persistedContent.getCategory().getContentType(); }
private void doExecuteAddContentToSectionCommand(final AddContentToSectionCommand command) { Preconditions.checkNotNull(command, "a command is required"); Preconditions.checkNotNull( command.getContributor(), "the command's contributor argument is required"); Preconditions.checkNotNull(command.getContent(), "the command's content argument is required"); Preconditions.checkNotNull(command.getSection(), "the command's section argument is required"); if (!command.isApproveInSection()) { Preconditions.checkArgument( !command.isAddOnTop(), "no point in adding content to top when not approving"); } final ContentEntity content = contentDao.findByKey(command.getContent()); Preconditions.checkNotNull(content, "content does not exist: " + command.getContent()); Preconditions.checkArgument( !content.isDeleted(), "content is deleted: " + command.getContent()); final MenuItemEntity section = doResolveSection(command.getSection()); if (!section.isOrderedSection()) { Preconditions.checkArgument( command.getOrderContentsInSectionCommand() == null, "section is not ordered, did not expect to get order specified in command"); } final UserEntity contributor = doResolveUser(command.getContributor(), "contributor"); final MenuItemAccessResolver menuItemAccessResolver = new MenuItemAccessResolver(groupDao); menuItemAccessResolver.checkAccessToAddContentToSection( contributor, section, "Cannot add content in section."); if (command.isApproveInSection()) { menuItemAccessResolver.checkAccessToApproveContentInSection( contributor, section, "Cannot approve content in section."); } if (section.isSection() && section.hasSectionContentTypeFilter()) { if (!section.supportsSectionContentType(content.getCategory().getContentType())) { throw new ContentTypeNotSupportedException(content.getCategory().getContentType(), section); } } else if (section.getType() == MenuItemType.PAGE && section.getPage().getTemplate().getContentTypes().size() > 0) { if (!section .getPage() .getTemplate() .supportsContentType(content.getCategory().getContentType())) { throw new ContentTypeNotSupportedException(content.getCategory().getContentType(), section); } } final SectionContentEntity sectionContent = new SectionContentEntity(); sectionContent.setOrder(0); sectionContent.setContent(content); sectionContent.setMenuItem(section); sectionContent.setApproved(command.isApproveInSection()); sectionContent.setTimestamp(timeService.getNowAsDateTime().toDate()); if (command.isAddOnTop() && section.isOrderedSection()) { sectionContent.setOrder(resolveOrderValueForInsertOnTopOfApprovedContentInSection(section)); } content.addSectionContent(sectionContent); sectionContentDao.getHibernateTemplate().flush(); sectionContentDao .getHibernateTemplate() .getSessionFactory() .evictCollection(MenuItemEntity.class.getName() + ".sectionContents", section.getKey()); if (!content.hasHome(section.getSite().getKey())) { doSetContentHome(content, section, null); } if (section.isOrderedSection()) { if (command.getOrderContentsInSectionCommand() != null) { // ensure section will have it's newly added content sectionContentDao.getHibernateTemplate().refresh(section); List<ContentKey> wantedOrder = command.getOrderContentsInSectionCommand().getWantedOrder(); ContentsInSectionOrderer orderer = new ContentsInSectionOrderer(wantedOrder, section, ORDER_SPACE); orderer.order(); } } indexTransactionService.registerUpdate(command.getContent(), true); }
public static void enforceNoLazyInitialization(ContentEntity content) { content.setCategory( content.getCategory() != null ? new CategoryEntity(content.getCategory()) : null); content.setAssignee( content.getAssignee() != null ? new UserEntity(content.getAssignee()) : null); content.setAssigner( content.getAssigner() != null ? new UserEntity(content.getAssigner()) : null); content.setOwner(content.getOwner() != null ? new UserEntity(content.getOwner()) : null); content.setLanguage( content.getLanguage() != null ? new LanguageEntity(content.getLanguage()) : null); content.setDraftVersion( content.getDraftVersion() != null ? new ContentVersionEntity(content.getDraftVersion()) : null); content.setMainVersion( content.getMainVersion() != null ? new ContentVersionEntity(content.getMainVersion()) : null); }
@Test public void testCreateContentWithBlockGroup() { fixture.createAndStoreUserAndUserGroup( "testuser", "testuser fullname", UserType.NORMAL, "testuserstore"); fixture.save( factory.createContentHandler( "Custom content", ContentHandlerName.CUSTOM.getHandlerClassShortName())); // setup content type ContentTypeConfigBuilder ctyconf = new ContentTypeConfigBuilder("Skole", "tittel"); ctyconf.startBlock("Skole"); ctyconf.addInput("tittel", "text", "contentdata/tittel", "Tittel", true); ctyconf.endBlock(); ctyconf.startBlock("Elever", "contentdata/elever"); ctyconf.addInput("elev-navn", "text", "navn", "Navn"); ctyconf.addInput("elev-karakter", "text", "karakter", "Karakter"); ctyconf.endBlock(); ctyconf.startBlock("Laerere", "contentdata/laerere"); ctyconf.addInput("laerer-navn", "text", "navn", "Navn"); ctyconf.addInput("laerer-karakter", "text", "karakter", "Karakter"); ctyconf.endBlock(); Document configAsXmlBytes = XMLDocumentFactory.create(ctyconf.toString()).getAsJDOMDocument(); fixture.save( factory.createContentType( "Skole", ContentHandlerName.CUSTOM.getHandlerClassShortName(), configAsXmlBytes)); fixture.save(factory.createUnit("MyUnit", "en")); fixture.save(factory.createCategory("Skole", "Skole", "MyUnit", "testuser", "testuser")); fixture.save(factory.createCategoryAccessForUser("Skole", "testuser", "read,create,approve")); UserEntity runningUser = fixture.findUserByName("testuser"); PortalSecurityHolder.setImpersonatedUser(runningUser.getKey()); CreateContentParams content = new CreateContentParams(); content.categoryKey = fixture.findCategoryByName("Skole").getKey().toInt(); content.publishFrom = new Date(); content.status = ContentStatus.STATUS_APPROVED; ContentDataInput contentData = new ContentDataInput("Skole"); contentData.add(new TextInput("tittel", "St. Olav Videregaende skole")); GroupInput groupInputElev1 = contentData.addGroup("Elever"); groupInputElev1.add(new TextInput("elev-navn", "Vegar Jansen")); groupInputElev1.add(new TextInput("elev-karakter", "S")); GroupInput groupInputElev2 = contentData.addGroup("Elever"); groupInputElev2.add(new TextInput("elev-navn", "Thomas Sigdestad")); groupInputElev2.add(new TextInput("elev-karakter", "M")); GroupInput groupInputLaerer1 = contentData.addGroup("Laerere"); groupInputLaerer1.add(new TextInput("laerer-navn", "Mutt Hansen")); groupInputLaerer1.add(new TextInput("laerer-karakter", "LG")); GroupInput groupInputLaerer2 = contentData.addGroup("Laerere"); groupInputLaerer2.add(new TextInput("laerer-navn", "Striks Jansen")); groupInputLaerer2.add(new TextInput("laerer-karakter", "M")); content.contentData = contentData; ContentKey contentKey = new ContentKey(internalClient.createContent(content)); ContentEntity createdContent = fixture.findContentByKey(contentKey); ContentVersionEntity createdVersion = createdContent.getMainVersion(); CustomContentData createdContentData = (CustomContentData) createdVersion.getContentData(); BlockGroupDataEntries elever = createdContentData.getBlockGroupDataEntries("Elever"); GroupDataEntry elev1 = elever.getGroupDataEntry(1); assertEquals("Vegar Jansen", ((TextDataEntry) elev1.getEntry("elev-navn")).getValue()); assertEquals("S", ((TextDataEntry) elev1.getEntry("elev-karakter")).getValue()); GroupDataEntry elev2 = elever.getGroupDataEntry(2); assertEquals("Thomas Sigdestad", ((TextDataEntry) elev2.getEntry("elev-navn")).getValue()); assertEquals("M", ((TextDataEntry) elev2.getEntry("elev-karakter")).getValue()); BlockGroupDataEntries laerere = createdContentData.getBlockGroupDataEntries("Laerere"); GroupDataEntry laerer1 = laerere.getGroupDataEntry(1); assertEquals("Mutt Hansen", ((TextDataEntry) laerer1.getEntry("laerer-navn")).getValue()); assertEquals("LG", ((TextDataEntry) laerer1.getEntry("laerer-karakter")).getValue()); GroupDataEntry laerer2 = laerere.getGroupDataEntry(2); assertEquals("Striks Jansen", ((TextDataEntry) laerer2.getEntry("laerer-navn")).getValue()); assertEquals("M", ((TextDataEntry) laerer2.getEntry("laerer-karakter")).getValue()); }
@Test public void testUpdateCurrentVersion() { ContentKey relatedContentKey1 = storeSimpleContent("rel1"); ContentKey relatedContentKey2 = storeSimpleContent("rel2"); ContentKey relatedContentKey3 = storeSimpleContent("rel3"); ContentKey relatedContentKey4 = storeSimpleContent("rel4"); ContentKey relatedContentKey5 = storeSimpleContent("rel5"); ContentEntity content = factory.createContent("MyCategory", "en", "testuser", "0", new Date()); ContentVersionEntity version = factory.createContentVersion("0", "testuser"); ContentTypeConfig contentTypeConfig = ContentTypeConfigParser.parse(ContentHandlerName.CUSTOM, configEl); CustomContentData contentData = new CustomContentData(contentTypeConfig); TextDataEntryConfig titleConfig = new TextDataEntryConfig("myTitle", true, "Tittel", "contentdata/mytitle"); contentData.add(new TextDataEntry(titleConfig, "test title")); RelatedContentDataEntryConfig multipleRelatedContentsConfig = (RelatedContentDataEntryConfig) contentTypeConfig.getInputConfig("myMultipleRelatedContent"); contentData.add( new RelatedContentsDataEntry(multipleRelatedContentsConfig) .add(new RelatedContentDataEntry(multipleRelatedContentsConfig, relatedContentKey1)) .add(new RelatedContentDataEntry(multipleRelatedContentsConfig, relatedContentKey2))); RelatedContentDataEntryConfig soleRelatedConfig = (RelatedContentDataEntryConfig) contentTypeConfig.getInputConfig("mySoleRelatedContent"); contentData.add(new RelatedContentDataEntry(soleRelatedConfig, relatedContentKey3)); version.setContentData(contentData); UserEntity runningUser = fixture.findUserByName("testuser"); CreateContentCommand createContentCommand = new CreateContentCommand(); createContentCommand.setCreator(runningUser); createContentCommand.populateCommandWithContentValues(content); createContentCommand.populateCommandWithContentVersionValues(version); createContentCommand.setBinaryDatas(new ArrayList<BinaryDataAndBinary>()); createContentCommand.setUseCommandsBinaryDataToAdd(true); ContentKey contentKey = contentService.createContent(createContentCommand); hibernateTemplate.flush(); hibernateTemplate.clear(); ContentEntity persistedContent = contentDao.findByKey(contentKey); assertNotNull(persistedContent); ContentVersionEntity persistedVersion = persistedContent.getMainVersion(); assertNotNull(persistedVersion); assertEquals(3, persistedVersion.getRelatedChildren(true).size()); ContentEntity changedContent = factory.createContent("MyCategory", "en", "testuser", "0", new Date()); changedContent.setKey(contentKey); ContentVersionEntity changedVersion = factory.createContentVersion("0", "testuser"); changedVersion.setKey(persistedVersion.getKey()); CustomContentData changedCD = new CustomContentData(contentTypeConfig); TextDataEntryConfig changedTitleConfig = new TextDataEntryConfig("myTitle", true, "Tittel", "contentdata/mytitle"); changedCD.add(new TextDataEntry(changedTitleConfig, "changed title")); changedCD.add( new RelatedContentsDataEntry(multipleRelatedContentsConfig) .add(new RelatedContentDataEntry(multipleRelatedContentsConfig, relatedContentKey3)) .add(new RelatedContentDataEntry(multipleRelatedContentsConfig, relatedContentKey5))); changedCD.add(new RelatedContentDataEntry(soleRelatedConfig, relatedContentKey4)); changedVersion.setContentData(changedCD); UpdateContentCommand updateContentCommand = UpdateContentCommand.updateExistingVersion2(persistedVersion.getKey()); updateContentCommand.setModifier(runningUser); updateContentCommand.setUpdateAsMainVersion(false); updateContentCommand.populateContentValuesFromContent(persistedContent); updateContentCommand.populateContentVersionValuesFromContentVersion(changedVersion); contentService.updateContent(updateContentCommand); hibernateTemplate.flush(); hibernateTemplate.clear(); ContentEntity contentAfterUpdate = contentDao.findByKey(contentKey); ContentVersionEntity versionAfterUpdate = contentVersionDao.findByKey(persistedVersion.getKey()); Document contentDataXmlAfterUpdate = versionAfterUpdate.getContentDataAsJDomDocument(); AssertTool.assertXPathEquals( "/contentdata/mysolerelatedcontent/@key", contentDataXmlAfterUpdate, relatedContentKey4.toString()); AssertTool.assertXPathEquals( "/contentdata/myrelatedcontents/content[1]/@key", contentDataXmlAfterUpdate, relatedContentKey3.toString()); AssertTool.assertXPathEquals( "/contentdata/myrelatedcontents/content[2]/@key", contentDataXmlAfterUpdate, relatedContentKey5.toString()); assertEquals(3, versionAfterUpdate.getRelatedChildren(true).size()); }