added form for requesting VREs

git-svn-id: http://svn.research-infrastructures.eu/public/d4science/gcube/trunk/portal/sbd-uploadshare-portlet@169350 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Massimiliano Assante 2018-06-20 14:23:53 +00:00
parent b27ac6a41c
commit 59ca1a0a3a
8 changed files with 503 additions and 1 deletions

View File

@ -0,0 +1,298 @@
package org.gcube.portlets.user.vremanagement;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletRequest;
import org.gcube.applicationsupportlayer.social.ApplicationNotificationsManager;
import org.gcube.applicationsupportlayer.social.NotificationsManager;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingSite;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingUser;
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.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.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.scope.api.ScopeProvider;
import org.gcube.portal.notifications.bean.GenericItemBean;
import org.gcube.portal.notifications.thread.MessageNotificationsThread;
import org.gcube.vomanagement.usermanagement.exception.RoleRetrievalFault;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.gcube.vomanagement.usermanagement.model.GatewayRolesNames;
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.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
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.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
*
- Request a VRE form
* Portlet implementation class RequestVRE
*/
public class RequestVRE extends MVCPortlet {
private static Log _log = LogFactoryUtil.getLog(RequestVRE.class);
private static String REQUEST_VRE_ROLE_MANAGER_NAME = "Infrastructure-Manager";
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 LiferayUserManager userManager = new LiferayUserManager();
public void addIdea(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException {
try{
User currentUser = (User) actionRequest.getAttribute(WebKeys.USER);
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
long groupId = themeDisplay.getLayout().getGroupId();
String vre_name = ParamUtil.getString(actionRequest, "vre_name");
String theAbstract = ParamUtil.getString(actionRequest, "abstract");
String vreManagerName = ParamUtil.getString(actionRequest, "vre-manager-name");
String contact_email = ParamUtil.getString(actionRequest, "email");
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 VRE Request: " + vre_name);
SessionMessages.add(actionRequest.getPortletSession(), "experiment-form-success");
long roleId = roleManager.getRole(REQUEST_VRE_ROLE_MANAGER_NAME, groupId).getRoleId();
List<GCubeUser> theManagers = userManager.listUsersByGroupAndRole(groupId, roleId);
long infraManagerRoleId = -1;
boolean result = false;
if (theManagers == null || theManagers.isEmpty()) {
try {
infraManagerRoleId = roleManager.getRoleIdByName(GatewayRolesNames.INFRASTRUCTURE_MANAGER.getRoleName());
}
catch (RoleRetrievalFault e) {
_log.warn("There is no (Site) Role " + infraManagerRoleId + " in this portal. Will not notify about removed user accounts.");
return;
}
theManagers = userManager.listUsersByGlobalRole(infraManagerRoleId);
}
if (theManagers == null || theManagers.isEmpty()) {
_log.warn("There are no users with (Site) Role " + infraManagerRoleId + " on this portal. Will not notify about this vre request.");
}
else {
HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
result = sendNotificationToUser(request, groupId, currentUser, theManagers,
vre_name, theAbstract, vreManagerName, contact_email, attachmentIds);
}
if (result)
actionResponse.setRenderParameter("mvcPath", "/html/requestvre/view-experiment-inserted.jsp");
else
actionResponse.setRenderParameter("mvcPath", "/html/requestvre/view-experiment-error.jsp");
} catch(Exception e){
SessionErrors.add(actionRequest.getPortletSession(),"experiment-form-error");
e.printStackTrace();
}
}
@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
, String vre_name, String theAbstract, String vreManagerName, String email, String[] attachmentIds) throws Exception {
String scope = PortalContext.getConfiguration().getCurrentScope(""+groupId);
_log.info("sendNotificationToUser Scope: " + scope);
String authorizationToken = PortalContext.getConfiguration().getCurrentUserToken(scope, currentUser.getScreenName());
ScopeProvider.instance.set(scope);
SecurityTokenProvider.instance.set(authorizationToken);
Workspace workspace = HomeLibrary.getUserWorkspace(currentUser.getScreenName());
List<String> recipientIds = new ArrayList<String>();
List<GenericItemBean> recipients = new ArrayList<GenericItemBean>();
for (GCubeUser addressee : theManagers) {
recipients.add(new GenericItemBean(addressee.getUsername(), addressee.getUsername(), addressee.getFullname(), ""));
recipientIds.add(addressee.getUsername());
}
String subject = "A new VRE has been requested";
StringBuilder sb = new StringBuilder("Hi, the following VRE was requested by ").append(currentUser.getFullName())
.append(" (").append(currentUser.getEmailAddress()).append(").")
.append("\n\n").append("VRE name: ").append(vre_name).append("\n")
.append("\n").append("Manager(s)").append(vreManagerName).append("\n")
.append("\n").append("Abstract:\n").append(theAbstract).append("\n")
.append("\n").append("Contact email: ").append(email).append("\n");
List<String> attachmentsList = Arrays.asList(attachmentIds);
String body = sb.toString();
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.info("Sending upload method message notification to: " + recipientIds.toString());
NotificationsManager nm = new ApplicationNotificationsManager(new SocialNetworkingSite(request), scope, new SocialNetworkingUser(
currentUser.getScreenName(), currentUser.getEmailAddress(), currentUser.getFullName(), ""));
Thread thread = new Thread(new MessageNotificationsThread(recipients, messageId, subject, body, nm));
thread.start();
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

@ -8,4 +8,7 @@
<portlet id="access-exploratory"></portlet>
<portlet id="access-application"></portlet>
</category>
<category name="D4Science">
<portlet id="request-vre"></portlet>
</category>
</display>

View File

@ -1,6 +1,6 @@
name=SBD-UploadAndSharePortlets
module-group-id=liferay
module-incremental-version=2
module-incremental-version=3
tags=
short-description=
change-log=

View File

@ -54,6 +54,15 @@
access-application-portlet
</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>request-vre</portlet-name>
<icon>/icon.png</icon>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>request-vre-portlet</css-class-wrapper>
</portlet>
<role-mapper>
<role-name>administrator</role-name>
<role-link>Administrator</role-link>

View File

@ -143,4 +143,37 @@
<role-name>user</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>request-vre</portlet-name>
<display-name>Request a VRE</display-name>
<portlet-class>
org.gcube.portlets.user.vremanagement.RequestVRE
</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/requestvre/view.jsp</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>view</portlet-mode>
</supports>
<portlet-info>
<title>Request a VRE</title>
<short-title>Request Vre</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
<security-role-ref>
<role-name>guest</role-name>
</security-role-ref>
<security-role-ref>
<role-name>power-user</role-name>
</security-role-ref>
<security-role-ref>
<role-name>user</role-name>
</security-role-ref>
</portlet>
</portlet-app>

View File

@ -0,0 +1,29 @@
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui"%>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui"%>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme"%>
<%@page import="com.liferay.portal.kernel.portlet.LiferayWindowState"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionErrors"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionMessages"%>
<%@page import="com.liferay.portal.model.User"%>
<%@page import="com.liferay.portal.kernel.util.WebKeys"%>
<portlet:defineObjects />
<liferay-theme:defineObjects />
<%
User currentUser = (User) request.getAttribute(WebKeys.USER);
%>
<portlet:renderURL var="normalState"
windowState="<%=LiferayWindowState.NORMAL.toString()%>" />
<p class="lead">
Thank you
<%=currentUser.getFirstName()%>. There was an error submitting your request. Please report this issue.
</p>
<a class="btn btn-large btn-primary" href="${normalState}"><i
class="icon icon-angle-left"></i>&nbsp;Close and return to home</a>
<div

View File

@ -0,0 +1,30 @@
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui"%>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui"%>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme"%>
<%@page import="com.liferay.portal.kernel.portlet.LiferayWindowState"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionErrors"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionMessages"%>
<%@page import="com.liferay.portal.model.User"%>
<%@page import="com.liferay.portal.kernel.util.WebKeys"%>
<portlet:defineObjects />
<liferay-theme:defineObjects />
<%
User currentUser = (User) request.getAttribute(WebKeys.USER);
%>
<portlet:renderURL var="normalState"
windowState="<%=LiferayWindowState.NORMAL.toString()%>" />
<p class="lead">
Thank you
<%=currentUser.getFirstName()%>. We have been notified about your
request, will get back to you shortly.
</p>
<a class="btn btn-large btn-primary" href="${normalState}"><i
class="icon icon-angle-left"></i>&nbsp;Close and return to home</a>
<div

View File

@ -0,0 +1,100 @@
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui"%>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui"%>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme"%>
<%@page import="com.liferay.portal.kernel.portlet.LiferayWindowState"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionErrors"%>
<portlet:defineObjects />
<liferay-theme:defineObjects />
<portlet:resourceURL var="uploadFileURL" id="uploadFiles" />
<%
if (SessionErrors.contains(renderRequest.getPortletSession(), "experiment-form-error")) {
%>
<liferay-ui:error key="experiment-form-error"
message="Request VRE form submit had an issue, Please try again." />
<%
}
%>
<portlet:actionURL var="addIdeaActionURL" windowState="maximized"
name="addIdea">
</portlet:actionURL>
<portlet:renderURL var="maximizedState"
windowState="<%=LiferayWindowState.MAXIMIZED.toString()%>" />
<portlet:renderURL var="normalState"
windowState="<%=LiferayWindowState.NORMAL.toString()%>" />
<c:set var="maximised" scope="session"
value="${renderRequest.getWindowState().toString().equalsIgnoreCase('maximized')}" />
<c:choose>
<c:when test="${not maximised}">
<div style="width: 100%; text-align: center; color: #3B5998;">
<a class="btn btn-link" href="${maximizedState}"><i
class="icon icon-bar-chart icon-3x"></i></a>
</div>
</c:when>
<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
class="icon icon-angle-left"></i>&nbsp;Back (Cancel)</a>
<p style="font-size: 15px; padding: 15px;">Please give us a
description about the Virtual Research Environment (VRE) you wish to
create. The project research, technical and ethical boards will
evaluate your application and contact you about the result as soon as possible and always within 5 working days.</p>
<div
style="width: 100%; text-align: left; padding: 10px; color: #3B5998;">
<aui:form action="<%=addIdeaActionURL%>" method="post" name="fm">
<aui:input name="vre_name" label="VRE name" value="" required="true" />
<aui:input type="textarea" rows="5" name="abstract"
label="Abstract, 150 to 250 words" value="" required="true"
style="width:90%;" />
<aui:input name="vre-manager-name"
label="Responsible person(s)" value=""
required="true" style="width:90%;" />
<aui:input name="email" value="" label="Contact email (where to reach you)">
<aui:validator name="required" />
<aui:validator name="email" />
</aui:input>
<span>Logo and Additional Material (max 3 files, allowed maxsize per file: 10 MB):</span>
<div id="multipleupload">Select file to attach</div>
<div id="attachedFiles"></div>
<aui:button-row>
<a class="btn" href="${normalState}"><i class="icon-remove"></i>
Cancel</a>
<aui:button type="submit" value="Submit" />
</aui:button-row>
</aui:form>
</div>
</c:otherwise>
</c:choose>