Search in sources :

Example 11 with DocumentReference

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

the class AnnotationsRESTResource method doPostAnnotation.

/**
 * Add annotation to a given page.
 *
 * @param wiki the wiki of the document to add annotation on
 * @param space the space of the document to add annotation on
 * @param page the name of the document to add annotation on
 * @param request the request object with the annotation to be added
 * @return AnnotationRequestResponse, responseCode = 0 if no error
 * @throws XWikiRestException when failing to parse space
 */
@POST
public AnnotationResponse doPostAnnotation(@PathParam("wikiName") String wiki, @PathParam("spaceName") String space, @PathParam("pageName") String page, AnnotationAddRequest request) throws XWikiRestException {
    try {
        DocumentReference documentReference = new DocumentReference(wiki, parseSpaceSegments(space), page);
        // Initialize the context with the correct value.
        updateContext(documentReference);
        String documentName = referenceSerializer.serialize(documentReference);
        // check access to this function
        if (!annotationRightService.canAddAnnotation(documentName, getXWikiUser())) {
            throw new WebApplicationException(Status.UNAUTHORIZED);
        }
        // add the annotation
        Map<String, Object> annotationMetadata = getMap(request.getAnnotation());
        annotationService.addAnnotation(documentName, request.getSelection(), request.getSelectionContext(), request.getSelectionOffset(), getXWikiUser(), annotationMetadata);
        // and then return the annotated content, as specified by the annotation request
        AnnotationResponse response = getSuccessResponseWithAnnotatedContent(documentName, request);
        return response;
    } catch (AnnotationServiceException e) {
        getLogger().error(e.getMessage(), e);
        return getErrorResponse(e);
    } catch (XWikiException e) {
        getLogger().error(e.getMessage(), e);
        return getErrorResponse(e);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) AnnotationServiceException(org.xwiki.annotation.AnnotationServiceException) AnnotationResponse(org.xwiki.annotation.rest.model.jaxb.AnnotationResponse) DocumentReference(org.xwiki.model.reference.DocumentReference) XWikiException(com.xpn.xwiki.XWikiException) POST(javax.ws.rs.POST)

Example 12 with DocumentReference

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

the class AnnotationsRESTResource method doGetAnnotatedContent.

/**
 * @param wiki the wiki of the document to get annotations for
 * @param space the space of the document to get annotations for
 * @param page the name of the document to get annotation for
 * @return annotations of a given XWiki page. Note that we're returning a response holding the AnnotatedContent
 *         instead of an AnnotatedContent object because we need to be able to set custom expire fields to prevent
 *         IE from caching this resource.
 * @throws XWikiRestException when failing to parse space
 */
@GET
public Response doGetAnnotatedContent(@PathParam("spaceName") String space, @PathParam("pageName") String page, @PathParam("wikiName") String wiki) throws XWikiRestException {
    try {
        DocumentReference documentReference = new DocumentReference(wiki, parseSpaceSegments(space), page);
        // Initialize the context with the correct value.
        updateContext(documentReference);
        String documentName = referenceSerializer.serialize(documentReference);
        // check access to this function
        if (!annotationRightService.canViewAnnotatedTarget(documentName, getXWikiUser())) {
            throw new WebApplicationException(Status.UNAUTHORIZED);
        }
        // Manually construct the Annotation request entity
        // Historically it used to be passed as method argument, but this only worked because of a bug in
        // earlier version of Restlet (1.1.x) ; the JAX-RS specification explicitly states that such entity
        // parameters "[are] mapped from the request entity body.", and thus cannot be passed to a GET resource.
        // See paragraph 3.3.2.1 "Entity Parameters" of JAX-RS 1.1 specification.
        Form form = Request.getCurrent().getResourceRef().getQueryAsForm();
        AnnotationRequest request = new AnnotationRequest();
        AnnotationFieldCollection fields = new AnnotationFieldCollection();
        List<AnnotationField> annotationFields = new ArrayList<AnnotationField>();
        AnnotationRequest.Request requestedFields = new AnnotationRequest.Request();
        for (String name : form.getNames()) {
            if (StringUtils.startsWith(name, ANNOTATION_REQUEST_FILTER_PARAMETER_PREFIX)) {
                for (String value : form.getValuesArray(name)) {
                    AnnotationField field = new AnnotationField();
                    field.setName(StringUtils.substringAfter(name, ANNOTATION_REQUEST_FILTER_PARAMETER_PREFIX));
                    field.setValue(value);
                    annotationFields.add(field);
                }
            } else if (StringUtils.equals(name, ANNOTATION_REQUEST_REQUESTED_FIELD_PARAMETER)) {
                requestedFields.getFields().addAll(Arrays.asList(form.getValuesArray(name)));
            }
        }
        request.setRequest(requestedFields);
        fields.getFields().addAll(annotationFields);
        request.setFilter(fields);
        AnnotationResponse response = getSuccessResponseWithAnnotatedContent(documentName, request);
        // make this content expire now because cacheControl is not implemented in this version of restlet
        return Response.ok(response).expires(new Date()).build();
    } catch (AnnotationServiceException e) {
        getLogger().error(e.getMessage(), e);
        return Response.ok(getErrorResponse(e)).build();
    } catch (XWikiException e) {
        getLogger().error(e.getMessage(), e);
        return Response.ok(getErrorResponse(e)).build();
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) AnnotationRequest(org.xwiki.annotation.rest.model.jaxb.AnnotationRequest) AnnotationServiceException(org.xwiki.annotation.AnnotationServiceException) Form(org.restlet.data.Form) ArrayList(java.util.ArrayList) AnnotationAddRequest(org.xwiki.annotation.rest.model.jaxb.AnnotationAddRequest) AnnotationRequest(org.xwiki.annotation.rest.model.jaxb.AnnotationRequest) Request(org.restlet.Request) AnnotationResponse(org.xwiki.annotation.rest.model.jaxb.AnnotationResponse) Date(java.util.Date) AnnotationField(org.xwiki.annotation.rest.model.jaxb.AnnotationField) AnnotationFieldCollection(org.xwiki.annotation.rest.model.jaxb.AnnotationFieldCollection) DocumentReference(org.xwiki.model.reference.DocumentReference) XWikiException(com.xpn.xwiki.XWikiException) GET(javax.ws.rs.GET)

Example 13 with DocumentReference

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

the class WikiEventListener method onWikiCreated.

private void onWikiCreated(WikiCreatedEvent event, XWikiContext context) {
    String namespace = "wiki:" + event.getWikiId();
    Collection<InstalledExtension> installedExtensions = this.installedRepository.getInstalledExtensions(null);
    InstallRequest installRequest = new InstallRequest();
    DocumentReference userReference = context.getUserReference();
    if (userReference != null) {
        installRequest.setProperty(PROPERTY_USER_REFERENCE, userReference);
        // We set the string value because the extension repository doesn't know how to serialize/parse an extension
        // property whose value is a DocumentReference, and adding support for it requires considerable refactoring
        // because ExtensionPropertySerializers are not components (they are currently hard-coded).
        installRequest.setExtensionProperty(PROPERTY_USER_REFERENCE, userReference.toString());
    }
    installRequest.setVerbose(false);
    // TODO: make it interactive ? (require wiki creation to be job based)
    installRequest.setInteractive(false);
    ExtensionHandler xarHandler = this.xarHandlerProvider.get();
    for (InstalledExtension installedExtension : installedExtensions) {
        if (installedExtension.getType().equals(XarExtensionHandler.TYPE)) {
            installRequest.addExtension(installedExtension.getId());
            try {
                xarHandler.install(installedExtension, namespace, installRequest);
            } catch (InstallException e) {
                this.logger.error("Failed to import extension [{}] in wiki [{}]", installedExtension, event.getWikiId(), e);
            }
        }
    }
}
Also used : InstalledExtension(org.xwiki.extension.InstalledExtension) InstallRequest(org.xwiki.extension.job.InstallRequest) ExtensionHandler(org.xwiki.extension.handler.ExtensionHandler) InstallException(org.xwiki.extension.InstallException) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 14 with DocumentReference

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

the class XarExtensionHandler method initJobPackageConfiguration.

private void initJobPackageConfiguration(Request request, boolean defaultConflict) throws InterruptedException {
    ExecutionContext context = this.execution.getContext();
    if (context != null && context.getProperty(CONTEXTKEY_PACKAGECONFIGURATION) == null) {
        Job currentJob = null;
        try {
            currentJob = this.componentManager.<JobContext>getInstance(JobContext.class).getCurrentJob();
        } catch (Exception e) {
            this.logger.error("Failed to lookup JobContext, it will be impossible to do interactive install");
        }
        if (currentJob != null) {
            PackageConfiguration configuration = new PackageConfiguration();
            context.setProperty(CONTEXTKEY_PACKAGECONFIGURATION, configuration);
            DocumentReference userReference = getRequestUserReference(AbstractExtensionValidator.PROPERTY_USERREFERENCE, request);
            configuration.setInteractive(request.isInteractive());
            configuration.setUser(userReference);
            configuration.setVerbose(request.isVerbose());
            configuration.setSkipMandatorytDocuments(true);
            configuration.setXarExtensionPlan(getXARExtensionPlan());
            configuration.setJobStatus(currentJob.getStatus());
            // Non blocker conflicts
            configuration.setConflictAction(ConflictType.CURRENT_DELETED, request.getProperty(ConflictQuestion.REQUEST_CONFLICT_DEFAULTANSWER_CURRENT_DELETED), GlobalAction.CURRENT);
            configuration.setConflictAction(ConflictType.MERGE_SUCCESS, request.getProperty(ConflictQuestion.REQUEST_CONFLICT_DEFAULTANSWER_MERGE_SUCCESS), GlobalAction.MERGED);
            // Blocker conflicts
            configuration.setConflictAction(ConflictType.CURRENT_EXIST, request.getProperty(ConflictQuestion.REQUEST_CONFLICT_DEFAULTANSWER_CURRENT_EXIST), configuration.isInteractive() ? GlobalAction.ASK : GlobalAction.NEXT);
            configuration.setConflictAction(ConflictType.MERGE_FAILURE, request.getProperty(ConflictQuestion.REQUEST_CONFLICT_DEFAULTANSWER_MERGE_FAILURE), configuration.isInteractive() ? GlobalAction.ASK : GlobalAction.MERGED);
            // If user asked to be asked about conflict behavior
            if (defaultConflict && currentJob.getStatus().getRequest().isInteractive()) {
                XWikiContext xcontext = xcontextProvider.get();
                // Make sure the context has the right user
                xcontext.setUserReference(userReference);
                int extensionConflictSetup = NumberUtils.toInt(xcontext.getWiki().getUserPreference("extensionConflictSetup", xcontext), 0);
                if (extensionConflictSetup == 1) {
                    DefaultConflictActionQuestion question = new DefaultConflictActionQuestion(configuration);
                    currentJob.getStatus().ask(question, 1, TimeUnit.HOURS);
                }
            }
        }
    }
}
Also used : ExecutionContext(org.xwiki.context.ExecutionContext) DefaultConflictActionQuestion(org.xwiki.extension.xar.question.DefaultConflictActionQuestion) XWikiContext(com.xpn.xwiki.XWikiContext) JobContext(org.xwiki.job.JobContext) Job(org.xwiki.job.Job) AbstractExtensionJob(org.xwiki.extension.job.internal.AbstractExtensionJob) PackageConfiguration(org.xwiki.extension.xar.internal.handler.packager.PackageConfiguration) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) ExtensionException(org.xwiki.extension.ExtensionException) IOException(java.io.IOException) UninstallException(org.xwiki.extension.UninstallException) InstallException(org.xwiki.extension.InstallException) XarException(org.xwiki.xar.XarException) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 15 with DocumentReference

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

the class DocumentMergeImporter method askDocumentToSave.

private XWikiDocument askDocumentToSave(XWikiDocument currentDocument, XWikiDocument previousDocument, XWikiDocument nextDocument, XWikiDocument mergedDocument, PackageConfiguration configuration, MergeResult documentMergeResult) {
    // Indicate future author to whoever is going to answer the question
    if (currentDocument != null) {
        nextDocument.setCreatorReference(currentDocument.getCreatorReference());
    }
    if (mergedDocument != null) {
        mergedDocument.setCreatorReference(currentDocument.getCreatorReference());
    }
    DocumentReference userReference = configuration != null ? configuration.getUserReference() : null;
    if (userReference != null) {
        nextDocument.setAuthorReference(userReference);
        nextDocument.setContentAuthorReference(userReference);
        for (XWikiAttachment attachment : nextDocument.getAttachmentList()) {
            attachment.setAuthorReference(nextDocument.getAuthorReference());
        }
        if (mergedDocument != null) {
            mergedDocument.setAuthorReference(userReference);
            mergedDocument.setContentAuthorReference(userReference);
            for (XWikiAttachment attachment : mergedDocument.getAttachmentList()) {
                if (attachment.isContentDirty()) {
                    attachment.setAuthorReference(mergedDocument.getAuthorReference());
                }
            }
        }
    }
    // Calculate the conflict type
    ConflictQuestion.ConflictType type;
    if (previousDocument == null) {
        type = ConflictQuestion.ConflictType.CURRENT_EXIST;
    } else if (currentDocument == null) {
        type = ConflictQuestion.ConflictType.CURRENT_DELETED;
    } else if (documentMergeResult != null) {
        if (!documentMergeResult.getLog().getLogs(LogLevel.ERROR).isEmpty()) {
            type = ConflictQuestion.ConflictType.MERGE_FAILURE;
        } else {
            type = ConflictQuestion.ConflictType.MERGE_SUCCESS;
        }
    } else {
        type = null;
    }
    // Create a question
    ConflictQuestion question = new ConflictQuestion(currentDocument, previousDocument, nextDocument, mergedDocument, type);
    // Find the answer
    GlobalAction contextAction = getMergeConflictAnswer(question.getType(), configuration);
    if (contextAction != null && contextAction != GlobalAction.ASK) {
        question.setGlobalAction(contextAction);
    } else if (configuration != null && configuration.getJobStatus() != null && configuration.isInteractive()) {
        try {
            // Ask what to do
            configuration.getJobStatus().ask(question);
            if (question.isAlways()) {
                setMergeConflictAnswer(question.getType(), question.getGlobalAction());
            }
        } catch (InterruptedException e) {
        // TODO: log something ?
        }
    }
    // Find the XWikiDocument to save
    XWikiDocument documentToSave;
    switch(question.getGlobalAction()) {
        case CURRENT:
            documentToSave = currentDocument;
            break;
        case NEXT:
            documentToSave = nextDocument;
            break;
        case PREVIOUS:
            documentToSave = previousDocument;
            break;
        case CUSTOM:
            documentToSave = question.getCustomDocument() != null ? question.getCustomDocument() : mergedDocument;
            break;
        default:
            documentToSave = mergedDocument;
            break;
    }
    return documentToSave;
}
Also used : XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) GlobalAction(org.xwiki.extension.xar.question.ConflictQuestion.GlobalAction) DocumentReference(org.xwiki.model.reference.DocumentReference) LocalDocumentReference(org.xwiki.model.reference.LocalDocumentReference) ConflictQuestion(org.xwiki.extension.xar.question.ConflictQuestion)

Aggregations

DocumentReference (org.xwiki.model.reference.DocumentReference)1324 Test (org.junit.Test)711 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)482 BaseObject (com.xpn.xwiki.objects.BaseObject)250 XWikiContext (com.xpn.xwiki.XWikiContext)186 LocalDocumentReference (org.xwiki.model.reference.LocalDocumentReference)157 ArrayList (java.util.ArrayList)128 WikiReference (org.xwiki.model.reference.WikiReference)127 XWikiException (com.xpn.xwiki.XWikiException)121 EntityReference (org.xwiki.model.reference.EntityReference)113 SpaceReference (org.xwiki.model.reference.SpaceReference)96 XWiki (com.xpn.xwiki.XWiki)82 HashMap (java.util.HashMap)54 XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)52 Expectations (org.jmock.Expectations)50 Before (org.junit.Before)50 DocumentModelBridge (org.xwiki.bridge.DocumentModelBridge)46 BaseClass (com.xpn.xwiki.objects.classes.BaseClass)45 AttachmentReference (org.xwiki.model.reference.AttachmentReference)44 Date (java.util.Date)42