Converting ImageServices to a SCA Component and making accessing album images more like a rest stype using 'gallery/album/image' path

git-svn-id: https://svn.apache.org/repos/asf/incubator/photark/trunk@918876 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/photark-jcr/src/main/java/org/apache/photark/services/ImageDisplayerImpl.java b/photark-jcr/src/main/java/org/apache/photark/jcr/services/JCRImageCollectionImpl.java
similarity index 78%
rename from photark-jcr/src/main/java/org/apache/photark/services/ImageDisplayerImpl.java
rename to photark-jcr/src/main/java/org/apache/photark/jcr/services/JCRImageCollectionImpl.java
index 5bab3af..c694a2e 100644
--- a/photark-jcr/src/main/java/org/apache/photark/services/ImageDisplayerImpl.java
+++ b/photark-jcr/src/main/java/org/apache/photark/jcr/services/JCRImageCollectionImpl.java
@@ -17,7 +17,7 @@
  * under the License.    
  */
 
-package org.apache.photark.services;
+package org.apache.photark.jcr.services;
 
 import java.io.InputStream;
 
@@ -25,25 +25,41 @@
 import javax.jcr.PathNotFoundException;
 import javax.jcr.RepositoryException;
 import javax.jcr.Session;
+import javax.servlet.Servlet;
 
 import org.apache.commons.lang.StringUtils;
+import org.apache.photark.services.ImageCollection;
 import org.apache.photark.services.gallery.jcr.JCRSession;
 import org.apache.tuscany.sca.data.collection.Entry;
 import org.apache.tuscany.sca.data.collection.NotFoundException;
+import org.oasisopen.sca.annotation.Destroy;
 import org.oasisopen.sca.annotation.Init;
+import org.oasisopen.sca.annotation.Scope;
+import org.oasisopen.sca.annotation.Service;
 
-public class ImageDisplayerImpl implements ImageDisplayer {
+/**
+ * JCR based implementation of the Image collection component 
+ * Used to retrieve image files from the JCR repository
+ */
+@Scope("COMPOSITE")
+@Service(ImageCollection.class)
+public class JCRImageCollectionImpl implements ImageCollection {
     private Session session = JCRSession.getSession();
 
     @Init
     public void init() {
     }
+    
+    @Destroy
+    public void destroy() {    
+    }
 
-    public ImageDisplayerImpl() {
+    public JCRImageCollectionImpl() {
+        
     }
 
     public InputStream get(String key) throws NotFoundException {
-        String sub = StringUtils.substringAfter(key, "splayer/");
+        String sub = StringUtils.substringAfter(key, "gallery/");
         String stringArray[] = StringUtils.split(sub, "/");
         String albumName = stringArray[0];
         InputStream inStream = null;
diff --git a/photark-jcr/src/main/java/org/apache/photark/jcr/services/JCRImageUploadServiceImpl.java b/photark-jcr/src/main/java/org/apache/photark/jcr/services/JCRImageUploadServiceImpl.java
new file mode 100644
index 0000000..afd46b1
--- /dev/null
+++ b/photark-jcr/src/main/java/org/apache/photark/jcr/services/JCRImageUploadServiceImpl.java
@@ -0,0 +1,175 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.photark.jcr.services;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.compress.archivers.ArchiveException;
+import org.apache.commons.compress.archivers.ArchiveStreamFactory;
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.FileUploadException;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+import org.apache.commons.fileupload.servlet.ServletFileUpload;
+import org.apache.photark.Image;
+import org.apache.photark.jcr.util.ArchiveFileExtractor;
+import org.apache.photark.services.ImageUploadService;
+import org.apache.photark.services.album.Album;
+import org.apache.photark.services.album.jcr.AlbumImpl;
+import org.apache.photark.services.gallery.Gallery;
+import org.apache.photark.services.gallery.jcr.GalleryImpl;
+import org.oasisopen.sca.annotation.Init;
+import org.oasisopen.sca.annotation.Scope;
+
+/**
+ * Servlet responsible for receiving image uploads
+ * Album name is passed with the post, and should be created in case of new album 
+ */
+@Scope("COMPOSITE")
+public class JCRImageUploadServiceImpl extends HttpServlet implements ImageUploadService {
+    private static final Logger logger = Logger.getLogger(JCRImageUploadServiceImpl.class.getName());
+
+    private static final long serialVersionUID = -7842318322982743234L;
+    public static final long MAX_UPLOAD_ZIP_IN_MEGS = 30;
+    
+    private String supportedImageTypes[] = {".jpg", ".jpeg", ".png", ".gif"};
+    
+    private ServletFileUpload upload;
+    
+    /**
+     * Initialize the component.
+     */
+    @Init
+    public void initialize() throws IOException {
+        upload = new ServletFileUpload(new DiskFileItemFactory());
+        upload.setSizeMax(MAX_UPLOAD_ZIP_IN_MEGS * 1024 * 1024);
+    }
+
+    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
+        response.setContentType("text/html");
+
+        boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
+        if (!isMultipartContent) {
+            return;
+        }
+
+        try {
+            List<FileItem> fields = (List<FileItem>) upload.parseRequest(request);
+            if(logger.isLoggable(Level.INFO)) {
+                logger.log(Level.INFO, "Number of fields: " + fields.size());
+            }
+            
+            Iterator<FileItem> fileItems = fields.iterator();
+
+            if (!fileItems.hasNext()) {
+                if(logger.isLoggable(Level.INFO)) {
+                    logger.log(Level.INFO, "No fields found");
+                }
+                return;
+            }
+
+            String albumName = "";
+            StringBuffer sb = new StringBuffer();
+            while (fileItems.hasNext()) {
+                FileItem fileItem = fileItems.next();
+
+                if (fileItem.getFieldName().equalsIgnoreCase("albumName")) {
+                    albumName = fileItem.getString();
+                }
+                boolean isFormField = fileItem.isFormField();
+                
+                if (!isFormField) {
+                    String fileName = fileItem.getName();
+                    
+                    if(logger.isLoggable(Level.INFO)) {
+                        logger.log(Level.INFO, "fileName:"+fileName);
+                    }
+
+                    InputStream inStream = fileItem.getInputStream();
+                    List<Image> pictures = new ArrayList<Image>();
+
+                    if (isArchive(inStream)) {
+                        ArchiveFileExtractor archiveFileExtractor = new ArchiveFileExtractor(supportedImageTypes);
+                        pictures = archiveFileExtractor.extractArchive(inStream);
+                    } else {
+                        // this is a picture file and not the archive file
+                        Image picture = new Image(fileName, new Date(), inStream);
+                        pictures.add(picture);
+                    }
+
+                    for (Image picture : pictures) {
+                        addPictureToAlbum(albumName, picture);
+                    }
+                    sb.append("file=uploaded/" + fileName);
+                    sb.append(",name=" + fileName);
+                    //sb.append(",error=Not recognized file type");
+                }
+            }
+            PrintWriter out = response.getWriter();
+            out.write(sb.toString());
+
+        } catch (FileUploadException e) {
+            System.out.println("Error: " + e.getMessage());
+            e.printStackTrace();
+        } catch (Exception e) {
+            System.out.println("Error: " + e.getMessage());
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * @param albumName String
+     * @param picture Picture
+     */
+    private void addPictureToAlbum(String albumName, Image image) {
+    	Gallery gallery = new GalleryImpl();
+    	gallery.addAlbum(albumName);
+        Album album = new AlbumImpl(albumName);
+        album.addPicture(image);
+    }
+    
+    /**
+     * Test whether this stream is of archive or not
+     * 
+     * @param inStream InputStream
+     * @return boolean
+     */
+    private static boolean isArchive(InputStream inStream) {
+        ArchiveStreamFactory streamFactory = new ArchiveStreamFactory();
+        try {
+            streamFactory.createArchiveInputStream(inStream);
+            return true;
+        } catch (ArchiveException e) {
+            e.printStackTrace();
+        }
+        return false;
+    }
+}
diff --git a/photark-jcr/src/main/java/org/apache/photark/upload/ArchiveFileExtractor.java b/photark-jcr/src/main/java/org/apache/photark/jcr/util/ArchiveFileExtractor.java
similarity index 98%
rename from photark-jcr/src/main/java/org/apache/photark/upload/ArchiveFileExtractor.java
rename to photark-jcr/src/main/java/org/apache/photark/jcr/util/ArchiveFileExtractor.java
index 6b31477..b994e9f 100644
--- a/photark-jcr/src/main/java/org/apache/photark/upload/ArchiveFileExtractor.java
+++ b/photark-jcr/src/main/java/org/apache/photark/jcr/util/ArchiveFileExtractor.java
@@ -17,7 +17,7 @@
  * under the License.
  */
 
-package org.apache.photark.upload;
+package org.apache.photark.jcr.util;
 
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
diff --git a/photark-jcr/src/main/java/org/apache/photark/upload/FileUploader.java b/photark-jcr/src/main/java/org/apache/photark/upload/FileUploader.java
deleted file mode 100644
index 2d12f52..0000000
--- a/photark-jcr/src/main/java/org/apache/photark/upload/FileUploader.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.photark.upload;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-import org.apache.commons.compress.archivers.ArchiveException;
-import org.apache.commons.compress.archivers.ArchiveStreamFactory;
-import org.apache.photark.Image;
-
-public class FileUploader {
-
-    private String entryTypes[] = {".jpg", ".jpeg", ".png", ".gif"};
-
-    public FileUploader() {
-    }
-
-    public List<Image> uploadFile(InputStream inStream, String fileName) throws IOException {
-
-        List<Image> pictures = new ArrayList<Image>();
-
-        if (isArchive(inStream)) {
-            ArchiveFileExtractor archiveFileExtractor = new ArchiveFileExtractor(entryTypes);
-            pictures = archiveFileExtractor.extractArchive(inStream);
-        } else {
-            // this is a picture file and not the archive file
-            Image picture = new Image(fileName, new Date(), inStream);
-            pictures.add(picture);
-        }
-        return pictures;
-    }
-
-    /**
-     * Test whether this stream is of archive or not
-     * 
-     * @param inStream InputStream
-     * @return boolean
-     */
-    public boolean isArchive(InputStream inStream) {
-        ArchiveStreamFactory streamFactory = new ArchiveStreamFactory();
-        try {
-            streamFactory.createArchiveInputStream(inStream);
-            return true;
-        } catch (ArchiveException e) {
-            e.printStackTrace();
-        }
-        return false;
-    }
-}
diff --git a/photark-jcr/src/main/java/org/apache/photark/upload/PhotoUploadServlet.java b/photark-jcr/src/main/java/org/apache/photark/upload/PhotoUploadServlet.java
deleted file mode 100644
index dfaa21a..0000000
--- a/photark-jcr/src/main/java/org/apache/photark/upload/PhotoUploadServlet.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.photark.upload;
-
-import java.io.BufferedInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintWriter;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.fileupload.FileItem;
-import org.apache.commons.fileupload.FileItemFactory;
-import org.apache.commons.fileupload.FileUploadException;
-import org.apache.commons.fileupload.disk.DiskFileItemFactory;
-import org.apache.commons.fileupload.servlet.ServletFileUpload;
-import org.apache.photark.Image;
-import org.apache.photark.services.album.Album;
-import org.apache.photark.services.album.jcr.AlbumImpl;
-import org.apache.photark.services.gallery.Gallery;
-import org.apache.photark.services.gallery.jcr.GalleryImpl;
-
-/**
- * Servlet responsible for receiving image uploads
- * Album name is passed with the post, and should be created in case of new album 
- */
-public class PhotoUploadServlet extends HttpServlet {
-
-    private static final long serialVersionUID = -7842318322982743234L;
-    public static final long MAX_UPLOAD_ZIP_IN_MEGS = 30;
-
-    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
-        doPost(request, response);
-    }
-
-    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
-        response.setContentType("text/html");
-
-        boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
-        if (!isMultipartContent) {
-            return;
-        }
-
-        FileItemFactory factory = new DiskFileItemFactory();
-        ServletFileUpload upload = new ServletFileUpload(factory);
-        upload.setSizeMax(MAX_UPLOAD_ZIP_IN_MEGS * 1024 * 1024);
-
-        try {
-            List<FileItem> fields = upload.parseRequest(request);
-            System.out.println("Number of fields: " + fields.size());
-            Iterator<FileItem> it = fields.iterator();
-
-            if (!it.hasNext()) {
-                System.out.println("No fields found");
-                return;
-            }
-
-            String albumName = "";
-            StringBuffer sb = new StringBuffer();
-            while (it.hasNext()) {
-                FileItem fileItem = it.next();
-
-                if (fileItem.getFieldName().equalsIgnoreCase("albumName")) {
-                    albumName = fileItem.getString();
-                }
-                boolean isFormField = fileItem.isFormField();
-                
-                if (!isFormField) {
-                    String fileName = fileItem.getName();
-                    System.out.println("fileName:"+fileName);
-                    InputStream inStream = fileItem.getInputStream();
-
-                    FileUploader uploader = new FileUploader();
-                    List<Image> pictures = uploader.uploadFile(new BufferedInputStream(inStream), fileName);
-
-                    for (Image picture : pictures) {
-                        addPictureToAlbum(albumName, picture);
-                    }
-                    sb.append("file=uploaded/" + fileName);
-                    sb.append(",name=" + fileName);
-                    sb.append(",error=Not recognized file type");
-                }
-            }
-            PrintWriter out = response.getWriter();
-            out.write(sb.toString());
-
-        } catch (FileUploadException e) {
-            System.out.println("Error: " + e.getMessage());
-            e.printStackTrace();
-        } catch (Exception e) {
-            System.out.println("Error: " + e.getMessage());
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * @param albumName String
-     * @param picture Picture
-     */
-    private void addPictureToAlbum(String albumName, Image image) {
-    	Gallery gallery = new GalleryImpl();
-    	gallery.addAlbum(albumName);
-        Album album = new AlbumImpl(albumName);
-        album.addPicture(image);
-    }
-}
diff --git a/photark-ui/src/main/webapp/constants.js b/photark-ui/src/main/webapp/constants.js
index 82bdb34..3cf149d 100644
--- a/photark-ui/src/main/webapp/constants.js
+++ b/photark-ui/src/main/webapp/constants.js
@@ -25,4 +25,4 @@
 	photark.constants = {};
 }
 
-photark.constants.GalleryServiceEndpoint = "/photark/Gallery?smd";
\ No newline at end of file
+photark.constants.GalleryServiceEndpoint = "GalleryService?smd";
\ No newline at end of file
diff --git a/photark-ui/src/main/webapp/gallery.html b/photark-ui/src/main/webapp/gallery.html
index b7fb531..d83e167 100644
--- a/photark-ui/src/main/webapp/gallery.html
+++ b/photark-ui/src/main/webapp/gallery.html
@@ -103,7 +103,7 @@
 			
 				var albumName = galleryAlbums[i].name;
 				var img = document.createElement("img");
-				img.src = window.location.href + "ImageDisplayer/"+ albumName +"/" + albumCovers[i];
+				img.src = window.location.href + "gallery/"+ albumName +"/" + albumCovers[i];
 				var img_html = "<img src=" + img.src + " class=\"slideImage\" height=25% width=25% ondragstart=\"return false\" onselectstart=\"return false\" oncontextmenu=\"return false\" galleryimg=\"no\" usemap=\"#imagemap\" alt=\"\"/>";
 				var html = "<a href=\"javascript:initializeAlbum('" + albumName + "')\">" + img_html + "</a>";
 				column.innerHTML = html;
@@ -163,7 +163,7 @@
 	        document.getElementById("albumImage").width=this.width;
 	        document.getElementById("albumImage").height=this.height;
 	    }
-	    img.src = window.location.href + "ImageDisplayer/"+ this.albumName +"/" + albumItems[albumPos];
+	    img.src = window.location.href + "gallery/"+ this.albumName +"/" + albumItems[albumPos];
 	    return false;
 	}
 	
diff --git a/photark-webapp/src/main/webapp/WEB-INF/web.composite b/photark-webapp/src/main/webapp/WEB-INF/web.composite
index 31a8c52..dad9cd3 100644
--- a/photark-webapp/src/main/webapp/WEB-INF/web.composite
+++ b/photark-webapp/src/main/webapp/WEB-INF/web.composite
@@ -27,14 +27,14 @@
    		<property name="name">gallery</property>
    		<service name="Gallery">
    			<interface.java interface="org.apache.photark.services.gallery.Gallery"/>
-   			<tuscany:binding.jsonrpc uri="/Gallery"/>
+   			<tuscany:binding.jsonrpc uri="/GalleryService"/>
    		</service>
     </component>
     
-    <component name="ImageDisplayer">
-		<implementation.java class="org.apache.photark.services.ImageDisplayerImpl"/>
-		<service name="ImageDisplayer">
-			<tuscany:binding.http uri="/ImageDisplayer"/>
+    <component name="ImageServiceComponent">
+		<implementation.java class="org.apache.photark.jcr.services.JCRImageCollectionImpl"/>
+		<service name="ImageCollection">
+			<tuscany:binding.http uri="/gallery"/>
 		</service>    	  	
 	</component>
     
diff --git a/photark-webapp/src/main/webapp/WEB-INF/web.xml b/photark-webapp/src/main/webapp/WEB-INF/web.xml
index ed5e3fb..7caf9a5 100644
--- a/photark-webapp/src/main/webapp/WEB-INF/web.xml
+++ b/photark-webapp/src/main/webapp/WEB-INF/web.xml
@@ -37,16 +37,6 @@
 		<url-pattern>/*</url-pattern>
 	</filter-mapping>
 
-	<servlet>
-		<servlet-name>Upload</servlet-name>
-		<servlet-class>org.apache.photark.upload.PhotoUploadServlet</servlet-class>
-	</servlet>
-
-	<servlet-mapping>
-		<servlet-name>Upload</servlet-name>
-		<url-pattern>/admin/Upload</url-pattern>
-	</servlet-mapping>
-
 	<welcome-file-list id="WelcomeFileList">
 		<welcome-file>gallery.html</welcome-file>
 	</welcome-file-list>
diff --git a/photark/src/main/java/org/apache/photark/services/ImageDisplayer.java b/photark/src/main/java/org/apache/photark/services/ImageCollection.java
similarity index 89%
rename from photark/src/main/java/org/apache/photark/services/ImageDisplayer.java
rename to photark/src/main/java/org/apache/photark/services/ImageCollection.java
index c8feff5..4a2109c 100644
--- a/photark/src/main/java/org/apache/photark/services/ImageDisplayer.java
+++ b/photark/src/main/java/org/apache/photark/services/ImageCollection.java
@@ -24,7 +24,10 @@
 import org.apache.tuscany.sca.data.collection.Collection;
 import org.oasisopen.sca.annotation.Remotable;
 
+/**
+ * Image collection component
+ */
 @Remotable
-public interface ImageDisplayer extends Collection<String, InputStream> {
+public interface ImageCollection extends Collection<String, InputStream> {
 
 }
diff --git a/photark/src/main/java/org/apache/photark/services/ImageDisplayer.java b/photark/src/main/java/org/apache/photark/services/ImageUploadService.java
similarity index 84%
copy from photark/src/main/java/org/apache/photark/services/ImageDisplayer.java
copy to photark/src/main/java/org/apache/photark/services/ImageUploadService.java
index c8feff5..95acff3 100644
--- a/photark/src/main/java/org/apache/photark/services/ImageDisplayer.java
+++ b/photark/src/main/java/org/apache/photark/services/ImageUploadService.java
@@ -19,12 +19,11 @@
 
 package org.apache.photark.services;
 
-import java.io.InputStream;
+import javax.servlet.Servlet;
 
-import org.apache.tuscany.sca.data.collection.Collection;
 import org.oasisopen.sca.annotation.Remotable;
 
 @Remotable
-public interface ImageDisplayer extends Collection<String, InputStream> {
+public interface ImageUploadService extends Servlet {
 
 }