예제 #1
0
  protected static BaseClass getXWikiGroupRelationClass(XWikiContext context)
      throws XWikiException {
    XWikiDocument doc;
    XWiki xwiki = context.getWiki();
    boolean needsUpdate = false;

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

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

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

    if (needsUpdate) xwiki.saveDocument(doc, context);
    return bclass;
  }
  /**
   * 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);
  }
  /**
   * 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());
  }
  private BaseClass getSubscriptionClass(XWikiContext context) throws XWikiException {
    XWikiDocument doc;
    XWiki xwiki = context.getWiki();
    boolean needsUpdate = false;

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

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

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

    if (needsUpdate) {
      xwiki.saveDocument(doc, context);
    }
    return bclass;
  }
예제 #5
0
  /** @since 2.2.3 */
  public static BaseObject newCustomClassInstance(
      DocumentReference classReference, XWikiContext context) throws XWikiException {
    BaseClass bclass = context.getWiki().getXClass(classReference, context);
    BaseObject object =
        (bclass == null) ? new BaseObject() : bclass.newCustomClassInstance(context);

    return object;
  }
예제 #6
0
  /**
   * @deprecated since 2.2.3 use {@link #newCustomClassInstance(DocumentReference, XWikiContext)}
   */
  @Deprecated
  public static BaseObject newCustomClassInstance(String className, XWikiContext context)
      throws XWikiException {
    BaseClass bclass = context.getWiki().getClass(className, context);
    BaseObject object =
        (bclass == null) ? new BaseObject() : bclass.newCustomClassInstance(context);

    return object;
  }
  /**
   * Configure BaseClass.
   *
   * @param baseClass the baseClass to configure.
   * @return true if <code>baseClass</code> modified.
   */
  protected boolean updateBaseClass(BaseClass baseClass) {
    boolean needUpdate = false;

    if (!baseClass.getName().equals(getClassFullName())) {
      baseClass.setName(getClassFullName());
      needUpdate = true;
    }

    return needUpdate;
  }
예제 #8
0
  @Override
  public List<ObjectDiff> getDiff(Object oldObject, XWikiContext context) {
    ArrayList<ObjectDiff> difflist = new ArrayList<ObjectDiff>();
    BaseClass oldClass = (BaseClass) oldObject;
    for (PropertyClass newProperty : (Collection<PropertyClass>) getFieldList()) {
      String propertyName = newProperty.getName();
      PropertyClass oldProperty = (PropertyClass) oldClass.get(propertyName);
      String propertyType = newProperty.getClassType();

      if (oldProperty == null) {
        difflist.add(
            new ObjectDiff(
                getXClassReference(),
                getNumber(),
                "",
                ObjectDiff.ACTION_PROPERTYADDED,
                propertyName,
                propertyType,
                "",
                ""));
      } else if (!oldProperty.equals(newProperty)) {
        difflist.add(
            new ObjectDiff(
                getXClassReference(),
                getNumber(),
                "",
                ObjectDiff.ACTION_PROPERTYCHANGED,
                propertyName,
                propertyType,
                "",
                ""));
      }
    }

    for (PropertyClass oldProperty : (Collection<PropertyClass>) oldClass.getFieldList()) {
      String propertyName = oldProperty.getName();
      PropertyClass newProperty = (PropertyClass) get(propertyName);
      String propertyType = oldProperty.getClassType();

      if (newProperty == null) {
        difflist.add(
            new ObjectDiff(
                getXClassReference(),
                getNumber(),
                "",
                ObjectDiff.ACTION_PROPERTYREMOVED,
                propertyName,
                propertyType,
                "",
                ""));
      }
    }

    return difflist;
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    this.authService = new XWikiAuthServiceImpl();

    this.mockXWiki = mock(XWiki.class);
    getContext().setWiki((XWiki) this.mockXWiki.proxy());

    BaseClass userClass = new BaseClass();
    userClass.setDocumentReference(
        new DocumentReference(getContext().getWikiId(), "XWiki", "XWikiUsers"));
    userClass.addPasswordField("password", "Password", 10);

    this.mockXWiki.stubs().method("getUserClass").will(returnValue(userClass));
  }
예제 #10
0
  public void reload(Document doc, XWikiContext context) throws XWikiException {
    if (doc == null)
      doc = context.getWiki().getDocument(this.doc.getFullName(), context).newDocument(context);
    this.doc = doc;

    BaseClass dirGrpClass = getXWikiDirectoryGroupClass(context);
    Object obj;

    if ((obj = doc.getObject(dirGrpClass.getName())) == null) {
      doc.createNewObject(dirGrpClass.getName());
      obj = doc.getObject(dirGrpClass.getName());
      this.isNew = true;
    }

    this.objDirectoryGroup = obj;
  }
예제 #11
0
  @Override
  public BaseClass clone() {
    BaseClass bclass = (BaseClass) super.clone();
    bclass.setCustomClass(getCustomClass());
    bclass.setCustomMapping(getCustomMapping());
    bclass.setDefaultWeb(getDefaultWeb());
    bclass.setDefaultViewSheet(getDefaultViewSheet());
    bclass.setDefaultEditSheet(getDefaultEditSheet());
    bclass.setNameField(getNameField());
    bclass.setDirty(this.isDirty);
    bclass.setOwnerDocument(this.ownerDocument);

    return bclass;
  }
예제 #12
0
  public boolean add(XWikiDocument doc, int defaultAction, XWikiContext context)
      throws XWikiException {
    if (!context.getWiki().checkAccess("edit", doc, context)) {
      return false;
    }

    for (int i = 0; i < this.files.size(); i++) {
      DocumentInfo di = this.files.get(i);
      if (di.getFullName().equals(doc.getFullName())
          && (di.getLanguage().equals(doc.getLanguage()))) {
        if (defaultAction != DocumentInfo.ACTION_NOT_DEFINED) {
          di.setAction(defaultAction);
        }
        if (!doc.isNew()) {
          di.setDoc(doc);
        }

        return true;
      }
    }

    doc = doc.clone();

    try {
      filter(doc, context);

      DocumentInfo docinfo = new DocumentInfo(doc);
      docinfo.setAction(defaultAction);
      this.files.add(docinfo);
      BaseClass bclass = doc.getXClass();
      if (bclass.getFieldList().size() > 0) {
        this.classFiles.add(docinfo);
      }
      if (bclass.getCustomMapping() != null) {
        this.customMappingFiles.add(docinfo);
      }
      return true;
    } catch (ExcludeDocumentException e) {
      LOGGER.info("Skip the document " + doc.getDocumentReference());

      return false;
    }
  }
  /**
   * Set the default value of a boolean field of a XWiki class.
   *
   * @param baseClass the XWiki class.
   * @param fieldName the name of the field.
   * @param value the default value.
   * @return true if <code>baseClass</code> modified.
   */
  protected boolean updateBooleanClassDefaultValue(
      BaseClass baseClass, String fieldName, Boolean value) {
    boolean needsUpdate = false;

    BooleanClass bc = (BooleanClass) baseClass.get(fieldName);

    int old = bc.getDefaultValue();
    int intvalue = intFromBoolean(value);

    if (intvalue != old) {
      bc.setDefaultValue(intvalue);
      needsUpdate = true;
    }

    return needsUpdate;
  }
예제 #14
0
  @Override
  public boolean equals(Object obj) {
    // Same Java object, they sure are equal
    if (this == obj) {
      return true;
    }

    if (!super.equals(obj)) {
      return false;
    }

    BaseClass bclass = (BaseClass) obj;

    if (!getCustomClass().equals(bclass.getCustomClass())) {
      return false;
    }

    if (!getCustomMapping().equals(bclass.getCustomMapping())) {
      return false;
    }

    if (!getDefaultViewSheet().equals(bclass.getDefaultViewSheet())) {
      return false;
    }

    if (!getDefaultEditSheet().equals(bclass.getDefaultEditSheet())) {
      return false;
    }

    if (!getDefaultWeb().equals(bclass.getDefaultWeb())) {
      return false;
    }

    if (!getValidationScript().equals(bclass.getValidationScript())) {
      return false;
    }

    if (!getNameField().equals(bclass.getNameField())) {
      return false;
    }

    return true;
  }
  @Override
  public void write(
      BaseClass xclass,
      Object filter,
      BaseClassFilter xclassFilter,
      DocumentInstanceInputProperties properties)
      throws FilterException {
    // WikiClass

    FilterEventParameters classParameters = new FilterEventParameters();

    classParameters.put(WikiClassFilter.PARAMETER_CUSTOMCLASS, xclass.getCustomClass());
    classParameters.put(WikiClassFilter.PARAMETER_CUSTOMMAPPING, xclass.getCustomMapping());
    classParameters.put(WikiClassFilter.PARAMETER_DEFAULTSPACE, xclass.getDefaultWeb());
    classParameters.put(WikiClassFilter.PARAMETER_NAMEFIELD, xclass.getNameField());
    classParameters.put(WikiClassFilter.PARAMETER_SHEET_DEFAULTEDIT, xclass.getDefaultEditSheet());
    classParameters.put(WikiClassFilter.PARAMETER_SHEET_DEFAULTVIEW, xclass.getDefaultViewSheet());
    classParameters.put(WikiClassFilter.PARAMETER_VALIDATIONSCRIPT, xclass.getValidationScript());

    xclassFilter.beginWikiClass(classParameters);

    // Properties

    // Iterate over values sorted by field name so that the values are
    // exported to XML in a consistent order.
    Iterator<PropertyClass> it = xclass.getSortedIterator();
    while (it.hasNext()) {
      PropertyClass xclassProperty = it.next();

      ((PropertyClassEventGenerator) this.propertyEventGenerator)
          .write(xclassProperty, filter, xclassFilter, properties);
    }

    // /WikiClass

    xclassFilter.endWikiClass(classParameters);
  }
  public static Object createObject(
      ObjectFactory objectFactory,
      URI baseUri,
      XWikiContext xwikiContext,
      Document doc,
      BaseObject xwikiObject,
      boolean useVersion,
      XWiki xwikiApi,
      Boolean withPrettyNames)
      throws XWikiException {
    Object object = objectFactory.createObject();
    fillObjectSummary(object, objectFactory, baseUri, doc, xwikiObject, xwikiApi, withPrettyNames);

    BaseClass xwikiClass = xwikiObject.getXClass(xwikiContext);

    for (java.lang.Object propertyClassObject : xwikiClass.getProperties()) {
      com.xpn.xwiki.objects.classes.PropertyClass propertyClass =
          (com.xpn.xwiki.objects.classes.PropertyClass) propertyClassObject;

      Property property = objectFactory.createProperty();

      for (java.lang.Object o : propertyClass.getProperties()) {
        BaseProperty baseProperty = (BaseProperty) o;
        Attribute attribute = objectFactory.createAttribute();
        attribute.setName(baseProperty.getName());

        /* Check for null values in order to prevent NPEs */
        if (baseProperty.getValue() != null) {
          attribute.setValue(baseProperty.getValue().toString());
        } else {
          attribute.setValue("");
        }

        property.getAttributes().add(attribute);
      }

      if (propertyClass instanceof ListClass) {
        ListClass listClass = (ListClass) propertyClass;

        List allowedValueList = listClass.getList(xwikiContext);

        if (!allowedValueList.isEmpty()) {
          Formatter f = new Formatter();
          for (int i = 0; i < allowedValueList.size(); i++) {
            if (i != allowedValueList.size() - 1) {
              f.format("%s,", allowedValueList.get(i).toString());
            } else {
              f.format("%s", allowedValueList.get(i).toString());
            }
          }

          Attribute attribute = objectFactory.createAttribute();
          attribute.setName(Constants.ALLOWED_VALUES_ATTRIBUTE_NAME);
          attribute.setValue(f.toString());
          property.getAttributes().add(attribute);
        }
      }

      property.setName(propertyClass.getName());
      property.setType(propertyClass.getClassType());
      if (xwikiObject.get(propertyClass.getName()) != null) {
        property.setValue(xwikiObject.get(propertyClass.getName()).toFormString());
      } else {
        property.setValue("");
      }

      String propertyUri;

      if (useVersion) {
        propertyUri =
            uri(
                baseUri,
                ObjectPropertyAtPageVersionResource.class,
                doc.getWiki(),
                doc.getSpace(),
                doc.getName(),
                doc.getVersion(),
                xwikiObject.getClassName(),
                xwikiObject.getNumber(),
                propertyClass.getName());
      } else {
        propertyUri =
            uri(
                baseUri,
                ObjectPropertyResource.class,
                doc.getWiki(),
                doc.getSpace(),
                doc.getName(),
                xwikiObject.getClassName(),
                xwikiObject.getNumber(),
                propertyClass.getName());
      }
      Link propertyLink = objectFactory.createLink();
      propertyLink.setHref(propertyUri);
      propertyLink.setRel(Relations.SELF);
      property.getLinks().add(propertyLink);

      object.getProperties().add(property);
    }

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

    return object;
  }
  private BaseClass getCalendarClass(XWikiContext context) throws XWikiException {
    XWikiDocument doc;
    XWiki xwiki = context.getWiki();
    boolean needsUpdate = false;

    try {
      doc = xwiki.getDocument(CelementsCalendarPlugin.CLASS_CALENDAR, context);
    } catch (Exception e) {
      doc = new XWikiDocument();
      doc.setSpace(CelementsCalendarPlugin.CLASS_CALENDAR_SPACE);
      doc.setName(CelementsCalendarPlugin.CLASS_CALENDAR_DOC);
      needsUpdate = true;
    }

    BaseClass bclass = doc.getxWikiClass();
    bclass.setName(CelementsCalendarPlugin.CLASS_CALENDAR);
    needsUpdate |=
        bclass.addTextField(
            CelementsCalendarPlugin.PROPERTY_CALENDAR_SPACE,
            CelementsCalendarPlugin.PROPERTY_CALENDAR_SPACE,
            30);
    String hql = "select doc.fullName from XWikiDocument as doc, BaseObject as obj,";
    hql += " IntegerProperty as int ";
    hql += "where obj.name=doc.fullName ";
    hql += "and not doc.fullName='$doc.getFullName()' ";
    hql += "and obj.className='" + CelementsCalendarPlugin.CLASS_CALENDAR + "' ";
    hql += "and int.id.id=obj.id ";
    hql += "and int.id.name='" + CelementsCalendarPlugin.PROPERTY_IS_SUBSCRIBABLE + "' ";
    hql += "and int.value='1' ";
    hql += "order by doc.fullName asc";
    needsUpdate |=
        bclass.addDBListField(
            CelementsCalendarPlugin.PROPERTY_SUBSCRIBE_TO,
            CelementsCalendarPlugin.PROPERTY_SUBSCRIBE_TO,
            5,
            true,
            hql);
    needsUpdate |=
        bclass.addTextField(
            CelementsCalendarPlugin.PROPERTY_OVERVIEW_COLUMN_CONFIG,
            CelementsCalendarPlugin.PROPERTY_OVERVIEW_COLUMN_CONFIG,
            30);
    needsUpdate |=
        bclass.addTextField(
            CelementsCalendarPlugin.PROPERTY_EVENT_COLUMN_CONFIG,
            CelementsCalendarPlugin.PROPERTY_EVENT_COLUMN_CONFIG,
            30);
    needsUpdate |=
        bclass.addNumberField(
            CelementsCalendarPlugin.PROPERTY_EVENT_PER_PAGE,
            CelementsCalendarPlugin.PROPERTY_EVENT_PER_PAGE,
            5,
            "integer");
    needsUpdate |=
        bclass.addBooleanField(
            CelementsCalendarPlugin.PROPERTY_HAS_MORE_LINK,
            CelementsCalendarPlugin.PROPERTY_HAS_MORE_LINK,
            "yesno");
    needsUpdate |=
        bclass.addBooleanField(
            CelementsCalendarPlugin.PROPERTY_IS_SUBSCRIBABLE,
            CelementsCalendarPlugin.PROPERTY_IS_SUBSCRIBABLE,
            "yesno");

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

    if (needsUpdate) {
      xwiki.saveDocument(doc, context);
    }
    return bclass;
  }
예제 #18
0
  @Override
  public void merge(
      ElementInterface previousElement,
      ElementInterface newElement,
      MergeConfiguration configuration,
      XWikiContext context,
      MergeResult mergeResult) {
    BaseClass previousClass = (BaseClass) previousElement;
    BaseClass newClass = (BaseClass) newElement;

    setCustomClass(
        MergeUtils.mergeCharacters(
            previousClass.getCustomClass(),
            newClass.getCustomClass(),
            getCustomClass(),
            mergeResult));

    setCustomMapping(
        MergeUtils.mergeCharacters(
            previousClass.getCustomMapping(),
            newClass.getCustomMapping(),
            getCustomMapping(),
            mergeResult));

    setDefaultWeb(
        MergeUtils.mergeCharacters(
            previousClass.getDefaultWeb(), newClass.getDefaultWeb(), getDefaultWeb(), mergeResult));

    setDefaultViewSheet(
        MergeUtils.mergeCharacters(
            previousClass.getDefaultViewSheet(),
            newClass.getDefaultViewSheet(),
            getDefaultViewSheet(),
            mergeResult));

    setDefaultEditSheet(
        MergeUtils.mergeCharacters(
            previousClass.getDefaultEditSheet(),
            newClass.getDefaultEditSheet(),
            getDefaultEditSheet(),
            mergeResult));

    setNameField(
        MergeUtils.mergeCharacters(
            previousClass.getNameField(), newClass.getNameField(), getNameField(), mergeResult));

    // Properties

    List<ObjectDiff> classDiff = newClass.getDiff(previousClass, context);
    for (ObjectDiff diff : classDiff) {
      PropertyClass propertyResult = (PropertyClass) getField(diff.getPropName());
      PropertyClass previousProperty = (PropertyClass) previousClass.getField(diff.getPropName());
      PropertyClass newProperty = (PropertyClass) newClass.getField(diff.getPropName());

      if (diff.getAction() == ObjectDiff.ACTION_PROPERTYADDED) {
        if (propertyResult == null) {
          // Add if none has been added by user already
          addField(
              diff.getPropName(),
              configuration.isProvidedVersionsModifiables()
                  ? newClass.getField(diff.getPropName())
                  : newClass.getField(diff.getPropName()).clone());
          mergeResult.setModified(true);
        } else if (!propertyResult.equals(newProperty)) {
          // XXX: collision between DB and new: property to add but already exists in the DB
          mergeResult
              .getLog()
              .error("Collision found on class property [{}]", newProperty.getReference());
        }
      } else if (diff.getAction() == ObjectDiff.ACTION_PROPERTYREMOVED) {
        if (propertyResult != null) {
          if (propertyResult.equals(previousProperty)) {
            // Delete if it's the same as previous one
            removeField(diff.getPropName());
            mergeResult.setModified(true);
          } else {
            // XXX: collision between DB and new: property to remove but not the same as previous
            // version
            mergeResult
                .getLog()
                .error("Collision found on class property [{}]", previousProperty.getReference());
          }
        } else {
          // Already removed from DB, lets assume the user is prescient
          mergeResult
              .getLog()
              .warn("Object property [{}] already removed", previousProperty.getReference());
        }
      } else if (diff.getAction() == ObjectDiff.ACTION_PROPERTYCHANGED) {
        if (propertyResult != null) {
          if (propertyResult.equals(previousProperty)) {
            // Let some automatic migration take care of that modification between DB and new
            addField(diff.getPropName(), newClass.getField(diff.getPropName()));
            mergeResult.setModified(true);
          } else if (!propertyResult.equals(newProperty)) {
            propertyResult.merge(
                previousProperty, newProperty, configuration, context, mergeResult);
          }
        } else {
          // XXX: collision between DB and new: property to modify but does not exists in DB
          // Lets assume it's a mistake to fix
          mergeResult
              .getLog()
              .warn("Collision found on class property [{}]", newProperty.getReference());

          addField(diff.getPropName(), newClass.getField(diff.getPropName()));
          mergeResult.setModified(true);
        }
      }
    }
  }
예제 #19
0
  @Override
  public boolean apply(ElementInterface newElement, boolean clean) {
    boolean modified = super.apply(newElement, clean);

    BaseClass newBaseClass = (BaseClass) newElement;

    if (!StringUtils.equals(getCustomClass(), newBaseClass.getCustomClass())) {
      setCustomClass(newBaseClass.getCustomClass());
      modified = true;
    }

    if (!StringUtils.equals(getCustomMapping(), newBaseClass.getCustomMapping())) {
      setCustomMapping(newBaseClass.getCustomMapping());
      modified = true;
    }

    if (!StringUtils.equals(getDefaultWeb(), newBaseClass.getDefaultWeb())) {
      setDefaultWeb(newBaseClass.getDefaultWeb());
      modified = true;
    }

    if (!StringUtils.equals(getDefaultViewSheet(), newBaseClass.getDefaultViewSheet())) {
      setDefaultViewSheet(newBaseClass.getDefaultViewSheet());
      modified = true;
    }

    if (!StringUtils.equals(getDefaultEditSheet(), newBaseClass.getDefaultEditSheet())) {
      setDefaultEditSheet(newBaseClass.getDefaultEditSheet());
      modified = true;
    }

    if (!StringUtils.equals(getNameField(), newBaseClass.getNameField())) {
      setNameField(newBaseClass.getNameField());
      modified = true;
    }

    return modified;
  }
  private BaseClass getCalendarEventClass(XWikiContext context) throws XWikiException {
    XWikiDocument doc;
    XWiki xwiki = context.getWiki();
    boolean needsUpdate = false;

    try {
      doc = xwiki.getDocument(CelementsCalendarPlugin.CLASS_EVENT, context);
    } catch (Exception e) {
      doc = new XWikiDocument();
      doc.setSpace(CelementsCalendarPlugin.CLASS_EVENT_SPACE);
      doc.setName(CelementsCalendarPlugin.CLASS_EVENT_DOC);
      needsUpdate = true;
    }

    BaseClass bclass = doc.getxWikiClass();
    bclass.setName(CelementsCalendarPlugin.CLASS_EVENT);
    needsUpdate |=
        bclass.addTextField(
            CelementsCalendarPlugin.PROPERTY_LANG, CelementsCalendarPlugin.PROPERTY_LANG, 30);
    needsUpdate |=
        bclass.addTextField(
            CelementsCalendarPlugin.PROPERTY_TITLE, CelementsCalendarPlugin.PROPERTY_TITLE, 30);
    needsUpdate |=
        bclass.addTextAreaField(
            CelementsCalendarPlugin.PROPERTY_TITLE_RTE,
            CelementsCalendarPlugin.PROPERTY_TITLE_RTE,
            80,
            15);
    needsUpdate |=
        bclass.addTextAreaField(
            CelementsCalendarPlugin.PROPERTY_DESCRIPTION,
            CelementsCalendarPlugin.PROPERTY_DESCRIPTION,
            80,
            15);
    needsUpdate |=
        bclass.addTextField(
            CelementsCalendarPlugin.PROPERTY_LOCATION,
            CelementsCalendarPlugin.PROPERTY_LOCATION,
            30);
    needsUpdate |=
        bclass.addTextAreaField(
            CelementsCalendarPlugin.PROPERTY_LOCATION_RTE,
            CelementsCalendarPlugin.PROPERTY_LOCATION_RTE,
            80,
            15);
    needsUpdate |=
        bclass.addDateField(
            CelementsCalendarPlugin.PROPERTY_EVENT_DATE,
            CelementsCalendarPlugin.PROPERTY_EVENT_DATE,
            null,
            0);
    needsUpdate |=
        bclass.addDateField(
            CelementsCalendarPlugin.PROPERTY_EVENT_DATE_END,
            CelementsCalendarPlugin.PROPERTY_EVENT_DATE_END,
            null,
            0);
    needsUpdate |=
        bclass.addBooleanField(
            CelementsCalendarPlugin.PROPERTY_EVENT_IS_SUBSCRIBABLE,
            CelementsCalendarPlugin.PROPERTY_EVENT_IS_SUBSCRIBABLE,
            "yesno");

    if (!"internal".equals(bclass.getCustomMapping())) {
      needsUpdate = true;
      bclass.setCustomMapping("internal");
    }

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

    if (needsUpdate) {
      xwiki.saveDocument(doc, context);
    }
    return bclass;
  }
  @Test
  public void getDocumentWithObjects() throws Exception {
    DocumentReference commentsClassReference =
        new DocumentReference("wiki", "space", "commentsClass");
    String commentContent = "This is a comment";
    String commentAuthor = "wiki:space.commentAuthor";
    Date commentDate = new Date();
    // Adding a fake password field to the comments class just to test the branch in the code.
    String commentPassword = "******";
    List<String> commentList = Arrays.asList("a", "list");

    List<BaseProperty<EntityReference>> commentFields =
        new ArrayList<BaseProperty<EntityReference>>();

    // Mock

    BaseProperty<EntityReference> mockCommentField = mock(BaseProperty.class);
    when(mockCommentField.getName()).thenReturn("comment");
    when(mockCommentField.getValue()).thenReturn(commentContent);
    commentFields.add(mockCommentField);

    BaseProperty<EntityReference> mockAuthorField = mock(BaseProperty.class);
    when(mockAuthorField.getName()).thenReturn("author");
    when(mockAuthorField.getValue()).thenReturn(commentAuthor);
    commentFields.add(mockAuthorField);

    BaseProperty<EntityReference> mockDateField = mock(BaseProperty.class);
    when(mockDateField.getName()).thenReturn("date");
    when(mockDateField.getValue()).thenReturn(commentDate);
    commentFields.add(mockDateField);

    BaseProperty<EntityReference> mockPasswordField = mock(BaseProperty.class);
    when(mockPasswordField.getName()).thenReturn("password");
    when(mockPasswordField.getValue()).thenReturn(commentPassword);
    commentFields.add(mockPasswordField);

    BaseProperty<EntityReference> mockListField = mock(BaseProperty.class);
    when(mockListField.getName()).thenReturn("list");
    when(mockListField.getValue()).thenReturn(commentList);
    commentFields.add(mockListField);

    BaseClass mockXClass = mock(BaseClass.class);

    BaseObject mockComment = mock(BaseObject.class);

    // When handled as a comment
    Vector<BaseObject> comments = new Vector<BaseObject>();
    comments.add(mockComment);
    when(mockDocument.getComments()).thenReturn(comments);

    when(mockComment.getStringValue("comment")).thenReturn(commentContent);
    when(mockComment.getStringValue("author")).thenReturn(commentAuthor);
    when(mockComment.getDateValue("date")).thenReturn(commentDate);

    // When handled as a general object
    HashMap<DocumentReference, List<BaseObject>> xObjects =
        new HashMap<DocumentReference, List<BaseObject>>();
    xObjects.put(commentsClassReference, Arrays.asList(mockComment));
    when(mockDocument.getXObjects()).thenReturn(xObjects);

    when(mockComment.getXClass(mockContext)).thenReturn(mockXClass);
    when(mockComment.getFieldList()).thenReturn(commentFields);

    PropertyClass passwordClass = mock(PasswordClass.class);
    when(mockXClass.get("password")).thenReturn(passwordClass);
    when(passwordClass.getClassType()).thenReturn("Password");

    // Call

    DocumentSolrMetadataExtractor extractor =
        (DocumentSolrMetadataExtractor) mocker.getComponentUnderTest();
    SolrInputDocument solrDocument = extractor.getSolrDocument(documentReference);

    // Assert and verify

    Assert.assertEquals(
        String.format("%s by %s on %s", commentContent, commentAuthor, commentDate),
        solrDocument.getFieldValue(
            String.format(Fields.MULTILIGNUAL_FORMAT, Fields.COMMENT, language)));

    Collection<Object> objectProperties =
        solrDocument.getFieldValues(
            String.format(Fields.MULTILIGNUAL_FORMAT, Fields.OBJECT_CONTENT, language));
    MatcherAssert.assertThat(
        objectProperties,
        Matchers.containsInAnyOrder(
            (Object) ("comment:" + commentContent),
            (Object) ("author:" + commentAuthor),
            (Object) ("date:" + commentDate.toString()),
            (Object) ("list:" + commentList.get(0)),
            (Object) ("list:" + commentList.get(1))));
    Assert.assertEquals(5, objectProperties.size());
  }