Class JcmsTestCaseUtil

java.lang.Object
com.jalios.jcms.test.JcmsTestCaseUtil
All Implemented Interfaces:
JcmsConstants, WorkflowConstants, JaliosConstants

public abstract class JcmsTestCaseUtil extends Object implements JcmsConstants, WorkflowConstants
  • Field Details

    • A_VERY_LONG_TEXT

      public static String A_VERY_LONG_TEXT
    • ASYNC_TEST__MAX_WAIT_TIME_BEFORE_FAILURE

      public static long ASYNC_TEST__MAX_WAIT_TIME_BEFORE_FAILURE
    • ASYNC_TEST__ITERATION_WAIT_TIME

      public static long ASYNC_TEST__ITERATION_WAIT_TIME
    • ASYNC_TEST__MAX_ITERATION

      public static long ASYNC_TEST__MAX_ITERATION
    • MEMBER_DEFAULT_PWD_VALUE

      public static final String MEMBER_DEFAULT_PWD_VALUE
      Default Member password clear value.
      Since:
      jcms-10.0.7 JCMS-9172
      See Also:
    • MEMBER_DEFAULT_PWD

      public static final String MEMBER_DEFAULT_PWD
      Convenient one-time crypted password as a constant, since each crypt operation takes some milliseconds.

      Password value (MEMBER_DEFAULT_PWD_VALUE) is crypted by Channel.crypt(String).

      Should be used to enable Member(s) when specific password content is not needed.

       member1.setPassword(JcmsTestCaseUtil.MEMBER_DEFAULT_PWD);
       ...
       memberN.setPassword(JcmsTestCaseUtil.MEMBER_DEFAULT_PWD);
       
      Instead of:
       member1.setPassword(channel.crypt("P@ssw0rd"));
       ...
       memberN.setPassword(channel.crypt("testMyHander.other-P@ssw0rd"));
       
      Since:
      jcms-10.0.7 JCMS-9172
  • Constructor Details

    • JcmsTestCaseUtil

      public JcmsTestCaseUtil()
  • Method Details

    • configureLoggerAppender

      public static void configureLoggerAppender(org.apache.log4j.Logger logger)
    • enableVerboseForbidden

      public static void enableVerboseForbidden()
      Enabled Level Level.ALL on several classes to help diagnose a FORBIDDEN operation (it is probably be logged in trace or debug level).
      Since:
      jcms-10.0.6
    • setLogLevel

      public static void setLogLevel(String packageOrClass, org.apache.log4j.Level level)
    • getMockServletContext

      public static javax.servlet.ServletContext getMockServletContext()
      Convenient Method to return the fake servlet context used for this JCMS test.
      Returns:
      a ServletContext
      See Also:
    • getMockHttpSession

      public static javax.servlet.http.HttpSession getMockHttpSession()
      Convenient Method to return a new instance of a fake http session.
      Returns:
      a HttpSession
      See Also:
      • HttpSession
    • getMockHttpServletRequest

      public static javax.servlet.http.HttpServletRequest getMockHttpServletRequest()
      Convenient Method to return a new instance of a fake http servlet request.
      Returns:
      a HttpServletRequest
      See Also:
    • getMockHttpServletRequest

      public static javax.servlet.http.HttpServletRequest getMockHttpServletRequest(javax.servlet.http.HttpSession session)
      Convenient Method to return a new instance of a fake http servlet request using the specified mock session
      Parameters:
      session - the session
      Returns:
      a HttpServletRequest
      See Also:
    • getMockHttpServletResponse

      public static javax.servlet.http.HttpServletResponse getMockHttpServletResponse()
      Convenient Method to return a new instance of a fake http servlet response.
      Returns:
      a HttpServletResponse
      See Also:
    • getMockHttpServletResponse

      public static javax.servlet.http.HttpServletResponse getMockHttpServletResponse(javax.servlet.http.HttpSession session)
      Convenient Method to return a new instance of a fake http servlet response using the specified mock session
      Parameters:
      session - the session
      Returns:
      a HttpServletResponse
      See Also:
    • getMockJcmsJspContext

      public static JcmsJspContext getMockJcmsJspContext()
      Retrieve a mock explorer JcmsJspContext.
      Returns:
      a new instance of JcmsJspContext
      Since:
      jcms-5.7.3
    • getMockJcmsJspContext

      public static JcmsJspContext getMockJcmsJspContext(javax.servlet.http.HttpServletRequest request)
      Retrieve a mock explorer JcmsJspContext based on the specified request
      Parameters:
      request - the mock request to use, if null a new mock request is created
      Returns:
      a new instance of JcmsJspContext
      Since:
      jcms-5.7.3
    • serialize

      public static File serialize(Object obj) throws Exception
      Serialize the given object into a temp file and return this file.
      Parameters:
      obj - the Object to be serialized
      Returns:
      the file where the object has been serialized.
      Throws:
      Exception - if an error occurs
    • deserialize

      public static Object deserialize(File file) throws Exception
      Deserialize the given file into a new object which is returned.
      Parameters:
      file - the file
      Returns:
      the object
      Throws:
      Exception - if an error occurs
    • beginTransaction

      public static void beginTransaction()
    • commitTransaction

      public static void commitTransaction()
    • excludeDataFromTearDownCheck

      public static void excludeDataFromTearDownCheck(Data... data)
      Exclude the specified data from the check performed on tear down, that ensures no data were created but not deleted, or deleted even though it existed prior test and should have been kept.

      Invoke when your test purposely :

      • created a new data that must persist after your test
      • or deleted a data that existed prior the current test but you did it on purpose
      Warning! : Use wisely as create new data or deleted existing ones may lead to side effect for other tests.
      Parameters:
      data - the Data that will not be verified on tear down
      Since:
      JCMS-11330
    • deleteData

      public static void deleteData(Data... array)
    • deleteData

      public static void deleteData(String... ids)
    • getControllerStatusDebugString

      public static String getControllerStatusDebugString(ControllerStatus actualStatus)
    • deleteOnTearDown

      public static void deleteOnTearDown(Data data)
      Adds given Data in list of Data to be deleted on test's tearDown.
      Parameters:
      data - data to be deleted at the end of a Test
    • deleteOnTearDown

      public static void deleteOnTearDown(String id)
      Adds given Data's id in list of Data to be deleted on test's tearDown.
      Parameters:
      id - a data id which Data is to delete at the end of a Test
      Since:
      jcms-10.0.3
    • deleteOnTearDown

      public static void deleteOnTearDown(Workspace ws, Set<Data> initialDataSet)
      Deletes on tear down the workspace, and all its Datas, but not those contained in optional initialDataSet.
      The initialDataSet should be initialized before the Workspace was created, using for example :
        Set<Data> initialDataSet = channel.getAllDataSet();
       
      Then, the workspace is created, using :
       Workspace workspace = new Workspace();
       ...
       workspace.performCreate(admin);
       
      Then you might want to delete it on tear down, using :
       deleteOnTearDown(workspace, initialDataSet);
       

      Deleted datas will be :

      • all the workspace's publications
      • the following datas that are not in initialDataSet :
        • the workspace's categories, and their CategoryRights
        • the workspace's groups

      Parameters:
      ws - the workspace to delete.
      initialDataSet - a Set of Datas not to delete, since already existing before the start of the test
      Since:
      jcms-7.1.3, jcms-8.0.0
    • getWorkspaceDeleteOnTearDownSet

      public static Set<Data> getWorkspaceDeleteOnTearDownSet(Workspace ws, Set<Data> initialDataSet)
      Returns a collection of Datas (bound to the Workspace) that have been created since the workspace creation.

      Helper method to retrieve datas to delete when the Workspace needs to be deleted.

      Parameters:
      ws - the workspace to retrieve its created Data to delete
      initialDataSet - the collection of existing datas before workspace has been created.
      Returns:
      datas bound to the workspace, and that have been created since the workspace creation.
      Since:
      jcms-9.0.3
    • deleteAll

      public static void deleteAll(Class<? extends DBData> dbDataClazz)
    • deleteAllAlerts

      public static void deleteAllAlerts()
    • deleteAllAlerts

      public static void deleteAllAlerts(Member mbr)
      Delete all alerts for given Member in a dedicated transaction.

      If member is a DBMember, see also deleteAllAlertsTx(String) to pass member identifier instead of DBMember instance.

      Parameters:
      mbr - member to delete all its alerts
    • deleteAllAlertsTx

      public static void deleteAllAlertsTx(String mid)
      Delete all alerts for Member with given id in a dedicated transaction.
      Parameters:
      mid - if of member to delete all its alerts
      Since:
      jcms-10.0.6
    • getResourceFile

      public static File getResourceFile(Class<?> clazz, String name)
      Retrieves a new File instance pointing to the specified resource name. Example :
       File testFile1 = getResourceFile("com/company/jcms/MyFeature_testFile1.txt");
       
      Current implementation is to invoke class loader of current class : return new File(clazzInstance.getClass().getClassLoader().getResource(name).getFile());
      Parameters:
      clazz - the clazz where to find the file
      name - the name of the resource, a '/'-separated path name that identifies the resource. e.g "com/company/jcms/MyFeature_testFile1.txt"
      Returns:
      the file
      Since:
      jcms-10.0.1
    • sleep

      public static void sleep(long millis)
      Parameters:
      millis - the length of time to sleep in milliseconds.
    • waitForAlarm

      public static void waitForAlarm(long time, AlarmManager alarmMgr, boolean reallyWaitFor, String logPrefix)
    • waitForLuceneIndexation

      public static void waitForLuceneIndexation(Publication... pubs)
      Wait for the specified publication(s) to be indexed in all the lucene publication index in its current version as returned by Publication.getVersionString().

      For this method to work properly with DBData, it must be invoked in a different transaction than the transaction in which the create/update operation of the DBData was performed. Indeed indexing is trigger by the PublicationSearchEngineListener during the transaction commit, thus indexing will have been performed only after transaction end.

      If needed, several verification for the maximum duration specified ASYNC_TEST__MAX_WAIT_TIME_BEFORE_FAILURE.

      Parameters:
      pubs - the publications to found in index.
    • waitForLuceneIndexation

      public static void waitForLuceneIndexation(boolean checkFileContentIndexing, Publication... pubs)
    • waitForMemberLuceneIndexation

      public static void waitForMemberLuceneIndexation(String... ids) throws Exception
      Wait for the specified Members(s) to be indexed in the lucene member index in its current mdate as returned by BasicStorable.getMdate().

      For this method to work properly with DBMember, it must be invoked in a different transaction than the transaction in which the create/update operation of the DBMember was performed. Indeed indexing is trigger by the MemberSearchEngineListener during the transaction commit, thus indexing will have been performed only after transaction end.

      If needed, several verification for the maximum duration specified ASYNC_TEST__MAX_WAIT_TIME_BEFORE_FAILURE.

      Parameters:
      ids - the ids of Member to found in index.
      Throws:
      Exception - if index could not be read or member could not be found
    • waitForMemberLuceneIndexation

      public static void waitForMemberLuceneIndexation(Member... mbrs) throws Exception
      Wait for the specified Members(s) to be indexed in the lucene member index in its current mdate as returned by BasicStorable.getMdate().

      For this method to work properly with DBMember, it must be invoked in a different transaction than the transaction in which the create/update operation of the DBMember was performed. Indeed indexing is trigger by the MemberSearchEngineListener during the transaction commit, thus indexing will have been performed only after transaction end.

      If needed, several verification for the maximum duration specified ASYNC_TEST__MAX_WAIT_TIME_BEFORE_FAILURE.

      Parameters:
      mbrs - the Members to found in index.
      Throws:
      Exception - if index could not be read or member could not be found
    • logC3P0Data

      public static void logC3P0Data()
      Retrieve current C3P0 information from JXM and log them.
    • waitForDBTimePrecision

      public static void waitForDBTimePrecision()
      wait 1 ms if the DB support time with ms precision, otherwise 1 s
    • setProperty

      public static void setProperty(String name, String value)
      Parameters:
      name - the property name to set
      value - the property value to set
      Since:
      jcms-8.0.3, jcms-9.0.0
      See Also:
    • setProperties

      public static void setProperties(Map<String,String> map)
      Parameters:
      map - the map of properties to set
      Since:
      jcms-8.0.3, jcms-9.0.0
      See Also:
    • setProperties

      public static void setProperties(JProperties properties)
      Sets given JProperties.

      First call of this method will backup propertys current value, for automatic restore in test tear down.

      Example:

       // How to disabled channel mails
       setProperty("mail.enabled", "false");
       
       // How to update several properties
       JProperties props = new JProperties();
       props.put("my-first-property", "true");
       props.put("my-second-property", "foo");
       setProperties(props);
       
       // How to restore properties (If not done, it will be restored automatically during tearDown())
       // Using a single String
       restoreProperty("mail.enabled"); // Restore one property
       
       //  Using a Collection<String>
       restoreProperties(Util.getArrayList("my-first-property", "my-second-property"); // Restore several properties
       
       // Using a JProperties
       restoreProperties((JProperties) props); // Restore several properties
       

      Complete Test Case:
      If you had to write a unit test which is only relevant when site authentication is required.
      Preparing and restoring the environnement at start and end of each test can be painful.
      To make this initialization easier, you can do:

       PrivateSiteTest extends JcmsTestCase {
         @Override
         protected void setUp() throws Exception {
           super.setUp();
           logger.info("Channel authentication required: " + channel.isAuthenticationRequired()); // Prints "false" by default
           setAuthenticationRequired(true);
         }
         
         public void testPrivateSite() {
           assertTrue("The site must be private to run this test...", channel.isAuthenticationRequired());
           ...
         }
         
         private void setAuthenticationRequired(boolean isPrivateSite) {
           setProperty("channel.is-authentication-required", String.valuedOf(isPrivateSite));
         }
       }
       
      You may also want to restore initial value during the test:
       PrivateSiteTest extends JcmsTestCase {
         ...
         
         public void testPrivateSite() {
           assertTrue("The site must be private to run this test...", channel.isAuthenticationRequired());
           // ... first test with authentication required
           
           restoreAuthenticationRequired();
           assertFalse("The site must be public to run this test...", channel.isAuthenticationRequired());
           // ... second test with initial authentication required
         }
           
         private void restoreAuthenticationRequired() {
           restoreProperty("channel.is-authentication-required");
         }
       }
       
      Implementation details:
      • channel.setProperty is called for each property to set
      • then, properties.firePropertiesChange() is called one time
      • thus, JPropertiesListener will be called.
      Parameters:
      properties - the JProperties to set
      Since:
      jcms-8.0.3, jcms-9.0.0
    • restoreProperty

      public static void restoreProperty(String name)
      Restores given property.
      Parameters:
      name - the name of property to restore
      Since:
      jcms-8.0.3, jcms-9.0.0
      See Also:
    • restoreProperties

      public static void restoreProperties(Collection<String> names)
      Restores given properties represented by their names.
      Parameters:
      names - the names of properties to restore
      Since:
      jcms-8.0.3, jcms-9.0.0
      See Also:
    • restoreProperties

      public static void restoreProperties(JProperties properties)
      Restores given JProperties.
      Parameters:
      properties - the JProperties to restore.
      Since:
      jcms-8.0.3, jcms-9.0.0
    • setIncomingMail

      public static void setIncomingMail(boolean enabled)
      Sets property "mail.incoming.enabled" to enabled.
      Parameters:
      enabled - the value to set.
      Since:
      jcms-8.0.3, jcms-9.0.0
    • restoreIncomingMail

      public static void restoreIncomingMail()
      Restores property "mail.incoming.enabled".
      Since:
      jcms-8.0.3, jcms-9.0.0
    • setAuthenticationRequired

      public static void setAuthenticationRequired(boolean isAuthRequired)
      Sets property "channel.is-authentication-required" to isAuthRequired.
      Parameters:
      isAuthRequired - the value to set.
      Since:
      jcms-8.0.3, jcms-9.0.0
    • restoreAuthenticationRequired

      public static void restoreAuthenticationRequired()
      Restores property "channel.is-authentication-required".
      Since:
      jcms-8.0.3, jcms-9.0.0
    • enableJSync

      public static void enableJSync()
      Enable JSync in Junit prop.

      Sets property "jsync.enabled" to true.

    • disableJSync

      public static void disableJSync()
      Disable JSync in Junit prop.

      Sets property "jsync.enabled" to false.

    • enableLdap

      public static void enableLdap()
      Enable LDAP in Junit prop.

      Sets property "ldap.enabled" to true.

      Since:
      jcms-9.0.3
    • disableLdap

      public static void disableLdap()
      Disable LDAP in Junit prop.

      Sets property "ldap.enabled" to false.

      Since:
      jcms-9.0.3
    • setGuestAccountsEnabled

      public static void setGuestAccountsEnabled(boolean enabled) throws Exception
      Forces Channel.isGuestAccountsEnabled() to return given value.
      Parameters:
      enabled - true to force enabled state, false disabled state
      Throws:
      Exception - ...
      Since:
      jcms-10.0.6
    • restoreGuestAccountsEnabled

      public static void restoreGuestAccountsEnabled() throws Exception
      Throws:
      Exception - ...
      Since:
      jcms-10.0.6
    • createCategory

      public static Category createCategory(String name, Category parent)
    • createWorkspace

      public static void createWorkspace(Workspace workspace)
      Utility method to create the given Workspace by admin Member.

      Manages deleteOnTearDown, and clears the workspace's id if already set.

      Use as follow:

       Workspace ws = new Workspace(otherWs);   // Bootstraps a Workspace based on another WS
       ws.setTitle("my test workspace");        // ws customization
       createWorkspace(ws);                     // handles deleteOnTearDown
       
      Parameters:
      workspace - the workspace to create
      Since:
      jcms-8.0.3, jcms-9.0.0
    • createWorkspace

      public static void createWorkspace(Workspace workspace, Member author)
      Utility method to create the given Workspace by admin Member.

      Manages deleteOnTearDown, and clears the workspace's id if already set.

      Use as follow:

       Workspace ws = new Workspace(otherWs);   // Bootstraps a Workspace based on another WS
       ws.setTitle("my test workspace");        // ws customization
       createWorkspace(ws, author);             // handles deleteOnTearDown
       
      Utility method to create the given Workspace.

      Manages deleteOnTearDown.

      Parameters:
      workspace - the workspace to create
      author - the create operation author
      Since:
      jcms-8.0.3, jcms-9.0.0
    • createACLGroup

      public static Group createACLGroup(String resource)
    • createGroupTx

      public static Group createGroupTx(String name)
      Creates a new group inside a new transaction that is commited at the end of process.
      Parameters:
      name - the name of the group to create
      Returns:
      the created group
      Since:
      jcms-10.0.6
    • createGroupTx

      public static Group createGroupTx(String name, Collection<Group> parentGroups)
      Creates a new group inside a new transaction that is commited at the end of process.
      Parameters:
      name - the name of the group to create
      parentGroups - option parentSet to set on the group
      Returns:
      the created group
      Since:
      jcms-10.0.6
    • addParentGroupTx

      public static void addParentGroupTx(Group group, Group parentGroup)
      Add given parent Group on given Group.
      Parameters:
      group - group be added parentGroup as parent, cannot be null
      parentGroup - parent group to add, cannot be null
      Since:
      jcms-10.0.6
    • createMember

      public static Member createMember(String name)
    • createMemberTx

      public static String createMemberTx(String name)
      Creates a JStore member in a dedicated transaction.

      Example of use:

       // Create members in transaction, keep ids reference
       String mbrId = JcmsTestCaseUtil.createMemberTx("JStore member");
       String dbMbrId = JcmsTestCaseUtil.createDBMemberTx("DB member");
       
       // Common test for both JStore and DBMember
       for (String mid : Util.getArrayList(mbrId, dbMbrId)) {
         beginTransaction();
         {
           // Test stuff
           assertNotNull(channel.getMember(mid));
         }
         commitTransaction();
       }
       
      Parameters:
      name - name to set
      Returns:
      member id
      Since:
      jcms-10.0.6
    • createMember

      public static Member createMember(String name, boolean deleteOnTearDown)
    • createMember

      public static Member createMember(String name, Group... groups)
    • createMember

      public static Member createMember(String name, boolean deleteOnTearDown, Group... groups)
    • createDBMember

      public static DBMember createDBMember(String name)
    • createDBMemberTx

      public static String createDBMemberTx(String name)
      Creates a DB member in a dedicated transaction.

      Example of use: see createMemberTx(String)

      Parameters:
      name - name to set
      Returns:
      member id
      Since:
      jcms-10.0.6
    • createDBMemberTx

      public static String createDBMemberTx(String name, Group... groups)
      Creates a DB member in a dedicated transaction.

      Example of use: see createMemberTx(String)

      Parameters:
      name - name to set
      groups - groups to add member in
      Returns:
      member id
      Since:
      jcms-10.0.6
    • createDBMember

      public static DBMember createDBMember(String name, boolean deleteOnTearDown)
    • createDBMember

      public static DBMember createDBMember(String name, Group... groups)
    • createDBMember

      public static DBMember createDBMember(String name, boolean deleteOnTearDown, Group... groups)
    • copyPhotoAndSetMemberPhoto

      public static void copyPhotoAndSetMemberPhoto(Member member, File origPhotoFile)
      Copies unittest mock photo file to a new tempFile.

      Move copy in JCMS webapp (to work with use of getRelativePath(file))

      Update member with this photo file in webapp.

      Parameters:
      member - the member to set a photo
      origPhotoFile - the unittest photo ressource to be copied
      Since:
      jcms-10.0.8 JCMS-10422
    • createFile

      public static String createFile(String filename)
    • createFile

      public static void createFile(File file, String content) throws Exception
      Throws:
      Exception
    • waitForFileAvailability

      public static void waitForFileAvailability(File file) throws Exception
      Throws:
      Exception
    • getFileDocument

      public static FileDocument getFileDocument(Member writer, Workspace ws, String title, String filename)
    • createFileDocument

      public static FileDocument createFileDocument(Member writer, Workspace ws, String title, String filename)
    • getDBFileDocument

      public static DBFileDocument getDBFileDocument(Member writer, Workspace ws, String title, String filename)
    • createDBFileDocument

      public static DBFileDocument createDBFileDocument(Member writer, Workspace ws, String title, String filename)
    • createMedia

      public static generated.Media createMedia(Member writer, Workspace ws, String title, String filename)
    • getMedia

      public static generated.Media getMedia(Member writer, Workspace ws, String title, String filename)
    • getArticle

      public static generated.Article getArticle(Member writer, Workspace ws)
    • createArticle

      public static generated.Article createArticle(Member writer, Workspace ws, boolean deleteOnTearDown)
    • getSmallNews

      protected static generated.SmallNews getSmallNews(Member writer, Workspace ws, boolean insertDateInContent)
    • createSmallNews

      public static generated.SmallNews createSmallNews(Member writer, Workspace ws, boolean deleteOnTearDown)
    • getShortcut

      public static AbstractShortcut getShortcut(String link, Member writer, Workspace ws)
    • getShortcut

      public static AbstractShortcut getShortcut(Publication pub, Member writer, Workspace ws)
    • getShortcut

      public static AbstractShortcut getShortcut(Member writer, Workspace ws)
      Returns:
      a Shortcut with no pub nor link set.
    • createShortcut

      public static AbstractShortcut createShortcut(Publication pub, Member writer, Workspace ws, boolean deleteOnTearDown)
    • createShortcut

      public static AbstractShortcut createShortcut(String link, Member writer, Workspace ws, boolean deleteOnTearDown)
    • getPortletQueryForeach

      public static generated.PortletQueryForeach getPortletQueryForeach(Member writer, Workspace ws)
      Get a new, not created yet, pub instance.
      Parameters:
      writer - publication author
      ws - workpsace
      Returns:
      a PortletQueryForeach with title only.
      Since:
      jcms-10.0.8 / JCMS-10823
    • createPortletQueryForeach

      public static generated.PortletQueryForeach createPortletQueryForeach(Member writer, Workspace ws, boolean deleteOnTearDown)
      Creates a new pub instance.
      Parameters:
      writer - publication author
      ws - workpsace
      deleteOnTearDown - true for auto delete
      Returns:
      a PortletQueryForeach with title only.
      Since:
      jcms-10.0.8 / JCMS-10823
    • addReadRights

      public static Set<Member> addReadRights(Publication pub, Member... members)
      Convenient method to add read right Members on given publication.

      Can be used as follow:

       Set<Member> initialAuthMemberSet = addReadRights(pub, member1, member2); 
       // custom processing here
       // [...]
       // Restore
       restoreReadRightsMembers(pub, initialAuthMemberSet);
       
      Parameters:
      pub - the pub to add a read right on given Members
      members - the member(s) to add in pub's authorizedMemberSet
      Returns:
      the initial authorizedMemberSet for restore purpose
    • addReadRights

      public static Set<Group> addReadRights(Publication pub, Group... groups)
      Convenient method to add read right Groups on given publication.

      Can be used as follow:

       Set<Group> initialAuthGroupSet = addReadRights(pub, group1, group2); 
       // custom processing here
       // [...]
       // Restore
       restoreReadRightsGroups(pub, initialAuthGroupSet);
       
      Parameters:
      pub - the pub to add a read right on given Groups
      groups - the group(s) to add in pub's authorizedGroupSet
      Returns:
      the initial authorizedGroupSet for restore purpose
    • restoreReadRightsMembers

      public static void restoreReadRightsMembers(Publication pub, Collection<Member> initialAuthorizedMembers)
      Parameters:
      pub - the pub to restore its initial authorizedMemberSet
      initialAuthorizedMembers - initial authorized members to restore (typically returned by addReadRights(Publication, Member...))
    • restoreReadRightsGroups

      public static void restoreReadRightsGroups(Publication pub, Collection<Group> initialAuthorizedGroups)
      Parameters:
      pub - the pub to restore its initial authorizedGrouSet
      initialAuthorizedGroups - initial authorized groups to restore (typically returned by addReadRights(Publication, Group...))
    • updatePstatusTransaction

      public static void updatePstatusTransaction(String pubId, Member opAuthor, int newPstatus)
      Checks and performs update the publication (makes an update instance) with given pstatus.

      If pstatus is WorkflowConstants.PUBLISHED_PSTATUS, and publication's pdate is null, sets a new pdate.

      Opens and closes a new transaction.

      Parameters:
      pubId - the id of publication to udpate its pstatus
      opAuthor - the author of operation
      newPstatus - the new pstatus to set
      Since:
      jcms-10.0.1
      See Also:
    • publishPublicationTransaction

      public static void publishPublicationTransaction(String pubId, Member opAuthor)
      Parameters:
      pubId - the id of publication to udpate its pstatus
      opAuthor - the author of operation
      Since:
      jcms-10.0.1
      See Also:
    • updateTitleTransaction

      public static void updateTitleTransaction(String pubId, Member opAuthor, String newTitle)
      Checks and performs update the publication (makes an update instance) with given title.

      Use it as follow:

         final String pubId;
         beginTransaction();
         {
           pubId = createMedia().getId();
         }
         commitTransaction();
         JcmsTestCaseUtil.updateTitleTransaction(pubId, admin, "My FOO media");
       
      Parameters:
      pubId - the id of publication to udpate its pstatus
      opAuthor - the author of operation
      newTitle - the new title to set
      Since:
      jcms-10.0.6
    • ignoreUnstableTest

      public static boolean ignoreUnstableTest()
    • updateGroupVisibilityTx

      public static void updateGroupVisibilityTx(String grpId, int visibility)
      Parameters:
      grpId - group to set new visibility
      visibility - the new visibility to set
      Since:
      jcms-10.0.8 / JCMS-10641
    • updateWorkspaceTypeWorkflow

      public static void updateWorkspaceTypeWorkflow(Workspace ws, Class<? extends Data> typeClass, Object workflowToUse)

      An utility method to update the given Workspace, with the chosen Workflow associated to the given Type.

      Note: It is better to make a backup of the Type Workflow in order to restore at the end of the test:

       Object wfBackup = myWs.getTypeMap().get(MyType.class);
       JcmsTestCaseUtil.updateWorkspaceTypeWorkflow(myWs, MyType.class, "");
       // ... (processing)
       JcmsTestCaseUtil.updateWorkspaceTypeWorkflow(myWs, MyType.class, wfBackup);
       
      Parameters:
      ws - the workspace
      typeClass - the class
      workflowToUse - the workflow Id. Use an empty string if it is just to activate the type.
    • updateWorkspaceTypeWorkflow

      public static void updateWorkspaceTypeWorkflow(Workspace ws, HashMap<Class<?>,Object> subTypeMap)

      An utility method to update the given Workspace typeMap.

      Note: It is better to make a backup of the Type Workflow in order to restore at the end of the test:

       Object wfBackup = myWs.getTypeMap().get(MyType.class);
       JcmsTestCaseUtil.updateWorkspaceTypeWorkflow(myWs, MyType.class, "");
       // ... (processing)
       JcmsTestCaseUtil.updateWorkspaceTypeWorkflow(myWs, MyType.class, wfBackup);
       
      Update given workspace's typeMap with given subset typeMap.
      Parameters:
      ws - the workspace to apply changes
      subTypeMap - the typeMap subset to change
    • voteForPubTransaction

      public static String voteForPubTransaction(String pubId, String voterId)
      Adds a 1 point vote on given pub by given member.

      May return null if no pub or no member.

      Opens and closes a new transaction.

      Parameters:
      pubId - the publication to vote for
      voterId - the member performing the vote
      Returns:
      the created vote identifier if any
      Since:
      jcms-10.0.1
    • dataToDebugString

      public static String dataToDebugString(Data data)
      Produces a String representation of given Data for debug, log purpose.

      See JcmsUtil.dataToString(Data)

      Parameters:
      data - the data to get the debug string.
      Returns:
      the debugging String of the data.
      Since:
      jcms-7.1.3, jcms-8.0.0
      See Also:
    • toReflectString

      public static String toReflectString(Object o)
      Parameters:
      o - object to render as reflection String
      Returns:
      toString multiline representation of object using ReflectionToStringBuilder.
      Since:
      jcms-10.0.8
    • datasToString

      public static String datasToString(List<Data> datas)
      Use as follow:
      JcmsTestCaseUtil.datasToString(Util.getArrayList(recommendation, null, member, article))

      Produces output like:

      [
         #1: [Recommendation] [class: com.jalios.jcms.recommendation.Recommendation] [id: 1_Recommendation] [author: Admin] (1_Recommendation),
         #2: null,
         #3: [Member] Alice (c_1234)
         #4: [Article] My article (c_1333)
      ]
      
      Parameters:
      datas - collection of data to debug
      Returns:
      a multiline String representation of a List of Data, with new line and comma separator, with indices and mapped with JcmsUtil.dataToString(Data)
      Since:
      jcms-10.0.8 / JCMS-10771
    • setupRootLogger

      public static org.apache.log4j.Logger setupRootLogger()
      Configures the root logger (adds a console appender, see BasicConfigurator.configure()) if it has no appender defined yet (see Util.hasAppenderDefined(Logger)).
      Returns:
      the root logger (see Logger.getRootLogger()
      Since:
      jcms-10.0.2
    • setupRootLogger

      public static org.apache.log4j.Logger setupRootLogger(org.apache.log4j.Level level)
      First, setups root logger. (See setupRootLogger()).

      Then, sets given level if any.

      Parameters:
      level - new level to set
      Returns:
      the root logger (see Logger.getRootLogger()
      Since:
      jcms-10.0.2
      See Also:
    • restoreRootLogger

      public static void restoreRootLogger(org.apache.log4j.Logger rootLogger, org.apache.log4j.Level level)
      Restores given level (backup before modification) on logger if both not null.
      Parameters:
      rootLogger - the root logger to restore with given level
      level - the level to restore
      Since:
      jcms-10.0.2
    • updateMemberEmailTransaction

      public static void updateMemberEmailTransaction(String mid, String authorMid, String emailAddress)
      Checks and performs update given Member with given email address.

      Opens and closes a new transaction.

      Parameters:
      mid - the id of Member to be updated
      authorMid - the id of author of operation
      emailAddress - the new email to set
      Since:
      jcms-10.0.3
    • updateToLDAP_accountTx

      public static void updateToLDAP_accountTx(String mid, String opAuthorId)
      Performs member update as LDAP account by setting him a lastLdapSynchro.
      Parameters:
      mid - id of member to update
      opAuthorId - id of opAuthor
      Since:
      jcms-10.0.8 / JCMS-10223
    • disableMemberTx

      public static void disableMemberTx(String mid)
      Performs member disable update in a dedicated transaction using default admin as opAuthor.
      Parameters:
      mid - id of member to disable
      Since:
      jcms-10.0.8 / JCMS-9978
    • disableMemberTx

      public static void disableMemberTx(String mid, String opAuthorId)
      Performs member disable update in a dedicated transaction.
      Parameters:
      mid - id of member to disable
      opAuthorId - id of opAuthor
      Since:
      jcms-10.0.8 / JCMS-9978
    • enableMemberTx

      public static void enableMemberTx(String mid)
      Sets a new password on member to enable it.
      Parameters:
      mid - id of member to enable
      Since:
      jcms-10.0.8 / JCMS-9978
    • enableMemberTx

      public static void enableMemberTx(String mid, String opAuthorId)
      Sets a new password on member to enable it.
      Parameters:
      mid - id of member to enable
      opAuthorId - id of opAuthor
      Since:
      jcms-10.0.8 / JCMS-9978
    • updateToAccountTx

      public static void updateToAccountTx(String mid)
      Performs update of member usage to Account in a dedicated transaction using default admin as opAuthor.
      Parameters:
      mid - id of member to convert to a Contact
      Since:
      jcms-10.0.8 / JCMS-9978
    • updateToAccountTx

      public static void updateToAccountTx(String mid, String opAuthorId)
      Performs update of member usage to Account in a dedicated transaction.
      Parameters:
      mid - id of member to convert to a Contact
      opAuthorId - id of opAuthor
      Since:
      jcms-10.0.8 / JCMS-9978
    • updateToContactTx

      public static void updateToContactTx(String mid)
      Performs update of member usage to Contact in a dedicated transaction using default admin as opAuthor.
      Parameters:
      mid - id of member to convert to a Contact
      Since:
      jcms-10.0.8 / JCMS-9978
    • updateToContactTx

      public static void updateToContactTx(String mid, String opAuthorId)
      Performs update of member usage to Contact in a dedicated transaction.
      Parameters:
      mid - id of member to convert to a Contact
      opAuthorId - id of opAuthor
      Since:
      jcms-10.0.8 / JCMS-9978
    • addMemberInGroupTx

      public static void addMemberInGroupTx(Group group, String memberId)
      Checks and performs update given Member by adding him in given Group.

      Opens and closes a new transaction.

      opAuthor will be default admin.

      Parameters:
      group - the Group to add the member in
      memberId - the id of Member to update
      Since:
      jcms-10.0.6
    • removeMemberFromGroupTx

      public static void removeMemberFromGroupTx(Group group, String memberId)
      Checks and performs update given Member by removing hime from given Group.

      Opens and closes a new transaction.

      opAuthor will be default admin.

      Parameters:
      group - the Group to remove the member from
      memberId - the id of Member to update
      Since:
      jcms-10.0.6
    • updateMemberDeclaredManagerTx

      public static void updateMemberDeclaredManagerTx(String mid, String declaredManagerId)
      Checks and performs update given Member with given declared manager.

      Opens and closes a new transaction.

      opAuthor will be default admin.

      Parameters:
      mid - the id of Member to be updated
      declaredManagerId - the id of Member to set as declaredManager
      Since:
      jcms-10.0.8
    • updateMemberAssistantTx

      public static void updateMemberAssistantTx(String memberId, String assistantId)
      Checks and performs update given Member with given assistant.

      Opens and closes a new transaction.

      opAuthor will be default admin.

      Parameters:
      memberId - the Member to be updated
      assistantId - the id of Member to set as assistant
      Since:
      jcms-10.0.8
    • checkAndCreate

      public static <T extends Data> String checkAndCreate(T data, Consumer<T> beforePerformConsumer)
      Delegates to checkAndCreate(Data, Consumer, Member) with data's author as create opAuthor.

      Should be inside a transaction.

      Type Parameters:
      T - type of data to create
      Parameters:
      data - the data instance to create
      beforePerformConsumer - the consumer to be called before creation.
      Returns:
      the created's data identifier
      Since:
      jcms-10.0.6
      See Also:
    • checkAndCreate

      public static <T extends Data> String checkAndCreate(T data, Consumer<T> beforePerformConsumer, Member opAuthor)
      Checks and creates the given data instance.

      Allows to modify the data before it gets created.

      Calls the consumer on data before checkAndPerformCreate is called.

      Should be inside a transaction. You can use it as follow:

      • Define a consumer that will be called before data creation, which allows to update fields that are not available in the getDataInstance method.
      • Instanciate a Data using a method that does not allow to set all data's fields
       beginTransaction();
       {
         // Here we will override data's title
         Consumer<TestType> beforePerformConsumer = new Consumer<TestType>() {
           @Override
           public void accept(TestType pub) {
             pub.setTitle("My custom title");
           }
         };
         // Here we instanciate a TestType for which we cannot define a custom title.
         pubId = JcmsTestCaseUtil.checkAndCreate(getTestType(author, srcWorkspace), beforePerformConsumer, admin);
       }
       commitTransaction();
       
      Or shorter:
       beginTransaction();
       {
        // Here we pass an inline consumer:
        JcmsTestCaseUtil.checkAndCreate(getTestType(author, srcWorkspace), pub -> pub.setTitle("My custom title"), admin);
       }
       commitTransaction();
       
      Type Parameters:
      T - type of data to create
      Parameters:
      data - the data instance to create
      beforePerformConsumer - the consumer to be called before creation.
      opAuthor - the member to use for opCreate
      Returns:
      the created's data identifier
      Since:
      jcms-10.0.6
    • checkAndUpdate

      public static <T extends Data> void checkAndUpdate(T data)
      Checks and performs update of given data update instance.

      Delegates to checkAndUpdate(Data, Consumer).

      Type Parameters:
      T - type of data to work with
      Parameters:
      data - the data instance to update
      Since:
      jcms-10.0.6
      See Also:
    • checkAndUpdate

      public static <T extends Data> void checkAndUpdate(T data, Consumer<T> beforePerformConsumer)
      Delegates to checkAndUpdate(Data, Consumer, Member) with data's author as update opAuthor, or default admin as update opAuthor if data author is null.
      Type Parameters:
      T - type of data to work with
      Parameters:
      data - the data instance to update
      beforePerformConsumer - the optional consumer to be called before update.
      Since:
      jcms-10.0.6
      See Also:
    • checkAndUpdate

      public static <T extends Data> void checkAndUpdate(T data, Consumer<T> beforePerformConsumer, Member opAuthor)
      Checks and updates the given data instance.

      Allows to modify the data before it gets updated.

      Calls the consumer on data before checkAndPerformUpdate is called.

      The consumer will receive the "updated instance" to work on.

      Should be inside a transaction. You can use it as follow:

      • Define a consumer that will work on data's updated instance before it opUpdate is called.
      • Pass an existing data instance (the original instance, not an update instance) to modify before update.
       Member member = createMbr("Foo", defaultGroup);
       beginTransaction();
       {
         // Here we will override member's email
         Consumer<Member> beforePerformConsumer = new Consumer<Member>() {
           @Override
           public void accept(Member member) {
             member.setEmail("foo@bar.baz");
           }
         };
         // Here we pass an existing Data to modifiy before opUpdate is called
         JcmsTestCaseUtil.checkAndUpdate(member, beforePerformConsumer, admin);
       }
       commitTransaction();
       
      Or shorter:
       Member member = createMbr("Foo", defaultGroup);
       beginTransaction();
       {
         // Here we pass an inline consumer:
         JcmsTestCaseUtil.checkAndUpdate(member, updated -> ((Member) updated).setEmail("foo@bar.baz"), admin);
       }
       commitTransaction();
       
      This is equivalent to:
       Member member = createMbr("Foo", defaultGroup);
       beginTransaction();
       {
         Member udpate = (Member) data.getUpdateInstance();
         udpate.setEmail("foo@bar.baz");
         assertStatusOK(update.checkAndPerformUpdate(admin));
       }
       commitTransaction();
       
      Type Parameters:
      T - type of data to work with
      Parameters:
      data - the data instance to update
      beforePerformConsumer - the optional consumer to be called before update.
      opAuthor - the member to use for opUpdate
      Since:
      jcms-10.0.6
    • checkAndUpdateTx

      public static <T extends Data> void checkAndUpdateTx(String dataId, Consumer<T> beforePerformConsumer)
      One-line update statement within a dedicated transaction.
       JcmsTestCaseUtil.checkAndUpdateTx(mid, updated -> ((Member) updated).setUsage(Member.USAGE_CONTACT));
       JcmsTestCaseUtil.checkAndUpdateTx(pub.getId(), updated -> ((Article) updated).setPicture(doc.getFilename()));
       
      Type Parameters:
      T - type of data to work with
      Parameters:
      dataId - the ID of data instance to update
      beforePerformConsumer - the optional consumer to be called before update.
      See Also:
    • checkAndUpdateTx

      public static <T extends Data> void checkAndUpdateTx(String dataId, Consumer<T> beforePerformConsumer, String opAuthorId)
      One-line update statement within a dedicated transaction.
       JcmsTestCaseUtil.checkAndUpdateTx(mid, updated -> ((Member) updated).setUsage(Member.USAGE_CONTACT), admin.getId());
       JcmsTestCaseUtil.checkAndUpdateTx(pub.getId(), updated -> ((Article) updated).setPicture(doc.getFilename()), admin.getId());
       
      Type Parameters:
      T - type of data to work with
      Parameters:
      dataId - the ID of data instance to update
      beforePerformConsumer - the optional consumer to be called before update.
      opAuthorId - the ID of member to use for opUpdate
      See Also:
    • checkAndDelete

      public static void checkAndDelete(Data data, Member opAuthor)
    • checkAndDeleteTx

      public static void checkAndDeleteTx(String dataId)
    • checkAndDeleteTx

      public static void checkAndDeleteTx(String dataId, String opAuthorId)
    • asSet

      public static <T> HashSet<T> asSet(T... array)
      Convenient shorthand for Util.getHashSet(Object...).

      Never returns null.

      Type Parameters:
      T - type of element
      Parameters:
      array - elements to return in a new Set
      Returns:
      a set with given elements
      Since:
      jcms-10.0.6
    • setupOrganizationRootGroupTx

      public static String setupOrganizationRootGroupTx()
      Creates a group and sets it as organization root group in properties.
      Returns:
      id of created group
      Since:
      jcms-10.0.8 JCMS-10641
      See Also:
    • createOrganizationGroupTx

      public static String createOrganizationGroupTx(String name)
      Creates a group, direct child of organization root group.
      Parameters:
      name - name of new group
      Returns:
      id of created group
      Since:
      jcms-10.0.8 JCMS-10641
      See Also:
    • assertSameData

      public static void assertSameData(Data expectedData, Data actualData)
      Assert 2 datas are the same.
      Since:
      jcms-10.0.6
      See Also:
    • assertSameData

      public static void assertSameData(String message, Data expectedData, Data actualData)
      Assert 2 datas are the same.
      Since:
      jcms-10.0.6
      See Also:
    • assertNotSameData

      public static void assertNotSameData(Data expectedData, Data actualData)
      Assert 2 datas are not the same.
      Since:
      jcms-10.0.6
      See Also:
    • assertNotSameData

      public static void assertNotSameData(String message, Data expectedData, Data actualData)
      Assert 2 datas are not the same.
      Since:
      jcms-10.0.6
      See Also:
    • assertSameData

      public static void assertSameData(String message, boolean expectedSameData, Data expectedData, Data actualData)
      Assert 2 datas are or are not the same.

      Gives more details about expected and actual datas, than a simple assertEquals.

      Parameters:
      message - optional contextual message
      expectedSameData - if true, both data must be the same
      expectedData - the expected data
      actualData - the actual data
      Since:
      jcms-10.0.6