You are viewing a plain text version of this content. The canonical link for it is here.
Posted to olio-commits@incubator.apache.org by sh...@apache.org on 2009/11/02 18:20:06 UTC
svn commit: r831998 - in /incubator/olio/webapp/java/trunk/ws/apps/webapp:
src/conf/ src/java/org/apache/olio/webapp/controller/
src/java/org/apache/olio/webapp/fileupload/
src/java/org/apache/olio/webapp/model/
src/java/org/apache/olio/webapp/rest/ sr...
Author: shanti
Date: Mon Nov 2 18:20:05 2009
New Revision: 831998
URL: http://svn.apache.org/viewvc?rev=831998&view=rev
Log:
Fixes for OLIO-40. Extensive since primary key for PERSON changed to
new field.
Removed:
incubator/olio/webapp/java/trunk/ws/apps/webapp/web/person.jsp
Modified:
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/conf/orm.xml
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/conf/persistence.xml
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/controller/ArtifactAction.java
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/fileupload/FileUploadHandler.java
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/CommentsRating.java
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/Invitation.java
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/ModelFacade.java
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/Person.java
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/SocialEvent.java
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/EventRestAction.java
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/PersonRestAction.java
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/UsersResource.java
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/ImageScaler.java
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/WebappUtil.java
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/WriteThroughInputStream.java
incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/fs/local/LocalFileSystem.java
incubator/olio/webapp/java/trunk/ws/apps/webapp/web/AjaxRequest.js
incubator/olio/webapp/java/trunk/ws/apps/webapp/web/WEB-INF/web.xml
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/conf/orm.xml
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/conf/orm.xml?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/conf/orm.xml (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/conf/orm.xml Mon Nov 2 18:20:05 2009
@@ -38,6 +38,11 @@
</named-query>
</entity>
<entity name="Person" class="org.apache.olio.webapp.model.Person">
+ <named-query name="getUserByName">
+ <query>SELECT u FROM Person u WHERE u.userName = :userName</query>
+ <hint name="eclipselink.query-results-cache" value="true"/>
+ <hint name="eclipselink.query-results-cache.size" value="500"/>
+ </named-query>
<named-query name="getPostedEvents">
<query>SELECT s FROM SocialEvent s WHERE s.submitterUserName = :submitter</query>
<hint name="eclipselink.query-results-cache" value="true"/>
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/conf/persistence.xml
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/conf/persistence.xml?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/conf/persistence.xml (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/conf/persistence.xml Mon Nov 2 18:20:05 2009
@@ -28,17 +28,12 @@
-->
<jta-data-source>jdbc/BPWebappDB</jta-data-source>
<properties>
- <!--property name="toplink.ddl-generation" value="create-tables" /-->
- <!-- property name="toplink.logging.level" value="SEVERE"/ -->
<property name="eclipselink.target-server" value="SunAS9"/>
<!-- for eclipselink 1.0 -->
+ <!--property name="eclipselink.ddl-generation" value="create-tables" -->
<property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.MySQLPlatform"/>
<!--property name="eclipselink.logging.level" value="FINE"/-->
- <!-- for eclipselink 0.9 -->
- <!--property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.MySQL4Platform"/-->
- <!--property name="eclipselink.ddl-generation" value="create-tables"/-->
- <!--property name="eclipselink.ddl-generation.output-mode" value="database" /-->
</properties>
</persistence-unit>
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/controller/ArtifactAction.java
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/controller/ArtifactAction.java?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/controller/ArtifactAction.java (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/controller/ArtifactAction.java Mon Nov 2 18:20:05 2009
@@ -76,11 +76,21 @@
// Modified for DFS support
FileSystem fs = ServiceLocator.getInstance().getFileSystem();
-
+ /*
+ * Shanti: Do not try and get image path here. Delegate to filesystem
// look for file in default location such as WEB-INF
String imagePath = WebappUtil.getArtifactLocalionDir() + pathInfo;
+ */
+ // Strip leading slash from pathInfo
+ String imagePath;
+ if (pathInfo.charAt(0) == '/')
+ imagePath = pathInfo.substring(1);
+ else
+ imagePath = pathInfo;
+
logger.finer("Image path = " + imagePath);
File imageFile = new File(imagePath);
+
/* Assume image exists -- This was done to reduce FileSystem interaction
if(!fs.exists(imagePath)) {
System.out.println ("Could not find file - " + imagePath);
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/fileupload/FileUploadHandler.java
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/fileupload/FileUploadHandler.java?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/fileupload/FileUploadHandler.java (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/fileupload/FileUploadHandler.java Mon Nov 2 18:20:05 2009
@@ -27,33 +27,23 @@
*/
package org.apache.olio.webapp.fileupload;
-import org.apache.olio.webapp.util.fs.FileSystem;
+import org.apache.commons.fileupload.FileItemIterator;
+import org.apache.commons.fileupload.FileItemStream;
+import org.apache.commons.fileupload.servlet.ServletFileUpload;
+import org.apache.olio.webapp.controller.WebConstants;
import org.apache.olio.webapp.util.ServiceLocator;
import org.apache.olio.webapp.util.WebappConstants;
-import org.apache.olio.webapp.controller.WebConstants;
-import org.apache.olio.webapp.model.Person;
-import org.apache.olio.webapp.security.SecurityHandler;
import org.apache.olio.webapp.util.WebappUtil;
-import java.io.IOException;
-import java.io.File;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.logging.Logger;
-import java.util.logging.Level;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
+import org.apache.olio.webapp.util.fs.FileSystem;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
-
-import org.apache.commons.fileupload.FileItemIterator;
-import org.apache.commons.fileupload.FileItemStream;
-import org.apache.commons.fileupload.servlet.ServletFileUpload;
+import java.io.*;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.logging.Level;
+import java.util.logging.Logger;
/**
* This class uses Apache Commons FileUpload to parse the multi-part mime that is sent via the HttpServletRequest InputStream.
@@ -66,7 +56,10 @@
private static Logger logger = Logger.getLogger(FileUploadHandler.class.getName());
private FileUploadStatus fileUploadStatus = null;
-
+ private FileItemIterator itemIter;
+ private FileItemStream item;
+ private Hashtable<String, String> requestParams;
+
/**
* Default location of upload directory is /domain_dir/lib/upload, unless the Sun Appserver system property exits, then it will
* use the domain's lib/upload directory instead
@@ -157,12 +150,13 @@
}
/**
- * Invoke the fileupload process that reads the input from the HttpServletRequest inputStream. Since this
- * component accesses the HttpServletRequest directly, this component currently may not work from within a portlet.
- * This method assumes that the fileUploadStatus will be set using the managed property functionality of a backing bean.
- * This relationship is specified in the faces-config.xml file. This method is accessed through the Shale-remoting dynamic framework.
+ * Handles the initial fields up to the first upload field. This will
+ * allow creating the database entry and obtaining the auto-generated
+ * ids.
+ * @return A hash table with the initial field values
*/
- public Hashtable<String, String> handleFileUpload(HttpServletRequest request, HttpServletResponse response) {
+ public Hashtable<String, String> getInitialParams(HttpServletRequest request, HttpServletResponse response) {
+
// print out header for
Enumeration enumx = request.getHeaderNames();
String key = "";
@@ -172,10 +166,9 @@
listx += "\n" + key + ":" + request.getHeader(key);
}
logger.fine("Incoming Header Item:" + listx);
-
- // enable progress bar (this managed bean that is in the session could be comp specific, but I can't create the component specific
+ // enable progress bar (this managed bean that is in the session could be comp specific, but I can't create the component specific
// session object until I have the components name. For now use static key through backing bean).
- // Use session to allow the monitoring of the fileupload based
+ // Use session to allow the monitoring of the fileupload based
HttpSession session = request.getSession();
FileUploadStatus status = new FileUploadStatus();
@@ -203,88 +196,104 @@
// Now we should have the componentsName and upload directory to setup remaining upload of file items
String compName = htUpload.get(FileUploadUtil.COMPONENT_NAME);
status.setName(compName);
- // get directory to dump file into
- String serverLocationDir = htUpload.get(compName + "_" + FileUploadUtil.SERVER_LOCATION_DIR);
- logger.fine("\n*** locationDir=" + serverLocationDir);
-
- File fileDir = null;
- if (serverLocationDir == null) {
- // ??? need to fix incase other than glassfish
- // set to default dir location for glassfish
- serverLocationDir = System.getProperty("com.sun.aas.instanceRoot");
- if (serverLocationDir != null) {
- serverLocationDir = WebappConstants.WEBAPP_IMAGE_DIRECTORY;
- fileDir = new File(serverLocationDir);
- fileDir.mkdirs();
- } else {
- // use the standard tmp directory
- logger.fine("\n*** other default locationDir=" + serverLocationDir);
-
- //fileDir = (File) request.getAttribute("javax.servlet.context.tempdir");
- // we don't need the tmp directory since we are avoiding writing twice - once to /tmp and then to filestore
- // pick this up from the system environment(or web.xml) that WebappUtil sets
- serverLocationDir = WebappConstants.WEBAPP_IMAGE_DIRECTORY;
- serverLocationDir = fileDir.toString();
- }
- } else {
- // make sure directory exists, don't create automatically for security reasons
- fileDir = new File(serverLocationDir);
- }
-
- // make sure dir exists and is writable
- if (fileDir == null || !fileDir.isDirectory() || !fileDir.canWrite()) {
- // error, directory doesn't exist or isn't writable
- status.setUploadError("Directory \"" + fileDir.toString() + "\" doesn't exist!");
- logger.log(Level.SEVERE, "directory.inaccessable", fileDir.toString());
- return null;
- }
// Parse the request and return list of "FileItem" whle updating status
FileItemIterator iter = upload.getItemIterator(request);
status.setReadingComplete();
- FileItemStream item = null;
- String itemName = null;
-
while (iter.hasNext()) {
item = iter.next();
if (item.isFormField()) {
// handle a form item being uploaded
- itemName = item.getFieldName();
+ String itemName = item.getFieldName();
- // process form(non-file) item
+ // process form(non-file) item200002
int size = formItemFound(item, htUpload);
updateSessionStatus(itemName, size);
logger.fine("Form field item:" + itemName);
} else {
- String username = htUpload.get(WebConstants.SUBMITTER_USER_NAME_PARAM);
- if (username == null) {
- Person person = SecurityHandler.getInstance().getLoggedInPerson(request);
- if (person != null) {
- username = person.getUserName();
- }
- }
-
- fileItemFound(item, htUpload, serverLocationDir, username);
+ // At the first find of an uploaded file, stop.
+ // We need to insert our record first in order
+ // to find the id.
+ break;
}
}
-
- // put upload to 100% to handle rounding errors in status calc
- status.setUploadComplete();
- logger.fine("Final session status - " + status);
-
+ itemIter = iter;
} catch (Exception e) {
status.setUploadError("FileUpload didn't complete successfully. Exception received:" + e.toString());
logger.log(Level.SEVERE, "file.upload.exception", e);
}
}
-
+ fileUploadStatus = status;
+ requestParams = htUpload;
return htUpload;
}
+
+
+ /**
+ * Invoke the fileupload process that reads the input from the HttpServletRequest inputStream. Since this
+ * component accesses the HttpServletRequest directly, this component currently may not work from within a portlet.
+ * This method assumes that the fileUploadStatus will be set using the managed property functionality of a backing bean.
+ * This relationship is specified in the faces-config.xml file. This method is accessed through the Shale-remoting dynamic framework.
+ */
+ public Hashtable<String, String> handleFileUpload(String id, HttpServletRequest request, HttpServletResponse response) {
+ File fileDir = null;
+ String compName = requestParams.get(FileUploadUtil.COMPONENT_NAME);
+ String serverLocationDir = requestParams.get(compName + "_" + FileUploadUtil.SERVER_LOCATION_DIR);
+ logger.finest("\n*** locationDir=" + serverLocationDir);
+ if (serverLocationDir == null) {
+ serverLocationDir = WebappConstants.WEBAPP_IMAGE_DIRECTORY;
+ fileDir = new File(serverLocationDir);
+ fileDir.mkdirs();
+ } else {
+ // make sure directory exists, don't create automatically for security reasons
+ fileDir = new File(serverLocationDir);
+ }
+ logger.finest("serverLocationDir = " + serverLocationDir);
+ // make sure dir exists and is writable
+ if (fileDir == null || !fileDir.isDirectory() || !fileDir.canWrite()) {
+ // error, directory doesn't exist or isn't writable
+ fileUploadStatus.setUploadError("Directory \"" + fileDir.toString() + "\" doesn't exist!");
+ logger.log(Level.SEVERE, "directory.inaccessable:", fileDir.toString());
+ return null;
+ }
+ try {
+ for (;;) {
+ if (item.isFormField()) {
+ // handle a form item being uploaded
+ String itemName = item.getFieldName();
+
+ // process form(non-file) item
+ int size = formItemFound(item, requestParams);
+ updateSessionStatus(itemName, size);
+
+ logger.fine("Form field item:" + itemName);
+
+ } else {
+ fileItemFound(item, requestParams, serverLocationDir, id);
+ }
+ if (itemIter.hasNext())
+ item = itemIter.next();
+ else
+ break;
+ }
+
+ // put upload to 100% to handle rounding errors in status calc
+ fileUploadStatus.setUploadComplete();
+ logger.fine("Final session status - " + fileUploadStatus);
+
+ } catch (Exception e) {
+ fileUploadStatus.setUploadError("FileUpload didn't complete successfully. Exception received:" + e.toString());
+ logger.log(Level.SEVERE, "file.upload.exception:", e);
+ }
+ return requestParams;
+ }
+
+
/**
* Handle upload of a standard form item
*
@@ -302,20 +311,15 @@
// Read from the stream
int i = 0;
-
while ((i = is.read(buf)) != -1) {
strb.append(new String(buf, 0, i));
size += i;
}
-
String value = strb.toString();
// put in Hashtable for later access
logger.fine("Inserting form item in map " + key + " = " + value);
-
htUpload.put(key, value);
-
-
} catch (IOException ex) {
Logger.getLogger(FileUploadHandler.class.getName()).log(Level.SEVERE, null, ex);
} finally {
@@ -336,15 +340,10 @@
* @param serverLocationDir The Status Hashtable that contains the items that have been uploaded for post-processing use
*/
protected void fileItemFound(FileItemStream item, Hashtable<String, String> htUpload,
- String serverLocationDir, String user) throws Exception {
- if (user == null) {
- user = "guest";
- }
+ String serverLocationDir, String id) throws Exception {
+
String fileLocation = null;
String fileName = item.getName();
- //issue is that the same filename on client machine is being used on mastermachine. this could lead to conflicts.
- //use the username since is unique for image name. retrieve this from the Hashtable.
- String username = htUpload.get(WebConstants.USER_NAME_PARAM);
if (fileName != null && !fileName.equals("")) {
// see if IE on windows which send full path with item, but just filename
@@ -364,45 +363,35 @@
logger.fine("Have full path, need to truncate \n" + item.getName() + "\n" + fileName);
}
fileLocation = serverLocationDir + File.separator + fileName;
- DateFormat dateFormat = new SimpleDateFormat("MMMMddyyyy_hh_mm_ss");
- Date date = null;
String thumbnailName;
- String thumbnailLocation;
String ext = WebappUtil.getFileExtension(fileName);
if (item.getFieldName().equals(WebConstants.UPLOAD_PERSON_IMAGE_PARAM)) {
- fileName = "p" + username;
- thumbnailName = fileName + "_thumb" + ext;
- thumbnailLocation = serverLocationDir + "/" + thumbnailName;
+ fileName = "P" + id;
+ thumbnailName = fileName + 'T' + ext;
// Append the extension
fileName += ext;
- fileLocation = serverLocationDir + "/" + fileName;
- writeWithThumbnail(item, fileLocation, thumbnailLocation);
+ writeWithThumbnail(item, fileName, thumbnailName);
+ htUpload.put(WebConstants.UPLOAD_PERSON_IMAGE_PARAM, fileName);
htUpload.put(WebConstants.UPLOAD_PERSON_IMAGE_THUMBNAIL_PARAM, thumbnailName);
} else if (item.getFieldName().equals(WebConstants.UPLOAD_PERSON_IMAGE_THUMBNAIL_PARAM)) {
- fileName = "p" + username + "_t" + ext;
- fileLocation = serverLocationDir + "/" + fileName;
- write(item, fileLocation);
+ fileName = "P" + id + "T" + ext;
+ write(item, fileName);
htUpload.put(WebConstants.UPLOAD_PERSON_IMAGE_THUMBNAIL_PARAM, fileName);
} else if (item.getFieldName().equals(WebConstants.UPLOAD_EVENT_IMAGE_PARAM)) {
- date = new Date();
//String submitter = htUpload.get(WebConstants.SUBMITTER_USER_NAME_PARAM);
- fileName = "e" + user + dateFormat.format(date);
- thumbnailName = fileName + "_thumb" + ext;
- thumbnailLocation = serverLocationDir + "/" + thumbnailName;
+ fileName = "E" + id;
+ thumbnailName = fileName + 'T' + ext;
fileName += ext;
- fileLocation = serverLocationDir + "/" + fileName;
- writeWithThumbnail(item, fileLocation, thumbnailLocation);
+ writeWithThumbnail(item, fileName, thumbnailName);
+ htUpload.put(WebConstants.UPLOAD_EVENT_IMAGE_PARAM, fileName);
htUpload.put(WebConstants.UPLOAD_EVENT_IMAGE_THUMBNAIL_PARAM, thumbnailName);
} else if (item.getFieldName().equals("eventThumbnail")) {
- date = new Date();
- fileName = "e" + user + dateFormat.format(date) + "_t" + ext;
- fileLocation = serverLocationDir + "/" + fileName;
- write(item, fileLocation);
+ fileName = "E" + id + 'T' + ext;
+ write(item, fileName);
htUpload.put(WebConstants.UPLOAD_EVENT_IMAGE_THUMBNAIL_PARAM, fileName);
} else if (item.getFieldName().equals("upload_event_literature")) {
- date = new Date();
- fileName = "e" + user + dateFormat.format(date) + ext;
+ fileName = "E" + id + 'L' + ext;
fileLocation = serverLocationDir + "/" + fileName;
write(item, fileLocation);
htUpload.put(WebConstants.UPLOAD_LITERATURE_PARAM, fileName);
@@ -431,7 +420,8 @@
* If the post processing method wants to provide a custom response, the method can call the "enableCustomReturn" method on the
* FileUploadStatus object so that the default fileupload response will not be sent.
*
- * @param htUpload The Status Hashtable that contains the items that have been uploaded for post-processing use
+ * @param writer The writer to write the output
+ * @param status The Status object that contains the items that have been uploaded for post-processing use
*/
public static void writeUploadResponse(PrintWriter writer, FileUploadStatus status) {
Hashtable<String, String> htUpload = status.getUploadItems();
@@ -510,10 +500,10 @@
* so the output could be monitored
*
* @param item The Commons Fileupload item being loaded
- * @param file File path to write uploaded data.
+ * @param fileName File name to write uploaded data.
* @throws Exception Exceptions propagated from Apache Commons Fileupload classes
*/
- public void write(FileItemStream item, String filePath) throws Exception {
+ public void write(FileItemStream item, String fileName) throws Exception {
// use name for update of session
String itemName = item.getName();
@@ -523,7 +513,7 @@
logger.fine("Getting fileItem from memory - " + itemName);
- OutputStream fout = fs.create(filePath);
+ OutputStream fout = fs.create(fileName);
// It would have been more efficient to use NIO if we are writing to
// the local filesystem. However, since we need to support DFS,
@@ -531,7 +521,7 @@
// TO DO: Optimize write if required.
try {
- byte[] buf = new byte[2048];
+ byte[] buf = new byte[8192];
int count, size = 0;
InputStream is = item.openStream();
while ((count = is.read(buf)) != -1) {
@@ -549,13 +539,54 @@
/**
*
* @param item FileItemStream from the file upload handler
- * @param imagePath path to the save the image.
- * @param thumbnailPath path prefix to the thumbnail. Extension is appended.
+ * @param imageName name to save the image.
+ * @param thumbnailName name to save the thumbnail. Extension is appended.
* @throws java.lang.Exception
*/
public void writeWithThumbnail(FileItemStream item,
- String imagePath, String thumbnailPath) throws Exception {
- WebappUtil.saveImageWithThumbnail(item.openStream(), imagePath, thumbnailPath);
+ String imageName, String thumbnailName) throws Exception {
+ // use name for update of session
+ String itemName = item.getName();
+
+ ServiceLocator locator = ServiceLocator.getInstance();
+
+ FileSystem fs = locator.getFileSystem();
+
+ logger.fine("Getting fileItem from memory - " + itemName);
+
+ OutputStream imgOut = null;
+ OutputStream thumbOut = null;
+ InputStream is = null;
+ try {
+ imgOut = fs.create(imageName);
+ thumbOut = fs.create(thumbnailName);
+ // It would have been more efficient to use NIO if we are writing to
+ // the local filesystem. However, since we need to support DFS,
+ // a simple solution is provided.
+ // TO DO: Optimize write if required.
+
+ is = item.openStream();
+ FileUploadStatus status = getFileUploadStatus();
+ status.setCurrentItem(itemName);
+
+ WebappUtil.saveImageWithThumbnail(is, imgOut, thumbOut, status);
+ } finally {
+ if (imgOut != null)
+ try {
+ imgOut.close();
+ } catch (IOException e) {
+ }
+ if (thumbOut != null)
+ try {
+ thumbOut.close();
+ } catch (IOException e) {
+ }
+ if (is != null)
+ try {
+ is.close();
+ } catch (IOException e) {
+ }
+ }
}
public void updateSessionStatus(String itemName, long incrementAmount) {
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/CommentsRating.java
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/CommentsRating.java?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/CommentsRating.java (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/CommentsRating.java Mon Nov 2 18:20:05 2009
@@ -42,6 +42,7 @@
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Transient;
+import javax.persistence.JoinColumn;
/**
* Entity class CommentsRating
@@ -139,7 +140,7 @@
*/
@Override
public String toString() {
- return "com.sun.javaee.blueprints.webapp.model.CommentRating[id=" + commentsRatingId + "]";
+ return "org.apache.olio.webapp.model.CommentRating[id=" + commentsRatingId + "]";
}
@Lob
@@ -170,6 +171,11 @@
}
@OneToOne
+ @JoinColumn(
+ name = "USERNAME_USERNAME",
+ referencedColumnName = "USERNAME",
+ unique = true
+ )
public Person getUserName() {
return userName;
}
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/Invitation.java
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/Invitation.java?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/Invitation.java (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/Invitation.java Mon Nov 2 18:20:05 2009
@@ -26,7 +26,7 @@
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
-
+import javax.persistence.JoinColumn;
import java.util.logging.Logger;
/**
@@ -59,8 +59,18 @@
@Id
private int invitationID;
@ManyToOne
+ @JoinColumn(
+ name = "REQUESTOR_USERNAME",
+ referencedColumnName = "USERNAME",
+ unique = true
+ )
private Person requestor;
@ManyToOne
+ @JoinColumn(
+ name = "CANDIDATE_USERNAME",
+ referencedColumnName = "USERNAME",
+ unique = true
+ )
private Person candidate;
private boolean isAccepted;
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/ModelFacade.java
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/ModelFacade.java?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/ModelFacade.java (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/ModelFacade.java Mon Nov 2 18:20:05 2009
@@ -134,7 +134,8 @@
public int addInvitation(Person loggedInUser, Invitation invitation) {
EntityManager em = emf.createEntityManager();
- Person friend = em.find(Person.class, invitation.getCandidate().getUserName());
+ //Person friend = em.find(Person.class, invitation.getCandidate().getUserName());
+ Person friend = findPerson(invitation.getCandidate().getUserName());
try {
utx.begin();
logger.finer("Before: size of outgoingInvitations for loggedInUser " + loggedInUser.getOutgoingInvitations().size());
@@ -172,15 +173,20 @@
public Person findPerson(String userName) {
EntityManager em = emf.createEntityManager();
- Person p = null;
+ logger.finest("In findPerson for " + userName);
try {
- p = em.find(Person.class, userName);
- return p;
- } catch (Exception e) {
+ Query q = em.createNamedQuery("getUserByName");
+ q.setParameter("userName", userName);
+ List<Person> users = q.getResultList();
+ if (users.size() < 1) {
+ logger.warning("Person with username = " + userName + " not found");
+ return null;
+ } else {
+ return users.get(0);
+ }
} finally {
em.close();
}
- return p;
}
/**
@@ -214,8 +220,13 @@
EntityManager em = emf.createEntityManager();
Query q = em.createQuery("Select i FROM Invitation i where i.requestor.userName=\'" + requestorUsername + "\'" +
" AND i.candidate.userName=\'" + candidateUsername + "\'");
- Invitation invite = (Invitation) q.getSingleResult();
- return invite;
+ // The getSingleResult doesn't work as sometimes you may have none
+ // Invitation invite = (Invitation) q.getSingleResult();
+ List<Invitation> invitations = q.getResultList();
+ if (invitations.size() > 0)
+ return(invitations.get(0));
+ else
+ return null;
}
@SuppressWarnings("unchecked")
@@ -228,26 +239,27 @@
@SuppressWarnings("unchecked")
public Person getPerson(String userName) {
+ logger.finest("In getPerson for " + userName);
if (userName == null) {
return null;
}
Person person = null;
- if (person == null) {
- EntityManager em = emf.createEntityManager();
- person = em.find(Person.class, userName);
- //Even though EclipseLink allows access of of Lazy fetched realtionships from detached
- // entities, other JPA implementations may not.
- // Manual loading of these relationships are done to support other implementations.
- // Making it eager fetch will cause cascade fetching.
- if (person != null) {
- person.getAddress();
- person.getFriends();
- person.getSocialEvents();
- person.getIncomingInvitations();
- }
- em.close();
+ // EntityManager em = emf.createEntityManager();
+ // person = em.find(Person.class, userName);
+ person = findPerson(userName);
+
+ //Even though EclipseLink allows access of of Lazy fetched realtionships from detached
+ // entities, other JPA implementations may not.
+ // Manual loading of these relationships are done to support other implementations.
+ // Making it eager fetch will cause cascade fetching.
+ if (person != null) {
+ person.getAddress();
+ person.getFriends();
+ person.getSocialEvents();
+ person.getIncomingInvitations();
}
+ // em.close();
return person;
}
@@ -269,7 +281,7 @@
utx.rollback();
} catch (Exception e) {
}
- throw new RuntimeException("Error updating rating", exe);
+ throw new RuntimeException("Error updating person", exe);
} finally {
em.close();
}
@@ -284,7 +296,8 @@
//try with em.remove instead
utx.begin();
- Person person = em.find(Person.class, userName);
+ //Person person = em.find(Person.class, userName);
+ Person person = findPerson(userName);
if (person == null) // Not a valid event
{
return;
@@ -374,8 +387,10 @@
try {
utx.begin();
//need to add error checks if friend exists etc
- Person friend = em.find(Person.class, friendUserName);
- person = em.find(Person.class, userName);
+ //Person friend = em.find(Person.class, friendUserName);
+ Person friend = findPerson(friendUserName);
+ //person = em.find(Person.class, userName);
+ person = findPerson(userName);
person.getFriends().add(friend);
//logger.finer("**** ModelFacade::addFriend about to merge, person username=" + person.getUserName() +
// " and friend username=" + friend.getUserName());
@@ -1137,6 +1152,7 @@
}
public Person login(String user_name, String password) {
+ logger.finest("In login for user " + user_name + " password " + password);
if (user_name == null || password == null) {
return null;
}
@@ -1226,7 +1242,8 @@
EntityManager em = emf.createEntityManager();
String username = inv.getRequestor().getUserName();
String candidateUsername = inv.getCandidate().getUserName();
- Person person = em.find(Person.class, username);
+ //Person person = em.find(Person.class, username);
+ Person person = findPerson(username);
person.getIncomingInvitations().remove(inv);
try {
utx.begin();
@@ -1283,11 +1300,13 @@
//outgoing
isIncoming = false;
requestor = loggedInUser;
- candidate = em.find(Person.class, inv.getCandidate().getUserName());
+ //candidate = em.find(Person.class, inv.getCandidate().getUserName());
+ candidate = findPerson(inv.getCandidate().getUserName());
} else if (loggedInUser.getUserName().equalsIgnoreCase(inv.getCandidate().getUserName())) {
//incoming
isIncoming = true;
- requestor = em.find(Person.class, inv.getRequestor().getUserName());
+ //requestor = em.find(Person.class, inv.getRequestor().getUserName());
+ requestor = findPerson(inv.getRequestor().getUserName());
candidate = loggedInUser;
}
//if incoming, then requestor is the friend, and the candidate is the loggedInUser
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/Person.java
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/Person.java?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/Person.java (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/Person.java Mon Nov 2 18:20:05 2009
@@ -27,7 +27,6 @@
import javax.persistence.ManyToMany;
import java.text.SimpleDateFormat;
import org.apache.olio.webapp.util.WebappUtil;
-import java.util.List;
import static org.apache.olio.webapp.controller.WebConstants.*;
import javax.persistence.CascadeType;
import javax.persistence.NamedQuery;
@@ -36,6 +35,10 @@
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
+import javax.persistence.TableGenerator;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.JoinColumn;
import java.util.Set;
import java.util.HashSet;
@@ -46,6 +49,8 @@
*/
@NamedQueries(
{
+ @NamedQuery(name = "getUserByName",
+ query = "SELECT u FROM Person u WHERE u.userName = :userName"),
@NamedQuery(name = "getPostedEvents",
query = "SELECT s FROM SocialEvent s WHERE s.submitterUserName = :submitter"),
@NamedQuery(name = "getIncomingInvitations",
@@ -58,7 +63,8 @@
@Entity
@Table (name="PERSON")
public class Person implements java.io.Serializable {
-
+
+ private int userID;
private String userName;
private String password;
private String firstName;
@@ -76,10 +82,7 @@
private Address address;
//used for UI display purposes
private boolean hasReceivedInvitation;
- private Collection<Person> nonFriendList = new ArrayList<Person>();
- private int friendshipRequests;
-
-
+ private Collection<Person> nonFriendList = new ArrayList<Person>();
//private Collection<SocialEvent> planToAttendEvents=new Vector<SocialEvent>();
//private Address location; //do I need some location info for viewing events listing or is it stored as cookie?
@@ -102,7 +105,18 @@
this.address = address;
}
+ @TableGenerator(name="PERSON_ID_GEN",
+ table="ID_GEN",
+ pkColumnName="GEN_KEY",
+ valueColumnName="GEN_VALUE",
+ pkColumnValue="PERSON_ID",
+ allocationSize=50000)
+ @GeneratedValue(strategy=GenerationType.TABLE,generator="PERSON_ID_GEN")
@Id
+ public int getUserID() {
+ return userID;
+ }
+
public String getUserName() {
return userName;
}
@@ -153,6 +167,12 @@
}
@ManyToMany(fetch=FetchType.LAZY)
+ /***
+ @JoinTable(
+ name = "PERSON_PERSON",
+ joinColumns = { @JoinColumn(name = "Person_USERNAME", referencedColumnName = "USERNAME"),
+ @JoinColumn(name = "friends_USERNAME", referencedColumnName = "USERNAME")})
+ */
public Collection<Person> getFriends() {
return friends;
}
@@ -197,6 +217,10 @@
return outgoingInvitations;
}
+ public void setUserID(int userID) {
+ this.userID = userID;
+ }
+
public void setOutgoingInvitations(Collection<Invitation> outgoingInvitations) {
this.outgoingInvitations = outgoingInvitations;
}
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/SocialEvent.java
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/SocialEvent.java?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/SocialEvent.java (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/model/SocialEvent.java Mon Nov 2 18:20:05 2009
@@ -89,6 +89,7 @@
this.disabled = 0;
this.createdTimestamp=new Timestamp(new Date().getTime());
}
+
/* EclipseLink 1.0 sometimes generated the same ID
* under heavy load leading to transaction failures during the insertion of
* SocialEvents (PK violation). The problem seems to happen when the allocation size is exceeded.
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/EventRestAction.java
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/EventRestAction.java?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/EventRestAction.java (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/EventRestAction.java Mon Nov 2 18:20:05 2009
@@ -18,6 +18,7 @@
package org.apache.olio.webapp.rest;
import org.apache.olio.webapp.controller.Action;
+import org.apache.olio.webapp.controller.WebConstants;
import org.apache.olio.webapp.model.Address;
import org.apache.olio.webapp.model.ModelFacade;
import org.apache.olio.webapp.util.WebappUtil;
@@ -83,7 +84,8 @@
// file upload
logger.finer("AddEvent ... ");
FileUploadHandler fuh = new FileUploadHandler();
- Hashtable<String, String> htUpload = fuh.handleFileUpload(request, response);
+ Hashtable<String, String> htUpload = fuh.getInitialParams(request, response);
+
// file is upload check for error and then write to database
if (htUpload != null) {
StringBuilder sb = new StringBuilder();
@@ -93,22 +95,31 @@
}
logger.finer("\n***elements = " + sb.toString());
SocialEvent event = null;
+ /* Don't check for submit since we're doing upload in 2 phases
+ * and we may not have read it in. We don't do updates.
String type = htUpload.get("submit");
if (type == null) {
return "/site.jsp?page=error.jsp";
}
-
- if (type != null && type.equals("Update")) {
- event = updateEvent(request, modelFacade, htUpload);
+ if (type.equals("Update")) {
+ event = getEvent(modelFacade, htUpload);
} else {
- event = createEvent(request, modelFacade, htUpload);
+ */
+ event = createEvent(request, modelFacade, htUpload);
if (request.getSession(true).getAttribute("userBean") != null) {
UserBean uBean = (UserBean) request.getSession(true).getAttribute("userBean");
uBean.setDisplayMessage("Event added successfully");
logger.log(Level.FINER, "A new Event has been added and persisted");
}
- }
- // clear the cache
+ //}
+
+ String id = String.valueOf(event.getSocialEventID());
+ htUpload = fuh.handleFileUpload(id, request, response);
+
+ // Update the event with the right stuff.
+ updateEvent(event, request, modelFacade, htUpload);
+
+ // clear the cache
WebappUtil.clearCache("/event/list");
response.sendRedirect(request.getContextPath() + "/event/detail?socialEventID=" + event.getSocialEventID());
return null;
@@ -176,7 +187,7 @@
modelFacade.updateSocialEvent(event);
}
- String s = this.getAttendeesAsJson(event.getAttendees(), status);
+ String s = getAttendeesAsJson(event.getAttendees(), status);
logger.finer("\n*** people = " + s);
response.setContentType("application/json;charset=UTF-8");
@@ -265,6 +276,7 @@
}
public SocialEvent createEvent(HttpServletRequest request, ModelFacade modelFacade, Hashtable<String, String> htUpload) {
+ /* We don't worry about the address at creation time. Only do at update.
String street1 = htUpload.get(STREET1_PARAM);
String street2 = htUpload.get(STREET2_PARAM);
String city = htUpload.get(CITY_PARAM);
@@ -272,6 +284,7 @@
String country = htUpload.get(COUNTRY_PARAM);
String zip = htUpload.get(ZIP_PARAM);
Address address = WebappUtil.handleAddress(context, street1, street2, city, state, zip, country);
+ */
String title = htUpload.get(TITLE_PARAM);
String description = htUpload.get(DESCRIPTION_PARAM);
@@ -339,7 +352,7 @@
logger.finer("\n***local = " + localCal + "\n Millis = " + localCal.getTimeInMillis());
Timestamp eventTimestamp = new Timestamp(localCal.getTimeInMillis());
- SocialEvent socialEvent = new SocialEvent(title, summary, description, submitterUserName, address, telephone, 0, 0,
+ SocialEvent socialEvent = new SocialEvent(title, summary, description, submitterUserName, null, telephone, 0, 0,
imagex, thumbImage, literaturex, eventTimestamp);
logger.finer("Event title = " + socialEvent.getTitle());
@@ -352,21 +365,23 @@
return socialEvent;
}
- public SocialEvent updateEvent(HttpServletRequest request, ModelFacade modelFacade, Hashtable<String, String> htUpload) throws IOException {
- // Update requires an id
+ public SocialEvent getEvent(ModelFacade modelFacade, Hashtable<String, String> htUpload) {
String sids = htUpload.get("socialEventID");
if (sids == null) {
throw new RuntimeException("socialEventID is not set for updateEVent");
}
- SocialEvent event = null;
try {
int id = Integer.parseInt(sids);
- event = modelFacade.getSocialEvent(id);
+ return modelFacade.getSocialEvent(id);
} catch (Exception e) {
throw new RuntimeException("updateSocialEvent: SocialEvent could not be retrieved - id = " +
sids);
}
+ }
+ public SocialEvent updateEvent(SocialEvent event, HttpServletRequest request, ModelFacade modelFacade, Hashtable<String, String> htUpload) throws IOException {
+
+ // Update requires an id
String street1 = htUpload.get(STREET1_PARAM);
String street2 = htUpload.get(STREET2_PARAM);
String city = htUpload.get(CITY_PARAM);
@@ -413,8 +428,8 @@
String thumbImage;
thumbImage = htUpload.get(UPLOAD_EVENT_IMAGE_THUMBNAIL_PARAM);
// get upload location from map
- String imageLocation = htUpload.get(UPLOAD_EVENT_IMAGE_PARAM + FileUploadUtil.FILE_LOCATION_KEY);
- logger.finer("\n image path = " + imageLocation);
+ //String imageLocation = htUpload.get(UPLOAD_EVENT_IMAGE_PARAM + FileUploadUtil.FILE_LOCATION_KEY);
+ logger.finer("\n image path = " + imagex);
// This is done during upload for efficiency.
// thumbImage=WebappUtil.constructThumbnail(imageLocation);
logger.finer("\n thumb path = " + thumbImage);
@@ -423,6 +438,9 @@
// If empty, leave the old one alone
// Delete the old images since it is being replaced
// Do the same for literature
+ // The following doesn't work for AddEvent. Since we don't support an
+ // updateEvent currently, commenting for now
+ /****
ServiceLocator locator = ServiceLocator.getInstance();
FileSystem fs = (FileSystem) locator.getFileSystem();
if (imagex != null) {
@@ -441,10 +459,12 @@
}
event.setLiteratureURL(literaturex);
}
-
- // Submitter is not necessarily an attendde
+ ****/
+ event.setImageURL(imagex);
+ event.setImageThumbURL(thumbImage);
+ event.setLiteratureURL(literaturex);
+
event = modelFacade.updateSocialEvent(event, tags);
-
logger.log(Level.FINER, "SocialEvent " + event.getSocialEventID() + " has been updated");
return event;
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/PersonRestAction.java
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/PersonRestAction.java?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/PersonRestAction.java (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/PersonRestAction.java Mon Nov 2 18:20:05 2009
@@ -75,14 +75,17 @@
if (path.equals("/person/fileuploadPerson")) {
// file upload
FileUploadHandler fuh = new FileUploadHandler();
- Hashtable<String, String> htUpload = fuh.handleFileUpload(request, response);
+ Hashtable<String, String> htUpload = fuh.getInitialParams(request, response);
+
// file is upload check for error and then write to database
if (htUpload != null) {
+ /*
StringBuilder sb = new StringBuilder();
for (String key : htUpload.keySet()) {
sb.append(key);
sb.append(",");
}
+ */
//logger.finer("\n***elements = " + sb.toString());
//createUser(request, htUpload);
@@ -92,7 +95,7 @@
boolean isEditable = Boolean.parseBoolean(request.getParameter("isEditable"));
if (isEditable) {
- newEditPerson = updateUser(request, htUpload, fuh);
+ newEditPerson = getPerson(request);
} else {
newEditPerson = createUser(request, htUpload, fuh);
}
@@ -100,6 +103,10 @@
logger.log(Level.FINER, "A new Person has been added and persisted");
request.setAttribute("displayPerson", newEditPerson);
+ String id = String.valueOf(newEditPerson.getUserID());
+ htUpload = fuh.handleFileUpload(id, request, response);
+
+ updateUser(newEditPerson, htUpload);
}
return "/site.jsp?page=personContent.jsp";
@@ -246,16 +253,19 @@
String firstName = htUpload.get(FIRST_NAME_PARAM);
String lastName = htUpload.get(LAST_NAME_PARAM);
String summary = htUpload.get(SUMMARY_PARAM);
+ /* We do the address in the update phase.
String street1 = htUpload.get(STREET1_PARAM);
String street2 = htUpload.get(STREET2_PARAM);
String city = htUpload.get(CITY_PARAM);
String state = htUpload.get(STATE_PARAM);
String country = htUpload.get(COUNTRY_PARAM);
String zip = htUpload.get(ZIP_PARAM);
+ */
String timezone = htUpload.get(TIMEZONE_PARAM);
String telephone = htUpload.get(TELEPHONE_PARAM);
String email = htUpload.get(EMAIL_PARAM);
- Address address = WebappUtil.handleAddress(context, street1, street2, city, state, zip, country);
+ // Address address = WebappUtil.handleAddress(context, street1, street2, city, state, zip, country);
+
// get image from fileupload
String imageURL = htUpload.get(UPLOAD_PERSON_IMAGE_PARAM);
@@ -271,7 +281,7 @@
" last_name" + lastName +
" summary" + summary);
- Person person = new Person(userName, password, firstName, lastName, summary, email, telephone, imageURL, thumbImage, timezone, address);
+ Person person = new Person(userName, password, firstName, lastName, summary, email, telephone, imageURL, thumbImage, timezone, null);
ModelFacade mf = (ModelFacade) context.getAttribute(MF_KEY);
//do not really need username since you set this value, not sure why it is returned
//String userName = mf.addPerson(person, userSignOn);
@@ -287,7 +297,7 @@
return person;
}
- private Person updateUser(HttpServletRequest request, Hashtable<String, String> htUpload, FileUploadHandler fuh) {
+ private Person updateUser(Person person, Hashtable<String, String> htUpload) {
String userName = htUpload.get(USER_NAME_PARAM);
String password = htUpload.get(PASSWORD_PARAM);
String firstName = htUpload.get(FIRST_NAME_PARAM);
@@ -314,28 +324,39 @@
//Person loggedInPerson = this.getPerson(request);
ModelFacade mf = (ModelFacade) context.getAttribute(MF_KEY);
Person loggedInPerson = mf.getPerson(userName);
-
- if (thumbImage == null) {
- thumbImage = loggedInPerson.getImageThumbURL();
- }
- if (imageURL == null) {
- imageURL = loggedInPerson.getImageURL();
+ if (loggedInPerson != null) {
+ if (thumbImage == null) {
+ thumbImage = loggedInPerson.getImageThumbURL();
+ }
+ if (imageURL == null) {
+ imageURL = loggedInPerson.getImageURL();
+ }
}
-
logger.finer("************** data entered is*** " + "user_name*" + userName +
" password=" + password +
- " first_name=*" + firstName +
- " last_name" + lastName +
- " summary" + summary);
-
- Person person = new Person(userName, password, firstName, lastName, summary, email, telephone, imageURL, thumbImage, timezone, address);
+ " first_name=" + firstName +
+ " last_name=" + lastName +
+ " summary=" + summary + " thumbUrl=" + thumbImage +
+ " imageURL=" + imageURL);
+ //Person person = new Person(userName, password, firstName, lastName, summary, email, telephone, imageURL, thumbImage, timezone, address);
//ModelFacade mf= (ModelFacade) context.getAttribute(MF_KEY);
//do not really need username since you set this value, not sure why it is returned
//String userName = mf.addPerson(person, userSignOn);
//changed above line to this since username already a variable name
//userName = mf.addPerson(person, userSignOn);
+ // Update person with all field values
+ person.setUserName(userName);
+ person.setPassword(password);
+ person.setAddress(address);
+ person.setTimezone(timezone);
+ person.setTelephone(telephone);
+ person.setFirstName(firstName);
+ person.setLastName(lastName);
+ person.setSummary(summary);
+ person.setImageURL(imageURL);
+ person.setImageThumbURL(thumbImage);
person = mf.updatePerson(person);
logger.log(Level.FINER, "Person " + userName + " has been updated");
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/UsersResource.java
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/UsersResource.java?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/UsersResource.java (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/rest/UsersResource.java Mon Nov 2 18:20:05 2009
@@ -74,7 +74,7 @@
private static final String USERNAME = "user_name";
private static final String FIRSTNAME = "first_name";
private static final String LASTNAME = "last_name";
- private static final String IMAGEFILE = "imagefile";
+ private static final String IMAGEFILE = "upload_person_image";
private static final String PASSWORD = "password";
private static final String SUMMARY = "summary";
private static final String TELEPHONE = "telephone";
@@ -187,6 +187,7 @@
summary = getFieldValue(multiPart, SUMMARY, false);
telephone = getFieldValue(multiPart,TELEPHONE, false);
email = getFieldValue(multiPart, EMAIL, false);
+ timezone = getFieldValue(multiPart, TIMEZONE, false);
logger.finer("in POST - multipart first name is "+ firstName);
//address
@@ -200,21 +201,17 @@
//image processing
- if(multiPart.getField("imagefile")!=null){
- bpe = ((BodyPartEntity) multiPart.getField("imagefile").getEntity());
- logger.finer("the value of the imageFile body part is "+ multiPart.getField("imagefile").getHeaders());
- mvMap = multiPart.getField("imagefile").getHeaders();
+ if(multiPart.getField(IMAGEFILE)!=null){
+ bpe = ((BodyPartEntity) multiPart.getField(IMAGEFILE).getEntity());
+ logger.finer("the value of the imageFile body part is "+ multiPart.getField(IMAGEFILE).getHeaders());
+ mvMap = multiPart.getField(IMAGEFILE).getHeaders();
headerList = (List)mvMap.get("Content-Disposition");
contentHeader = headerList.get(0);
filename = WebappUtil.parseValueFromHeader(contentHeader, "filename");
imageStream = bpe.getInputStream();
- }
- /* image is not required
-
} else {
- throw new Exception("parameter imagefile is missing");
+ logger.finer("parameter " + IMAGEFILE + " is missing");
}
- */
/* temporary - testing multipart post
File tempFile = new File("/tmp/copyImagefile.jpg");
@@ -225,9 +222,9 @@
fos.close();
bpe.cleanup();
*/
-
+
HashMap<String,String> fileInfo = saveImageWithThumbnail(userName, imageStream, filename);
-
+
//create Person
Person person = new Person(userName, password, firstName, lastName,
summary, email, telephone, fileInfo.get(FILE_LOCATION), fileInfo.get(THUMBNAIL_LOCATION), timezone, address);
@@ -272,7 +269,9 @@
// Append the extension
fileName += ext;
fileLocation = serverLocationDir + "/" + fileName;
+ /*** Shanti - commenting as not used and incorrect call
WebappUtil.saveImageWithThumbnail(imageInputStream, fileLocation, thumbnailLocation);
+ ****/
HashMap imageInfo = new HashMap(2);
imageInfo.put(FILE_LOCATION, fileLocation);
imageInfo.put(THUMBNAIL_LOCATION, thumbnailLocation);
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/ImageScaler.java
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/ImageScaler.java?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/ImageScaler.java (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/ImageScaler.java Mon Nov 2 18:20:05 2009
@@ -163,7 +163,7 @@
* @param from the path of the original image
* @param to the path of the target thumbnail
*/
- public void resizeWithGraphics(String to) throws IOException {
+ public void resizeWithGraphics(OutputStream to) throws IOException {
BufferedImage th = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = th.createGraphics();
/* Simplify - trade off performance for quality
@@ -183,14 +183,7 @@
// Added for for distributed file system support
// Store image based on local of distributed files systems
- FileSystem fs = ServiceLocator.getInstance().getFileSystem();
- OutputStream oStream = fs.create(to);
- ImageIO.write(th, format, oStream);
-
- try {
- oStream.close();
- }
- catch (Exception e) {}
+ ImageIO.write(th, format, to);
}
/* Using Affine transform
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/WebappUtil.java
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/WebappUtil.java?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/WebappUtil.java (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/WebappUtil.java Mon Nov 2 18:20:05 2009
@@ -22,6 +22,8 @@
import org.apache.olio.webapp.model.Address;
import org.apache.olio.webapp.model.SocialEvent;
import org.apache.olio.webapp.model.SocialEventTag;
+import org.apache.olio.webapp.fileupload.FileUploadStatus;
+
import java.text.MessageFormat;
import java.util.PropertyResourceBundle;
import java.util.logging.Level;
@@ -147,24 +149,25 @@
/* Load Image, create thumbnail and save images.
This does not close the Input Stream */
- public static boolean saveImageWithThumbnail (InputStream is, String imagePath,
- String thumbnailPath) throws IOException {
+ public static boolean saveImageWithThumbnail (InputStream is,
+ OutputStream imageOut,
+ OutputStream thumbnailOut,
+ FileUploadStatus status)
+ throws IOException {
ImageScaler scaler = new ImageScaler ();
- FileOutputStream fos = new FileOutputStream (imagePath);
- WriteThroughInputStream wis = new WriteThroughInputStream (is, fos);
- // logger.finer(" the imagePath in saveImageWithThumbnail is "+ imagePath);
+ WriteThroughInputStream wis =
+ new WriteThroughInputStream(is, imageOut, status);
try {
scaler.customLoad(wis);
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
//ex.printStackTrace();
}
- if (thumbnailPath != null) {
- scaler.resizeWithGraphics(thumbnailPath);
+ if (thumbnailOut != null) {
+ scaler.resizeWithGraphics(thumbnailOut);
}
// logger.finer(" the thumbNailPath in saveImageWithThumbnail is "+ thumbnailPath);
- wis.closeOutputStream();
return true;
}
@@ -175,13 +178,24 @@
if (idx > 0) {
thumbPath = path.substring(0, idx)+"_thumb"+path.substring(idx, path.length());
}
-
+
+ FileOutputStream thumbOut = null;
try {
ImageScaler imgScaler = new ImageScaler(path);
+ thumbOut = new FileOutputStream(thumbPath);
imgScaler.keepAspectWithWidth();
- imgScaler.resizeWithGraphics(thumbPath);
+
+ imgScaler.resizeWithGraphics(thumbOut);
} catch (Exception e) {
logger.log(Level.SEVERE, "ERROR in generating thumbnail", e);
+ } finally {
+ if (thumbOut != null) {
+ try {
+ thumbOut.close();
+ } catch (IOException e) {
+ }
+ }
+
}
// remove path info and just return the thumb file name
thumbPath=thumbPath.substring(thumbPath.lastIndexOf("/") + 1);
@@ -218,7 +232,7 @@
/**
* This method uses the default message strings property file to resolve
* resultant string to show to an end user
- * @param Key to use in MessageString.properties file
+ * @param key to use in MessageString.properties file
*
* @return Formated message for external display
*/
@@ -391,8 +405,8 @@
}
return strb.toString();
}
-
- public static List getPagedList (List list, int index) {
+
+ public static List<SocialEvent> getPagedList (List<SocialEvent> list, int index) {
int size = list.size();
int numPages = getNumPages(list);
if (size <= WebappConstants.ITEMS_PER_PAGE) {
@@ -408,9 +422,10 @@
if (endIndex > size)
endIndex = size;
- List slist = list.subList(startIndex, endIndex);
+ List<SocialEvent> slist = list.subList(startIndex, endIndex);
return slist;
}
+
public static int getNumPages (long size) {
if (size % WebappConstants.ITEMS_PER_PAGE != 0)
return (int) size/WebappConstants.ITEMS_PER_PAGE + 1;
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/WriteThroughInputStream.java
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/WriteThroughInputStream.java?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/WriteThroughInputStream.java (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/WriteThroughInputStream.java Mon Nov 2 18:20:05 2009
@@ -18,6 +18,8 @@
package org.apache.olio.webapp.util;
+import org.apache.olio.webapp.fileupload.FileUploadStatus;
+
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -32,13 +34,20 @@
private OutputStream os;
private InputStream is;
-
+ private FileUploadStatus status;
+
public WriteThroughInputStream (InputStream is, OutputStream os) {
this.is = is;
this.os = os;
}
-
- @Override
+
+ public WriteThroughInputStream (InputStream is, OutputStream os,
+ FileUploadStatus status) {
+ this.is = is;
+ this.os = os;
+ this.status = status;
+ }
+
public int read() throws IOException {
byte[] b = new byte[1];
return read (b);
@@ -49,6 +58,8 @@
int rCount = is.read(buf, offset, length);
if (os != null && rCount != -1)
os.write(buf, offset, rCount);
+ if (status != null)
+ status.incrementCurrentSizeWritten(rCount);
return rCount;
}
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/fs/local/LocalFileSystem.java
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/fs/local/LocalFileSystem.java?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/fs/local/LocalFileSystem.java (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/src/java/org/apache/olio/webapp/util/fs/local/LocalFileSystem.java Mon Nov 2 18:20:05 2009
@@ -19,12 +19,15 @@
package org.apache.olio.webapp.util.fs.local;
import org.apache.olio.webapp.util.fs.FileSystem;
+//import org.apache.olio.webapp.filestore.LocalFS;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.util.logging.Logger;
/**
*
@@ -33,46 +36,183 @@
public class LocalFileSystem implements FileSystem {
public static String FS_KEY = "localFS";
+ private static Logger logger = Logger.getLogger(LocalFileSystem.class.getName());
+ private String baseLocation;
+
+ // Indices into the attributes array.
+ private static final int ID = 0;
+ private static final int TYPE = 1;
+
/** Creates a new instance of LocalFileSystem */
public LocalFileSystem() {
+ //baseLocation = System.getProperty("olio.localfs.basedir", "/filestore");
+ baseLocation = System.getProperty("webapp.image.directory", "/filestore");
+ logger.finest("baseLocation = " + baseLocation);
}
- public OutputStream create(String path) throws IOException {
- return create (path, 0, true);
+ private String getType(char t) {
+ String type = null;
+ switch (t) {
+ case 'P' :
+ case 'p' : type = "person"; break;
+ case 'E' :
+ case 'e' : type = "event"; break;
+ }
+ return type;
}
- public OutputStream create(String path, int replication) throws IOException {
- return create (path, replication, true);
+ private String[] mapAttributes(String fileName) {
+ // Do pattern matching and splitting.
+ char prefix = fileName.charAt(0);
+ String[] attrs = new String[2];
+ attrs[TYPE] = getType(prefix);
+ int dotIdx = fileName.lastIndexOf('.');
+ char postfix = fileName.charAt(dotIdx - 1);
+ if (Character.isDigit(postfix)) {
+ attrs[ID] = fileName.substring(1, dotIdx);
+ attrs[TYPE] += 's';
+ } else if (postfix == 't' || postfix == 'T') {
+ attrs[ID] = fileName.substring(1, dotIdx - 1);
+ attrs[TYPE] += "Thumbs";
+ } else if (postfix == 'l' || postfix == 'L') {
+ attrs[ID] = fileName.substring(1, dotIdx - 2);
+ attrs[TYPE] += "Lits";
+ } else {
+ logger.warning("Invalid file name pattern: " + fileName);
+ attrs[TYPE] = null;
+ }
+ return attrs;
}
- public OutputStream create(String path, int replication, boolean overwrite) throws IOException {
- // The replication factor is ignored for LocalFileSystem
- if (!overwrite) {
- File file = new File(path);
- if (file.exists())
- throw new IOException ("File exists - " + path);
+ private String getFullPath(String fileName, String[] attrs) {
+ if (attrs == null) {
+ attrs = mapAttributes(fileName);
}
-
- return new FileOutputStream (path);
+
+ if (attrs[TYPE] == null) {
+ logger.warning("Cannot process file : " + fileName);
+ return(null);
+ }
+ //build path
+ long id = Long.parseLong(attrs[ID]);
+ String dirPrimaryPath = String.format("%03d", id % 1000l);
+ String dirSecondaryPath = String.format("%03d", id / 1000000l % 1000l);
+
+ StringBuilder path = new StringBuilder();
+ path.append(baseLocation).append('/').append(attrs[TYPE]);
+ path.append('/').append(dirPrimaryPath).append('/');
+ path.append(dirSecondaryPath).append('/').append(fileName);
+ logger.finest("getFullPath returning " + path.toString());
+ return path.toString();
+ }
+
+ /**
+ * Creates a file.
+ *
+ * @param name The file name
+ * @return An output stream to write the content of the file
+ * @throws java.io.IOException Error creating the file
+ */
+ public OutputStream create(String name) throws IOException {
+ return create (name, 0, true);
+ }
+
+ /**
+ * Creates a file.
+ *
+ * @param name The file name
+ * @param replication The number of copies of the file to keep around
+ * @return An output stream to write the content of the file
+ * @throws java.io.IOException Error creating the file
+ */ public OutputStream create(String name, int replication) throws IOException {
+ return create (name, replication, true);
+ }
+
+ /**
+ * Creates a file.
+ *
+ * @param name The file name
+ * @param replication The number of copies of the file to keep around
+ * @param overwrite Overwrite the file if already exists?
+ * @return An output stream to write the content of the file
+ * @throws java.io.IOException Error creating the file
+ */
+ public OutputStream create(String name, int replication, boolean overwrite) throws IOException {
+ File fileToCreate = new File(name);
+ String fileName = fileToCreate.getName();
+ String[] attrs = mapAttributes(fileName);
+ String destPath = getFullPath(name, attrs);
+
+ if (destPath != null) {
+ File dest = new File(destPath);
+ if (overwrite || !dest.exists()) {
+ File destDir = dest.getParentFile();
+ if (!destDir.isDirectory())
+ if (!destDir.mkdirs()) {
+ logger.warning("Cannot create directory " +
+ destDir.toString());
+ return null;
+ }
+
+ FileOutputStream out = new FileOutputStream(dest);
+ return out;
+ }
+ }
+ return null;
}
- public boolean exists(String path) {
- File file = new File(path);
- return file.exists();
+ /**
+ * Checks whether a file with the name already exists.
+ *
+ * @param name The name of the file to check
+ * @return Whether the file in question does indeed exist
+ */
+ public boolean exists(String name) {
+ String fullPath = getFullPath(name, null);
+ if (fullPath != null) {
+ File f = new File(fullPath);
+ return f.isFile();
+ }
+ return false;
}
- public InputStream open(String path) throws IOException {
- /* Will not check for the existence of the file. */
-
- return new FileInputStream (path);
+ /**
+ * Opens the file for reading. Note, we cannot change an existing file
+ * with this file architecture. To change, you need to create a new file.
+ *
+ * @param name The file name
+ * @return An input stream allowing reading the content of the file
+ * @throws java.io.IOException Error opening the file
+ */
+ public InputStream open(String name) throws IOException {
+ logger.finest("Opening file " + name);
+ String fullPath = getFullPath(name, null);
+ if (fullPath != null) {
+ File f = new File(fullPath);
+ if (f.isFile())
+ return new FileInputStream(f);
+ }
+ return null;
}
- public void delete(String path) throws IOException {
- File file = new File(path);
- if (file.exists())
- file.delete();
+ /**
+ * Deletes a file.
+ *
+ * @param name The name of the file to delete
+ * @throws java.io.IOException Error deleting the file
+ */
+ public void delete(String name) throws IOException {
+ String fullPath = getFullPath(name, null);
+ if (fullPath != null) {
+ File f = new File(fullPath);
+ f.delete();
+ }
}
+ /**
+ * Checks whether this file system is local.
+ * @return Always true for the LocalFileSystem
+ */
public boolean isLocal() {
return true;
}
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/web/AjaxRequest.js
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/web/AjaxRequest.js?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/web/AjaxRequest.js (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/web/AjaxRequest.js Mon Nov 2 18:20:05 2009
@@ -1,19 +1,23 @@
+/*
+ * 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.
+ */
// ===================================================================
// Author: Matt Kruse <ma...@ajaxtoolbox.com>
// WWW: http://www.AjaxToolbox.com/
-// NOTICE: You may use this code for any purpose, commercial or
-// private, without any further permission from the author. You may
-// remove this notice from your final code if you wish, however it is
-// appreciated by the author if at least my web site address is kept. //
-// You may *NOT* re-distribute this code in any way except through its
-// use. That means, you can include it in your product, or your web
-// site, or any other form where the code is actually being used. You
-// may not put the plain javascript up on your site for download or
-// include it in your javascript libraries for download.
-// If you wish to share this code with others, please just point them
-// to the URL instead.
-// Please DO NOT link directly to my .js files from your site. Copy
-// the files to your server and use them there. Thank you.
// ===================================================================
/**
* The AjaxRequest class is a wrapper for the XMLHttpRequest objects which
Modified: incubator/olio/webapp/java/trunk/ws/apps/webapp/web/WEB-INF/web.xml
URL: http://svn.apache.org/viewvc/incubator/olio/webapp/java/trunk/ws/apps/webapp/web/WEB-INF/web.xml?rev=831998&r1=831997&r2=831998&view=diff
==============================================================================
--- incubator/olio/webapp/java/trunk/ws/apps/webapp/web/WEB-INF/web.xml (original)
+++ incubator/olio/webapp/java/trunk/ws/apps/webapp/web/WEB-INF/web.xml Mon Nov 2 18:20:05 2009
@@ -156,7 +156,7 @@
<description>Geocoder URL</description>
<env-entry-name>geocoderURL</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
- <env-entry-value>http://localhost:8080/geocoder/geocode</env-entry-value>
+ <env-entry-value>http://pae4150-5:8080/geocoder/geocode</env-entry-value>
</env-entry>
<jsp-config>