Search in sources :

Example 1 with ResourceReference

use of org.xwiki.resource.ResourceReference in project xwiki-platform by xwiki.

the class DeleteAttachmentAction method getFileName.

/**
 * @return the filename of the attachment.
 */
private String getFileName() {
    // Extract the Attachment file name from the parsed request URL that was done before this Action is called
    ResourceReference resourceReference = Utils.getComponent(ResourceReferenceManager.class).getResourceReference();
    EntityResourceReference entityResource = (EntityResourceReference) resourceReference;
    return entityResource.getEntityReference().extractReference(EntityType.ATTACHMENT).getName();
}
Also used : ResourceReferenceManager(org.xwiki.resource.ResourceReferenceManager) EntityResourceReference(org.xwiki.resource.entity.EntityResourceReference) ResourceReference(org.xwiki.resource.ResourceReference) EntityResourceReference(org.xwiki.resource.entity.EntityResourceReference)

Example 2 with ResourceReference

use of org.xwiki.resource.ResourceReference in project xwiki-platform by xwiki.

the class XWiki method initializeResourceFromURL.

private static EntityResourceReference initializeResourceFromURL(XWikiContext context) throws XWikiException {
    // Extract the Entity Resource from the URL
    // TODO: This code should be put in an ExecutionContextInitializer but we couldn't do yet since this code
    // requires that the XWiki object be initialized first (the line above). Thus we'll be able to to move it only
    // after the XWiki init is done also in an ExecutionContextInitializer (and with priorities).
    @SuppressWarnings("deprecation") EntityResourceReference entityResourceReference;
    URL url = context.getURL();
    try {
        ExtendedURL extendedURL = new ExtendedURL(url, context.getRequest().getContextPath());
        ResourceTypeResolver<ExtendedURL> typeResolver = Utils.getComponent(new DefaultParameterizedType(null, ResourceTypeResolver.class, ExtendedURL.class));
        ResourceType type = typeResolver.resolve(extendedURL, Collections.<String, Object>emptyMap());
        ResourceReferenceResolver<ExtendedURL> resourceResolver = Utils.getComponent(new DefaultParameterizedType(null, ResourceReferenceResolver.class, ExtendedURL.class));
        ResourceReference reference = resourceResolver.resolve(extendedURL, type, Collections.<String, Object>emptyMap());
        entityResourceReference = reference instanceof EntityResourceReference ? (EntityResourceReference) reference : null;
    } catch (Exception e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION, String.format("Failed to extract Entity Resource Reference from URL [%s]", url), e);
    }
    Utils.getComponent(Execution.class).getContext().setProperty(ResourceReferenceManager.RESOURCE_CONTEXT_PROPERTY, entityResourceReference);
    return entityResourceReference;
}
Also used : ResourceReferenceResolver(org.xwiki.resource.ResourceReferenceResolver) EntityResourceReference(org.xwiki.resource.entity.EntityResourceReference) ResourceType(org.xwiki.resource.ResourceType) ExtendedURL(org.xwiki.url.ExtendedURL) ExtendedURL(org.xwiki.url.ExtendedURL) URL(java.net.URL) WikiManagerException(org.xwiki.wiki.manager.WikiManagerException) IOException(java.io.IOException) JobException(org.xwiki.job.JobException) ParseException(org.xwiki.rendering.parser.ParseException) QueryException(org.xwiki.query.QueryException) URIException(org.apache.commons.httpclient.URIException) InvocationTargetException(java.lang.reflect.InvocationTargetException) HibernateException(org.hibernate.HibernateException) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) NamingException(javax.naming.NamingException) FileNotFoundException(java.io.FileNotFoundException) MalformedURLException(java.net.MalformedURLException) ResourceTypeResolver(org.xwiki.resource.ResourceTypeResolver) ResourceReference(org.xwiki.resource.ResourceReference) EntityResourceReference(org.xwiki.resource.entity.EntityResourceReference) DefaultParameterizedType(org.xwiki.component.util.DefaultParameterizedType)

Example 3 with ResourceReference

use of org.xwiki.resource.ResourceReference in project xwiki-platform by xwiki.

the class DownloadActionTest method downloadWhenURLNotPointingToAttachment.

@Test
public void downloadWhenURLNotPointingToAttachment() throws XWikiException {
    ResourceReference rr = new EntityResourceReference(this.documentReference, EntityResourceAction.VIEW);
    when(this.resourceReferenceManager.getResourceReference()).thenReturn(rr);
    when(this.request.getRequestURI()).thenReturn("/xwiki/bin/download/space/page");
    try {
        this.action.render(this.oldcore.getXWikiContext());
        fail("Should have thrown an exception before reaching here");
    } catch (XWikiException expected) {
        assertEquals("Error number 11003 in 11: Attachment not found", expected.getMessage());
    }
}
Also used : EntityResourceReference(org.xwiki.resource.entity.EntityResourceReference) ResourceReference(org.xwiki.resource.ResourceReference) EntityResourceReference(org.xwiki.resource.entity.EntityResourceReference) XWikiException(com.xpn.xwiki.XWikiException) Test(org.junit.Test)

Example 4 with ResourceReference

use of org.xwiki.resource.ResourceReference in project xwiki-platform by xwiki.

the class ViewAttachRevAction method getFileName.

/**
 * @return the filename of the attachment.
 */
private String getFileName() {
    // Extract the Attachment file name from the parsed request URL that was done before this Action is called
    ResourceReference resourceReference = Utils.getComponent(ResourceReferenceManager.class).getResourceReference();
    EntityResourceReference entityResource = (EntityResourceReference) resourceReference;
    return entityResource.getEntityReference().extractReference(EntityType.ATTACHMENT).getName();
}
Also used : ResourceReferenceManager(org.xwiki.resource.ResourceReferenceManager) EntityResourceReference(org.xwiki.resource.entity.EntityResourceReference) EntityResourceReference(org.xwiki.resource.entity.EntityResourceReference) ResourceReference(org.xwiki.resource.ResourceReference)

Example 5 with ResourceReference

use of org.xwiki.resource.ResourceReference in project xwiki-platform by xwiki.

the class XWikiAction method execute.

public ActionForward execute(XWikiContext context) throws Exception {
    MonitorPlugin monitor = null;
    FileUploadPlugin fileupload = null;
    DefaultJobProgress actionProgress = null;
    ObservationManager om = Utils.getComponent(ObservationManager.class);
    Execution execution = Utils.getComponent(Execution.class);
    String docName = "";
    boolean debug = StringUtils.equals(context.getRequest().get("debug"), "true");
    try {
        String action = context.getAction();
        // Start progress
        if (debug && om != null && execution != null) {
            actionProgress = new DefaultJobProgress(context.getURL().toExternalForm());
            om.addListener(new WrappedThreadEventListener(actionProgress));
            // Register the action progress in the context
            ExecutionContext econtext = execution.getContext();
            if (econtext != null) {
                econtext.setProperty(XWikiAction.ACTION_PROGRESS, actionProgress);
            }
        }
        getProgress().pushLevelProgress(2, this);
        getProgress().startStep(this, "Get XWiki instance");
        // Initialize context.getWiki() with the main wiki
        XWiki xwiki;
        // Verify that the requested wiki exists
        try {
            xwiki = XWiki.getXWiki(this.waitForXWikiInitialization, context);
            // If XWiki is still initializing display initialization template
            if (xwiki == null) {
                // Display initialization template
                renderInit(context);
                // Initialization template has been displayed, stop here.
                return null;
            }
        } catch (XWikiException e) {
            // redirects. If there are none, then we display the specific error template.
            if (e.getCode() == XWikiException.ERROR_XWIKI_DOES_NOT_EXIST) {
                xwiki = XWiki.getMainXWiki(context);
                // Initialize the url factory
                XWikiURLFactory urlf = xwiki.getURLFactoryService().createURLFactory(context.getMode(), context);
                context.setURLFactory(urlf);
                // Initialize the velocity context and its bindings so that it may be used in the velocity templates
                // that we
                // are parsing below.
                VelocityManager velocityManager = Utils.getComponent(VelocityManager.class);
                VelocityContext vcontext = velocityManager.getVelocityContext();
                if (!sendGlobalRedirect(context.getResponse(), context.getURL().toString(), context)) {
                    // Starting XWiki 5.0M2, 'xwiki.virtual.redirect' was removed. Warn users still using it.
                    if (!StringUtils.isEmpty(context.getWiki().Param("xwiki.virtual.redirect"))) {
                        LOGGER.warn(String.format("%s %s", "'xwiki.virtual.redirect' is no longer supported.", "Please update your configuration and/or see XWIKI-8914 for more details."));
                    }
                    // Display the error template only for actions that are not ignored
                    if (!ACTIONS_IGNORED_WHEN_WIKI_DOES_NOT_EXIST.contains(action)) {
                        // Add localization resources to the context
                        xwiki.prepareResources(context);
                        // Set the main home page in the main space of the main wiki as the current requested entity
                        // since we cannot set the non existing one as it would generate errors obviously...
                        EntityReferenceValueProvider valueProvider = Utils.getComponent(EntityReferenceValueProvider.class);
                        xwiki.setPhonyDocument(new DocumentReference(valueProvider.getDefaultValue(EntityType.WIKI), valueProvider.getDefaultValue(EntityType.SPACE), valueProvider.getDefaultValue(EntityType.DOCUMENT)), context, vcontext);
                        // Parse the error template
                        Utils.parseTemplate(context.getWiki().Param("xwiki.wiki_exception", "wikidoesnotexist"), context);
                        // Error template was displayed, stop here.
                        return null;
                    }
                // At this point, we allow regular execution of the ignored action because even if the wiki
                // does not exist, we still need to allow UI resources to be retrieved (from the filesystem
                // and the main wiki) or our error template will not be rendered properly.
                // Proceed with serving the main wiki
                } else {
                    // Global redirect was executed, stop here.
                    return null;
                }
            } else {
                LOGGER.error("Uncaught exception during XWiki initialisation:", e);
                throw e;
            }
        }
        // Send global redirection (if any)
        if (sendGlobalRedirect(context.getResponse(), context.getURL().toString(), context)) {
            return null;
        }
        XWikiURLFactory urlf = xwiki.getURLFactoryService().createURLFactory(context.getMode(), context);
        context.setURLFactory(urlf);
        // Handle ability to enter space URLs and convert them to page URLs (Nested Documents)
        if (redirectSpaceURLs(action, urlf, xwiki, context)) {
            return null;
        }
        String sajax = context.getRequest().get("ajax");
        boolean ajax = false;
        if (sajax != null && !sajax.trim().equals("") && !sajax.equals("0")) {
            ajax = true;
        }
        context.put("ajax", ajax);
        if (monitor != null) {
            monitor.startTimer("request");
        }
        getProgress().startStep(this, "Execute request");
        VelocityManager velocityManager = Utils.getComponent(VelocityManager.class);
        VelocityContext vcontext = velocityManager.getVelocityContext();
        getProgress().pushLevelProgress(7, this);
        boolean eventSent = false;
        try {
            getProgress().startStep(this, "Prepare documents and put them in the context");
            // Prepare documents and put them in the context
            if (!xwiki.prepareDocuments(context.getRequest(), context, vcontext)) {
                return null;
            }
            // Start monitoring timer
            monitor = (MonitorPlugin) xwiki.getPlugin("monitor", context);
            if (monitor != null) {
                monitor.startRequest("", context.getAction(), context.getURL());
                monitor.startTimer("multipart");
            }
            getProgress().startStep(this, "Parses multipart");
            // Parses multipart so that params in multipart are available for all actions
            fileupload = Utils.handleMultipart(context.getRequest().getHttpServletRequest(), context);
            if (monitor != null) {
                monitor.endTimer("multipart");
            }
            if (monitor != null) {
                monitor.setWikiPage(context.getDoc().getFullName());
            }
            getProgress().startStep(this, "Send [" + context.getAction() + "] action start event");
            // and there won't be a need for the context.
            try {
                ActionExecutingEvent event = new ActionExecutingEvent(context.getAction());
                om.notify(event, context.getDoc(), context);
                eventSent = true;
                if (event.isCanceled()) {
                    // TODO: do something special ?
                    return null;
                }
            } catch (Throwable ex) {
                LOGGER.error("Cannot send action notifications for document [" + context.getDoc() + " using action [" + context.getAction() + "]", ex);
            }
            if (monitor != null) {
                monitor.endTimer("prenotify");
            }
            // Call the Actions
            getProgress().startStep(this, "Search and execute entity resource handler");
            // Call the new Entity Resource Reference Handler.
            ResourceReferenceHandler entityResourceReferenceHandler = Utils.getComponent(new DefaultParameterizedType(null, ResourceReferenceHandler.class, ResourceType.class), "bin");
            ResourceReference resourceReference = Utils.getComponent(ResourceReferenceManager.class).getResourceReference();
            try {
                entityResourceReferenceHandler.handle(resourceReference, DefaultResourceReferenceHandlerChain.EMPTY);
                // Don't let the old actions kick in!
                return null;
            } catch (NotFoundResourceHandlerException e) {
            // No Entity Resource Action has been found. Don't do anything and let it go through
            // so that the old Action system kicks in...
            } catch (Throwable e) {
                // Some real failure, log it since it's a problem but still allow the old Action system a chance
                // to do something...
                LOGGER.error("Failed to handle Action for Resource [{}]", resourceReference, e);
            }
            getProgress().startStep(this, "Execute action render");
            // Handle the XWiki.RedirectClass object that can be attached to the current document
            boolean hasRedirect = false;
            if (handleRedirectObject) {
                hasRedirect = handleRedirectObject(context);
            }
            // Then call the old Actions for backward compatibility (and because a lot of them have not been
            // migrated to new Actions yet).
            String renderResult = null;
            XWikiDocument doc = context.getDoc();
            docName = doc.getFullName();
            if (!hasRedirect && action(context)) {
                renderResult = render(context);
            }
            if (renderResult != null) {
                if (doc.isNew() && "view".equals(context.getAction()) && !"recyclebin".equals(context.getRequest().get("viewer")) && !"children".equals(context.getRequest().get("viewer")) && !"siblings".equals(context.getRequest().get("viewer"))) {
                    String page = Utils.getPage(context.getRequest(), "docdoesnotexist");
                    getProgress().startStep(this, "Execute template [" + page + "]");
                    Utils.parseTemplate(page, context);
                } else {
                    String page = Utils.getPage(context.getRequest(), renderResult);
                    getProgress().startStep(this, "Execute template [" + page + "]");
                    Utils.parseTemplate(page, !page.equals("direct"), context);
                }
            }
            return null;
        } catch (Throwable e) {
            if (e instanceof IOException) {
                e = new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION, "Exception while sending response", e);
            }
            if (!(e instanceof XWikiException)) {
                e = new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_UNKNOWN, "Uncaught exception", e);
            }
            try {
                XWikiException xex = (XWikiException) e;
                if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION) {
                    // Connection aborted from the client side, there's not much we can do on the server side. We
                    // simply ignore it.
                    LOGGER.debug("Connection aborted", e);
                    // We don't write any other message to the response, as the connection is broken, anyway.
                    return null;
                } else if (xex.getCode() == XWikiException.ERROR_XWIKI_ACCESS_DENIED) {
                    Utils.parseTemplate(context.getWiki().Param("xwiki.access_exception", "accessdenied"), context);
                    return null;
                } else if (xex.getCode() == XWikiException.ERROR_XWIKI_USER_INACTIVE) {
                    Utils.parseTemplate(context.getWiki().Param("xwiki.user_exception", "userinactive"), context);
                    return null;
                } else if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_ATTACHMENT_NOT_FOUND) {
                    context.put("message", "attachmentdoesnotexist");
                    Utils.parseTemplate(context.getWiki().Param("xwiki.attachment_exception", "attachmentdoesnotexist"), context);
                    return null;
                } else if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION) {
                    vcontext.put("message", localizePlainOrKey("platform.core.invalidUrl"));
                    xwiki.setPhonyDocument(xwiki.getDefaultSpace(context) + "." + xwiki.getDefaultPage(context), context, vcontext);
                    context.getResponse().setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    Utils.parseTemplate(context.getWiki().Param("xwiki.invalid_url_exception", "error"), context);
                    return null;
                }
                vcontext.put("exp", e);
                if (LOGGER.isWarnEnabled()) {
                    // connection.
                    if (ExceptionUtils.getRootCauseMessage(e).equals("IOException: Broken pipe")) {
                        return null;
                    }
                    LOGGER.warn("Uncaught exception: " + e.getMessage(), e);
                }
                // If the request is an AJAX request, we don't return a whole HTML page, but just the exception
                // inline.
                String exceptionTemplate = ajax ? "exceptioninline" : "exception";
                Utils.parseTemplate(Utils.getPage(context.getRequest(), exceptionTemplate), context);
                return null;
            } catch (XWikiException ex) {
                if (ex.getCode() == XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION) {
                    LOGGER.error("Connection aborted");
                }
            } catch (Exception e2) {
                // I hope this never happens
                LOGGER.error("Uncaught exceptions (inner): ", e);
                LOGGER.error("Uncaught exceptions (outer): ", e2);
            }
            return null;
        } finally {
            // Let's make sure we have flushed content and closed
            try {
                context.getResponse().getWriter().flush();
            } catch (Throwable e) {
            // This might happen if the connection was closed, for example.
            // If we can't flush, then there's nothing more we can send to the client.
            }
            if (monitor != null) {
                monitor.endTimer("request");
                monitor.startTimer("notify");
            }
            if (eventSent) {
                // and there won't be a need for the context.
                try {
                    om.notify(new ActionExecutedEvent(context.getAction()), context.getDoc(), context);
                } catch (Throwable ex) {
                    LOGGER.error("Cannot send action notifications for document [" + docName + " using action [" + context.getAction() + "]", ex);
                }
            }
            if (monitor != null) {
                monitor.endTimer("notify");
            }
            getProgress().startStep(this, "Cleanup database connections");
            // Make sure we cleanup database connections
            // There could be cases where we have some
            xwiki.getStore().cleanUp(context);
            getProgress().popLevelProgress(this);
        }
    } finally {
        // End request
        if (monitor != null) {
            monitor.endRequest();
        }
        // Stop progress
        if (actionProgress != null) {
            getProgress().popLevelProgress(this);
            om.removeListener(actionProgress.getName());
        }
        if (fileupload != null) {
            fileupload.cleanFileList(context);
        }
    }
}
Also used : ResourceReferenceHandler(org.xwiki.resource.ResourceReferenceHandler) EntityReferenceValueProvider(org.xwiki.model.reference.EntityReferenceValueProvider) VelocityContext(org.apache.velocity.VelocityContext) ObservationManager(org.xwiki.observation.ObservationManager) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) FileUploadPlugin(com.xpn.xwiki.plugin.fileupload.FileUploadPlugin) Execution(org.xwiki.context.Execution) DefaultJobProgress(org.xwiki.job.internal.DefaultJobProgress) ActionExecutingEvent(org.xwiki.bridge.event.ActionExecutingEvent) ResourceReference(org.xwiki.resource.ResourceReference) EntityResourceReference(org.xwiki.resource.entity.EntityResourceReference) XWikiException(com.xpn.xwiki.XWikiException) DocumentReference(org.xwiki.model.reference.DocumentReference) MonitorPlugin(com.xpn.xwiki.monitor.api.MonitorPlugin) NotFoundResourceHandlerException(org.xwiki.resource.NotFoundResourceHandlerException) XWiki(com.xpn.xwiki.XWiki) ResourceType(org.xwiki.resource.ResourceType) IOException(java.io.IOException) WrappedThreadEventListener(org.xwiki.observation.WrappedThreadEventListener) XWikiException(com.xpn.xwiki.XWikiException) ServletException(javax.servlet.ServletException) ServletContainerException(org.xwiki.container.servlet.ServletContainerException) NotFoundResourceHandlerException(org.xwiki.resource.NotFoundResourceHandlerException) IOException(java.io.IOException) ExecutionContext(org.xwiki.context.ExecutionContext) VelocityManager(org.xwiki.velocity.VelocityManager) ActionExecutedEvent(org.xwiki.bridge.event.ActionExecutedEvent) ResourceReferenceManager(org.xwiki.resource.ResourceReferenceManager) DefaultParameterizedType(org.xwiki.component.util.DefaultParameterizedType)

Aggregations

ResourceReference (org.xwiki.resource.ResourceReference)14 EntityResourceReference (org.xwiki.resource.entity.EntityResourceReference)11 ResourceReferenceManager (org.xwiki.resource.ResourceReferenceManager)6 DefaultParameterizedType (org.xwiki.component.util.DefaultParameterizedType)4 ResourceType (org.xwiki.resource.ResourceType)4 XWikiException (com.xpn.xwiki.XWikiException)3 IOException (java.io.IOException)3 Test (org.junit.Test)3 EntityReference (org.xwiki.model.reference.EntityReference)3 ExtendedURL (org.xwiki.url.ExtendedURL)3 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)2 URL (java.net.URL)2 ComponentLookupException (org.xwiki.component.manager.ComponentLookupException)2 ExecutionContext (org.xwiki.context.ExecutionContext)2 DocumentReference (org.xwiki.model.reference.DocumentReference)2 XWiki (com.xpn.xwiki.XWiki)1 MonitorPlugin (com.xpn.xwiki.monitor.api.MonitorPlugin)1 BaseObject (com.xpn.xwiki.objects.BaseObject)1 FileUploadPlugin (com.xpn.xwiki.plugin.fileupload.FileUploadPlugin)1 FileNotFoundException (java.io.FileNotFoundException)1