Added the upload servlet

This commit is contained in:
francesco 2020-10-05 12:38:16 +02:00
parent 8486bf0089
commit dde2d039d9
15 changed files with 1885 additions and 145 deletions

View File

@ -4,9 +4,9 @@ import com.google.gwt.core.client.GWT;
public class ConstantsMPFormBuilder {
public static final String WORKSPACE_UPLOADER_SERVLET_STREAM__MODIFIED = GWT.getModuleBaseURL() + "workspaceUploadServletStream";
public static final String WORKSPACE_UPLOADER_SERVLET_STREAM__MODIFIED = GWT.getModuleBaseURL() + "mpformbuilderUploadServlet";
public static final String CURR_GROUP_ID = "currGroupId";
//public static final String CURR_USER_ID = "currUserId";
public static final String IS_OVERWRITE = "isOverwrite";
public static final String UPLOAD_TYPE = "uploadType";

View File

@ -2,7 +2,6 @@ package org.gcube.portlets.widgets.mpformbuilder.client;
import org.gcube.portlets.widgets.mpformbuilder.client.form.generic.CreateMetadataForm;
import com.github.gwtbootstrap.client.ui.FileUpload;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.HandlerManager;

View File

@ -16,7 +16,6 @@ import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.HTML;

View File

@ -0,0 +1,753 @@
/**
*
*/
package org.gcube.portlets.widgets.mpformbuilder.server;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.gcube.common.portal.PortalContext;
import org.gcube.portlets.widgets.mpformbuilder.client.ConstantsMPFormBuilder;
import org.gcube.portlets.widgets.mpformbuilder.server.util.WsUtil;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.AbstractUploadProgressListener;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.HandlerResultMessage;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.MemoryUploadListener;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.UploadCanceledException;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.UploadProgressInputStream;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.UploadProgressListener;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.WorkspaceUploadFile;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.WorkspaceUploaderItem;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.WorkspaceUploaderItem.UPLOAD_STATUS;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// TODO: Auto-generated Javadoc
/**
* The Class MetadataProfileBuilderUploadServlet.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it at ISTI-CNR
*
* Oct 5, 2020
*/
public class MetadataProfileFormBuilderUploadServlet extends HttpServlet implements Servlet{
/** The Constant UNKNOWN_UNKNOWN. */
public static final String UNKNOWN_UNKNOWN = "unknown/unknown";
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1778008252774571216L;
/** The Constant UTF_8. */
protected static final String UTF_8 = "UTF-8";
/** The Constant VRE_ID_ATTR_NAME. */
public static final String VRE_ID_ATTR_NAME = "gcube-vreid";
/** The Constant CURR_GROUP_ID. */
public static final String CURR_GROUP_ID = ConstantsMPFormBuilder.CURR_GROUP_ID;
//public static final String CURR_USER_ID = ConstantsWorkspaceUploader.CURR_USER_ID;
/** The Constant UPLOAD_FORM_ELEMENT. */
public static final String UPLOAD_FORM_ELEMENT = ConstantsMPFormBuilder.UPLOAD_FORM_ELEMENT;
/** The Constant CLIENT_UPLOAD_KEYS. */
public static final String CLIENT_UPLOAD_KEYS = ConstantsMPFormBuilder.CLIENT_UPLOAD_KEYS;
/** The Constant JSON_CLIENT_KEYS. */
public static final String JSON_CLIENT_KEYS = ConstantsMPFormBuilder.JSON_CLIENT_KEYS;
/** The Constant CANCEL_UPLOAD. */
public static final String CANCEL_UPLOAD = ConstantsMPFormBuilder.CANCEL_UPLOAD;
/** The Constant FILE. */
public static final String FILE = "File";
/** The logger. */
public static Logger logger = LoggerFactory.getLogger(MetadataProfileFormBuilderUploadServlet.class);
/** The app engine. */
private static boolean appEngine = false;
/**
* Inits the.
*
* @throws ServletException the servlet exception
*/
/*
* (non-Javadoc)
*
* @see javax.servlet.GenericServlet#init()
*/
@Override
public void init() throws ServletException {
super.init();
String appe = getInitParameter("appEngine");
if (appe != null) {
appEngine = "true".equalsIgnoreCase(appe);
} else {
appEngine = isAppEngine();
}
logger.debug("init: appEngine is "+appEngine);
}
/**
* {@inheritDoc}
*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.debug("GET method in "+MetadataProfileFormBuilderUploadServlet.class.getName()+" is running");
String clientUploadKey = request.getParameter(CLIENT_UPLOAD_KEYS);
if (clientUploadKey == null){
sendError(response, "Internal error: UPLOAD KEY NOT FOUND");
return;
}
logger.debug("GET method CLIENT_UPLOAD_KEY "+clientUploadKey);
boolean cancelUpload = Boolean.parseBoolean(request.getParameter(CANCEL_UPLOAD));
logger.debug("GET method CANCEL_UPLOAD "+cancelUpload);
if (cancelUpload) {
boolean cancelled = cancelUpload(request.getSession(), clientUploadKey);
if(cancelled){
sendMessage(response, "Upload aborted "+clientUploadKey);
// try {
//// removeCurrentListener(request.getSession(), clientUploadKey);
// WsUtil.eraseWorkspaceUploaderInSession(request.getSession(), clientUploadKey);
// }catch (Exception e) {
// logger.warn("An error occurred during removing cancelled upload from session ");
// }
}
else
sendWarnMessage(response, "Upload aborted for id: "+clientUploadKey +" has skipped, already aborted or completed?");
}else
logger.debug(CANCEL_UPLOAD + " param not found");
return;
}
/**
* {@inheritDoc}
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("POST on UploadServlet");
boolean requestIsNull = request==null;
logger.trace("[1] HttpServletRequest is: null? "+requestIsNull+", URI: "+request.getRequestURI() +", ServerName: "+request.getServerName());
if (!ServletFileUpload.isMultipartContent(request)) {
logger.error("ERROR: multipart request not found");
sendError(response, "ERROR: multipart request not found");
return;
}
try {
logger.info("UPLOAD-SERVLET starting");
HttpSession session = request.getSession();
logger.info("UPLOAD-SERVLET session: "+session);
logger.debug("UPLOAD-SERVLET (" + session.getId() + ") new upload request received.");
if(WsUtil.isSessionExpired(request)){
logger.error("SESSION_EXPIRED: session is expired");
sendSessionExpired(response, "SESSION_EXPIRED: session is expired");
return;
}
String destinationId = null;
String uploadType = null;
// String clientUploadKey = null;
FileItemStream uploadItem = null;
ArrayList<String> listClientUploadKeys = null;
GCubeUser user = PortalContext.getConfiguration().getCurrentUser(request);
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
/**
* An iterator to instances of <code>FileItemStream</code>
* parsed from the request, in the order that they were
*transmitted.
*/
FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request);
int uploadItemsCnt = 0;
String scopeGroupId = "";
//GET FILE STREAM
while (fileItemIterator.hasNext()) {
FileItemStream item = fileItemIterator.next();
// if (item.isFormField() && UPLOAD_TYPE.equals(item.getFieldName())){
// uploadType = Streams.asString(item.openStream());
// logger.debug("UPLOAD_TYPE OK " +uploadType);
// }
// if (item.isFormField() && IS_OVERWRITE.equals(item.getFieldName())){
// try{
// isOverwrite = Boolean.parseBoolean(Streams.asString(item.openStream()));
// logger.debug("IS_OVERWRITE OK "+ isOverwrite);
// }catch(Exception e){
// //Silent exception;
// }
// }
if(item.isFormField() && CLIENT_UPLOAD_KEYS.equals(item.getFieldName())){
String jsonClientUploadKey = Streams.asString(item.openStream());
logger.debug("CLIENT_UPLOAD_KEY OK "+jsonClientUploadKey);
LinkedHashMap<String, String> mapKeys = parseJSONClientUploadKeys(jsonClientUploadKey);
listClientUploadKeys = new ArrayList<String>(mapKeys.keySet());
removeListenersIfDone(session, listClientUploadKeys);
for (String clientUploadKey : listClientUploadKeys) {
String fileName = mapKeys.get(clientUploadKey);
WorkspaceUploaderItem workspaceUploader = createNewWorkspaceUploader(clientUploadKey,fileName);
logger.debug("created "+workspaceUploader);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.WAIT, "Uploading "+fileName+" at 0%", request.getSession());
}
}
if (item.isFormField() && CURR_GROUP_ID.equals(item.getFieldName())){
scopeGroupId = Streams.asString(item.openStream());
logger.debug("currentGroupId passed as parameter = " + scopeGroupId);
logger.debug("currentGroupId into PortalContext scope= " + PortalContext.getConfiguration().getCurrentScope(scopeGroupId));
}
// if (item.isFormField() && CURR_USER_ID.equals(item.getFieldName())){
// currUserId = Streams.asString(item.openStream());
// logger.debug("currUserId passed as parameter = " + currUserId);
// logger.debug("currUserinto PortalContext = " + PortalContext.getConfiguration().getCurrentUser(request));
// }
//MUST BE THE LAST PARAMETER TRASMITTED
if (UPLOAD_FORM_ELEMENT.equals(item.getFieldName())){
uploadItem = item;
logger.debug("UPLOAD_FORM_ELEMENT OK "+uploadItem.getName() + " scopeGroupId="+scopeGroupId);
// break;
uploadData(user, scopeGroupId, request, response, uploadItem, destinationId, uploadType, listClientUploadKeys.get(uploadItemsCnt));
uploadItemsCnt++;
}
}
} catch (FileUploadException e) {
logger.error("Error processing request in upload servlet", e);
sendError(response, "Internal error: Error during request processing");
return;
} catch (Exception e) {
logger.error("Error processing request in upload servlet", e);
sendError(response, "Internal error: Error during request processing");
return;
}
}
/**
* Removes the listener if done.
*
* @param session the session
* @param keys the keys
*/
private void removeListenersIfDone(HttpSession session, List<String> keys){
for (String key : keys) {
AbstractUploadProgressListener listener = getCurrentListener(session, key);
if (listener != null) {
logger.debug("Listener found");
if (listener.isCanceled() || listener.getPercentage() >= 100){
logger.debug("Listener isCanceled or 100%, removing");
removeCurrentListener(session, key);
}
}else
logger.debug("Session id: "+session.getId() +" - "+key+" - Listener not found");
}
}
/**
* Parses the json client upload keys.
*
* @param jsonClientUploadKeys the json client upload keys
* @return the linked hash map
* @throws FileUploadException the file upload exception
*/
@SuppressWarnings("rawtypes")
private static LinkedHashMap<String, String> parseJSONClientUploadKeys(final String jsonClientUploadKeys) throws FileUploadException{
JSONTokener tokener = new JSONTokener(jsonClientUploadKeys);
JSONObject root;
LinkedHashMap<String, String> keyFiles = null;
try {
root = new JSONObject(tokener);
JSONArray jsonArray = root.getJSONArray(JSON_CLIENT_KEYS);
keyFiles = new LinkedHashMap<String, String>(jsonArray.length());
logger.debug("jsonArray :"+jsonArray.toString());
for (int i=0; i<jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
logger.debug("object :"+object);
String key = (String) object.keys().next();
String value = object.getString(key);
logger.debug("key :"+key+", value: "+value);
keyFiles.put(key, value);
}
} catch (JSONException e) {
logger.error("An error occurred during parsing file names: "+keyFiles, e);
throw new FileUploadException("An error occurred during parsing file names");
}
logger.debug("keyFiles: "+keyFiles);
return keyFiles;
}
/**
* Upload data.
*
* @param user the user
* @param scopeGroupId the scope group id
* @param request the request
* @param response the response
* @param uploadItem the upload item
* @param destinationId the destination id
* @param uploadType the upload type
* @param clientUploadKey the client upload key
* @throws ServletException the servlet exception
* @throws IOException Signals that an I/O exception has occurred.
*/
private void uploadData(GCubeUser user, String scopeGroupId, HttpServletRequest request, final HttpServletResponse response, final FileItemStream uploadItem, String destinationId,String uploadType,String clientUploadKey) throws ServletException, IOException{
String fileName = uploadItem.getName();
logger.info("Upload servlet parameters: [fileName: "+fileName+ ", destinationId: "+destinationId +", uploadType: "+uploadType+", clientUploadKey: "+clientUploadKey+"]");
if (uploadType == null || uploadType.isEmpty()) {
logger.error("Error processing request in upload servlet for: "+fileName+". No upload type found");
sendError(response, "Internal error: No upload type found");
return;
}
if(clientUploadKey==null || clientUploadKey.isEmpty()){
logger.error("Error processing request in upload servlet for: "+fileName+". No client upload key found");
sendError(response, "Internal error: No client upload key found");
return;
}
//CLIENT UPLOAD IS THE KEY
// WorkspaceUploaderItem workspaceUploader = createNewWorkspaceUploader(clientUploadKey,destinationId,fileName);
// saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.WAIT, "Uploading "+fileName+" at 0%", request.getSession());
//RETRIVE WORKSPACE UPLOADER FROM SESSION
WorkspaceUploaderItem workspaceUploader = null;
try {
workspaceUploader = WsUtil.getWorkspaceUploaderInSession(request, clientUploadKey);
} catch (Exception e) {
logger.error("Error during workspace uploader retrieving", e);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "An error occurred during upload: "+fileName+". Error processing request in upload servlet", request.getSession());
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error processing request in upload servlet");
return;
}
try {
//Removing path from fileName
String itemName = fileName;
//Getting extension
String extension = FilenameUtils.getExtension(itemName);
logger.debug("extension: "+extension);
//Getting base name
String baseName = FilenameUtils.getBaseName(itemName); //Using base name in order to avoid Task #12470
//Task #17152
extension = extension.isEmpty()?"":"."+extension;
itemName = baseName+extension;
logger.debug("purged item name is: "+itemName);
//SIZE
Long size = getContentLength(request);
logger.debug("size: " + size + " bytes");
//Instancing the progress listener
final AbstractUploadProgressListener uploadProgressListener = createNewListener(request.getSession(), clientUploadKey);
final UploadProgressInputStream inputStream = new UploadProgressInputStream(uploadItem.openStream(), size);
inputStream.addListener(uploadProgressListener);
workspaceUploader.setUploadProgress(uploadProgressListener.getUploadProgress());
saveWorkspaceUploaderInSession(workspaceUploader, request.getSession());
String contentType = uploadItem.getContentType();
logger.debug("Stream content type: "+contentType);
//UPLOAD FILE. IT IS DEFAULT CASE
logger.debug("Uploding file in the temp system TEMP");
workspaceUploader = createStreamToTempFile(workspaceUploader, inputStream, user.getUsername(), clientUploadKey, fileName, extension);
saveWorkspaceUploaderInSession(workspaceUploader, request.getSession());
if(workspaceUploader==null)
throw new Exception("Error when creating uploader, it is null!");
} catch (IOException e){
logger.error("Error creating elements, is it cancel?", e);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "Uploading error", request.getSession());
sendError(response, "Internal error: An item with that name already exists");
return;
// sendError(response, "Internal error: An item with that name already exists");
// return;
}catch (Exception e) {
logger.error("Error creating elements", e);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "Uploading error. "+e.getMessage(), request.getSession());
// sendError(response, "Internal error: An error occurred on uploading the file, try again later");
// return;
}finally{
removeCurrentListener(request.getSession(), clientUploadKey);
}
}
/**
* Save workspace uploader status.
*
* @param workspaceUploader the workspace uploader
* @param status the status
* @param description the description
* @param session the session
* @return the workspace uploader item
*/
private synchronized WorkspaceUploaderItem saveWorkspaceUploaderStatus(WorkspaceUploaderItem workspaceUploader, UPLOAD_STATUS status, String description, HttpSession session){
workspaceUploader.setUploadStatus(status);
workspaceUploader.setStatusDescription(description);
try {
saveWorkspaceUploaderInSession(workspaceUploader, session);
} catch (Exception e) {
logger.error(e.getMessage());
}
return workspaceUploader;
}
/**
* Creates the new workspace uploader.
*
* @param clientUploadKey the client upload key
* @param fileName the file name
* @return the workspace uploader item
*/
private WorkspaceUploaderItem createNewWorkspaceUploader(String clientUploadKey, String fileName){
//CLIENT UPLOAD IS THE KEY
WorkspaceUploaderItem workspaceUploader = new WorkspaceUploaderItem(clientUploadKey);
workspaceUploader.setClientUploadKey(clientUploadKey);
//Create File
WorkspaceUploadFile wsUploadFile = new WorkspaceUploadFile(fileName, null, null);
workspaceUploader.setFile(wsUploadFile);
return workspaceUploader;
}
/**
* Gets the random.
*
* @return the random
*/
private static int getRandom(){
Random randomGenerator = new Random();
return randomGenerator.nextInt(Integer.MAX_VALUE);
}
/**
* Save workspace uploader in session.
*
* @param workspaceUploader the workspace uploader
* @param httpSession the http session
* @return the workspace uploader item
* @throws Exception the exception
*/
public static void saveWorkspaceUploaderInSession(WorkspaceUploaderItem workspaceUploader, HttpSession httpSession) throws Exception {
if(workspaceUploader!=null){
try {
WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader);
} catch (Exception e) {
logger.error("Error during WorkspaceUploaderItem save in session workspace uploader: "+workspaceUploader,e);
throw new Exception("An error occurred in the upload. Try again");
}
}else
throw new Exception("An error occurred in the upload. Workspace Uploader not found. Abort and try again");
}
/**
* Creates the stream to temp file.
*
* @param workspaceUploader the workspace uploader
* @param in the in
* @param username the username
* @param clientUploadKey the client upload key
* @param fileName the file name
* @param fileExtension the file extension
* @return the workspace uploader item
* @throws IOException Signals that an I/O exception has occurred.
*/
public WorkspaceUploaderItem createStreamToTempFile(WorkspaceUploaderItem workspaceUploader, InputStream in, String username, String clientUploadKey, String fileName, String fileExtension) throws IOException{
if(fileExtension==null)
fileExtension = "";
try {
String uniqueFileName = String.format("%s_%s_%s",username,fileName,clientUploadKey);
File tempFile = File.createTempFile(uniqueFileName, fileExtension);
//tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out);
workspaceUploader.getFile().setTempSystemPath(tempFile.getAbsolutePath());
workspaceUploader.setStatusDescription("File uploaded correclty");
workspaceUploader.setUploadStatus(UPLOAD_STATUS.COMPLETED);
}catch (Exception e) {
workspaceUploader.setStatusDescription("Error on uploading: "+fileName+". "+e.getMessage());
workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED);
}
return workspaceUploader;
}
//TEST TIME
/**
* Prints the start time.
*
* @return the long
*/
public static Long printStartTime(){
Long startTime = System.currentTimeMillis();
logger.debug("Start time: "+startTime);
return startTime;
}
//TEST TIME
/**
* Prints the elapsed time.
*
* @param startTime the start time
*/
public static void printElapsedTime(long startTime){
Long endTime = System.currentTimeMillis() - startTime;
String time = String.format("%d msc %d sec", endTime, TimeUnit.MILLISECONDS.toSeconds(endTime));
logger.debug("Elapsed Time: "+time);
}
/**
* Send error.
*
* @param response the response
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
protected void sendError(HttpServletResponse response, String message) throws IOException{
try {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
HandlerResultMessage resultMessage = HandlerResultMessage.errorResult(message);
response.getWriter().write(resultMessage.toString());
//5.6 Closure of Response Object:
//When a response is closed, the container must immediately flush all remaining content in the response buffer to the client
// response.flushBuffer();
} catch (IOException e){
logger.warn("IOException class name: "+e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage());
else
throw e; //Sending Exceptions
}
}
/**
* Send session expired.
*
* @param response the response
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
protected void sendSessionExpired(HttpServletResponse response, String message) throws IOException{
try {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
HandlerResultMessage resultMessage = HandlerResultMessage.sessionExpiredResult(message);
response.getWriter().write(resultMessage.toString());
//5.6 Closure of Response Object:
//When a response is closed, the container must immediately flush all remaining content in the response buffer to the client
// response.flushBuffer();
} catch (IOException e){
logger.warn("IOException class name: "+e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage());
else
throw e; //Sending Exceptions
}
}
/**
* Send message.
*
* @param response the response
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
protected void sendMessage(HttpServletResponse response, String message) throws IOException{
try {
response.setStatus(HttpServletResponse.SC_ACCEPTED);
message = message.replaceAll(":", "");
HandlerResultMessage resultMessage = HandlerResultMessage.okResult(message);
response.getWriter().write(resultMessage.toString());
//5.6 Closure of Response Object:
//When a response is closed, the container must immediately flush all remaining content in the response buffer to the client
// response.flushBuffer();
} catch (IOException e){
logger.warn("IOException class name: "+e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage());
else
throw e; //Sending Exceptions
}
}
/**
* Send warn message.
*
* @param response the response
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
protected void sendWarnMessage(HttpServletResponse response, String message) throws IOException{
try {
response.setStatus(HttpServletResponse.SC_ACCEPTED);
HandlerResultMessage resultMessage = HandlerResultMessage.warnResult(message);
response.getWriter().write(resultMessage.toString());
//5.6 Closure of Response Object:
//When a response is closed, the container must immediately flush all remaining content in the response buffer to the client
// response.flushBuffer();
} catch (IOException e){
logger.warn("IOException class name: "+e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage());
else
throw e; //Sending Exceptions
}
}
/**
* Mark the current upload process to be canceled.
*
* @param session the session
* @param clientUploadKey the client upload key
* @return true, if successful
*/
public boolean cancelUpload(HttpSession session, String clientUploadKey) {
logger.debug("UPLOAD-SERVLET (" + session.getId()+ ") cancelling Upload: "+clientUploadKey);
AbstractUploadProgressListener listener = getCurrentListener(session, clientUploadKey);
if (listener != null && !listener.isCanceled()) {
logger.info("CancelUpload listener is "+listener.toString());
listener.setException(new UploadCanceledException());
return true;
}else{
logger.info("Skipping cancel upload: listener is null or is cancel");
return false;
}
}
/**
* Get the listener active in this session.
*
* @param session the session
* @param clientUploadKey the client upload key
* @return the listener active
*/
protected AbstractUploadProgressListener getCurrentListener(HttpSession session, String clientUploadKey) {
if (isAppEngine()) {
return MemoryUploadListener.current(session.getId(), clientUploadKey);
} else {
return UploadProgressListener.current(session, clientUploadKey);
}
}
/**
* Just a method to detect whether the web container is running with
* appengine restrictions.
*
* @return true if the case of the application is running in appengine
*/
public boolean isAppEngine() {
return appEngine;
}
/**
* Create a new listener for this session.
*
* @param session the session
* @param clientUploadKey the client upload key
* @return the appropriate listener
*/
protected AbstractUploadProgressListener createNewListener(HttpSession session, String clientUploadKey) {
if (isAppEngine()) {
return new MemoryUploadListener(session, clientUploadKey, 0, 100);
} else {
return new UploadProgressListener(session, clientUploadKey, 0, 100);
}
}
/**
* Gets the content length.
*
* @param request the request
* @return the content length
*/
private long getContentLength(HttpServletRequest request) {
long size = -1;
try {
size = Long.parseLong(request
.getHeader(FileUploadBase.CONTENT_LENGTH));
} catch (NumberFormatException e) {
}
return size;
}
/**
* Remove the listener active in this session.
*
* @param session the session
* @param clientUploadKey the client upload key
*/
protected void removeCurrentListener(HttpSession session, String clientUploadKey) {
logger.debug("RemoveCurrentListener: "+clientUploadKey);
AbstractUploadProgressListener listener = getCurrentListener(session, clientUploadKey);
if (listener != null) {
logger.debug("Removing listener: "+listener.getClientUploadKey());
listener.remove();
}else
logger.warn("Listener "+clientUploadKey+ "is null");
}
}

View File

@ -0,0 +1,102 @@
package org.gcube.portlets.widgets.mpformbuilder.server.util;
import java.util.List;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.exception.UserRetrievalFault;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class UserUtil.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it at ISTI-CNR
*
* Oct 5, 2020
*/
public class UserUtil {
/** The um. */
static UserManager um = new LiferayUserManager();
/** The logger. */
protected static Logger logger = LoggerFactory.getLogger(UserUtil.class);
/**
* Gets the user full name.
*
* @param portalLogin the portal login
* @return the user full name
*/
public static String getUserFullName(String portalLogin){
if(portalLogin==null)
return "";
if (WsUtil.isWithinPortal()) { //INTO PORTAL
GCubeUser curr = null;
try {
try {
curr = um.getUserByUsername(portalLogin);
} catch (UserManagementSystemException e) {
logger.error("An error occurred in getUserByUsername "+e,e);
} catch (UserRetrievalFault e) {
logger.error("An error occurred in getUserByUsername "+e,e);
}
}catch (Exception e) {
logger.error("An error occurred in getUserByUsername "+e,e);
logger.warn("Return portal login "+portalLogin);
return portalLogin;
}
if (curr != null){
// logger.trace("Return "+curr.getFullname() +" full name for: "+portalLogin);
return curr.getFullname();
}
}else{
logger.trace("DEVELOPEMENT MODE ON");
}
logger.trace("Return portal login as full name for: "+portalLogin);
return portalLogin;
}
/**
* Separate full name to comma for portal login.
*
* @param listLogin the list login
* @return the string
*/
public static String separateFullNameToCommaForPortalLogin(List<String> listLogin){
String users = "";
logger.trace("SeparateFullNameToCommaForPortalLogin converting: "+listLogin);
//N-1 MEMBERS
for (int i = 0; i < listLogin.size()-1; i++) {
// logger.trace("Converting: "+i+") "+listLogin.get(i));
users+= getUserFullName(listLogin.get(i)) + ", ";
}
//LAST MEMBER
if(listLogin.size()>=1){
// logger.trace("Converting: "+(listLogin.size()-1)+") " +listLogin.get(listLogin.size()-1));
users += getUserFullName(listLogin.get(listLogin.size()-1));
}
logger.trace("SeparateFullNameToCommaForPortalLogin returning: "+users);
return users;
}
}

View File

@ -0,0 +1,180 @@
/**
*
*/
package org.gcube.portlets.widgets.mpformbuilder.server.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.gcube.common.portal.PortalContext;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.WorkspaceUploaderItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.liferay.portal.service.UserLocalServiceUtil;
/**
* The Class WsUtil.
*
* author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it at ISTI-CNR
*
* Oct 5, 2020
*/
public class WsUtil {
/** The Constant NOTIFICATION_MANAGER_UPLOADER. */
public static final String NOTIFICATION_MANAGER_UPLOADER = "WS_UPLOADER_NOTIFICATION_MANAGER";
/** The Constant NOTIFICATION_PORTLET_CLASS_ID. */
public static final String NOTIFICATION_PORTLET_CLASS_ID = "org.gcube.portlets.user.workspace.server.GWTWorkspaceServiceImpl";
/** The logger. */
protected static Logger logger = LoggerFactory.getLogger(WsUtil.class);
/**
* Checks if is within portal.
*
* @return true if you're running into the portal, false if in development
*/
public static boolean isWithinPortal() {
try {
UserLocalServiceUtil.getService();
return true;
}
catch (Exception ex) {
logger.trace("Development Mode ON");
return false;
}
}
/**
* Checks if is session expired.
*
* @param request the request
* @return true, if is session expired
* @throws Exception the exception
*/
public static boolean isSessionExpired(HttpServletRequest request) throws Exception {
logger.debug("workspace session validating...");
return PortalContext.getConfiguration().getCurrentUser(request)==null;
}
/**
* Put workspace uploader in session.
*
* @param httpSession the http session
* @param uploader the uploader
* @throws Exception the exception
*/
public static void putWorkspaceUploaderInSession(final HttpSession httpSession, WorkspaceUploaderItem uploader) throws Exception {
logger.trace("Put workspace uploader in session: "+uploader.getIdentifier() + ", STATUS: "+uploader.getUploadStatus());
if(uploader.getIdentifier()==null || uploader.getIdentifier().isEmpty())
throw new Exception("Invalid uploader");
httpSession.setAttribute(uploader.getIdentifier(), uploader);
logger.debug("Added uploader: "+uploader.getIdentifier() +" in session");
}
/**
* Erase workspace uploader in session.
*
* @param httpSession the http session
* @param uploader the uploader
* @throws Exception the exception
*/
public static void forceEraseWorkspaceUploaderInSession(final HttpSession httpSession, WorkspaceUploaderItem uploader) throws Exception {
logger.trace("Force Erase WorkspaceUploader workspace uploader in session: "+uploader.getIdentifier());
if(uploader==null || uploader.getIdentifier()==null || uploader.getIdentifier().isEmpty())
throw new Exception("Invalid uploader");
httpSession.removeAttribute(uploader.getIdentifier());
logger.info("Erased uploader: "+uploader.getIdentifier());
}
/**
* Erase workspace uploader in session.
*
* @param httpSession the http session
* @param uploader the uploader
* @throws Exception the exception
*/
public static void eraseWorkspaceUploaderInSession(final HttpSession httpSession, WorkspaceUploaderItem uploader) throws Exception
{
logger.trace("Erase WorkspaceUploader workspace uploader in session: "+uploader.getIdentifier() + ", erasable? "+uploader.isErasable());
if(uploader==null || uploader.getIdentifier()==null || uploader.getIdentifier().isEmpty())
throw new Exception("Invalid uploader");
if(uploader.isErasable()){
httpSession.removeAttribute(uploader.getIdentifier());
logger.info("Erased uploader: "+uploader.getIdentifier());
}
}
/**
* Gets the workspace uploader in session.
*
* @param request the request
* @param uploaderIdentifier the uploader identifier
* @return the workspace uploader in session
* @throws Exception the exception
*/
public static WorkspaceUploaderItem getWorkspaceUploaderInSession(final HttpServletRequest request, String uploaderIdentifier) throws Exception {
HttpSession httpSession = request.getSession();
if(uploaderIdentifier==null || uploaderIdentifier.isEmpty())
throw new Exception("Invalid uploader");
return (WorkspaceUploaderItem) httpSession.getAttribute(uploaderIdentifier);
}
/**
* Sets the erasable workspace uploader in session.
*
* @param request the request
* @param uploaderIdentifier the uploader identifier
* @return true, if successful
* @throws Exception the exception
*/
public static boolean setErasableWorkspaceUploaderInSession(final HttpServletRequest request, String uploaderIdentifier) throws Exception {
HttpSession httpSession = request.getSession();
WorkspaceUploaderItem uploader = getWorkspaceUploaderInSession(request, uploaderIdentifier);
if(uploader!=null){
/*TODO REMOVE SESSION KEY FROM SESSION MUST BE MANAGED IN ANOTHER WAY IN ORDER TO AVOID THATH IT'S REMOVED FROM SESSION BEFORE THAT
* POLLING RETRIEVES STATUS, USE A FLAG REMOVED?*/
logger.debug("Set erasable uploader: "+uploader.getIdentifier() +" in session");
// uploader = null;
uploader.setErasable(true);
putWorkspaceUploaderInSession(httpSession, uploader);
return true;
}
logger.debug("Uploader not found, skipping erase from session");
return false;
}
/**
* Gets the user id.
*
* @param request the request
* @return the user id
*/
public static String getUserId(HttpServletRequest request) {
PortalContext pContext = PortalContext.getConfiguration();
String username = pContext.getCurrentUser(request).getUsername();
logger.debug("workspace upload UserId: "+username);
return username;
}
}

View File

@ -0,0 +1,265 @@
package org.gcube.portlets.widgets.mpformbuilder.shared.upload;
import java.io.Serializable;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.ProgressListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The listener interface for receiving uploadProgress events. The class that is
* interested in processing a uploadProgress event implements this interface,
* and the object created with that class is registered with a component using
* the component's <code>addUploadProgressListener<code> method. When
* the uploadProgress event occurs, that object's appropriate
* method is invoked.
*
* @see UploadProgressEvent
*/
public abstract class AbstractUploadProgressListener implements ProgressListener, Serializable {
/**
*
*/
private static final long serialVersionUID = -785329339005951465L;
private static final double COMPLETE_PERECENTAGE = 100d;
private int percentage = -1;
private UploadProgress uploadProgress;
private int percentageOffset = 0;
private double completePercentage = COMPLETE_PERECENTAGE;
private static Logger logger = LoggerFactory.getLogger(AbstractUploadProgressListener.class);
protected UploadCanceledException exception = null;
protected boolean exceptionTrhown = false;
protected String sessionId;
/**
* Current.
*
* @param sessionId the session id
* @return the abstract upload progress listener
*/
public static AbstractUploadProgressListener current(String sessionId) {
throw new RuntimeException("Implement the static method 'current' in your customized class");
}
protected Long bytesRead = 0L;
protected Long contentLength = 0L;
private String clientUploadKey;
// protected static HttpServletRequest request;
protected String sessionKey;
private HttpSession session;
/**
* Save itself in session or cache.
*/
public abstract void save();
/**
* Remove itself from session or cache.
*/
public abstract void remove();
/**
* Instantiates a new upload progress listener.
*
* @param session the session
* @param clientUploadKey the client upload key
* @param percentageOffset the percentage offset
* @param completePercentage the complete percentage
*/
public AbstractUploadProgressListener(HttpSession session,
String clientUploadKey, int percentageOffset,
double completePercentage) {
this.sessionId = session.getId();
this.session = session;
this.clientUploadKey = clientUploadKey;
this.sessionKey = sessionId + ":" + clientUploadKey;
this.uploadProgress = new UploadProgress();
this.percentageOffset = percentageOffset;
this.completePercentage = completePercentage;
logger.debug("Session key: " + sessionKey);
save();
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.fileupload.ProgressListener#update(long, long,
* int)
*/
@Override
public void update(final long bytesRead, final long totalBytes, final int items) {
if (exceptionTrhown) {
logger.warn("An exception thrown is already true. Is upload cancelled?, returning");
return;
}
// If other request has set an exception, it is thrown so the
// commons-fileupload's
// parser stops and the connection is closed.
if (isCanceled()) {
String eName = exception.getClass().getName().replaceAll("^.+\\.", "");
logger.info(AbstractUploadProgressListener.class.getName() + " "
+ sessionKey + " The upload has been canceled after "
+ bytesRead + " bytes received, raising an exception ("
+ eName + ") to close the socket");
exceptionTrhown = true;
throw exception;
}
this.bytesRead = bytesRead;
this.contentLength = totalBytes;
int percentage = percentageOffset+ (int) Math.floor((double) bytesRead / (double) totalBytes* completePercentage);
if (this.percentage == percentage)
return;
this.percentage = percentage;
UploadProgressChangeEvent event = new UploadProgressChangeEvent();
event.setReadPercentage(percentage);
event.setReadTime(System.currentTimeMillis());
event.setReadBytes(bytesRead);
event.setTotalBytes(totalBytes);
// logger.trace("Updating percentage.. "+percentage);
synchronized (this.uploadProgress) {
// logger.trace("Adding event: "+event);
this.uploadProgress.add(event);
// this.uploadProgress.notifyAll();
}
}
/**
* Gets the bytes read.
*
* @return the bytesRead
*/
public Long getBytesRead() {
return bytesRead;
}
/**
* Gets the content length.
*
* @return the contentLength
*/
public Long getContentLength() {
return contentLength;
}
/**
* Gets the upload progress.
*
* @return the uploadProgress
*/
public UploadProgress getUploadProgress() {
return uploadProgress;
}
/**
* Get the exception.
*
* @return the exception
*/
public UploadCanceledException getException() {
return exception;
}
/**
* Return true if the process has been canceled due to an error or by the
* user.
*
* @return boolean
*/
public boolean isCanceled() {
return exception != null;
}
/**
* Set the exception which cancels the upload.
*
* @param e the new exception
*/
public void setException(UploadCanceledException e) {
logger.info("Set exception to UploadCanceledException to cancel upload");
exception = e;
save();
}
/**
* Gets the percentage.
*
* @return the percentage
*/
public int getPercentage() {
return percentage;
}
/**
* Gets the client upload key.
*
* @return the clientUploadKey
*/
public String getClientUploadKey() {
return clientUploadKey;
}
/**
* Gets the session.
*
* @return the session
*/
public HttpSession getSession() {
return session;
}
/**
* Gets the session key.
*
* @param httpSessionId
* the http session id
* @param clientUploadKey
* the client upload key
* @return the session key
*/
public static String getSessionKey(String httpSessionId, String clientUploadKey) {
return httpSessionId + ":" + clientUploadKey;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AbstractUploadProgressListener [percentage=");
builder.append(percentage);
builder.append(", percentageOffset=");
builder.append(percentageOffset);
builder.append(", completePercentage=");
builder.append(completePercentage);
builder.append(", exception=");
builder.append(exception);
builder.append(", exceptionTrhown=");
builder.append(exceptionTrhown);
builder.append(", sessionId=");
builder.append(sessionId);
builder.append(", bytesRead=");
builder.append(bytesRead);
builder.append(", contentLength=");
builder.append(contentLength);
builder.append(", clientUploadKey=");
builder.append(clientUploadKey);
builder.append(", sessionKey=");
builder.append(sessionKey);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,112 @@
/*
* Copyright 2010 Manuel Carrasco Moñino. (manolo at apache/org)
* http://code.google.com/p/gwtupload
*
* Licensed 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.gcube.portlets.widgets.mpformbuilder.shared.upload;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This File Upload Listener is used by Apache Commons File Upload to monitor
* the progress of the uploaded file.
*
* This Listener saves itself into a unique map in memory. It doesn't work when
* the application is deployed in cluster.
*
* It is thought to be used in systems where session objects are not updated
* until the request has finished.
*
* @see MemoryUploadEvent
*/
public class MemoryUploadListener extends AbstractUploadProgressListener {
private static final long serialVersionUID = 2082376357722210169L;
private static final Map<String, MemoryUploadListener> listeners = new HashMap<String, MemoryUploadListener>();
private static Logger logger = LoggerFactory
.getLogger(MemoryUploadListener.class);
/**
* Instantiates a new memory upload listener.
*
* @param session
* the session
* @param clientUploadKey
* the client upload key
* @param percentageOffset
* the percentage offset
* @param completePercentage
* the complete percentage
*/
public MemoryUploadListener(HttpSession session, String clientUploadKey,
int percentageOffset, double completePercentage) {
super(session, clientUploadKey, percentageOffset, completePercentage);
}
/**
* Current.
*
* @param sessionId
* the session id
* @param clientUploadKey
* the client upload key
* @return the memory upload listener
*/
public static MemoryUploadListener current(String sessionId,
String clientUploadKey) {
String sessionKey = getSessionKey(sessionId, clientUploadKey);
MemoryUploadListener listener = listeners.get(sessionKey);
logger.debug(sessionKey + " get " + listener);
return listener;
}
/*
* (non-Javadoc)
*
* @see org.gcube.portlets.widgets.workspaceuploader.server.upload.
* AbstractUploadProgressListener#remove()
*/
public void remove() {
listeners.remove(sessionKey);
logger.info(sessionKey + " Remove " + this.toString());
current(sessionKey);
}
/*
* (non-Javadoc)
*
* @see org.gcube.portlets.widgets.workspaceuploader.server.upload.
* AbstractUploadProgressListener#save()
*/
public void save() {
listeners.put(sessionKey, this);
logger.debug(sessionKey + " Saved " + this.toString());
}
/* (non-Javadoc)
* @see org.gcube.portlets.widgets.workspaceuploader.server.upload.AbstractUploadProgressListener#toString()
*/
public String toString() {
return super.toString();
}
}

View File

@ -0,0 +1,29 @@
/*
* Copyright 2010 Manuel Carrasco Moñino. (manolo at apache/org)
* http://code.google.com/p/gwtupload
*
* Licensed 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.gcube.portlets.widgets.mpformbuilder.shared.upload;
/**
* The Class UploadCanceledException.
* thrown when the client cancels the upload transfer.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 8, 2015
*/
public class UploadCanceledException extends RuntimeException {
private static final long serialVersionUID = 1L;
}

View File

@ -12,7 +12,6 @@ import java.util.List;
*/
public final class UploadProgress implements Serializable{
/**
*
*/

View File

@ -0,0 +1,124 @@
package org.gcube.portlets.widgets.mpformbuilder.shared.upload;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.fileupload.ProgressListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class UploadProgressInputStream.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 1, 2015
*/
public final class UploadProgressInputStream extends FilterInputStream {
private List<ProgressListener> listeners;
private long bytesRead = 0L;
private long totalBytes = 0L;
private static Logger logger = LoggerFactory.getLogger(UploadProgressInputStream.class);
/**
* Instantiates a new upload progress input stream.
*
* @param in the in
* @param totalBytes the total bytes
*/
public UploadProgressInputStream(final InputStream in, final long totalBytes) {
super(in);
this.totalBytes = totalBytes;
listeners = new ArrayList<ProgressListener>();
}
/**
* Adds the listener.
*
* @param listener the listener
*/
public void addListener(final ProgressListener listener) {
listeners.add(listener);
}
/* (non-Javadoc)
* @see java.io.FilterInputStream#read()
*/
@Override
public int read() throws IOException {
int b = super.read();
this.bytesRead++;
updateListeners(bytesRead, totalBytes);
return b;
}
/* (non-Javadoc)
* @see java.io.FilterInputStream#read(byte[])
*/
@Override
public int read(final byte b[]) throws IOException {
return read(b, 0, b.length);
}
/* (non-Javadoc)
* @see java.io.FilterInputStream#read(byte[], int, int)
*/
@Override
public int read(final byte b[], final int off, final int len) throws IOException {
int bytesRead = in.read(b, off, len);
this.bytesRead = this.bytesRead + bytesRead;
updateListeners(this.bytesRead, totalBytes);
return bytesRead;
}
/* (non-Javadoc)
* @see java.io.FilterInputStream#close()
*/
@Override
public void close() throws IOException {
super.close();
updateListeners(totalBytes, totalBytes);
}
/**
* Update listeners.
*
* @param bytesRead the bytes read
* @param totalBytes the total bytes
*/
/*private void updateListeners(final long bytesRead, final long totalBytes) throws IOException{
try{
for (ProgressListener listener : listeners)
listener.update(bytesRead, totalBytes, listeners.size());
}catch(UploadCanceledException e){
logger.warn("Update Listener thrown UploadCanceledException: closing stream..");
try {
close();
}catch (IOException e1) {
logger.warn("Close stream thrown this Exception, silent catch");
}
throw new IOException("Upload cancelled from Client");
}
}*/
/**
* Update listeners.
*
* @param bytesRead the bytes read
* @param totalBytes the total bytes
*/
private void updateListeners(final long bytesRead, final long totalBytes){
for (ProgressListener listener : listeners)
listener.update(bytesRead, totalBytes, listeners.size());
//UploadCanceledException IS PROPAGATED HERE
}
}

View File

@ -0,0 +1,248 @@
package org.gcube.portlets.widgets.mpformbuilder.shared.upload;
import java.io.Serializable;
import java.util.Date;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is a File Upload Listener that is used by Apache Commons File Upload to
* monitor the progress of the uploaded file.
*
* This object and its attributes have to be serializable because Google
* App-Engine uses dataStore and memCache to store session objects.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Sep 8, 2015
*
*/
public class UploadProgressListener extends AbstractUploadProgressListener {
/**
*
*/
private static final long serialVersionUID = -7311261847805770831L;
private static Logger logger = LoggerFactory.getLogger(AbstractUploadProgressListener.class);
private static int noDataTimeout = 20000;
private static final int WATCHER_INTERVAL = 2000;
private TimeoutWatchDog watcher = null;
/**
* Sets the no data timeout.
*
* @param i
* the new no data timeout
*/
public static void setNoDataTimeout(int i) {
noDataTimeout = i;
}
/**
* A class which is executed in a new thread, so its able to detect when an
* upload process is frozen and sets an exception in order to be canceled.
* This doesn't work in Google application engine
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Sep 8,
* 2015
*/
public class TimeoutWatchDog extends Thread implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6958907286385617168L;
AbstractUploadProgressListener listener;
private long lastBytesRead = 0L;
private long lastData = new Date().getTime();
/**
* Instantiates a new timeout watch dog.
*
* @param l
* the l
*/
public TimeoutWatchDog(AbstractUploadProgressListener l) {
listener = l;
}
/**
* Cancel.
*/
public void cancel() {
listener = null;
}
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
Thread.sleep(WATCHER_INTERVAL);
} catch (InterruptedException e) {
if (listener != null) {
if (listener.getBytesRead() > 0
&& listener.getPercentage() >= 100
|| listener.isCanceled()) {
logger.debug(sessionKey
+ " TimeoutWatchDog: upload process has finished, stoping watcher");
listener = null;
} else {
// if (isFrozen()) {
// logger.info( sessionId +
// " TimeoutWatchDog: the recepcion seems frozen: " +
// listener.getBytesRead() + "/" +
// listener.getContentLength() + " bytes ("
// + listener.getPercentage() + "%) ");
// exception = new
// UploadTimeoutException("No new data received after "
// + noDataTimeout / 1000 + " seconds");
// } else {
run();
}
}
}
}
/**
* Checks if is frozen.
*
* @return true, if is frozen
*/
private boolean isFrozen() {
long now = new Date().getTime();
if (bytesRead > lastBytesRead) {
lastData = now;
lastBytesRead = bytesRead;
} else if (now - lastData > noDataTimeout) {
return true;
}
return false;
}
}
/**
* Current.
*
* @param request
* the request
* @param clientUploadKey
* the client upload key
* @return the abstract upload progress listener
*/
public static AbstractUploadProgressListener current(HttpSession session,
String clientUploadKey) {
String sessionKey = getSessionKey(session.getId(), clientUploadKey);
return (AbstractUploadProgressListener) session.getAttribute(sessionKey);
}
/**
* Instantiates a new upload listener.
*
* @param request
* the request
* @param clientUploadKey
* the client upload key
* @param percentageOffset
* the percentage offset
* @param completePercentage
* the complete percentage
*/
public UploadProgressListener(HttpSession session, String clientUploadKey,
int percentageOffset, double completePercentage) {
super(session, clientUploadKey, percentageOffset, completePercentage);
startWatcher();
}
/*
* (non-Javadoc)
*
* @see gwtupload.server.AbstractUploadListener#remove()
*/
/**
* Removes the.
*/
public void remove() {
logger.debug(sessionKey + " removing: " + toString());
if (getSession() != null) {
// logger.debug(sessionKey + " skipping remove. A TODO must be realized");
// /*TODO REMOVE SESSION KEY FROM SESSION MUST BE MANAGED IN ANOTHER WAY IN ORDER TO AVOID THAT
// * IT'S REMOVED FROM SESSION BEFORE THAT POLLING RETRIEVES STATUS, USE A FLAG REMOVED?*/
getSession().removeAttribute(sessionKey);
logger.info("Removed from session: " + toString());
}
}
/*
* (non-Javadoc)
*
* @see gwtupload.server.AbstractUploadListener#save()
*/
/**
* Save.
*/
public void save() {
if (getSession() != null) {
getSession().setAttribute(sessionKey, this);
logger.info("Save - Added in session: " + toString());
}
logger.debug(sessionKey + " save listener " + toString());
}
/*
* (non-Javadoc)
*
* @see gwtupload.server.AbstractUploadListener#update(long, long, int)
*/
@Override
public void update(long done, long total, int item) {
super.update(done, total, item);
if (getPercentage() >= 100) {
stopWatcher();
}
}
/**
* Start watcher.
*/
private void startWatcher() {
if (watcher == null) {
try {
watcher = new TimeoutWatchDog(this);
watcher.start();
} catch (Exception e) {
logger.error(sessionKey + " unable to create watchdog: "
+ e.getMessage());
}
}
}
/**
* Stop watcher.
*/
private void stopWatcher() {
if (watcher != null) {
watcher.cancel();
}
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("UploadProgressListener [watcher=");
builder.append(watcher);
builder.append(", "+super.toString());
return builder.toString();
}
}

View File

@ -8,162 +8,82 @@ import java.io.Serializable;
/**
* The Class WorkspaceUploadFile.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 3, 2015
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it at ISTI-CNR
*
* Oct 5, 2020
*/
public class WorkspaceUploadFile implements Serializable{
/**
*
*/
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 4693939404459889859L;
private String parentId;
/** The file name. */
private String fileName;
private String itemId;
private String versionName;
/** The item id. */
private String tempSystemPath;
private String createdByUser;
/**
* Instantiates a new workspace upload file.
*/
public WorkspaceUploadFile() {
}
/**
* Instantiates a new workspace upload file.
*
* @param parentId the parent id
* @param itemId the item id
* @param fileName the file name
* @param versionName the version
* @param tempSystemPath the temp system path
* @param createdByUser the created by user
*/
public WorkspaceUploadFile(String parentId, String itemId, String fileName, String versionName) {
public WorkspaceUploadFile(String fileName, String tempSystemPath, String createdByUser) {
super();
this.parentId = parentId;
this.itemId = itemId;
this.fileName = fileName;
this.versionName = versionName;
this.tempSystemPath = tempSystemPath;
this.createdByUser = createdByUser;
}
/**
* Gets the version name.
*
* @return the version name
*/
public String getVersionName() {
return versionName;
}
/**
* Sets the version name.
*
* @param versionName the new version name
*/
public void setVersionName(String versionName) {
this.versionName = versionName;
}
/**
* Sets the item id.
*
* @param itemId the itemId to set
*/
public void setItemId(String itemId) {
this.itemId = itemId;
}
/**
* Gets the parent id.
*
* @return the parentId
*/
public String getParentId() {
return parentId;
}
/**
* Gets the file name.
*
* @return the fileName
*/
public String getFileName() {
return fileName;
}
/**
* Sets the parent id.
*
* @param parentId the parentId to set
*/
public void setParentId(String parentId) {
this.parentId = parentId;
}
/**
* Gets the item id.
*
* @return the itemId
*/
public String getItemId() {
return itemId;
}
/**
* Sets the file name.
*
* @param fileName the fileName to set
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
int hash = 31;
hash = hash * 13 + (parentId == null ? 0 : parentId.hashCode());
hash = hash * 17 + (fileName == null ? 0 : fileName.hashCode());
hash = hash * 19 + (itemId == null ? 0 : itemId.hashCode());
return hash;
public String getTempSystemPath() {
return tempSystemPath;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public void setTempSystemPath(String tempSystemPath) {
this.tempSystemPath = tempSystemPath;
}
public String getCreatedByUser() {
return createdByUser;
}
public void setCreatedByUser(String createdByUser) {
this.createdByUser = createdByUser;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("WorkspaceUploadFile [parentId=");
builder.append(parentId);
builder.append(", fileName=");
builder.append(fileName);
builder.append(", itemId=");
builder.append(itemId);
builder.append(", versionName=");
builder.append(versionName);
builder.append("]");
return builder.toString();
return "WorkspaceUploadFile [fileName=" + fileName + ", tempSystemPath=" + tempSystemPath + ", createdByUser="
+ createdByUser + "]";
}
}

View File

@ -5,12 +5,7 @@ package org.gcube.portlets.widgets.mpformbuilder.shared.upload;
import java.io.Serializable;
/**
* The Class WorkspaceUploaderItem.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 3, 2015
*/
public class WorkspaceUploaderItem implements Serializable{

View File

@ -5,20 +5,35 @@
<web-app>
<!-- Servlets -->
<servlet>
<servlet-name>mpformbuilderServlet</servlet-name>
<servlet-class>org.gcube.portlets.widgets.mpformbuilder.server.MetadataProfileFormBuilderServiceImpl</servlet-class>
</servlet>
<!-- Servlets -->
<servlet>
<servlet-name>mpformbuilderServlet</servlet-name>
<servlet-class>org.gcube.portlets.widgets.mpformbuilder.server.MetadataProfileFormBuilderServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mpformbuilderServlet</servlet-name>
<url-pattern>/MetadataProfileFormBuilder/mpformbuilderservice</url-pattern>
</servlet-mapping>
<!-- Servlets -->
<servlet>
<servlet-name>mpformbuilderUploadServlet</servlet-name>
<servlet-class>org.gcube.portlets.widgets.mpformbuilder.server.MetadataProfileFormBuilderUploadServlet</servlet-class>
</servlet>
<!-- Default page to serve -->
<welcome-file-list>
<welcome-file>MetadataProfileFormBuilder.html</welcome-file>
</welcome-file-list>
<servlet-mapping>
<servlet-name>mpformbuilderServlet</servlet-name>
<url-pattern>/MetadataProfileFormBuilder/mpformbuilderservice</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>mpformbuilderUploadServlet</servlet-name>
<url-pattern>/MetadataProfileFormBuilder/mpformbuilderUploadServlet</url-pattern>
</servlet-mapping>
<!-- Default page to serve -->
<welcome-file-list>
<welcome-file>MetadataProfileFormBuilder.html</welcome-file>
</welcome-file-list>
</web-app>