/** * Listenet, that invoked during file upload process. Only registered users can upload images. * * @param event - event, indicated that file upload started */ @Restrict("#{s:hasRole('admin')}") public void listener(UploadEvent event) { UploadItem item = event.getUploadItem(); // Construct image from item Image image = constructImage(item); try { // Extract metadata(size, camera model etc..) extractMetadata(item, image); } catch (Exception e1) { addError(item, image, Constants.FILE_PROCESSING_ERROR); return; } image.setAlbum(model.getSelectedAlbum()); if (image.getAlbum() == null) { addError(item, image, Constants.NO_ALBUM_TO_DOWNLOAD_ERROR); return; } try { // Check if image with given name already exist if (imageAction.isImageWithThisPathExist(image.getAlbum(), image.getPath())) { // If exist generate new path for image String newPath = generateNewPath(image); image.setPath(newPath); image.setName(newPath); } // Save to database imageAction.addImage(image); } catch (Exception e) { addError(item, image, Constants.IMAGE_SAVING_ERROR); return; } // Save to disk if (!fileManager.addImage(image.getFullPath(), item.getFile().getPath())) { addError(item, image, Constants.FILE_SAVE_ERROR); return; } // Prepare to show in UI fileWrapper.getFiles().add(image); Events.instance().raiseEvent(Constants.IMAGE_ADDED_EVENT, image); // Delete temporary file item.getFile().delete(); }
private void extractMetadata(UploadItem item, Image image) { InputStream in = null; try { in = new FileInputStream(item.getFile()); Metadata metadata = JpegMetadataReader.readMetadata(in); Directory exifDirectory = metadata.getDirectory(ExifDirectory.class); Directory jpgDirectory = metadata.getDirectory(JpegDirectory.class); setupCameraModel(image, exifDirectory); setupDimensions(image, exifDirectory, jpgDirectory); setupCreatedDate(image, exifDirectory); } catch (Exception e) { addError(item, image, Constants.IMAGE_SAVING_ERROR); } finally { try { in.close(); } catch (IOException e) { addError(item, image, Constants.IMAGE_SAVING_ERROR); } } }
private void addError(UploadItem item, Image image, String error) { fileWrapper.onFileUploadError(image, error); item.getFile().delete(); }