Advertisement
isthmus86

primefaces 4.0.7-SNAPSHOT imageCropper-streamedContent (2)

Feb 8th, 2014
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.71 KB | None | 0 0
  1. /*
  2.  * Copyright 2009-2013 PrimeTek.
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  * http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16. package org.primefaces.component.imagecropper;
  17.  
  18. import java.awt.image.BufferedImage;
  19. import java.io.ByteArrayOutputStream;
  20. import java.io.File;
  21. import java.io.IOException;
  22. import java.net.URL;
  23. import java.net.URLEncoder;
  24. import java.util.Map;
  25. import javax.faces.application.Resource;
  26. import javax.faces.component.UIComponent;
  27. import javax.faces.component.UIParameter;
  28. import javax.faces.context.ExternalContext;
  29. import javax.faces.context.FacesContext;
  30. import javax.faces.context.ResponseWriter;
  31. import javax.faces.convert.ConverterException;
  32. import javax.imageio.ImageIO;
  33. import org.primefaces.context.RequestContext;
  34. import org.primefaces.model.CroppedImage;
  35. import org.primefaces.model.StreamedContent;
  36. import org.primefaces.renderkit.CoreRenderer;
  37. import org.primefaces.util.Constants;
  38. import org.primefaces.util.StringEncrypter;
  39. import org.primefaces.util.WidgetBuilder;
  40.  
  41. public class ImageCropperRenderer extends CoreRenderer {
  42.  
  43.     @Override
  44.     public void decode(FacesContext context, UIComponent component) {
  45.         ImageCropper cropper = (ImageCropper) component;
  46.         Map<String, String> params = context.getExternalContext().getRequestParameterMap();
  47.         String coordsParam = cropper.getClientId(context) + "_coords";
  48.  
  49.         if (params.containsKey(coordsParam)) {
  50.             cropper.setSubmittedValue(params.get(coordsParam));
  51.         }
  52.     }
  53.  
  54.     @Override
  55.     public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
  56.         ImageCropper cropper = (ImageCropper) component;
  57.  
  58.         encodeMarkup(context, cropper);
  59.         encodeScript(context, cropper);
  60.     }
  61.  
  62.     protected void encodeScript(FacesContext context, ImageCropper cropper) throws IOException {
  63.         String widgetVar = cropper.resolveWidgetVar();
  64.         String clientId = cropper.getClientId(context);
  65.         String image = clientId + "_image";
  66.         String select = null;
  67.  
  68.         WidgetBuilder wb = getWidgetBuilder(context);
  69.         wb.initWithComponentLoad("ImageCropper", widgetVar, clientId, clientId + "_image", "imagecropper")
  70.                 .attr("image", image);
  71.  
  72.         if (cropper.getMinSize() != null) {
  73.             wb.append(",minSize:[").append(cropper.getMinSize()).append("]");
  74.         }
  75.  
  76.         if (cropper.getMaxSize() != null) {
  77.             wb.append(",maxSize:[").append(cropper.getMaxSize()).append("]");
  78.         }
  79.  
  80.         wb.attr("bgColor", cropper.getBackgroundColor(), null)
  81.                 .attr("bgOpacity", cropper.getBackgroundOpacity(), 0.6)
  82.                 .attr("aspectRatio", cropper.getAspectRatio(), Double.MIN_VALUE);
  83.  
  84.         if (cropper.getValue() != null) {
  85.             CroppedImage croppedImage = (CroppedImage) cropper.getValue();
  86.  
  87.             int x = croppedImage.getLeft();
  88.             int y = croppedImage.getTop();
  89.             int x2 = x + croppedImage.getWidth();
  90.             int y2 = y + croppedImage.getHeight();
  91.  
  92.             select = "[" + x + "," + y + "," + x2 + "," + y2 + "]";
  93.         } else if (cropper.getInitialCoords() != null) {
  94.             select = "[" + cropper.getInitialCoords() + "]";
  95.         }
  96.  
  97.         wb.append(",setSelect:").append(select);
  98.  
  99.         wb.finish();
  100.     }
  101.  
  102.     protected void encodeMarkup(FacesContext context, ImageCropper cropper) throws IOException {
  103.         ResponseWriter writer = context.getResponseWriter();
  104.         String clientId = cropper.getClientId(context);
  105.         String coordsHolderId = clientId + "_coords";
  106.  
  107.         writer.startElement("div", cropper);
  108.         writer.writeAttribute("id", clientId, null);
  109.  
  110.         renderImage(context, cropper, clientId);
  111.  
  112.         writer.startElement("input", null);
  113.         writer.writeAttribute("type", "hidden", null);
  114.         writer.writeAttribute("id", coordsHolderId, null);
  115.         writer.writeAttribute("name", coordsHolderId, null);
  116.         writer.endElement("input");
  117.  
  118.         writer.endElement("div");
  119.     }
  120.  
  121.     @Override
  122.     public Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue) throws ConverterException {
  123.         String coords = (String) submittedValue;
  124.         if (isValueBlank(coords)) {
  125.             return null;
  126.         }
  127.  
  128.         ImageCropper cropper = (ImageCropper) component;
  129.  
  130.         //remove query string
  131.         Object imagePath = cropper.getImage();
  132.         if (imagePath instanceof String) {
  133.             int queryStringIndex = ((String) imagePath).indexOf("?");
  134.             if (queryStringIndex != -1) {
  135.                 imagePath = ((String) imagePath).substring(0, queryStringIndex);
  136.             }
  137.         }
  138.  
  139.         String[] cropCoords = coords.split("_");
  140.         String format = getFormat(imagePath);
  141.  
  142.         int x = Integer.parseInt(cropCoords[0]);
  143.         int y = Integer.parseInt(cropCoords[1]);
  144.         int w = Integer.parseInt(cropCoords[2]);
  145.         int h = Integer.parseInt(cropCoords[3]);
  146.  
  147.         try {
  148.             BufferedImage outputImage = getSourceImage(context, imagePath);
  149.             BufferedImage cropped = outputImage.getSubimage(x, y, w, h);
  150.  
  151.             ByteArrayOutputStream croppedOutImage = new ByteArrayOutputStream();
  152.             ImageIO.write(cropped, format, croppedOutImage);
  153.  
  154.             return new CroppedImage(new String(), croppedOutImage.toByteArray(), x, y, w, h);    // FIX THIS
  155.  
  156.         } catch (IOException e) {
  157.             throw new ConverterException(e);
  158.         }
  159.     }
  160.  
  161.     private void renderImage(FacesContext context, ImageCropper cropper, String clientId) throws IOException {
  162.         ResponseWriter writer = context.getResponseWriter();
  163.         String alt = cropper.getAlt() == null ? "" : cropper.getAlt();
  164.         String imageSrc;
  165.         try {
  166.             imageSrc = getImageSrc(context, cropper);
  167.         } catch (Exception e) {
  168.             throw new IOException(e);
  169.         }
  170.         writer.startElement("img", null);
  171.         writer.writeAttribute("id", clientId + "_image", null);
  172.         writer.writeAttribute("alt", alt, null);
  173.         writer.writeAttribute("src", imageSrc, null);
  174.         writer.endElement("img");
  175.     }
  176.  
  177.     protected String getFormat(Object path) {
  178.         if (path instanceof String) {
  179.             String[] pathTokens = ((String) path).split("\\.");
  180.  
  181.             return pathTokens[pathTokens.length - 1];
  182.         } else if (path instanceof StreamedContent) {
  183.             StreamedContent content = (StreamedContent) path;
  184.             return mapMimeTypeToFormat(content.getContentType());
  185.         }
  186.         return "";
  187.     }
  188.  
  189.     protected boolean isExternalImage(ImageCropper cropper) {
  190.         return (cropper.getImage() instanceof String) && ((String) cropper.getImage()).startsWith("http");
  191.     }
  192.  
  193.     private BufferedImage getSourceImage(FacesContext context, Object imagePath) throws IOException {
  194.         BufferedImage outputImage = null;
  195.         if (imagePath instanceof String) {
  196.             boolean isExternal = ((String) imagePath).startsWith("http");
  197.  
  198.             if (isExternal) {
  199.                 URL url = new URL((String) imagePath);
  200.  
  201.                 outputImage = ImageIO.read(url);
  202.             } else {
  203.                 ExternalContext externalContext = context.getExternalContext();
  204.  
  205.                 outputImage = ImageIO.read(new File(externalContext.getRealPath("") + (String) imagePath));
  206.             }
  207.         } else if (imagePath instanceof StreamedContent) {
  208.             outputImage = ImageIO.read(((StreamedContent) imagePath).getStream());
  209.         }
  210.         return outputImage;
  211.     }
  212.  
  213.     /**
  214.      * Additional method to handle StreamedContent image attribute
  215.      *
  216.      * @param context The current FacesContext
  217.      * @param cropper The imageCropper Object
  218.      * @return
  219.      */
  220.     private String getImageSrc(FacesContext context, ImageCropper cropper) throws Exception {
  221.         Object image = cropper.getImage();
  222.         if (image instanceof String) {
  223.             return getResourceURL(context, (String) cropper.getImage());
  224.         } else if (image instanceof StreamedContent) {
  225.             // Copied from GraphicImageRenderer
  226.             StreamedContent streamedContent = (StreamedContent) image;
  227.             Resource resource = context.getApplication().getResourceHandler().createResource("dynamiccontent.properties", "primefaces", streamedContent.getContentType());
  228.             String resourcePath = resource.getRequestPath();
  229.             StringEncrypter strEn = RequestContext.getCurrentInstance().getEncrypter();
  230.             String rid = strEn.encrypt(cropper.getValueExpression("image").getExpressionString());
  231.             StringBuilder builder = new StringBuilder(resourcePath);
  232.  
  233.             builder.append("&").append(Constants.DYNAMIC_CONTENT_PARAM).append("=").append(URLEncoder.encode(rid, "UTF-8"));
  234.  
  235.             for (UIComponent kid : cropper.getChildren()) {
  236.                 if (kid instanceof UIParameter) {
  237.                     UIParameter param = (UIParameter) kid;
  238.                     Object paramValue = param.getValue();
  239.  
  240.                     builder.append("&").append(param.getName()).append("=");
  241.  
  242.                     if (paramValue != null) {
  243.                         builder.append(URLEncoder.encode(param.getValue().toString(), "UTF-8"));
  244.                     }
  245.                 }
  246.             }
  247.             return builder.toString();
  248.         }
  249.         return "";
  250.     }
  251.  
  252.     /**
  253.      * Helper method to map mimeTypes from StreamedContent to proper ImageIO
  254.      * format string. Updated for JDK7.
  255.      *
  256.      * @param mimeType The mime type to be mapped.
  257.      * @return The proper ImageIO format string.
  258.      */
  259.     private String mapMimeTypeToFormat(String mimeType) {
  260.         if (mimeType != null) {
  261.             if (mimeType.equalsIgnoreCase("image/jpeg")) {
  262.                 return "jpg";
  263.             } else if (mimeType.equalsIgnoreCase("image/gif")) {
  264.                 return "gif";
  265.             } else if (mimeType.equalsIgnoreCase("image/bmp")) {
  266.                 return "bmp";
  267.             } else if (mimeType.equalsIgnoreCase("image/vnd.wap.wbmp")) {
  268.                 return "wbmp";
  269.             } else if (mimeType.equalsIgnoreCase("image/png")) {
  270.                 return "png";
  271.             }
  272.         }
  273.         return "";
  274.     }
  275. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement