@Override
  public void save(Patient patient) {
    try {
      XWikiDocument doc =
          (XWikiDocument) this.documentAccessBridge.getDocument(patient.getDocument());
      BaseObject xwikiDataObject = doc.getXObject(Patient.CLASS_REFERENCE);
      if (xwikiDataObject == null) {
        throw new IllegalArgumentException(ERROR_MESSAGE_NO_PATIENT_CLASS);
      }

      PatientData<String> data = patient.<String>getData(this.getName());
      if (!data.isNamed()) {
        return;
      }
      for (String property : this.getProperties()) {
        xwikiDataObject.setStringValue(property, data.get(property));
      }

      XWikiContext context = this.contextProvider.get();
      String comment = String.format("Updated %s from JSON", this.getName());
      context.getWiki().saveDocument(doc, comment, true, context);
    } catch (Exception e) {
      this.logger.error("Failed to save {}: [{}]", this.getName(), e.getMessage());
    }
  }
 /**
  * Creates a new sub-wiki with the given name.
  *
  * @param wikiName the wiki name
  * @throws Exception if creating the wiki fails
  */
 private void createWiki(String wikiName) throws Exception {
   String wikiDocName =
       "XWikiServer" + wikiName.substring(0, 1).toUpperCase() + wikiName.substring(1);
   XWikiDocument wikiDoc =
       getDocument(new DocumentReference(MAIN_WIKI_NAME, "XWiki", wikiDocName));
   BaseObject wikiObj = wikiDoc.newObject("XWiki.XWikiServerClass", getContext());
   wikiObj.setStringValue("server", wikiName + "server");
   saveDocument(wikiDoc);
 }
 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);
   }
 }
  private void setBundles(String bundles) throws XWikiException {
    XWikiDocument preferencesDocument =
        this.oldcore
            .getMockXWiki()
            .getDocument(this.preferencesDocumentReference, this.oldcore.getXWikiContext());
    BaseObject preferencesObject = preferencesDocument.getXObject();

    if (!bundles.equals(preferencesObject.getStringValue("documentBundles"))) {
      preferencesObject.setStringValue("documentBundles", bundles);

      this.oldcore
          .getMockXWiki()
          .saveDocument(preferencesDocument, "", this.oldcore.getXWikiContext());
    }
  }
 /**
  * Loops over the {@code rightsCombinations} and attaches a new rights object for each combination
  * to the document.
  *
  * @param rightsCombinations the string array containing all the combinations for which there
  *     should be an object created
  * @param rightsObjects the map of existing rights objects
  * @param doc XWikiDocument
  * @param context XWikiContext
  */
 private void createRights(
     List<String> rightsCombinations,
     Map<String, BaseObject> rightsObjects,
     XWikiDocument doc,
     XWikiContext context) {
   for (String rights : rightsCombinations) {
     try {
       BaseObject newRightObject = doc.newXObject(RIGHTS_CLASS, context);
       newRightObject.setStringValue("levels", rights);
       newRightObject.setIntValue("allow", 1);
       rightsObjects.put(rights, newRightObject);
     } catch (XWikiException ex) {
       this.logger.error("Failed to create rights: {}", ex.getMessage(), ex);
     }
   }
 }
 private BaseObject getBaseObject2() {
   BaseObject bObj = new BaseObject();
   bObj.setStringValue(fields.get(0), "val");
   bObj.setStringValue(fields.get(1), "val2");
   return bObj;
 }
  /**
   * Convert the old WorkspaceManager.WorkspaceCandidateMemberClass objects to the new candidacies
   * format.
   *
   * @param wikiId id of the wiki to upgrade
   * @throws XWikiException if problems occur
   */
  private void upgradeWorkspaceCandidacies(String wikiId) throws XWikiException {
    XWikiContext xcontext = getXWikiContext();
    XWiki xwiki = xcontext.getWiki();

    // We need to get the document that holds the candidacies
    DocumentReference candidaciesDocumentReference =
        new DocumentReference(wikiId, XWiki.SYSTEM_SPACE, "XWikiAllGroup");
    XWikiDocument candidaciesDocument = xwiki.getDocument(candidaciesDocumentReference, xcontext);

    // We need to get all the old candidacies
    DocumentReference oldCandidateClassReference =
        new DocumentReference(wikiId, XWiki.SYSTEM_SPACE, "WorkspaceCandidateMemberClass");
    List<BaseObject> candidacyObjects = candidaciesDocument.getXObjects(oldCandidateClassReference);
    if (candidacyObjects != null) {
      DocumentReference newCandidateClassReference =
          new DocumentReference(
              wikiId,
              WikiCandidateMemberClassInitializer.DOCUMENT_SPACE,
              WikiCandidateMemberClassInitializer.DOCUMENT_NAME);

      for (BaseObject oldObject : candidacyObjects) {
        if (oldObject == null) {
          continue;
        }
        // Transform the candidacy to the new class
        BaseObject newObject = candidaciesDocument.newXObject(newCandidateClassReference, xcontext);
        newObject.setStringValue(
            WikiCandidateMemberClassInitializer.FIELD_TYPE, oldObject.getStringValue("type"));
        newObject.setStringValue(
            WikiCandidateMemberClassInitializer.FIELD_STATUS, oldObject.getStringValue("status"));
        newObject.setStringValue(
            WikiCandidateMemberClassInitializer.FIELD_USER, oldObject.getStringValue("userName"));
        newObject.setLargeStringValue(
            WikiCandidateMemberClassInitializer.FIELD_USER_COMMENT,
            oldObject.getLargeStringValue("userComment"));
        newObject.setStringValue(
            WikiCandidateMemberClassInitializer.FIELD_ADMIN, oldObject.getStringValue("reviewer"));
        newObject.setLargeStringValue(
            WikiCandidateMemberClassInitializer.FIELD_ADMIN_COMMENT,
            oldObject.getLargeStringValue("reviewerComment"));
        newObject.setLargeStringValue(
            WikiCandidateMemberClassInitializer.FIELD_ADMIN_PRIVATE_COMMENT,
            oldObject.getLargeStringValue("reviewerPrivateComment"));
        newObject.setDateValue(
            WikiCandidateMemberClassInitializer.FIELD_DATE_OF_CREATION,
            oldObject.getDateValue("date"));
        newObject.setDateValue(
            WikiCandidateMemberClassInitializer.FIELD_DATE_OF_CLOSURE,
            oldObject.getDateValue("resolutionDate"));

        // Remove the old object
        candidaciesDocument.removeXObject(oldObject);
      }

      // Save
      xwiki.saveDocument(
          candidaciesDocument,
          "Upgrade candidacies from the old Workspace Application to the "
              + "new Wiki Application.",
          xcontext);
    }
  }
  /**
   * Install an application in the given space, by copying or linking documents. Read the list of
   * documents to include (link) and copy from the {@link ApplicationManagerPlugin} and save their
   * content locally in a wiki space (web) composed of the space wiki name and the application name.
   * Also make the application web inherits its rights from the space root space (web).
   *
   * @param appName the name of the application to install
   * @param spaceName the wiki name of the space to install the application in
   * @throws SpaceManagerException
   */
  public void installApplicationInSpace(String appName, String spaceName, XWikiContext context)
      throws WorkspacesManagerException {
    // TODO Note that this method makes a deviant usage of the application
    // manager plugin and XWiki application objects.
    // It uses the application field docsToInclude and documents
    // to make a local installation (as opposed as cross-wiki global
    // installation, which the application manager is initially designed
    // for).
    // In the future, the application manager should be able to
    // handle local installation/local copy parameters, and the
    // SpaceManagerPlugin implements a method to install a space
    // from an application or application list.

    // get the application manager api

    try {
      // Retrieve the application descriptor
      XWikiApplication app = getXWikiApplicationManagerApi(context).getApplicationDocument(appName);

      if (app == null)
        throw new WorkspacesManagerException(
            WorkspacesManagerException.MODULE_PLUGIN_XWS,
            WorkspacesManagerException.ERROR_XWSMGR_APPNOTFOUND_ON_INSTALL,
            "Could not find application descriptor when trying to install application ["
                + appName
                + "]"
                + "in space ["
                + spaceName
                + "]");

      ApplicationManagerExtension ext = getApplicationManagerExtension(app, context);

      String appSpace = spaceName + XWIKI_WORKSPACE_APPSEPARATOR + app.getAppName();

      // execute, if needed pre install operations
      if (ext != null) {
        ext.preInstall(appSpace, context);
      }

      // Retrieve the application document list
      Set<String> appDocs = app.getDocumentsNames(false, false);

      // Retrieve the application documents to include
      Set<String> docsToInclude = app.getDocsNameToInclude(true);

      for (String docFullName : appDocs) {
        // If the doc is not in the include list,
        // We copy it to the target space
        if (!docsToInclude.contains(docFullName)) {
          String docName = docFullName.substring(docFullName.indexOf('.') + 1);
          String targetDocName = appSpace + XWIKI_SPACE_SEPARATOR + docName;
          context.getWiki().copyDocument(docFullName, targetDocName, true, context);
        }
      }

      for (String docFullName : docsToInclude) {

        String docName = docFullName.substring(docFullName.indexOf('.') + 1);

        // Compute the target doc name based on application name, space
        // name and document
        // name
        // EX: Space_Wiki.WebHome for "Space" space name, "Wiki" appname
        // and "WebHome" doc
        String targetDocName = appSpace + XWIKI_SPACE_SEPARATOR + docName;
        XWikiDocument targetDoc = context.getWiki().getDocument(targetDocName, context);

        // Link the content with the application code
        targetDoc.setContent(
            MessageFormat.format(
                "#includeInContext(\"{0}\")", new java.lang.Object[] {docFullName}));

        // Save the document
        context.getWiki().saveDocument(targetDoc, context);
      }

      if (appDocs.size() > 0) {
        // if we've installed anything,
        // make the installed app inherit its right from the Workspace
        // root web
        XWikiDocument appPreferences =
            context
                .getWiki()
                .getDocument(appSpace + XWIKI_SPACE_SEPARATOR + "WebPreferences", context);
        BaseObject pObj = appPreferences.getObject("XWiki.XWikiPreferences", true, context);
        pObj.setStringValue("parent", spaceName);
        context.getWiki().saveDocument(appPreferences, context);
      }

      // execute, if needed post install operations
      if (ext != null) {
        ext.postInstall(appSpace, context);
      }

    } catch (XWikiException e) {
      throw new WorkspacesManagerException(e);
    }
  }