View Javadoc

1   /**
2    * 2007, Digitalis Informatica. All rights reserved. Distribuicao e Gestao de Informatica, Lda. Estrada de Paco de Arcos
3    * num.9 - Piso -1 2780-666 Paco de Arcos Telefone: (351) 21 4408990 Fax: (351) 21 4408999 http://www.digitalis.pt
4    */
5   package pt.digitalis.dif.dem.objects.parameters.types;
6   
7   import java.awt.image.BufferedImage;
8   import java.io.ByteArrayInputStream;
9   import java.io.ByteArrayOutputStream;
10  import java.io.IOException;
11  import java.math.BigDecimal;
12  import java.util.ArrayList;
13  import java.util.Date;
14  import java.util.List;
15  
16  import javax.imageio.ImageIO;
17  
18  import org.imgscalr.Scalr;
19  
20  import pt.digitalis.dif.controller.http.HTTPConstants;
21  import pt.digitalis.dif.controller.interfaces.IDIFContext;
22  import pt.digitalis.dif.controller.objects.DIFSessionConstants;
23  import pt.digitalis.dif.dem.interfaces.IStageInstance;
24  import pt.digitalis.dif.dem.objects.parameters.errors.ParameterError;
25  import pt.digitalis.dif.dem.objects.parameters.errors.ParameterErrorList;
26  import pt.digitalis.dif.dem.objects.parameters.errors.ParameterErrorType;
27  import pt.digitalis.dif.exception.objects.ParameterException;
28  import pt.digitalis.dif.ioc.DIFIoCRegistry;
29  import pt.digitalis.dif.utils.extensions.document.DocumentRepositoryEntry;
30  import pt.digitalis.dif.utils.extensions.document.DocumentRepositoryException;
31  import pt.digitalis.dif.utils.extensions.document.IDocumentRepositoryManager;
32  import pt.digitalis.dif.utils.logging.DIFLogger;
33  
34  /**
35   * /** This class will define a numeric Parameter.
36   * <p>
37   * It will hold information relative to the Parameter value, ID key and validation constraints.
38   * 
39   * @author Pedro Viegas <a href="mailto:pviegas@digitalis.pt">pviegas@digitalis.pt</a>
40   * @created Nov 23, 2007
41   */
42  public class DocumentParameter extends AbstractParameter<DocumentRepositoryEntry> {
43  
44      /** the ID if a companion hidden field that includes the document repository ID when a document is resubmitted */
45      private static final String DOCUMENT_ID_HIDDEN_FIELD = "_docid";
46      /** The list of supported classes to define in the concrete implementations */
47      @SuppressWarnings("serial")
48      final static private List<String> supportedClasses = new ArrayList<String>() {
49  
50          {
51              add(DocumentRepositoryEntry.class.getCanonicalName());
52          }
53      };
54  
55      /**
56       * @see pt.digitalis.dif.dem.objects.parameters.IParameter#getSupportedClasses()
57       */
58      public List<String> getSupportedClasses()
59      {
60          return supportedClasses;
61      }
62  
63      /**
64       * @see pt.digitalis.dif.dem.objects.parameters.IParameter#getValueAsBigDecimal(pt.digitalis.dif.controller.interfaces.IDIFContext)
65       */
66      public BigDecimal getValueAsBigDecimal(IDIFContext context) throws ParameterException
67      {
68          // Impossible conversion. Return an exception
69          throw new ParameterException(getMessages().getMessages(context.getLanguage()).get("invalidUsage"), this);
70      }
71  
72      /**
73       * @see pt.digitalis.dif.dem.objects.parameters.IParameter#getValueAsBoolean(IDIFContext)
74       */
75      public boolean getValueAsBoolean(IDIFContext context) throws ParameterException
76      {
77          // Impossible conversion. Return an exception
78          throw new ParameterException(getMessages().getMessages(context.getLanguage()).get("invalidUsage"), this);
79      }
80  
81      /**
82       * @see pt.digitalis.dif.dem.objects.parameters.IParameter#getValueAsDate(IDIFContext)
83       */
84      public Date getValueAsDate(IDIFContext context) throws ParameterException
85      {
86          // Impossible conversion. Return an exception
87          throw new ParameterException(getMessages().getMessages(context.getLanguage()).get("invalidUsage"), this);
88      }
89  
90      /**
91       * @see pt.digitalis.dif.dem.objects.parameters.types.AbstractParameter#getValueAsDocument(pt.digitalis.dif.controller.interfaces.IDIFContext)
92       */
93      @Override
94      public DocumentRepositoryEntry getValueAsDocument(IDIFContext context) throws ParameterException
95      {
96          return getValue(context);
97      }
98  
99      /**
100      * @see pt.digitalis.dif.dem.objects.parameters.IParameter#getValueAsDouble(IDIFContext)
101      */
102     public Double getValueAsDouble(IDIFContext context) throws ParameterException
103     {
104         // Impossible conversion. Return an exception
105         throw new ParameterException(getMessages().getMessages(context.getLanguage()).get("invalidUsage"), this);
106     }
107 
108     /**
109      * @see pt.digitalis.dif.dem.objects.parameters.IParameter#getValueAsLong(IDIFContext)
110      */
111     public Long getValueAsLong(IDIFContext context) throws ParameterException
112     {
113         // Impossible conversion. Return an exception
114         throw new ParameterException(getMessages().getMessages(context.getLanguage()).get("invalidUsage"), this);
115     }
116 
117     /**
118      * @see pt.digitalis.dif.dem.objects.parameters.types.AbstractParameter#getValueAsString(pt.digitalis.dif.controller.interfaces.IDIFContext)
119      */
120     @Override
121     public String getValueAsString(IDIFContext context) throws ParameterException
122     {
123         // Impossible conversion. Return an exception
124         throw new ParameterException(getMessages().getMessages(context.getLanguage()).get("invalidUsage"), this);
125     }
126 
127     /**
128      * @see pt.digitalis.dif.dem.objects.parameters.IParameter#isNumeric()
129      */
130     public boolean isNumeric()
131     {
132         return false;
133     }
134 
135     /**
136      * @see pt.digitalis.dif.dem.objects.parameters.types.AbstractParameter#isStringSetterSupported()
137      */
138     @Override
139     public boolean isStringSetterSupported()
140     {
141         return false;
142     }
143 
144     /**
145      * @see pt.digitalis.dif.dem.objects.parameters.types.AbstractParameter#refreshParameterValue(pt.digitalis.dif.dem.interfaces.IStageInstance)
146      */
147     @Override
148     public ParameterErrorList refreshParameterValue(IStageInstance stageInstance)
149     {
150         ParameterErrorList errorList = super.refreshParameterValue(stageInstance);
151 
152         if (!this.hasValue())
153         {
154             Object previousDocumentID = stageInstance.getContext().getRequest()
155                     .getParameter(this.getId() + DOCUMENT_ID_HIDDEN_FIELD);
156             if (previousDocumentID != null)
157             {
158                 try
159                 {
160                     this.setValue(DIFIoCRegistry.getRegistry().getImplementation(IDocumentRepositoryManager.class)
161                             .getDocument(Long.parseLong(previousDocumentID.toString())), stageInstance);
162                     if (hasValue())
163                     {
164                         for (ParameterError error: errorList.getErrorList())
165                         {
166                             if (error.getErrorType() == ParameterErrorType.MISSING)
167                             {
168                                 errorList.getErrorList().remove(error);
169                                 break;
170                             }
171                         }
172                     }
173                 }
174                 catch (Exception e)
175                 {
176                     // If any error occurs do nothing. If the parameter is mandatory the missing error will be
177                     // maintained
178                     e.printStackTrace();
179                 }
180             }
181         }
182 
183         if (stageInstance.getContext().getRequest().getAttribute(HTTPConstants.UPLOAD_FILE_SIZE_ERROR) != null)
184         {
185             ParameterError pError = new ParameterError(
186                     getMessages().getMessages(stageInstance.getContext().getLanguage()).get("fileUploadMaxSize")
187                             + " "
188                             + stageInstance.getContext().getSession()
189                                     .getAttribute(DIFSessionConstants.MAX_DOCUMENT_SIZE), ParameterErrorType.OTHER);
190             pError.setForceShowError(true);
191 
192             errorList.addError(pError);
193 
194             // Error reported. Discard the ChAL warning...
195             stageInstance.getContext().getRequest().addAttribute(HTTPConstants.UPLOAD_FILE_SIZE_ERROR, null);
196         }
197 
198         return errorList;
199     }
200 
201     /**
202      * @see pt.digitalis.dif.dem.objects.parameters.types.AbstractParameter#setValue(java.lang.Object,
203      *      pt.digitalis.dif.dem.interfaces.IStageInstance, boolean)
204      */
205     @Override
206     public ParameterErrorList setValue(DocumentRepositoryEntry value, IStageInstance stageInstance,
207             boolean initializationInProgress)
208     {
209         // Resize functionality
210         if (value != null && value.getBytes() != null
211                 && stageInstance.getContext().getRequest().getParameter(this.getId() + "_resize") != null)
212         {
213             // Resize issued
214             String resizeParams[] = ((String) stageInstance.getContext().getRequest()
215                     .getParameter(this.getId() + "_resize")).split("x");
216             Integer width = Integer.parseInt(resizeParams[0]);
217             Integer height = resizeParams.length > 1 ? Integer.parseInt(resizeParams[1]) : width;
218 
219             ByteArrayInputStream bais = new ByteArrayInputStream(value.getBytes());
220             BufferedImage image;
221             try
222             {
223                 image = ImageIO.read(bais);
224                 bais.close();
225 
226                 if (image.getHeight() > height || image.getWidth() > width)
227                 {
228                     BufferedImage resizedImage;
229                     // Resize the image to the conventioned size
230                     resizedImage = Scalr.resize(image, Scalr.Method.AUTOMATIC, Scalr.Mode.AUTOMATIC, width, height);
231 
232                     // Convert it back to byte[] in eventImage for saving
233                     ByteArrayOutputStream baos = new ByteArrayOutputStream();
234                     ImageIO.write(resizedImage, value.getMimeType(), baos);
235                     baos.flush();
236                     value.setBytes(baos.toByteArray());
237                     baos.close();
238                 }
239             }
240             catch (IOException e)
241             {
242                 DIFLogger.getLogger().warn("Could not resize the image: " + value.getFileName());
243                 e.printStackTrace();
244             }
245         }
246 
247         // Delete functionality
248         if (stageInstance.getContext().getRequest().getParameter(this.getId() + "_delete") != null)
249         {
250             Object docID = stageInstance.getContext().getRequest()
251                     .getParameter(this.getId() + DOCUMENT_ID_HIDDEN_FIELD);
252 
253             if (docID != null)
254             {
255                 // TODO: Implement the deletion for images
256                 // TODO: Implement the deletion for files
257                 value = new DocumentRepositoryEntry();
258                 value.setId(Long.parseLong(docID.toString()));
259 
260                 try
261                 {
262                     value = DIFIoCRegistry.getRegistry().getImplementation(IDocumentRepositoryManager.class)
263                             .getDocument(Long.parseLong(docID.toString()));
264                 }
265                 catch (NumberFormatException e)
266                 {
267                     e.printStackTrace();
268                 }
269                 catch (DocumentRepositoryException e)
270                 {
271                     e.printStackTrace();
272                 }
273 
274                 if (value != null)
275                     value.setDeleteRequested(true);
276             }
277         }
278 
279         return super.setValue(value, stageInstance, initializationInProgress);
280     }
281 
282     /**
283      * @see pt.digitalis.dif.dem.objects.parameters.IParameter#setValueFromString(java.lang.String,
284      *      pt.digitalis.dif.dem.interfaces.IStageInstance, boolean)
285      */
286     public ParameterErrorList setValueFromString(String value, IStageInstance stageInstance,
287             boolean initializationInProgress)
288     {
289         ParameterErrorList list = new ParameterErrorList(this, value);
290         ParameterError error = new ParameterError(getMessages().getMessages(stageInstance.getContext().getLanguage())
291                 .get("invalidUsage"), ParameterErrorType.OTHER);
292         list.addError(error);
293 
294         return list;
295     }
296 }