Package biz.artemis.confluence.xmlrpcwrapper.test

Source Code of biz.artemis.confluence.xmlrpcwrapper.test.RemoteWikiBrokerTest

package biz.artemis.confluence.xmlrpcwrapper.test;
/**
* Testing operations provided by the RemoteWikiBroker. Eventually
* this test class should verify that all the communications to
* and from Confluence are being properly handled. This will be
* an important class to run against new versions of Confluence
* as certain parts of their APIs do change.
*
*      * The setup method is currently hard coded to assume you're running
* these tests with:
* - a local instance of Confluence
* - running on port 1990
* - which has a test space called 'test'
* - with a user named 'test'
* - with the user password being 'test'
* - the user 'test' must have write access to the space 'test'
* - and an email address of 'test@test.com'
*/

import biz.artemis.confluence.xmlrpcwrapper.*;
import biz.artemis.confluence.xmlrpcwrapper.SpaceForXmlRpc.SpaceType;
import junit.framework.TestCase;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.xmlrpc.XmlRpcClient;
import org.apache.xmlrpc.XmlRpcException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RemoteWikiBrokerTest extends TestCase {
  private static final String TEST_SPACE_BAD = "test.space.bad";
  private static final String GROUP = "newgroup";
  private static final String TEST_NOPERMS_PASS = "test.noperms.pass";
  private static final String TEST_NOPERMS_LOGIN = "test.noperms.login";
  private static final String TEST_PERMS_PASS = "test.perms.pass";
  private static final String TEST_PERMS_LOGIN = "test.perms.login";
  private static final String TEST_URL = "test.url";
  private static final String TEST_SPACE = "test.space.key";
  private static final String TEST_USER_LOGIN = "test.user.login";
  private static final String TEST_PASS = "test.user.pass";
  private static final String TEST_USERADM_LOGIN = "test.useradmin.login";
  private static final String TEST_USERADM_PASS = "test.useradmin.pass";
  private static final String TEST_EMAIL = "test.user.email";
  private static final String URL_DEFAULT = "localhost:1990";
  RemoteWikiBroker remoteWikiBroker;
    ConfluenceServerSettings confSettings = null;
    Logger log = Logger.getLogger("RemoteWikiBrokerTest");
  private Properties props;

    /**
     * The setup method is currently hard coded to assume you're running
     * these tests with:
     * - a local instance of Confluence
     * - running on port 8080
     * - which has a test space called 'test'
     * - with a user named 'test'
     * - with the user password being 'test'
     *
     * @throws Exception
     */
    protected void setUp() throws Exception {
      PropertyConfigurator.configure("log4j.properties");
        super.setUp();
        confSettings = new ConfluenceServerSettings();
        props = new Properties();
    try {
            props.load(new FileInputStream("test.properties"));
        } catch (IOException e) {
          e.printStackTrace();
          fail();
        }
        confSettings.login = props.getProperty(TEST_USER_LOGIN);
        confSettings.password = props.getProperty(TEST_PASS);
        confSettings.spaceKey = props.getProperty(TEST_SPACE);
        confSettings.url = props.getProperty(TEST_URL);
    }

    /**
     * Test the ability to first add a new page and then update
     * that page.
     *
     * @throws Exception
     * @todo - currently verification of a successfull test here
     * involves looking at the wiki, this should be more automated
     * thought that will probably always be needed unless we implement some
     * kind of screen scraping or trust the XMLRPC API enough to
     * do its own verification
     */
    public void testAddThenUpdatePage() throws Exception {
        RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
        String uniqueId = getUniqueString();
        String title = "testing-update-" + uniqueId;

        //explicitly check that page does not exist - XXX not sure we're testing this right in conf4
        XmlRpcClient client = new XmlRpcClient("http://" + confSettings.url + "/rpc/xmlrpc");
        Vector paramsVector = new Vector();
        String loginToken = rwb.getLoginToken(confSettings);
        paramsVector.add(loginToken);
        paramsVector.add(confSettings.spaceKey);
        paramsVector.add(title);
        Hashtable retpage = null;
        try  {
          retpage = (Hashtable) client.execute("confluence1.getPage", paramsVector);
          fail();
        } catch (XmlRpcException e) {}
       
        //create page first time
        PageForXmlRpc page = new PageForXmlRpc();
    page.setTitle(title);
        String content1 = "this is some content " + uniqueId;
    page.setContent(content1);
        rwb.storeNewOrUpdatePage(confSettings, confSettings.spaceKey, page);
       
        try  {
          retpage = (Hashtable) client.execute("confluence1.getPage", paramsVector);
          assertNotNull(retpage);
          assertEquals(title, (String) retpage.get("title"));
          assertEquals(content1, (String) retpage.get("content")); //not allowed as of Conf 4
        } catch (XmlRpcException e) {
          try {
            retpage = (Hashtable) client.execute("confluence1.getPageSummary", paramsVector);
            assertNotNull(retpage);
            assertEquals(title, (String) retpage.get("title"));
            //assertEquals(content1, (String) retpage.get("content")); //not allowed as of Conf 4
          } catch (XmlRpcException e1) {
            fail();
          }
        }
       
        //update page
        page = new PageForXmlRpc();
        page.setTitle(title);
        String content2 = "this is some UPDATED content " + uniqueId;
    page.setContent(content2);
        rwb.storeNewOrUpdatePage(confSettings, confSettings.spaceKey, page);
       
        try  {
          retpage = (Hashtable) client.execute("confluence1.getPage", paramsVector);
          assertNotNull(retpage);
          assertEquals(title, (String) retpage.get("title"));
          assertEquals(content2, (String) retpage.get("content"));
        } catch (XmlRpcException e) {
          try { //XXX not sure how to test this in conf4
            retpage = (Hashtable) client.execute("confluence1.getPageSummary", paramsVector);
            assertNotNull(retpage);
            assertEquals(title, (String) retpage.get("title"));
            //assertEquals(content1, (String) retpage.get("content")); //not allowed as of Conf 4
          } catch (XmlRpcException e1) {
            fail();
          }
        }
    }

    /**
     * This test adds a page and then uploads an attachment to that page.
     * <p/>
     * Verify working: Go to Confluence and check that the new page was added
     * successfully, also verify that the attachment was added and it
     * contains the image file in the devel/sampleData dir.
     *
     * @throws Exception
     */
    public void testAddPageThenAddAttachment() throws Exception {
        RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
        PageForXmlRpc page = new PageForXmlRpc();
        String uniqueId = getUniqueString();
        page.setTitle("testing-attachment-" + uniqueId);
        page.setContent("this is some content " + uniqueId);
        page = rwb.storeNewOrUpdatePage(confSettings, props.getProperty(TEST_SPACE), page);

        // add attachment to page
        // add an attachment
        AttachmentForXmlRpc attachment = new AttachmentForXmlRpc();
        String filename = "cow.jpg";
    attachment.setFileName(filename);
        attachment.setContentType("jpg");
        attachment.setComment("RemoteWikiBrokerTest");
        String path = System.getProperty("user.dir") + File.separator +
                "sampleData" + File.separator + filename;
        assertTrue(new File(path).exists());
    attachment.setFileLocation(path);
        attachment = rwb.storeAttachment(confSettings, page.getId(), attachment);
       
        List<AttachmentForXmlRpc> attachments = rwb.getAttachments(confSettings, page.getId());
        assertNotNull(attachments);
        assertEquals(1, attachments.size());
        assertEquals(filename, attachments.get(0).getFileName());
    }
   
    /**
     * This test adds a page and then uploads an attachment to that page using the webdav methods.
     * <p/>
     * Verify working: Go to Confluence and check that the new page was added
     * successfully, also verify that the attachment was added and it
     * contains the image file in the devel/sampleData dir.
     *
     * @throws Exception
     */
    public void testAddAttachmentsWithWebdavMethods() throws Exception {
        RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
        PageForXmlRpc page = new PageForXmlRpc();
        String uniqueId = getUniqueString();
        page.setTitle("testing-attachment-" + uniqueId);
        page.setContent("this is some content " + uniqueId);
        String spacekey = props.getProperty(TEST_SPACE);
    page = rwb.storeNewOrUpdatePage(confSettings, spacekey, page);

        // add attachment to page
        // add an attachment
        AttachmentForXmlRpc attachment = new AttachmentForXmlRpc();
        String filename = "cow.jpg";
    attachment.setFileName(filename);
        attachment.setContentType("jpg");
        attachment.setComment("RemoteWikiBrokerTest");
        String path = System.getProperty("user.dir") + File.separator +
                "sampleData" + File.separator + filename;
        assertTrue(new File(path).exists());
    attachment.setFileLocation(path);
   
   
    Map pagesByIdMap = rwb.getAllServerPagesMapById(confSettings, spacekey);
    String webdavPath = rwb.getWebDAVPagePath(confSettings.url, spacekey, page.getId(), pagesByIdMap, rwb.WEBDAV_PATH_LATER);
    rwb.sendFileViaWebDAV(path, webdavPath, confSettings.login, confSettings.password);
       
        List<AttachmentForXmlRpc> attachments = rwb.getAttachments(confSettings, page.getId());
        assertNotNull(attachments);
        assertEquals(1, attachments.size());
        assertEquals(filename, attachments.get(0).getFileName());
    }
   
    public void testAddAttachmentsWithWebdavMethods_NeedsURLEncoding() throws Exception {
        RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
        PageForXmlRpc page = new PageForXmlRpc();
        String uniqueId = getUniqueString();
        page.setTitle("testing-encoding?" + uniqueId);
        page.setContent("this is some content " + uniqueId);
        String spacekey = props.getProperty(TEST_SPACE);
    page = rwb.storeNewOrUpdatePage(confSettings, spacekey, page);

        // add attachment to page
        // add an attachment
        AttachmentForXmlRpc attachment = new AttachmentForXmlRpc();
        String filename = "cow.jpg";
    attachment.setFileName(filename);
        attachment.setContentType("jpg");
        attachment.setComment("RemoteWikiBrokerTest");
        String path = System.getProperty("user.dir") + File.separator +
                "sampleData" + File.separator + filename;
        assertTrue(new File(path).exists());
    attachment.setFileLocation(path);
   
    //XXX We need to jav.net.URLEncoder.encode the pagetitle in the webdavPath method
    //BUT! initial tests showed that this failed with a 409 error.
    Map pagesByIdMap = rwb.getAllServerPagesMapById(confSettings, spacekey);
    String webdavPath = rwb.getWebDAVPagePath(confSettings.url, spacekey, page.getId(), pagesByIdMap, rwb.WEBDAV_PATH_LATER);
    rwb.sendFileViaWebDAV(path, webdavPath, confSettings.login, confSettings.password);
       
        List<AttachmentForXmlRpc> attachments = rwb.getAttachments(confSettings, page.getId());
        assertNotNull(attachments);
        assertEquals(1, attachments.size());
        assertEquals(filename, attachments.get(0).getFileName());
    }

    public String getUniqueString() {
        RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
        return String.valueOf((new Date()).getTime());
    }

    /**
     * Test the ability to first store and update a blog entry.
     * @throws Exception
     */
    public void testStoreBlog() throws Exception {
        RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
        String uniqueId = getUniqueString();
        String title = "testing-blog-" + uniqueId;

        //explicitly check that page does not exist
        XmlRpcClient client = new XmlRpcClient("http://" + confSettings.url + "/rpc/xmlrpc");
        Vector paramsVector = new Vector();
        String loginToken = rwb.getLoginToken(confSettings);
        paramsVector.add(loginToken);
        paramsVector.add(confSettings.spaceKey);
        int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
    paramsVector.add(day); //today's month
        paramsVector.add(title);
        Hashtable retblog = null;
        try  {
          retblog = (Hashtable) client.execute("confluence1.getBlogEntryByDayAndTitle", paramsVector);
          fail();
        } catch (XmlRpcException e) {}
       
        //create page first time
        BlogForXmlRpc blog = new BlogForXmlRpc();
    blog.setTitle(title);
        String content1 = "this is some content " + uniqueId;
    blog.setContent(content1);
    blog.setSpace(confSettings.spaceKey);
        rwb.storeBlog(confSettings, blog);
       
        try  {
          retblog = (Hashtable) client.execute("confluence1.getBlogEntryByDayAndTitle", paramsVector);
          assertNotNull(retblog);
          assertEquals(title, (String) retblog.get("title"));
          assertEquals(content1, (String) retblog.get("content"));
        } catch (XmlRpcException e) {
          fail();
        }
       
        //update blog
        blog = new BlogForXmlRpc();
        blog.setTitle(title);
        String content2 = "this is some UPDATED content " + uniqueId;
    blog.setContent(content2);
        rwb.storeBlog(confSettings, blog);
       
        try  {
          retblog = (Hashtable) client.execute("confluence1.getBlogEntryByDayAndTitle", paramsVector);
          assertNotNull(retblog);
          assertEquals(title, (String) retblog.get("title"));
          assertEquals(content2, (String) retblog.get("content"));
        } catch (XmlRpcException e) {
          fail();
        }
    }
   
    /**
     *
     */
    public void testGetAllServerPages() throws Exception {
        RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
        Map pagesMap = rwb.getAllServerPagesMapByTitle(confSettings, "crjwtest");
        Collection pagesCollection = pagesMap.values();
        for (Iterator iterator = pagesCollection.iterator(); iterator.hasNext();) {
            PageForXmlRpc page = (PageForXmlRpc) iterator.next();
            log.debug(page);
        }
        //no Exceptions were thrown. Success!!
    }

    public void testMovePage() throws Exception { //move page method is available in the Remote API as of Conf 2.9

      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      String uniqueId = getUniqueString();
      String title = "testing-move-" + uniqueId;
      String parentTitle  = "testing-move-parent-" + uniqueId;

      //explicitly check that pages do not exist
      XmlRpcClient client = new XmlRpcClient("http://" + confSettings.url + "/rpc/xmlrpc");
      Vector paramsVector = new Vector();
      String loginToken = rwb.getLoginToken(confSettings);
      paramsVector.add(loginToken);
      paramsVector.add(confSettings.spaceKey);
      paramsVector.add(title);
      Hashtable retpage = null;
      try  {
        retpage = (Hashtable) client.execute("confluence1.getPage", paramsVector);
        fail();
      } catch (XmlRpcException e) {}
      paramsVector.removeAllElements();
      paramsVector.add(loginToken);
      paramsVector.add(confSettings.spaceKey);
      paramsVector.add(parentTitle);
      try  {
        retpage = (Hashtable) client.execute("confluence1.getPage", paramsVector);
        fail();
      } catch (XmlRpcException e) {}
     
      //create page
      PageForXmlRpc page = new PageForXmlRpc();
      page.setTitle(title);
      String content1 = "this is some content " + uniqueId;
      page.setContent(content1);
      page = rwb.storeNewOrUpdatePage(confSettings, confSettings.spaceKey, page);

      //create another page (will be parent)
      PageForXmlRpc parent = new PageForXmlRpc();
      parent.setTitle(parentTitle);
      content1 = "parent page " + uniqueId;
      parent.setContent(content1);
      parent = rwb.storeNewOrUpdatePage(confSettings, confSettings.spaceKey, parent);

      //move page to parent
      try {
        boolean retval = rwb.movePage(confSettings, page.getId(), parent.getId(),
            RemoteWikiBroker.Position.APPEND);
        assertTrue(retval);
        //get the page object, and test that it's parent id is the parent page
        paramsVector.removeAllElements();
          paramsVector.add(loginToken);
          paramsVector.add(confSettings.spaceKey);
          paramsVector.add(title);
          try  {
            retpage = (Hashtable) client.execute("confluence1.getPage", paramsVector);
          } catch (XmlRpcException e) {}
          String id = (String) retpage.get("parentId");
          assertNotNull(id);
          assertEquals(parent.getId(), id);
      } catch (Exception e) {
        throw e;
      }
      finally {
        //clean up
        deletePage(page.getId(), confSettings);
        deletePage(parent.getId(), confSettings);
      }
    }

    public void testCheckConnectivity() throws Exception {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      ConfluenceServerSettings confSettingsTest = confSettings;
      String message = rwb.checkConnectivity(confSettingsTest);
      assertTrue(message!=null && message.startsWith(RemoteWikiBroker.USER_MESSAGE_CONNECTIVTY_SUCCESS));

      confSettingsTest.login = "wrong-login";
      message = rwb.checkConnectivity(confSettingsTest);
      assertTrue(message, message!=null && message.startsWith(RemoteWikiBroker.USER_ERROR_WRONG_USERNAME));

      confSettingsTest.login = props.getProperty(TEST_USER_LOGIN);
      confSettingsTest.password = "wrong-password";
      message = rwb.checkConnectivity(confSettingsTest);
      assertTrue(message, message!=null && message.startsWith(RemoteWikiBroker.USER_ERROR_WRONG_PASSWORD));

      confSettingsTest.password = props.getProperty(TEST_PASS);
      confSettingsTest.url = "wrong-server";
      message = rwb.checkConnectivity(confSettingsTest);
      assertTrue(message!=null && message.startsWith(RemoteWikiBroker.USER_ERROR_CANNOT_REACH_SERVER));

      confSettingsTest.url = "something.com";
      message = rwb.checkConnectivity(confSettingsTest);
      assertTrue(message!=null && message.startsWith(RemoteWikiBroker.USER_ERROR_CANNOT_REACH_SERVER));

      confSettingsTest.url = "www.something.com";
      message = rwb.checkConnectivity(confSettingsTest);
      assertTrue(message!=null && message.startsWith(RemoteWikiBroker.USER_ERROR_CANNOT_REACH_SERVER));

      confSettingsTest.url = "localhost:80832";
      message = rwb.checkConnectivity(confSettingsTest);
      assertTrue(message!=null && message.startsWith(RemoteWikiBroker.USER_ERROR_CANNOT_REACH_SERVER));

      confSettingsTest.url = "http:localhost:8082";
      message = rwb.checkConnectivity(confSettingsTest);
      assertTrue(message!=null && message.startsWith(RemoteWikiBroker.USER_ERROR_UNKNOWN));

      confSettingsTest.url = "https://localhost:8443";
      message = rwb.checkConnectivity(confSettingsTest);
      assertTrue(message!=null && message.startsWith(RemoteWikiBroker.BAD_TRUSTSTORE));

    }

    public void testCheckConnectivity_RemoteApiOff() {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      ConfluenceServerSettings confSettingsTest = confSettings;
      String message = rwb.checkConnectivity(confSettingsTest);
      assertTrue(message!=null);
      String expected = RemoteWikiBroker.USER_MESSAGE_FORBIDDEN;
      assertTrue("Remote API must be off for this test to work.", message.startsWith(expected));
    }

    //XXX This test appears to need to be before testGetUserPermissionsForUser
    public void testAddComment() throws IOException, XmlRpcException {
      RemoteWikiBroker broker = RemoteWikiBroker.getInstance();
      String spacekey = confSettings.spaceKey;
      String pagename = "Home"; //There's always a home
      String loginToken = broker.getLoginToken(confSettings);

      String id = broker.getPageIdFromConfluence(confSettings, spacekey, pagename);
      assertNotNull(id);

      CommentForXmlRpc comment = new CommentForXmlRpc();
      String input = "test content *bold*";
      comment.setContent(input);
      comment.setPageId(id);
      CommentForXmlRpc actual = broker.addComment(confSettings, comment);
      deleteComment(actual.getId()); //cleanup the unit test
      assertNotNull(actual);
      assertEquals("Re: Home", actual.getTitle());
      assertEquals(input, actual.getContent());
      assertEquals(confSettings.login, actual.getCreator());

      //creator, created, url, title, id
      try {
        comment.setCreator("testing");
        fail();
      } catch (UnsupportedOperationException e) {}
      try {
        comment.setCreated("testing");
        fail();
      } catch (UnsupportedOperationException e) {}
      try {
        comment.setUrl("testing");
        fail();
      } catch (UnsupportedOperationException e) {}
      try {
        comment.setTitle("testing");
        fail();
      } catch (UnsupportedOperationException e) {}
      try {
        comment.setId("testing");
        fail();
      } catch (UnsupportedOperationException e) {}

    }

    private void deleteComment(String commentid) throws XmlRpcException, IOException {
      log.debug("deleting junit created comment");
      XmlRpcClient client = new XmlRpcClient("http://" + confSettings.url + "/rpc/xmlrpc");
      String loginToken = RemoteWikiBroker.getInstance().getLoginToken(confSettings);
      Vector paramsVector = new Vector();
      paramsVector.add(loginToken);
      paramsVector.add(commentid);

      client.execute("confluence1.removeComment", paramsVector);
    }




    public void testGetSpace() {
      //The following to work. The second, 'cause we need a diff method to test it, see next test
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();

      //exists
      String spacekey = props.getProperty(TEST_SPACE);
      SpaceForXmlRpc space;
      try {
        space = rwb.getSpace(confSettings, spacekey);
        assertNotNull(space);
        assertEquals(spacekey, space.getSpaceKey());
      } catch (Exception e) {
        e.printStackTrace();
        fail();
      }

      //doesn't exist
      String badspace = "abcdef";
      confSettings.spaceKey = badspace;
      try {
        space = rwb.getSpace(confSettings, badspace);
        //Conf 2.x throws exception if it doesn't exist
        //Conf 3.x returns null
        assertNull(space);
      } catch (Exception e) {}


      //doesn't have view permissions for the space -
      //XXX:   It appears to be impossible to differentiate between
      //    a user not having view permissions, and
      //    the space not existing
      confSettings.spaceKey = props.getProperty(TEST_SPACE);
      confSettings.url = props.getProperty(TEST_URL);
      confSettings.login = props.getProperty(TEST_NOPERMS_LOGIN);
      confSettings.password = props.getProperty(TEST_NOPERMS_PASS);
      try {
        space = rwb.getSpace(confSettings, confSettings.spaceKey);
        //Conf 2.x throws exception if it doesn't exist
        //Conf 3.x returns null
        assertNull(space);
      } catch (Exception e) {}
    }

    private boolean testingSpace = false;
    public void testAddSpace () {
      //to test, set above boolean to true;
      if (!testingSpace) fail("Set testingSpace to true, if you want to test creating spaces");
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      SpaceForXmlRpc space = new SpaceForXmlRpc();
      space.setSpaceKey("testaddspace");
      space.setSpaceName("Testing Space Creation");
      space.setDescription("Global space");
    try {
      rwb.addSpace(confSettings, space);
    } catch (Exception e) {
      fail();
    }

    //personal space test
    rwb = RemoteWikiBroker.getInstance();
      space = new SpaceForXmlRpc();
      space.setSpaceKey("testaddspace2");
      space.setSpaceName("Testing PSpace Creation");
      space.setDescription("Personal space");
      space.setType(SpaceType.PERSONAL);
      space.setUsername(confSettings.login);
    try {
      rwb.addSpace(confSettings, space);
    } catch (Exception e) {
      fail();
    }
    }
   
   
    /**
     * Retrieve a user and confirm their properties
     * http://confluence.atlassian.com/display/DOC/Remote+API+Specification#RemoteAPISpecification-UserManagement
     */
    public void testHasUser() throws Exception {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      String username = confSettings.login;
      assertTrue(rwb.hasUser(confSettings, username));
    }


    /**
     * Retrieve a user and confirm their properties
     * http://confluence.atlassian.com/display/DOC/Remote+API+Specification#RemoteAPISpecification-UserManagement
     */
    public void testGetUser() throws Exception {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      String username = confSettings.login;
      UserForXmlRpc user = rwb.getUser(confSettings, username);
      assertEquals(props.getProperty(TEST_EMAIL), user.getEmail());
    }
   
    public void testGetUserInformation() throws Exception {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      String username = confSettings.login;
      UserInformation info = rwb.getUserInformation(confSettings, username);
      assertNotNull(info.getCreationDate());
      assertNotNull(info.getHashtable());
    }
    private static final int NUMUSERS = 5;
    public void testGetUsers() throws Exception {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      String username = confSettings.login;
      boolean viewAll = true;
      List<String> users = rwb.getActiveUsers(confSettings, viewAll);
      assertNotNull(users);
      assertEquals(NUMUSERS, users.size());
      String[] expected = { "admin", "notadmin", "notadmin2", "notadmin3", "notadmin4" };//XXX This needs to be set correctly
      for (String exp : expected) {
      assertTrue("No " + exp , users.contains(exp));
    }
     
      viewAll = false;
      users = null;
      users = rwb.getActiveUsers(confSettings, viewAll);
      assertNotNull(users);
      assertEquals(5, users.size());
     
    }
    public void testDeactivateUser() throws Exception {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      String testuser = "notadmin";
      UserForXmlRpc user = rwb.getUser(confSettings, testuser);
      assertNotNull(user); //XXX THIS USER NEEDS TO BE ALREADY SET UP IN THE TEST CONFLUENCE
     
      try {
        boolean status = rwb.deactivateUser(confSettings, testuser);
        assertTrue(status);
        List<String> all = rwb.getActiveUsers(confSettings, false);
        assertNotNull(all);
        assertEquals(NUMUSERS-1, all.size());
      } catch (Exception e) {
        fail(confSettings.login + " account must be able to deactivate users");
      } finally {
        rwb.reactivateUser(confSettings, testuser);
        List<String> all = rwb.getActiveUsers(confSettings, false);
        assertNotNull(all);
        assertEquals(NUMUSERS, all.size());
      }
    }
   
    public void testUdmfRpc_setCreator() throws IOException, XmlRpcException {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      PageForXmlRpc page = new PageForXmlRpc();
        String uniqueId = getUniqueString();
        page.setTitle("Test Crjw uses Udmf " + uniqueId);
        page.setContent("Testing 123 " + uniqueId);
        try {
          rwb.needNewLogin(); //we appear to need a new login token (probably the fault of testGetUser)
          page = rwb.storeNewOrUpdatePage(confSettings, props.getProperty(TEST_SPACE), page);
 
          String retval = rwb.setCreator(confSettings, "notmod", page.getId());
          assertNotNull(retval);
          assertEquals("notmod", retval);
          //double check the boolean variant
          String badusername = "notmod"+uniqueId;
          try {
            retval = rwb.setCreator(confSettings, badusername, page.getId());
            fail();
          } catch (Exception e) {}
         
          retval = rwb.setCreator(confSettings, badusername, page.getId(), false);
          assertNotNull(retval);
          assertEquals(badusername, retval);
        } finally {
          deletePage(page.getId(), confSettings);
        }
    }
   
    public void testUdmfRpc_setLastModifier() throws IOException, XmlRpcException {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      PageForXmlRpc page = new PageForXmlRpc();
        String uniqueId = getUniqueString();
        page.setTitle("Test Crjw uses Udmf " + uniqueId);
        page.setContent("Testing 123 " + uniqueId);
        try {
          page = rwb.storeNewOrUpdatePage(confSettings, props.getProperty(TEST_SPACE), page);

          String retval = rwb.setLastModifier(confSettings, "notmod", page.getId());
          assertNotNull(retval);
          assertEquals("notmod", retval);
         
          //double check the boolean variant
          String badusername = "notmod"+uniqueId;
          try {
            retval = rwb.setLastModifier(confSettings, badusername, page.getId());
            fail();
          } catch (Exception e) {}
         
          retval = rwb.setLastModifier(confSettings, badusername, page.getId(), false);
          assertNotNull(retval);
          assertEquals(badusername, retval);
        } finally {
          deletePage(page.getId(), confSettings);
        }
    }
   
    public void testUdmfRpc_setCreateDate() throws IOException, XmlRpcException {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      PageForXmlRpc page = new PageForXmlRpc();
        String uniqueId = getUniqueString();
        page.setTitle("Test Crjw uses Udmf " + uniqueId);
        page.setContent("Testing 123 " + uniqueId);
        try {
          page = rwb.storeNewOrUpdatePage(confSettings, props.getProperty(TEST_SPACE), page);
 
          String date = "2001:01:02:03:04:05:06";
      String retval = rwb.setCreateDate(confSettings, date , page.getId());
          assertNotNull(retval);
          assertEquals(date, retval);
        } finally {
          deletePage(page.getId(), confSettings);
        }
    }
   
    public void testUdmfRpc_setLastModifiedDate() throws IOException, XmlRpcException {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      PageForXmlRpc page = new PageForXmlRpc();
        String uniqueId = getUniqueString();
        page.setTitle("Test Crjw uses Udmf " + uniqueId);
        page.setContent("Testing 123 " + uniqueId);
        try {
          page = rwb.storeNewOrUpdatePage(confSettings, props.getProperty(TEST_SPACE), page);

          String date = "1995:12:31:23:59:58:57";
          String retval = rwb.setLastModifiedDate(confSettings, date, page.getId());
          assertNotNull(retval);
          assertEquals(date, retval);
        } finally {
          deletePage(page.getId(), confSettings);
        }
    }
   
    public void testIsPluginEnabled() throws XmlRpcException, IOException {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      String pluginkey = "com.steepdevelopment.confluence.udmf";
      boolean actual = rwb.isPluginEnabled(confSettings, pluginkey);
      assertTrue(actual);
    }

    Pattern permissions = Pattern.compile(
        "\\[" +        //left bracket
        "(" +      //begin capturing group 1
        "[" +     
        "^\\]" + //anything not a right bracket
        "]+" +    //until
        ")" +       //end capturing group 1
    "\\]");        //right bracket
    public void testGetUserPermissionsForUser() throws Exception {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();

      //with user who has create permissions for that space
      confSettings.login = props.getProperty(TEST_USER_LOGIN);
      confSettings.password = props.getProperty(TEST_PASS);
      String message = rwb.getUserPermissionsForUser(confSettings);

      assertNotNull(message);
      assertTrue(message.startsWith(RemoteWikiBroker.PERMS_SUCCESS_PREFIX));
      Matcher matcher = permissions.matcher(message);
      if (matcher.find()) {
        String permsString = matcher.group(1);
        assertTrue(message, permsString.matches(".*?modify.*"));
      }
      else
        fail("Should have found some permissions.");

      //with different user who doesn't have any permissions for that space
      //XXX:   It appears to be impossible to differentiate between
      //    a user not having view permissions, and
      //    the space not existing
      confSettings.login = props.getProperty(TEST_NOPERMS_LOGIN);
      confSettings.password = props.getProperty(TEST_NOPERMS_PASS);
      message = rwb.getUserPermissionsForUser(confSettings);

      assertNotNull(message);
      assertTrue(message.startsWith(RemoteWikiBroker.PERMS_FAILURE_PREFIX));

      //with different user who has view but not create permissions for that space
      confSettings.login = props.getProperty(TEST_PERMS_LOGIN);
      confSettings.password = props.getProperty(TEST_PERMS_PASS);
      message = rwb.getUserPermissionsForUser(confSettings);

      assertNotNull(message);
      assertTrue(message, message.startsWith(RemoteWikiBroker.PERMS_SUCCESS_PREFIX));
      matcher = permissions.matcher(message);
      if (matcher.find()) {
        String permsString = matcher.group(1);
        assertFalse(message, permsString.matches(".*?modify.*"));
        assertTrue(permsString.matches(".*?view.*"));
      }
      else
        fail("Should have found some permissions.");

      //the space doesn't exist
      //XXX:   It appears to be impossible to differentiate between
      //    a user not having view permissions, and
      //    the space not existing
      confSettings.login = props.getProperty(TEST_USER_LOGIN);
      confSettings.password = props.getProperty(TEST_PASS);
      confSettings.spaceKey = props.getProperty(TEST_SPACE_BAD);
      message = rwb.getUserPermissionsForUser(confSettings);

      assertNotNull(message);
      assertTrue(message.startsWith(RemoteWikiBroker.PERMS_FAILURE_PREFIX));

    }


    /**
     * Add a user
     * http://confluence.atlassian.com/display/DOC/Remote+API+Specification#RemoteAPISpecification-UserManagement
     */
    public void testAddUser() throws Exception {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      confSettings.login = props.getProperty(TEST_USERADM_LOGIN); //make sure this user part of confluence-admin group
      confSettings.password = props.getProperty(TEST_USERADM_PASS);

      UserForXmlRpc user = new UserForXmlRpc();
      user.setName("addeduser");
      user.setFullname("Added User");
      user.setEmail("addeduser@atlassian.com");
      user.setUrl("http://www.atlassian.com");
      //XXX make sure "addeduser" doesn't already exist
      rwb.addUser(confSettings, user, "password");
      assertTrue(rwb.hasUser(confSettings, "addeduser"));
    }


    /**
     * Check if a group exists
     * http://confluence.atlassian.com/display/DOC/Remote+API+Specification#RemoteAPISpecification-UserManagement
     */
    public void testHasGroup() throws Exception {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      confSettings.login = props.getProperty(TEST_USERADM_LOGIN); //make sure this user part of confluence-admin group
      confSettings.password = props.getProperty(TEST_USERADM_PASS);
      String groupname = "confluence-users";
      boolean groupExists = rwb.hasGroup(confSettings, groupname);
      assertTrue(groupExists);
    }

    /**
     * Create a new group
     * http://confluence.atlassian.com/display/DOC/Remote+API+Specification#RemoteAPISpecification-UserManagement
     */
    public void testAddGroup() throws Exception {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      confSettings.login = props.getProperty(TEST_USERADM_LOGIN); //make sure this user part of confluence-admin group
      confSettings.password = props.getProperty(TEST_USERADM_PASS);
      String groupname = "newgroup";
      rwb.addGroup(confSettings, groupname);
      assertTrue(rwb.hasGroup(confSettings, groupname));
    }
   
    /**
     * assign permissions to a new group for the testspace
     * @throws Exception
     */
    public void testAssignPermissions() throws Exception {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      confSettings.login = props.getProperty(TEST_USERADM_LOGIN); //make sure this user part of confluence-admin group
      confSettings.password = props.getProperty(TEST_USERADM_PASS);
      String groupname = "newgroup";
      if (!rwb.hasGroup(confSettings, groupname)) {
        rwb.addGroup(confSettings, groupname);
      }
      Vector<String> newperms = new Vector<String>();
      newperms.add("VIEWSPACE");
      newperms.add("EDITSPACE");
      newperms.add("EXPORTSPACE");
      newperms.add("REMOVECOMMENT");
      assertTrue(rwb.addPermissionsToSpace(confSettings, newperms, groupname));
    }

    /**
     * add a user to a group
     * http://confluence.atlassian.com/display/DOC/Remote+API+Specification#RemoteAPISpecification-UserManagement
     * this test will pretty obviously fail if either of the user or group don't already exist so
     * it would be nice to force those tests to go first (ah for TestNG).
     */
    public void testAddUserToGroup() throws Exception {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      String username = "addeduser";
      String groupname = "newgroup";
      rwb.addUserToGroup(confSettings, username, groupname);
      Vector groups = rwb.getUserGroups(confSettings, username);
      // 2 because of "confluence-users" and "newgroup"
      assertEquals(2, groups.size());
      assertTrue(groups.contains(groupname));
    }

    /**
     * retrieve the groups a user belongs to
     * without ordering or teardowns in the other group tests what exactly should we be testing for?
     *
     * @throws Exception
     */
    public void testGetUserGroups() throws Exception {
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      String username = "test";
      confSettings.login = props.getProperty(TEST_USERADM_LOGIN); //make sure this user part of confluence-admin group
      confSettings.password = props.getProperty(TEST_USERADM_PASS);
      Vector groups = rwb.getUserGroups(confSettings, username);
      assertNotNull(groups);
      assertTrue(groups.size() +"", groups.size() == 1 );
    }
   
    public void testGetPageSummary() { //Confluence 4.0+
      RemoteWikiBroker broker = RemoteWikiBroker.getInstance();
      try {
      broker.getPageSummary(confSettings, confSettings.spaceKey, "Home");
    } catch (Exception e) {
      fail();
    }
    }
   
    public void testGetPageIdFromConfluence() {
      RemoteWikiBroker broker = RemoteWikiBroker.getInstance();
      try {
        String idStr = broker.getPageIdFromConfluence(confSettings, confSettings.spaceKey, "Home");
        int id = Integer.parseInt(idStr);
        assertTrue(id > 0);
      } catch (Exception e) {
        fail();
      }
    }

    /* Helper Methods */

    private void deletePage(String id, ConfluenceServerSettings confSettings) {
      confSettings.url = confSettings.url.replaceFirst("https?://", "");
      RemoteWikiBroker rwb = RemoteWikiBroker.getInstance();
      XmlRpcClient client = getXmlRpcClient(confSettings);
      Vector paramsVector = new Vector();
      try {
        paramsVector.add(RemoteWikiBroker.getInstance().getLoginToken(confSettings));
      } catch (Exception e1) {
        e1.printStackTrace();
      }
      paramsVector.add(id);
      try {
        client.execute("confluence1.removePage", paramsVector );
      } catch (XmlRpcException e) {
      } catch (IOException e) {
        fail("Shouldn't have IO exception");
      }
    }
    private XmlRpcClient getXmlRpcClient(ConfluenceServerSettings confSettings) {
      String connectionURL = "http://" + confSettings.url + "/rpc/xmlrpc";
      XmlRpcClient clientConnection = null;
      try {
        clientConnection = new XmlRpcClient(connectionURL);
      } catch (MalformedURLException e) {
        e.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
      }
      return clientConnection;
    }
  

}
TOP

Related Classes of biz.artemis.confluence.xmlrpcwrapper.test.RemoteWikiBrokerTest

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.