@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;
 }
  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;
  }
 public void verify(XWikiDocument doc, String action, XWikiContext context) {
   // Call rules explicitly for any actions of this document
   Vector<XWikiNotificationRule> vnamedrules;
   String name = doc.getFullName();
   synchronized (namedrules) {
     vnamedrules = getNamedRules(name);
     if (vnamedrules != null) vnamedrules = (Vector<XWikiNotificationRule>) vnamedrules.clone();
   }
   if (vnamedrules != null) {
     for (XWikiNotificationRule rule : vnamedrules) {
       rule.verify(doc, action, context);
     }
   }
   name = context.getWikiId() + ":" + doc.getFullName();
   synchronized (namedrules) {
     vnamedrules = getNamedRules(name);
     if (vnamedrules != null) vnamedrules = (Vector<XWikiNotificationRule>) vnamedrules.clone();
   }
   if (vnamedrules != null) {
     for (XWikiNotificationRule rule : vnamedrules) {
       rule.verify(doc, action, context);
     }
   }
   Vector<XWikiNotificationRule> grules;
   synchronized (generalrules) {
     grules = (Vector<XWikiNotificationRule>) generalrules.clone();
   }
   for (XWikiNotificationRule rule : grules) {
     rule.verify(doc, action, context);
   }
 }
Exemplo n.º 5
0
 /**
  * Store the requested attachment on the filesystem and return a {@code file://} URL where FOP can
  * access that file.
  *
  * @param wiki the name of the owner document's wiki
  * @param space the name of the owner document's space
  * @param name the name of the owner document
  * @param filename the name of the attachment
  * @param revision an optional attachment version
  * @param context the current request context
  * @return a {@code file://} URL where the attachment has been stored
  * @throws Exception if the attachment can't be retrieved from the database and stored on the
  *     filesystem
  */
 private URL getURL(
     String wiki,
     String space,
     String name,
     String filename,
     String revision,
     XWikiContext context)
     throws Exception {
   Map<String, File> usedFiles = getFileMapping(context);
   String key = getAttachmentKey(space, name, filename, revision);
   if (!usedFiles.containsKey(key)) {
     File file = getTemporaryFile(key, context);
     XWikiDocument doc =
         context
             .getWiki()
             .getDocument(
                 new DocumentReference(
                     StringUtils.defaultString(wiki, context.getDatabase()), space, name),
                 context);
     XWikiAttachment attachment = doc.getAttachment(filename);
     if (StringUtils.isNotEmpty(revision)) {
       attachment = attachment.getAttachmentRevision(revision, context);
     }
     FileOutputStream fos = new FileOutputStream(file);
     IOUtils.copy(attachment.getContentInputStream(context), fos);
     fos.close();
     usedFiles.put(key, file);
   }
   return usedFiles.get(key).toURI().toURL();
 }
  @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;
  }
  public XWikiPageClassLoader(String jarWikiPage, ClassLoader parent, XWikiContext context)
      throws XWikiException {
    super(new URL[0], parent);

    XWikiDocument doc = context.getWiki().getDocument(jarWikiPage, context);
    if (!doc.isNew()) {
      List attachList = doc.getAttachmentList();
      for (int i = 0; i < attachList.size(); i++) {
        XWikiAttachment attach = (XWikiAttachment) attachList.get(i);
        String filename = attach.getFilename();
        if (filename.endsWith(".jar")) {
          String downloadURL = doc.getExternalAttachmentURL(filename, "download", context);
          try {
            addURL(new URL(downloadURL));
            if (LOGGER.isDebugEnabled()) {
              LOGGER.debug(
                  "Adding ["
                      + downloadURL
                      + "] JAR from page ["
                      + jarWikiPage
                      + "] to Groovy classloader");
            }
          } catch (Exception e) {
            LOGGER.warn(
                "Failed to add ["
                    + downloadURL
                    + "] JAR from page ["
                    + jarWikiPage
                    + "], ignoring it.");
          }
        }
      }
    }
  }
Exemplo n.º 8
0
  /**
   * Create a {@link XWikiDocument} from xml stream.
   *
   * @param is the xml stream.
   * @return the {@link XWikiDocument}.
   * @throws XWikiException error when creating the {@link XWikiDocument}.
   */
  private XWikiDocument readFromXML(InputStream is) throws XWikiException {
    XWikiDocument doc = new XWikiDocument();

    doc.fromXML(is, this.withVersions);

    return doc;
  }
Exemplo n.º 9
0
  /**
   * Create a {@link XWikiDocument} from xml {@link Document}.
   *
   * @param domDoc the xml {@link Document}.
   * @return the {@link XWikiDocument}.
   * @throws XWikiException error when creating the {@link XWikiDocument}.
   */
  private XWikiDocument readFromXML(Document domDoc) throws XWikiException {
    XWikiDocument doc = new XWikiDocument();

    doc.fromXML(domDoc, this.withVersions);

    return doc;
  }
  @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);
    }
  }
  @Test
  public void fallbackOnResource() throws XWikiException, ComponentLookupException {
    Assert.assertEquals("Language", this.tool.get("language"));

    XWikiDocument defaultWikiTranslation =
        this.oldcore
            .getMockXWiki()
            .getDocument(this.defaultWikiTranslationReference, this.oldcore.getXWikiContext());
    defaultWikiTranslation.setDefaultLocale(Locale.FRENCH);

    addWikiTranslation("language", "Overwritten language", Locale.ROOT);

    // ROOT language has been overwritten
    this.oldcore.getXWikiContext().setLocale(Locale.ROOT);
    Assert.assertEquals("Overwritten language", this.tool.get("language"));

    // The real locale of ROOT version in FRENCH so it's overwritten too
    this.oldcore.getXWikiContext().setLocale(Locale.FRENCH);
    Assert.assertEquals("Overwritten language", this.tool.get("language"));

    // GERMAN hasn't been overwritten
    this.oldcore.getXWikiContext().setLocale(Locale.GERMAN);
    Assert.assertEquals("Sprache", this.tool.get("language"));

    // There is no ENGLISH translation for this key so it fallback on ROOT
    this.oldcore.getXWikiContext().setLocale(Locale.ENGLISH);
    Assert.assertEquals("Overwritten language", this.tool.get("language"));
  }
  private void addWikiTranslation(String key, String message, Locale locale) throws XWikiException {
    XWikiDocument document =
        this.oldcore
            .getMockXWiki()
            .getDocument(this.defaultWikiTranslationReference, this.oldcore.getXWikiContext());

    if (!locale.equals(Locale.ROOT)) {
      XWikiDocument translatedDocument =
          document.getTranslatedDocument(locale, this.oldcore.getXWikiContext());
      if (translatedDocument == document) {
        translatedDocument = new XWikiDocument(document.getDocumentReference(), locale);
        translatedDocument.setDefaultLocale(document.getDefaultLocale());
      }
      document = translatedDocument;
    }

    document.setSyntax(Syntax.PLAIN_1_0);

    StringBuilder builder = new StringBuilder(document.getContent());

    builder.append('\n');
    builder.append(key);
    builder.append('=');
    builder.append(message);

    document.setContent(builder.toString());

    this.oldcore.getMockXWiki().saveDocument(document, "", this.oldcore.getXWikiContext());

    setBundles(document.getFullName());
  }
Exemplo n.º 13
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);
    }
  }
  /**
   * Test that SomeUser is correctly authenticated as XWiki.SomeUser when xwiki:SomeUser is entered
   * as username.
   */
  public void testLoginWithWikiPrefix() throws Exception {
    // Setup a simple user profile document
    XWikiDocument userDoc = new XWikiDocument("XWiki", "SomeUser");
    // Mock the XWikiUsers object, since a real objects requires more mocking on the XWiki object
    Mock mockUserObj = mock(BaseObject.class, new Class[] {}, new Object[] {});
    mockUserObj.stubs().method("setDocumentReference");
    mockUserObj.stubs().method("setNumber");
    mockUserObj.stubs().method("getStringValue").with(eq("password")).will(returnValue("pass"));
    mockUserObj.stubs().method("setOwnerDocument");
    userDoc.addObject("XWiki.XWikiUsers", (BaseObject) mockUserObj.proxy());

    // Make a simple XWiki.XWikiUsers class that will contain a default password field
    BaseClass userClass = new BaseClass();
    userClass.addPasswordField("password", "Password", 20);
    userClass.setClassName("XWiki.XWikiUsers");

    // Prepare the XWiki mock
    this.mockXWiki
        .stubs()
        .method("getDocument")
        .with(eq("XWiki.SomeUser"), eq(this.getContext()))
        .will(returnValue(userDoc));
    this.mockXWiki
        .stubs()
        .method("getClass")
        .with(eq("XWiki.XWikiUsers"), eq(this.getContext()))
        .will(returnValue(userClass));
    this.mockXWiki.stubs().method("exists").will(returnValue(true));

    // Finally run the test: Using xwiki:Admin should correctly authenticate the Admin user
    Principal principal =
        this.authService.authenticate("xwiki:SomeUser", "pass", this.getContext());
    assertNotNull(principal);
    assertEquals("xwiki:XWiki.SomeUser", principal.getName());
  }
Exemplo n.º 15
0
  private void unimportPagesFromWiki(
      Collection<XarEntry> pages, String wiki, PackageConfiguration configuration) {
    WikiReference wikiReference = new WikiReference(wiki);

    XWikiContext xcontext = getXWikiContext();
    for (XarEntry xarEntry : pages) {
      DocumentReference documentReference =
          this.resolver.resolve(xarEntry.getDocumentReference(), wikiReference);
      try {
        XWikiDocument document =
            getXWikiContext().getWiki().getDocument(documentReference, xcontext);

        if (!document.isNew()) {
          String language = xarEntry.getLanguage();
          if (language != null) {
            document = document.getTranslatedDocument(language, xcontext);
            getXWikiContext().getWiki().deleteDocument(document, xcontext);
          } else {
            getXWikiContext().getWiki().deleteAllDocuments(document, xcontext);
          }
        }
      } catch (XWikiException e) {
        this.logger.error("Failed to delete document [" + documentReference + "]", e);
      }
    }
  }
  @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());
  }
  @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);
  }
  @Override
  public void renameLinks(
      DocumentReference documentReference,
      DocumentReference oldLinkTarget,
      DocumentReference newLinkTarget) {
    boolean popLevelProgress = false;
    try {
      XWikiContext xcontext = this.xcontextProvider.get();
      XWikiDocument document = xcontext.getWiki().getDocument(documentReference, xcontext);
      List<Locale> locales = document.getTranslationLocales(xcontext);

      this.progressManager.pushLevelProgress(1 + locales.size(), this);
      popLevelProgress = true;

      // Update the default locale instance.
      this.progressManager.startStep(this);
      renameLinks(document, oldLinkTarget, newLinkTarget);

      // Update the translations.
      for (Locale locale : locales) {
        this.progressManager.startStep(this);
        renameLinks(document.getTranslatedDocument(locale, xcontext), oldLinkTarget, newLinkTarget);
      }
    } catch (XWikiException e) {
      this.logger.error(
          "Failed to rename the links that target [{}] from [{}].",
          oldLinkTarget,
          documentReference,
          e);
    } finally {
      if (popLevelProgress) {
        this.progressManager.popLevelProgress(this);
      }
    }
  }
  @Before
  public void setUp_AbstractDocumentUpdateListenerTest() throws Exception {
    context = getContext();
    classRef = new DocumentReference("wiki", "Classes", "SomeClass");
    fields = Arrays.asList("field1", "field2");
    docRef = new DocumentReference("wiki", "Space", "SomeDoc");
    docMock = createMockAndAddToDefault(XWikiDocument.class);
    expect(docMock.getDocumentReference()).andReturn(docRef).anyTimes();
    origDocMock = createMockAndAddToDefault(XWikiDocument.class);
    expect(origDocMock.getDocumentReference()).andReturn(docRef).anyTimes();
    expect(docMock.getOriginalDocument()).andReturn(origDocMock).anyTimes();

    listener = new TestDocumentUpdateListener();
    listener.injectWebUtilsService(Utils.getComponent(IWebUtilsService.class));
    listener.injecExecution(Utils.getComponent(Execution.class));
    listener.injectCopyDocService(Utils.getComponent(ICopyDocumentRole.class));
    listener.injectRemoteObservationManagerContext(
        remoteObsManContextMock = createMockAndAddToDefault(RemoteObservationManagerContext.class));
    listener.injectObservationManager(
        obsManagerMock = createMockAndAddToDefault(ObservationManager.class));
    listener.configSrc = Utils.getComponent(ConfigurationSource.class);

    creatingEventMock = createMockAndAddToDefault(Event.class);
    createdEventMock = createMockAndAddToDefault(Event.class);
    updatingEventMock = createMockAndAddToDefault(Event.class);
    updatedEventMock = createMockAndAddToDefault(Event.class);
    deletingEventMock = createMockAndAddToDefault(Event.class);
    deletedEventMock = createMockAndAddToDefault(Event.class);
  }
  @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);
    }
  }
  /**
   * Set the language to all the translations that the owning document has. This ensures that this
   * entity is found for all the translations of a document, not just the original document.
   *
   * <p>Also, index the content with each language so that the right analyzer is used.
   *
   * @param documentReference the original document's reference.
   * @param solrDocument the Solr document where to add the fields.
   * @param object the object.
   * @throws Exception if problems occur.
   */
  protected void addLanguageAndContentFields(
      DocumentReference documentReference, SolrInputDocument solrDocument, BaseObject object)
      throws Exception {
    XWikiDocument originalDocument = getDocument(documentReference);

    // Get all the languages in which the document is available.
    List<String> documentLanguages = originalDocument.getTranslationList(getXWikiContext());
    // Make sure that the original document's language is there as well.
    String originalDocumentLanguage = getLanguage(documentReference);
    if (!documentLanguages.contains(originalDocumentLanguage)) {
      documentLanguages.add(originalDocumentLanguage);
    }

    // Do the work for each language.
    for (String documentLanguage : documentLanguages) {
      if (!documentLanguage.equals(originalDocumentLanguage)) {
        // The original document's language is already set by the call to the addDocumentFields
        // method.
        solrDocument.addField(Fields.LANGUAGE, documentLanguage);
      }

      addObjectContent(solrDocument, object, documentLanguage);
    }

    // We can`t rely on the schema's copyField here because we would trigger it for each language.
    // Doing the copy to
    // the text_general field manually.
    addObjectContent(solrDocument, object, Fields.MULTILINGUAL);
  }
  /**
   * Save an XClass that has a Number property whose type has changed and there is an instance of
   * this class that has no value set for that Number property.
   *
   * @see <a href="http://jira.xwiki.org/browse/XWIKI-8649">XWIKI-8649: Error when changing the
   *     number type of a field from an application</a>
   */
  @Test
  public void saveXWikiDocWithXClassAndNumberPropertyTypeChange() throws Exception {
    // The number property whose type has changed from Double to Integer.
    IntegerProperty integerProperty = mock(IntegerProperty.class);
    NumberClass numberField = mock(NumberClass.class);
    when(numberField.newProperty()).thenReturn(integerProperty);
    when(numberField.getNumberType()).thenReturn("integer");

    // The XClass that has only the number property.
    List<NumberClass> fieldList = Collections.singletonList(numberField);
    BaseClass baseClass = mock(BaseClass.class);
    when(baseClass.getFieldList()).thenReturn(fieldList);

    // The document that is being saved.
    XWikiDocument document = mock(XWikiDocument.class);
    when(document.getXClass()).thenReturn(baseClass);

    // Assume there are two objects of the XClass previously defined: one that has no value set for
    // the number
    // property and one that has a value.
    Query query = mock(Query.class);
    DoubleProperty doubleProperty = mock(DoubleProperty.class);
    when(doubleProperty.getValue()).thenReturn(3.5);
    DoubleProperty doublePropertyUnset = mock(DoubleProperty.class, "unset");
    List<DoubleProperty> properties = Arrays.asList(doublePropertyUnset, doubleProperty);
    when(session.createQuery(anyString())).thenReturn(query);
    when(query.setString(anyInt(), anyString())).thenReturn(query);
    when(query.list()).thenReturn(properties);

    store.saveXWikiDoc(document, context);

    // 4 times, for each number type (Integer, Long, Double and Float).
    verify(integerProperty, times(4)).setValue(3);
  }
Exemplo n.º 23
0
  @Test
  public void deleteAllDocumentsAndWithoutSendingToTrash() throws Exception {
    XWiki xwiki = new XWiki();

    XWikiDocument document = mock(XWikiDocument.class);
    DocumentReference reference = new DocumentReference("wiki", "space", "page");
    when(document.getDocumentReference()).thenReturn(reference);

    // Make sure we have a trash for the test.
    XWikiRecycleBinStoreInterface recycleBinStoreInterface =
        mock(XWikiRecycleBinStoreInterface.class);
    xwiki.setRecycleBinStore(recycleBinStoreInterface);
    when(xwikiCfgConfigurationSource.getProperty("xwiki.recyclebin", "1")).thenReturn("1");

    // Configure the mocked Store to later verify if it's called
    XWikiStoreInterface storeInterface = mock(XWikiStoreInterface.class);
    xwiki.setStore(storeInterface);
    XWikiContext xwikiContext = mock(XWikiContext.class);

    xwiki.deleteAllDocuments(document, false, xwikiContext);

    // Verify that saveToRecycleBin is never called since otherwise it would mean the doc has been
    // saved in the
    // trash
    verify(recycleBinStoreInterface, never())
        .saveToRecycleBin(
            any(XWikiDocument.class),
            any(String.class),
            any(Date.class),
            any(XWikiContext.class),
            any(Boolean.class));

    // Verify that deleteXWikiDoc() is called
    verify(storeInterface).deleteXWikiDoc(document, xwikiContext);
  }
Exemplo n.º 24
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;
  }
  @Override
  public EntityReference getDefaultReference(EntityType type) {
    EntityReference result = null;

    XWikiContext xcontext = this.xcontextProvider.get();
    if (xcontext != null) {
      if (type == EntityType.WIKI) {
        result = xcontext.getWikiReference();
      } else if (type == EntityType.SPACE) {
        XWikiDocument currentDoc = xcontext.getDoc();
        if (currentDoc != null) {
          SpaceReference spaceReference = currentDoc.getDocumentReference().getLastSpaceReference();
          // Keep only the spaces part
          result = spaceReference.removeParent(spaceReference.getWikiReference());
        }
      } else if (type == EntityType.DOCUMENT) {
        XWikiDocument currentDoc = xcontext.getDoc();
        if (currentDoc != null) {
          DocumentReference documentReference = currentDoc.getDocumentReference();
          // Keep only the document part
          result = documentReference.removeParent(documentReference.getLastSpaceReference());
        }
      }
    }

    if (result == null) {
      result = super.getDefaultReference(type);
    }

    return result;
  }
Exemplo n.º 26
0
 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;
 }
 /**
  * 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);
 }
Exemplo n.º 28
0
  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();
      }
    }
  }
  /**
   * Set the value of a boolean field in a document.
   *
   * @param doc the document to modify.
   * @param fieldName the name of the field.
   * @param value the value.
   * @return true if <code>doc</code> modified.
   */
  protected boolean updateDocStringValue(XWikiDocument doc, String fieldName, String value) {
    boolean needsUpdate = false;

    if (!value.equals(doc.getStringValue(getClassFullName(), fieldName))) {
      doc.setStringValue(getClassFullName(), fieldName, value);
      needsUpdate = true;
    }

    return needsUpdate;
  }
 /**
  * HACK: Save the given document without changing the content author because the document may
  * loose or win programming and script rights as a consequence and this is not the intent of this
  * operation. Even though the document content field was modified, the change is purely syntactic;
  * the semantic is not affected so it's not clear whether the content author deserves to be
  * updated or not (even without the side effects).
  *
  * @param document the document to be saved
  * @param comment the revision comment
  * @param minorEdit whether it's a minor edit or not
  * @throws XWikiException if saving the document fails
  */
 private void saveDocumentPreservingContentAuthor(
     XWikiDocument document, String comment, boolean minorEdit) throws XWikiException {
   XWikiContext xcontext = this.xcontextProvider.get();
   // Preserve the content author.
   document.setContentDirty(false);
   // Make sure the version is incremented.
   document.setMetaDataDirty(true);
   document.setAuthorReference(xcontext.getUserReference());
   xcontext.getWiki().saveDocument(document, comment, minorEdit, xcontext);
 }