@Before
  public void before() throws IOException, JDOMException {

    factory = fixture.getFactory();
    fixture.initSystemData();

    StringBuffer standardConfigXml = new StringBuffer();
    standardConfigXml.append("<config name=\"MyContentType\" version=\"1.0\">");
    standardConfigXml.append("     <form>");

    standardConfigXml.append("         <title name=\"myTitle\"/>");

    standardConfigXml.append("         <block name=\"TestBlock1\">");

    standardConfigXml.append(
        "             <input name=\"myTitle\" required=\"true\" type=\"text\">");
    standardConfigXml.append("                 <display>My title</display>");
    standardConfigXml.append("                 <xpath>contentdata/mytitle</xpath>");
    standardConfigXml.append("             </input>");

    standardConfigXml.append("             <input name=\"myBinaryfile\" type=\"uploadfile\">");
    standardConfigXml.append("                 <display>My binaryfile</display>");
    standardConfigXml.append("                 <xpath>contentdata/mybinaryfile</xpath>");
    standardConfigXml.append("             </input>");

    standardConfigXml.append("         </block>");
    standardConfigXml.append("     </form>");
    standardConfigXml.append("</config>");
    standardConfig = XMLDocumentFactory.create(standardConfigXml.toString()).getAsJDOMDocument();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("127.0.0.1");
    ServletRequestAccessor.setRequest(request);
  }
  @After
  public void shutdown() throws Exception {

    fixture.flushAndClearHibernateSession();
    fixture.flushIndexTransaction();
    System.out.println("Shutting down everything");

    Thread.sleep(1000);
  }
  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 ContentKey storeSimpleContent(String title) {

    ContentEntity content = factory.createContent("MyCategory", "en", "testuser", "0", new Date());
    ContentVersionEntity version = factory.createContentVersion("0", "testuser");

    ContentTypeConfig contentTypeConfig =
        ContentTypeConfigParser.parse(ContentHandlerName.CUSTOM, createSimpleContentTypeConfig());

    CustomContentData contentData = new CustomContentData(contentTypeConfig);

    TextDataEntryConfig titleConfig =
        new TextDataEntryConfig("myTitle", true, title, "contentdata/mytitle");
    contentData.add(new TextDataEntry(titleConfig, "relatedconfig"));

    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();

    return contentKey;
  }
 private CreateContentCommand createCreateContentCommand(
     String categoryName, ContentData contentData, String creatorUid) {
   CreateContentCommand createContentCommand = new CreateContentCommand();
   createContentCommand.setCategory(fixture.findCategoryByName(categoryName));
   createContentCommand.setCreator(fixture.findUserByName(creatorUid).getKey());
   createContentCommand.setLanguage(fixture.findLanguageByCode("en"));
   createContentCommand.setStatus(ContentStatus.APPROVED);
   createContentCommand.setPriority(0);
   createContentCommand.setAccessRightsStrategy(
       CreateContentCommand.AccessRightsStrategy.INHERIT_FROM_CATEGORY);
   createContentCommand.setContentData(contentData);
   createContentCommand.setAvailableFrom(DATE_TIME_2010_01_01.toDate());
   createContentCommand.setAvailableTo(null);
   createContentCommand.setContentName("testcontent");
   return createContentCommand;
 }
  @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 request_user_image() throws Exception {
    byte[] bytes = loadImage("Arn.JPG");
    UserEntity testUser = fixture.findUserByName("testuser");
    testUser.setPhoto(bytes);

    fixture.flushAndClearHibernateSesssion();

    String imageRequestPath = "_image/user/" + testUser.getKey() + ".jpg";
    setPathInfoAndRequestURI(httpServletRequest, imageRequestPath);
    httpServletRequest.setParameter("_background", "0xffffff");
    httpServletRequest.setParameter("_quality", "100");
    imageController.handleRequestInternal(httpServletRequest, httpServletResponse);

    assertEquals(HttpServletResponse.SC_OK, httpServletResponse.getStatus());
    assertEquals("image/jpg", httpServletResponse.getContentType());
  }
 private ContentVersionEntity createDraftVersion(String title) {
   ContentVersionEntity draftVersion =
       factory.createContentVersion("" + ContentStatus.DRAFT.getKey(), "testuser/testuserstore");
   draftVersion.setCreatedAt(new Date());
   draftVersion.setModifiedAt(new Date());
   draftVersion.setModifiedBy(fixture.findUserByName("testuser"));
   draftVersion.setTitle(title);
   return draftVersion;
 }
  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();
  }
  @Before
  public void before() throws IOException, JDOMException {
    factory = fixture.getFactory();
    fixture.initSystemData();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("127.0.0.1");
    ServletRequestAccessor.setRequest(request);

    createContentTypeXml();

    saveNeededEntities();

    UserEntity runningUser = fixture.findUserByName("testuser");
    PortalSecurityHolder.setImpersonatedUser(runningUser.getKey());

    createUpdateContent();
    createUpdateContentWithBinary();
  }
  @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());
  }
  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;
  }
  @Test
  public void
      update_existing_version_with_publishFrom_without_contentdata_changes_only_publishFrom() {
    CreateContentParams createParams = new CreateContentParams();
    createParams.categoryKey = fixture.findCategoryByName("MyCategory").getKey().toInt();
    createParams.publishFrom = new DateTime(2100, 1, 1, 0, 0, 0, 0).toDate();
    createParams.status = ContentStatus.STATUS_APPROVED;
    ContentDataInput contentdataForCreate = new ContentDataInput("MyContentType");
    contentdataForCreate.add(new TextInput("myTitle", "title from creation"));
    createParams.contentData = contentdataForCreate;
    ContentKey contentKeyToUpdate = new ContentKey(internalClient.createContent(createParams));

    UpdateContentParams updateParams = new UpdateContentParams();
    updateParams.updateStrategy = ContentDataInputUpdateStrategy.REPLACE_NEW;
    updateParams.contentKey = contentKeyToUpdate.toInt();
    updateParams.createNewVersion = false;
    updateParams.publishFrom = new DateTime(2010, 1, 1, 0, 0, 0, 0).toDate();
    updateParams.setAsCurrentVersion = true;
    updateParams.status = null;

    ContentVersionKey versionKey =
        new ContentVersionKey(internalClient.updateContent(updateParams));
    assertNotNull(versionKey);

    assertEquals(1, fixture.countContentVersionsByTitle("title from creation"));
    assertEquals(
        versionKey, fixture.findFirstContentVersionByTitle("title from creation").getKey());
    assertEquals(
        new DateTime(2010, 1, 1, 0, 0, 0, 0).toDate(),
        fixture
            .findFirstContentVersionByTitle("title from creation")
            .getContent()
            .getAvailableFrom());
    assertEquals(
        1,
        fixture
            .findFirstContentVersionByTitle("title from creation")
            .getContent()
            .getVersions()
            .size());
  }
  @Test
  public void request_content_image_with_no_access() 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);

    fixture.createAndStoreUserAndUserGroup(
        "user-with-no-access", "testuser fullname", UserType.NORMAL, "testuserstore");
    loginUserInAdmin(fixture.findUserByName("user-with-no-access").getKey());

    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);
  }
  @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());
  }
  @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);
  }
 private ContentData createMyRelatedContentData(String title, ContentKey... relatedContents) {
   CustomContentData contentData =
       new CustomContentData(
           fixture.findContentTypeByName("MyRelatedType").getContentTypeConfig());
   if (title != null) {
     contentData.add(new TextDataEntry(contentData.getInputConfig("title"), title));
   }
   if (relatedContents != null && relatedContents.length > 0) {
     RelatedContentsDataEntry relatedContentsDataEntry =
         new RelatedContentsDataEntry(contentData.getInputConfig("myRelatedContent"));
     for (ContentKey relatedKey : relatedContents) {
       relatedContentsDataEntry.add(
           new RelatedContentDataEntry(
               contentData.getInputConfig("myRelatedContent"), relatedKey));
     }
     contentData.add(relatedContentsDataEntry);
   }
   return contentData;
 }
 private void saveNeededEntities() {
   // prepare: save needed entities
   fixture.createAndStoreUserAndUserGroup(
       "testuser", "testuser fullname", UserType.NORMAL, "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", null, "MyContentType", "MyUnit", "testuser", "testuser"));
   fixture.save(
       factory.createCategoryAccessForUser("MyCategory", "testuser", "read, create, approve"));
   fixture.flushAndClearHibernateSession();
 }
  private ContentKey createImageContent(
      String name,
      int contentStatus,
      byte[] bytes,
      String categoryName,
      DateTime availableFrom,
      DateTime availableTo)
      throws IOException {
    ImageContentDataInput imageContentDataInput = new ImageContentDataInput();
    imageContentDataInput.name = new ImageNameInput(name);
    imageContentDataInput.binary = new ImageBinaryInput(bytes, name);

    CreateImageContentParams params = new CreateImageContentParams();
    params.categoryKey = fixture.findCategoryByName(categoryName).getKey().toInt();
    params.publishFrom = availableFrom != null ? availableFrom.toDate() : null;
    params.publishTo = availableTo != null ? availableTo.toDate() : null;
    params.status = contentStatus;
    params.contentData = imageContentDataInput;

    return new ContentKey(internalClientContentService.createImageContent(params));
  }
  @Before
  public void setUp() {

    factory = fixture.getFactory();

    // setup needed common data for each test
    fixture.initSystemData();

    fixture.save(
        factory.createContentHandler(
            "Custom content", ContentHandlerName.CUSTOM.getHandlerClassShortName()));

    MockHttpServletRequest httpRequest = new MockHttpServletRequest("GET", "/");
    ServletRequestAccessor.setRequest(httpRequest);

    dataSourceService = new DataSourceServiceImpl();
    dataSourceService.setContentService(contentService);
    dataSourceService.setTimeService(new MockTimeService(new DateTime(2010, 7, 1, 12, 0, 0, 0)));
    dataSourceService.setUserDao(userDao);

    fixture.createAndStoreNormalUserWithUserGroup("content-creator", "Creator", "testuserstore");
    fixture.createAndStoreNormalUserWithUserGroup("content-querier", "Querier", "testuserstore");

    // setup content type
    ContentTypeConfigBuilder ctyconf = new ContentTypeConfigBuilder("MyContent", "title");
    ctyconf.startBlock("MyContent");
    ctyconf.addInput("title", "text", "contentdata/title", "Title", true);
    ctyconf.addRelatedContentInput(
        "myRelatedContent", "contentdata/myRelatedContent", "My related content", false, true);
    ctyconf.endBlock();
    Document configAsXmlBytes = XMLDocumentFactory.create(ctyconf.toString()).getAsJDOMDocument();

    fixture.save(
        factory.createContentType(
            "MyRelatedType",
            ContentHandlerName.CUSTOM.getHandlerClassShortName(),
            configAsXmlBytes));
    fixture.save(factory.createUnit("MyUnit", "en"));
    fixture.save(
        factory.createCategory(
            "MyCategory",
            null,
            "MyRelatedType",
            "MyUnit",
            User.ANONYMOUS_UID,
            User.ANONYMOUS_UID,
            false));
    fixture.save(
        factory.createCategory(
            "MyOtherCategory",
            null,
            "MyRelatedType",
            "MyUnit",
            User.ANONYMOUS_UID,
            User.ANONYMOUS_UID,
            false));

    fixture.save(
        factory.createCategoryAccessForUser(
            "MyCategory", "content-creator", "read, create, approve, admin_browse"));
    fixture.save(
        factory.createCategoryAccessForUser("MyCategory", "content-querier", "read, admin_browse"));
    fixture.save(
        factory.createCategoryAccessForUser(
            "MyOtherCategory", "content-creator", "read, create, approve, admin_browse"));
    fixture.save(
        factory.createCategoryAccessForUser(
            "MyOtherCategory", "content-querier", "read, admin_browse"));

    fixture.flushAndClearHibernateSession();
    fixture.flushIndexTransaction();
  }
  @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());
  }
  @Before
  public void before() throws IOException, JDOMException {

    factory = fixture.getFactory();

    fixture.initSystemData();

    StringBuffer configXml = new StringBuffer();
    configXml.append("<config name=\"MyContentType\" version=\"1.0\">");
    configXml.append("     <form>");

    configXml.append("         <title name=\"myTitle\"/>");

    configXml.append("         <block name=\"General\">");

    configXml.append("             <input name=\"myTitle\" required=\"true\" type=\"text\">");
    configXml.append("                 <display>My title</display>");
    configXml.append("                 <xpath>contentdata/mytitle</xpath>");
    configXml.append("             </input>");

    configXml.append("         </block>");

    configXml.append("         <block name=\"Related content\">");

    configXml.append(
        "             <input name=\"myMultipleRelatedContent\" type=\"relatedcontent\" multiple=\"true\">");
    configXml.append("                 <display>My related content</display>");
    configXml.append("                 <xpath>contentdata/myrelatedcontents</xpath>");
    configXml.append("             </input>");

    configXml.append(
        "             <input name=\"mySoleRelatedContent\" type=\"relatedcontent\" multiple=\"false\">");
    configXml.append("                 <display>My sole related content</display>");
    configXml.append("                 <xpath>contentdata/mysolerelatedcontent</xpath>");
    configXml.append("                 <contenttype name=\"MyContentType\"/>");
    configXml.append("             </input>");

    configXml.append("         </block>");
    configXml.append("     </form>");
    configXml.append("</config>");
    configEl = JDOMUtil.parseDocument(configXml.toString()).getRootElement();
    config = XMLDocumentFactory.create(configXml.toString()).getAsJDOMDocument();

    fixture.createAndStoreNormalUserWithUserGroup("testuser", "testuser fullname", "testuserstore");
    hibernateTemplate.save(
        factory.createContentHandler(
            "Custom content", ContentHandlerName.CUSTOM.getHandlerClassShortName()));
    hibernateTemplate.save(
        factory.createContentType(
            "MyContentType", ContentHandlerName.CUSTOM.getHandlerClassShortName(), config));
    hibernateTemplate.save(factory.createUnit("MyUnit"));
    hibernateTemplate.save(
        factory.createCategory(
            "MyCategory", null, "MyContentType", "MyUnit", "testuser", "testuser"));
    hibernateTemplate.save(
        factory.createCategoryAccess(
            "MyCategory", fixture.findUserByName("testuser"), "read, create, approve"));

    hibernateTemplate.flush();
    hibernateTemplate.clear();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("127.0.0.1");
    ServletRequestAccessor.setRequest(request);
  }
  @Before
  public void before() {
    factory = fixture.getFactory();

    fixture.initSystemData();
    fixture.createAndStoreUserAndUserGroup(
        "testuser", "testuser fullname", UserType.NORMAL, "testuserstore");

    ServletRequestAttributes servletRequestAttributes =
        new ServletRequestAttributes(httpServletRequest);
    RequestContextHolder.setRequestAttributes(servletRequestAttributes);
    httpServletRequest.setCharacterEncoding("UTF-8");
    ServletRequestAccessor.setRequest(httpServletRequest);

    loginUserInAdmin(fixture.findUserByName("testuser").getKey());
    loginUserInPortal(fixture.findUserByName("testuser").getKey());

    imageController.setGroupDao(groupDao);
    imageController.setContentDao(contentDao);
    imageController.setSecurityService(securityService);
    imageController.setImageService(imageService);
    imageController.setDisableParamEncoding(true);

    previewService = Mockito.mock(PreviewService.class);
    Mockito.when(previewService.isInPreview()).thenReturn(false);
    Mockito.when(previewService.getPreviewContext()).thenReturn(PreviewContext.NO_PREVIEW);

    site1 = factory.createSite("MySite", new Date(), null, "en");
    fixture.save(site1);
    MenuItemEntity firstPage = createPage("Firstpage", null, "MySite");
    fixture.save(firstPage);

    site1.setFirstPage(firstPage);

    fixture.flushAndClearHibernateSesssion();

    fixture.save(
        factory.createContentHandler(
            "Image content", ContentHandlerName.IMAGE.getHandlerClassShortName()));
    fixture.save(
        factory.createContentType(
            "ImageContentType", ContentHandlerName.IMAGE.getHandlerClassShortName()));
    fixture.save(factory.createUnit("ImageUnit"));
    fixture.save(
        factory.createCategory(
            "ImageCategory", "ImageContentType", "ImageUnit", "testuser", "testuser"));
    fixture.save(
        factory.createCategoryAccessForUser("ImageCategory", "testuser", "read, create, approve"));

    fixture.flushAndClearHibernateSesssion();
  }
  @Test
  public void
      content_queried_with_both_related_child_and_parent_having_related_content_existing_as_the_queried_content_is_still_listed_as_related_content() {
    // setup: create same content in two different categories
    ContentKey grandChildContentKey =
        contentService.createContent(
            createCreateContentCommand(
                "MyCategory", createMyRelatedContentData("Grand child"), "content-creator"));

    ContentKey sonContentKey =
        contentService.createContent(
            createCreateContentCommand(
                "MyCategory",
                createMyRelatedContentData("Son", grandChildContentKey),
                "content-creator"));

    ContentKey daughterContentKey =
        contentService.createContent(
            createCreateContentCommand(
                "MyCategory", createMyRelatedContentData("Daughter"), "content-creator"));

    ContentKey fatherContentKey =
        contentService.createContent(
            createCreateContentCommand(
                "MyCategory",
                createMyRelatedContentData("Father", sonContentKey, daughterContentKey),
                "content-creator"));

    fixture.flushIndexTransaction();

    // setup: verify that the content was created
    assertEquals(4, fixture.countAllContent());

    // exercise
    DataSourceContext context = new DataSourceContext();
    context.setUser(fixture.findUserByName("content-querier"));

    String query = "categorykey = " + fixture.findCategoryByName("MyCategory").getKey();
    String orderyBy = "@key desc";
    int index = 0;
    int count = 10;
    boolean includeData = true;
    int childrenLevel = 10;
    int parentLevel = 10;

    XMLDocument xmlDocResult =
        dataSourceService.getContentByQuery(
            context, query, orderyBy, index, count, includeData, childrenLevel, parentLevel, null);

    // verify
    Document jdomDocResult = xmlDocResult.getAsJDOMDocument();

    AssertTool.assertSingleXPathValueEquals("/contents/@totalcount", jdomDocResult, "4");
    AssertTool.assertXPathEquals(
        "/contents/content/@key",
        jdomDocResult,
        fatherContentKey.toString(),
        daughterContentKey.toString(),
        sonContentKey.toString(),
        grandChildContentKey.toString());

    AssertTool.assertXPathEquals(
        "/contents/content[title = 'Father']/relatedcontentkeys/relatedcontentkey [@level = 1]/@key",
        jdomDocResult,
        sonContentKey.toString(),
        daughterContentKey.toString());

    AssertTool.assertXPathEquals(
        "/contents/content[title = 'Daughter']/relatedcontentkeys/relatedcontentkey[@level = -1]/@key",
        jdomDocResult,
        fatherContentKey.toString());
    AssertTool.assertXPathEquals(
        "/contents/content[title = 'Son']/relatedcontentkeys/relatedcontentkey[@level = -1]/@key",
        jdomDocResult,
        fatherContentKey.toString());
    AssertTool.assertXPathEquals(
        "/contents/content[title = 'Son']/relatedcontentkeys/relatedcontentkey[@level = 1]/@key",
        jdomDocResult,
        grandChildContentKey.toString());
    AssertTool.assertXPathEquals(
        "/contents/content[title = 'Grand child']/relatedcontentkeys/relatedcontentkey[@level = -1]/@key",
        jdomDocResult,
        sonContentKey.toString());
    AssertTool.assertSingleXPathValueEquals("/contents/relatedcontents/@count", jdomDocResult, "4");
    AssertTool.assertXPathEquals(
        "/contents/relatedcontents/content/@key",
        jdomDocResult,
        grandChildContentKey.toString(),
        sonContentKey.toString(),
        daughterContentKey.toString(),
        fatherContentKey.toString());
  }
  @Test
  public void
      common_content_related_to_between_two_content_is_listed_both_contents_relatedcontentkeys() {
    // setup: create same content in two different categories
    ContentKey commonChildContentKey =
        contentService.createContent(
            createCreateContentCommand(
                "MyCategory", createMyRelatedContentData("Common child"), "content-creator"));

    ContentKey contentA =
        contentService.createContent(
            createCreateContentCommand(
                "MyCategory",
                createMyRelatedContentData("Content A", commonChildContentKey),
                "content-creator"));

    ContentKey contentB =
        contentService.createContent(
            createCreateContentCommand(
                "MyCategory",
                createMyRelatedContentData("Content B", commonChildContentKey),
                "content-creator"));

    fixture.flushIndexTransaction();

    // setup: verify that 2 content is created
    assertEquals(3, fixture.countAllContent());

    // exercise
    DataSourceContext context = new DataSourceContext();
    context.setUser(fixture.findUserByName("content-querier"));

    String query = "title STARTS WITH 'Content '";
    String orderBy = "@title asc";
    int index = 0;
    int count = 10;
    boolean includeData = true;
    int childrenLevel = 1;
    int parentLevel = 0;

    XMLDocument xmlDocResult =
        dataSourceService.getContentByQuery(
            context, query, orderBy, index, count, includeData, childrenLevel, parentLevel, null);

    // verify
    Document jdomDocResult = xmlDocResult.getAsJDOMDocument();

    System.out.println(JDOMUtil.prettyPrintDocument(jdomDocResult));

    AssertTool.assertSingleXPathValueEquals("/contents/@totalcount", jdomDocResult, "2");
    AssertTool.assertXPathEquals(
        "/contents/content/@key", jdomDocResult, contentA.toString(), contentB.toString());
    AssertTool.assertXPathEquals(
        "/contents/content[ title = 'Content A']/relatedcontentkeys/relatedcontentkey/@key",
        jdomDocResult,
        commonChildContentKey.toString());
    AssertTool.assertXPathEquals(
        "/contents/content[ title = 'Content B']/relatedcontentkeys/relatedcontentkey/@key",
        jdomDocResult,
        commonChildContentKey.toString());
    AssertTool.assertSingleXPathValueEquals("/contents/relatedcontents/@count", jdomDocResult, "1");
    AssertTool.assertSingleXPathValueEquals(
        "/contents/relatedcontents/content/@key", jdomDocResult, commonChildContentKey.toString());
  }
  @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);
  }
  @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());
  }