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 injectContentIntoContentDao(ContentKey contentKey, String contentName) {
    ContentEntity content = new ContentEntity();
    content.setKey(contentKey);
    content.setName(contentName);

    when(contentDao.findByKey(contentKey)).thenReturn(content);
  }
  @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 doDeleteContent(
      UserEntity importer, ContentKey contentKey, ImportResult importResult) {
    final ContentEntity content = contentDao.findByKey(contentKey);

    if (content == null) {
      // content must have been removed by another process during the import
    } else {
      contentStorer.deleteContent(importer, content);
      importResult.addDeleted(content);
    }
  }
  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 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;
  }
  public void moveContent(MoveContentParams params) {
    validateMoveContentParams(params);

    ContentEntity content = contentDao.findByKey(new ContentKey(params.contentKey));
    if (content == null) {
      throw new IllegalArgumentException("No content for given contentKey: " + params.contentKey);
    }

    CategoryEntity category = categoryDao.findByKey(new CategoryKey(params.categoryKey));
    if (category == null) {
      throw new IllegalArgumentException(
          "No category for given categoryKey: " + params.categoryKey);
    }

    contentService.moveContent(securityService.getImpersonatedPortalUser(), content, category);
  }
  private boolean doImportData(ImportDataEntry importDataEntry, ImportJob importJob) {
    try {
      ContentImporterImpl contentImporter =
          new ContentImporterImpl(importJob, importDataEntry, transliterate);
      contentImporter.setContentStorer(contentStorer);
      contentImporter.setContentDao(contentDao);

      RelatedContentFinder relatedContentFinder =
          new RelatedContentFinder(contentTypeDao, contentIndexService);
      contentImporter.setRelatedContentFinder(relatedContentFinder);

      return contentImporter.importData();
    } finally {
      /* Clear all instances in first level cache since the transaction boundary doesn't (single session) */
      contentDao.getHibernateTemplate().clear();
    }
  }
  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);
    }
  }
  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 void validateUpdateFileContentParams(UpdateFileContentParams params) {
    if (params.contentKey == null) {
      throw new IllegalArgumentException("contentKey must be specified");
    }
    if (params.fileContentData == null) {
      throw new IllegalArgumentException("data must be specified");
    }
    if (params.status == null) {
      throw new IllegalArgumentException("status must be specified");
    }
    if (params.publishFrom != null
        && params.publishTo != null
        && !params.publishTo.after(params.publishFrom)) {
      throw new IllegalArgumentException("publishTo must be after publishFrom");
    }

    ContentEntity content = contentDao.findByKey(new ContentKey(params.contentKey));
    if (content == null) {
      throw new IllegalArgumentException("No content for given contentKey: " + params.contentKey);
    }
  }
  @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());
  }
  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);
    }
  }
  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 ContentTypeEntity resolveContentType(int contentKey) {
   ContentEntity persistedContent = contentDao.findByKey(new ContentKey(contentKey));
   return persistedContent.getCategory().getContentType();
 }
  private String getUpdatedContentXMLWithDao() {

    ContentEntity entity = contentDao.findByKey(updateContentKey);
    return entity.getMainVersion().getContentDataAsXmlString();
  }
  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);
  }
  @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());
  }