@Test
  public void getVelocityEngineWhenNoVelocityEngineInCache() throws Exception {
    Execution execution = this.mocker.getInstance(Execution.class);
    ExecutionContext executionContext = new ExecutionContext();
    when(execution.getContext()).thenReturn(executionContext);

    XWikiContext xwikiContext = mock(XWikiContext.class);
    Provider<XWikiContext> xcontextProvider = this.mocker.getInstance(XWikiContext.TYPE_PROVIDER);
    when(xcontextProvider.get()).thenReturn(xwikiContext);
    com.xpn.xwiki.XWiki xwiki = mock(com.xpn.xwiki.XWiki.class);
    when(xwikiContext.getWiki()).thenReturn(xwiki);
    when(xwiki.getSkin(any(XWikiContext.class))).thenReturn("testskin");

    VelocityFactory velocityFactory = this.mocker.getInstance(VelocityFactory.class);
    when(velocityFactory.hasVelocityEngine("default")).thenReturn(false);

    VelocityConfiguration velocityConfiguration =
        this.mocker.getInstance(VelocityConfiguration.class);
    when(velocityConfiguration.getProperties()).thenReturn(new Properties());

    VelocityEngine velocityEngine = mock(VelocityEngine.class);
    when(velocityFactory.createVelocityEngine(eq("default"), any(Properties.class)))
        .thenReturn(velocityEngine);

    Assert.assertSame(velocityEngine, this.mocker.getComponentUnderTest().getVelocityEngine());
  }
 protected List<String> getDefaultContributors(
     Document doc, Map<String, Object> params, XWikiContext context) {
   XWiki xwiki = context.getWiki();
   List<String> contributors = new ArrayList<String>();
   contributors.add(xwiki.getUserName(doc.getAuthor(), null, false, context));
   return contributors;
 }
  @Override
  protected void hibernateMigrate() throws DataMigrationException, XWikiException {
    // Context, XWiki
    XWikiContext context = getXWikiContext();
    XWiki xwiki = context.getWiki();

    // Current wiki
    String currentWikiId = wikiDescriptorManager.getCurrentWikiId();

    // Get the old wiki descriptor
    DocumentReference oldWikiDescriptorReference =
        new DocumentReference(
            wikiDescriptorManager.getMainWikiId(),
            XWiki.SYSTEM_SPACE,
            String.format("XWikiServer%s", StringUtils.capitalize(currentWikiId)));
    XWikiDocument oldWikiDescriptor = xwiki.getDocument(oldWikiDescriptorReference, context);

    // Try to get the old workspace object
    DocumentReference oldClassDocument =
        new DocumentReference(
            wikiDescriptorManager.getMainWikiId(), WORKSPACE_CLASS_SPACE, WORKSPACE_CLASS_PAGE);
    BaseObject oldObject = oldWikiDescriptor.getXObject(oldClassDocument);

    // Upgrade depending of the type
    if (oldObject != null || isWorkspaceTemplate(currentWikiId)) {
      // It's a workspace
      upgradeWorkspace(oldObject, currentWikiId, oldWikiDescriptor);
    } else {
      // It's a regular subwiki
      upgradeRegularSubwiki(currentWikiId);
    }
  }
  protected void setUp() throws Exception {
    super.setUp();

    getContext().setDoc(new XWikiDocument());

    XWiki xwiki = new XWiki();

    Mock mockXWikiStore =
        mock(
            XWikiHibernateStore.class,
            new Class[] {XWiki.class, XWikiContext.class},
            new Object[] {xwiki, getContext()});
    xwiki.setStore((XWikiStoreInterface) mockXWikiStore.proxy());

    Mock mockXWikiRenderingEngine = mock(XWikiRenderingEngine.class);
    mockXWikiRenderingEngine
        .stubs()
        .method("interpretText")
        .will(
            new CustomStub("Implements XWikiRenderingEngine.interpretText") {
              public Object invoke(Invocation invocation) throws Throwable {
                return invocation.parameterValues.get(0);
              }
            });

    xwiki.setRenderingEngine((XWikiRenderingEngine) mockXWikiRenderingEngine.proxy());

    getContext().setWiki(xwiki);
  }
  @Override
  public int verify(String identifier, char[] secret) throws IllegalArgumentException {
    XWikiContext xwikiContext = Utils.getXWikiContext(this.componentManager);
    XWiki xwiki = Utils.getXWiki(this.componentManager);

    try {
      Principal principal =
          (secret == null)
              ? null
              : xwiki.getAuthService().authenticate(identifier, new String(secret), xwikiContext);
      if (principal != null) {
        String xwikiUser = principal.getName();

        xwikiContext.setUser(xwikiUser);

        this.context
            .getLogger()
            .log(Level.FINE, String.format("Authenticated as '%s'.", identifier));

        return RESULT_VALID;
      }
    } catch (XWikiException e) {
      this.context.getLogger().log(Level.WARNING, "Exception occurred while authenticating.", e);
    }

    this.context
        .getLogger()
        .log(Level.WARNING, String.format("Cannot authenticate '%s'.", identifier));

    return RESULT_INVALID;
  }
  @Test
  public void onEventWithExceptions() throws ComponentLookupException, XWikiException {
    Utils.setComponentManager(this.mocker);

    DocumentReference docReference = new DocumentReference("xwiki", "Groups", "Group1");
    XWikiContext context = mock(XWikiContext.class);
    XWiki xwiki = mock(XWiki.class);
    when(context.getWiki()).thenReturn(xwiki);

    XWikiDocument doc = mock(XWikiDocument.class);
    when(doc.getDocumentReference()).thenReturn(docReference);
    when(doc.getXObject(Group.CLASS_REFERENCE)).thenReturn(mock(BaseObject.class));

    DocumentReference adminsDocReference =
        new DocumentReference("xwiki", "Groups", "Group1 Administrators");
    when(xwiki.getDocument(eq(adminsDocReference), eq(context)))
        .thenThrow(new XWikiException(0, 0, "DB Error"));

    DocumentAccessBridge dab = this.mocker.getInstance(DocumentAccessBridge.class);

    DocumentReference userReference = new DocumentReference("xwiki", "XWiki", "User");
    when(dab.getCurrentUserReference()).thenReturn(userReference);

    this.mocker
        .getComponentUnderTest()
        .onEvent(new DocumentCreatingEvent(docReference), doc, context);

    Mockito.verify(xwiki, Mockito.never())
        .saveDocument(eq(doc), any(String.class), any(Boolean.class), eq(context));

    Mockito.verify(doc).getXObject(Group.CLASS_REFERENCE);
    Mockito.verify(doc).getDocumentReference();
    Mockito.verifyNoMoreInteractions(doc);
  }
Example #7
0
  protected static BaseClass getXWikiGroupRelationClass(XWikiContext context)
      throws XWikiException {
    XWikiDocument doc;
    XWiki xwiki = context.getWiki();
    boolean needsUpdate = false;

    try {
      doc = xwiki.getDocument("XWiki.GroupRelationClass", context);
    } catch (Exception e) {
      doc = new XWikiDocument();
      doc.setSpace("XWiki");
      doc.setName("GroupRelationClass");
      needsUpdate = true;
    }

    BaseClass bclass = doc.getxWikiClass();
    bclass.setName("XWiki.GroupRelationClass");
    needsUpdate |= bclass.addTextField("name", "Name", 30);
    needsUpdate |= bclass.addTextField("parentpage", "Parent", 30);
    needsUpdate |= bclass.addTextAreaField("description", "Description", 40, 5);

    String content = doc.getContent();
    if ((content == null) || (content.equals(""))) {
      needsUpdate = true;
      doc.setContent("1 XWikiGroup");
      doc.setSyntax(Syntax.XWIKI_1_0);
    }

    if (needsUpdate) xwiki.saveDocument(doc, context);
    return bclass;
  }
  private BaseClass getSubscriptionClass(XWikiContext context) throws XWikiException {
    XWikiDocument doc;
    XWiki xwiki = context.getWiki();
    boolean needsUpdate = false;

    try {
      doc = xwiki.getDocument(CelementsCalendarPlugin.SUBSCRIPTION_CLASS, context);
    } catch (Exception e) {
      doc = new XWikiDocument();
      doc.setSpace(CelementsCalendarPlugin.SUBSCRIPTION_CLASS_SPACE);
      doc.setName(CelementsCalendarPlugin.SUBSCRIPTION_CLASS_DOC);
      needsUpdate = true;
    }

    BaseClass bclass = doc.getxWikiClass();
    bclass.setName(CelementsCalendarPlugin.SUBSCRIPTION_CLASS);
    needsUpdate |= bclass.addTextField("subscriber", "subscriber", 30);
    needsUpdate |= bclass.addBooleanField("doSubscribe", "doSubscribe", "yesno");

    String content = doc.getContent();
    if ((content == null) || (content.equals(""))) {
      needsUpdate = true;
      doc.setContent(" ");
    }

    if (needsUpdate) {
      xwiki.saveDocument(doc, context);
    }
    return bclass;
  }
  @Override
  public void copyDocuments(String fromWikiId, String toWikiId, boolean withHistory)
      throws WikiManagerException {
    XWikiContext context = xcontextProvider.get();
    XWiki xwiki = context.getWiki();

    try {
      Query query =
          queryManager.createQuery("select distinct doc.fullName from Document as doc", Query.XWQL);
      query.setWiki(fromWikiId);
      List<String> documentFullnames = query.execute();

      observationManager.notify(new PushLevelProgressEvent(documentFullnames.size()), this);

      WikiReference fromWikiReference = new WikiReference(fromWikiId);
      for (String documentFullName : documentFullnames) {
        DocumentReference origDocReference =
            documentReferenceResolver.resolve(documentFullName, fromWikiReference);
        DocumentReference newDocReference =
            new DocumentReference(
                toWikiId,
                origDocReference.getLastSpaceReference().getName(),
                origDocReference.getName());
        xwiki.copyDocument(origDocReference, newDocReference, null, !withHistory, true, context);

        observationManager.notify(new StepProgressEvent(), this);
      }

      observationManager.notify(new PopLevelProgressEvent(), this);
    } catch (QueryException e) {
      throw new WikiManagerException("Unable to get the source wiki documents.", e);
    } catch (XWikiException e) {
      throw new WikiManagerException("Failed to copy document.", e);
    }
  }
 protected String getDefaultDescription(
     Document doc, Map<String, Object> params, XWikiContext context) {
   XWiki xwiki = context.getWiki();
   String author = xwiki.getUserName(doc.getAuthor(), null, false, context);
   // the description format should be taken from a resource bundle, and thus localized
   String descFormat = "Version %1$s edited by %2$s on %3$s";
   return String.format(descFormat, new Object[] {doc.getVersion(), author, doc.getDate()});
 }
  @Test
  public void getMembersWhenGroupIsLooping() throws Exception {
    setUpBaseMocks();

    DocumentReference groupReference = new DocumentReference("groupwiki", "XWiki", "grouppage");
    XWikiDocument document = mock(XWikiDocument.class);
    when(document.isNew()).thenReturn(false);
    when(document.getDocumentReference()).thenReturn(groupReference);
    when(xwiki.getDocument(groupReference, this.xwikiContext)).thenReturn(document);

    List<BaseObject> memberObjects = new ArrayList<>();
    BaseObject bo = mock(BaseObject.class);
    when(bo.getStringValue("member")).thenReturn("XWiki.othergroup");
    memberObjects.add(bo);
    bo = mock(BaseObject.class);
    when(bo.getStringValue("member")).thenReturn("XWiki.userpage");
    memberObjects.add(bo);
    when(document.getXObjects(new DocumentReference("groupwiki", "XWiki", "XWikiGroups")))
        .thenReturn(memberObjects);

    DocumentReference userpageReference = new DocumentReference("groupwiki", "XWiki", "userpage");
    setUpUserPageMocks(userpageReference);
    when(this.resolver.resolve("XWiki.userpage", groupReference)).thenReturn(userpageReference);

    DocumentReference otherGroupReference =
        new DocumentReference("groupwiki", "XWiki", "othergroup");
    document = mock(XWikiDocument.class);
    when(document.isNew()).thenReturn(false);
    when(document.getDocumentReference()).thenReturn(otherGroupReference);
    when(xwiki.getDocument(otherGroupReference, this.xwikiContext)).thenReturn(document);

    memberObjects = new ArrayList<>();
    bo = mock(BaseObject.class);
    when(bo.getStringValue("member")).thenReturn("XWiki.grouppage");
    memberObjects.add(bo);
    bo = mock(BaseObject.class);
    when(bo.getStringValue("member")).thenReturn("XWiki.anotheruser");
    memberObjects.add(bo);
    when(document.getXObjects(new DocumentReference("groupwiki", "XWiki", "XWikiGroups")))
        .thenReturn(memberObjects);

    DocumentReference anotheruserReference =
        new DocumentReference("groupwiki", "XWiki", "anotheruser");
    setUpUserPageMocks(anotheruserReference);
    when(this.resolver.resolve("XWiki.anotheruser", otherGroupReference))
        .thenReturn(anotheruserReference);

    when(this.resolver.resolve("XWiki.grouppage", otherGroupReference)).thenReturn(groupReference);
    when(this.resolver.resolve("XWiki.othergroup", groupReference)).thenReturn(otherGroupReference);

    Iterator<DocumentReference> iterator =
        new ReferenceUserIterator(groupReference, this.resolver, this.execution);

    assertThat(
        (List<DocumentReference>) IteratorUtils.toList(iterator),
        containsInAnyOrder(userpageReference, anotheruserReference));
  }
  @Test
  public void onEvent() throws ComponentLookupException, XWikiException {
    Utils.setComponentManager(this.mocker);

    DocumentReference docReference = new DocumentReference("xwiki", "Groups", "Group1");
    XWikiContext context = mock(XWikiContext.class);
    XWiki xwiki = mock(XWiki.class);
    when(context.getWiki()).thenReturn(xwiki);

    XWikiDocument doc = mock(XWikiDocument.class);
    when(doc.getDocumentReference()).thenReturn(docReference);
    BaseObject groupObject = new BaseObject();
    BaseObject rightsObject = new BaseObject();
    when(doc.newXObject(eq(this.groupsClassReference), eq(context))).thenReturn(groupObject);
    when(doc.newXObject(eq(this.rightsClassReference), eq(context))).thenReturn(rightsObject);
    when(doc.getXObject(Group.CLASS_REFERENCE)).thenReturn(mock(BaseObject.class));

    DocumentReference adminsDocReference =
        new DocumentReference("xwiki", "Groups", "Group1 Administrators");
    XWikiDocument adminsDoc = mock(XWikiDocument.class);
    BaseObject adminsGroupObject = new BaseObject();
    BaseObject adminsRightsObject = new BaseObject();
    when(adminsDoc.newXObject(eq(this.groupsClassReference), eq(context)))
        .thenReturn(adminsGroupObject);
    when(adminsDoc.newXObject(eq(this.rightsClassReference), eq(context)))
        .thenReturn(adminsRightsObject);
    when(xwiki.getDocument(eq(adminsDocReference), eq(context))).thenReturn(adminsDoc);

    DocumentAccessBridge dab = this.mocker.getInstance(DocumentAccessBridge.class);

    DocumentReference userReference = new DocumentReference("xwiki", "XWiki", "User");
    when(dab.getCurrentUserReference()).thenReturn(userReference);

    this.mocker
        .getComponentUnderTest()
        .onEvent(new DocumentCreatingEvent(docReference), doc, context);

    Mockito.verify(xwiki).saveDocument(eq(adminsDoc), any(String.class), eq(true), eq(context));
    Mockito.verify(xwiki, Mockito.never())
        .saveDocument(eq(doc), any(String.class), any(Boolean.class), eq(context));

    Assert.assertEquals(1, rightsObject.getIntValue("allow"));
    Assert.assertEquals("edit", rightsObject.getStringValue("levels"));
    Assert.assertEquals(
        "xwiki:Groups.Group1 Administrators", rightsObject.getLargeStringValue("groups"));
    Assert.assertEquals("", rightsObject.getLargeStringValue("users"));

    Assert.assertEquals(1, adminsRightsObject.getIntValue("allow"));
    Assert.assertEquals("edit", adminsRightsObject.getStringValue("levels"));
    Assert.assertEquals(
        "xwiki:Groups.Group1 Administrators", adminsRightsObject.getLargeStringValue("groups"));
    Assert.assertEquals("", adminsRightsObject.getLargeStringValue("users"));

    Assert.assertEquals("xwiki:Groups.Group1 Administrators", groupObject.getStringValue("member"));
    Assert.assertEquals("xwiki:XWiki.User", adminsGroupObject.getStringValue("member"));
  }
  private boolean isWorkspaceTemplate(String wikiId) {
    // Context, XWiki
    XWikiContext context = getXWikiContext();
    XWiki xwiki = context.getWiki();

    // In the first version of the Workspace Application, workspacetemplate did not have the
    // workspace object.
    // We test for the existence of XWiki.ManageWorkspace just to be sure that the workspacetemplate
    // is a workspace.
    return wikiId.equals("workspacetemplate")
        && xwiki.exists(new DocumentReference(wikiId, "XWiki", "ManageWorkspace"), context);
  }
Example #14
0
 public void deleteAllWikiDocuments(XWikiContext context) throws XWikiException {
   XWiki wiki = context.getWiki();
   List<String> spaces = wiki.getSpaces(context);
   for (int i = 0; i < spaces.size(); i++) {
     List<String> docNameList = wiki.getSpaceDocsName(spaces.get(i), context);
     for (String docName : docNameList) {
       String docFullName = spaces.get(i) + "." + docName;
       XWikiDocument doc = wiki.getDocument(docFullName, context);
       wiki.deleteAllDocuments(doc, context);
     }
   }
 }
  /**
   * Initializes the XWiki context.
   *
   * @param request the request being processed
   * @param response the response
   * @throws ServletException if the initialization fails
   */
  protected void initializeXWikiContext(ServletRequest request, ServletResponse response)
      throws ServletException {
    try {
      // Not all request types specify an action (e.g. GWT-RPC) so we default to the empty string.
      String action = "";
      XWikiServletContext xwikiEngine =
          new XWikiServletContext(this.filterConfig.getServletContext());
      XWikiServletRequest xwikiRequest = new XWikiServletRequest((HttpServletRequest) request);
      XWikiServletResponse xwikiResponse = new XWikiServletResponse((HttpServletResponse) response);

      // Create the XWiki context.
      XWikiContext context = Utils.prepareContext(action, xwikiRequest, xwikiResponse, xwikiEngine);

      // Overwrite the context mode if the mode filter initialization parameter is specified.
      if (this.mode >= 0) {
        context.setMode(this.mode);
      }

      // Initialize the Container component which is the new way of transporting the Context in the
      // new component
      // architecture. Further initialization might require the Container component.
      initializeContainerComponent(context);

      // Initialize the XWiki database. XWiki#getXWiki(XWikiContext) calls
      // XWikiContext.setWiki(XWiki).
      XWiki xwiki = XWiki.getXWiki(context);

      // Initialize the URL factory.
      context.setURLFactory(
          xwiki.getURLFactoryService().createURLFactory(context.getMode(), context));

      // Prepare the localized resources, according to the selected language.
      xwiki.prepareResources(context);

      // Initialize the current user.
      XWikiUser user = context.getWiki().checkAuth(context);
      if (user != null) {
        @SuppressWarnings("deprecation")
        DocumentReferenceResolver<String> documentReferenceResolver =
            Utils.getComponent(DocumentReferenceResolver.TYPE_STRING, "explicit");
        SpaceReference defaultUserSpace =
            new SpaceReference(XWiki.SYSTEM_SPACE, new WikiReference(context.getDatabase()));
        DocumentReference userReference =
            documentReferenceResolver.resolve(user.getUser(), defaultUserSpace);
        context.setUserReference(
            XWikiRightService.GUEST_USER.equals(userReference.getName()) ? null : userReference);
      }
    } catch (XWikiException e) {
      throw new ServletException("Failed to initialize the XWiki context.", e);
    }
  }
Example #16
0
 public void addAllWikiDocuments(XWikiContext context) throws XWikiException {
   XWiki wiki = context.getWiki();
   try {
     List<String> documentNames =
         wiki.getStore().getQueryManager().getNamedQuery("getAllDocuments").execute();
     for (String docName : documentNames) {
       add(docName, DocumentInfo.ACTION_OVERWRITE, context);
     }
   } catch (QueryException ex) {
     throw new PackageException(
         PackageException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH,
         "Cannot retrieve the list of documents to export",
         ex);
   }
 }
Example #17
0
  @Override
  public void displayEdit(
      StringBuffer buffer,
      String name,
      String prefix,
      BaseCollection object,
      XWikiContext context) {
    input input = new input();
    input.setAttributeFilter(new XMLAttributeValueFilter());
    BaseProperty prop = (BaseProperty) object.safeget(name);
    if (prop != null) {
      input.setValue(prop.toText());
    }

    input.setType("text");
    input.setName(prefix + name);
    input.setID(prefix + name);
    input.setSize(getSize());
    input.setDisabled(isDisabled());

    if (isPicker()) {
      input.setClass("suggested");
      String path = "";
      XWiki xwiki = context.getWiki();
      path = xwiki.getURL("Main.WebHome", "view", context);

      String classname = this.getObject().getName();
      String fieldname = this.getName();
      String secondCol = "-", firstCol = "-";

      String script =
          "\""
              + path
              + "?xpage=suggest&classname="
              + classname
              + "&fieldname="
              + fieldname
              + "&firCol="
              + firstCol
              + "&secCol="
              + secondCol
              + "&\"";
      String varname = "\"input\"";
      input.setOnFocus("new ajaxSuggest(this, {script:" + script + ", varname:" + varname + "} )");
    }

    buffer.append(input.toString());
  }
  /**
   * Check if class template document exists in this context and update. Create if not exists.
   *
   * @param context the XWiki context.
   * @throws XWikiException error when saving document.
   */
  protected void checkClassTemplateDocument(XWikiContext context) throws XWikiException {
    if (this.checkingClassTemplate) {
      return;
    }

    this.checkingClassTemplate = true;

    try {
      XWikiDocument doc;
      XWiki xwiki = context.getWiki();
      boolean needsUpdate = false;

      try {
        doc = xwiki.getDocument(getClassTemplateFullName(), context);
      } catch (Exception e) {
        doc = new XWikiDocument();
        doc.setSpace(getClassTemplateSpace());
        doc.setName(getClassTemplateName());
        needsUpdate = true;
      }

      if (doc.getObject(getClassFullName()) == null) {
        doc.createNewObject(getClassFullName(), context);

        needsUpdate = true;
      }

      if (doc.isNew()) {
        String content =
            getResourceDocumentContent(
                DOCUMENTCONTENT_TEMPLATE_PREFIX + getClassTemplateFullName() + DOCUMENTCONTENT_EXT);
        doc.setContent(content != null ? content : getClassTemplateDefaultContent());
        doc.setSyntax(Syntax.XWIKI_1_0);

        doc.setParent(getClassFullName());
      }

      needsUpdate |= updateClassTemplateDocument(doc);

      if (doc.isNew() || needsUpdate) {
        xwiki.saveDocument(doc, context);
      }
    } finally {
      this.checkingClassTemplate = false;
    }
  }
  @Override
  public boolean action(XWikiContext context) throws XWikiException {
    XWiki xwiki = context.getWiki();
    XWikiResponse response = context.getResponse();
    XWikiDocument doc = context.getDoc();
    XWikiRequest request = context.getRequest();

    String className = request.getParameter("classname");
    String objectNumber = request.getParameter("object");

    if (className != null && objectNumber != null) {
      try {
        BaseObject object = doc.getObject(className, Integer.valueOf(objectNumber));
        synchronizeObject(object, context);
      } catch (Exception ex) {
        // Wrong parameters, non-existing object
        return true;
      }
    } else {
      for (List<BaseObject> classObjects : doc.getXObjects().values()) {
        for (BaseObject object : classObjects) {
          synchronizeObject(object, context);
        }
      }
    }

    // Set the new author
    doc.setAuthorReference(context.getUserReference());

    xwiki.saveDocument(
        doc,
        localizePlainOrKey("core.model.xobject.synchronizeObjects.versionSummary"),
        true,
        context);

    if (Utils.isAjaxRequest(context)) {
      response.setStatus(HttpServletResponse.SC_NO_CONTENT);
      response.setContentLength(0);
    } else {
      // forward to edit
      String redirect = Utils.getRedirect("edit", "editor=object", context);
      sendRedirect(response, redirect);
    }
    return false;
  }
  /**
   * Create a user if none exists.
   *
   * @param name the short name, must be scrubbed of chars which XWiki doesn't like.
   * @param fullName name, prefixed with 'XWiki.'.
   * @param context the ball of mud.
   * @throws XWikiException if thrown by {@link XWiki#createEmptyUser()}.
   */
  private void createUserIfNeeded(
      final String name, final String fullName, final XWikiContext context) throws XWikiException {
    final String database = context.getDatabase();
    try {
      // Switch to main wiki to force users to be global users
      context.setDatabase(context.getMainXWiki());

      final XWiki wiki = context.getWiki();

      // test if user already exists
      if (!wiki.exists(fullName, context)) {
        LOGGER.info("Need to create user [{0}]", fullName);
        wiki.createEmptyUser(name, "edit", context);
      }
    } finally {
      context.setDatabase(database);
    }
  }
  public void init(XWikiContext context) throws XWikiException, IOException {
    // first check versions
    XWikiDocument doc = xwiki.getDocument(docFullName, context);
    String xwikiVersion = doc.getVersion();

    String fn = "fullname:" + docFullName;
    String solrRev = useBackEnd ? currikiPlugin.solrGetSingleValue(fn, "revisionNumber") : "";
    if (useBackEnd && xwikiVersion.equals(solrRev)) {
      isBackEndStream = true;
      get = currikiPlugin.solrCreateQueryGetMethod(fn, solrField, 0, 100);
      currikiPlugin.solrCollectResultsFromQuery(
          "fullname:" + docFullName,
          "childRights,childPages",
          0,
          1,
          new CurrikiPlugin.SolrResultCollector() {
            public void status(int statusCode, int qTime, int numFound, int start) {}

            public void newDocument() {}

            public void addValue(String name, String value) {
              if ("childRights".equals(name)) childRightsS = value;
              else if ("childPages".equals(name)) childPagesS = value;
            }
          });
    } else {
      isBackEndStream = false;
      // identify docs to queries
      if (type == Type.USER_COLLECTIONS) {
        propNameForFullname = "collectionPage";
        subAssetNames = currikiPlugin.fetchCollectionsList(docFullName, context);
        objectToOutput = currikiPlugin.fetchCollectionsInfo(docFullName, context);
      } else if (type == Type.GROUP_COLLECTIONS) {
        propNameForFullname = "collectionPage";
        String groupName = docFullName.replace(".WebPreferences", "");
        subAssetNames = currikiPlugin.fetchCollectionsList(groupName, context);
        objectToOutput = currikiPlugin.fetchCollectionsInfo(groupName, context);
      } else if (type == Type.USER_GROUPS) {
        propNameForFullname = "groupSpace";
        subAssetNames = null;
        objectToOutput = currikiPlugin.fetchUserGroups(docFullName, context);
      } else if (type == Type.COLLECTION_CONTENT) {
        propNameForFullname = "assetpage";

        FolderCompositeAsset fca =
            (FolderCompositeAsset)
                currikiPlugin.fetchAssetAs(docFullName, FolderCompositeAsset.class, context);
        if (fca != null) {
          FolderCompositeAsset fAsset = fca.as(FolderCompositeAsset.class);
          objectToOutput = fAsset.getSubassetsInfo();
        } else objectToOutput = new LinkedList();
      } else {
        throw new UnsupportedEncodingException();
      }
    }
  }
  /**
   * Verify that if there's no configuration document in the current wiki then we'll look into the
   * main wiki.
   */
  @Test
  public void getConfigurationDocumentWhenLocatedInMainWiki() throws Exception {
    when(this.configDoc.isNew()).thenReturn(true);
    XWikiDocument mainConfigDoc = mock(XWikiDocument.class);
    when(xwiki.getDocument(
            new DocumentReference("xwiki", "IRC", "IRCConfiguration"), this.xwikiContext))
        .thenReturn(mainConfigDoc);

    Assert.assertSame(
        mainConfigDoc, this.componentManager.getComponentUnderTest().getConfigurationDocument());
  }
  private void deleteOldWorkspaceObject(BaseObject oldObject, XWikiDocument oldWikiDescriptor)
      throws DataMigrationException {
    // Context, XWiki
    XWikiContext context = getXWikiContext();
    XWiki xwiki = context.getWiki();

    // Delete the old object
    oldWikiDescriptor.removeXObject(oldObject);

    // Save the document
    try {
      xwiki.saveDocument(
          oldWikiDescriptor, "Remove the old WorkspaceManager.WorkspaceClass object.", context);
    } catch (XWikiException e) {
      throw new DataMigrationException(
          String.format(
              "Failed to save the document [%s] to remove the WorkspaceManager.WorkspaceClass object.",
              oldWikiDescriptor.getDocumentReference().toString()),
          e);
    }
  }
 @Override
 public Object doInHibernate(Session session) throws HibernateException, XWikiException {
   XWikiContext context = getXWikiContext();
   XWiki xwiki = context.getWiki();
   DocumentReference oldClassReference =
       new DocumentReference(context.getWikiId(), "ClinicalInformationCode", this.className);
   DocumentReference newClassReference =
       new DocumentReference(context.getWikiId(), Constants.CODE_SPACE, this.className);
   Query q =
       session.createQuery(
           "select distinct o.name from BaseObject o where o.className = '"
               + R45391PhenoTips434DataMigration.this.serializer.serialize(oldClassReference)
               + "'");
   @SuppressWarnings("unchecked")
   List<String> documents = q.list();
   for (String docName : documents) {
     XWikiDocument doc =
         xwiki.getDocument(
             R45391PhenoTips434DataMigration.this.resolver.resolve(docName), context);
     for (BaseObject oldObject : doc.getXObjects(oldClassReference)) {
       BaseObject newObject = oldObject.duplicate();
       newObject.setXClassReference(newClassReference);
       doc.addXObject(newObject);
     }
     doc.removeXObjects(oldClassReference);
     doc.setComment("Migrated patient data in class " + this.className);
     doc.setMinorEdit(true);
     try {
       // There's a bug in XWiki which prevents saving an object in the same session that it was
       // loaded,
       // so we must clear the session cache first.
       session.clear();
       ((XWikiHibernateStore) getStore()).saveXWikiDoc(doc, context, false);
       session.flush();
     } catch (DataMigrationException e) {
       // We're in the middle of a migration, we're not expecting another migration
     }
   }
   return null;
 }
 private XWikiDocument addDocument(String documentName, String author, Date date, int vote)
     throws RatingsException {
   try {
     String ratingsClassName = RatingsManager.RATINGS_CLASSNAME;
     String pageName = getPageName(documentName);
     String parentDocName = documentName;
     XWiki xwiki = context.getWiki();
     XWikiDocument doc = xwiki.getDocument(pageName, context);
     doc.setParent(parentDocName);
     BaseObject obj = new BaseObject();
     obj.setClassName(ratingsClassName);
     obj.setName(pageName);
     obj.setStringValue(RatingsManager.RATING_CLASS_FIELDNAME_AUTHOR, author);
     obj.setDateValue(RatingsManager.RATING_CLASS_FIELDNAME_DATE, date);
     obj.setIntValue(RatingsManager.RATING_CLASS_FIELDNAME_VOTE, vote);
     obj.setStringValue(RatingsManager.RATING_CLASS_FIELDNAME_PARENT, parentDocName);
     doc.addObject(ratingsClassName, obj);
     return doc;
   } catch (XWikiException e) {
     throw new RatingsException(e);
   }
 }
 @Test
 public void testGetConfigDocFieldInheritor_fullnames() throws Exception {
   PageLayoutCommand mockPageLayoutCmd = createMock(PageLayoutCommand.class);
   _factory.injectPageLayoutCmd(mockPageLayoutCmd);
   String className = "mySpace.myClassName";
   String fullName = "mySpace.myDocName";
   List<String> docList = new ArrayList<String>();
   docList.add("mySpace.WebPreferences");
   docList.add("XWiki.XWikiPreferences");
   DocumentReference webHomeDocRef =
       new DocumentReference(_context.getDatabase(), "mySpace", "WebHome");
   expect(_xwiki.exists(eq(webHomeDocRef), same(_context))).andReturn(false).anyTimes();
   expect(mockPageLayoutCmd.getPageLayoutForDoc(eq(fullName), same(_context))).andReturn(null);
   expect(_xwiki.getSpacePreference(eq("skin"), same(_context))).andReturn(null);
   replayAll(mockPageLayoutCmd);
   FieldInheritor fieldInheritor =
       _factory.getConfigDocFieldInheritor(className, fullName, _context);
   XObjectIterator iterator = fieldInheritor.getIteratorFactory().createIterator();
   verifyAll(mockPageLayoutCmd);
   assertEquals(className, iterator.getClassName());
   assertEquals(docList, iterator.getDocListCopy());
 }
  /**
   * Check if class document exists in this context and update. Create if not exists.
   *
   * @param context the XWiki context.
   * @throws XWikiException error when saving document.
   */
  protected void checkClassDocument(XWikiContext context) throws XWikiException {
    if (this.checkingClass) {
      return;
    }

    this.checkingClass = true;

    try {
      XWikiDocument doc;
      XWiki xwiki = context.getWiki();
      boolean needsUpdate = false;

      try {
        doc = xwiki.getDocument(getClassFullName(), context);
      } catch (Exception e) {
        doc = new XWikiDocument();
        doc.setSpace(getClassSpace());
        doc.setName(getClassName());
        doc.setCreator(XWikiRightService.SUPERADMIN_USER);
        doc.setAuthor(doc.getCreator());
        needsUpdate = true;
      }

      if (doc.isNew()) {
        doc.setParent(DEFAULT_XWIKICLASS_PARENT);
      }

      this.baseClass = doc.getXClass();

      needsUpdate |= updateBaseClass(this.baseClass);

      if (doc.isNew() || needsUpdate) {
        xwiki.saveDocument(doc, context);
      }
    } finally {
      this.checkingClass = false;
    }
  }
  public CTVRepresentation(String targetDocument, Type type, XWikiContext context)
      throws IOException, XWikiException {
    super(jsonMediaType);
    this.xwiki = context.getWiki();
    this.userGroups = new TreeSet<String>();
    for (Object groupName :
        ((CurrikiSpaceManager) xwiki.getPlugin("csm", context))
            .getSpaceNames(context.getUser(), null, context)) {
      userGroups.add(((String) groupName).substring("Group_".length()));
    }
    this.type = type;
    this.userName = context.getUser();
    if (userName.startsWith("XWiki.")) userName = userName.substring("XWiki.".length());
    this.userIsAdmin =
        xwiki.checkAccess("admin", xwiki.getDocument("XWiki.XWikiPreferences", context), context);
    this.docFullName = targetDocument;
    this.currikiPlugin = (CurrikiPlugin) xwiki.getPlugin("curriki", context);

    if (!currikiPlugin.solrCheckIsUp()) useBackEnd = false;

    // identify docs to queries
    if (type == Type.USER_COLLECTIONS) {
      solrField = "userCollections";
      propNameForFullname = "collectionPage";
    } else if (type == Type.USER_GROUPS) {
      solrField = "userGroups";
      propNameForFullname = "groupSpace";
    } else if (type == Type.GROUP_COLLECTIONS) {
      solrField = "childInfo";
      propNameForFullname = "collectionPage";
    } else if (type == Type.COLLECTION_CONTENT) {
      solrField = "childInfo";
      propNameForFullname = "assetpage";
    } else {
      throw new UnsupportedEncodingException();
    }
  }
  /**
   * Check if class sheet document exists in this context and update. Create if not exists.
   *
   * @param context the XWiki context.
   * @throws XWikiException error when saving document.
   */
  protected void checkClassSheetDocument(XWikiContext context) throws XWikiException {
    if (this.checkingClassSheet) {
      return;
    }

    this.checkingClassSheet = true;

    try {
      XWikiDocument doc;
      XWiki xwiki = context.getWiki();
      boolean needsUpdate = false;

      try {
        doc = xwiki.getDocument(getClassSheetFullName(), context);
      } catch (Exception e) {
        doc = new XWikiDocument();
        doc.setSpace(getClassSheetSpace());
        doc.setName(getClassSheetName());
        needsUpdate = true;
      }

      if (doc.isNew()) {
        String documentContentPath =
            DOCUMENTCONTENT_SHEET_PREFIX + getClassSheetFullName() + DOCUMENTCONTENT_EXT;
        String content = getResourceDocumentContent(documentContentPath);
        doc.setContent(content != null ? content : getClassSheetDefaultContent());
        doc.setSyntax(Syntax.XWIKI_1_0);
        doc.setParent(getClassFullName());
      }

      if (doc.isNew() || needsUpdate) {
        xwiki.saveDocument(doc, context);
      }
    } finally {
      this.checkingClassSheet = false;
    }
  }
  public void testSwitchOrderOfRenderers() throws Exception {
    String text = "#set($x = '<' + '% println(\"hello world\"); %' + '>')\n$x";
    String velocityFirst = "hello world";
    String groovyFirst = "<% println(\"hello world\"); %>";

    XWikiDocument document = new XWikiDocument();

    // Prove that the renderers are in the right order by default.
    assertEquals(
        engine.getRendererNames(),
        new ArrayList<String>() {
          {
            add("mapping");
            add("groovy");
            add("velocity");
            add("plugin");
            add("wiki");
            add("xwiki");
          }
        });

    assertEquals(groovyFirst, engine.renderText(text, document, getContext()));

    xwiki
        .getConfig()
        .put(
            "xwiki.render.renderingorder",
            "macromapping, velocity, groovy, plugin, wiki, wikiwiki");

    DefaultXWikiRenderingEngine myEngine = new DefaultXWikiRenderingEngine(xwiki, getContext());

    assertEquals(
        myEngine.getRendererNames(),
        new ArrayList<String>() {
          {
            add("mapping");
            add("velocity");
            add("groovy");
            add("plugin");
            add("wiki");
            add("xwiki");
          }
        });

    assertEquals(velocityFirst, myEngine.renderText(text, document, getContext()));
  }