sbd-uploadshare-portlet/src/main/java/org/gcube/portlets/user/vremanagement/RequestVRE.java

334 lines
14 KiB
Java

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.Date;
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.portal.PortalContext;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.storagehub.client.plugins.AbstractPlugin;
import org.gcube.common.storagehub.client.proxies.MessageManagerClient;
import org.gcube.common.storagehub.model.items.FolderItem;
import org.gcube.common.storagehubwrapper.server.StorageHubWrapper;
import org.gcube.common.storagehubwrapper.server.tohl.Workspace;
import org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceFolder;
import org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem;
import org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItemType;
import org.gcube.common.storagehubwrapper.shared.tohl.exceptions.InternalErrorException;
import org.gcube.common.storagehubwrapper.shared.tohl.exceptions.ItemNotFoundException;
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.LiferayGroupManager;
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()) {
String rootVoName = PortalContext.getConfiguration().getInfrastructureName();
long therootGroupId = new LiferayGroupManager().getGroupIdFromInfrastructureScope("/"+rootVoName);
try {
infraManagerRoleId = roleManager.getRoleIdByName(GatewayRolesNames.INFRASTRUCTURE_MANAGER.getRoleName());
theManagers = userManager.listUsersByGroupAndRole(therootGroupId, infraManagerRoleId);
}
catch (RoleRetrievalFault e) {
_log.warn("There are no users with (Site) Role " + infraManagerRoleId + " on " + rootVoName + " in this portal. Will not notify about this vre request");
return;
}
}
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
*/
public static Workspace getWorkspace(UploadPortletRequest uploadRequest) {
long userId;
String username = null;
try {
userId = PortalUtil.getUser(uploadRequest).getUserId();
username = new LiferayUserManager().getUserById(userId).getUsername();
} catch (Exception e) {
e.printStackTrace();
}
PortalContext pContext = PortalContext.getConfiguration();
String context = pContext.getCurrentScope(uploadRequest);
ScopeProvider.instance.set(context);
String authorizationToken = PortalContext.getConfiguration().getCurrentUserToken(context, username);
SecurityTokenProvider.instance.set(authorizationToken);
ScopeProvider.instance.set(context);
try {
StorageHubWrapper wrap = new StorageHubWrapper(context, authorizationToken);
return wrap.getWorkspace();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
*
* @param currentUsername
* @param context
* @return
*/
public static Workspace getWorkspace(String currentUsername, String context) {
String username = currentUsername;
String authorizationToken = PortalContext.getConfiguration().getCurrentUserToken(context, username);
SecurityTokenProvider.instance.set(authorizationToken);
ScopeProvider.instance.set(context);
try {
StorageHubWrapper wrap = new StorageHubWrapper(context, authorizationToken);
return wrap.getWorkspace();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
private String uploadToUserWorkspace(Workspace ownerWS, String fileName, String mimeType,InputStream fileData) throws Exception {
WorkspaceFolder attachment = null;
if (!ownerWS.exists(ATTACHMENT_FOLDER, ownerWS.getRoot().getId())) {
_log.info(ATTACHMENT_FOLDER + " Workspace Folder does not exists, creating it ");
attachment = ownerWS.createFolder(ATTACHMENT_FOLDER, "Folder created automatically by the System", ownerWS.getRoot().getId());
}
else {
attachment = (WorkspaceFolder) ownerWS.find(ATTACHMENT_FOLDER, ownerWS.getRoot().getId()).get(0);
}
WorkspaceItem item = ownerWS.uploadFile(attachment.getId(), fileData, fileName, "File created automatically by the System on " + new Date());
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 context = PortalContext.getConfiguration().getCurrentScope(""+groupId);
_log.info("sendNotificationToUser context: " + context);
String authorizationToken = PortalContext.getConfiguration().getCurrentUserToken(context, currentUser.getScreenName());
ScopeProvider.instance.set(context);
SecurityTokenProvider.instance.set(authorizationToken);
Workspace workspace = getWorkspace(currentUser.getScreenName(), context);
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");
}
MessageManagerClient client = AbstractPlugin.messages().build();
String messageId = client.sendMessage(recipientIds, subject, body, attachmentsList);
_log.info("Sending new VRE Request message notification to: " + recipientIds.toString());
NotificationsManager nm = new ApplicationNotificationsManager(new SocialNetworkingSite(request), context, 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 Exception
* @throws ItemNotFoundException
* @throws InternalErrorException
*/
private String getPublicLinksForAttachs(Workspace workspace, List<String> listAttachmentsId) throws ItemNotFoundException, InternalErrorException, Exception {
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.FILE_ITEM)) {
FolderItem folderItem = (FolderItem) workspaceItem;
String publicLink = "";
String itemName = "";
try {
itemName = workspaceItem.getName();
publicLink = workspace.getPublicLinkForFile(folderItem.getId()).toString();
}
catch (Exception 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 "";
}
}