Search in sources :

Example 16 with Resource

use of javax.faces.application.Resource in project primefaces by primefaces.

the class ImageCropperRenderer method getConvertedValue.

@Override
public Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue) throws ConverterException {
    String coords = (String) submittedValue;
    if (isValueBlank(coords)) {
        return null;
    }
    String[] cropCoords = coords.split("_");
    int x = (int) Double.parseDouble(cropCoords[0]);
    int y = (int) Double.parseDouble(cropCoords[1]);
    int w = (int) Double.parseDouble(cropCoords[2]);
    int h = (int) Double.parseDouble(cropCoords[3]);
    if (w <= 0 || h <= 0) {
        return null;
    }
    ImageCropper cropper = (ImageCropper) component;
    Resource resource = getImageResource(context, cropper);
    InputStream inputStream = null;
    Object imageObject = cropper.getImage();
    String imagePath = null;
    StreamedContent stream = null;
    if (imageObject instanceof String) {
        imagePath = imageObject.toString();
    } else if (imageObject instanceof StreamedContent) {
        stream = (StreamedContent) imageObject;
    } else {
        throw new IllegalArgumentException("'image' must be either an String relative path or a StreamedObject.");
    }
    String contentType = null;
    try {
        if (resource != null && !"RES_NOT_FOUND".equals(resource.toString())) {
            inputStream = resource.getInputStream();
            contentType = resource.getContentType();
        } else {
            if (imagePath != null) {
                boolean isExternal = imagePath.startsWith("http");
                if (isExternal) {
                    URL url = new URL(imagePath);
                    URLConnection urlConnection = url.openConnection();
                    inputStream = urlConnection.getInputStream();
                    contentType = urlConnection.getContentType();
                } else {
                    ExternalContext externalContext = context.getExternalContext();
                    // GitHub #3268 OWASP Path Traversal
                    imagePath = FileUploadUtils.checkPathTraversal(imagePath);
                    String webRoot = externalContext.getRealPath(Constants.EMPTY_STRING);
                    String fileSeparator = Constants.EMPTY_STRING;
                    if (!(webRoot.endsWith("\\") || webRoot.endsWith("/")) && !(imagePath.startsWith("\\") || imagePath.startsWith("/"))) {
                        fileSeparator = "/";
                    }
                    File file = new File(webRoot + fileSeparator + imagePath);
                    inputStream = new FileInputStream(file);
                }
            } else if (stream != null) {
                inputStream = stream.getStream().get();
                contentType = stream.getContentType();
            }
        }
        // wrap input stream by BoundedInputStream to prevent uncontrolled resource consumption (#3286)
        if (cropper.getSizeLimit() != null) {
            inputStream = new BoundedInputStream(inputStream, cropper.getSizeLimit());
        }
        BufferedImage outputImage = ImageIO.read(inputStream);
        // see #1208
        if (x + w > outputImage.getWidth()) {
            w = outputImage.getWidth() - x;
        }
        if (y + h > outputImage.getHeight()) {
            h = outputImage.getHeight() - y;
        }
        BufferedImage cropped = outputImage.getSubimage(x, y, w, h);
        ByteArrayOutputStream croppedOutImage = new ByteArrayOutputStream();
        String format = guessImageFormat(contentType, imagePath);
        ImageIO.write(cropped, format, croppedOutImage);
        return new CroppedImage(cropper.getImage().toString(), croppedOutImage.toByteArray(), x, y, w, h);
    } catch (IOException e) {
        LOGGER.severe(e.getMessage());
        throw new ConverterException(e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                LOGGER.severe(e.getMessage());
            }
        }
    }
}
Also used : ConverterException(javax.faces.convert.ConverterException) BoundedInputStream(org.apache.commons.io.input.BoundedInputStream) Resource(javax.faces.application.Resource) URL(java.net.URL) URLConnection(java.net.URLConnection) BufferedImage(java.awt.image.BufferedImage) CroppedImage(org.primefaces.model.CroppedImage) ExternalContext(javax.faces.context.ExternalContext) BoundedInputStream(org.apache.commons.io.input.BoundedInputStream) StreamedContent(org.primefaces.model.StreamedContent)

Example 17 with Resource

use of javax.faces.application.Resource in project primefaces by primefaces.

the class ImageCropperRenderer method getImageResource.

/**
 * Attempt to obtain the resource from the server by parsing the valueExpression of the image attribute. Returns null
 * if the valueExpression is not of the form #{resource['path/to/resource']} or #{resource['library:name']}. Otherwise
 * returns the value obtained by ResourceHandler.createResource().
 */
private Resource getImageResource(FacesContext facesContext, ImageCropper imageCropper) {
    Resource resource = null;
    ValueExpression imageValueExpression = imageCropper.getValueExpression(ImageCropper.PropertyKeys.image.toString());
    if (imageValueExpression != null) {
        String imageValueExpressionString = imageValueExpression.getExpressionString();
        if (imageValueExpressionString.matches("^[#][{]resource\\['[^']+'\\][}]$")) {
            imageValueExpressionString = imageValueExpressionString.replaceFirst("^[#][{]resource\\['", "");
            imageValueExpressionString = imageValueExpressionString.replaceFirst("'\\][}]$", "");
            String resourceLibrary = null;
            String resourceName;
            String[] resourceInfo = imageValueExpressionString.split(":");
            if (resourceInfo.length == 2) {
                resourceLibrary = resourceInfo[0];
                resourceName = resourceInfo[1];
            } else {
                resourceName = resourceInfo[0];
            }
            if (resourceName != null) {
                Application application = facesContext.getApplication();
                ResourceHandler resourceHandler = application.getResourceHandler();
                if (resourceLibrary != null) {
                    resource = resourceHandler.createResource(resourceName, resourceLibrary);
                } else {
                    resource = resourceHandler.createResource(resourceName);
                }
            }
        }
    }
    return resource;
}
Also used : ValueExpression(javax.el.ValueExpression) Resource(javax.faces.application.Resource) ResourceHandler(javax.faces.application.ResourceHandler) Application(javax.faces.application.Application)

Example 18 with Resource

use of javax.faces.application.Resource in project primefaces by primefaces.

the class HeadRenderer method encodeJS.

protected void encodeJS(FacesContext context, String library, String script) throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    ExternalContext externalContext = context.getExternalContext();
    Resource resource = context.getApplication().getResourceHandler().createResource(script, library);
    if (resource == null) {
        throw new FacesException("Error loading JavaScript, cannot find \"" + script + "\" resource of \"" + library + "\" library");
    } else {
        writer.startElement("script", null);
        writer.writeAttribute("src", externalContext.encodeResourceURL(resource.getRequestPath()), null);
        writer.endElement("script");
    }
}
Also used : ResponseWriter(javax.faces.context.ResponseWriter) ExternalContext(javax.faces.context.ExternalContext) Resource(javax.faces.application.Resource) FacesException(javax.faces.FacesException)

Example 19 with Resource

use of javax.faces.application.Resource in project primefaces by primefaces.

the class HeadRenderer method encodeCSS.

protected void encodeCSS(FacesContext context, String library, String resource) throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    ExternalContext externalContext = context.getExternalContext();
    Resource cssResource = context.getApplication().getResourceHandler().createResource(resource, library);
    if (cssResource == null) {
        throw new FacesException("Error loading CSS, cannot find \"" + resource + "\" resource of \"" + library + "\" library");
    } else {
        writer.startElement("link", null);
        writer.writeAttribute("type", "text/css", null);
        writer.writeAttribute("rel", "stylesheet", null);
        writer.writeAttribute("href", externalContext.encodeResourceURL(cssResource.getRequestPath()), null);
        writer.endElement("link");
    }
}
Also used : ResponseWriter(javax.faces.context.ResponseWriter) ExternalContext(javax.faces.context.ExternalContext) Resource(javax.faces.application.Resource) FacesException(javax.faces.FacesException)

Example 20 with Resource

use of javax.faces.application.Resource in project primefaces by primefaces.

the class DynamicContentSrcBuilder method buildStreaming.

public static String buildStreaming(FacesContext context, UIComponent component, ValueExpression valueExpression, boolean cache) {
    // just a dummy file for streaming
    // JSF will also append the suffix (e.g. -> dynamiccontent.properties.xhtml)
    // the real content type will be written to the response by the StreamedContentHandler
    Resource resource = context.getApplication().getResourceHandler().createResource("dynamiccontent.properties", "primefaces", "text/plain");
    String resourcePath = resource.getRequestPath();
    Map<String, Object> session = context.getExternalContext().getSessionMap();
    Map<String, String> dynamicResourcesMapping = (Map) session.get(Constants.DYNAMIC_RESOURCES_MAPPING);
    if (dynamicResourcesMapping == null) {
        dynamicResourcesMapping = new LimitedSizeHashMap<>(200);
        session.put(Constants.DYNAMIC_RESOURCES_MAPPING, dynamicResourcesMapping);
    }
    String expressionString = valueExpression.getExpressionString();
    String resourceKey = md5(expressionString);
    dynamicResourcesMapping.put(resourceKey, expressionString);
    try {
        StringBuilder builder = SharedStringBuilder.get(context, SB_BUILD_STREAMING);
        builder.append(resourcePath).append("&").append(Constants.DYNAMIC_CONTENT_PARAM).append("=").append(URLEncoder.encode(resourceKey, "UTF-8")).append("&").append(Constants.DYNAMIC_CONTENT_TYPE_PARAM).append("=").append(DynamicContentType.STREAMED_CONTENT.toString());
        if (component != null) {
            for (int i = 0; i < component.getChildCount(); i++) {
                UIComponent child = component.getChildren().get(i);
                if (child instanceof UIParameter) {
                    UIParameter param = (UIParameter) child;
                    if (!param.isDisable()) {
                        Object paramValue = param.getValue();
                        builder.append("&").append(param.getName()).append("=");
                        if (paramValue != null) {
                            builder.append(URLEncoder.encode(paramValue.toString(), "UTF-8"));
                        }
                    }
                }
            }
        }
        return ResourceUtils.encodeResourceURL(context, builder.toString(), cache);
    } catch (UnsupportedEncodingException ex) {
        throw new FacesException(ex);
    }
}
Also used : UIParameter(javax.faces.component.UIParameter) Resource(javax.faces.application.Resource) UIComponent(javax.faces.component.UIComponent) UnsupportedEncodingException(java.io.UnsupportedEncodingException) FacesException(javax.faces.FacesException) Map(java.util.Map)

Aggregations

Resource (javax.faces.application.Resource)27 ExternalContext (javax.faces.context.ExternalContext)10 ResourceHandler (javax.faces.application.ResourceHandler)9 FacesContext (javax.faces.context.FacesContext)7 FacesResource (com.liferay.faces.util.application.FacesResource)5 Application (javax.faces.application.Application)5 IOException (java.io.IOException)4 ResponseWriter (javax.faces.context.ResponseWriter)4 URL (java.net.URL)3 Collection (java.util.Collection)3 FacesException (javax.faces.FacesException)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 MalformedURLException (java.net.MalformedURLException)2 LocalDateTime (java.time.LocalDateTime)2 ZoneId (java.time.ZoneId)2 ZonedDateTime (java.time.ZonedDateTime)2 DateTimeFormatter (java.time.format.DateTimeFormatter)2 Arrays (java.util.Arrays)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2