Search in sources :

Example 31 with PortalResponse

use of com.enonic.xp.portal.PortalResponse in project xp by enonic.

the class ImageHandlerWorker method execute.

@Override
public PortalResponse execute() throws Exception {
    final Media content = getImage(this.contentId);
    final String contentName = content.getName().toString();
    final boolean contentNameEquals = contentName.equals(this.name);
    if (!(contentNameEquals || contentName.equals(Files.getNameWithoutExtension(this.name)))) {
        throw WebException.notFound(String.format("Image [%s] not found for content [%s]", this.name, this.contentId));
    }
    final Attachment attachment = content.getMediaAttachment();
    if (attachment == null) {
        throw WebException.notFound(String.format("Attachment [%s] not found", content.getName()));
    }
    final BinaryReference binaryReference = attachment.getBinaryReference();
    final ByteSource binary = this.contentService.getBinary(this.contentId, binaryReference);
    if (binary == null) {
        throw WebException.notFound(String.format("Binary [%s] not found for content [%s]", binaryReference, this.contentId));
    }
    if (request.getMethod() == HttpMethod.OPTIONS) {
        // it will be handled by default OPTIONS handler in BaseWebHandler
        return PortalResponse.create().status(HttpStatus.METHOD_NOT_ALLOWED).build();
    }
    final String attachmentMimeType = attachment.getMimeType();
    final PortalResponse.Builder portalResponse = PortalResponse.create();
    if ("svgz".equals(attachment.getExtension())) {
        portalResponse.contentType(MediaType.SVG_UTF_8.withoutParameters());
        portalResponse.header("Content-Encoding", "gzip");
        portalResponse.body(binary);
    } else if (attachmentMimeType.equals("image/svg+xml") || attachmentMimeType.equals("image/gif")) {
        portalResponse.contentType(MediaType.parse(attachmentMimeType));
        portalResponse.body(binary);
    } else {
        final ImageOrientation imageOrientation = Objects.requireNonNullElseGet(content.getOrientation(), () -> Objects.requireNonNullElse(mediaInfoService.getImageOrientation(binary), ImageOrientation.TopLeft));
        final MediaType mimeType = contentNameEquals ? MediaType.parse(attachmentMimeType) : MediaTypes.instance().fromFile(this.name);
        portalResponse.contentType(mimeType);
        try {
            final ReadImageParams readImageParams = ReadImageParams.newImageParams().contentId(this.contentId).binaryReference(binaryReference).cropping(content.getCropping()).scaleParams(this.scaleParams).focalPoint(content.getFocalPoint()).filterParam(this.filterParam).backgroundColor(getBackgroundColor()).mimeType(mimeType.toString()).quality(getImageQuality()).orientation(imageOrientation).build();
            portalResponse.body(this.imageService.readImage(readImageParams));
        } catch (IllegalArgumentException e) {
            throw new WebException(HttpStatus.BAD_REQUEST, "Invalid parameters", e);
        } catch (ThrottlingException e) {
            throw new WebException(HttpStatus.TOO_MANY_REQUESTS, "Try again later", e);
        }
    }
    if (!nullToEmpty(this.fingerprint).isBlank()) {
        final boolean isPublic = content.getPermissions().isAllowedFor(RoleKeys.EVERYONE, Permission.READ) && ContentConstants.BRANCH_MASTER.equals(request.getBranch());
        final String cacheControlHeaderConfig = isPublic ? publicCacheControlHeaderConfig : privateCacheControlHeaderConfig;
        if (!nullToEmpty(cacheControlHeaderConfig).isBlank() && this.fingerprint.equals(resolveHash(content))) {
            portalResponse.header(HttpHeaders.CACHE_CONTROL, cacheControlHeaderConfig);
        }
    }
    final Trace trace = Tracer.current();
    if (trace != null) {
        trace.put("contentPath", content.getPath());
        trace.put("type", "image");
    }
    return portalResponse.build();
}
Also used : WebException(com.enonic.xp.web.WebException) Media(com.enonic.xp.content.Media) Attachment(com.enonic.xp.attachment.Attachment) BinaryReference(com.enonic.xp.util.BinaryReference) ImageOrientation(com.enonic.xp.media.ImageOrientation) ReadImageParams(com.enonic.xp.image.ReadImageParams) Trace(com.enonic.xp.trace.Trace) PortalResponse(com.enonic.xp.portal.PortalResponse) ByteSource(com.google.common.io.ByteSource) MediaType(com.google.common.net.MediaType) ThrottlingException(com.enonic.xp.exception.ThrottlingException)

Example 32 with PortalResponse

use of com.enonic.xp.portal.PortalResponse in project xp by enonic.

the class ComponentHandlerWorker method execute.

@Override
public PortalResponse execute() throws Exception {
    final ContentResolverResult resolvedContent = contentResolver.resolve(this.request);
    final Content content = resolvedContent.getContentOrElseThrow();
    final Site site = resolvedContent.getNearestSiteOrElseThrow();
    Page page = content.getPage();
    final PageResolverResult resolvedPage = pageResolver.resolve(request.getMode(), content, site);
    Component component = null;
    if (content.getType().isFragment()) {
        // fragment content, try resolving component path in Layout fragment
        final Component fragmentComponent = page.getFragment();
        if (this.componentPath.isEmpty()) {
            component = fragmentComponent;
        } else if (fragmentComponent instanceof LayoutComponent) {
            component = ((LayoutComponent) fragmentComponent).getComponent(this.componentPath);
        }
    }
    final Page effectivePage;
    if (component == null) {
        effectivePage = inlineFragments(resolvedPage.getEffectivePage(), this.componentPath);
        component = effectivePage.getRegions().getComponent(this.componentPath);
    } else {
        effectivePage = resolvedPage.getEffectivePage();
    }
    if (component == null) {
        throw WebException.notFound(String.format("Page component for [%s] not found", this.componentPath));
    }
    final Content effectiveContent = Content.create(content).page(effectivePage).build();
    final DescriptorKey controller = resolvedPage.getController();
    this.request.setSite(site);
    this.request.setContent(effectiveContent);
    this.request.setComponent(component);
    this.request.setApplicationKey(controller != null ? controller.getApplicationKey() : null);
    final Trace trace = Tracer.current();
    if (trace != null) {
        trace.put("componentPath", component.getPath());
        trace.put("type", component.getType().toString());
    }
    final PortalResponse response = rendererDelegate.render(component, this.request);
    return this.postProcessor.processResponseInstructions(this.request, response);
}
Also used : ContentResolverResult(com.enonic.xp.portal.impl.ContentResolverResult) Site(com.enonic.xp.site.Site) Trace(com.enonic.xp.trace.Trace) PortalResponse(com.enonic.xp.portal.PortalResponse) Content(com.enonic.xp.content.Content) DescriptorKey(com.enonic.xp.page.DescriptorKey) Page(com.enonic.xp.page.Page) FragmentComponent(com.enonic.xp.region.FragmentComponent) Component(com.enonic.xp.region.Component) LayoutComponent(com.enonic.xp.region.LayoutComponent) LayoutComponent(com.enonic.xp.region.LayoutComponent)

Example 33 with PortalResponse

use of com.enonic.xp.portal.PortalResponse in project xp by enonic.

the class ServiceHandlerWorker method execute.

@Override
public PortalResponse execute() throws Exception {
    // Retrieves the ServiceDescriptor
    final DescriptorKey descriptorKey = DescriptorKey.from(applicationKey, name);
    final ServiceDescriptor serviceDescriptor = serviceDescriptorService.getByKey(descriptorKey);
    if (serviceDescriptor == null) {
        throw WebException.notFound(String.format("Service [%s] not found", descriptorKey));
    }
    // Checks if the access to ServiceDescriptor is allowed
    final PrincipalKeys principals = ContextAccessor.current().getAuthInfo().getPrincipals();
    if (!serviceDescriptor.isAccessAllowed(principals)) {
        throw WebException.forbidden(String.format("You don't have permission to access [%s]", descriptorKey));
    }
    final ContentResolverResult resolvedContent = contentResolver.resolve(request);
    final Site site = resolvedContent.getNearestSite();
    // Checks if the application is set on the current site
    if (site != null) {
        final PropertyTree siteConfig = site.getSiteConfig(applicationKey);
        if (siteConfig == null) {
            throw WebException.forbidden(String.format("Service [%s] forbidden for this site", descriptorKey));
        }
    }
    // Checks if the application is set on the current application
    final ApplicationKey baseApplicationKey = getBaseApplicationKey();
    if (baseApplicationKey != null && !baseApplicationKey.equals(applicationKey)) {
        throw WebException.forbidden(String.format("Service [%s] forbidden for this application", descriptorKey));
    }
    // Prepares the request
    this.request.setApplicationKey(applicationKey);
    this.request.setContent(resolvedContent.getContent());
    this.request.setSite(site);
    // Executes the service
    final ControllerScript controllerScript = getScript();
    final PortalResponse portalResponse = controllerScript.execute(this.request);
    final WebSocketConfig webSocketConfig = portalResponse.getWebSocket();
    final WebSocketContext webSocketContext = this.request.getWebSocketContext();
    if ((webSocketContext != null) && (webSocketConfig != null)) {
        final WebSocketEndpoint webSocketEndpoint = newWebSocketEndpoint(webSocketConfig);
        webSocketContext.apply(webSocketEndpoint);
    }
    return portalResponse;
}
Also used : ContentResolverResult(com.enonic.xp.portal.impl.ContentResolverResult) Site(com.enonic.xp.site.Site) ApplicationKey(com.enonic.xp.app.ApplicationKey) PortalResponse(com.enonic.xp.portal.PortalResponse) WebSocketConfig(com.enonic.xp.web.websocket.WebSocketConfig) PrincipalKeys(com.enonic.xp.security.PrincipalKeys) ControllerScript(com.enonic.xp.portal.controller.ControllerScript) ServiceDescriptor(com.enonic.xp.service.ServiceDescriptor) PropertyTree(com.enonic.xp.data.PropertyTree) WebSocketEndpoint(com.enonic.xp.web.websocket.WebSocketEndpoint) DescriptorKey(com.enonic.xp.page.DescriptorKey) WebSocketContext(com.enonic.xp.web.websocket.WebSocketContext)

Example 34 with PortalResponse

use of com.enonic.xp.portal.PortalResponse in project xp by enonic.

the class IdProviderControllerServiceImpl method execute.

@Override
public PortalResponse execute(final IdProviderControllerExecutionParams params) throws IOException {
    final IdProviderKey idProviderKey = retrieveIdProviderKey(params);
    final IdProvider idProvider = retrieveIdProvider(idProviderKey);
    final IdProviderDescriptor idProviderDescriptor = retrieveIdProviderDescriptor(idProvider);
    if (idProviderDescriptor != null) {
        final IdProviderControllerScript idProviderControllerScript = idProviderControllerScriptFactory.fromScript(idProviderDescriptor.getResourceKey());
        final String functionName = params.getFunctionName();
        if (idProviderControllerScript.hasMethod(functionName)) {
            PortalRequest portalRequest = params.getPortalRequest();
            if (portalRequest == null) {
                portalRequest = new PortalRequestAdapter().adapt(params.getServletRequest());
            }
            portalRequest.setApplicationKey(idProviderDescriptor.getKey());
            portalRequest.setIdProvider(idProvider);
            final PortalResponse portalResponse = idProviderControllerScript.execute(functionName, portalRequest);
            if (portalResponse != null) {
                final HttpServletResponse response = params.getResponse();
                if (response != null) {
                    responseSerializationService.serialize(portalRequest, portalResponse, response);
                }
            }
            return portalResponse;
        }
    }
    return null;
}
Also used : PortalResponse(com.enonic.xp.portal.PortalResponse) PortalRequestAdapter(com.enonic.xp.portal.impl.PortalRequestAdapter) IdProvider(com.enonic.xp.security.IdProvider) IdProviderDescriptor(com.enonic.xp.idprovider.IdProviderDescriptor) IdProviderKey(com.enonic.xp.security.IdProviderKey) HttpServletResponse(javax.servlet.http.HttpServletResponse) PortalRequest(com.enonic.xp.portal.PortalRequest)

Example 35 with PortalResponse

use of com.enonic.xp.portal.PortalResponse in project xp by enonic.

the class PostProcessingRenderer method render.

@Override
public PortalResponse render(final R component, final PortalRequest portalRequest) {
    PortalResponse portalResponse = doRender(component, portalRequest);
    portalResponse = this.postProcessor.processResponseInstructions(portalRequest, portalResponse);
    portalResponse = executeResponseProcessors(portalRequest, portalResponse);
    portalResponse = this.postProcessor.processResponseContributions(portalRequest, portalResponse);
    return portalResponse;
}
Also used : PortalResponse(com.enonic.xp.portal.PortalResponse)

Aggregations

PortalResponse (com.enonic.xp.portal.PortalResponse)104 Test (org.junit.jupiter.api.Test)78 PortalRequest (com.enonic.xp.portal.PortalRequest)21 WebException (com.enonic.xp.web.WebException)14 BaseHandlerTest (com.enonic.xp.web.handler.BaseHandlerTest)14 Assertions.assertEquals (org.junit.jupiter.api.Assertions.assertEquals)13 PostProcessInstruction (com.enonic.xp.portal.postprocess.PostProcessInstruction)10 WebResponse (com.enonic.xp.web.WebResponse)10 ContentService (com.enonic.xp.content.ContentService)9 ControllerScript (com.enonic.xp.portal.controller.ControllerScript)9 ResourceKey (com.enonic.xp.resource.ResourceKey)9 RenderMode (com.enonic.xp.portal.RenderMode)8 HtmlTag (com.enonic.xp.portal.postprocess.HtmlTag)8 PostProcessInjection (com.enonic.xp.portal.postprocess.PostProcessInjection)8 ByteSource (com.google.common.io.ByteSource)8 InputStream (java.io.InputStream)8 StandardCharsets (java.nio.charset.StandardCharsets)8 Arrays (java.util.Arrays)8 Collections (java.util.Collections)8 List (java.util.List)8