also share idea can now upload files

git-svn-id: http://svn.research-infrastructures.eu/public/d4science/gcube/trunk/portal/sbd-uploadshare-portlet@164647 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Massimiliano Assante 2018-03-01 15:34:53 +00:00
parent 85f3e56a06
commit e3bb17d065
7 changed files with 200 additions and 23 deletions

View File

@ -25,7 +25,7 @@
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes> <attributes>
<attribute name="owner.project.facets" value="java"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="output" path="target/classes"/> <classpathentry kind="output" path="target/classes"/>

View File

@ -12,7 +12,7 @@
<artifactId>sbd-uploadshare-portlet</artifactId> <artifactId>sbd-uploadshare-portlet</artifactId>
<packaging>war</packaging> <packaging>war</packaging>
<name>SBD-UploadAndSharePortlets Portlet</name> <name>SBD-UploadAndSharePortlets Portlet</name>
<version>1.0.0-SNAPSHOT</version> <version>1.1.0-SNAPSHOT</version>
<description> <description>
Upload Dataset And Share Idea Portlets Upload Dataset And Share Idea Portlets
</description> </description>

View File

@ -1,12 +1,18 @@
package org.gcube.portlets.user.sbdportlets; package org.gcube.portlets.user.sbdportlets;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import javax.portlet.ActionRequest; import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse; import javax.portlet.ActionResponse;
import javax.portlet.PortletException; import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.gcube.applicationsupportlayer.social.ApplicationNotificationsManager; import org.gcube.applicationsupportlayer.social.ApplicationNotificationsManager;
@ -14,8 +20,17 @@ import org.gcube.applicationsupportlayer.social.NotificationsManager;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingSite; import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingSite;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingUser; import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingUser;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider; import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.homelibary.model.items.type.WorkspaceItemType;
import org.gcube.common.homelibrary.home.HomeLibrary; import org.gcube.common.homelibrary.home.HomeLibrary;
import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException;
import org.gcube.common.homelibrary.home.exceptions.InternalErrorException;
import org.gcube.common.homelibrary.home.workspace.Workspace; import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder;
import org.gcube.common.homelibrary.home.workspace.WorkspaceItem;
import org.gcube.common.homelibrary.home.workspace.exceptions.ItemNotFoundException;
import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException;
import org.gcube.common.homelibrary.home.workspace.folder.FolderItem;
import org.gcube.common.homelibrary.util.WorkspaceUtil;
import org.gcube.common.portal.PortalContext; import org.gcube.common.portal.PortalContext;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.notifications.bean.GenericItemBean; import org.gcube.portal.notifications.bean.GenericItemBean;
@ -24,10 +39,15 @@ import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager; import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeUser; import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors; import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages; import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.upload.FileItem;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.User; import com.liferay.portal.model.User;
@ -43,6 +63,10 @@ import com.liferay.util.bridges.mvc.MVCPortlet;
public class CollaborateWithUs extends MVCPortlet { public class CollaborateWithUs extends MVCPortlet {
private static Log _log = LogFactoryUtil.getLog(CollaborateWithUs.class); private static Log _log = LogFactoryUtil.getLog(CollaborateWithUs.class);
private static String SHARE_IDEA_ROLE_MANAGER_NAME = "UserIdea-Admin"; private static String SHARE_IDEA_ROLE_MANAGER_NAME = "UserIdea-Admin";
private final static String UPLOADED_FILE_ATTR_NAME = "myfile";
//make sure in the jsp there's <portlet:resourceURL var="uploadFileURL" id="uploadFiles" />
private final static String RESOURCE_URL_ID = "uploadFiles";
public static final String ATTACHMENT_FOLDER ="_shared attachments";
private LiferayRoleManager roleManager = new LiferayRoleManager(); private LiferayRoleManager roleManager = new LiferayRoleManager();
private LiferayUserManager userManager = new LiferayUserManager(); private LiferayUserManager userManager = new LiferayUserManager();
@ -56,6 +80,12 @@ public class CollaborateWithUs extends MVCPortlet {
String people_institutions = ParamUtil.getString(actionRequest, "people_institutions"); String people_institutions = ParamUtil.getString(actionRequest, "people_institutions");
String theAbstract = ParamUtil.getString(actionRequest, "abstract"); String theAbstract = ParamUtil.getString(actionRequest, "abstract");
String experiment_tags = ParamUtil.getString(actionRequest, "experiment_tags"); String experiment_tags = ParamUtil.getString(actionRequest, "experiment_tags");
String[] attachmentIds = ParamUtil.getParameterValues(actionRequest, "selected-attachment");
for (int i = 0; i < attachmentIds.length; i++) {
_log.debug(i+"id="+attachmentIds[i]);
}
SessionMessages.add(actionRequest.getPortletSession(), "method-form-success");
_log.debug("new experiment shared: " + experiment_name); _log.debug("new experiment shared: " + experiment_name);
SessionMessages.add(actionRequest.getPortletSession(), "experiment-form-success"); SessionMessages.add(actionRequest.getPortletSession(), "experiment-form-success");
@ -64,7 +94,8 @@ public class CollaborateWithUs extends MVCPortlet {
long teamId = roleManager.getTeam(groupId, SHARE_IDEA_ROLE_MANAGER_NAME).getTeamId(); long teamId = roleManager.getTeam(groupId, SHARE_IDEA_ROLE_MANAGER_NAME).getTeamId();
List<GCubeUser> theManagers = userManager.listUsersByTeam(teamId); List<GCubeUser> theManagers = userManager.listUsersByTeam(teamId);
HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest); HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
boolean result = sendNotificationToUser(request, groupId, currentUser, theManagers, experiment_name, people_institutions, theAbstract, experiment_tags); boolean result = sendNotificationToUser(request, groupId, currentUser, theManagers,
experiment_name, people_institutions, theAbstract, attachmentIds, experiment_tags);
if (result) if (result)
actionResponse.setRenderParameter("mvcPath", "/html/collaboratewithus/view-experiment-inserted.jsp"); actionResponse.setRenderParameter("mvcPath", "/html/collaboratewithus/view-experiment-inserted.jsp");
else else
@ -75,8 +106,76 @@ public class CollaborateWithUs extends MVCPortlet {
} }
} }
@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws PortletException, IOException {
String resourceID = resourceRequest.getResourceID();
if (resourceID.equals(RESOURCE_URL_ID)) {
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(resourceRequest);
File multipartFile = uploadRequest.getFile(UPLOADED_FILE_ATTR_NAME);
FileItem[] items = uploadRequest.getMultipartParameterMap().get(UPLOADED_FILE_ATTR_NAME);
String fileName = "";
String contentType = "";
for (int i = 0; i < items.length; i++) {
fileName = items[i].getFileName();
contentType = items[i].getContentType();
System.out.println(fileName);
System.out.println(contentType);
}
JSONObject fileObject = JSONFactoryUtil.createJSONObject();
try {
Workspace workspace = getWorkspace(uploadRequest);
String wsItemId = uploadToUserWorkspace(workspace, fileName, contentType, new ByteArrayInputStream(FileUtil.getBytes(multipartFile)));
fileObject.put("itemId", wsItemId);
fileObject.put("fileName", fileName);
} catch (Exception e) {
_log.error("There was an error uploading the file " + fileName, e);
}
resourceResponse.getWriter().println(fileObject);
} else {
_log.debug("nothing to do");
}
}
/**
*
* @param uploadRequest is the XHR http servlet request
* @return
* @throws Exception
*/
private Workspace getWorkspace(UploadPortletRequest uploadRequest ) throws Exception {
Workspace workspace;
try{
PortalContext pContext = PortalContext.getConfiguration();
ScopeProvider.instance.set(pContext.getCurrentScope(uploadRequest));
workspace = HomeLibrary.getUserWorkspace(pContext.getCurrentUser(uploadRequest).getUsername());
}catch(InternalErrorException | HomeNotFoundException | WorkspaceFolderNotFoundException e){
String msg = "Sorry, an error occurred when retrieving workspace item, Refresh an try again";
_log.error("HL error: ",e);
throw new Exception(msg);
}
return workspace;
}
private String uploadToUserWorkspace(Workspace ownerWS, String fileName, String mimeType,InputStream fileData) throws Exception {
WorkspaceFolder attachment = null;
try{
attachment = (WorkspaceFolder) ownerWS.getItemByPath(ownerWS.getRoot().getPath() + "/" + ATTACHMENT_FOLDER);
} catch (ItemNotFoundException e) {
_log.info(ATTACHMENT_FOLDER + " Workspace Folder does not exists, creating it ");
attachment = ownerWS.getRoot().createFolder(ATTACHMENT_FOLDER, "Folder created automatically by the System");
}
String itemName = WorkspaceUtil.getUniqueName(fileName, attachment);
FolderItem item = WorkspaceUtil.createExternalFile(attachment, itemName, "File created automatically by the System", mimeType, fileData);
String toReturn = item.getId();
_log.debug("Uploaded " + item.getName() + " - Returned Workspace id=" +toReturn);
return toReturn;
}
private boolean sendNotificationToUser(HttpServletRequest request, long groupId, User currentUser, List<GCubeUser> theManagers private boolean sendNotificationToUser(HttpServletRequest request, long groupId, User currentUser, List<GCubeUser> theManagers
, String experiment_name, String people_institutions, String theAbstract, String experiment_tags) throws Exception { , String experiment_name, String people_institutions, String theAbstract, String[] attachmentIds, String experiment_tags) throws Exception {
String scope = PortalContext.getConfiguration().getCurrentScope(""+groupId); String scope = PortalContext.getConfiguration().getCurrentScope(""+groupId);
_log.info("sendNotificationToUser Scope: " + scope); _log.info("sendNotificationToUser Scope: " + scope);
@ -100,10 +199,19 @@ public class CollaborateWithUs extends MVCPortlet {
.append("\n").append("Abstract:\n").append(theAbstract).append("\n") .append("\n").append("Abstract:\n").append(theAbstract).append("\n")
.append("\n").append("Keywords (Comma separated): ").append(experiment_tags).append("\n"); .append("\n").append("Keywords (Comma separated): ").append(experiment_tags).append("\n");
List<String> attachmentsList = Arrays.asList(attachmentIds);
String body = sb.toString(); String body = sb.toString();
String messageId = workspace.getWorkspaceMessageManager().sendMessageToPortalLogins(subject, body, new ArrayList<String>(), recipientIds); try {
body += getPublicLinksForAttachs(workspace, attachmentsList);
}
catch (Exception e) {
_log.error("Ops, could not generate publick link for some of the attachments");
}
String messageId =
workspace.getWorkspaceMessageManager().
sendMessageToPortalLogins(subject, body, attachmentsList, recipientIds);
_log.debug("Sending message notification to: " + recipientIds.toString()); _log.info("Sending upload method message notification to: " + recipientIds.toString());
NotificationsManager nm = new ApplicationNotificationsManager(new SocialNetworkingSite(request), scope, new SocialNetworkingUser( NotificationsManager nm = new ApplicationNotificationsManager(new SocialNetworkingSite(request), scope, new SocialNetworkingUser(
currentUser.getScreenName(), currentUser.getEmailAddress(), currentUser.getFullName(), "")); currentUser.getScreenName(), currentUser.getEmailAddress(), currentUser.getFullName(), ""));
Thread thread = new Thread(new MessageNotificationsThread(recipients, messageId, subject, body, nm)); Thread thread = new Thread(new MessageNotificationsThread(recipients, messageId, subject, body, nm));
@ -111,4 +219,53 @@ public class CollaborateWithUs extends MVCPortlet {
return (messageId != null); return (messageId != null);
} }
/**
*
* @param workspace
* @param listAttachmentsId
* @return
* @throws ItemNotFoundException
* @throws InternalErrorException
*/
private String getPublicLinksForAttachs(Workspace workspace, List<String> listAttachmentsId) throws ItemNotFoundException, InternalErrorException{
if (listAttachmentsId != null && (!listAttachmentsId.isEmpty()) ) {
List<WorkspaceItem> attachments = new ArrayList<WorkspaceItem>();
for (String itemId : listAttachmentsId) {
attachments.add(workspace.getItem(itemId));
}
StringBuilder builder = new StringBuilder();
if(attachments!=null && attachments.size() > 0){
builder.append("\n\n\nThe following ");
String msg = attachments.size()>1?"files were attached to this message:":"file was attached to this message:";
builder.append(msg+"\n");
for (WorkspaceItem workspaceItem : attachments) {
if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)) {
FolderItem folderItem = (FolderItem) workspaceItem;
String publicLink = "";
String itemName = "";
try {
itemName = workspaceItem.getName();
publicLink = folderItem.getPublicLink(true);
}
catch (InternalErrorException e) {
_log.warn("An error occurred when creating public link for attachment, skipping file: " + itemName);
return "";
}
builder.append(itemName + " ("+publicLink+")");
builder.append("\n");
}
}
_log.debug("returning public links: "+builder.toString());
return builder.toString();
}
else return "";
}
else return "";
}
} }

View File

@ -120,8 +120,6 @@ public class UploadDataset extends MVCPortlet {
System.out.println(fileName); System.out.println(fileName);
System.out.println(contentType); System.out.println(contentType);
} }
// Path written = Files.write(Paths.get(System.getProperty("catalina.home")+"/temp/"+fileName), FileUtil.getBytes(multipartFile));
// System.out.println("Written File = " + written.toRealPath());
JSONObject fileObject = JSONFactoryUtil.createJSONObject(); JSONObject fileObject = JSONFactoryUtil.createJSONObject();
try { try {
Workspace workspace = getWorkspace(uploadRequest); Workspace workspace = getWorkspace(uploadRequest);

View File

@ -2,16 +2,10 @@
<!DOCTYPE display PUBLIC "-//Liferay//DTD Display 6.2.0//EN" "http://www.liferay.com/dtd/liferay-display_6_2_0.dtd"> <!DOCTYPE display PUBLIC "-//Liferay//DTD Display 6.2.0//EN" "http://www.liferay.com/dtd/liferay-display_6_2_0.dtd">
<display> <display>
<category name="category.sample">
<portlet id="SBD-UploadAndSharePortlets" />
</category>
<category name="SoBigData Apps"> <category name="SoBigData Apps">
<portlet id="upload-dataset"></portlet> <portlet id="upload-dataset"></portlet>
<portlet id="collaborate-with-us"></portlet> <portlet id="collaborate-with-us"></portlet>
</category>
<category name="gCube Applications">
<portlet id="access-exploratory"></portlet> <portlet id="access-exploratory"></portlet>
<portlet id="access-application"></portlet> <portlet id="access-application"></portlet>
<portlet id="file-upload"></portlet>
</category> </category>
</display> </display>

View File

@ -20,6 +20,9 @@
<icon>/icon.png</icon> <icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters> <requires-namespaced-parameters>false</requires-namespaced-parameters>
<header-portlet-css>/css/main.css</header-portlet-css> <header-portlet-css>/css/main.css</header-portlet-css>
<header-portlet-javascript>
/js/jquery.min.js
</header-portlet-javascript>
<footer-portlet-javascript> <footer-portlet-javascript>
/js/main.js /js/main.js
</footer-portlet-javascript> </footer-portlet-javascript>
@ -38,7 +41,6 @@
<css-class-wrapper> <css-class-wrapper>
access-exploratory-portlet access-exploratory-portlet
</css-class-wrapper> </css-class-wrapper>
</portlet> </portlet>
<portlet> <portlet>
<portlet-name>access-application</portlet-name> <portlet-name>access-application</portlet-name>

View File

@ -8,6 +8,7 @@
<portlet:defineObjects /> <portlet:defineObjects />
<liferay-theme:defineObjects /> <liferay-theme:defineObjects />
<portlet:resourceURL var="uploadFileURL" id="uploadFiles" />
<% <%
if (SessionErrors.contains(renderRequest.getPortletSession(), "experiment-form-error")) { if (SessionErrors.contains(renderRequest.getPortletSession(), "experiment-form-error")) {
@ -39,16 +40,38 @@
</div> </div>
</c:when> </c:when>
<c:otherwise> <c:otherwise>
<script
src="<%=request.getContextPath()%>/js/jquery.uploadfile.min.js"></script>
<script>
$(document).ready(function(){
$("#multipleupload").uploadFile({
url:"<%=uploadFileURL.toString()%>",
multiple : true,
dragDrop : true,
sequential : true,
sequentialCount : 1,
maxFileCount : 3,
maxFileSize: 10*1024*1024,
showStatusAfterSuccess: false,
fileName : "myfile",
onSuccess : function(files, data, xhr, pd) {
var content = JSON.parse(data);
appendChip(content.fileName, content.itemId);
}
});
});
</script>
<a class="btn btn-link btn-large" href="${normalState}"><i <a class="btn btn-link btn-large" href="${normalState}"><i
class="icon icon-angle-left"></i>&nbsp;Back (Cancel)</a> class="icon icon-angle-left"></i>&nbsp;Back (Cancel)</a>
<p style="font-size: 15px; padding: 15px;">Please give us a description about the <p style="font-size: 15px; padding: 15px;">
dataset/method you want to insert in the catalogue. The SoBigData Please give us a description about the dataset/method you want to
research, technical and ethical boards will evaluate your application insert in the catalogue. The SoBigData research, technical and
before the actual upload. In particular, in case of datasets, please ethical boards will evaluate your application before the actual
visit also our <a href="http://146.48.83.51/moodle" target="_blank"> upload. In particular, in case of datasets, please visit also our <a
First aid for Responsible data Scientists</a>: we href="http://146.48.83.51/moodle" target="_blank"> First aid for
provide resources and information to understand and check possible Responsible data Scientists</a>: we provide resources and information to
ethical issues for your dataset.</p> understand and check possible ethical issues for your dataset.
</p>
<div <div
style="width: 100%; text-align: left; padding: 10px; color: #3B5998;"> style="width: 100%; text-align: left; padding: 10px; color: #3B5998;">
<aui:form action="<%=addIdeaActionURL%>" method="post" name="fm"> <aui:form action="<%=addIdeaActionURL%>" method="post" name="fm">
@ -61,6 +84,9 @@
<aui:input type="textarea" rows="10" name="abstract" <aui:input type="textarea" rows="10" name="abstract"
label="Abstract, 2 pages max" value="" required="true" label="Abstract, 2 pages max" value="" required="true"
style="width:90%;" /> style="width:90%;" />
<span> Additional Material (max 3 files, allowed max size per file: 10 MB):</span>
<div id="multipleupload">Select file to attach</div>
<div id="attachedFiles"></div>
<aui:input name="experiment_tags" label="Keywords (Comma separated)" <aui:input name="experiment_tags" label="Keywords (Comma separated)"
value="" required="false" style="width:90%;" /> value="" required="false" style="width:90%;" />
<aui:button-row> <aui:button-row>