private void setRights(BaseObject rightsObject, String field, String value) {
   String currentValue = rightsObject.getStringValue(field);
   if (!StringUtils.isEmpty(currentValue)) {
     currentValue += ",";
   }
   rightsObject.setLargeStringValue(field, currentValue + value);
 }
  @Override
  public List<T> newXObjectDocumentList(List<XWikiDocument> documents, XWikiContext context)
      throws XWikiException {
    List<T> list;

    if (!documents.isEmpty()) {
      check(context);

      list = new ArrayList<T>(documents.size());

      for (XWikiDocument doc : documents) {
        List<BaseObject> objects = doc.getObjects(getClassFullName());

        for (BaseObject bobject : objects) {
          if (bobject != null) {
            list.add(newXObjectDocument(doc, bobject.getNumber(), context));
          }
        }
      }
    } else {
      list = Collections.emptyList();
    }

    return list;
  }
  private Map<AccessLevel, List<DocumentReference>> getCollaborators(XWikiDocument doc) {
    Map<AccessLevel, List<DocumentReference>> collaborators =
        new LinkedHashMap<AccessLevel, List<DocumentReference>>();
    List<BaseObject> collaboratorObjects = doc.getXObjects(Collaborator.CLASS_REFERENCE);
    if (collaboratorObjects == null || collaboratorObjects.isEmpty()) {
      return Collections.emptyMap();
    }
    for (BaseObject collaborator : collaboratorObjects) {
      if (collaborator == null) {
        continue;
      }
      String collaboratorName = collaborator.getStringValue("collaborator");
      String accessName = collaborator.getStringValue("access");

      if (StringUtils.isBlank(collaboratorName) || StringUtils.isBlank(accessName)) {
        continue;
      }
      DocumentReference userOrGroup =
          this.stringEntityResolver.resolve(collaboratorName, doc.getDocumentReference());
      AccessLevel access = this.manager.resolveAccessLevel(accessName);
      List<DocumentReference> list = collaborators.get(access);
      if (list == null) {
        list = new LinkedList<DocumentReference>();
        collaborators.put(access, list);
      }
      list.add(userOrGroup);
    }
    return collaborators;
  }
  @Test
  public void getMembersWhenSingleUserButBothUserAndGroupReference() throws Exception {
    setUpBaseMocks();
    DocumentReference reference = new DocumentReference("wiki", "XWiki", "page");

    XWikiDocument document = mock(XWikiDocument.class);
    when(document.isNew()).thenReturn(false);
    when(document.getDocumentReference()).thenReturn(reference);
    when(this.xwiki.getDocument(reference, this.xwikiContext)).thenReturn(document);

    // It's a user reference
    BaseObject bo1 = mock(BaseObject.class);
    when(document.getXObject(new DocumentReference("wiki", "XWiki", "XWikiUsers"))).thenReturn(bo1);

    // It's also a group reference (with one user in it)
    List<BaseObject> memberObjects = new ArrayList<>();
    BaseObject bo2 = mock(BaseObject.class);
    when(bo2.getStringValue("member")).thenReturn("XWiki.user");
    memberObjects.add(bo2);
    when(document.getXObjects(new DocumentReference("wiki", "XWiki", "XWikiGroups")))
        .thenReturn(memberObjects);
    DocumentReference userReference = new DocumentReference("wiki", "XWiki", "user");
    when(this.resolver.resolve("XWiki.user", reference)).thenReturn(userReference);
    setUpUserPageMocks(userReference);

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

    assertTrue(iterator.hasNext());
    assertEquals(new DocumentReference("wiki", "XWiki", "page"), iterator.next());
    assertTrue(iterator.hasNext());
    assertEquals(new DocumentReference("wiki", "XWiki", "user"), iterator.next());
    assertFalse(iterator.hasNext());
  }
Esempio n. 5
0
  /**
   * Check if the password passed as argument is the user password. This method is used when a user
   * wants to change its password. To make sure that it wouldn't be used to perform brute force
   * attacks, we ensure that this is only used to check the current user password on its profile
   * page.
   *
   * @param password Password submitted.
   * @return true if password is really the user password.
   * @throws XWikiException error if authorization denied.
   */
  public boolean checkPassword(String password) throws XWikiException {
    EntityReference userReference = REFERENCE_RESOLVER.resolve(this.user.getUser());
    EntityReference docReference = getXWikiContext().getDoc().getDocumentReference();
    if (userReference.equals(getXWikiContext().getUserReference())
        && userReference.equals(docReference)) {
      try {
        boolean result = false;

        XWikiDocument userDoc =
            getXWikiContext().getWiki().getDocument(userReference, getXWikiContext());
        BaseObject obj = userDoc.getXObject(USERCLASS_REFERENCE);
        // We only allow empty password from users having a XWikiUsers object.
        if (obj != null) {
          final String stored = obj.getStringValue("password");
          result = new PasswordClass().getEquivalentPassword(stored, password).equals(stored);
        }

        return result;
      } catch (Throwable e) {
        LOGGER.error("Failed to check password", e);
        return false;
      }
    } else {
      throw new XWikiException(
          XWikiException.MODULE_XWIKI_ACCESS,
          XWikiException.ERROR_XWIKI_ACCESS_DENIED,
          "You cannot use this method for checking another user password.",
          null);
    }
  }
  @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());
    }
  }
 @Override
 public PatientData<String> load(Patient patient) {
   try {
     XWikiDocument doc =
         (XWikiDocument) this.documentAccessBridge.getDocument(patient.getDocument());
     BaseObject data = doc.getXObject(Patient.CLASS_REFERENCE);
     if (data == null) {
       return null;
     }
     Map<String, String> result = new LinkedHashMap<>();
     for (String propertyName : getProperties()) {
       String value = data.getStringValue(propertyName);
       if (StringUtils.isNotBlank(value)) {
         result.put(propertyName, value);
       }
     }
     return new DictionaryPatientData<>(getName(), result);
   } catch (Exception e) {
     this.logger.error(
         "Could not find requested document or some unforeseen"
             + " error has occurred during controller loading ",
         e.getMessage());
   }
   return null;
 }
  @Override
  public SolrInputDocument getSolrDocument(EntityReference entityReference)
      throws SolrIndexException, IllegalArgumentException {
    BaseObjectReference objectReference = new BaseObjectReference(entityReference);

    try {
      SolrInputDocument solrDocument = new SolrInputDocument();

      DocumentReference classReference = objectReference.getXClassReference();
      DocumentReference documentReference = new DocumentReference(objectReference.getParent());
      XWikiDocument document = getDocument(documentReference);

      BaseObject object = document.getXObject(objectReference);

      solrDocument.addField(Fields.ID, getId(object.getReference()));
      addDocumentFields(documentReference, solrDocument);
      solrDocument.addField(Fields.TYPE, objectReference.getType().name());
      solrDocument.addField(Fields.CLASS, localSerializer.serialize(classReference));

      addLanguageAndContentFields(documentReference, solrDocument, object);

      return solrDocument;
    } catch (Exception e) {
      throw new SolrIndexException(
          String.format(
              "Failed to get Solr document for '%s'", serializer.serialize(objectReference)),
          e);
    }
  }
Esempio n. 9
0
  /**
   * Send redirection based on a regexp pattern (if any) set at the main wiki level. To enable this
   * feature you must add xwiki.preferences.redirect=1 to your xwiki.cfg.
   *
   * @param response the servlet response
   * @param url url of the request
   * @param context the XWiki context
   * @return true if a redirection has been sent
   */
  protected boolean sendGlobalRedirect(XWikiResponse response, String url, XWikiContext context)
      throws Exception {
    if ("1".equals(context.getWiki().Param("xwiki.preferences.redirect"))) {
      // Note: This implementation is not performant at all and will slow down the wiki as the
      // number
      // of redirects increases. A better implementation would use a cache of redirects and would
      // use
      // the notification mechanism to update the cache when the XWiki.XWikiPreferences document is
      // modified.
      XWikiDocument globalPreferences =
          context.getWiki().getDocument("xwiki:XWiki.XWikiPreferences", context);
      Vector<BaseObject> redirects = globalPreferences.getObjects("XWiki.GlobalRedirect");

      if (redirects != null) {
        for (BaseObject redir : redirects) {
          if (redir != null) {
            String p = redir.getStringValue("pattern");
            if (p != null && url.matches(p)) {
              String dest = redir.getStringValue("destination");
              response.sendRedirect(url.replaceAll(p, dest));
              return true;
            }
          }
        }
      }
    }
    return false;
  }
 private Visibility getVisibility(XWikiDocument doc) {
   String visibility = null;
   BaseObject visibilityObj = doc.getXObject(Visibility.CLASS_REFERENCE);
   if (visibilityObj != null) {
     visibility = visibilityObj.getStringValue("visibility");
   }
   return this.manager.resolveVisibility(StringUtils.defaultIfBlank(visibility, "private"));
 }
Esempio n. 11
0
  /** @deprecated since 2.2.3 use {@link com.xpn.xwiki.doc.XWikiDocument#newXObject} */
  @Deprecated
  public BaseCollection newObject(XWikiContext context) throws XWikiException {
    BaseObject bobj = newCustomClassInstance(context);
    DocumentReference classReference = getDocumentReference();
    bobj.setXClassReference(classReference.removeParent(classReference.getWikiReference()));

    return bobj;
  }
  @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));
  }
 /**
  * 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 DocumentReference getOwner(XWikiDocument doc) {
   String owner = null;
   BaseObject ownerObj = doc.getXObject(Owner.CLASS_REFERENCE);
   if (ownerObj != null) {
     owner = ownerObj.getStringValue("owner");
   }
   if (StringUtils.isNotBlank(owner)) {
     return this.stringEntityResolver.resolve(owner);
   } else if (doc.getCreatorReference() != null) {
     return doc.getCreatorReference();
   }
   return null;
 }
Esempio n. 15
0
 /**
  * API to retrieve the e-mail address of this user. This e-mail address is taken from the user
  * profile. If the user hasn't changed his profile, then this is the e-mail address he filled in
  * the registration form.
  *
  * @return The e-mail address from the user profile, or <tt>null</tt> if there is an error
  *     retrieving the email.
  * @since 1.1.3
  * @since 1.2.2
  * @since 1.3M2
  */
 public String getEmail() {
   XWikiDocument userDoc;
   try {
     userDoc = getXWikiContext().getWiki().getDocument(this.user.getUser(), getXWikiContext());
     BaseObject obj = userDoc.getObject("XWiki.XWikiUsers");
     return obj.getStringValue("email");
   } catch (Exception e) {
     // APIs should never throw errors, as velocity cannot catch them, and scripts should be
     // as robust as possible. Instead, the code using this should know that null means there
     // was an error, if it really needs to report these exceptions.
     return null;
   }
 }
Esempio n. 16
0
  /**
   * {@inheritDoc} <br>
   * This implementation deletes the annotation object with the object number indicated by {@code
   * annotationID} from the document indicated by {@code target}, if its stored target matches the
   * passed target.
   *
   * @see org.xwiki.annotation.io.IOService#removeAnnotation(String, String)
   */
  @Override
  public void removeAnnotation(String target, String annotationID) throws IOServiceException {
    try {
      if (annotationID == null || target == null) {
        return;
      }

      EntityReference targetReference = referenceResolver.resolve(target, EntityType.DOCUMENT);
      // get the target identifier and the document name from the parsed reference
      String localTargetId = target;
      String docName = target;
      if (targetReference.getType() == EntityType.DOCUMENT
          || targetReference.getType() == EntityType.OBJECT_PROPERTY) {
        localTargetId = localSerializer.serialize(targetReference);
        docName = serializer.serialize(targetReference.extractReference(EntityType.DOCUMENT));
      }
      // get the document
      XWikiContext deprecatedContext = getXWikiContext();
      XWikiDocument document = deprecatedContext.getWiki().getDocument(docName, deprecatedContext);
      if (document.isNew()) {
        // if the document doesn't exist already skip it
        return;
      }
      // and the document object on it
      BaseObject annotationObject =
          document.getXObject(
              configuration.getAnnotationClassReference(),
              Integer.valueOf(annotationID.toString()));

      // if object exists and its target matches the requested target, delete it
      if (annotationObject != null
          && localTargetId.equals(annotationObject.getStringValue(Annotation.TARGET_FIELD))) {
        document.removeObject(annotationObject);
        document.setAuthor(deprecatedContext.getUser());
        deprecatedContext
            .getWiki()
            .saveDocument(document, "Deleted annotation " + annotationID, deprecatedContext);
        // notify listeners that an annotation was deleted
        ObservationManager observationManager = componentManager.lookup(ObservationManager.class);
        observationManager.notify(
            new AnnotationDeletedEvent(docName, annotationID), document, deprecatedContext);
      }
    } catch (NumberFormatException e) {
      throw new IOServiceException("An exception has occurred while parsing the annotation id", e);
    } catch (XWikiException e) {
      throw new IOServiceException("An exception has occurred while removing the annotation", e);
    } catch (ComponentLookupException exc) {
      this.logger.warn(
          "Could not get the observation manager to send notifications about the annotation delete");
    }
  }
  public static ObjectSummary createObjectSummary(
      ObjectFactory objectFactory,
      URI baseUri,
      XWikiContext xwikiContext,
      Document doc,
      BaseObject xwikiObject,
      boolean useVersion,
      XWiki xwikiApi,
      Boolean withPrettyNames)
      throws XWikiException {
    ObjectSummary objectSummary = objectFactory.createObjectSummary();
    fillObjectSummary(
        objectSummary, objectFactory, baseUri, doc, xwikiObject, xwikiApi, withPrettyNames);

    Link objectLink =
        getObjectLink(objectFactory, baseUri, doc, xwikiObject, useVersion, Relations.OBJECT);
    objectSummary.getLinks().add(objectLink);

    String propertiesUri;

    if (useVersion) {
      propertiesUri =
          uri(
              baseUri,
              ObjectPropertiesAtPageVersionResource.class,
              doc.getWiki(),
              doc.getSpace(),
              doc.getName(),
              doc.getVersion(),
              xwikiObject.getClassName(),
              xwikiObject.getNumber());
    } else {
      propertiesUri =
          uri(
              baseUri,
              ObjectPropertiesResource.class,
              doc.getWiki(),
              doc.getSpace(),
              doc.getName(),
              xwikiObject.getClassName(),
              xwikiObject.getNumber());
    }

    Link propertyLink = objectFactory.createLink();
    propertyLink.setHref(propertiesUri);
    propertyLink.setRel(Relations.PROPERTIES);
    objectSummary.getLinks().add(propertyLink);

    return objectSummary;
  }
  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());
    }
  }
Esempio n. 19
0
  /**
   * Retrieves deprecated properties of the given object compared to the class. A deprecated
   * property is a property which exists in the Object but doesn't exist anymore in the Class, or
   * which has the wrong data type. This is used for synchronization of existing or imported Objects
   * with respect to the modifications of their associated Class.
   *
   * @param object the instance of this class where to look for undefined properties
   * @return an unmodifiable list containing the properties of the object which don't exist in the
   *     class
   * @since 2.4M2
   */
  public List<BaseProperty> getDeprecatedObjectProperties(BaseObject object) {
    @SuppressWarnings("unchecked")
    Collection<BaseProperty> objectProperties = object.getFieldList();
    if (objectProperties == null) {
      return Collections.emptyList();
    }

    List<BaseProperty> deprecatedObjectProperties = new ArrayList<BaseProperty>();

    for (BaseProperty property : objectProperties) {
      if (safeget(property.getName()) == null) {
        deprecatedObjectProperties.add(property);
      } else {
        String propertyClass =
            ((PropertyClass) safeget(property.getName())).newProperty().getClassType();
        String objectPropertyClass = property.getClassType();

        if (!propertyClass.equals(objectPropertyClass)) {
          deprecatedObjectProperties.add(property);
        }
      }
    }

    return Collections.unmodifiableList(deprecatedObjectProperties);
  }
  /**
   * Convert the old WorkspaceManager.WorkspaceClass objects to the new configuration format.
   *
   * @param oldObject old workspace object
   * @param wikiId id of the wiki to upgrade
   * @param oldWikiDescriptor document that holds the old object
   * @throws DataMigrationException if problems occur
   * @throws XWikiException if problems occur
   */
  private void upgradeWorkspaceConfiguration(
      BaseObject oldObject, String wikiId, XWikiDocument oldWikiDescriptor)
      throws DataMigrationException, XWikiException {
    // Context, XWiki
    XWikiContext context = getXWikiContext();
    XWiki xwiki = context.getWiki();

    // Create the new configuration
    WikiUserConfiguration configuration = new WikiUserConfiguration();

    // No local users
    configuration.setUserScope(UserScope.GLOBAL_ONLY);

    // Set the membershipType value
    if (oldObject != null) {
      // Get the membershipType value
      String membershipTypeValue = oldObject.getStringValue("membershipType");
      MembershipType membershipType;
      try {
        membershipType = MembershipType.valueOf(membershipTypeValue.toUpperCase());
      } catch (Exception e) {
        // Default value
        membershipType = MembershipType.INVITE;
      }
      configuration.setMembershipType(membershipType);
    } else {
      // If there is no workspace object, we put a default value.
      configuration.setMembershipType(MembershipType.INVITE);
    }

    // Save the new configuration
    saveConfiguration(configuration, wikiId);
  }
 /**
  * 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);
     }
   }
 }
Esempio n. 22
0
 /**
  * Helper function to set a field on an object only if the new value is not null. If you wish to
  * reset the value of a field, pass the empty string for the new value.
  *
  * @param object the object to set the value of the field
  * @param fieldName the name of the field to set
  * @param newValue the new value to set to the field. It will be ignored if it's {@code null}
  * @param deprecatedContext the XWikiContext
  * @return {@code true} if the field was set to newValue, {@code false} otherwise
  */
 protected boolean setIfNotNull(
     BaseObject object, String fieldName, Object newValue, XWikiContext deprecatedContext) {
   if (newValue != null) {
     object.set(fieldName, newValue, deprecatedContext);
     return true;
   }
   return false;
 }
  /**
   * Adds the document comments using the multiValued field {@link Fields#COMMENT}.
   *
   * @param solrDocument the Solr document where to add the comments.
   * @param originalDocument the XWiki document from which to extract the comments.
   */
  protected void addComments(SolrInputDocument solrDocument, XWikiDocument originalDocument) {
    List<BaseObject> comments = originalDocument.getComments();
    if (comments == null) {
      return;
    }

    for (BaseObject comment : comments) {
      // Yes, objects can be null at this point...
      if (comment != null) {
        String commentString = comment.getStringValue("comment");
        String author = comment.getStringValue("author");
        Date date = comment.getDateValue("date");
        solrDocument.addField(
            Fields.COMMENT, String.format("%s by %s on %s", commentString, author, date));
      }
    }
  }
Esempio n. 24
0
  /**
   * Helper function to load an annotation object from an xwiki object.
   *
   * @param object the xwiki object to load an annotation from
   * @param deprecatedContext XWikiContext to make operations on xwiki data
   * @return the Annotation instance for the annotation stored in BaseObject
   */
  protected Annotation loadAnnotationFromObject(BaseObject object, XWikiContext deprecatedContext) {
    // load the annotation with its ID, special handling of the state since it needs
    // deserialization, special
    // handling of the original selection which shouldn't be set if it's empty
    Annotation annotation = new Annotation(object.getNumber() + "");
    annotation.setState(AnnotationState.valueOf(object.getStringValue(Annotation.STATE_FIELD)));
    String originalSelection = object.getStringValue(Annotation.ORIGINAL_SELECTION_FIELD);
    if (originalSelection != null && originalSelection.length() > 0) {
      annotation.setOriginalSelection(originalSelection);
    }

    Collection<String> skippedFields =
        Arrays.asList(new String[] {Annotation.ORIGINAL_SELECTION_FIELD, Annotation.STATE_FIELD});
    // go through all props and load them in the annotation, except for the ones already loaded
    // get all the props, filter those that need to be skipped and save the rest
    for (String propName : object.getPropertyNames()) {
      if (!skippedFields.contains(propName)) {
        try {
          annotation.set(propName, ((BaseProperty) object.get(propName)).getValue());
        } catch (XWikiException e) {
          this.logger.warn(
              "Unable to get property "
                  + propName
                  + " from object "
                  + object.getClassName()
                  + "["
                  + object.getNumber()
                  + "]. Will not be saved in the annotation.",
              e);
        }
      }
    }
    return annotation;
  }
 /**
  * Finds all existing rights objects.
  *
  * @param doc XWikiDocument
  * @return map of rights combination as keys, and corresponding existing rights objects as values
  */
 private Map<String, BaseObject> findRights(XWikiDocument doc) {
   List<BaseObject> allRights = doc.getXObjects(RIGHTS_CLASS);
   if (allRights == null) {
     return new HashMap<String, BaseObject>();
   }
   Map<String, BaseObject> rightsObjects = new HashMap<String, BaseObject>();
   List<String> missingRights = new LinkedList<String>(rightsCombinations);
   for (BaseObject right : allRights) {
     // getXObjects returns an ArrayList that could be lacking elements
     if (right == null) {
       continue;
     }
     String rightLevel = right.getStringValue("levels");
     if (rightsCombinations.contains(rightLevel)) {
       rightsObjects.put(rightLevel, right);
     }
   }
   return rightsObjects;
 }
Esempio n. 26
0
 /**
  * Trigger a BaseObject job (execute it now).
  *
  * @param object the BaseObject Job to be triggered
  * @return true on success, false on failure.
  */
 public boolean triggerJob(BaseObject object) {
   try {
     getProtectedPlugin().triggerJob(object, this.context);
     LOGGER.debug("Trigger Job: [{}]", object.getStringValue("jobName"));
     return true;
   } catch (XWikiException e) {
     this.context.put("error", e.getMessage());
     return false;
   }
 }
  @Test
  public void getMembersWhenGroupWithOneBlankUser() 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("");
    memberObjects.add(bo);
    when(document.getXObjects(new DocumentReference("groupwiki", "XWiki", "XWikiGroups")))
        .thenReturn(memberObjects);

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

    assertFalse(iterator.hasNext());
  }
  private static void fillObjectSummary(
      ObjectSummary objectSummary,
      ObjectFactory objectFactory,
      URI baseUri,
      Document doc,
      BaseObject xwikiObject,
      XWiki xwikiApi,
      Boolean withPrettyNames)
      throws XWikiException {

    objectSummary.setId(String.format("%s:%s", doc.getPrefixedFullName(), xwikiObject.getGuid()));
    objectSummary.setGuid(xwikiObject.getGuid());
    objectSummary.setPageId(doc.getPrefixedFullName());
    objectSummary.setPageVersion(doc.getVersion());
    objectSummary.setPageAuthor(doc.getAuthor());
    if (withPrettyNames) {
      objectSummary.setPageAuthorName(xwikiApi.getUserName(doc.getAuthor(), false));
    }
    objectSummary.setWiki(doc.getWiki());
    objectSummary.setSpace(doc.getSpace());
    objectSummary.setPageName(doc.getName());
    objectSummary.setClassName(xwikiObject.getClassName());
    objectSummary.setNumber(xwikiObject.getNumber());

    String[] propertyNames = xwikiObject.getPropertyNames();
    if (propertyNames.length > 0) {
      objectSummary.setHeadline(xwikiObject.get(propertyNames[0]).toFormString());
    }
  }
 @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;
 }
  @Before
  public void before() throws Exception {
    Locale.setDefault(Locale.ROOT);

    // checking

    this.preferencesDocumentReference =
        new DocumentReference(
            this.oldcore.getXWikiContext().getWikiId(), "XWiki", "XWikiPreferences");

    XWikiDocument preferencesDocument = new XWikiDocument(this.preferencesDocumentReference);
    BaseObject preferencesObject = new BaseObject();
    preferencesObject.setXClassReference(
        new DocumentReference(
            this.oldcore.getXWikiContext().getWikiId(), "XWiki", "XWikiPreferences"));
    preferencesDocument.addXObject(preferencesObject);
    preferencesDocument.setSyntax(Syntax.PLAIN_1_0);
    this.oldcore
        .getMockXWiki()
        .saveDocument(preferencesDocument, "", this.oldcore.getXWikiContext());

    this.defaultWikiTranslationReference =
        new DocumentReference(this.oldcore.getXWikiContext().getWikiId(), "XWiki", "Translations");

    XWikiDocument defaultWikiTranslation = new XWikiDocument(this.defaultWikiTranslationReference);
    defaultWikiTranslation.setSyntax(Syntax.PLAIN_1_0);
    this.oldcore
        .getMockXWiki()
        .saveDocument(defaultWikiTranslation, "", this.oldcore.getXWikiContext());

    // MessageTool

    this.tool =
        new XWikiMessageTool(
            this.oldcore
                .getMocker()
                .<ContextualLocalizationManager>getInstance(ContextualLocalizationManager.class));
  }