moving-map-portlet/src/main/java/org/gcube/portlets/user/moving/CompileForm.java

346 lines
16 KiB
Java

package org.gcube.portlets.user.moving;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.http.HttpServletRequest;
import org.gcube.common.portal.GCubePortalConstants;
import org.gcube.common.portal.PortalContext;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.gcube.vomanagement.usermanagement.model.GatewayRolesNames;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class CompileForm
*/
public class CompileForm extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(CompileForm.class);
private static final String MANAGE_USERS_REQUESTS_FRIENDLY_URL = "/manage-expression-of-interest";
protected static final String MAIL_FROM = "MOVING Gateway <moving@d4science.org>";
private static final String MAIL_SUBJECT = "MOVING EU Multi-Actor Platform: email confirmation";
private static final String MAIL_SUBJECT_VRE_MANAGER = "MOVING EU Multi-Actor Platform: new form submission notification";
private static final String MAIL_BODY = "Dear Sir/Madam,\n"
+ "Thank you for expressing your interest to join the MOVING EU-level Multi-Actor Platform (MAP). The MOVING team will carefully review the information provided and assess the suitability of your involvement to form a dynamic and relevant community.\n"
+ "Please receive below a copy of the information submitted. \n"
+ "\n"
+ "Best regards,\n"
+ "MOVING team\n";
private static final String MAIL_BODY_VRE_MANAGER = "Dear MOVING EU-MAP Manager,\n"
+ "A new request to join the MOVING EU-level Multi-Actor Platform (MAP) has been submitted.\n"
+ "\nPlease manage this request:\n";
private String mailServiceHost = "localhost";
private String mailServicePort = "25";
@Override
public void render(RenderRequest renderRequest, RenderResponse renderResponse) {
Connection conn = null;
try {
conn = DatabaseConnection.getInstance("/"+PortalContext.getConfiguration().getInfrastructureName()).getConnection();
_log.info("Trying queries for getting combo values from DB");
List<String> organisation_types = getOrganisationTypes(conn);
List<String> main_motivations = getMainMotivations(conn);
List<String> areas_of_expertise = getAreasOfExpertise(conn);
List<String> degrees_of_participation = getDgreesOfParticipation(conn);
_log.info("Succesfully got combo values from DB, organisation_types found: " +organisation_types.size());
renderRequest.setAttribute("organisation_types", organisation_types);
renderRequest.setAttribute("main_motivations", main_motivations);
renderRequest.setAttribute("areas_of_expertise", areas_of_expertise);
renderRequest.setAttribute("degrees_of_participation", degrees_of_participation);
super.render(renderRequest, renderResponse);
} catch (Exception e) {
_log.error("Something wrong with Databaseconnection or with queries while getting combo types", e);
}
}
public void submittedForm(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException {
String name = actionRequest.getParameter("name");
String surname = actionRequest.getParameter("surname");
String organisation = actionRequest.getParameter("organisation");
String organisationType = actionRequest.getParameter("organisationType");
String emailAddress = actionRequest.getParameter("emailAddress");
String[] itemsAreaOfExpertiseSelectValues = actionRequest.getParameterValues("areaOfExpertiseSelect");
String areaOfExpertise = "";
for (int i = 0; i < itemsAreaOfExpertiseSelectValues.length; i++) {
areaOfExpertise += itemsAreaOfExpertiseSelectValues[i];
areaOfExpertise += "; ";
}
String country = actionRequest.getParameter("country");
String participatedInActivitiesString = (String) actionRequest.getParameter("participatedInActivities");
boolean participatedInActivities = Boolean.parseBoolean(participatedInActivitiesString);
String mainMotivation = actionRequest.getParameter("mainMotivation");
String textareaMotivation = actionRequest.getParameter("textareaMotivation");
String elaborated_expertise = actionRequest.getParameter("textareaExperience");
String degree_of_participation = actionRequest.getParameter("commitment");
_log.debug("name:" + name);
_log.debug("surname:" + surname);
_log.debug("organisation:" + organisation);
_log.debug("organisationType:" + organisationType);
_log.debug("email:" + emailAddress);
_log.debug("country:" + country);
_log.debug("participatedInActivities:" + participatedInActivities);
_log.debug("mainMotivation:" + mainMotivation);
_log.debug("textareaMotivation:\n" + textareaMotivation+"\n");
_log.debug("itemsAreaOfExpertise (Multi):\n");
for (int i = 0; i < itemsAreaOfExpertiseSelectValues.length; i++) {
_log.debug(itemsAreaOfExpertiseSelectValues[i]);
}
_log.debug("textareaExperience:\n" + elaborated_expertise+"\n");
_log.debug("degrees_of_participation: "+ degree_of_participation);
_log.info("Got form compiled, inserting in DB.");
try {
Connection conn = DatabaseConnection.getInstance("/"+PortalContext.getConfiguration().getInfrastructureName()).getConnection();
String insertTableSQL = "INSERT INTO forms(name, surname, organisation, organisation_type, email, "
+ "country, activities_participation, main_motivation, elaborated_motivation, area_of_expertise, "
+ "elaborated_expertise, degree_of_participation, data_management, datecreated, processed_form, user_accepted) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,current_timestamp,?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(insertTableSQL);
preparedStatement.setString(1, name);
preparedStatement.setString(2, surname);
preparedStatement.setString(3, organisation);
preparedStatement.setString(4, organisationType);
preparedStatement.setString(5, emailAddress);
preparedStatement.setString(6, country);
preparedStatement.setBoolean(7, participatedInActivities);
preparedStatement.setString(8, mainMotivation);
preparedStatement.setString(9, textareaMotivation);
preparedStatement.setString(10, areaOfExpertise);
preparedStatement.setString(11, elaborated_expertise);
preparedStatement.setString(12, degree_of_participation);
preparedStatement.setBoolean(13, true); //data_management
preparedStatement.setBoolean(14, false); //processed_form
preparedStatement.setBoolean(15, false); //user_accepted
// execute insert SQL stetement
preparedStatement .executeUpdate();
_log.info("Inserting in DB done, sending confirmation to user and notification to managers via email");
String copySubmitted = new StringBuffer("\n\n\nCOPY OF INFORMATION SUBMITTED\n\n")
.append("\n").append("Name: ")
.append(name).append(" ").append(surname)
.append("\n").append("Organisation: ")
.append(organisation)
.append("\n").append("Organisation type: ")
.append(organisationType)
.append("\n").append("emailAddress: ")
.append("*** hidden on purpose ***")
.append("\n").append("Country: ")
.append(country)
.append("\n\n").append("Have you participated in the activities of any of our MOVING Regional Multi-Actors Platforms? ")
.append(participatedInActivities)
.append("\n\n").append("What is your main motivation for joining the EU MAP of MOVING? ")
.append(mainMotivation)
.append("\n\n").append("Please elaborate on your motivation expressed above so that we understand better your interest, and form a dynamic and relevant community. Vague explanations of the motivation might not be taken into consideration. ")
.append("\n\n").append(textareaMotivation).append("\n")
.append("\n\n").append("What is your main area of expertise in relation to mountain sustainability and resilience? (Multiple choice): ")
.append(areaOfExpertise)
.append("\n\n").append("Please elaborate on the relevant experience you can bring to mountain value chains and the resilience of these areas, so that we have more detailed information to be able to form a dynamic and relevant community: ")
.append("\n\n").append(elaborated_expertise)
.append("\n\n").append("As a starting point, the degree of participation you commit to is: ")
.append(degree_of_participation)
.append("\n").append("\n").append("Data Management: ")
.append("Agreed")
.append("\n\nEND COPY OF INFORMATION SUBMITTED\n\n").toString();
Properties props = System.getProperties();
Session session = null;
props.put("mail.smtp.host", mailServiceHost);
props.put("mail.smtp.port", mailServicePort);
//use localhost (probaly postfix instance)
session = Session.getDefaultInstance(props);
sendEmailConfirmationToUser(props, session, emailAddress, copySubmitted);
String groupIdVREforManagers = GetterUtil.getString(actionRequest.getPreferences().getValue("VREGroupId", StringPool.BLANK));
if (groupIdVREforManagers != null && groupIdVREforManagers.compareTo("") != 0) {
HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(actionRequest);
sendEmailNotificationToVREManagers(httpRequest, props, session, groupIdVREforManagers, copySubmitted);
}
else {
_log.warn("WARNING, non config found for groupId, no email will be send to VRE Managers");
}
} catch (Exception e) {
_log.error("Some error while trying to insert form");
e.printStackTrace();
}
}
/**
*
* @param props
* @param session
* @param emailadress
* @throws AddressException
* @throws MessagingException
*/
private void sendEmailConfirmationToUser(Properties props, Session session, String emailadress, String copySubmitted) throws AddressException, MessagingException {
_log.info("Sending confirmation to user");
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(MAIL_FROM));
message.setRecipients(
Message.RecipientType.TO, InternetAddress.parse(emailadress));
message.setSubject(MAIL_SUBJECT);
message.setText(MAIL_BODY+copySubmitted);
// Send message
Transport.send(message);
_log.info("Sending confirmation email done");
}
/**
*
* @param props
* @param session
* @param groupId the groupid of the VRE where to find the managers to alert
* @throws MessagingException
* @throws AddressException
* @throws SystemException
* @throws PortalException
*/
private void sendEmailNotificationToVREManagers(HttpServletRequest httprequest , Properties props, Session session, String groupIdString, String copySubmitted) throws AddressException, MessagingException, PortalException, SystemException {
_log.info("Sending notification email to VRE-Managers");
long groupId = Long.parseLong(groupIdString);
List<String> vreManagersEmails = getAdministratorsEmails(groupId);
for (String emailadress : vreManagersEmails) {
_log.info("Sending notificsation to user");
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(MAIL_FROM));
message.setRecipients(
Message.RecipientType.TO, InternetAddress.parse(emailadress));
message.setSubject(MAIL_SUBJECT_VRE_MANAGER);
String vreName = GroupLocalServiceUtil.getGroup(groupId).getName();
String gatewayURL = PortalContext.getConfiguration().getGatewayURL(httprequest);
String manageRequestURL = new StringBuffer(gatewayURL)
.append(GCubePortalConstants.PREFIX_GROUP_URL)
.append("/").append(vreName.toLowerCase())
.append(MANAGE_USERS_REQUESTS_FRIENDLY_URL).toString();
message.setText(MAIL_BODY_VRE_MANAGER+manageRequestURL+copySubmitted);
// Send message
Transport.send(message);
_log.info("Sending notification email to VRE-Managers done");
}
}
/**
*
* @param groupId the VRE group id
* @return the VRE Managers emails of the VRE groupid passed in the parameter
*/
private static List<String> getAdministratorsEmails(long groupId) {
_log.debug("getAdministratorsEmails");
LiferayUserManager userManager = new LiferayUserManager();
Map<GCubeUser, List<GCubeRole>> usersAndRoles = null;
try {
usersAndRoles = userManager.listUsersAndRolesByGroup(groupId);
} catch (Exception e) {
e.printStackTrace();
}
Set<GCubeUser> users = usersAndRoles.keySet();
ArrayList<String> adminEmailsList = new ArrayList<String>();
for (GCubeUser usr:users) {
List<GCubeRole> roles = usersAndRoles.get(usr);
for (int i = 0; i < roles.size(); i++) {
if (roles.get(i).getRoleName().equals(GatewayRolesNames.VRE_MANAGER.getRoleName())) {
adminEmailsList.add(usr.getEmail());
_log.debug("Manager: " + usr.getFullname());
break;
}
}
}
return adminEmailsList;
}
private static List<String> getOrganisationTypes(Connection conn) throws Exception {
_log.debug("getting organisation_types ");
List<String> toReturn = new ArrayList<>();
String selectSQL = "SELECT * FROM organisation_types";
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
String toAdd = rs.getString("combo_value");
_log.debug("Adding organisation_types" + toAdd);
toReturn.add(toAdd);
}
return toReturn;
}
private static List<String> getMainMotivations(Connection conn) throws Exception {
_log.debug("getting main_motivations ");
List<String> toReturn = new ArrayList<>();
String selectSQL = "SELECT * FROM main_motivations";
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
String toAdd = rs.getString("combo_value");
_log.debug("Adding main_motivations" + toAdd);
toReturn.add(toAdd);
}
return toReturn;
}
private static List<String> getAreasOfExpertise(Connection conn) throws Exception {
_log.debug("getting areas_of_expertise ");
List<String> toReturn = new ArrayList<>();
String selectSQL = "SELECT * FROM areas_of_expertise";
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
String toAdd = rs.getString("combo_value");
_log.debug("Adding areas_of_expertise" + toAdd);
toReturn.add(toAdd);
}
return toReturn;
}
private static List<String> getDgreesOfParticipation(Connection conn) throws Exception {
_log.debug("getting degrees_of_participation ");
List<String> toReturn = new ArrayList<>();
String selectSQL = "SELECT * FROM degrees_of_participation";
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
String toAdd = rs.getString("combo_value");
_log.debug("Adding degrees_of_participation" + toAdd);
toReturn.add(toAdd);
}
return toReturn;
}
}