Search in sources :

Example 1 with EntityReferenceSerializer

use of org.xwiki.model.reference.EntityReferenceSerializer in project xwiki-platform by xwiki.

the class SSXListenerTest method onEvent.

@Test
public void onEvent() throws Exception {
    // Mocks
    when(wikiDescriptorManager.getCurrentWikiId()).thenReturn("wiki");
    XWikiDocument doc = mock(XWikiDocument.class);
    BaseObject obj1 = mock(BaseObject.class);
    BaseObject obj2 = mock(BaseObject.class);
    List<BaseObject> objList = new ArrayList<>();
    DocumentReference ssxDocRef = new DocumentReference("wiki", "XWiki", "StyleSheetExtension");
    when(doc.getXObjects(eq(ssxDocRef))).thenReturn(objList);
    objList.add(obj1);
    objList.add(null);
    objList.add(obj2);
    when(obj1.getStringValue("contentType")).thenReturn("CSS");
    when(obj2.getStringValue("contentType")).thenReturn("LESS");
    when(obj2.getNumber()).thenReturn(2);
    DocumentReference documentReference = new DocumentReference("wiki", "Space", "Doc");
    when(doc.getDocumentReference()).thenReturn(documentReference);
    // Because BaseObjectReference uses components from the Utils class, we need to set up the component manager
    ComponentManager rootComponentManager = mock(ComponentManager.class);
    Utils.setComponentManager(rootComponentManager);
    ComponentManager contextComponentManager = mock(ComponentManager.class);
    when(rootComponentManager.getInstance(ComponentManager.class, "context")).thenReturn(contextComponentManager);
    // Mock to serialize the object
    EntityReferenceSerializer entityReferenceSerializer = mock(EntityReferenceSerializer.class);
    when(contextComponentManager.getInstance(EntityReferenceSerializer.TYPE_STRING, "compactwiki")).thenReturn(entityReferenceSerializer);
    when(entityReferenceSerializer.serialize(any(EntityReference.class), any(EntityReference.class))).thenReturn("objName");
    ObjectPropertyReference objPropertyReference = new ObjectPropertyReference("code", new BaseObjectReference(ssxDocRef, 2, documentReference));
    LESSObjectPropertyResourceReference lessObjectPropertyResourceReference = new LESSObjectPropertyResourceReference(objPropertyReference, null, null);
    when(lessResourceReferenceFactory.createReferenceForXObjectProperty(eq(objPropertyReference))).thenReturn(lessObjectPropertyResourceReference);
    // Test
    mocker.getComponentUnderTest().onEvent(new DocumentUpdatedEvent(), doc, new Object());
    // Verify
    verify(lessResourcesCache, atLeastOnce()).clearFromLESSResource(lessObjectPropertyResourceReference);
    verify(colorThemeCache, atLeastOnce()).clearFromLESSResource(lessObjectPropertyResourceReference);
}
Also used : ObjectPropertyReference(org.xwiki.model.reference.ObjectPropertyReference) LESSObjectPropertyResourceReference(org.xwiki.lesscss.internal.resources.LESSObjectPropertyResourceReference) ArrayList(java.util.ArrayList) DocumentUpdatedEvent(org.xwiki.bridge.event.DocumentUpdatedEvent) BaseObject(com.xpn.xwiki.objects.BaseObject) EntityReferenceSerializer(org.xwiki.model.reference.EntityReferenceSerializer) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) BaseObjectReference(com.xpn.xwiki.objects.BaseObjectReference) ComponentManager(org.xwiki.component.manager.ComponentManager) EntityReference(org.xwiki.model.reference.EntityReference) BaseObject(com.xpn.xwiki.objects.BaseObject) DocumentReference(org.xwiki.model.reference.DocumentReference) Test(org.junit.Test)

Example 2 with EntityReferenceSerializer

use of org.xwiki.model.reference.EntityReferenceSerializer in project xwiki-platform by xwiki.

the class TextAreaClass method getObjectDocumentSyntax.

/**
 * @return the syntax for the document to which the passed objects belongs to or the XWiki Syntax 1.0 if the object
 *         document cannot be retrieved
 */
private Syntax getObjectDocumentSyntax(BaseCollection object, XWikiContext context) {
    Syntax syntax;
    try {
        XWikiDocument doc = object.getOwnerDocument();
        if (doc == null) {
            doc = context.getWiki().getDocument(object.getDocumentReference(), context);
        }
        syntax = doc.getSyntax();
    } catch (Exception e) {
        // Used to convert a Document Reference to string (compact form without the wiki part if it matches the
        // current wiki).
        EntityReferenceSerializer<String> compactWikiEntityReferenceSerializer = Utils.getComponent(EntityReferenceSerializer.TYPE_STRING, "compactwiki");
        LOGGER.warn("Error while getting the syntax corresponding to object [" + compactWikiEntityReferenceSerializer.serialize(object.getDocumentReference()) + "]. Defaulting to using XWiki 1.0 syntax. Internal error [" + e.getMessage() + "]");
        syntax = Syntax.XWIKI_1_0;
    }
    return syntax;
}
Also used : EntityReferenceSerializer(org.xwiki.model.reference.EntityReferenceSerializer) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) Syntax(org.xwiki.rendering.syntax.Syntax) EditException(org.xwiki.edit.EditException)

Example 3 with EntityReferenceSerializer

use of org.xwiki.model.reference.EntityReferenceSerializer in project xwiki-platform by xwiki.

the class CreateActionRequestHandler method loadAvailableTemplateProviders.

/**
 * @param spaceReference the space to check if there are available templates for
 * @param context the context of the current request
 * @param templateClassReference the reference to the template provider class
 * @return the available template providers for the passed space, as {@link Document}s
 */
private List<Document> loadAvailableTemplateProviders(SpaceReference spaceReference, DocumentReference templateClassReference, XWikiContext context) {
    List<Document> templates = new ArrayList<>();
    try {
        QueryManager queryManager = Utils.getComponent((Type) QueryManager.class, "secure");
        Query query = queryManager.createQuery("from doc.object(XWiki.TemplateProviderClass) as template " + "where doc.fullName not like 'XWiki.TemplateProviderTemplate' " + "order by template.name", Query.XWQL);
        // TODO: Extend the above query to include a filter on the type and allowed spaces properties so we can
        // remove the java code below, thus improving performance by not loading all the documents, but only the
        // documents we need.
        List<XWikiDocument> recommendedTemplates = new ArrayList<>();
        List<String> templateProviderDocNames = query.execute();
        for (String templateProviderName : templateProviderDocNames) {
            // get the document and template provider object
            DocumentReference reference = getCurrentMixedResolver().resolve(templateProviderName);
            // Verify that the current user has the view right on the Template document
            if (!getAuthManager().hasAccess(Right.VIEW, reference)) {
                continue;
            }
            XWikiDocument templateDoc = context.getWiki().getDocument(reference, context);
            BaseObject templateObject = templateDoc.getXObject(templateClassReference);
            // Check the template provider's visibility restrictions.
            if (isTemplateProviderAllowedInSpace(templateObject, spaceReference, TP_VISIBILITY_RESTRICTIONS_PROPERTY)) {
                List<String> creationRestrictions = getTemplateProviderRestrictions(templateObject, TP_CREATION_RESTRICTIONS_PROPERTY);
                if (creationRestrictions.size() > 0 && isTemplateProviderAllowedInSpace(templateObject, spaceReference, TP_CREATION_RESTRICTIONS_PROPERTY)) {
                    // Consider providers that have creations restrictions matching the current space as
                    // "recommended" and handle them separately.
                    recommendedTemplates.add(templateDoc);
                } else {
                    // Other visible providers.
                    templates.add(new Document(templateDoc, context));
                }
            }
        }
        EntityReferenceSerializer<String> localSerializer = Utils.getComponent(EntityReferenceSerializer.TYPE_STRING, LOCAL_SERIALIZER_HINT);
        String spaceStringReference = localSerializer.serialize(spaceReference);
        // Sort the recommended providers and promote the most specific ones.
        recommendedTemplates.sort(Comparator.comparing((XWikiDocument templateProviderDocument) -> {
            BaseObject templateProviderObject = templateProviderDocument.getXObject(templateClassReference);
            // Look at any set creation restrictions.
            List<String> restrictions = getTemplateProviderRestrictions(templateProviderObject, TP_CREATION_RESTRICTIONS_PROPERTY);
            // Return the longest (max) matching restriction reference size as being the most specific.
            return restrictions.stream().filter(restriction -> matchesRestriction(spaceStringReference, restriction)).mapToInt(restriction -> {
                SpaceReferenceResolver<String> spaceResolver = Utils.getComponent(SpaceReferenceResolver.TYPE_STRING);
                SpaceReference restrictionSpaceReference = spaceResolver.resolve(restriction);
                // The specificity score.
                int specificity = restrictionSpaceReference.getReversedReferenceChain().size();
                return specificity;
            }).max().orElse(0);
        }).reversed());
        this.recommendedTemplateProviders = recommendedTemplates.stream().map(recommendedTemplate -> new Document(recommendedTemplate, context)).collect(Collectors.toList());
        // Give priority to the providers that that specify creation restrictions
        templates.addAll(0, recommendedTemplateProviders);
    } catch (Exception e) {
        LOGGER.warn("There was an error getting the available templates for space {0}", spaceReference, e);
    }
    return templates;
}
Also used : XWiki(com.xpn.xwiki.XWiki) XWikiException(com.xpn.xwiki.XWikiException) Right(org.xwiki.security.authorization.Right) Query(org.xwiki.query.Query) EntityReference(org.xwiki.model.reference.EntityReference) LoggerFactory(org.slf4j.LoggerFactory) SpaceReference(org.xwiki.model.reference.SpaceReference) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) ContextualAuthorizationManager(org.xwiki.security.authorization.ContextualAuthorizationManager) DocumentReferenceResolver(org.xwiki.model.reference.DocumentReferenceResolver) Map(java.util.Map) VelocityManager(org.xwiki.velocity.VelocityManager) ScriptContextManager(org.xwiki.script.ScriptContextManager) EntityType(org.xwiki.model.EntityType) EntityReferenceSerializer(org.xwiki.model.reference.EntityReferenceSerializer) Logger(org.slf4j.Logger) BaseObject(com.xpn.xwiki.objects.BaseObject) SpaceReferenceResolver(org.xwiki.model.reference.SpaceReferenceResolver) QueryManager(org.xwiki.query.QueryManager) Collectors(java.util.stream.Collectors) VelocityContext(org.apache.velocity.VelocityContext) Document(com.xpn.xwiki.api.Document) ScriptContext(javax.script.ScriptContext) EntityReferenceResolver(org.xwiki.model.reference.EntityReferenceResolver) List(java.util.List) Type(java.lang.reflect.Type) DocumentReference(org.xwiki.model.reference.DocumentReference) XWikiContext(com.xpn.xwiki.XWikiContext) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) Comparator(java.util.Comparator) Query(org.xwiki.query.Query) SpaceReference(org.xwiki.model.reference.SpaceReference) ArrayList(java.util.ArrayList) Document(com.xpn.xwiki.api.Document) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) XWikiException(com.xpn.xwiki.XWikiException) BaseObject(com.xpn.xwiki.objects.BaseObject) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) QueryManager(org.xwiki.query.QueryManager) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 4 with EntityReferenceSerializer

use of org.xwiki.model.reference.EntityReferenceSerializer in project xwiki-platform by xwiki.

the class LinkCheckerEventListenerTest method testOnEvent.

@Test
public void testOnEvent() throws Exception {
    final DocumentModelBridge documentModelBridge = getMockery().mock(DocumentModelBridge.class);
    final EntityReferenceSerializer serializer = getComponentManager().getInstance(EntityReferenceSerializer.TYPE_STRING);
    final DocumentReference reference = new DocumentReference("wiki", "space", "page");
    final LinkStateManager linkStateManager = getComponentManager().getInstance(LinkStateManager.class);
    final Map<String, Map<String, LinkState>> states = new HashMap<String, Map<String, LinkState>>();
    Map<String, LinkState> referenceStates1 = new HashMap<String, LinkState>();
    referenceStates1.put("wiki1:space1.page1", new LinkState(200, System.currentTimeMillis()));
    referenceStates1.put("wiki2:space2.page2", new LinkState(200, System.currentTimeMillis()));
    states.put("url1", referenceStates1);
    Map<String, LinkState> referenceStates2 = new HashMap<String, LinkState>();
    referenceStates2.put("wiki1:space1.page1", new LinkState(200, System.currentTimeMillis()));
    states.put("url2", referenceStates2);
    getMockery().checking(new Expectations() {

        {
            oneOf(documentModelBridge).getDocumentReference();
            will(returnValue(reference));
            oneOf(serializer).serialize(reference);
            will(returnValue("wiki1:space1.page1"));
            oneOf(linkStateManager).getLinkStates();
            will(returnValue(states));
        }
    });
    this.listener.onEvent(new DocumentUpdatingEvent(), documentModelBridge, null);
    Assert.assertEquals(1, states.size());
    Assert.assertEquals(1, states.get("url1").size());
    Assert.assertNull(states.get("url2"));
}
Also used : EntityReferenceSerializer(org.xwiki.model.reference.EntityReferenceSerializer) Expectations(org.jmock.Expectations) DocumentUpdatingEvent(org.xwiki.bridge.event.DocumentUpdatingEvent) LinkStateManager(org.xwiki.rendering.transformation.linkchecker.LinkStateManager) DocumentModelBridge(org.xwiki.bridge.DocumentModelBridge) HashMap(java.util.HashMap) HashMap(java.util.HashMap) Map(java.util.Map) DocumentReference(org.xwiki.model.reference.DocumentReference) LinkState(org.xwiki.rendering.transformation.linkchecker.LinkState) Test(org.junit.Test)

Aggregations

EntityReferenceSerializer (org.xwiki.model.reference.EntityReferenceSerializer)4 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)3 DocumentReference (org.xwiki.model.reference.DocumentReference)3 BaseObject (com.xpn.xwiki.objects.BaseObject)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 Test (org.junit.Test)2 EntityReference (org.xwiki.model.reference.EntityReference)2 XWiki (com.xpn.xwiki.XWiki)1 XWikiContext (com.xpn.xwiki.XWikiContext)1 XWikiException (com.xpn.xwiki.XWikiException)1 Document (com.xpn.xwiki.api.Document)1 BaseObjectReference (com.xpn.xwiki.objects.BaseObjectReference)1 Type (java.lang.reflect.Type)1 Comparator (java.util.Comparator)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Collectors (java.util.stream.Collectors)1 ScriptContext (javax.script.ScriptContext)1 StringUtils (org.apache.commons.lang3.StringUtils)1