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