@Test
  public void testOnEvent_update_ed_noChange() {
    Event event = new DocumentUpdatedEvent();

    expect(remoteObsManContextMock.isRemoteState()).andReturn(false).once();
    expect(docMock.getXObject(eq(classRef))).andReturn(new BaseObject()).once();
    expect(origDocMock.getXObject(eq(classRef))).andReturn(new BaseObject()).once();

    replayDefault();
    listener.onEvent(event, docMock, context);
    verifyDefault();
  }
  @Test
  public void testOnEvent_update_ed() {
    Event event = new DocumentUpdatedEvent();

    expect(remoteObsManContextMock.isRemoteState()).andReturn(false).once();
    expect(docMock.getXObject(eq(classRef))).andReturn(getBaseObject1()).once();
    expect(origDocMock.getXObject(eq(classRef))).andReturn(getBaseObject2()).once();
    obsManagerMock.notify(same(updatedEventMock), same(docMock), same(context));
    expectLastCall().once();

    replayDefault();
    listener.onEvent(event, docMock, context);
    verifyDefault();
  }
Esempio n. 3
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
  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);
    }
  }
 @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 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());
    }
  }
  @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());
  }
  @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);
    }
  }
  @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);
  }
 private boolean isGroup(DocumentReference profile) {
   try {
     XWikiDocument doc = (XWikiDocument) this.bridge.getDocument(profile);
     return doc == null ? false : (doc.getXObject(GROUP_CLASS) != null);
   } catch (Exception e) {
   }
   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"));
 }
  @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 void setUpUserPageMocks(DocumentReference userReference) throws Exception {
   XWikiDocument document = mock(XWikiDocument.class);
   when(document.isNew()).thenReturn(false);
   when(document.getDocumentReference()).thenReturn(userReference);
   BaseObject baseObject = mock(BaseObject.class);
   when(document.getXObject(
           new DocumentReference(
               userReference.getWikiReference().getName(), "XWiki", "XWikiUsers")))
       .thenReturn(baseObject);
   when(this.xwiki.getDocument(userReference, this.xwikiContext)).thenReturn(document);
 }
 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
 /**
  * {@inheritDoc} <br>
  * Implementation which gets all the annotation class objects in the document pointed by the
  * target, and matches their ids against the ids in the passed collection of annotations. If they
  * match, they are updated with the new data in the annotations in annotation.
  *
  * @see org.xwiki.annotation.io.IOService#updateAnnotations(String, java.util.Collection)
  */
 @Override
 public void updateAnnotations(String target, Collection<Annotation> annotations)
     throws IOServiceException {
   try {
     EntityReference targetReference = referenceResolver.resolve(target, EntityType.DOCUMENT);
     // get the document name from the parsed reference
     String docName = target;
     if (targetReference.getType() == EntityType.DOCUMENT
         || targetReference.getType() == EntityType.OBJECT_PROPERTY) {
       docName = serializer.serialize(targetReference.extractReference(EntityType.DOCUMENT));
     }
     // get the document pointed to by the target
     XWikiContext deprecatedContext = getXWikiContext();
     XWikiDocument document = deprecatedContext.getWiki().getDocument(docName, deprecatedContext);
     List<String> updateNotifs = new ArrayList<String>();
     boolean updated = false;
     for (Annotation annotation : annotations) {
       // parse annotation id as string. If cannot parse, then ignore annotation, is not valid
       int annId = 0;
       try {
         annId = Integer.parseInt(annotation.getId());
       } catch (NumberFormatException e) {
         continue;
       }
       BaseObject object = document.getXObject(configuration.getAnnotationClassReference(), annId);
       if (object == null) {
         continue;
       }
       updated = updateObject(object, annotation, deprecatedContext) || updated;
       updateNotifs.add(annotation.getId());
     }
     if (updated) {
       // set the author of the document to the current user
       document.setAuthor(deprecatedContext.getUser());
       deprecatedContext
           .getWiki()
           .saveDocument(document, "Updated annotations", deprecatedContext);
       // send annotation update notifications for all annotations set to notify for
       ObservationManager observationManager = componentManager.lookup(ObservationManager.class);
       for (String updateNotif : updateNotifs) {
         observationManager.notify(
             new AnnotationUpdatedEvent(docName, updateNotif), document, deprecatedContext);
       }
     }
   } catch (XWikiException e) {
     throw new IOServiceException("An exception has occurred while updating the annotation", e);
   } catch (ComponentLookupException exc) {
     this.logger.warn(
         "Could not get the observation manager to send notifications about the annotation update");
   }
 }
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");
    }
  }
  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());
    }
  }
  @Test
  public void getMembersWhenSingleReferenceNotAUser() throws Exception {
    setUpBaseMocks();
    XWikiDocument document = mock(XWikiDocument.class);
    when(document.isNew()).thenReturn(false);
    DocumentReference reference = new DocumentReference("somewiki", "XWiki", "somepage");
    when(document.getDocumentReference()).thenReturn(reference);
    when(document.getXObject(new DocumentReference("somewiki", "XWiki", "XWikiUsers")))
        .thenReturn(null);
    when(this.xwiki.getDocument(reference, this.xwikiContext)).thenReturn(document);

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

    assertFalse(iterator.hasNext());
  }
  @Test
  public void onEventWithNonGroup() throws ComponentLookupException, XWikiException {
    Utils.setComponentManager(this.mocker);

    DocumentReference docReference = new DocumentReference("xwiki", "Groups", "Group1");
    XWikiContext context = mock(XWikiContext.class);
    XWikiDocument doc = mock(XWikiDocument.class);
    when(doc.getXObject(Group.CLASS_REFERENCE)).thenReturn(null);

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

    Mockito.verifyZeroInteractions(context);
    Mockito.verify(doc).getXObject(Group.CLASS_REFERENCE);
    Mockito.verifyNoMoreInteractions(doc);
  }
  @Test
  public void loadBotData() throws Exception {
    BaseObject botDataObject = mock(BaseObject.class);

    when(configDoc.getXObject(WIKI_BOT_CONFIGURATION_CLASS)).thenReturn(botDataObject);
    when(botDataObject.getStringValue("botname")).thenReturn("mybotname");
    when(botDataObject.getStringValue("server")).thenReturn("myserver");
    when(botDataObject.getStringValue("channel")).thenReturn("mychannel");
    when(botDataObject.getStringValue("password")).thenReturn("mypassword");
    when(botDataObject.getIntValue("inactive")).thenReturn(0);

    BotData botData = this.componentManager.getComponentUnderTest().loadBotData();
    Assert.assertEquals("mybotname", botData.getName());
    Assert.assertEquals("myserver", botData.getServer());
    Assert.assertEquals("mychannel", botData.getChannel());
    Assert.assertEquals("mypassword", botData.getPassword());
    Assert.assertTrue(botData.isActive());
  }
Esempio n. 21
0
  /**
   * This function allow to retrieve a com.xpn.xwiki.objects.BaseObject from a
   * com.xpn.xwiki.api.Object without that the current user needs programming rights (as in
   * com.xpn.xwiki.api.Object#getXWikiObject(). The function is used internally by this api class
   * and allows wiki users to call methods from the scheduler without having programming right. The
   * programming right is only needed at script execution time.
   *
   * @return object the unwrapped version of the passed api object
   */
  private BaseObject retrieveBaseObject(Object object) throws SchedulerPluginException {
    String docName = object.getName();
    int objNb = object.getNumber();
    try {

      XWikiDocument jobHolder = this.context.getWiki().getDocument(docName, this.context);
      BaseObject jobObject = jobHolder.getXObject(SchedulerPlugin.XWIKI_JOB_CLASSREFERENCE, objNb);
      return jobObject;
    } catch (XWikiException e) {
      throw new SchedulerPluginException(
          SchedulerPluginException.ERROR_SCHEDULERPLUGIN_UNABLE_TO_RETRIEVE_JOB,
          "Job in document ["
              + docName
              + "] with object number ["
              + objNb
              + "] could not be retrieved.",
          e);
    }
  }
Esempio n. 22
0
  @Override
  public ExtensionId getUIExtensionId(String wiki) {
    XWikiContext xcontext = this.xcontextProvider.get();

    // If it is the main wiki, return the main UI.
    if (xcontext.isMainWiki(wiki)) {
      return this.distributionManager.getMainUIExtensionId();
    }

    try {
      // Get the wiki document
      DocumentReference wikiDocumentRef =
          documentReferenceResolver.resolve(
              xcontext.getMainXWiki() + ":" + XWiki.getServerWikiPage(wiki));

      XWikiDocument wikiDocument = xcontext.getWiki().getDocument(wikiDocumentRef, xcontext);

      // Let see if the wiki document has an Workspace object
      DocumentReference workspaceClassRef =
          new DocumentReference(xcontext.getMainXWiki(), "WorkspaceManager", "WorkspaceClass");

      // If there is an object, then it's a "workspace"
      if (wikiDocument.getXObject(workspaceClassRef) != null) {

        CoreExtension distributionExtension =
            this.coreExtensionRepository.getEnvironmentExtension();
        // Get the maven model
        Model mavenModel =
            (Model) distributionExtension.getProperty(MavenCoreExtension.PKEY_MAVEN_MODEL);
        // Get the UI Id
        String wikiUIId =
            mavenModel.getProperties().getProperty("xwiki.extension.distribution.workspaceui");

        return new ExtensionId(wikiUIId, distributionExtension.getId().getVersion());
      }

    } catch (XWikiException e) {
      logger.error("Failed to get wiki descriptor for wiki [{}]", wiki, e);
    }

    // Other case, it is a "normal" subwiki
    return this.distributionManager.getWikiUIExtensionId();
  }
Esempio n. 23
0
 @Override
 public Annotation getAnnotation(String target, String annotationID) throws IOServiceException {
   try {
     if (annotationID == null || target == null) {
       return null;
     }
     // parse the target and extract the local reference serialized from it, by the same rules
     EntityReference targetReference = referenceResolver.resolve(target, EntityType.DOCUMENT);
     // build the target identifier for the annotation
     String localTargetId = target;
     // and the name of the document where it should be stored
     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);
     // and the annotation class objects in it
     // parse the annotation id as object index
     BaseObject object =
         document.getXObject(
             configuration.getAnnotationClassReference(),
             Integer.valueOf(annotationID.toString()));
     if (object == null || !localTargetId.equals(object.getStringValue(Annotation.TARGET_FIELD))) {
       return null;
     }
     // use the object number as annotation id
     return loadAnnotationFromObject(object, deprecatedContext);
   } catch (NumberFormatException e) {
     throw new IOServiceException("Could not parse annotation id " + annotationID, e);
   } catch (XWikiException e) {
     throw new IOServiceException(
         "An exception has occurred while loading the annotation with id " + annotationID, e);
   }
 }
  @Override
  public boolean setFieldsInternal(
      LengthSolrInputDocument solrDocument, EntityReference entityReference) throws Exception {
    BaseObjectReference objectReference = new BaseObjectReference(entityReference);

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

    XWikiDocument document = getDocument(documentReference);
    BaseObject object = document.getXObject(objectReference);
    if (object == null) {
      return false;
    }

    solrDocument.setField(FieldUtils.ID, resolver.getId(object.getReference()));
    setDocumentFields(documentReference, solrDocument);
    solrDocument.setField(FieldUtils.TYPE, objectReference.getType().name());
    solrDocument.setField(FieldUtils.CLASS, localSerializer.serialize(classReference));
    solrDocument.setField(FieldUtils.NUMBER, objectReference.getObjectNumber());

    setLocaleAndContentFields(documentReference, solrDocument, object);

    return true;
  }
  @Test
  public void testImportUsersAndGroupsPreserveVersion()
      throws WikiStreamException, XWikiException, ParseException {
    UserInstanceOutputProperties outputProperties = new UserInstanceOutputProperties();

    outputProperties.setPreserveVersion(true);

    importFromXML("user1", outputProperties);

    // XWiki.user1

    XWikiDocument userDocument =
        this.oldcore
            .getMockXWiki()
            .getDocument(
                new DocumentReference("wiki1", "XWiki", "user1"), this.oldcore.getXWikiContext());

    Assert.assertFalse(userDocument.isNew());

    Assert.assertEquals(
        new DocumentReference("wiki1", "XWiki", "user1"), userDocument.getCreatorReference());
    Assert.assertEquals(toDate("2000-01-10 00:00:00.0 UTC"), userDocument.getCreationDate());
    Assert.assertEquals(
        new DocumentReference("wiki1", "XWiki", "user1"), userDocument.getAuthorReference());
    Assert.assertEquals(toDate("2000-01-11 00:00:00.0 UTC"), userDocument.getDate());
    Assert.assertEquals(toDate("2000-01-11 00:00:00.0 UTC"), userDocument.getContentUpdateDate());
    Assert.assertEquals(
        new DocumentReference("wiki1", "XWiki", "user1"), userDocument.getContentAuthorReference());
    Assert.assertEquals(false, userDocument.isMinorEdit());
    Assert.assertEquals("Import", userDocument.getComment());

    BaseObject userObject = userDocument.getXObject(USER_CLASS);
    Assert.assertEquals(0, userObject.getNumber());
    Assert.assertEquals("user1 first name", userObject.getStringValue("first_name"));
    Assert.assertEquals("user1 last name", userObject.getStringValue("last_name"));
    Assert.assertEquals("*****@*****.**", userObject.getStringValue("email"));
    Assert.assertEquals(1, userObject.getIntValue("active"));

    // XWiki.user2

    userDocument =
        this.oldcore
            .getMockXWiki()
            .getDocument(
                new DocumentReference("wiki1", "XWiki", "user2"), this.oldcore.getXWikiContext());

    Assert.assertFalse(userDocument.isNew());

    Assert.assertEquals(
        new DocumentReference("wiki1", "XWiki", "user2"), userDocument.getCreatorReference());
    Assert.assertEquals(toDate("2000-01-20 00:00:00.0 UTC"), userDocument.getCreationDate());
    Assert.assertEquals(
        new DocumentReference("wiki1", "XWiki", "user2"), userDocument.getAuthorReference());
    Assert.assertEquals(toDate("2000-01-21 00:00:00.0 UTC"), userDocument.getDate());
    Assert.assertEquals(toDate("2000-01-21 00:00:00.0 UTC"), userDocument.getContentUpdateDate());
    Assert.assertEquals(
        new DocumentReference("wiki1", "XWiki", "user2"), userDocument.getContentAuthorReference());
    Assert.assertEquals(false, userDocument.isMinorEdit());
    Assert.assertEquals("Import", userDocument.getComment());

    userObject = userDocument.getXObject(USER_CLASS);
    Assert.assertEquals(0, userObject.getNumber());
    Assert.assertEquals("user2 first name", userObject.getStringValue("first_name"));
    Assert.assertEquals("user2 last name", userObject.getStringValue("last_name"));
    Assert.assertEquals("*****@*****.**", userObject.getStringValue("email"));
    Assert.assertEquals(0, userObject.getIntValue("active"));

    // XWiki.group1

    XWikiDocument groupDocument =
        this.oldcore
            .getMockXWiki()
            .getDocument(
                new DocumentReference("wiki1", "XWiki", "group1"), this.oldcore.getXWikiContext());

    Assert.assertFalse(groupDocument.isNew());

    BaseObject groupMemberObject0 = groupDocument.getXObject(GROUP_CLASS, 0);
    Assert.assertEquals("XWiki.user1", groupMemberObject0.getStringValue("member"));
    BaseObject groupMemberObject1 = groupDocument.getXObject(GROUP_CLASS, 1);
    Assert.assertEquals("XWiki.user2", groupMemberObject1.getStringValue("member"));

    // XWiki.group2

    groupDocument =
        this.oldcore
            .getMockXWiki()
            .getDocument(
                new DocumentReference("wiki1", "XWiki", "group2"), this.oldcore.getXWikiContext());

    Assert.assertFalse(groupDocument.isNew());

    groupMemberObject0 = groupDocument.getXObject(GROUP_CLASS, 0);
    Assert.assertEquals("XWiki.group1", groupMemberObject0.getStringValue("member"));

    // XWiki.emptygroup

    groupDocument =
        this.oldcore
            .getMockXWiki()
            .getDocument(
                new DocumentReference("wiki1", "XWiki", "emptygroup"),
                this.oldcore.getXWikiContext());

    Assert.assertFalse(groupDocument.isNew());

    groupMemberObject0 = groupDocument.getXObject(GROUP_CLASS, 0);
    Assert.assertEquals("", groupMemberObject0.getStringValue("member"));
  }
Esempio n. 26
0
  /**
   * {@inheritDoc} <br>
   * This implementation saves the added annotation in the document where the target of the
   * annotation is.
   *
   * @see org.xwiki.annotation.io.IOService#addAnnotation(String, org.xwiki.annotation.Annotation)
   */
  @Override
  public void addAnnotation(String target, Annotation annotation) throws IOServiceException {
    try {
      // extract the document name from the passed target
      // by default the fullname is the passed target
      String documentFullName = target;
      EntityReference targetReference = referenceResolver.resolve(target, EntityType.DOCUMENT);
      // try to get a document reference from the passed target reference
      EntityReference docRef = targetReference.extractReference(EntityType.DOCUMENT);
      if (docRef != null) {
        documentFullName = serializer.serialize(docRef);
      }
      // now get the document with that name
      XWikiContext deprecatedContext = getXWikiContext();
      XWikiDocument document =
          deprecatedContext.getWiki().getDocument(documentFullName, deprecatedContext);
      // create a new object in this document to hold the annotation
      int id =
          document.createXObject(configuration.getAnnotationClassReference(), deprecatedContext);
      BaseObject object = document.getXObject(configuration.getAnnotationClassReference(), id);
      updateObject(object, annotation, deprecatedContext);
      // and set additional data: author to annotation author, date to now and the annotation target
      object.set(Annotation.DATE_FIELD, new Date(), deprecatedContext);
      // TODO: maybe we shouldn't trust what we receive from the caller but set the author from the
      // context.
      // Or the other way around, set the author of the document from the annotations author.
      object.set(Annotation.AUTHOR_FIELD, annotation.getAuthor(), deprecatedContext);
      // store the target of this annotation, serialized with a local serializer, to be exportable
      // and importable
      // in a different wiki
      // TODO: figure out if this is the best idea in terms of target serialization
      // 1/ the good part is that it is a fixed value that can be searched with a query in all
      // objects in the wiki
      // 2/ the bad part is that copying a document to another space will not also update its
      // annotation targets
      // 3/ if annotations are stored in the same document they annotate, the targets are only
      // required for object
      // fields
      // ftm don't store the type of the reference since we only need to recognize the field, not to
      // also read it.
      if (targetReference.getType() == EntityType.OBJECT_PROPERTY
          || targetReference.getType() == EntityType.DOCUMENT) {
        object.set(
            Annotation.TARGET_FIELD, localSerializer.serialize(targetReference), deprecatedContext);
      } else {
        object.set(Annotation.TARGET_FIELD, target, deprecatedContext);
      }
      // set the author of the document to the current user
      document.setAuthor(deprecatedContext.getUser());
      deprecatedContext
          .getWiki()
          .saveDocument(
              document,
              "Added annotation on \"" + annotation.getSelection() + "\"",
              deprecatedContext);

      // notify listeners that an annotation was added
      ObservationManager observationManager = componentManager.lookup(ObservationManager.class);
      observationManager.notify(
          new AnnotationAddedEvent(documentFullName, object.getNumber() + ""),
          document,
          deprecatedContext);

    } catch (XWikiException e) {
      throw new IOServiceException(
          "An exception message has occurred while saving the annotation", e);
    } catch (ComponentLookupException exc) {
      this.logger.warn(
          "Could not get the observation manager to send notifications about the annotation add");
    }
  }
 private boolean isPatient(XWikiDocument doc) {
   return (doc.getXObject(Patient.CLASS_REFERENCE) != null)
       && !"PatientTemplate".equals(doc.getDocumentReference().getName());
 }