Massimiliano Assante 5 years ago
parent e0ef35a8a7
commit f1a1063383

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>PerformFISH-Apps</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>com.liferay.ide.core.liferayNature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>
</projectDescription>

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/webapp"/>
<classpathentry excluding="**/bower_components/*|**/node_modules/*|**/*.min.js" kind="src" path="target/m2e-wtp/web-resources"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.WebProject">
<attributes>
<attribute name="hide" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
<classpathentry kind="output" path=""/>
</classpath>

@ -0,0 +1,5 @@
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/main/resources=UTF-8
encoding//src/test/java=UTF-8
encoding/<project>=UTF-8

@ -0,0 +1,14 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8

@ -0,0 +1,3 @@
eclipse.preferences.version=1
validateFragments=false
validation.use-project-settings=true

@ -0,0 +1,4 @@
activeProfiles=Liferay-v6.2-CE-(Tomcat-7)-(2)
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="PerformFISH-Apps-portlet">
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<property name="java-output-path" value="/PerformFISH-Apps/target/classes"/>
<property name="context-root" value="PerformFISH-Apps-portlet"/>
</wb-module>
</project-modules>

@ -0,0 +1,7 @@
<root>
<facet id="jst.jaxrs">
<node name="libprov">
<attribute name="provider-id" value="jaxrs-no-op-library-provider"/>
</node>
</facet>
</root>

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="wst.jsdt.web"/>
<installed facet="jst.web" version="2.5"/>
<installed facet="liferay.portlet" version="6.0"/>
<installed facet="wst.jsdt.web" version="1.0"/>
<installed facet="jst.jaxrs" version="2.0"/>
<installed facet="java" version="1.8"/>
</faceted-project>

@ -0,0 +1 @@
org.eclipse.wst.jsdt.launching.baseBrowserLibrary

@ -0,0 +1,2 @@
disabled=06target
eclipse.preferences.version=1

@ -0,0 +1,23 @@
{
"plugins": {
"guess-types": {
},
"outline": {
},
"liferay": {
},
"yui3": {
},
"aui2.0.x": {
}
},
"libs": [
"ecma5",
"browser"
]
}

@ -0,0 +1 @@
${gcube.license}

@ -0,0 +1,62 @@
The gCube System - ${name}
--------------------------------------------------
${description}
${gcube.description}
${gcube.funding}
Version
--------------------------------------------------
${version} (${buildDate})
Please see the file named "changelog.xml" in this directory for the release notes.
Authors
--------------------------------------------------
* Massimiliano Assante (massimiliano.assante@isti.cnr.it), Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo" - CNR, Pisa (Italy).
Maintainers
-----------
* Massimiliano Assante (massimiliano.assante@isti.cnr.it), Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo" - CNR, Pisa (Italy).
Download information
--------------------------------------------------
Source code is available from SVN:
${scm.url}
Binaries can be downloaded from the gCube website:
${gcube.website}
Installation
--------------------------------------------------
Installation documentation is available on-line in the gCube Wiki:
${gcube.wikiRoot}
Documentation
--------------------------------------------------
Documentation is available on-line in the gCube Wiki:
${gcube.wikiRoot}
Support
--------------------------------------------------
Bugs and support requests can be reported in the gCube issue tracking tool:
${gcube.issueTracking}
Licensing
--------------------------------------------------
This software is licensed under the terms you may find in the file named "LICENSE" in this directory.

@ -0,0 +1,10 @@
<ReleaseNotes>
<Changeset component="org.gcube.portlets.user.performfish.PerformFISH-Apps.1-2-0"
date="2018-12-18">
<Change>UUID Field Valorisation upon new Association, Company and Farms creation</Change>
</Changeset>
<Changeset component="org.gcube.portlets.user.performfish.PerformFISH-Apps.1-1-0"
date="2018-10-10">
<Change>First Release</Change>
</Changeset>
</ReleaseNotes>

@ -0,0 +1,31 @@
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>servicearchive</id>
<formats>
<format>tar.gz</format>
</formats>
<baseDirectory>/</baseDirectory>
<fileSets>
<fileSet>
<directory>${distroDirectory}</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<includes>
<include>README</include>
<include>LICENSE</include>
<include>changelog.xml</include>
<include>profile.xml</include>
</includes>
<fileMode>755</fileMode>
<filtered>true</filtered>
</fileSet>
</fileSets>
<files>
<file>
<source>target/${build.finalName}.${project.packaging}</source>
<outputDirectory>/${artifactId}</outputDirectory>
</file>
</files>
</assembly>

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<Resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ID></ID>
<Type>Service</Type>
<Profile>
<Description>${Description}</Description>
<Class>PortletUser</Class>
<Name>${artifactId}</Name>
<Version>${version}</Version>
<Packages>
<Software>
<Name>${artifactId}</Name>
<Version>${version}</Version>
<MavenCoordinates>
<groupId>${groupId}</groupId>
<artifactId>${artifactId}</artifactId>
<version>${version}</version>
</MavenCoordinates>
<Files>
<File>target/${build.finalName}.war</File>
</Files>
</Software>
</Packages>
</Profile>
</Resource>

@ -0,0 +1,239 @@
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>maven-parent</artifactId>
<groupId>org.gcube.tools</groupId>
<version>1.0.0</version>
<relativePath />
</parent>
<groupId>org.gcube.portlets.user.performfish</groupId>
<artifactId>PerformFISH-Apps-portlet</artifactId>
<packaging>war</packaging>
<name>PerformFISH-Apps Portlet</name>
<version>1.3.0-SNAPSHOT</version>
<description>
PerformFISH Apps is a set of portlet for the implementation of the Form Submission useful to calculate KPIs
</description>
<scm>
<connection>scm:svn:http://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/user/${project.artifactId}</connection>
<developerConnection>scm:https://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/user/${project.artifactId}</developerConnection>
<url>http://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/user/${project.artifactId}</url>
</scm>
<profiles>
<profile>
<id>Liferay-v6.2-CE-(Tomcat-7)-(2)</id>
<properties>
<distroDirectory>distro</distroDirectory>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<liferay.version>6.2.5</liferay.version>
<liferay.maven.plugin.version>6.2.10.12</liferay.maven.plugin.version>
<liferay.auto.deploy.dir>/Users/massi/portal/liferay-portal-6.2-ce-ga6/deploy</liferay.auto.deploy.dir>
<liferay.app.server.deploy.dir>/Users/massi/portal/liferay-portal-6.2-ce-ga6/tomcat-7.0.62/webapps</liferay.app.server.deploy.dir>
<liferay.app.server.lib.global.dir>/Users/massi/portal/liferay-portal-6.2-ce-ga6/tomcat-7.0.62/lib/ext</liferay.app.server.lib.global.dir>
<liferay.app.server.portal.dir>/Users/massi/portal/liferay-portal-6.2-ce-ga6/tomcat-7.0.62/webapps/ROOT</liferay.app.server.portal.dir>
</properties>
</profile>
</profiles>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>maven-portal-bom</artifactId>
<version>LATEST</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.resources.discovery</groupId>
<artifactId>ic-client</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.resources</groupId>
<artifactId>registry-publisher</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.gcube.portal</groupId>
<artifactId>storagehub-icons-library</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.dvos</groupId>
<artifactId>usermanagement-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.portal</groupId>
<artifactId>storagehub-icons-library</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.common.portal</groupId>
<artifactId>portal-manager</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>storagehub-client-library</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-scope-maps</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>home-library</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>home-library-jcr</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>home-library-model</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-client</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>common-authorization</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1102-jdbc41</version>
</dependency>
<dependency>
<groupId>com.liferay.portal</groupId>
<artifactId>portal-service</artifactId>
<version>${liferay.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.liferay.portal</groupId>
<artifactId>util-bridges</artifactId>
<version>${liferay.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.liferay.portal</groupId>
<artifactId>util-taglib</artifactId>
<version>${liferay.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.liferay.portal</groupId>
<artifactId>util-java</artifactId>
<version>${liferay.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.portlet</groupId>
<artifactId>portlet-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>com.liferay.maven.plugins</groupId>
<artifactId>liferay-maven-plugin</artifactId>
<version>${liferay.maven.plugin.version}</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>build-css</goal>
</goals>
</execution>
</executions>
<configuration>
<autoDeployDir>${liferay.auto.deploy.dir}</autoDeployDir>
<appServerDeployDir>${liferay.app.server.deploy.dir}</appServerDeployDir>
<appServerLibGlobalDir>${liferay.app.server.lib.global.dir}</appServerLibGlobalDir>
<appServerPortalDir>${liferay.app.server.portal.dir}</appServerPortalDir>
<liferayVersion>${liferay.version}</liferayVersion>
<pluginType>portlet</pluginType>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5</version>
<configuration>
<encoding>UTF-8</encoding>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- SA Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2</version>
<configuration>
<descriptors>
<descriptor>${distroDirectory}/descriptor.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>servicearchive</id>
<phase>install</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,152 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.gcube.portlets.user.performfish.bean.Association;
import org.gcube.portlets.user.performfish.bean.Company;
import org.gcube.portlets.user.performfish.bean.Farm;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.portlets.user.performfish.util.db.DBUtil;
import org.gcube.portlets.user.performfish.util.db.DatabaseConnection;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class AddNewCompanyOrAssociation
*/
public class AddNewCompanyOrAssociation extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(AssociateUsersToCompany.class);
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.info(" This is render method of AddNewCompanyOrAssociation");
try {
long groupId = PortalUtil.getScopeGroupId(request);
String vreName = GroupLocalServiceUtil.getGroup(groupId).getName();
request.setAttribute("vreName", vreName);
List<GCubeTeam> allTeams = getAllTeams(request);
List<GCubeTeam> availableTeams = new ArrayList<>();
Connection conn = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
List<Company> companies = DBUtil.getCompanies(conn);
List<Farm> farms = DBUtil.getAllFarms(conn);
List<Association> associations = DBUtil.getAllAssociations(conn);
for (GCubeTeam gCubeTeam : allTeams) {
boolean found = false;
for (Company c : companies) {
if (gCubeTeam.getTeamId() == c.getCompanyId()) {
found = true;
break;
}
}
for (Farm f : farms) {
if (gCubeTeam.getTeamId() == f.getFarmId()) {
found = true;
break;
}
}
for (Association a : associations) {
if (gCubeTeam.getTeamId() == a.getAssociationId()) {
found = true;
break;
}
}
if (!found)
availableTeams.add(gCubeTeam);
}
request.setAttribute("availableTeams", availableTeams);
super.render(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
private List<GCubeTeam> getAllTeams(RenderRequest request) throws Exception {
long groupId = PortalUtil.getScopeGroupId(request);
RoleManager rm = new LiferayRoleManager();
return rm.listTeamsByGroup(groupId);
}
/**
*
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void makeCompanies(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
_log.info("makeCompanies action request ...");
long groupId = ParamUtil.getLong(actionRequest, "groupId");
Connection conn = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
try {
String[] companyIdsToAdd = ParamUtil.getParameterValues(actionRequest, "selectedTeamIds");
String currentUsername = ParamUtil.getString(actionRequest, "currentUsername", "unknown");
if (companyIdsToAdd.length > 0) {
_log.info("associateCompanies writing to DB now ...");
boolean result = DBUtil.addCompany(conn, companyIdsToAdd, currentUsername);
if (!result) {
SessionErrors.add(actionRequest.getPortletSession(), "operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
}
}
else {
SessionErrors.add(actionRequest.getPortletSession(), "operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
}
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
/**
*
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void makeAssociations(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
_log.info("makeAssociations action request ...");
long groupId = ParamUtil.getLong(actionRequest, "groupId");
Connection conn = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
try {
String[] associationsIdsToAdd = ParamUtil.getParameterValues(actionRequest, "selectedTeamIds");
String currentUsername = ParamUtil.getString(actionRequest, "currentUsername", "unknown");
if (associationsIdsToAdd.length > 0) {
_log.info("associateCompanies writing to DB now ...");
boolean result = DBUtil.addAssociation(conn, associationsIdsToAdd, currentUsername);
if (!result) {
SessionErrors.add(actionRequest.getPortletSession(), "operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
}
}
else {
SessionErrors.add(actionRequest.getPortletSession(), "operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
}
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
}

@ -0,0 +1,102 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;
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.portlets.user.performfish.bean.Company;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.portlets.user.performfish.util.db.DBUtil;
import org.gcube.portlets.user.performfish.util.db.DatabaseConnection;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.model.Team;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class AssociateCompaniesToAssociation
*/
public class AssociateCompaniesToAssociation extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(AssociateCompaniesToAssociation.class);
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.info(" This is render method of AssociateCompaniesToAssociation");
try {
long groupId = PortalUtil.getScopeGroupId(request);
HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
long[] associationIds = ParamUtil.getLongValues(httpReq, "associationId");
if (associationIds.length > 0) { //super user mode
String vreName = GroupLocalServiceUtil.getGroup(groupId).getName();
Connection conn = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
List<Company> companies = DBUtil.listCompaniesNotAssociatedToAssociations(conn);
for (Company company : companies) {
company.setName(TeamLocalServiceUtil.getTeam(company.getCompanyId()).getName());
company.setImageUrl(Utils.getCompanyLogoURL(company.getName(), groupId, request));
}
Team theAssociation = TeamLocalServiceUtil.getTeam(associationIds[0]);
request.setAttribute("companies", companies);
request.setAttribute("selectedAssociation", theAssociation);
request.setAttribute("vreName", vreName);
request.setAttribute("operationFinished", false);
} else {
request.setAttribute("operationFinished", true);
super.render(request, response);
}
super.render(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void associateCompanies(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
String currentUsername = ParamUtil.getString(actionRequest, "currentUsername", "unknown");
_log.info("associateCompanies action request from " + currentUsername);
long groupId = ParamUtil.getLong(actionRequest, "groupId");
long selectedAssociationId = ParamUtil.getLong(actionRequest, "selectedAssociationId");
Connection conn = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
try {
long[] companyIdsToAssociate = ParamUtil.getLongValues(actionRequest, "associateCompanyIds");
if (companyIdsToAssociate.length > 0) {
_log.info("associateCompanyIds writing to DB now ... \nselectedAssociationId="+selectedAssociationId+"\n companyIdsToAssociate="+companyIdsToAssociate.toString());
boolean result = DBUtil.associateCompaniesToAssociation(conn, selectedAssociationId, companyIdsToAssociate);
if (!result) {
SessionErrors.add(actionRequest.getPortletSession(), "operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
}
}
else {
SessionErrors.add(actionRequest.getPortletSession(), "operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
}
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
}

@ -0,0 +1,126 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder;
import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder;
import org.gcube.common.homelibrary.home.workspace.accessmanager.ACLType;
import org.gcube.portlets.user.performfish.bean.CompanyMember;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.portlets.user.performfish.util.comparators.CompanyMemberComparator;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.cache.MultiVMPoolUtil;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.webcache.WebCachePoolUtil;
import com.liferay.portal.model.Team;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class AssociateUsersToCompany
*/
public class AssociateUsersToCompany extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(AssociateUsersToCompany.class);
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.info(" This is render method of AssociateUsersToCompany");
try {
long groupId = PortalUtil.getScopeGroupId(request);
GCubeTeam theTeam = Utils.checkBelongingToOneCompanyOnly(request, response, this);
request.setAttribute("theTeam", TeamLocalServiceUtil.getTeam(theTeam.getTeamId()));
if (theTeam == null || !Utils.isCompanyAdmin(Utils.getCurrentUser(request), groupId, theTeam)) { //check is Admin
_log.error("Some error occurred");
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_ADMIN_PAGE_PATH);
dispatcher.include(request, response);
} else {
List<CompanyMember> companyMembers = Utils.getRegularCompanyMembers(theTeam.getTeamId(), theTeam.getGroupId());
Collections.sort(companyMembers, new CompanyMemberComparator());
request.setAttribute("companyMembers", companyMembers); //pass to the JSP
String imageUrl = Utils.getCompanyLogoURL(theTeam.getTeamName(), groupId, request);
request.setAttribute("companyLogoURL", imageUrl); //pass to logo URL to the JSP
super.render(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void associateCompanyUsers(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
try {
String[] usernamesToAssociateToCompany = ParamUtil.getParameterValues(actionRequest, "addUserIds");
long teamId = ParamUtil.getLong(actionRequest, "teamId");
String currentUsername = ParamUtil.getString(actionRequest, "currentUsername");
long currentGroupId = ParamUtil.getLong(actionRequest, "currentGroupId");
String context = Utils.getCurrentContext(currentGroupId);
_log.info(currentUsername + " has requested the association of some user(s) to the company having id="+teamId + " in context="+context);
LiferayRoleManager rm = new LiferayRoleManager();
LiferayUserManager um = new LiferayUserManager();
GCubeTeam team = rm.getTeam(teamId);
WorkspaceFolder wsFolder = Utils.getWSCompanyFolder(currentUsername, context, team);
if (wsFolder.isShared()) {
WorkspaceSharedFolder sharedFolder = (WorkspaceSharedFolder) wsFolder;
List<String> usersToShareWith = Arrays.asList(usernamesToAssociateToCompany);
_log.info("Sharing with users =>"+usersToShareWith.toString());
sharedFolder.share(usersToShareWith);
sharedFolder.setACL(usersToShareWith, ACLType.WRITE_ALL);
for (int i = 0; i < usernamesToAssociateToCompany.length; i++) {
_log.info("sharing OK associateing user to team =>"+usernamesToAssociateToCompany[i]);
long userId = um.getUserByUsername(usernamesToAssociateToCompany[i]).getUserId();
List<Team> currentTeams = TeamLocalServiceUtil.getUserTeams(userId, currentGroupId);
long[] teamIds = null;
if (currentTeams != null && !currentTeams.isEmpty()) {
teamIds = new long[currentTeams.size()+1];
int j = 0;
for (Team t : currentTeams) {
teamIds[j] = t.getTeamId();
j++;
}
teamIds[j] = teamId;
TeamLocalServiceUtil.setUserTeams(userId, teamIds);
} else {
teamIds = new long[1];
teamIds[0] = teamId;
TeamLocalServiceUtil.setUserTeams(userId, teamIds);
}
CacheRegistryUtil.clear();
MultiVMPoolUtil.clear();
WebCachePoolUtil.clear();
_log.info("added user to team Done");
}
}
else {
SessionErrors.add(actionRequest.getPortletSession(), "operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
}
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
}

@ -0,0 +1,110 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.http.HttpServletRequest;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.portlets.user.performfish.util.comparators.UserComparator;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.cache.MultiVMPoolUtil;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.webcache.WebCachePoolUtil;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class AssociateUsersToFarm
*/
public class AssociateUsersToFarm extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(AssociateUsersToFarm.class);
private static RoleManager RM = new LiferayRoleManager();
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.info(" This is render method of AssociateUsersToFarm");
try {
long groupId = PortalUtil.getScopeGroupId(request);
GCubeTeam theCompany = Utils.checkBelongingToOneCompanyOnly(request, response, this);
HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
String[] farmIds = ParamUtil.getParameterValues(httpReq, Utils.ENCODED_FARM_PARAM);
GCubeTeam theFarm = null;
if (farmIds != null && farmIds.length > 0) {
long selectedFarmId = Utils.unmaskId(farmIds[0]);
theFarm = RM.getTeam(selectedFarmId);
request.getPortletSession().setAttribute("theFarm", theFarm);
} else {
theFarm = (GCubeTeam) request.getPortletSession().getAttribute("theFarm");
}
request.setAttribute("theTeam", TeamLocalServiceUtil.getTeam(theFarm.getTeamId()));
if (theFarm == null || !Utils.isFarmAdmin(Utils.getCurrentUser(request), groupId, theFarm)) { //check is Admin
_log.error("Some error occurred");
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_FARM_ADMIN_PAGE_PATH);
dispatcher.include(request, response);
} else {
List<GCubeUser> nonFarmMembers = Utils.getAvailableFarmMembersToAssociate(theFarm.getTeamId(), theCompany.getTeamId(), theCompany.getGroupId());
Collections.sort(nonFarmMembers, new UserComparator());
request.setAttribute("nonFarmMembers", nonFarmMembers); //pass to the JSP
String imageUrl = Utils.getCompanyLogoURL(theCompany.getTeamName(), groupId, request);
request.setAttribute("companyLogoURL", imageUrl); //pass to logo URL to the JSP
super.render(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
//TODO: yiou have to manage the workspace folder still ...
public void associateFarmUsers(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
try {
String[] usernamesToAssociateToFarm = ParamUtil.getParameterValues(actionRequest, "addUserIds");
long teamId = ParamUtil.getLong(actionRequest, "teamId");
String currentUsername = ParamUtil.getString(actionRequest, "currentUsername");
long currentGroupId = ParamUtil.getLong(actionRequest, "currentGroupId");
String context = Utils.getCurrentContext(currentGroupId);
_log.info(currentUsername + " has requested the association of some user(s) to the farm having id="+teamId + " in context="+context);
LiferayRoleManager rm = new LiferayRoleManager();
LiferayUserManager um = new LiferayUserManager();
for (int i = 0; i < usernamesToAssociateToFarm.length; i++) {
_log.info("sharing OK associating user to team =>"+usernamesToAssociateToFarm[i]);
long userId = um.getUserByUsername(usernamesToAssociateToFarm[i]).getUserId();
rm.assignTeamToUser(userId, teamId);
_log.info("added user to farm Done");
CacheRegistryUtil.clear();
MultiVMPoolUtil.clear();
WebCachePoolUtil.clear();
}
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
}

@ -0,0 +1,71 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.gcube.portlets.user.performfish.bean.Company;
import org.gcube.portlets.user.performfish.bean.Farm;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.portlets.user.performfish.util.db.DBUtil;
import org.gcube.portlets.user.performfish.util.db.DatabaseConnection;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.model.Team;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class AssociationDashboard
*/
public class AssociationDashboard extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(AssociationDashboard.class);
@Override
public void render(RenderRequest request, RenderResponse response) throws PortletException, IOException {
try {
long groupId = PortalUtil.getScopeGroupId(request);
GCubeTeam theAsso = Utils.checkBelongingToOneAssociationOnly(request, response, this);
request.setAttribute("theAssociation", theAsso);
if (theAsso != null) {
Connection conn = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
_log.debug("Association name =" + theAsso.getTeamName());
String imageUrl = Utils.getCompanyLogoURL(theAsso.getTeamName(), groupId, request);
request.setAttribute("associationLogoURL", imageUrl); //pass to logo URL to the JSP
_log.debug("Featching companies and farms =" + theAsso.getTeamName());
LinkedHashMap<Company, List<Farm>> associationCompanies = new LinkedHashMap<>();
List<Long> companIds = DBUtil.getCompaniesIdsByAssociation(conn, theAsso.getTeamId());
for (Long companId : companIds) {
Team theCompany = TeamLocalServiceUtil.getTeam(companId);
Company toPut = new Company(companId, theAsso.getTeamId(), false);
toPut.setName(theCompany.getName());
toPut.setImageUrl(Utils.getCompanyLogoURL(theCompany.getName(), groupId, request));
List<Farm> companyFarms = DBUtil.listFarmsByCompanyId(conn, companId);
for (Farm farm : companyFarms) {
String farmName = TeamLocalServiceUtil.getTeam(farm.getFarmId()).getName();
farm.setName(farmName);
}
associationCompanies.put(toPut, companyFarms);
request.setAttribute("associationCompanies", associationCompanies);
}
//display the view.jsp
super.render(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,482 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.WindowState;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.homelibary.model.versioning.WorkspaceVersion;
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.folder.items.ExternalFile;
import org.gcube.common.storagehub.client.StreamDescriptor;
import org.gcube.common.storagehub.client.dsl.StorageHubClient;
import org.gcube.common.storagehub.client.plugins.AbstractPlugin;
import org.gcube.common.storagehub.client.proxies.ItemManagerClient;
import org.gcube.common.storagehub.model.items.Item;
import org.gcube.common.storagehub.model.service.Version;
import org.gcube.portlets.user.performfish.bean.PublishAnonymisedJob;
import org.gcube.portlets.user.performfish.bean.SubmittedForm;
import org.gcube.portlets.user.performfish.util.ImportedBatchChecker;
import org.gcube.portlets.user.performfish.util.PFISHConstants;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.portlets.user.performfish.util.comparators.WSItemComparator;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.ServletResponseUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
*
* @author M. Assante CNR-ISTI
*/
public class CompanyFarmRepository extends MVCPortlet {
public static final String PHASE_PREFERENCE_ATTR_NAME = "phase";
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(CompanyFarmRepository.class);
private static RoleManager RM = new LiferayRoleManager();
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.info(" This is render method of CompanyFarmRepository");
try {
GCubeTeam theFarm = null;
HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
String[] farmIds = ParamUtil.getParameterValues(httpReq, Utils.ENCODED_FARM_PARAM);
String selectedItemId = (String) request.getAttribute("itemId");
if (selectedItemId == null) {//this handles when show version is clicked
if (farmIds == null || farmIds.length == 0) {
List<GCubeTeam> theFarms = Utils.getUserFarms(request, response, this); //if pass here only one farm is returned otherswise ir renders Utils.SELECT_FARM_PAGE_PATH
if (theFarms != null && ! theFarms.isEmpty()) {
theFarm = theFarms.get(0);
request.setAttribute("theFarm", theFarms.get(0)); //pass to the JSP
}
}
else { //the farmId is passed via param on the query string
long selectedFarmId = Utils.unmaskId(farmIds[0]);
theFarm = RM.getTeam(selectedFarmId);
if ( Utils.checkBelongsToTeam(PortalUtil.getUserId(request), theFarm.getTeamId(), PortalUtil.getScopeGroupId(request)) ) //check that the user belong ot the farm
request.setAttribute("theFarm", theFarm); //pass to the JSP
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_BELONGING_ANY_FARM_PAGE_PATH);
dispatcher.include(request, response);
}
}
_log.info(" initialise of CompanyFarmRepository Page done");
long groupId = PortalUtil.getScopeGroupId(request);
GCubeTeam theCompany = Utils.checkBelongingToOneCompanyOnly(request, response, this);
request.setAttribute("theCompany", theCompany);
String context = Utils.getCurrentContext(request);
String username = Utils.getCurrentUser(request).getUsername();
if (theFarm != null ) {
//check folder exists
WorkspaceFolder sharedFolder = Utils.getWSFarmFolder(
username,
context,
theCompany, theFarm);
List<WorkspaceItem> companyFiles = sharedFolder.getChildren(true);
Collections.sort(companyFiles, new WSItemComparator());
List<ExternalFile> filteredFiles = new ArrayList<>();
PortletPreferences portletPreferences = request.getPreferences();
String selectedPhase = GetterUtil.getString(portletPreferences.getValue(PHASE_PREFERENCE_ATTR_NAME, StringPool.BLANK));
_log.debug("selectedPhase: "+selectedPhase);
String adjustedPhaseName = selectedPhase;
if (selectedPhase.compareTo("Pre") == 0)
adjustedPhaseName = "Pre-grow";
if (selectedPhase.compareTo(PFISHConstants.SHOW_ALL_PHASES) != 0) {
for (WorkspaceItem workspaceItem : companyFiles) {
if (workspaceItem.getName().contains(adjustedPhaseName) ||
((selectedPhase.compareTo("Grow") == 0) && workspaceItem.getName().contains("Farm Data")) ) {
if (workspaceItem instanceof ExternalFile) {
ExternalFile file = (ExternalFile) workspaceItem;
filteredFiles.add(file);
}
}
}
}
else {
for (WorkspaceItem workspaceItem : companyFiles) {
if (workspaceItem instanceof ExternalFile) {
ExternalFile file = (ExternalFile) workspaceItem;
filteredFiles.add(file);
}
}
}
//TODO
List<SubmittedForm> submittedFormsWithPublishStatus= getSubmittedFormPublishAndAnonimStatus(request, context, theFarm.getTeamId(), filteredFiles);
request.setAttribute("submittedFormsWithPublishStatus", submittedFormsWithPublishStatus); //pass to the JSP
String imageUrl = Utils.getCompanyLogoURL(theCompany.getTeamName(), groupId, request);
request.setAttribute("companyLogoURL", imageUrl); //pass to logo URL to the JSP
}
}
super.render(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
private List<SubmittedForm> getSubmittedFormPublishAndAnonimStatus(RenderRequest renderRequest, String context, long farmId, List<ExternalFile> filteredFiles) throws Exception {
List<SubmittedForm> toReturn = new ArrayList<>();
String authorizationToken = "";
try {
authorizationToken = Utils.getCurrentUserToken(context, Utils.getCurrentUser(renderRequest).getUsername());
} catch (Exception e) {
_log.error("Cannot get user token");
}
String analyticalToolkitServiceURL = Utils.getAnalyticalToolkitEndpoint(context) ;
SecurityTokenProvider.instance.set(authorizationToken);
StringBuilder sb = new StringBuilder(analyticalToolkitServiceURL)
.append("/import/")
.append(farmId).append("?gcube-token="+authorizationToken);
String request = sb.toString();
fixUntrustCertificate() ;
URL url= new URL(request);
HttpsURLConnection conn= (HttpsURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "GET" );
conn.setRequestProperty( "Content-Type", "application/json");
conn.setRequestProperty( "charset", "utf-8");
conn.setUseCaches( false );
InputStream in = conn.getInputStream();
String encoding = conn.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
JSONArray jsArray = JSONFactoryUtil.createJSONArray(body);
Map<String, PublishAnonymisedJob> jobs = new HashMap<>();
System.out.println("*** Processing list, no of items = "+jsArray.length());
for (int i = 0; i < jsArray.length(); i++) {
JSONObject cData = jsArray.getJSONObject(i);
PublishAnonymisedJob toPut = new PublishAnonymisedJob(cData);
String sourceUrl = toPut.getSourceUrl(); //theKey
if (jobs.containsKey(sourceUrl)) {
PublishAnonymisedJob toCompare = jobs.get(sourceUrl);
if (toPut.getEndTimeEpochSecond() > toCompare.getEndTimeEpochSecond()) { //if the current (toPut) is more recent than the one in the map (toCompare) we replace it
jobs.put(sourceUrl, toPut);
}
}
else
jobs.put(sourceUrl, new PublishAnonymisedJob(cData));
}
/*here we have the list of the most recent jobs per type (GROW_OUT_INDIVIDUAL, PRE_ONGROWING etc)
* with their STATUS (COMPLETE, FAILED, IN PROGRESS)
*
*/
_log.debug("*** List Processed, no of items = "+jobs.keySet().size());
for (String key : jobs.keySet()) {
System.out.println(jobs.get(key));
}
//
StorageHubClient shub = new StorageHubClient();
for (ExternalFile externalFile : filteredFiles) {
String publicURL = shub.open(externalFile.getId()).asFile().getPublicLink().toString();
PublishAnonymisedJob job = jobs.get(publicURL);
if (job != null) {
long endTimeInMillis = job.getEndTimeEpochSecond()*1000;
toReturn.add(new SubmittedForm(externalFile, job.getStatus(), job.getSubmitterIdentity(), endTimeInMillis));
} else
toReturn.add(new SubmittedForm(externalFile));
}
return toReturn;
}
public void displayVersions(ActionRequest request, ActionResponse response) throws Exception {
System.out.println("**** displayVersionsdisplayVersionsdisplayVersionsdisplayVersions");
String itemId = ParamUtil.getString(request, "fileItem");
long farmId = ParamUtil.getLong(request, "farmId");
if (itemId == null || itemId.compareTo("")==0) {
SessionErrors.add(request.getPortletSession(),"form-error");
return;
}
HttpServletRequest httpReq = PortalUtil.getHttpServletRequest(request);
GCubeUser currentUser = Utils.getCurrentUser(httpReq);
String context = Utils.getCurrentContext(httpReq);
Workspace ws = Utils.getWS(currentUser.getUsername(), context) ;
WorkspaceItem theItem = ws.getItem(itemId);
if (theItem instanceof ExternalFile) {
ExternalFile file = (ExternalFile) theItem;
List<WorkspaceVersion> versions = file.getVersionHistory();
request.setAttribute("versions", versions); //pass to the JSP
} else {
response.setRenderParameter("jspPage", PFISHConstants.OPERATION_ERROR_PATH);
}
request.setAttribute("farmId", farmId);
request.setAttribute("itemId", itemId);
request.setAttribute("itemName", theItem.getName());
response.setWindowState(WindowState.MAXIMIZED);
response.setRenderParameter("jspPage", "/html/farmrepository/show_all_versions.jsp");
}
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException {
//if download file
String fileToDownloadId = ParamUtil.getString(resourceRequest, "fileToDownloadId", null);
//if download version
String versionDownloadItemId = ParamUtil.getString(resourceRequest, "versionDownloadItemId", null);
String versionDownloadName = ParamUtil.getString(resourceRequest, "versionDownloadName", null);
String fileToPublishId = ParamUtil.getString(resourceRequest, "fileToPublishId", null);
String farmIdString = ParamUtil.getString(resourceRequest, "farmId", null);
String authToken = setAuthorizationToken(resourceRequest);
//check if is a file download
if (fileToDownloadId != null) {
String selectedItemId = fileToDownloadId;
try {
ItemManagerClient client = AbstractPlugin.item().build();
StreamDescriptor streamDescr = client.download(selectedItemId);
HttpServletResponse httpRes = PortalUtil.getHttpServletResponse(resourceResponse);
HttpServletRequest httpReq = PortalUtil.getHttpServletRequest(resourceRequest);
ServletResponseUtil.sendFile(httpReq,httpRes, streamDescr.getFileName(), streamDescr.getStream(), "application/download");
streamDescr.getStream().close();
}
catch (Exception e) {
e.printStackTrace();
}
}
else if (versionDownloadItemId != null && versionDownloadName != null) { //check if download version
GCubeUser currentUser = Utils.getCurrentUser(resourceRequest);
String context = Utils.getCurrentContext(resourceRequest);
Workspace ws = Utils.getWS(currentUser.getUsername(), context) ;
WorkspaceItem theItem;
try {
theItem = ws.getItem(versionDownloadItemId);
if (theItem instanceof ExternalFile) {
ExternalFile file = (ExternalFile) theItem;
InputStream is = file.downloadVersion(versionDownloadName);
HttpServletResponse httpRes = PortalUtil.getHttpServletResponse(resourceResponse);
HttpServletRequest httpReq = PortalUtil.getHttpServletRequest(resourceRequest);
ServletResponseUtil.sendFile(httpReq,httpRes, versionDownloadName+"_"+file.getName(), is, "application/download");
}
} catch (ItemNotFoundException | InternalErrorException e) {
e.printStackTrace();
}
}
else if (fileToPublishId != null && farmIdString != null) { //check if is publish and anonimyse
long farmId = Long.parseLong(farmIdString);
try {
ItemManagerClient client = AbstractPlugin.item().build();
Item selectedForm = client.get(fileToPublishId, "hl:accounting");
String publicLink = client.getPublickLink(fileToPublishId).toString();
List<Version> versions = client.getFileVersions(fileToPublishId);
String theVersion = "1.0";
for (Version version : versions) {
if (version.isCurrent())
theVersion = version.getName();
}
_log.debug("Publish and Anonymise " + selectedForm.getName());
String batchType = Utils.getBatchTypeName(Utils.getPhaseByFileName(selectedForm.getName()), selectedForm.getName());
String result = submitPublishAndAnonymise(resourceRequest, farmId, publicLink, theVersion, batchType, authToken);
JSONObject fileObject = JSONFactoryUtil.createJSONObject();
fileObject.put("success", result);
resourceResponse.getWriter().println(fileObject);
}
catch (Exception e) {
e.printStackTrace();
}
}
else {
String batchType = ParamUtil.getString(resourceRequest, "batchType", null);
String farmIdStr = ParamUtil.getString(resourceRequest, "farmId", null);
String context = Utils.getCurrentContext(resourceRequest);
long farmId = Long.parseLong(farmIdStr);
boolean analyisisEnabled = false;
try {
analyisisEnabled = ImportedBatchChecker.checkAnalysisAvailability(farmId, batchType, context);
}
catch (Exception e) {
JSONObject fileObject = JSONFactoryUtil.createJSONObject();
fileObject.put("success", "NOK");
fileObject.put("message", " There was an error on the server, please report this issue");
resourceResponse.getWriter().println(fileObject);
}
if (analyisisEnabled) {
JSONObject fileObject = JSONFactoryUtil.createJSONObject();
fileObject.put("success", "OK");
resourceResponse.getWriter().println(fileObject);
} else {
JSONObject fileObject = JSONFactoryUtil.createJSONObject();
fileObject.put("success", "NOK");
fileObject.put("message", " Low number of batches");
resourceResponse.getWriter().println(fileObject);
}
}
}
/**
* set the authorization token in Thread local and return the current {@link AuthorizedUser} instance
* @param request
* @return
*/
private String setAuthorizationToken(ResourceRequest request) {
GCubeUser currentUser = Utils.getCurrentUser(request);
String scope = Utils.getCurrentContext(request);
String authorizationToken = Utils.getCurrentUserToken(scope, currentUser.getUsername());
SecurityTokenProvider.instance.set(authorizationToken);
return authorizationToken;
}
private static String submitPublishAndAnonymise(ResourceRequest request, long farmId, String publicLink, String version, String batchType, String token) {
String encodedURL = publicLink;
try {
encodedURL = URLEncoder.encode(publicLink, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
_log.debug("farmId " + farmId);
_log.debug("item URL encoded " + encodedURL);
_log.debug("version " + version);
_log.debug("batchType " + batchType);
Map<String, String> params = new HashMap<>();
params.put("batch_type", batchType);
params.put("farmid", ""+farmId);
params.put("source", encodedURL);
params.put("source_version", version);
params.put("gcube-token", token);
String urlParameters = "batch_type="+batchType+"&farmid="+farmId+"&source="+encodedURL+"&source_version="+version+"&gcube-token="+token;
String context = Utils.getCurrentContext(request);
String analyticalToolkitServiceURL = Utils.getAnalyticalToolkitEndpoint(context) ;
return doPOSTRequest(analyticalToolkitServiceURL, params, urlParameters);
}
private static String doPOSTRequest(String analyticalToolkitServiceURL, Map<String, String> params, String urlParameters) {
StringBuilder sb = new StringBuilder(analyticalToolkitServiceURL)
.append("/import?")
.append(urlParameters);
String request = sb.toString();
_log.info("Performing POST to: " + request);
int status = -1;
try {
fixUntrustCertificate() ;
URL url= new URL(request);
HttpsURLConnection conn= (HttpsURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "utf-8");
conn.setUseCaches( false );
System.out.println("Posted with code "+ conn.getResponseCode() +" Response: " + conn.getResponseMessage());
System.out.println("Parameters:" + params.toString());
//responseMessage = conn.getResponseMessage();
status = conn.getResponseCode();
InputStream in = conn.getInputStream();
String encoding = conn.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
System.out.println("Response Body:");
System.out.println(body);
if (status >= 200 && status <= 300) {
return "OK";
}
else
return "KO";
}
catch (Exception e) {
e.printStackTrace();
return "KO";
}
}
private static void fixUntrustCertificate() throws KeyManagementException, NoSuchAlgorithmException{
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws CertificateException {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// set the allTrusting verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
}

@ -0,0 +1,30 @@
package org.gcube.portlets.user.performfish;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletPreferences;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.portlet.DefaultConfigurationAction;
public class CompanyFarmRepositoryConfigurationAction extends DefaultConfigurationAction {
private static Log _log = LogFactoryUtil.getLog(CompanyFarmRepositoryConfigurationAction.class);
@Override
public void processAction(PortletConfig portletConfig, ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
super.processAction(portletConfig, actionRequest, actionResponse);
PortletPreferences prefs = actionRequest.getPreferences();
String phaseValue = prefs.getValue("phase", "");
_log.info("selected phase = " + phaseValue + " in ConfigurationAction.processAction() saved correctly");
}
@Override
public String render(PortletConfig portletConfig,
RenderRequest renderRequest, RenderResponse renderResponse)
throws Exception {
return "/html/farmrepository/config.jsp";
}
}

@ -0,0 +1,195 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.WindowState;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.homelibary.model.versioning.WorkspaceVersion;
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.folder.items.ExternalFile;
import org.gcube.common.storagehub.client.StreamDescriptor;
import org.gcube.common.storagehub.client.plugins.AbstractPlugin;
import org.gcube.common.storagehub.client.proxies.ItemManagerClient;
import org.gcube.portlets.user.performfish.bean.Farm;
import org.gcube.portlets.user.performfish.util.PFISHConstants;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.portlets.user.performfish.util.comparators.WSItemComparator;
import org.gcube.portlets.user.performfish.util.db.DBUtil;
import org.gcube.portlets.user.performfish.util.db.DatabaseConnection;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.ServletResponseUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class CompanyPrivateRepository
*/
public class CompanyPrivateRepository extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(CompanyFarmRepository.class);
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.info(" This is render method of CompanyPrivateRepository");
try {
_log.info(" initialise of CompanyPrivateRepository done");
long groupId = PortalUtil.getScopeGroupId(request);
GCubeTeam theCompany = Utils.checkBelongingToOneCompanyOnly(request, response, this);
boolean isCompanyAdmin = Utils.isCompanyAdmin( Utils.getCurrentUser(request), groupId, theCompany);
if (theCompany != null && isCompanyAdmin) { //check is Admin
request.setAttribute("theCompany", theCompany);
String currentContext = Utils.getCurrentContext(request);
GCubeUser currentUser = Utils.getCurrentUser(request);
RoleManager rm = new LiferayRoleManager();
//check folder exists
Utils.getWSCompanyFolder(currentUser.getUsername(), currentContext, theCompany);
//look for company farms
Connection conn = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
List<Farm> companyFarms = DBUtil.listFarmsByCompanyId(conn, theCompany.getTeamId());
LinkedHashMap<Farm, List<ExternalFile>> theFiles = new LinkedHashMap<>();
for (Farm farm : companyFarms) {
GCubeTeam theFarm = rm.getTeam(farm.getFarmId());
farm.setName(theFarm.getTeamName());
WorkspaceFolder farmFolder = Utils.getWSFarmFolder(
currentUser.getUsername(),
currentContext,
theCompany, theFarm);
List<WorkspaceItem> farmItems = farmFolder.getChildren(true);
Collections.sort(farmItems, new WSItemComparator());
List<ExternalFile> farmFiles = new ArrayList<>();
for (WorkspaceItem workspaceItem : farmItems) {
if (workspaceItem instanceof ExternalFile) {
ExternalFile file = (ExternalFile) workspaceItem;
farmFiles.add(file);
}
}
theFiles.put(farm, farmFiles);
}
request.setAttribute("companyPrivateFiles", theFiles); //pass to the JSP
String imageUrl = Utils.getCompanyLogoURL(theCompany.getTeamName(), groupId, request);
request.setAttribute("companyLogoURL", imageUrl); //pass to logo URL to the JSP
//display the view.jsp
super.render(request, response);
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_ADMIN_PAGE_PATH);
dispatcher.include(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void displayVersions(ActionRequest request, ActionResponse response) throws Exception {
String itemId = ParamUtil.getString(request, "fileItem");
if (itemId == null || itemId.compareTo("")==0) {
SessionErrors.add(request.getPortletSession(),"form-error");
return;
}
HttpServletRequest httpReq = PortalUtil.getHttpServletRequest(request);
GCubeUser currentUser = Utils.getCurrentUser(httpReq);
String context = Utils.getCurrentContext(httpReq);
Workspace ws = Utils.getWS(currentUser.getUsername(), context) ;
WorkspaceItem theItem = ws.getItem(itemId);
if (theItem instanceof ExternalFile) {
ExternalFile file = (ExternalFile) theItem;
List<WorkspaceVersion> versions = file.getVersionHistory();
request.setAttribute("versions", versions); //pass to the JSP
} else {
response.setRenderParameter("jspPage", PFISHConstants.OPERATION_ERROR_PATH);
}
request.setAttribute("itemId", itemId);
request.setAttribute("itemName", theItem.getName());
response.setWindowState(WindowState.MAXIMIZED);
response.setRenderParameter("jspPage", "/html/farmrepository/show_all_versions.jsp");
}
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException {
//if download file
String fileToDownloadId = ParamUtil.getString(resourceRequest, "fileToDownloadId", null);
//if download version
String versionDownloadItemId = ParamUtil.getString(resourceRequest, "versionDownloadItemId", null);
String versionDownloadName = ParamUtil.getString(resourceRequest, "versionDownloadName", null);
setAuthorizationToken(resourceRequest);
//check if is a file download
if (fileToDownloadId != null) {
String selectedItemId = fileToDownloadId;
try {
ItemManagerClient client = AbstractPlugin.item().build();
StreamDescriptor streamDescr = client.download(selectedItemId);
HttpServletResponse httpRes = PortalUtil.getHttpServletResponse(resourceResponse);
HttpServletRequest httpReq = PortalUtil.getHttpServletRequest(resourceRequest);
ServletResponseUtil.sendFile(httpReq,httpRes, streamDescr.getFileName(), streamDescr.getStream(), "application/download");
streamDescr.getStream().close();
} catch (Exception e) {
e.printStackTrace();
}
}
else if (versionDownloadItemId != null && versionDownloadName != null) { //check if download version
GCubeUser currentUser = Utils.getCurrentUser(resourceRequest);
String context = Utils.getCurrentContext(resourceRequest);
Workspace ws = Utils.getWS(currentUser.getUsername(), context) ;
WorkspaceItem theItem;
try {
theItem = ws.getItem(versionDownloadItemId);
if (theItem instanceof ExternalFile) {
ExternalFile file = (ExternalFile) theItem;
InputStream is = file.downloadVersion(versionDownloadName);
HttpServletResponse httpRes = PortalUtil.getHttpServletResponse(resourceResponse);
HttpServletRequest httpReq = PortalUtil.getHttpServletRequest(resourceRequest);
ServletResponseUtil.sendFile(httpReq,httpRes, versionDownloadName+"_"+file.getName(), is, "application/download");
}
} catch (ItemNotFoundException | InternalErrorException e) {
e.printStackTrace();
}
}
}
/**
* set the authorization token in Thread local and return the current {@link AuthorizedUser} instance
* @param request
* @return
*/
private void setAuthorizationToken(ResourceRequest request) {
GCubeUser currentUser = Utils.getCurrentUser(request);
String scope = Utils.getCurrentContext(request);
String authorizationToken = Utils.getCurrentUserToken(scope, currentUser.getUsername());
SecurityTokenProvider.instance.set(authorizationToken);
}
}

@ -0,0 +1,30 @@
package org.gcube.portlets.user.performfish;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletPreferences;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.portlet.DefaultConfigurationAction;
public class EmptyFormsConfigurationAction extends DefaultConfigurationAction {
private static Log _log = LogFactoryUtil.getLog(EmptyFormsConfigurationAction.class);
@Override
public void processAction(PortletConfig portletConfig, ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
super.processAction(portletConfig, actionRequest, actionResponse);
PortletPreferences prefs = actionRequest.getPreferences();
String phaseValue = prefs.getValue("phase", "");
_log.info("selected phase to display= " + phaseValue + " in EmptyFormsConfigurationAction.processAction() saved correctly");
}
@Override
public String render(PortletConfig portletConfig,
RenderRequest renderRequest, RenderResponse renderResponse)
throws Exception {
return "/html/emptyformsdocumentsdisplay/empty_forms_config.jsp";
}
}

@ -0,0 +1,220 @@
package org.gcube.portlets.user.performfish;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
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.folder.FolderItem;
import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile;
import org.gcube.common.homelibrary.util.WorkspaceUtil;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portlets.user.performfish.util.PFISHConstants;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.ServletResponseUtil;
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.GetterUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class EmptyFormsDocumentsDisplay
*/
public class EmptyFormsDocumentsDisplay extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(EmptyFormsDocumentsDisplay.class);
public static final String FOLDERID_PREFERENCE_ATTR_NAME = "folderId";
private final static String RESOURCE_URL_ID = "uploadFiles";
private final static String UPLOADED_FILE_ATTR_NAME = "myfile";
private static String XLS_MIMETYPE = "application/vnd.ms-excel";
private static String XLSX_MIMETYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
public static final String ATTACHMENT_FOLDER ="_uploaded_forms";
private static RoleManager RM = new LiferayRoleManager();
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.info(" This is render method of EmptyFormsDocumentsDisplay");
try {
HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
String[] farmIds = ParamUtil.getParameterValues(httpReq, Utils.ENCODED_FARM_PARAM);
GCubeTeam theFarm = null;
if (farmIds == null || farmIds.length == 0 ) {
if (Utils.getUserFarmsNumber(request, response, this) < 2) {
theFarm = Utils.checkBelongingToOneFarmOnly(request, response, this);
request.setAttribute("theFarm", theFarm); //pass to the JSP
}
}
else { //the farmId is passed via param on the query string
long selectedFarmId = Utils.unmaskId(farmIds[0]);
theFarm = RM.getTeam(selectedFarmId);
if (Utils.checkBelongsToTeam(PortalUtil.getUserId(request), theFarm.getTeamId(), PortalUtil.getScopeGroupId(request)) ) {//check that the user belong ot the farm
request.setAttribute("theFarm", theFarm); //pass to the JSP
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_BELONGING_ANY_FARM_PAGE_PATH);
dispatcher.include(request, response);
}
}
if (theFarm != null) {
setGuestAuthorizationToken(request);
PortletPreferences portletPreferences = request.getPreferences();
String folderId = GetterUtil.getString(portletPreferences.getValue(FOLDERID_PREFERENCE_ATTR_NAME, StringPool.BLANK));
if (folderId != null && !folderId.equals("")) {
String context = Utils.getCurrentContext(request);
Workspace ws = Utils.getWS("guest", context) ;
String selectedPhase = GetterUtil.getString(portletPreferences.getValue(PFISHConstants.PHASE_PREFERENCE_ATTR_NAME, StringPool.BLANK));
//in theChildren expected to find 3 subfolders: Utils.SHOW_HATCHERY, SHOW_PRE_ONGROWING ..
for (WorkspaceItem item : ws.getItem(folderId).getChildren()) {
if (item.getName().equalsIgnoreCase(selectedPhase)) {
List<? extends WorkspaceItem> thefiles = item.getChildren();
List<ExternalFile> theSheets = new ArrayList<>();
List<ExternalFile> theInstructions = new ArrayList<>();
List<String >theSheetNames = new ArrayList<>();
//separate from instructions
for (WorkspaceItem workspaceItem : thefiles) {
if (workspaceItem instanceof ExternalFile) {
ExternalFile file = (ExternalFile) workspaceItem;
if (file.getMimeType().equals(XLS_MIMETYPE) || file.getMimeType().equals(XLSX_MIMETYPE)) { //is a form
theSheets.add(file);
theSheetNames.add("'"+file.getName()+"'"); //serializing for Javascript
}
else
theInstructions.add(file);
}
}
request.setAttribute("theSheetNames", theSheetNames); //pass to the JSP
request.setAttribute("theSheets", theSheets); //pass to the JSP
request.setAttribute("theInstructions", theInstructions); //pass to the JSP
break;
}
}
}
super.render(request, response);
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.TOO_MANY_FARM_PAGE_PATH);
dispatcher.include(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException {
_log.debug("serveResource ...");
String resourceID = resourceRequest.getResourceID();
if (resourceID != null && resourceID.equals(RESOURCE_URL_ID)) {
_log.debug("Upload File");
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();
_log.debug(fileName);
_log.debug(contentType);
}
JSONObject fileObject = JSONFactoryUtil.createJSONObject();
try {
String context = Utils.getCurrentContext(resourceRequest);
_log.debug("upload file, context="+context);
String username = Utils.getCurrentUser(resourceRequest).getUsername();
String authorizationToken = Utils.getCurrentUserToken(context, username );
SecurityTokenProvider.instance.set(authorizationToken);
ScopeProvider.instance.set(context);
Workspace workspace = Utils.getWS(username, context) ;
String wsItemId = uploadToUserWorkspace(workspace, fileName, contentType, new ByteArrayInputStream(FileUtil.getBytes(multipartFile)));
String toReturn = workspace.getItem(wsItemId).getPublicLink(false);
fileObject.put("fileName", fileName);
fileObject.put("urlEncoded", URLEncoder.encode(toReturn, "UTF-8"));
} catch (Exception e) {
_log.error("There was an error uploading the file " + fileName, e);
}
resourceResponse.getWriter().println(fileObject);
}
else {
_log.debug("Download Original File");
//if download file
String fileToDownloadId = ParamUtil.getString(resourceRequest, "fileToDownloadId", null);
String context = Utils.getCurrentContext(resourceRequest);
Workspace ws = Utils.getWS("guest", context) ;
WorkspaceItem theItem;
try {
theItem = ws.getItem(fileToDownloadId);
if (theItem instanceof ExternalFile) {
ExternalFile file = (ExternalFile) theItem;
InputStream is = file.getData();
HttpServletResponse httpRes = PortalUtil.getHttpServletResponse(resourceResponse);
HttpServletRequest httpReq = PortalUtil.getHttpServletRequest(resourceRequest);
ServletResponseUtil.sendFile(httpReq,httpRes, file.getName(), is, "application/download");
}
} catch (ItemNotFoundException | InternalErrorException e) {
e.printStackTrace();
}
}
}
/**
* set the authorization token in Thread local and return the current {@link AuthorizedUser} instance
* @param request
* @return
*/
private void setGuestAuthorizationToken(RenderRequest request) {
String scope = Utils.getCurrentContext(request);
String authorizationToken = Utils.getCurrentUserToken(scope, "guest");
SecurityTokenProvider.instance.set(authorizationToken);
}
private String uploadToUserWorkspace(Workspace ownerWS, String fileName, String mimeType,InputStream fileData) throws Exception {
WorkspaceFolder attachmentDirectory = null;
try{
attachmentDirectory = (WorkspaceFolder) ownerWS.getItemByPath(ownerWS.getRoot().getPath() + "/" + ATTACHMENT_FOLDER);
} catch (ItemNotFoundException e) {
_log.info(ATTACHMENT_FOLDER + " Workspace Folder does not exists, creating it ");
attachmentDirectory = ownerWS.getRoot().createFolder(ATTACHMENT_FOLDER, "Folder created automatically by the System");
}
System.out.println("attachmentDirectory="+attachmentDirectory);
String itemName = WorkspaceUtil.getUniqueName(fileName, attachmentDirectory);
FolderItem item = WorkspaceUtil.createExternalFile(attachmentDirectory, itemName, "System created upon user form submission " + new Date(), mimeType, fileData);
String toReturn = item.getId();
_log.debug("Uploaded " + item.getName() + " - Returned Workspace id=" +toReturn);
return toReturn;
}
}

@ -0,0 +1,71 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.gcube.portlets.user.performfish.bean.Association;
import org.gcube.portlets.user.performfish.bean.Company;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.portlets.user.performfish.util.db.DBUtil;
import org.gcube.portlets.user.performfish.util.db.DatabaseConnection;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.model.Team;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class ManageAssociations
*/
public class ManageAssociations extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(ManageCompanies.class);
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.info(" This is render method of ManageAssociations");
try {
long groupId = PortalUtil.getScopeGroupId(request);
String vreName = GroupLocalServiceUtil.getGroup(groupId).getName();
Connection conn = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
List<Association> associations = DBUtil.getAllAssociations(conn);
LinkedHashMap<Association, List<Company>> associationCompanies = new LinkedHashMap<>();
for (Association ass : associations) {
Team theTeam = TeamLocalServiceUtil.getTeam(ass.getAssociationId());
ass.setShortName(theTeam.getName());
ass.setFullName(theTeam.getDescription());
ass.setImageUrl(Utils.getCompanyLogoURL(ass.getShortName(), groupId, request));
List<Long> companIds = DBUtil.getCompaniesIdsByAssociation(conn, ass.getAssociationId());
List<Company> children = new ArrayList<>();
for (Long companId : companIds) {
Team theCompany = TeamLocalServiceUtil.getTeam(companId);
Company toAdd = new Company(companId, ass.getAssociationId(), false);
toAdd.setName(theCompany.getName());
toAdd.setImageUrl(Utils.getCompanyLogoURL(theCompany.getName(), groupId, request));
children.add(toAdd);
}
associationCompanies.put(ass, children);
}
request.setAttribute("associations", associations);
request.setAttribute("associationCompanies", associationCompanies);
request.setAttribute("vreName", vreName);
super.render(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,111 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.gcube.portlets.user.performfish.bean.Company;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.portlets.user.performfish.util.db.DBUtil;
import org.gcube.portlets.user.performfish.util.db.DatabaseConnection;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class ManageCompanies
*/
public class ManageCompanies extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(ManageCompanies.class);
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.info(" This is render method of ManageCompanies");
try {
long groupId = PortalUtil.getScopeGroupId(request);
String vreName = GroupLocalServiceUtil.getGroup(groupId).getName();
Connection conn = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
List<Company> companies = DBUtil.getCompanies(conn);
for (Company company : companies) {
company.setName(TeamLocalServiceUtil.getTeam(company.getCompanyId()).getName());
company.setImageUrl(Utils.getCompanyLogoURL(company.getName(), groupId, request));
}
request.setAttribute("companies", companies);
request.setAttribute("vreName", vreName);
super.render(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void removeCompanies(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
String currentUsername = ParamUtil.getString(actionRequest, "currentUsername", "unknown");
_log.info("removeCompanies action request from " + currentUsername);
long groupId = ParamUtil.getLong(actionRequest, "groupId");
Connection conn = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
try {
String[] companyIdsToRemove = ParamUtil.getParameterValues(actionRequest, "removeCompanyIds");
if (companyIdsToRemove.length > 0) {
_log.info("removeCompanyIds writing to DB now ...");
boolean result = DBUtil.removeCompany(conn, companyIdsToRemove);
if (!result) {
SessionErrors.add(actionRequest.getPortletSession(), "operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
}
}
else {
SessionErrors.add(actionRequest.getPortletSession(), "operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
}
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
/**
*
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void manageCompanyFarms(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
String currentUsername = ParamUtil.getString(actionRequest, "currentUsername", "unknown");
_log.info("manageCompanyFarms action request from " + currentUsername);
String[] companyIdsToManage = ParamUtil.getParameterValues(actionRequest, "companyIds");
if (companyIdsToManage.length == 1) {
System.out.println("tutto ok");
}
else {
SessionErrors.add(actionRequest.getPortletSession(), "operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
}
}
}

@ -0,0 +1,139 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.gcube.portlets.user.performfish.bean.CompanyMember;
import org.gcube.portlets.user.performfish.bean.Farm;
import org.gcube.portlets.user.performfish.util.PFISHConstants;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.model.Team;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class ManageCompanyAdmins
*/
public class ManageCompanyAdmins extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(ManageCompanyAdmins.class);
@Override
public void render(RenderRequest request, RenderResponse response) throws PortletException, IOException {
try {
long groupId = PortalUtil.getScopeGroupId(request);
GCubeTeam theTeam = Utils.checkBelongingToOneCompanyOnly(request, response, this);
request.setAttribute("theTeam", TeamLocalServiceUtil.getTeam(theTeam.getTeamId()));
RoleManager rm = new LiferayRoleManager();
if (theTeam != null && Utils.isCompanyAdmin(Utils.getCurrentUser(request), groupId, theTeam)) { //check is Admin
//check folder exists
Utils.getWSCompanyFolder(Utils.getCurrentUser(request).getUsername(), Utils.getCurrentContext(request), theTeam);
List<CompanyMember> companyAdmins = Utils.getCompanyAdminTeamMembers(theTeam.getTeamId(), theTeam.getGroupId());
for (CompanyMember member : companyAdmins) { //anonymising email
member.setEmail(member.getUser().getEmail());
List<Farm> theFarms = Utils.getFarmsByUserId(member.getUserId(), theTeam.getTeamId(), groupId);
if (theFarms != null && !theFarms.isEmpty()) {
GCubeTeam theFarmTeam = rm.getTeam(theFarms.get(0).getFarmId());
member.setAssociatedFarms(theFarms);
member.setAdmin(Utils.isFarmAdmin(member.getUser(), groupId, theFarmTeam));
}
}
request.setAttribute("companyAdmins", companyAdmins); //pass to the JSP
String imageUrl = Utils.getCompanyLogoURL(theTeam.getTeamName(), groupId, request);
request.setAttribute("companyLogoURL", imageUrl); //pass to logo URL to the JSP
//display the view.jsp
super.render(request, response);
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_ADMIN_PAGE_PATH);
dispatcher.include(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void removeAdministratorRoleFromUsers(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
try {
long[] userIdsToRemoveFromCompanyAdmins = ParamUtil.getLongValues(actionRequest, "removeUserIds");
long teamId = ParamUtil.getLong(actionRequest, "teamId");
String currentUsername = ParamUtil.getString(actionRequest, "currentUsername");
long currentGroupId = ParamUtil.getLong(actionRequest, "currentGroupId");
_log.info(currentUsername + " has requested the deletion of some user(s) from company administrator having id="+teamId );
LiferayRoleManager rm = new LiferayRoleManager();
GCubeRole adminRole = new LiferayRoleManager().getRole(PFISHConstants.COMPANY_ADMIN_SITE_ROLE, currentGroupId);
for (int i = 0; i < userIdsToRemoveFromCompanyAdmins.length; i++) {
rm.removeRoleFromUser(userIdsToRemoveFromCompanyAdmins[i], currentGroupId, adminRole.getRoleId());
_log.info("removing role from user with id " + userIdsToRemoveFromCompanyAdmins[i] + " done");
}
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
/**
*
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void removeFarmUsers(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
try {
String currentUsername = ParamUtil.getString(actionRequest, "currentUsername");
long currentGroupId = ParamUtil.getLong(actionRequest, "currentGroupId");
long companyUserId = ParamUtil.getLong(actionRequest, "companyUserId");
long companyId = ParamUtil.getLong(actionRequest, "companyId");
String context = Utils.getCurrentContext(currentGroupId);
_log.info(currentUsername + " has requested the deletion of userid " + companyUserId + " from farms in context="+context);
List<Farm> theUserFarms = Utils.getFarmsByUserId(companyUserId, companyId, currentGroupId);
for (Farm farm : theUserFarms) {
removeFromFarm(farm.getFarmId(), currentGroupId, companyUserId);
}
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
private boolean removeFromFarm(long farmId, long currentGroupId, long companyUserId) throws Exception {
Team team = TeamLocalServiceUtil.getTeam(farmId);//check that the farm is real
TeamLocalServiceUtil.deleteUserTeam(companyUserId, team.getTeamId());
_log.info("removing user from farm Done");
LiferayRoleManager rm = new LiferayRoleManager();
GCubeRole adminRole = new LiferayRoleManager().getRole(PFISHConstants.FARM_ADMIN_SITE_ROLE, currentGroupId);
_log.info("removing role from user with id " + companyUserId);
return rm.removeRoleFromUser(companyUserId, currentGroupId, adminRole.getRoleId());
}
}

@ -0,0 +1,160 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder;
import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder;
import org.gcube.portlets.user.performfish.bean.CompanyMember;
import org.gcube.portlets.user.performfish.bean.Farm;
import org.gcube.portlets.user.performfish.util.PFISHConstants;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.portlets.user.performfish.util.comparators.CompanyMemberComparator;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.model.Team;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class ManageCompanyUsers
*/
public class ManageCompanyUsers extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(ManageCompanyUsers.class);
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.info(" This is render method of ManageCompanyusers");
try {
long groupId = PortalUtil.getScopeGroupId(request);
GCubeTeam theTeam = Utils.checkBelongingToOneCompanyOnly(request, response, this);
request.setAttribute("theTeam", TeamLocalServiceUtil.getTeam(theTeam.getTeamId()));
RoleManager rm = new LiferayRoleManager();
if (theTeam != null && Utils.isCompanyAdmin(Utils.getCurrentUser(request), groupId, theTeam)) { //check is Admin
//check folder exists
Utils.getWSCompanyFolder(Utils.getCurrentUser(request).getUsername(), Utils.getCurrentContext(request), theTeam);
List<CompanyMember> companyMembers = Utils.getRegularCompanyMembers(theTeam.getTeamId(), theTeam.getGroupId());
for (CompanyMember member : companyMembers) { //anonymising email
member.setEmail(member.getUser().getEmail());
List<Farm> theFarms = Utils.getFarmsByUserId(member.getUserId(), theTeam.getTeamId(), groupId);
if (theFarms != null && !theFarms.isEmpty()) {
GCubeTeam theFarmTeam = rm.getTeam(theFarms.get(0).getFarmId());
member.setAssociatedFarms(theFarms);
member.setAdmin(Utils.isFarmAdmin(member.getUser(), groupId, theFarmTeam));
}
}
Collections.sort(companyMembers, new CompanyMemberComparator());
request.setAttribute("companyMembers", companyMembers); //pass to the JSP
String imageUrl = Utils.getCompanyLogoURL(theTeam.getTeamName(), groupId, request);
request.setAttribute("companyLogoURL", imageUrl); //pass to logo URL to the JSP
//display the view.jsp
super.render(request, response);
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_ADMIN_PAGE_PATH);
dispatcher.include(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void removeCompanUsers(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
try {
String[] usernamesToRemoveFromCompany = ParamUtil.getParameterValues(actionRequest, "removeUserIds");
long teamId = ParamUtil.getLong(actionRequest, "teamId");
String currentUsername = ParamUtil.getString(actionRequest, "currentUsername");
long currentGroupId = ParamUtil.getLong(actionRequest, "currentGroupId");
String context = Utils.getCurrentContext(currentGroupId);
_log.info(currentUsername + " has requested the deletion of some user(s) from company having id="+teamId + " in context="+context);
LiferayRoleManager rm = new LiferayRoleManager();
LiferayUserManager um = new LiferayUserManager();
GCubeTeam team = rm.getTeam(teamId);
WorkspaceFolder wsFolder = Utils.getWSCompanyFolder(currentUsername, context, team);
if (wsFolder.isShared()) {
WorkspaceSharedFolder sharedFolder = (WorkspaceSharedFolder) wsFolder;
for (int i = 0; i < usernamesToRemoveFromCompany.length; i++) {
_log.info("Unsharing user =>"+usernamesToRemoveFromCompany[i]);
sharedFolder.unShare(usernamesToRemoveFromCompany[i]);
_log.info("Unsharing OK removing user from team =>"+usernamesToRemoveFromCompany[i]);
long userId = um.getUserByUsername(usernamesToRemoveFromCompany[i]).getUserId();
TeamLocalServiceUtil.deleteUserTeam(userId, team.getTeamId());
List<Farm> thePossibleFarms = Utils.getFarmsByUserId(userId, teamId, currentGroupId);
if (thePossibleFarms != null && !thePossibleFarms.isEmpty()) {
for (Farm farm : thePossibleFarms) {
removeFromFarm(farm.getFarmId(), currentGroupId, userId);
}
}
_log.info("removing user from team Done");
}
}
else {
SessionErrors.add(actionRequest.getPortletSession(), "operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
}
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
/**
*
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void removeFarmUsers(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
try {
String currentUsername = ParamUtil.getString(actionRequest, "currentUsername");
long currentGroupId = ParamUtil.getLong(actionRequest, "currentGroupId");
long companyUserId = ParamUtil.getLong(actionRequest, "companyUserId");
long companyId = ParamUtil.getLong(actionRequest, "companyId");
String context = Utils.getCurrentContext(currentGroupId);
_log.info(currentUsername + " has requested the deletion of userid " + companyUserId + " from farms in context="+context);
List<Farm> theUserFarms = Utils.getFarmsByUserId(companyUserId, companyId, currentGroupId);
for (Farm farm : theUserFarms) {
removeFromFarm(farm.getFarmId(), currentGroupId, companyUserId);
}
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
private boolean removeFromFarm(long farmId, long currentGroupId, long companyUserId) throws Exception {
Team team = TeamLocalServiceUtil.getTeam(farmId);//check that the farm is real
TeamLocalServiceUtil.deleteUserTeam(companyUserId, team.getTeamId());
_log.info("removing user from farm Done");
LiferayRoleManager rm = new LiferayRoleManager();
GCubeRole adminRole = new LiferayRoleManager().getRole(PFISHConstants.FARM_ADMIN_SITE_ROLE, currentGroupId);
_log.info("removing role from user with id " + companyUserId);
return rm.removeRoleFromUser(companyUserId, currentGroupId, adminRole.getRoleId());
}
}

@ -0,0 +1,130 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.WindowState;
import javax.servlet.http.HttpServletRequest;
import org.gcube.portlets.user.performfish.util.PFISHConstants;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class ManageFarmAdministrators
*/
public class ManageFarmAdministrators extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(ManageFarmAdministrators.class);
private static RoleManager RM = new LiferayRoleManager();
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.info(" This is render method of ManageFarmAdministrators");
try {
HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
String[] farmIds = ParamUtil.getParameterValues(httpReq, Utils.ENCODED_FARM_PARAM);
long[] farmIds2 = ParamUtil.getLongValues(httpReq, "farmId");
GCubeTeam theFarm = null;
if ((farmIds == null || farmIds.length == 0) && (farmIds2 == null || farmIds2.length == 0)) {
if (Utils.getUserFarmsNumber(request, response, this) < 2) {
theFarm = Utils.checkBelongingToOneFarmOnly(request, response, this);
request.setAttribute("theFarm", theFarm); //pass to the JSP
}
}
else { //the farmId (encrypted) or farmId2 (not encrypted) is passed via param on the query string
long selectedFarmId = 0;
if (farmIds != null && farmIds.length > 0) {
selectedFarmId = Utils.unmaskId(farmIds[0]);
} else
selectedFarmId = farmIds2[0];
theFarm = RM.getTeam(selectedFarmId);
if (Utils.checkBelongsToTeam(PortalUtil.getUserId(request), theFarm.getTeamId(), PortalUtil.getScopeGroupId(request)) ) {//check that the user belong ot the farm
request.setAttribute("theFarm", theFarm); //pass to the JSP
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_BELONGING_ANY_FARM_PAGE_PATH);
dispatcher.include(request, response);
}
}
long groupId = PortalUtil.getScopeGroupId(request);
GCubeTeam theCompany = Utils.checkBelongingToOneCompanyOnly(request, response, this);
if (theCompany != null && theFarm !=null) {
request.setAttribute("theCompany", theCompany);
request.setAttribute("theFarm", TeamLocalServiceUtil.getTeam(theFarm.getTeamId()));
if (theCompany != null && Utils.isFarmAdmin(Utils.getCurrentUser(request), groupId, theCompany)) { //check is Admin
Boolean isCompanyAdministrator = Utils.isCompanyAdmin(Utils.getCurrentUser(request), groupId, theCompany);
request.setAttribute("isCompanyAdministrator", isCompanyAdministrator);
//check folder exists
Utils.getWSCompanyFolder(Utils.getCurrentUser(request).getUsername(), Utils.getCurrentContext(request), theCompany);
List<GCubeUser> farmAdmins = Utils.getFarmAdminTeamMembers(theCompany, theFarm);
request.setAttribute("farmAdmins", farmAdmins); //pass to the JSP
String imageUrl = Utils.getCompanyLogoURL(theCompany.getTeamName(), groupId, request);
request.setAttribute("companyLogoURL", imageUrl); //pass to logo URL to the JSP
//display the view.jsp
super.render(request, response);
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_FARM_ADMIN_PAGE_PATH);
dispatcher.include(request, response);
}
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.TOO_MANY_FARM_PAGE_PATH);
dispatcher.include(request, response);
}
} catch (Exception e) {
e.printStackTrace();
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_FARM_ADMIN_PAGE_PATH);
dispatcher.include(request, response);
}
}
/**
*
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void removeAdministratorRoleFromUsers(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
try {
long[] userIdsToRemoveFromCompanyAdmins = ParamUtil.getLongValues(actionRequest, "removeUserIds");
long teamId = ParamUtil.getLong(actionRequest, "teamId");
String currentUsername = ParamUtil.getString(actionRequest, "currentUsername");
long currentGroupId = ParamUtil.getLong(actionRequest, "currentGroupId");
_log.info(currentUsername + " has requested the deletion of some user(s) from company administrator having id="+teamId );
LiferayRoleManager rm = new LiferayRoleManager();
GCubeRole adminRole = new LiferayRoleManager().getRole(PFISHConstants.FARM_ADMIN_SITE_ROLE, currentGroupId);
for (int i = 0; i < userIdsToRemoveFromCompanyAdmins.length; i++) {
rm.removeRoleFromUser(userIdsToRemoveFromCompanyAdmins[i], currentGroupId, adminRole.getRoleId());
_log.info("removing role from user with id " + userIdsToRemoveFromCompanyAdmins[i] + " done");
}
actionResponse.setPortletMode(PortletMode.VIEW);
actionResponse.setWindowState(WindowState.NORMAL);
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
}

@ -0,0 +1,134 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.WindowState;
import javax.servlet.http.HttpServletRequest;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.portlets.user.performfish.util.comparators.UserComparator;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class ManageFarmUsers
*/
public class ManageFarmUsers extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(ManageFarmUsers.class);
private static RoleManager RM = new LiferayRoleManager();
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.info(" This is render method of ManageFarmUsers");
try {
HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
String[] farmIds = ParamUtil.getParameterValues(httpReq, Utils.ENCODED_FARM_PARAM);
long[] farmIds2 = ParamUtil.getLongValues(httpReq, "farmId");
GCubeTeam theFarm = null;
if ((farmIds == null || farmIds.length == 0) && (farmIds2 == null || farmIds2.length == 0)) {
if (Utils.getUserFarmsNumber(request, response, this) < 2) {
theFarm = Utils.checkBelongingToOneFarmOnly(request, response, this);
request.setAttribute("theFarm", theFarm); //pass to the JSP
}
}
else { //the farmId (encrypted) or farmId2 (not encrypted) is passed via param on the query string
long selectedFarmId = 0;
if (farmIds != null && farmIds.length > 0) {
selectedFarmId = Utils.unmaskId(farmIds[0]);
} else
selectedFarmId = farmIds2[0];
theFarm = RM.getTeam(selectedFarmId);
if (Utils.checkBelongsToTeam(PortalUtil.getUserId(request), theFarm.getTeamId(), PortalUtil.getScopeGroupId(request)) ) {//check that the user belong ot the farm
request.setAttribute("theFarm", theFarm); //pass to the JSP
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_BELONGING_ANY_FARM_PAGE_PATH);
dispatcher.include(request, response);
}
}
long groupId = PortalUtil.getScopeGroupId(request);
GCubeTeam theCompany = Utils.checkBelongingToOneCompanyOnly(request, response, this);
if (theCompany != null && theFarm !=null) {
request.setAttribute("theCompany", theCompany);
if (theFarm != null && Utils.isFarmAdmin(Utils.getCurrentUser(request), groupId, theFarm)) { //check is Admin
request.setAttribute("theFarm", TeamLocalServiceUtil.getTeam(theFarm.getTeamId()));
//check folder exists
Utils.getWSCompanyFolder(Utils.getCurrentUser(request).getUsername(), Utils.getCurrentContext(request), theCompany);
List<GCubeUser> farmMembers = Utils.getRegularFarmMembers(theFarm.getTeamId(), theFarm.getGroupId());
for (GCubeUser member : farmMembers) { //anonymising email
int n = member.getEmail().indexOf("@");
member.setEmail("********"+member.getEmail().substring(n));
}
Collections.sort(farmMembers, new UserComparator());
request.setAttribute("farmMembers", farmMembers); //pass to the JSP
String imageUrl = Utils.getCompanyLogoURL(theCompany.getTeamName(), groupId, request);
request.setAttribute("companyLogoURL", imageUrl); //pass to logo URL to the JSP
//display the view.jsp
super.render(request, response);
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_FARM_ADMIN_PAGE_PATH);
dispatcher.include(request, response);
}
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.TOO_MANY_FARM_PAGE_PATH);
dispatcher.include(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void removeFarmUsers(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
try {
String[] usernamesToRemoveFromCompany = ParamUtil.getParameterValues(actionRequest, "removeUserIds");
long farmId = ParamUtil.getLong(actionRequest, "farmId");
String currentUsername = ParamUtil.getString(actionRequest, "currentUsername");
long currentGroupId = ParamUtil.getLong(actionRequest, "currentGroupId");
String context = Utils.getCurrentContext(currentGroupId);
_log.info(currentUsername + " has requested the deletion of some user(s) from farm having id="+farmId + " in context="+context);
LiferayRoleManager rm = new LiferayRoleManager();
LiferayUserManager um = new LiferayUserManager();
GCubeTeam team = rm.getTeam(farmId);
for (int i = 0; i < usernamesToRemoveFromCompany.length; i++) {
_log.info("removing user from farm =>"+usernamesToRemoveFromCompany[i]);
long userId = um.getUserByUsername(usernamesToRemoveFromCompany[i]).getUserId();
TeamLocalServiceUtil.deleteUserTeam(userId, team.getTeamId());
_log.info("removing user from farm Done");
}
actionResponse.setPortletMode(PortletMode.VIEW);
actionResponse.setWindowState(WindowState.NORMAL);
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
}

@ -0,0 +1,277 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder;
import org.gcube.portlets.user.performfish.bean.Farm;
import org.gcube.portlets.user.performfish.util.PFISHConstants;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.portlets.user.performfish.util.comparators.FarmComparator;
import org.gcube.portlets.user.performfish.util.db.DBUtil;
import org.gcube.portlets.user.performfish.util.db.DatabaseConnection;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.model.Layout;
import com.liferay.portal.model.ResourceConstants;
import com.liferay.portal.model.ResourcePermission;
import com.liferay.portal.model.Role;
import com.liferay.portal.security.permission.ActionKeys;
import com.liferay.portal.service.LayoutServiceUtil;
import com.liferay.portal.service.ResourcePermissionLocalServiceUtil;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class ManageFarms
*/
public class ManageFarms extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(ManageCompanies.class);
private static RoleManager RM = new LiferayRoleManager();
@Override
public void render(RenderRequest request, RenderResponse response) throws PortletException, IOException {
try {
long groupId = PortalUtil.getScopeGroupId(request);
GCubeTeam theCompany = Utils.checkBelongingToOneCompanyOnly(request, response, this);
if (theCompany != null && Utils.isCompanyAdmin(Utils.getCurrentUser(request), groupId, theCompany)) { //check is Admin
Connection conn = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
List<Farm> farms = DBUtil.listFarmsByCompanyId(conn, theCompany.getTeamId());
for (Farm farm : farms) {
GCubeTeam theFarm = RM.getTeam(farm.getFarmId());
farm.setName(theFarm.getTeamName());
farm.setDateCreated(theFarm.getCreatedate());
farm.setImageUrl(Utils.getCompanyLogoURL(theCompany.getTeamName(), groupId, request));
List<GCubeUser> farmAdmins = Utils.getFarmAdminTeamMembers(theCompany, theFarm);
farm.setAdministrators(farmAdmins);
}
Collections.sort(farms, new FarmComparator());
request.setAttribute("farms", farms);
request.setAttribute("company", theCompany);
super.render(request, response);
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_ADMIN_PAGE_PATH);
dispatcher.include(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Delete FARM
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void deleteFarm(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
_log.info("deleteFarm ActionRequest=");
long groupId = ParamUtil.getLong(actionRequest, "currentGroupId");
long companyId = ParamUtil.getLong(actionRequest, "CompanyId");
long farmId = ParamUtil.getLong(actionRequest, "FarmId");
try {
Connection conn = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
if (groupId > 0 && companyId > 0 && farmId > 0) {
long userId = PortalUtil.getUserId(actionRequest);
String username = Utils.getCurrentUser(userId).getUsername();
String context = Utils.getCurrentContext(groupId);
GCubeTeam theFarm = RM.getTeam(farmId);
GCubeTeam theCompany = RM.getTeam(companyId);
_log.info("Trying Delete Farm with name " + theFarm.getTeamName() + " of Company: " + theCompany.getTeamName());
WorkspaceFolder farmFolder = Utils.getWSFarmFolder(username, context, theCompany, theFarm);
Utils.getWS(username, context).removeItem(farmFolder.getId());
_log.info(username + " Deleted Farm Folder with Id = "+farmId + " deleting farm row DB now ");
boolean resultDeleteFarmDB = DBUtil.deleteFarm(conn, farmId);
if (!resultDeleteFarmDB) {
renderErrorPage(actionRequest, actionResponse);
}
TeamLocalServiceUtil.deleteTeam(farmId);
}
else
renderErrorPage(actionRequest, actionResponse);
} catch (Exception e) {
e.printStackTrace();
renderErrorPage(actionRequest, actionResponse);
}
}
/**
* Edit FARM
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void editFarm(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
long groupId = ParamUtil.getLong(actionRequest, "currentGroupId");
long companyId = ParamUtil.getLong(actionRequest, "CompanyId");
long farmId = ParamUtil.getLong(actionRequest, "FarmId");
String farmName = ParamUtil.getString(actionRequest, "farmName");
String farmLocation = ParamUtil.getString(actionRequest, "Location", "");
try {
Connection dbConnection = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
if (groupId > 0 && companyId > 0 && !farmName.equals("")) {
//edit the team first
String companyName = TeamLocalServiceUtil.getTeam(companyId).getName();
String theNewFarmName = farmName.trim();
GCubeTeam editedFarm = null;
try {
editedFarm = new LiferayRoleManager().updateTeam(farmId, theNewFarmName, theNewFarmName + " is a farm belonging to " + companyName);
}
catch (Exception e) {
_log.error("editFarm error ... farm team name may exists already");
renderErrorPageFarmExistAlready(actionRequest, actionResponse);
return;
}
if (editedFarm != null) {
_log.info("editedFarm writing to DB now ... farm team edited with id="+editedFarm.getTeamId());
boolean resultUpdate = DBUtil.editFarm(dbConnection, editedFarm.getTeamId(), theNewFarmName, farmLocation);
if (!resultUpdate) {
renderErrorPage(actionRequest, actionResponse);
}
}
else {
renderErrorPage(actionRequest, actionResponse);
}
}
else
renderErrorPage(actionRequest, actionResponse);
} catch (Exception e) {
e.printStackTrace();
renderErrorPage(actionRequest, actionResponse);
}
}
/**
* ADD FARM
* @param actionRequest
* @param actionResponse
* @throws Exception
*/
public void addFarm(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
long groupId = ParamUtil.getLong(actionRequest, "currentGroupId");
long companyId = ParamUtil.getLong(actionRequest, "CompanyId");
String farmName = ParamUtil.getString(actionRequest, "farmName");
String farmLocation = ParamUtil.getString(actionRequest, "Location", "");
String theCreatorFullName = ParamUtil.getString(actionRequest, "theCreatorFullName", "");
try {
Connection dbConnection = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
if (groupId > 0 && companyId > 0 && !farmName.equals("")) {
//create the team first
String companyName = TeamLocalServiceUtil.getTeam(companyId).getName();
String theFarmName = farmName.trim();
GCubeTeam newFarm = null;
try {
newFarm = new LiferayRoleManager().createTeam(groupId, theFarmName, farmName + " is a farm belonging to " + companyName);
}
catch (Exception e) {
_log.error("addFarm error ... farm team name may exists already");
renderErrorPageFarmExistAlready(actionRequest, actionResponse);
return;
}
if (newFarm != null) {
_log.info("addFarm writing to DB now ... farm team created with id="+newFarm.getTeamId());
boolean resultInsert = DBUtil.addFarm(dbConnection, newFarm.getTeamId(), companyId, theFarmName, farmLocation, theCreatorFullName);
boolean resultAssignPermissions = assignToFarmTheCompanyPermissions(groupId, companyId, newFarm.getTeamId());
if (! (resultInsert && resultAssignPermissions) ) {
renderErrorPage(actionRequest, actionResponse);
}
}
else
renderErrorPage(actionRequest, actionResponse);
}
else
renderErrorPage(actionRequest, actionResponse);
} catch (Exception e) {
e.printStackTrace();
renderErrorPage(actionRequest, actionResponse);
}
}
/**
*
* @param groupId
* @return the layout objects of the pages for the phases enabled for a given company (e.g. phases: Hatchery, Growout)
* @throws Exception
*/
private List<Layout> getCompanyEnabledPhasesLayout(long groupId, long companyTeamId) throws Exception {
List<Layout> toReturn = new ArrayList<>();
List<Layout> all3phases = new ArrayList<>();
List<Layout> pages = LayoutServiceUtil.getLayouts(groupId, true);
for (Layout layout : pages) {
if (layout.getFriendlyURL().equalsIgnoreCase(PFISHConstants.GROWOUT_PAGE_LAYOUT_FRIENDLY_URL) ||
layout.getFriendlyURL().equalsIgnoreCase(PFISHConstants.HATCHERY_PAGE_LAYOUT_FRIENDLY_URL) ||
layout.getFriendlyURL().equalsIgnoreCase(PFISHConstants.PREGROW_PAGE_LAYOUT_FRIENDLY_URL)) {
all3phases.add(layout);
}
}
final long defaultCompanyId = PortalUtil.getDefaultCompanyId();
Role teamRoleCompany = RoleLocalServiceUtil.getTeamRole(defaultCompanyId, companyTeamId);
List<ResourcePermission> rPermissions = ResourcePermissionLocalServiceUtil.getRoleResourcePermissions(teamRoleCompany.getRoleId());
for (Layout layout : all3phases) {
for (ResourcePermission rp : rPermissions) {
if (layout.getPrimaryKey() == Long.parseLong(rp.getPrimKey()) && rp.getActionIds() == 1) { //tha actiondId has to be 1
toReturn.add(layout);
}
}
}
return toReturn;
}
/**
*
* @param groupId
* @param companyTeamId
* @param farmTeamId
* @return
*/
private boolean assignToFarmTheCompanyPermissions(long groupId, long companyTeamId, long farmTeamId) {
try {
final long defaultCompanyId = PortalUtil.getDefaultCompanyId();
List<Layout> layoutCompanyPhases = getCompanyEnabledPhasesLayout(groupId, companyTeamId);
Role teamRoleFarm = RoleLocalServiceUtil.getTeamRole(defaultCompanyId, farmTeamId);
for (Layout phase : layoutCompanyPhases) {
_log.info("setting Resource Permissions for farm with id = " + farmTeamId);
ResourcePermissionLocalServiceUtil.setResourcePermissions(
defaultCompanyId, Layout.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, String.valueOf(phase.getPrimaryKey()), teamRoleFarm.getRoleId(),
new String[] { ActionKeys.VIEW });
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private void renderErrorPage(ActionRequest actionRequest, ActionResponse actionResponse) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", PFISHConstants.OPERATION_ERROR_PATH);
}
private void renderErrorPageFarmExistAlready(ActionRequest actionRequest, ActionResponse actionResponse) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", PFISHConstants.FARM_NAME_ALREADY_EXIST_ERROR_PATH);
}
}

@ -0,0 +1,81 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.gcube.portlets.user.performfish.bean.CompanyMember;
import org.gcube.portlets.user.performfish.util.PFISHConstants;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class PromoteCompanyAdministrators
*/
public class PromoteCompanyAdministrators extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(PromoteCompanyAdministrators.class);
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.debug(" This is render method of PromoteCompanyAdministrators");
try {
long groupId = PortalUtil.getScopeGroupId(request);
GCubeTeam theTeam = Utils.checkBelongingToOneCompanyOnly(request, response, this);
request.setAttribute("theTeam", TeamLocalServiceUtil.getTeam(theTeam.getTeamId()));
if (theTeam != null && Utils.isCompanyAdmin(Utils.getCurrentUser(request), groupId, theTeam)) { //check is Admin
//check folder exists
Utils.getWSCompanyFolder(Utils.getCurrentUser(request).getUsername(), Utils.getCurrentContext(request), theTeam);
List<CompanyMember> companyAdmins = Utils.getCompanyAdminTeamMembers(theTeam.getTeamId(), theTeam.getGroupId());
request.setAttribute("companyAdmins", companyAdmins); //pass to the JSP
String imageUrl = Utils.getCompanyLogoURL(theTeam.getTeamName(), groupId, request);
request.setAttribute("companyLogoURL", imageUrl); //pass to logo URL to the JSP
//display the view.jsp
super.render(request, response);
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_ADMIN_PAGE_PATH);
dispatcher.include(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void promoteAdminUsers(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
try {
long[] userIdsToPromoteAdmins = ParamUtil.getLongValues(actionRequest, "addUserIds");
long currentGroupId = ParamUtil.getLong(actionRequest, "currentGroupId");
LiferayRoleManager rm = new LiferayRoleManager();
GCubeRole adminRole = new LiferayRoleManager().getRole(PFISHConstants.COMPANY_ADMIN_SITE_ROLE, currentGroupId);
for (int i = 0; i < userIdsToPromoteAdmins.length; i++) {
rm.assignRoleToUser(userIdsToPromoteAdmins[i], currentGroupId, adminRole.getRoleId());
_log.info("Associating Admin role to user with id " + userIdsToPromoteAdmins[i] + " done");
}
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
}

@ -0,0 +1,92 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.http.HttpServletRequest;
import org.gcube.portlets.user.performfish.util.PFISHConstants;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class PromoteFarmAdministrators
*/
public class PromoteFarmAdministrators extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(PromoteFarmAdministrators.class);
private static RoleManager RM = new LiferayRoleManager();
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.debug(" This is render method of PromoteFarmAdministrators");
try {
long groupId = PortalUtil.getScopeGroupId(request);
GCubeTeam theCompany = Utils.checkBelongingToOneCompanyOnly(request, response, this);
HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
//long[] farmIds = ParamUtil.getLongValues(httpReq, "farmId");
String[] farmIds = ParamUtil.getParameterValues(httpReq, Utils.ENCODED_FARM_PARAM);
GCubeTeam theFarm = null;
if (farmIds != null && farmIds.length > 0) {
long selectedFarmId = Utils.unmaskId(farmIds[0]);
theFarm = RM.getTeam(selectedFarmId);
request.getPortletSession().setAttribute("theFarm", theFarm);
} else {
theFarm = (GCubeTeam) request.getPortletSession().getAttribute("theFarm");
}
if (theFarm != null && Utils.isFarmAdmin(Utils.getCurrentUser(request), groupId, theFarm)) { //check is a Farm Admin
//check folder exists
Utils.getWSCompanyFolder(Utils.getCurrentUser(request).getUsername(), Utils.getCurrentContext(request), theFarm);
List<GCubeUser> companyAdmins = Utils.getFarmAdminTeamMembers(theCompany, theFarm);
request.setAttribute("companyAdmins", companyAdmins); //pass to the JSP
request.setAttribute("theFarm", theFarm); //pass to the JSP
String imageUrl = Utils.getCompanyLogoURL(theCompany.getTeamName(), groupId, request);
request.setAttribute("companyLogoURL", imageUrl); //pass to logo URL to the JSP
//display the view.jsp
super.render(request, response);
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_FARM_ADMIN_PAGE_PATH);
dispatcher.include(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void promoteAdminUsers(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
try {
long[] userIdsToPromoteAdmins = ParamUtil.getLongValues(actionRequest, "addUserIds");
long currentGroupId = ParamUtil.getLong(actionRequest, "currentGroupId");
LiferayRoleManager rm = new LiferayRoleManager();
GCubeRole adminRole = new LiferayRoleManager().getRole(PFISHConstants.FARM_ADMIN_SITE_ROLE, currentGroupId);
for (int i = 0; i < userIdsToPromoteAdmins.length; i++) {
rm.assignRoleToUser(userIdsToPromoteAdmins[i], currentGroupId, adminRole.getRoleId());
_log.info("Associating Admin role to user with id " + userIdsToPromoteAdmins[i] + " done");
}
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
}

@ -0,0 +1,131 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;
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.portlets.user.performfish.bean.Company;
import org.gcube.portlets.user.performfish.util.PFISHConstants;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.portlets.user.performfish.util.db.DBUtil;
import org.gcube.portlets.user.performfish.util.db.DatabaseConnection;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.model.Team;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
//TODO check why it gives error when the company administrator is set
/**
* Portlet implementation class SetCompanyAdministratorsSuperUser
*/
public class SetCompanyAdministratorsSuperUser extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(PromoteCompanyAdministrators.class);
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.debug(" This is render method of SetCompanyAdministratorsSuperUser");
try {
long groupId = PortalUtil.getScopeGroupId(request);
HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
long[] companyIds = ParamUtil.getLongValues(httpReq, "companyId");
if (companyIds.length > 0) { //super user mode
Team theTeam = TeamLocalServiceUtil.getTeam(companyIds[0]);
request.setAttribute("theTeam", theTeam);
List<GCubeUser> availableUsers = Utils.listVREUsersNotAssociatedToAnyCompany(theTeam.getTeamId(), theTeam.getGroupId());
request.setAttribute("availableUsers", availableUsers); //pass to the JSP
String imageUrl = Utils.getCompanyLogoURL(theTeam.getName(), groupId, request);
request.setAttribute("companyLogoURL", imageUrl); //pass to logo URL to the JSP
request.setAttribute("operationFinished", false);
//display the view.jsp
super.render(request, response);
} else {
request.setAttribute("operationFinished", true);
super.render(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void promoteAdminUsers(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
try {
long[] userIdsToPromoteAdmins = ParamUtil.getLongValues(actionRequest, "addUserIds");
long currentGroupId = ParamUtil.getLong(actionRequest, "currentGroupId");
long companyId = ParamUtil.getLong(actionRequest, "companyId");
LiferayRoleManager rm = new LiferayRoleManager();
GCubeRole adminRole = new LiferayRoleManager().getRole(PFISHConstants.COMPANY_ADMIN_SITE_ROLE, currentGroupId);
for (int i = 0; i < userIdsToPromoteAdmins.length; i++) {
rm.assignRoleToUser(userIdsToPromoteAdmins[i], currentGroupId, adminRole.getRoleId());
_log.info("Associating Admin role to user with id " + userIdsToPromoteAdmins[i] + " done");
rm.assignTeamToUser(userIdsToPromoteAdmins[i], companyId); //add the Admin to the Company
}
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
// /**
// *
// * @param actionRequest
// * @param actionResponse
// * @throws Exception
// */
// public void associateCompanyUsers(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
// try {
// long[] userIdsToPromoteAdmins = ParamUtil.getLongValues(actionRequest, "addUserIds");
// System.out.println("userIdsToPromoteAdmins length=" + userIdsToPromoteAdmins.length);
// String[] usernamesToAssociateToCompany = new String[userIdsToPromoteAdmins.length];
// _log.debug("converting userIds in usernames");
// for (int i = 0; i < userIdsToPromoteAdmins.length; i++) {
// usernamesToAssociateToCompany[i] = UserLocalServiceUtil.getUser(userIdsToPromoteAdmins[i]).getScreenName();
// }
// long companyId = ParamUtil.getLong(actionRequest, "companyId");
// String currentUsername = ParamUtil.getString(actionRequest, "currentUsername");
// long currentGroupId = ParamUtil.getLong(actionRequest, "currentGroupId");
// String context = Utils.getCurrentContext(currentGroupId);
// _log.info("Super User: " + currentUsername + " has requested the association of some user(s) to the company having id="+companyId + " in context="+context);
// LiferayRoleManager rm = new LiferayRoleManager();
// LiferayUserManager um = new LiferayUserManager();
// long firstUserId = um.getUserByUsername(usernamesToAssociateToCompany[0]).getUserId();
// rm.setUserTeams(firstUserId, new long[]{companyId}); //add the admin to the company
// if (usernamesToAssociateToCompany.length > 1) { //more than one admin was selected
// String[] remainingUsersToShare = new String[usernamesToAssociateToCompany.length-1];
// for (int i = 1; i < usernamesToAssociateToCompany.length; i++) {
// remainingUsersToShare[i-1] = usernamesToAssociateToCompany[i];
// }
//
// }
// }
// catch (Exception e) {
// SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
// actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
// e.printStackTrace();
// }
//
// }
}

@ -0,0 +1,90 @@
package org.gcube.portlets.user.performfish;
import java.io.IOException;
import java.util.List;
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.portlets.user.performfish.util.PFISHConstants;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.model.Team;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class SetFarmAdministrators
*/
public class SetFarmAdministrators extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(SetFarmAdministrators.class);
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
_log.debug(" This is render method of SetFarmAdministrators");
try {
long groupId = PortalUtil.getScopeGroupId(request);
HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
long[] companyIds = ParamUtil.getLongValues(httpReq, "companyId");
long[] farmIds = ParamUtil.getLongValues(httpReq, "farmId");
if (companyIds.length > 0 && farmIds.length > 0) { //super user mode
Team theCompany = TeamLocalServiceUtil.getTeam(companyIds[0]);
Team theFarm = TeamLocalServiceUtil.getTeam(farmIds[0]);
request.setAttribute("theCompany", theCompany);
request.setAttribute("theFarm", theFarm);
List<GCubeUser> availableUsers = Utils.getAvailableFarmMembersToAssociate(theFarm.getTeamId(), theCompany.getTeamId(), theCompany.getGroupId());
request.setAttribute("availableUsers", availableUsers); //pass to the JSP
String imageUrl = Utils.getCompanyLogoURL(theCompany.getName(), groupId, request);
request.setAttribute("companyLogoURL", imageUrl); //pass to logo URL to the JSP
request.setAttribute("operationFinished", false);
//display the view.jsp
super.render(request, response);
} else {
request.setAttribute("operationFinished", true);
super.render(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void promoteAdminUsers(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
try {
long[] userIdsToPromoteAdmins = ParamUtil.getLongValues(actionRequest, "addUserIds");
long currentGroupId = ParamUtil.getLong(actionRequest, "currentGroupId");
long farmId = ParamUtil.getLong(actionRequest, "farmId");
Team theFarm = TeamLocalServiceUtil.getTeam(farmId);
LiferayRoleManager rm = new LiferayRoleManager();
GCubeRole adminRole = new LiferayRoleManager().getRole(PFISHConstants.FARM_ADMIN_SITE_ROLE, currentGroupId);
for (int i = 0; i < userIdsToPromoteAdmins.length; i++) {
rm.assignRoleToUser(userIdsToPromoteAdmins[i], currentGroupId, adminRole.getRoleId());
_log.info("Associating Farm Admin role to user with id " + userIdsToPromoteAdmins[i] + " done");
rm.assignTeamToUser(userIdsToPromoteAdmins[i], theFarm.getTeamId()); //add the Admin to the farm
_log.info("Associating user with id " + userIdsToPromoteAdmins[i] + " to Farm done");
}
}
catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),"operation-error");
actionResponse.setRenderParameter("mvcPath", "/html/error_pages/operation-error.jsp");
e.printStackTrace();
}
}
}

@ -0,0 +1,334 @@
package org.gcube.portlets.user.performfish;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
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.folder.items.ExternalFile;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.utils.XPathHelper;
import org.gcube.portlets.user.performfish.util.Utils;
import org.gcube.portlets.user.performfish.util.ValidationResult;
import org.gcube.portlets.user.performfish.util.db.DBUtil;
import org.gcube.portlets.user.performfish.util.db.DatabaseConnection;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.service.TeamLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class SubmittedFormValidation
*/
public class SubmittedFormValidation extends MVCPortlet {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(SubmittedFormValidation.class);
private final static String XSLX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
private static final int RETRY_NO = 3;
private static String XML_RESULT_ROOT_EXCEPTION = "ExceptionReport";
private static final String USER_AGENT = "Mozilla/5.0";
public static final String VALIDATOR_METHOD_ID = "org.gcube.dataanalysis.wps.statisticalmanager.synchserver.mappedclasses.transducerers.PERFORMFISH_DATA_VALIDATOR_V2";
public void render(RenderRequest request, RenderResponse response) {
GCubeTeam theCompany;
try {
HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
String[] farmIds = ParamUtil.getParameterValues(httpReq, Utils.ENCODED_FARM_PARAM);
GCubeTeam theFarm = null;
theCompany = Utils.checkBelongingToOneCompanyOnly(request, response, this);
if (farmIds == null || farmIds.length == 0) {
System.out.println("farmIds == null || farmIds.length == 0");
if (Utils.getUserFarmsNumber(request, response, this) < 2) {
theFarm = Utils.checkBelongingToOneFarmOnly(request, response, this);
request.setAttribute("theFarm", theFarm); //pass to the JSP
}
}
else { //the farmId is passed via param on the query string
long selectedFarmId = Utils.unmaskId(farmIds[0]);
theFarm = new LiferayRoleManager().getTeam(selectedFarmId);
if (Utils.checkBelongsToTeam(PortalUtil.getUserId(request), theFarm.getTeamId(), PortalUtil.getScopeGroupId(request)) ) {//check that the user belong ot the farm
request.setAttribute("theFarm", theFarm); //pass to the JSP
}
else {
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_BELONGING_ANY_FARM_PAGE_PATH);
dispatcher.include(request, response);
}
}
if (theFarm != null) {
request.setAttribute("theCompany", TeamLocalServiceUtil.getTeam(theCompany.getTeamId()));
request.setAttribute("theFarm", theFarm);
super.render(request, response);
} else {
_log.warn("theFarm is null");
super.render(request, response);
}
} catch (Exception e) {
e.printStackTrace();
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(Utils.NOT_BELONGING_ANY_FARM_PAGE_PATH);
try {
dispatcher.include(request, response);
} catch (PortletException | IOException e1) {
e1.printStackTrace();
}
}
}
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException {
long companyId = ParamUtil.getLong(resourceRequest, "companyId");
long farmId = ParamUtil.getLong(resourceRequest, "farmId");
long userId = ParamUtil.getLong(resourceRequest, "userId");
long groupId = ParamUtil.getLong(resourceRequest, "groupId");
String encodedURI = ParamUtil.getString(resourceRequest, "encodedURI", null);
String fileName = ParamUtil.getString(resourceRequest, "fileName", null);
String username = Utils.getCurrentUser(userId).getUsername();
String phase = ParamUtil.getString(resourceRequest, "phase", null);
_log.debug("companyId: " + companyId);
_log.debug("farmId: " + farmId);
_log.debug("userId: " + userId);
_log.debug("groupId: " + groupId);
_log.debug("encodedURI: " + encodedURI);
_log.debug("phase: " + phase);
_log.debug("fileName: " + fileName);
String inputFileLink = encodedURI;
String template = Utils.getBatchTypeName(phase, fileName);
String context = Utils.getCurrentContext(groupId);
String token = Utils.getCurrentUserToken(context, username);
_log.debug("context: " + context);
_log.debug("token: " + token);
_log.debug("template: " + template);
ValidationResult result = doWPSCallToDataMiner(inputFileLink, context, token, template);
_log.debug("RESULT:\n"+result);
if (result.isSuccess()) {
try {
String decodedURL = new java.net.URI(inputFileLink).getPath();
uploadToCompanyRepository(username, context, companyId, farmId, fileName, new URL(decodedURL).openConnection().getInputStream());
Connection conn = DatabaseConnection.getInstance(Utils.getCurrentContext(groupId)).getConnection();
java.sql.Date lastActivity = new java.sql.Date(new Date().getTime());
DBUtil.updateFarmLastSubmissionActivity(conn, farmId, lastActivity);
} catch (Exception e) {
result.setComment("The file is valid but we could not upload it in the company repository, please report this issue at support.d4science.org");
e.printStackTrace();
}
}
JSONObject fileObject = JSONFactoryUtil.createJSONObject();
fileObject.put("success", result.isSuccess());
fileObject.put("comment", result.getComment());
resourceResponse.getWriter().println(fileObject);
}
private String uploadToCompanyRepository(String username, String context, long companyId, long farmId, String fileName, InputStream fileData) throws Exception {
GCubeTeam theCompany = new LiferayRoleManager().getTeam(companyId);
GCubeTeam theFarm = new LiferayRoleManager().getTeam(farmId);
Workspace ws = Utils.getWS(username, context);
WorkspaceFolder companyRepoFolder = Utils.getWSFarmFolder(username, context, theCompany, theFarm);
WorkspaceItem overwriteItem = ws.find(fileName, companyRepoFolder.getId());
String toReturn = "";
if (overwriteItem == null) {
ExternalFile item = companyRepoFolder.createExternalFileItem(fileName, "User form submission on " + new Date(), XSLX_MIME, fileData);
toReturn = item.getId();
}
else {
ws.updateItem(overwriteItem.getId(), fileData);
toReturn = overwriteItem.getId();
_log.debug("updateItem with id: "+overwriteItem.getId()+ ", is completed");
}
_log.info("Uploaded " + fileName + " - Returned Workspace id=" +toReturn);
return toReturn;
}
/**
* performs tha actual call to the service
* @param peer session
* @param entry authEntry
* @param token token
* @param username username
* @param inputText
* @param options
* @return
*/
private ValidationResult doWPSCallToDataMiner(String inputFileLink, String context, String token, String template) {
_log.info("doWPSCallToDataMiner");
ValidationResult toReturn = null;
List<ServiceEndpoint> dms = null;
try {
dms = Utils.getDataMinerInstance(context);
if (dms == null || dms.isEmpty()) {
return new ValidationResult(false, "Error, no DataMiner cluster in this VRE, please report this issue at www.d4science.org/contact-us");
}
ServiceEndpoint se = dms.get(0);
ServiceEndpoint.AccessPoint ap = se.profile().accessPoints().asCollection().iterator().next();
_log.info("got DataMiner instance="+ap.address());
String apAddress = ap.address();
_log.info("inputFileLink at: " + inputFileLink);
String wpsParams = getWPSCallURLParameters(token, inputFileLink, template);
String responseXML = sendGet(apAddress, wpsParams, token);
String resultFileURL = parseResult(responseXML);
_log.info("PARSED OK resultFileURL: " + resultFileURL);
InputStream is = new URL(resultFileURL).openConnection().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
List<String> resultLines = new ArrayList<>();
while ((line = reader.readLine()) != null) {
if (line.split("=").length > 1)
resultLines.add(line.split("=")[1]); //if the split fails it means there is no comment
else
resultLines.add("Validation is successful");
}
reader.close();
for (int i = 0; i < resultLines.size(); i++) {
_log.debug("Line " + i + ": " + resultLines.get(i));
}
toReturn = new ValidationResult(resultLines.get(0).equalsIgnoreCase("OK"), resultLines.get(1));
} catch (Exception e) {
e.printStackTrace();
return new ValidationResult(false, "There was a problem contacting the DataMiner cluster in this VRE ("
+ context+ ")"
+ "), please report this issue at http://support.d4science.org");
}
return toReturn;
}
private String parseResult(String xml) throws Exception {
String elem = removeXmlStringNamespaceAndPreamble(xml);
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement();
String rootElement = node.getNodeName();
XPathHelper helper = new XPathHelper(node);
List<String> currValue = null;
if (rootElement.compareTo(XML_RESULT_ROOT_EXCEPTION) == 0) {
currValue = helper.evaluate("/ExceptionReport");
if (currValue != null && currValue.size() > 0)
return currValue.get(0);
}
else {
currValue = helper.evaluate("//ProcessOutputs/Output/Data/ComplexData/FeatureCollection/featureMember/Result/Data/text()");
if (currValue != null && currValue.size() > 1)
return currValue.get(1);
}
return null;
}
//this remove all the namespaces causing parsing errors as i don't have time to deal with this.
private static String removeXmlStringNamespaceAndPreamble(String xmlString) {
return xmlString.replaceAll("(<\\?[^<]*\\?>)?", "") /* remove preamble */
.replaceAll("xmlns.*?(\"|\').*?(\"|\')", "") /* remove xmlns declaration */
.replaceAll("(<)(\\w+:)(.*?>)", "$1$3") /* remove opening tag prefix */
.replaceAll("(</)(\\w+:)(.*?>)", "$1$3")
.replaceAll("wps:", "")
.replaceAll("xsi:", "")
.replaceAll("ogr:",""); /* remove closing tags prefix */
}
// HTTP request
private String sendGet(String url, String urlParameters, String token) {
StringBuilder toReturn = new StringBuilder();
try {
int i = 1;
while (i <= RETRY_NO) {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(url+"?"+urlParameters);
_log.info("request to="+request.toString());
// add header
request.setHeader("User-Agent", USER_AGENT);
request.setHeader("Accept-Encoding","UTF-8");
request.setHeader("Accept-Charset","UTF-8");
request.setHeader("Content-Encoding","UTF-8");
HttpResponse response = client.execute(request);
// Get the response
BufferedReader rd = new BufferedReader
(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
toReturn.append(line);
}
i++;
if (toReturn.toString().compareTo("") == 0 || toReturn.toString().startsWith("Error")) {
_log.warn("response from Dataminer is empty or an error occurred, retry tentative: " + i + " of " + RETRY_NO);
_log.error("here is the faulty response from Dataminer="+toReturn.toString());
} else {
_log.debug("response from Dataminer="+toReturn.toString());
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return toReturn.toString();
}
/**
*
* @param token the token
* @param inputFileLink the http of the input file
* @param options
* @return the url paramters for WPS Call to perform
*/
private String getWPSCallURLParameters(String token, String inputFileLink, String template) {
StringBuilder sb = new StringBuilder("request=Execute&service=WPS&Version=1.0.0&gcube-token=")
.append(token)
.append("&lang=en-US&Identifier=")
.append(VALIDATOR_METHOD_ID)
.append("&DataInputs=CompanyData=")
.append(inputFileLink)
.append(";Template=")
.append(template)
.append(";")
.append("Overwrite=false;LatestCompanyData=")
.append(inputFileLink)
.append(";");
return sb.toString();
}
}

@ -0,0 +1,99 @@
package org.gcube.portlets.user.performfish.bean;
import java.util.Date;
public class Association {
private long associationId;
private String shortName;
private String fullName;
private String imageUrl;
private Date dateCreated;
private String createdBy;
public Association(long associationId, String createdBy) {
super();
this.associationId = associationId;
this.createdBy = createdBy;
}
public Association() {
super();
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public long getAssociationId() {
return associationId;
}
public void setAssociationId(long associationId) {
this.associationId = associationId;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Association [associationId=");
builder.append(associationId);
builder.append(", shortName=");
builder.append(shortName);
builder.append(", fullName=");
builder.append(fullName);
builder.append(", imageUrl=");
builder.append(imageUrl);
builder.append(", dateCreated=");
builder.append(dateCreated);
builder.append(", createdBy=");
builder.append(createdBy);
builder.append("]");
return builder.toString();
}
}

@ -0,0 +1,77 @@
package org.gcube.portlets.user.performfish.bean;
public class Company {
private long companyId;
private String name;
private long associatationId;
private String imageUrl;
private boolean staged;
public Company(long companyId, long associatationId, boolean staged) {
super();
this.companyId = companyId;
this.associatationId = associatationId;
this.staged = staged;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public long getCompanyId() {
return companyId;
}
public void setCompanyId(long companyId) {
this.companyId = companyId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getAssociatationId() {
return associatationId;
}
public void setAssociatationId(long associatationId) {
this.associatationId = associatationId;
}
public boolean isStaged() {
return staged;
}
public void setStaged(boolean staged) {
this.staged = staged;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Company [companyId=");
builder.append(companyId);
builder.append(", name=");
builder.append(name);
builder.append(", associatationId=");
builder.append(associatationId);
builder.append(", imageUrl=");
builder.append(imageUrl);
builder.append(", staged=");
builder.append(staged);
builder.append("]");
return builder.toString();
}
}

@ -0,0 +1,90 @@
package org.gcube.portlets.user.performfish.bean;
import java.util.ArrayList;
import java.util.List;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
public class CompanyMember {
private GCubeUser user;
private List<Farm> associatedFarms = new ArrayList<>();
private boolean isAdmin;
public CompanyMember(GCubeUser user) {
super();
this.user = user;
}
public boolean isAdmin() {
return isAdmin;
}
public void setAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}
public GCubeUser getUser() {
return user;
}
public void setUser(GCubeUser user) {
this.user = user;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CompanyMember [user=");
builder.append(user);
builder.append(", associatedFarms=");
builder.append(associatedFarms);
builder.append(", isAdmin=");
builder.append(isAdmin);
builder.append("]");
return builder.toString();
}
public List<Farm> getAssociatedFarms() {
return associatedFarms;
}
public String getAssociatedFarmNames() {
String toReturn = "";
for (Farm farm : associatedFarms) {
toReturn += " " + farm.getName();
}
return toReturn;
}
public void setAssociatedFarms(List<Farm> associatedFarms) {
this.associatedFarms = associatedFarms;
}
public String getUserAvatarURL() {
return this.user.getUserAvatarURL();
}
public String getjobTitle() {
return this.user.getJobTitle();
}
public String getFullname() {
return this.user.getFullname();
}
public long getUserId() {
return this.user.getUserId();
}
public String getUsername() {
return this.user.getUsername();
}
public String getEmail() {
return this.user.getEmail();
}
public void setEmail(String email) {
this.user.setEmail(email);
}
}

@ -0,0 +1,126 @@
package org.gcube.portlets.user.performfish.bean;
import java.util.Date;
import java.util.List;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
public class Farm {
private long farmId;
private String name;
private long companyId;
private String creatorFullname;
private String imageUrl;
private String location;
private Date dateCreated;
private Date dateLastActivity;
private List<GCubeUser> administrators;
public Farm(long farmId, String location, long companyId, String creatorFullname) {
super();
this.farmId = farmId;
this.location = location;
this.companyId = companyId;
this.creatorFullname = creatorFullname;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public String getCreatorFullname() {
return creatorFullname;
}
public void setCreatorFullname(String creatorFullname) {
this.creatorFullname = creatorFullname;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public long getFarmId() {
return farmId;
}
public void setFarmId(long farmId) {
this.farmId = farmId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getCompanyId() {
return companyId;
}
public void setCompanyId(long companyId) {
this.companyId = companyId;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public List<GCubeUser> getAdministrators() {
return administrators;
}
public void setAdministrators(List<GCubeUser> administrators) {
this.administrators = administrators;
}
public Date getDateLastActivity() {
return dateLastActivity;
}
public void setDateLastActivity(Date dateLastActivity) {
this.dateLastActivity = dateLastActivity;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Farm [farmId=");
builder.append(farmId);
builder.append(", name=");
builder.append(name);
builder.append(", companyId=");
builder.append(companyId);
builder.append(", creatorFullname=");
builder.append(creatorFullname);
builder.append(", imageUrl=");
builder.append(imageUrl);
builder.append(", location=");
builder.append(location);
builder.append(", dateCreated=");
builder.append(dateCreated);
builder.append(", dateLastActivity=");
builder.append(dateLastActivity);
builder.append(", administrators=");
builder.append(administrators);
builder.append("]");
return builder.toString();
}
}

@ -0,0 +1,89 @@
package org.gcube.portlets.user.performfish.bean;
import com.liferay.portal.kernel.json.JSONObject;
public class PublishAnonymisedJob {
//STATUSES ACCEPTED, RUNNING, COMPLETE, FAILED, CANCELLED
public static Long EPOCH_TIME_JOB_NOTFINISHED = 3050596467L; //September 1, 2066, Likely retired or dead by then
private String jobId;
private String farmId;
private String batch_type;
private String sourceUrl;
private String status;
private String submitterIdentity;
private Long endTimeepochSecond;
public PublishAnonymisedJob(JSONObject cData) {
this.jobId=cData.getString("id");
this.farmId=cData.getString("farmId");
this.batch_type=cData.getString("batch_type");
this.sourceUrl=cData.getString("sourceUrl");
this.status=cData.getString("status");
this.submitterIdentity=cData.getString("submitterIdentity");
if (cData.getJSONObject("endTime") != null) //if there is no end time the status is not COMPLETE
this.endTimeepochSecond=cData.getJSONObject("endTime").getLong("epochSecond");
else
this.endTimeepochSecond = EPOCH_TIME_JOB_NOTFINISHED;
}
public String getJobId() {
return jobId;
}
public String getFarmId() {
return farmId;
}
public String getBatch_type() {
return batch_type;
}
public String getSourceUrl() {
return sourceUrl;
}
public String getStatus() {
return status;
}
public String getSubmitterIdentity() {
return submitterIdentity;
}
public Long getEndTimeEpochSecond() {
return endTimeepochSecond;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("PublishAnonymisedJob [jobId=");
builder.append(jobId);
builder.append(", farmId=");
builder.append(farmId);
builder.append(", batch_type=");
builder.append(batch_type);
builder.append(", sourceUrl=");
builder.append(sourceUrl);
builder.append(", status=");
builder.append(status);
builder.append(", submitterIdentity=");
builder.append(submitterIdentity);
builder.append(", endTime=");
builder.append(endTimeepochSecond);
builder.append("]");
return builder.toString();
}
}

@ -0,0 +1,98 @@
package org.gcube.portlets.user.performfish.bean;
import java.io.Serializable;
import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile;
import org.gcube.portlets.user.performfish.util.Utils;
@SuppressWarnings("serial")
public class SubmittedForm implements Serializable {
public static String NOT_YET_PUBLISHER = "No one";
private static String UNPUBLISHED_LABEL = "Unpublished";
private static String SUBMITTER_NONE = null;
private ExternalFile file;
private String status;
private String submitterIdentity;
private long endTimeinMillis = -1;
public SubmittedForm() {
this.status = UNPUBLISHED_LABEL;
this.submitterIdentity = SUBMITTER_NONE;
}
public SubmittedForm(ExternalFile file, String status, String submitterIdentity, long endTimeinMillis) {
super();
this.file = file;
this.status = status;
this.submitterIdentity = submitterIdentity;
this.endTimeinMillis = endTimeinMillis;
}
public SubmittedForm(ExternalFile file) {
super();
this.file = file;
this.status = UNPUBLISHED_LABEL;
this.submitterIdentity = SUBMITTER_NONE;
this.endTimeinMillis = -1;
}
public String getBatchType() {
String batchType = "unknown";
try {
batchType = Utils.getBatchTypeName(Utils.getPhaseByFileName(this.file.getName()), this.file.getName());
} catch (Exception e) {
e.printStackTrace();
}
return batchType;
}
public ExternalFile getFormFile() {
return file;
}
public void setFormFile(ExternalFile file) {
this.file = file;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSubmitterIdentity() {
return submitterIdentity;
}
public void setSubmitterIdentity(String submitterIdentity) {
this.submitterIdentity = submitterIdentity;
}
public long getEndTimeinMillis() {
return endTimeinMillis;
}
public void setEndTimeinMillis(long endTimeinMillis) {
this.endTimeinMillis = endTimeinMillis;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("SubmittedForm [file=");
builder.append(file);
builder.append(", status=");
builder.append(status);
builder.append(", submitterIdentity=");
builder.append(submitterIdentity);
builder.append(", endTimeinMillis=");
builder.append(endTimeinMillis);
builder.append("]");
return builder.toString();
}
}

@ -0,0 +1,182 @@
package org.gcube.portlets.user.performfish.util;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.IOUtils;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.common.resources.gcore.GenericResource;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import com.liferay.portal.kernel.log.LogFactoryUtil;
/**
*
* @author F. Sinibaldi CNR-ISTI
* @author M. Assante CNR-ISTI
*/
public class ImportedBatchChecker {
private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(ImportedBatchChecker.class);
private static String ANALYTICAL_TOOLKIT_SERVICE_GCORE_ENDPOINT_NAME = "perform-service";
private static String ANALYTICAL_TOOLKIT_SERVICE_GCORE_ENDPOINT_CLASS = "Application";
private static String CONFIGURATION_RESOURCE_SECONDARY_TYPE="ApplicationConfiguration";
private static String CONFIGURATION_RESOURCE_NAME="PerformFishConfiguration";
private static final int N_BATCHES_THRESHOLD_FALLBACK = 4;
public static boolean checkAnalysisAvailability(long farmid,String batchType, String context) throws JSONException, IOException, KeyManagementException, NoSuchAlgorithmException, NumberFormatException, XPathExpressionException {
fixUntrustCertificate();
String servicecall=formServiceCall(batchType,farmid, context);
JSONObject jsonObject=readFromURL(servicecall);
String csvUrl=jsonObject.getString("BatchesTable_internal");
long csvLines=readCSVLines(csvUrl);
return csvLines-1>getThresholdFromIS();
}
private static int getThresholdFromIS() throws NumberFormatException, XPathExpressionException {
try {
SimpleQuery query = queryFor(GenericResource.class);
query.addCondition("$resource/Profile/SecondaryType/text() eq '"+ CONFIGURATION_RESOURCE_SECONDARY_TYPE+"'");
query.addCondition("$resource/Profile/Name/text() eq '"+ CONFIGURATION_RESOURCE_NAME+"'");
DiscoveryClient<GenericResource> client = clientFor(GenericResource.class);
String xmlConfiguration=client.submit(query).get(0).profile().bodyAsString();
InputSource source = new InputSource(new StringReader(xmlConfiguration));
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
return Integer.parseInt(xpath.evaluate("//config/analysis_threshold/text()", source));
}
catch (Exception e) {
_log.error("There was an error contacting the IS for reading the Batch threshold, returning fallback value="+N_BATCHES_THRESHOLD_FALLBACK, e);
return N_BATCHES_THRESHOLD_FALLBACK;
}
}
private static String formServiceCall(String batchtype, long farmid, String context) {
return new StringBuilder(Utils.getAnalyticalToolkitEndpoint(context))
.append("/performance")
.append("?")
.append("batch_type=").append(batchtype)
.append("&gcube-token="+SecurityTokenProvider.instance.get())
.append("&farmid=").append(farmid).toString();
}
private static long readCSVLines(String csvUrl) throws IOException {
URL url= new URL(csvUrl);
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( true );
conn.setRequestMethod( "GET" );
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
int lines = 0;
while (reader.readLine() != null) lines++;
reader.close();
return lines;
}
private static JSONObject readFromURL(String request) throws IOException, JSONException {
URL url= new URL(request);
HttpsURLConnection conn= (HttpsURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "GET" );
conn.setRequestProperty( "Content-Type", "application/json");
conn.setRequestProperty( "charset", "utf-8");
conn.setUseCaches( false );
InputStream in = conn.getInputStream();
String encoding = conn.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
return new JSONObject(body);
}
private static void fixUntrustCertificate() throws KeyManagementException, NoSuchAlgorithmException{
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws CertificateException {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// set the allTrusting verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
public static List<GCoreEndpoint> getAnalyticalToolkitServiceInstance() throws Exception {
SimpleQuery query = queryFor(GCoreEndpoint.class);
query.addCondition("$resource/Profile/ServiceClass/text() eq '"+ ANALYTICAL_TOOLKIT_SERVICE_GCORE_ENDPOINT_CLASS +"'");
query.addCondition("$resource/Profile/ServiceName/text() eq '"+ ANALYTICAL_TOOLKIT_SERVICE_GCORE_ENDPOINT_NAME +"'");
DiscoveryClient<GCoreEndpoint> client = clientFor(GCoreEndpoint.class);
List<GCoreEndpoint> toReturn = client.submit(query);
return toReturn;
}
// public static void main(String[] args) throws JSONException, IOException, KeyManagementException, NoSuchAlgorithmException, NumberFormatException, XPathExpressionException {
// //SecurityTokenProvider.instance.set("****");
// ScopeProvider.instance.set("/gcube/preprod/preVRE");
// String batchtype="GROW_OUT_INDIVIDUAL";
// long farmid=12682549;
//
// System.out.println("IS ANALYSIS AVAILABLE : "+checkAnalysisAvailability(farmid, batchtype));
// }
}

@ -0,0 +1,85 @@
package org.gcube.portlets.user.performfish.util;
public class PFISHConstants {
/**
* set to true if the private company repo should not appear in the workspace (portlet) of the company users
*/
public static final boolean HIDE_COMPANY_SHARED_FOLDER = true;
/**
*
*/
public static final String SET_COMPANY_ADMINISTRATOR_PORTLETID = "setcompanyadministratorssuperuser_WAR_PerformFISHAppsportlet";
public static final String SET_FARM_ADMINISTRATOR_PORTLETID = "setfarmadministrators_WAR_PerformFISHAppsportlet";
public static final String ASSOCIATE_COMPANIES_TO_ASSOC_PORTLETID = "associatecompaniestoassociation_WAR_PerformFISHAppsportlet";
/**
* The URL (relative) of the Company Dashboard
*/
public static final String COMPANY_DASHBOARD_URL = "company-dashboard";
/**
* The URL (relative) of the Company Farms Dashboard
*/
public static final String FARMS_DASHBOARD_URL = "farm-dashboard";
/**
* The URL (relative) of the From submission pages
*/
public static final String HATCHERY_PAGE_LAYOUT_FRIENDLY_URL = "/hatchery";
public static final String PREGROW_PAGE_LAYOUT_FRIENDLY_URL = "/pre-grow";
public static final String GROWOUT_PAGE_LAYOUT_FRIENDLY_URL = "/grow-out";
/**
* This is the role a company Administrator should have to be interpreted as Administrator by this application
*/
public static final String COMPANY_ADMIN_SITE_ROLE = "Infrastructure-Manager";
/**
* This is the role a company farm Administrator should have to be interpreted as Administrator by this application
*/
public static final String FARM_ADMIN_SITE_ROLE = "Data-Manager";
/**
* These are the 2 coordinates for the Database containing the logic of the app
*/
public static final String PF_DB_SERVICE_ENDPOINT_NAME = "PF_DB";
public static final String PF_DB_SERVICE_ENDPOINT_CATEGORY = "Database";
/**
* used to call the display of a user profile
*/
public static final String USER_PROFILE_OID = "userIdentificationParameter";
/**
* this is the default role of the authorization service
*/
public final static String DEFAULT_ROLE = "OrganizationMember";
/**
* The hidden ws folder suffix automatically created by in the workspace for the compani repositories
*/
public static final String COMPANY_WS_FOLDER_SUFFIX = "_PerformFISH_Data";
/**
* The name of the folder containing the logo of the companies
*/
public static final String LOGO_FOLDER_NAME = "Logo";
/**
* The attribute name for the portlet preference that indicates which phase is displaying
*/
public static final String PHASE_PREFERENCE_ATTR_NAME = "phase";
/**
* And these 4 are the possible values for the attribute above (PHASE_PREFERENCE_ATTR_NAME)
*/
public static final String SHOW_ALL_PHASES = "All";
public static final String SHOW_HATCHERY = "Hatchery";
public static final String SHOW_PRE_ONGROWING = "Pre";
public static final String SHOW_GROW_OUT = "Grow";
/**
* waringin or error pages paths
*/
public static final String OPERATION_ERROR_PATH = "/html/error_pages/operation-error.jsp";
public static final String FARM_NAME_ALREADY_EXIST_ERROR_PATH = "/html/error_pages/farmname_exists_already.jsp";
public static final String TEMPLATE_HATCHERY_INDIVIDUAL = "HATCHERY_INDIVIDUAL";
public static final String TEMPLATE_HATCHERY_AGGREGATED = "HATCHERY_AGGREGATED";
public static final String TEMPLATE_HATCHERY_INDIVIDUAL_CLOSED = "HATCHERY_INDIVIDUAL_CLOSED_BATCHES";
public static final String TEMPLATE_HATCHERY_AGGREGATED_CLOSED = "HATCHERY_AGGREGATED_CLOSED_BATCHES";
public static final String TEMPLATE_PRE_ONGROWING = "PRE_ONGROWING";
public static final String TEMPLATE_PRE_ONGROWING_CLOSED = "PRE_ONGROWING_CLOSED_BATCHES";
public static final String TEMPLATE_GROWOUT_INDIVIDUAL = "GROW_OUT_INDIVIDUAL";
public static final String TEMPLATE_GROWOUT_AGGREGATED = "GROW_OUT_AGGREGATED";
public static final String TEMPLATE_GROWOUT_INDIVIDUAL_CLOSED = "GROW_OUT_INDIVIDUAL_CLOSED_BATCHES";
public static final String TEMPLATE_GROWOUT_AGGREGATED_CLOSED = "GROW_OUT_AGGREGATED_CLOSED_BATCHES";
}

@ -0,0 +1,35 @@
package org.gcube.portlets.user.performfish.util;
public class ValidationResult {
boolean success;
String comment;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public ValidationResult(boolean success, String comment) {
super();
this.success = success;
this.comment = comment;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ValidationResult [success=");
builder.append(success);
builder.append(", comment=");
builder.append(comment);
builder.append("]");
return builder.toString();
}
}

@ -0,0 +1,14 @@
package org.gcube.portlets.user.performfish.util.comparators;
import java.util.Comparator;
import org.gcube.portlets.user.performfish.bean.Association;
public class AssociationComparator implements Comparator<Association> {
@Override
public int compare(Association o1, Association o2) {
return o1.getShortName().compareTo(o2.getShortName());
}
}

@ -0,0 +1,14 @@
package org.gcube.portlets.user.performfish.util.comparators;
import java.util.Comparator;
import org.gcube.portlets.user.performfish.bean.Company;
public class CompanyComparator implements Comparator<Company> {
@Override
public int compare(Company o1, Company o2) {
return o1.getName().compareTo(o2.getName());
}
}

@ -0,0 +1,14 @@
package org.gcube.portlets.user.performfish.util.comparators;
import java.util.Comparator;
import org.gcube.portlets.user.performfish.bean.CompanyMember;
public class CompanyMemberComparator implements Comparator<CompanyMember> {
@Override
public int compare(CompanyMember o1, CompanyMember o2) {
return o1.getUser().getFullname().compareTo(o2.getUser().getFullname());
}
}

@ -0,0 +1,14 @@
package org.gcube.portlets.user.performfish.util.comparators;
import java.util.Comparator;
import org.gcube.portlets.user.performfish.bean.Farm;
public class FarmComparator implements Comparator<Farm> {
@Override
public int compare(Farm o1, Farm o2) {
return o1.getName().compareTo(o2.getName());
}
}

@ -0,0 +1,14 @@
package org.gcube.portlets.user.performfish.util.comparators;
import java.util.Comparator;
import org.gcube.common.homelibary.model.versioning.WorkspaceVersion;
public class FileVersionComparator implements Comparator<WorkspaceVersion> {
@Override
public int compare(WorkspaceVersion o1, WorkspaceVersion o2) {
return o1.getName().compareTo(o2.getName());
}
}

@ -0,0 +1,12 @@
package org.gcube.portlets.user.performfish.util.comparators;
import java.util.Comparator;
import org.gcube.common.storagehub.model.items.GenericFileItem;
public class GenericFileComparator implements Comparator<GenericFileItem> {
@Override
public int compare(GenericFileItem o1, GenericFileItem o2) {
return o1.getName().compareTo(o2.getName());
}
}

@ -0,0 +1,14 @@
package org.gcube.portlets.user.performfish.util.comparators;
import java.util.Comparator;
import org.gcube.vomanagement.usermanagement.model.GCubeTeam;
public class TeamComparator implements Comparator<GCubeTeam> {
@Override
public int compare(GCubeTeam o1, GCubeTeam o2) {
return o1.getTeamName().compareTo(o2.getTeamName());
}
}

@ -0,0 +1,14 @@
package org.gcube.portlets.user.performfish.util.comparators;
import java.util.Comparator;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
public class UserComparator implements Comparator<GCubeUser> {
@Override
public int compare(GCubeUser o1, GCubeUser o2) {
return o1.getFullname().compareTo(o2.getFullname());
}
}

@ -0,0 +1,20 @@
package org.gcube.portlets.user.performfish.util.comparators;
import java.util.Comparator;
import org.gcube.common.homelibrary.home.exceptions.InternalErrorException;
import org.gcube.common.homelibrary.home.workspace.WorkspaceItem;
public class WSItemComparator implements Comparator<WorkspaceItem> {
@Override
public int compare(WorkspaceItem o1, WorkspaceItem o2) {
try {
return o1.getName().compareTo(o2.getName());
} catch (InternalErrorException e) {
e.printStackTrace();
}
return 0;
}
}

@ -0,0 +1,361 @@
package org.gcube.portlets.user.performfish.util.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.gcube.portlets.user.performfish.bean.Association;
import org.gcube.portlets.user.performfish.bean.Company;
import org.gcube.portlets.user.performfish.bean.Farm;
import org.postgresql.util.PGobject;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
public class DBUtil {
private static Log _log = LogFactoryUtil.getLog(DBUtil.class);
public static List<Company> getCompanies(Connection conn) throws Exception {
_log.debug("getting Companies ");
List<Company> toReturn = new ArrayList<>();
String selectSQL = "SELECT * FROM companies";
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
Long companyId = rs.getLong("companyid");
Long associationid = rs.getLong("associationid");
boolean staged = rs.getBoolean("isstaged");
Company toAdd = new Company(companyId, associationid, staged);
_log.debug("Adding " + toAdd);
toReturn.add(toAdd);
}
return toReturn;
}
public static List<Farm> getAllFarms(Connection conn) throws Exception {
_log.debug("getting Farms ");
List<Farm> toReturn = new ArrayList<>();
String selectSQL = "SELECT * FROM Farms";
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
Long farmid = rs.getLong("farmid");
String location = rs.getString("opt1");
Long companyid = rs.getLong("companyid");
String creator = rs.getString("opt2");
Farm toAdd = new Farm(farmid, location, companyid, creator);
Date dateLastActivity = rs.getDate("dateLastActivity");
toAdd.setDateLastActivity(dateLastActivity);
_log.debug("Adding " + toAdd);
toReturn.add(toAdd);
}
return toReturn;
}
public static List<Association> getAllAssociations(Connection conn) throws Exception {
_log.debug("getting Associations ");
List<Association> toReturn = new ArrayList<>();
String selectSQL = "SELECT * FROM Associations";
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
Long associationid = rs.getLong("associationid");
String createdBy = rs.getString("opt1");
Association toAdd = new Association(associationid, createdBy);
_log.debug("Adding " + toAdd);
toReturn.add(toAdd);
}
return toReturn;
}
public static List<Company> listCompaniesNotAssociatedToAssociations(Connection conn) throws Exception {
_log.debug("getting Companies not associated ");
List<Company> toReturn = new ArrayList<>();
String selectSQL = "SELECT * FROM companies where companyid NOT IN (SELECT C.companyid FROM companies as C, associations as A WHERE C.associationid = A.associationid)";
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
Long companyId = rs.getLong("companyid");
Long associationid = rs.getLong("associationid");
boolean staged = rs.getBoolean("isstaged");
Company toAdd = new Company(companyId, associationid, staged);
_log.debug("Adding " + toAdd);
toReturn.add(toAdd);
}
return toReturn;
}
public static List<Long> getCompaniesIdsByAssociation(Connection conn, long associationId) throws Exception {
_log.debug("getting Companies of association with id = " +associationId);
List<Long> toReturn = new ArrayList<>();
String selectSQL = "SELECT companyId FROM Associations as A, Companies as C WHERE A.associationId = C.associationId and A.associationId = ?";
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
preparedStatement.setLong(1, associationId);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
Long companyid = rs.getLong("companyid");
toReturn.add(companyid);
}
return toReturn;
}
public static List<Farm> listFarmsByCompanyId(Connection conn, long companyId) throws Exception {
_log.debug("getting Farms of company with id = " +companyId);
List<Farm> toReturn = new ArrayList<>();
String selectSQL = "SELECT farmid, F.opt1, F.opt2, F.dateLastActivity, F.companyid FROM Farms as F, Companies as C WHERE C.companyid = F.companyid and F.companyId = ?";
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
preparedStatement.setLong(1, companyId);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
Long farmid = rs.getLong("farmid");
String location = rs.getString("opt1");
Long companyid = rs.getLong("companyid");
String creator = rs.getString("opt2");
Farm toAdd = new Farm(farmid, location, companyid, creator);
Date dateLastActivity = rs.getDate("dateLastActivity");
toAdd.setDateLastActivity(dateLastActivity);
_log.debug("Adding " + toAdd);
toReturn.add(toAdd);
}
return toReturn;
}
public static long getCompanyByFarmId(Connection conn, long farmId) throws Exception {
_log.debug("getting company of farm with id = " +farmId);
long toReturn = -1;
String selectSQL = "SELECT C.companyid FROM Farms as F, Companies as C WHERE C.companyid = F.companyid and F.farmId = ?";
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
preparedStatement.setLong(1, farmId);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
Long companyid = rs.getLong("companyid");
toReturn = companyid;
}
return toReturn;
}
public static boolean addCompany(Connection conn, String[] companyIdsToAdd, String username) {
String insertTableSQL = "INSERT INTO companies"
+ "(companyid, opt1, uuid) VALUES"
+ "(?,?,?)";
try {
PreparedStatement preparedStatement = conn.prepareStatement(insertTableSQL);
for (int i = 0; i < companyIdsToAdd.length; i++) {
PGobject toInsertUUID = new PGobject();
toInsertUUID.setType("uuid");
toInsertUUID.setValue(UUID.randomUUID().toString());
preparedStatement.setLong(1, Long.parseLong(companyIdsToAdd[i]));
preparedStatement.setString(2, "Created by: "+username);
preparedStatement.setObject(3,toInsertUUID);
// execute insert SQL stetement
preparedStatement .executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public static boolean addAssociation(Connection conn, String[] associationsIdsToAdd, String username) {
String insertTableSQL = "INSERT INTO associations"
+ "(associationid, opt1, uuid) VALUES"
+ "(?,?,?)";
try {
PreparedStatement preparedStatement = conn.prepareStatement(insertTableSQL);
for (int i = 0; i < associationsIdsToAdd.length; i++) {
PGobject toInsertUUID = new PGobject();
toInsertUUID.setType("uuid");
toInsertUUID.setValue(UUID.randomUUID().toString());
preparedStatement.setLong(1, Long.parseLong(associationsIdsToAdd[i]));
preparedStatement.setString(2, "Created by: "+username);
preparedStatement.setObject(3,toInsertUUID);
// execute insert SQL stetement
preparedStatement .executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public static boolean associateCompaniesToAssociation(Connection conn, long associationId, long[] companiesId) {
String updateTableSQL = "UPDATE Companies SET associationid = ? WHERE companyId = ?";
for (int i = 0; i < companiesId.length; i++) {
try {
PreparedStatement preparedStatement = conn.prepareStatement(updateTableSQL);
preparedStatement.setLong(1, associationId);
preparedStatement.setLong(2, companiesId[i]);
preparedStatement .executeUpdate();
}catch (SQLException e) {
e.printStackTrace();
return false;
}
}
return true;
}
public static boolean deleteFarm(Connection conn, long farmId) {
String updateTableSQL = "DELETE FROM Farms WHERE farmId = ?";
try {
PreparedStatement preparedStatement = conn.prepareStatement(updateTableSQL);
preparedStatement.setLong(1, farmId);
// execute insert SQL stetement
preparedStatement .executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public static boolean editFarm(Connection conn, long farmId, String name, String farmLocation) {
String updateTableSQL = "Update Farms set name = ?, opt1 = ? WHERE farmId = ?";
try {
PreparedStatement preparedStatement = conn.prepareStatement(updateTableSQL);
preparedStatement.setString(1, name);
preparedStatement.setString(2, farmLocation);
preparedStatement.setLong(3, farmId);
// execute insert SQL stetement
preparedStatement .executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public static boolean updateFarmLastSubmissionActivity(Connection conn, long farmId, java.sql.Date lastActivity) {
String updateTableSQL = "Update Farms set datelastactivity = ? WHERE farmId = ?";
try {
PreparedStatement preparedStatement = conn.prepareStatement(updateTableSQL);
preparedStatement.setDate(1, lastActivity);
preparedStatement.setLong(2, farmId);
// execute insert SQL stetement
preparedStatement .executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public static boolean addFarm(Connection conn, long farmId, long companyId, String farmName, String farmLocation, String usernameCreator) {
String insertTableSQL = "INSERT INTO Farms"
+ "(farmid, opt1, companyid, opt2, uuid, name) VALUES"
+ "(?,?,?,?,?,?)";
try {
PGobject toInsertUUID = new PGobject();
toInsertUUID.setType("uuid");
toInsertUUID.setValue(UUID.randomUUID().toString());
PreparedStatement preparedStatement = conn.prepareStatement(insertTableSQL);
preparedStatement.setLong(1, farmId);
preparedStatement.setString(2, farmLocation);
preparedStatement.setLong(3, companyId);
preparedStatement.setString(4, usernameCreator);
preparedStatement.setObject(5,toInsertUUID);
preparedStatement.setObject(6,farmName);
// execute insert SQL stetement
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public static boolean removeCompany(Connection conn, String[] companyIdsToRemove) {
String insertTableSQL = "DELETE FROM companies WHERE companyId = ?";
try {
PreparedStatement preparedStatement = conn.prepareStatement(insertTableSQL);
for (int i = 0; i < companyIdsToRemove.length; i++) {
preparedStatement.setLong(1, Long.parseLong(companyIdsToRemove[i]));
// execute insert SQL stetement
preparedStatement .executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public static boolean setCompanyStaged(Connection conn, long companyId) {
String insertTableSQL = "UPDATE companies SET isStaged = true WHERE companyId = ?";
try {
PreparedStatement preparedStatement = conn.prepareStatement(insertTableSQL);
preparedStatement.setLong(1, companyId);
// execute insert SQL stetement
preparedStatement .executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public static Company getCompanyById(Connection conn, long companyId) throws Exception {
_log.debug("getting Companies ");
Company toReturn = null;
String selectSQL = "SELECT companyid, associationid, isStaged FROM companies WHERE companyId = ?";
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
preparedStatement.setLong(1, companyId);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
Long associationid = rs.getLong("associationid");
boolean staged = rs.getBoolean("isStaged");
toReturn = new Company(companyId, associationid, staged);
}
return toReturn;
}
/**
*
* @param conn
* @throws SQLException
*/
protected static void initializeTablesIfNotExist(Connection conn) throws SQLException {
String assTable = "CREATE TABLE IF NOT EXISTS Associations ("
+ "AssociationId bigint PRIMARY KEY NOT NULL, "
+ "Opt1 text, "
+ "Opt2 text, "
+ "dateCreated date)";
String companyTable = "CREATE TABLE IF NOT EXISTS Companies ("
+ "CompanyId bigint PRIMARY KEY NOT NULL, "
+ "isStaged boolean NOT NULL DEFAULT FALSE, "
+ "Opt1 text, "
+ "Opt2 text, "
+ "AssociationId bigint, "
+ "FOREIGN KEY(AssociationId) REFERENCES Associations(AssociationId))";
String farmTable = "CREATE TABLE IF NOT EXISTS Farms ("
+ "FarmId bigint PRIMARY KEY NOT NULL, "
+ "Opt1 text, "
+ "Opt2 text, "
+ "dateLastActivity date, "
+ "CompanyId bigint, "
+ "FOREIGN KEY(CompanyId) REFERENCES Companies(CompanyId))";
Statement stmt = conn.createStatement();
stmt.execute(assTable);
stmt.execute(companyTable);
stmt.execute(farmTable);
}
}

@ -0,0 +1,70 @@
package org.gcube.portlets.user.performfish.util.db;
public class DB_Credentials {
private String DBURL, DBName, user, pwd;
public DB_Credentials(String DBURL, String DBName, String user, String pwd) {
super();
this.DBURL = DBURL;
this.DBName = DBName;
this.user = user;
this.pwd = pwd;
}
public DB_Credentials() {
// TODO Auto-generated constructor stub
}
public String getJDBCURL() {
return new StringBuilder("jdbc:postgresql://").append(DBURL).append("/").append(DBName).append("?user=").append(this.user).toString();
}
public String getDBURL() {
return DBURL;
}
public void setDBURL(String dBURL) {
DBURL = dBURL;
}
public String getDBName() {
return DBName;
}
public void setDBName(String dBName) {
DBName = dBName;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DB_Credentials [DBURL=");
builder.append(DBURL);
builder.append(", DBName=");
builder.append(DBName);
builder.append(", user=");
builder.append(user);
builder.append(", pwd=");
builder.append(pwd);
builder.append("]");
return builder.toString();
}
}

@ -0,0 +1,101 @@
package org.gcube.portlets.user.performfish.util.db;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import org.gcube.common.encryption.StringEncrypter;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portlets.user.performfish.util.PFISHConstants;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
public class DatabaseConnection {
private static Log _log = LogFactoryUtil.getLog(DatabaseConnection.class);
private static DatabaseConnection instance;
private Connection connection;
private DatabaseConnection(DB_Credentials dbparams) throws SQLException {
try {
Class.forName("org.postgresql.Driver");
this.connection = DriverManager.getConnection(dbparams.getJDBCURL(), dbparams.getUser(), dbparams.getPwd());
DBUtil.initializeTablesIfNotExist(connection);
} catch (ClassNotFoundException ex) {
_log.error("Database Connection Creation Failed : " + ex.getMessage());
}
}
public Connection getConnection() {
return connection;
}
public static DatabaseConnection getInstance(String context) throws Exception {
if (instance == null || instance.getConnection().isClosed()) {
DB_Credentials cred = getDBCredentials(context);
instance = new DatabaseConnection(cred);
_log.info("Database Connection acquired for : " + cred.getJDBCURL());
}
return instance;
}
/**
*
* @param request
* @param response
* @param instance
* @return the credentails, and if the db is empty created the schema
* @throws Exception
*/
private static DB_Credentials getDBCredentials(String currContext) throws Exception {
AccessPoint ac = getDBAccessPoint(currContext);
DB_Credentials toReturn = new DB_Credentials();
_log.debug("Got AccessPoint:" + ac.toString());
String dbAddress = ac.address(); //"localhost:5432"; //
toReturn.setDBURL(dbAddress);
_log.debug("DB address: "+ dbAddress);
String dbName = ac.name();
toReturn.setDBName(dbName);
_log.debug("DB name: "+ dbName);
String dbUser = ac.username();
toReturn.setUser(dbUser);
_log.debug("DB user: " + dbUser);
String jdbcURL = new StringBuffer("jdbc:postgresql://").append(dbAddress).append("/").append(dbName).toString();
_log.debug("jdbc.url: "+jdbcURL);
ScopeProvider.instance.set(currContext);
String pwd = StringEncrypter.getEncrypter().decrypt(ac.password());
toReturn.setPwd(pwd);
_log.debug("Decrypted Password OK");
return toReturn;
}
/**
* Gets the survey DB access point.
*
* @return the survey DB access point
*/
private static AccessPoint getDBAccessPoint(String currContext) {
//set the context for this resource
ScopeProvider.instance.set(currContext);
//construct the xquery
SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/text() eq '"+ PFISHConstants.PF_DB_SERVICE_ENDPOINT_NAME +"'");
query.addCondition("$resource/Profile/Category/text() eq '"+ PFISHConstants.PF_DB_SERVICE_ENDPOINT_CATEGORY +"'");
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
List<ServiceEndpoint> conf = client.submit(query);
ServiceEndpoint res = conf.get(0);
return res.profile().accessPoints().iterator().next();
}
}

@ -0,0 +1,27 @@
<?xml version="1.0"?>
<!DOCTYPE display PUBLIC "-//Liferay//DTD Display 6.2.0//EN" "http://www.liferay.com/dtd/liferay-display_6_2_0.dtd">
<display>
<category name="PerformFISH Apps">
<portlet id="manage-company-users"></portlet>
<portlet id="manage-company-admins"></portlet>
<portlet id="company-repository"></portlet>
<portlet id="associate-users-to-company"></portlet>
<portlet id="promote-administrators"></portlet>
<portlet id="empty-forms-documents-display"></portlet>
<portlet id="submitted-form-validation"></portlet>
<portlet id="manage-companies"></portlet>
<portlet id="add-new-company"></portlet>
<portlet id="manage-farms"></portlet>
<portlet id="manage-farm-administratos"></portlet>
<portlet id="promote-farm-administrators"></portlet>
<portlet id="manage-farm-users"></portlet>
<portlet id="associate-users-to-farm"></portlet>
<portlet id="set-company-administrators-super-user"></portlet>
<portlet id="set-farm-administrators"></portlet>
<portlet id="company-private-repository"></portlet>
<portlet id="manage-associations"></portlet>
<portlet id="associate-companies-to-association"></portlet>
<portlet id="association-dashboard"></portlet>
</category>
</display>

@ -0,0 +1,9 @@
name=PerformFISH-Apps
module-group-id=liferay
module-incremental-version=8
tags=
short-description=
change-log=
page-url=http://www.gcube-system.org
author=M. Assante, CNR-ISTI
licenses=EUPL

@ -0,0 +1,257 @@
<?xml version="1.0"?>
<!DOCTYPE liferay-portlet-app PUBLIC "-//Liferay//DTD Portlet Application 6.2.0//EN" "http://www.liferay.com/dtd/liferay-portlet-app_6_2_0.dtd">
<liferay-portlet-app>
<portlet>
<portlet-name>manage-company-users</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<ajaxable>true</ajaxable>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
manage-company-users-portlet
</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>manage-company-admins</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<ajaxable>true</ajaxable>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
manage-company-admins-portlet
</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>company-repository</portlet-name>
<icon>/icon.png</icon>
<configuration-action-class>org.gcube.portlets.user.performfish.CompanyFarmRepositoryConfigurationAction</configuration-action-class>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<ajaxable>true</ajaxable>
<header-portlet-css>/css/main.css</header-portlet-css>
<header-portlet-javascript>
/js/main.js
</header-portlet-javascript>
<css-class-wrapper>
company-repository-portlet
</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>associate-users-to-company</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
associate-users-to-company-portlet
</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>promote-administrators</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
promote-administrators-portlet
</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>empty-forms-documents-display</portlet-name>
<icon>/icon.png</icon>
<configuration-action-class>org.gcube.portlets.user.performfish.EmptyFormsConfigurationAction</configuration-action-class>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<header-portlet-css>/css/main.css</header-portlet-css>
<header-portlet-javascript>/js/jquery.min.js</header-portlet-javascript>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
empty-forms-documents-display-portlet
</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>submitted-form-validation</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
submitted-form-validation-portlet
</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>manage-companies</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>manage-companies-portlet</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>add-new-company</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>add-new-company-portlet</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>manage-farms</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>manage-farms-portlet</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>manage-farm-administratos</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
manage-farm-administratos-portlet
</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>promote-farm-administrators</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
promote-farm-administrators-portlet
</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>manage-farm-users</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>manage-farm-users-portlet</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>associate-users-to-farm</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
associate-users-to-farm-portlet
</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>
set-company-administrators-super-user
</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<ajaxable>true</ajaxable>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
set-company-administrators-super-user-portlet
</css-class-wrapper>
<add-default-resource>true</add-default-resource>
</portlet>
<portlet>
<portlet-name>set-farm-administrators</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
set-farm-administrators-portlet
</css-class-wrapper>
<add-default-resource>true</add-default-resource>
</portlet>
<portlet>
<portlet-name>company-private-repository</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<ajaxable>true</ajaxable>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
company-private-repository-portlet
</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>manage-associations</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<ajaxable>true</ajaxable>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
manage-associations-portlet
</css-class-wrapper>
</portlet>
<portlet>
<portlet-name>associate-companies-to-association</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<ajaxable>true</ajaxable>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
associate-companies-to-association-portlet
</css-class-wrapper>
<add-default-resource>true</add-default-resource>
</portlet>
<portlet>
<portlet-name>association-dashboard</portlet-name>
<icon>/icon.png</icon>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<ajaxable>true</ajaxable>
<header-portlet-css>/css/table.css</header-portlet-css>
<footer-portlet-javascript>
/js/main.js
</footer-portlet-javascript>
<css-class-wrapper>
association-dashboard-portlet
</css-class-wrapper>
</portlet>
<role-mapper>
<role-name>administrator</role-name>
<role-link>Administrator</role-link>
</role-mapper>
</liferay-portlet-app>

@ -0,0 +1,492 @@
<?xml version="1.0"?>
<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd"
version="2.0">
<portlet>
<portlet-name>manage-company-users</portlet-name>
<display-name>Manage Company Users</display-name>
<portlet-class>org.gcube.portlets.user.performfish.ManageCompanyUsers</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/managecompanyusers/company_users.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>Manage Company Regular Users</title>
<short-title>Manage Company Users</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>manage-company-admins</portlet-name>
<display-name>Manage Company Admins</display-name>
<portlet-class>
org.gcube.portlets.user.performfish.ManageCompanyAdmins
</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/managecompanyadmins/company_admins.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>Manage Company Administrators</title>
<short-title>Manage Company Admins</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>company-repository</portlet-name>
<display-name>Company Farm Repository</display-name>
<portlet-class>org.gcube.portlets.user.performfish.CompanyFarmRepository</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/farmrepository/view_farm_repository.jsp</value>
</init-param>
<init-param>
<name>config-template</name>
<value>/html/farmrepository/config.jsp</value>
</init-param>
<init-param>
<name>add-process-action-success-action</name>
<value>false</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>view</portlet-mode>
<portlet-mode>config</portlet-mode>
</supports>
<portlet-info>
<title>Company Farm Repository</title>
<short-title>Company Farm Repository</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>associate-users-to-company</portlet-name>
<display-name>Associate Users To Company</display-name>
<portlet-class>
org.gcube.portlets.user.performfish.AssociateUsersToCompany</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/adduserstocompany/add_users_toCompany.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>Associate Users To Company</title>
<short-title>Associate Users To Company</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>promote-administrators</portlet-name>
<display-name>Promote Company Administrators</display-name>
<portlet-class>
org.gcube.portlets.user.performfish.PromoteCompanyAdministrators</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/adduserstocompany/promote_company_administrators.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>Promote Company Administrators</title>
<short-title>Promote Company Administrators</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>empty-forms-documents-display</portlet-name>
<display-name>Empty Forms Documents Display</display-name>
<portlet-class>
org.gcube.portlets.user.performfish.EmptyFormsDocumentsDisplay</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/emptyformsdocumentsdisplay/empty_forms_fileupload_display.jsp</value>
</init-param>
<init-param>
<name>config-template</name>
<value>/html/emptyformsdocumentsdisplay/empty_forms_config.jsp</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>view</portlet-mode>
<portlet-mode>config</portlet-mode>
</supports>
<portlet-info>
<title>Documents for initials submission with instructions and new
submissions</title>
<short-title>Empty Forms Documents Display</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>submitted-form-validation</portlet-name>
<display-name>Submitted form validation</display-name>
<portlet-class>
org.gcube.portlets.user.performfish.SubmittedFormValidation</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/submittedformvalidation/validation.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>Submitted Form Validation</title>
<short-title>Submitted Form Validation</short-title>
<keywords></keywords>
</portlet-info>
<portlet-preferences>
<preference>
<name>portletSetupShowBorders</name>
<value>false</value>
</preference>
</portlet-preferences>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>manage-companies</portlet-name>
<display-name>Manage Companies</display-name>
<portlet-class>org.gcube.portlets.user.performfish.ManageCompanies</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/managecompanies/manage_companies.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>Manage Companies</title>
<short-title>Manage Companies</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>add-new-company</portlet-name>
<display-name>Add New Company or Association</display-name>
<portlet-class>org.gcube.portlets.user.performfish.AddNewCompanyOrAssociation</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/addnewcompany_or_assoc/AddNewCompany.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>Add New Company or Association</title>
<short-title>Add New Company</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>manage-farms</portlet-name>
<display-name>Manage Company Farms</display-name>
<portlet-class>org.gcube.portlets.user.performfish.ManageFarms</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/managefarms/managefarms_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>Manage Company Farms</title>
<short-title>Manage Farms</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>manage-farm-administratos</portlet-name>
<display-name>Manage Farm Administrators</display-name>
<portlet-class>
org.gcube.portlets.user.performfish.ManageFarmAdministrators</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/managefarmadministratos/farm_admins.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>Manage Farm Administrators</title>
<short-title>Manage Farm Administrators</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>promote-farm-administrators</portlet-name>
<display-name>Promote Farm Administrators</display-name>
<portlet-class>
org.gcube.portlets.user.performfish.PromoteFarmAdministrators</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/adduserstocompany/promote_farm_administrators.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>Promote Farm Administrators</title>
<short-title>Promote Farm Administrators</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>manage-farm-users</portlet-name>
<display-name>Manage Farm Users</display-name>
<portlet-class>org.gcube.portlets.user.performfish.ManageFarmUsers</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/managefarmusers/manage_farm_users_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>Manage Farm Users</title>
<short-title>Manage Farm Users</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>associate-users-to-farm</portlet-name>
<display-name>Associate Users To Farm</display-name>
<portlet-class>
org.gcube.portlets.user.performfish.AssociateUsersToFarm</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/adduserstocompany/add_users_toFarm.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>Associate Users To Farm</title>
<short-title>Associate Users To Farm</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>set-company-administrators-super-user</portlet-name>
<display-name>Set Company Administrators Super User</display-name>
<portlet-class>
org.gcube.portlets.user.performfish.SetCompanyAdministratorsSuperUser</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/setcompanyadministratorssuperuser/set_company_admin.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>Set Company Administrators Super User</title>
<short-title>Set Company Administrators Super User</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>set-farm-administrators</portlet-name>
<display-name>Set Farm Administrators</display-name>
<portlet-class>
org.gcube.portlets.user.performfish.SetFarmAdministrators
</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/setfarmadministrators/set_farm_admin.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>Set Farm Administrators</title>
<short-title>Set Farm Administrators</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>company-private-repository</portlet-name>
<display-name>Company Private Repository</display-name>
<portlet-class>
org.gcube.portlets.user.performfish.CompanyPrivateRepository
</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/companyprivaterepository/company_private_repository.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>Company Private Repository</title>
<short-title>Company Private Repository</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>manage-associations</portlet-name>
<display-name>Manage Associations</display-name>
<portlet-class>
org.gcube.portlets.user.performfish.ManageAssociations
</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/manageassociations/manage_associations_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>Manage Associations</title>
<short-title>Manage Associations</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>associate-companies-to-association</portlet-name>
<display-name>Associate Companies To Association</display-name>
<portlet-class>
org.gcube.portlets.user.performfish.AssociateCompaniesToAssociation
</portlet-class>
<init-param>
<name>view-template</name>
<value>
/html/associatecompaniestoassociation/companies_to_ass_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>Associate Companies To Association</title>
<short-title>
Associate Companies To Association
</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>association-dashboard</portlet-name>
<display-name>Association Dashboard</display-name>
<portlet-class>
org.gcube.portlets.user.performfish.AssociationDashboard
</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/associationdashboard/association_dashboard.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>Association Dashboard</title>
<short-title>Association Dashboard</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
</portlet>
</portlet-app>

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"/>

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

@ -0,0 +1,185 @@
/* hides submitted-form-validation-portlet */
.portlet-icon-back {
display: none;
}
div#vloader {
width: 100%;
height: 100px;
background: url("loading_result.gif") no-repeat center top;
}
div.submitted-form-validation-portlet {
display: none;
}
.no-padding {
padding-left: 0 !important;
}
.logo-circular{
width: 32px;
height: 32px;
display: block;
border: 1px solid #AAA;
border-radius: 32px;
-webkit-border-radius: 16px;
-moz-border-radius: 16px;
background-position: 50% 50%;
}
/* file upload css */
.ajax-file-upload-error {
color: red;
}
.ajax-file-upload-statusbar {
border: 1px solid #0ba1b5;
margin-top: 10px;
width: 420px;
margin-right: 10px;
margin: 5px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
padding: 5px 5px 5px 15px
}
.ajax-file-upload-filename {
width: 300px;
height: auto;
margin: 0 5px 5px 0px;
}
.ajax-file-upload-filesize {
width: 50px;
height: auto;
margin: 0 5px 5px 0px;
display: inline-block;
vertical-align: middle;
}
.ajax-file-upload-progress {
margin: 5px 10px 5px 0px;
position: relative;
width: 250px;
border: 1px solid #ddd;
padding: 1px;
border-radius: 3px;
display: inline-block;
color: #FFFFFF;
}
.ajax-file-upload-bar {
background-color: #0ba1b5;
width: 0;
height: 20px;
border-radius: 3px;
color: #FFFFFF;
}
.ajax-file-upload-percent {
position: absolute;
display: inline-block;
top: 3px;
left: 48%
}
.ajax-file-upload-red {
-moz-box-shadow: inset 0 39px 0 -24px #e67a73;
-webkit-box-shadow: inset 0 39px 0 -24px #e67a73;
box-shadow: inset 0 39px 0 -24px #e67a73;
background-color: #e4685d;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
display: inline-block;
color: #fff;
font-family: arial;
font-size: 13px;
font-weight: normal;
padding: 4px 15px;
text-decoration: none;
text-shadow: 0 1px 0 #b23e35;
cursor: pointer;
vertical-align: top;
margin: 5px 10px 5px 0px;
}
.ajax-file-upload-green {
background-color: #77b55a;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
margin: 0;
padding: 0;
display: inline-block;
color: #fff;
font-family: arial;
font-size: 13px;
font-weight: normal;
padding: 4px 15px;
text-decoration: none;
cursor: pointer;
text-shadow: 0 1px 0 #5b8a3c;
vertical-align: top;
margin: 5px 10px 5px 0px;
}
.ajax-file-upload {
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
font-weight: bold;
padding: 15px 20px;
cursor: pointer;
line-height: 20px;
height: 25px;
margin: 0 10px 10px 0;
display: inline-block;
background: #fff;
border: 1px solid #e8e8e8;
color: #888;
text-decoration: none;
border-radius: 3px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
-moz-box-shadow: 0 2px 0 0 #e8e8e8;
-webkit-box-shadow: 0 2px 0 0 #e8e8e8;
box-shadow: 0 2px 0 0 #e8e8e8;
padding: 6px 10px 4px 10px;
color: #fff;
background: #2f8ab9;
border: none;
-moz-box-shadow: 0 2px 0 0 #13648d;
-webkit-box-shadow: 0 2px 0 0 #13648d;
box-shadow: 0 2px 0 0 #13648d;
vertical-align: middle;
}
.ajax-file-upload:hover {
background: #3396c9;
-moz-box-shadow: 0 2px 0 0 #15719f;
-webkit-box-shadow: 0 2px 0 0 #15719f;
box-shadow: 0 2px 0 0 #15719f;
}
.ajax-upload-dragdrop {
background: url("up_img.png") no-repeat 50%;
border: 2px dotted #A5A5C7;
width: 90% !important;
height: 180px;
color: #DADCE3;
text-align: left;
vertical-align: middle;
padding: 10px 10px 0px 10px;
}
.state-hover {
border: 2px solid #A5A5C7;
}
.ajax-file-upload-container {
margin: -52px 0px 20px 10px;
width: 90%;
background-color: white;
}

@ -0,0 +1,42 @@
table.paleBlueRows {
font-family: Tahoma, Geneva, sans-serif;
border: 1px solid #FFFFFF;
width: 100%;
text-align: left;
border-collapse: collapse;
}
table.paleBlueRows td, table.paleBlueRows th {
border: 1px solid #FFFFFF;
padding: 3px 5px;
}
table.paleBlueRows tbody td {
font-size: 13px;
}
table.paleBlueRows tr:nth-child(even) {
background: #D0E4F5;
}
table.paleBlueRows thead {
background: #0B6FA4;
border-bottom: 5px solid #FFFFFF;
}
table.paleBlueRows thead th {
font-size: 15px;
font-weight: bold;
color: #FFFFFF;
text-align: left;
border-left: 2px solid #FFFFFF;
}
table.paleBlueRows thead th:first-child {
border-left: none;
}
table.paleBlueRows tfoot {
font-size: 14px;
font-weight: bold;
color: #333333;
background: #D0E4F5;
border-top: 3px solid #444444;
}
table.paleBlueRows tfoot td {
font-size: 14px;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

@ -0,0 +1,117 @@
<%@include file="../init.jsp"%>
<%
String portletURLString = PortalUtil.getCurrentURL(request);
RowChecker rowChecker = new RowChecker(renderResponse);
String currentUsername = Utils.getCurrentUser(request).getUsername();
String vreName = (String) renderRequest.getAttribute("vreName");
pageContext.setAttribute("vreName", vreName);
Group group = (Group) GroupLocalServiceUtil.getGroup(PortalUtil.getScopeGroupId(request));
long currentGroupId = group.getGroupId();
String currentURL = PortalUtil.getCurrentURL(request);
//this is the list to be working on manage
List<GCubeTeam> availableTeams = (List<GCubeTeam>) request.getAttribute("availableTeams");
%>
<a class="btn btn-link btn-large no-padding" href="control-centre"><i
class="icon icon-angle-left"></i>&nbsp;Back to manage companies</a>
<p class="lead">Available teams to promote as Company or Association in ${vreName }:</p>
<liferay-portlet:renderURL varImpl="iteratorURL">
</liferay-portlet:renderURL>
<%
String orderByCol = ParamUtil.getString(request, "orderByCol");
String orderByType = ParamUtil.getString(request, "orderByType");
String sortingOrder = orderByType;
//Logic for toggle asc and desc
if (orderByType.equals("desc"))
orderByType = "asc";
else
orderByType = "desc";
if (Validator.isNull(orderByType)) {
orderByType = "asc";
}
%>
<aui:form action="<%=portletURLString%>" method="post" name="fm">
<liferay-ui:search-container var="searchContainer" delta="5"
deltaConfigurable="true"
emptyResultsMessage="Sorry. There are no available teams to display."
iteratorURL="<%=iteratorURL%>" rowChecker="<%=rowChecker%>"
orderByType="<%=orderByType%>">
<liferay-ui:search-container-results>
<%
int totalteams = availableTeams.size();
List<GCubeTeam> sortableTeams = ListUtil.subList(availableTeams, searchContainer.getStart(),
searchContainer.getEnd());
if (Validator.isNotNull(orderByCol)) {
Collections.sort(sortableTeams, new TeamComparator());
if (sortingOrder.equalsIgnoreCase("desc"))
Collections.reverse(sortableTeams);
}
pageContext.setAttribute("results", sortableTeams);
pageContext.setAttribute("total", totalteams);
%>
</liferay-ui:search-container-results>
<liferay-ui:search-container-row
className="org.gcube.vomanagement.usermanagement.model.GCubeTeam"
modelVar="item" keyProperty="teamId">
<liferay-ui:search-container-column-text orderable="true" name="Name">${item.teamName}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Id">${item.teamId}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Other info">${item.description}</liferay-ui:search-container-column-text>
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
<button name="associate" type="button" class="btn btn-info"
onClick='<%=renderResponse.getNamespace() + "makeCompanies();"%>'>Make
selected a Company</button>
<button name="associate" type="button" class="btn btn-warning"
onClick='<%=renderResponse.getNamespace() + "makeAssociations();"%>'>Make
selected an Association</button>
<aui:input name="selectedTeamIds" type="hidden" />
<aui:input name="currentUsername" type="hidden"
value="<%=currentUsername%>" />
<aui:input name="groupId" type="hidden"
value="<%=currentGroupId%>" />
</aui:form>
<aui:script>
Liferay.provide(
window,
'<portlet:namespace />makeCompanies',
function() {
var selectedTeamIds = Liferay.Util.listCheckedExcept(document.<portlet:namespace />fm, '<portlet:namespace />allRowIds');
if (selectedTeamIds && confirm("Are you sure to make the selected team a Company? Cannot be undone via GUI")) {
document.<portlet:namespace />fm.<portlet:namespace />selectedTeamIds.value = selectedTeamIds;
submitForm(document.<portlet:namespace />fm, '<portlet:actionURL name="makeCompanies"></portlet:actionURL>');
} else {
}
},
['liferay-util-list-fields']
);
Liferay.provide(
window,
'<portlet:namespace />makeAssociations',
function() {
var selectedTeamIds = Liferay.Util.listCheckedExcept(document.<portlet:namespace />fm, '<portlet:namespace />allRowIds');
if (selectedTeamIds && confirm("Are you sure to make the selected team an Association? Cannot be undone via GUI")) {
document.<portlet:namespace />fm.<portlet:namespace />selectedTeamIds.value = selectedTeamIds;
submitForm(document.<portlet:namespace />fm, '<portlet:actionURL name="makeAssociations"></portlet:actionURL>');
} else {
}
},
['liferay-util-list-fields']
);
</aui:script>

@ -0,0 +1,118 @@
<%@include file="../init.jsp"%>
<%
String portletURLString = PortalUtil.getCurrentURL(request);
RowChecker rowChecker = new RowChecker(renderResponse);
String currentUsername = Utils.getCurrentUser(request).getUsername();
Team team = (Team) request.getAttribute("theTeam");
Group group = (Group) GroupLocalServiceUtil.getGroup(PortalUtil.getScopeGroupId(request));
long currentGroupId = group.getGroupId();
String currentURL = PortalUtil.getCurrentURL(request);
List<GCubeUser> siteUsers = Utils.listVREUsersNotAssociatedToAnyCompany(team.getTeamId(), group.getGroupId());
pageContext.setAttribute("logoURL", renderRequest.getAttribute("companyLogoURL"));
pageContext.setAttribute("companyName", team.getName());
%>
<a class="btn btn-link btn-large no-padding" href="company-dashboard"><i
class="icon icon-angle-left"></i>&nbsp;Back to manage company users</a>
<div style="text-align: center; padding-bottom: 15px;">
<table>
<tr>
<c:if test="${not empty logoURL}">
<td>
<div class="logo-circular"
style="background-image: url('${logoURL}');
background-size: cover; "></div>
</td>
</c:if>
<td><p
style="font-size: 1.5em; padding-top: 12px; padding-left: 5px;">${companyName}
</p></td>
</tr>
</table>
</div>
<p class="lead">Available users to associate to <%= team.getName() %>:</p>
<liferay-portlet:renderURL varImpl="iteratorURL">
</liferay-portlet:renderURL>
<%
String orderByCol = ParamUtil.getString(request, "orderByCol");
String orderByType = ParamUtil.getString(request, "orderByType");
String sortingOrder = orderByType;
//Logic for toggle asc and desc
if (orderByType.equals("desc"))
orderByType = "asc";
else
orderByType = "desc";
if (Validator.isNull(orderByType)) {
orderByType = "asc";
}
%>
<aui:form action="<%=portletURLString%>" method="post" name="fm">
<liferay-ui:search-container var="searchContainer" delta="5"
deltaConfigurable="true"
emptyResultsMessage="Sorry. There are no users to display."
iteratorURL="<%=iteratorURL%>" rowChecker="<%=rowChecker%>"
orderByType="<%=orderByType%>">
<liferay-ui:search-container-results>
<%
int totalUsers = siteUsers.size();
List<GCubeUser> sortableUsers = ListUtil.subList(siteUsers, searchContainer.getStart(),
searchContainer.getEnd());
if (Validator.isNotNull(orderByCol)) {
Collections.sort(sortableUsers, new UserComparator());
if (sortingOrder.equalsIgnoreCase("desc"))
Collections.reverse(sortableUsers);
}
pageContext.setAttribute("results", sortableUsers);
pageContext.setAttribute("total", totalUsers);
%>
</liferay-ui:search-container-results>
<liferay-ui:search-container-row
className="org.gcube.vomanagement.usermanagement.model.GCubeUser"
modelVar="item" keyProperty="username">
<liferay-ui:search-container-column-text orderable="true" name="Name">${item.fullname}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Email">${item.email}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Position">${item.jobTitle}</liferay-ui:search-container-column-text>
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
<button name="associate" type="button" class="btn btn-primary"
onClick='<%=renderResponse.getNamespace() + "associateCompanyUsers();"%>'>Associate
selected</button>
<aui:input name="addUserIds" type="hidden" />
<aui:input name="teamId" type="hidden" value="<%=team.getTeamId()%>" />
<aui:input name="currentUsername" type="hidden"
value="<%=currentUsername%>" />
<aui:input name="currentGroupId" type="hidden"
value="<%=currentGroupId%>" />
</aui:form>
<aui:script>
Liferay.provide(
window,
'<portlet:namespace />associateCompanyUsers',
function() {
var addUserIds = Liferay.Util.listCheckedExcept(document.<portlet:namespace />fm, '<portlet:namespace />allRowIds');
if (addUserIds && confirm("Are you sure you want to associate the selected users to this company?")) {
document.<portlet:namespace />fm.<portlet:namespace />addUserIds.value = addUserIds;
submitForm(document.<portlet:namespace />fm, '<portlet:actionURL name="associateCompanyUsers"></portlet:actionURL>');
} else {
}
},
['liferay-util-list-fields']
);
</aui:script>

@ -0,0 +1,119 @@
<%@include file="../init.jsp"%>
<%
String portletURLString = PortalUtil.getCurrentURL(request);
RowChecker rowChecker = new RowChecker(renderResponse);
String currentUsername = Utils.getCurrentUser(request).getUsername();
Team team = (Team) request.getAttribute("theTeam");
Group group = (Group) GroupLocalServiceUtil.getGroup(PortalUtil.getScopeGroupId(request));
long currentGroupId = group.getGroupId();
String currentURL = PortalUtil.getCurrentURL(request);
//this is the list to be working on manage
List<GCubeUser> nonFarmMembers = (List<GCubeUser>) request.getAttribute("nonFarmMembers");
pageContext.setAttribute("logoURL", renderRequest.getAttribute("companyLogoURL"));
pageContext.setAttribute("farmName", team.getName());
%>
<a class="btn btn-link btn-large no-padding" href="farm-dashboard"><i
class="icon icon-angle-left"></i>&nbsp;Back to manage farm users</a>
<div style="text-align: center; padding-bottom: 15px;">
<table>
<tr>
<c:if test="${not empty logoURL}">
<td>
<div class="logo-circular"
style="background-image: url('${logoURL}');
background-size: cover; "></div>
</td>
</c:if>
<td><p
style="font-size: 1.5em; padding-top: 12px; padding-left: 5px;">${farmName}
</p></td>
</tr>
</table>
</div>
<p class="lead">Available company users to associate to ${farmName}:</p>
<liferay-portlet:renderURL varImpl="iteratorURL">
</liferay-portlet:renderURL>
<%
String orderByCol = ParamUtil.getString(request, "orderByCol");
String orderByType = ParamUtil.getString(request, "orderByType");
String sortingOrder = orderByType;
//Logic for toggle asc and desc
if (orderByType.equals("desc"))
orderByType = "asc";
else
orderByType = "desc";
if (Validator.isNull(orderByType)) {
orderByType = "asc";
}
%>
<aui:form action="<%=portletURLString%>" method="post" name="fm">
<liferay-ui:search-container var="searchContainer" delta="5"
deltaConfigurable="true"
emptyResultsMessage="Sorry. There are no users to display."
iteratorURL="<%=iteratorURL%>" rowChecker="<%=rowChecker%>"
orderByType="<%=orderByType%>">
<liferay-ui:search-container-results>
<%
int totalUsers = nonFarmMembers.size();
List<GCubeUser> sortableUsers = ListUtil.subList(nonFarmMembers, searchContainer.getStart(),
searchContainer.getEnd());
if (Validator.isNotNull(orderByCol)) {
Collections.sort(sortableUsers, new UserComparator());
if (sortingOrder.equalsIgnoreCase("desc"))
Collections.reverse(sortableUsers);
}
pageContext.setAttribute("results", sortableUsers);
pageContext.setAttribute("total", totalUsers);
%>
</liferay-ui:search-container-results>
<liferay-ui:search-container-row
className="org.gcube.vomanagement.usermanagement.model.GCubeUser"
modelVar="item" keyProperty="username">
<liferay-ui:search-container-column-text orderable="true" name="Name">${item.fullname}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Email">${item.email}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Position">${item.jobTitle}</liferay-ui:search-container-column-text>
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
<button name="associate" type="button" class="btn btn-primary"
onClick='<%=renderResponse.getNamespace() + "associateFarmUsers();"%>'>Associate
selected</button>
<aui:input name="addUserIds" type="hidden" />
<aui:input name="teamId" type="hidden" value="<%=team.getTeamId()%>" />
<aui:input name="currentUsername" type="hidden"
value="<%=currentUsername%>" />
<aui:input name="currentGroupId" type="hidden"
value="<%=currentGroupId%>" />
</aui:form>
<aui:script>
Liferay.provide(
window,
'<portlet:namespace />associateFarmUsers',
function() {
var addUserIds = Liferay.Util.listCheckedExcept(document.<portlet:namespace />fm, '<portlet:namespace />allRowIds');
if (addUserIds && confirm("Are you sure you want to associate the selected users to this farm?")) {
document.<portlet:namespace />fm.<portlet:namespace />addUserIds.value = addUserIds;
submitForm(document.<portlet:namespace />fm, '<portlet:actionURL name="associateFarmUsers"></portlet:actionURL>');
} else {
}
},
['liferay-util-list-fields']
);
</aui:script>

@ -0,0 +1,118 @@
<%@include file="../init.jsp"%>
<%
String portletURLString = PortalUtil.getCurrentURL(request);
RowChecker rowChecker = new RowChecker(renderResponse);
String currentUsername = Utils.getCurrentUser(request).getUsername();
Team team = (Team) request.getAttribute("theTeam");
Group group = (Group) GroupLocalServiceUtil.getGroup(PortalUtil.getScopeGroupId(request));
long currentGroupId = group.getGroupId();
String currentURL = PortalUtil.getCurrentURL(request);
//this is the list to be working on manage
List<CompanyMember> siteUsers = Utils.getRegularCompanyMembers(team.getTeamId(), team.getGroupId());
pageContext.setAttribute("logoURL", renderRequest.getAttribute("companyLogoURL"));
pageContext.setAttribute("companyName", team.getName());
%>
<a class="btn btn-link btn-large no-padding" href="company-dashboard"><i
class="icon icon-angle-left"></i>&nbsp;Back to manage company Administrators</a>
<div style="text-align: center; padding-bottom: 15px;">
<table>
<tr>
<c:if test="${not empty logoURL}">
<td>
<div class="logo-circular"
style="background-image: url('${logoURL}');
background-size: cover; "></div>
</td>
</c:if>
<td><p
style="font-size: 1.5em; padding-top: 12px; padding-left: 5px;">${companyName}
</p></td>
</tr>
</table>
</div>
<p class="lead">Users currently associated to <%= team.getName() %> that can be promoted as Administrators:</p>
<liferay-portlet:renderURL varImpl="iteratorURL">
</liferay-portlet:renderURL>
<%
String orderByCol = ParamUtil.getString(request, "orderByCol");
String orderByType = ParamUtil.getString(request, "orderByType");
String sortingOrder = orderByType;
//Logic for toggle asc and desc
if (orderByType.equals("desc"))
orderByType = "asc";
else
orderByType = "desc";
if (Validator.isNull(orderByType)) {
orderByType = "asc";
}
%>
<aui:form action="<%=portletURLString%>" method="post" name="fm">
<liferay-ui:search-container var="searchContainer" delta="5"
deltaConfigurable="true"
emptyResultsMessage="Sorry. There are no users to display."
iteratorURL="<%=iteratorURL%>" rowChecker="<%=rowChecker%>"
orderByType="<%=orderByType%>">
<liferay-ui:search-container-results>
<%
int totalUsers = siteUsers.size();
List<CompanyMember> sortableUsers = ListUtil.subList(siteUsers, searchContainer.getStart(),
searchContainer.getEnd());
if (Validator.isNotNull(orderByCol)) {
Collections.sort(sortableUsers, new org.gcube.portlets.user.performfish.util.comparators.CompanyMemberComparator());
if (sortingOrder.equalsIgnoreCase("desc"))
Collections.reverse(sortableUsers);
}
pageContext.setAttribute("results", sortableUsers);
pageContext.setAttribute("total", totalUsers);
%>
</liferay-ui:search-container-results>
<liferay-ui:search-container-row
className="org.gcube.portlets.user.performfish.bean.CompanyMember"
modelVar="item" keyProperty="userId">
<liferay-ui:search-container-column-text orderable="true" name="Name">${item.fullname}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Email">${item.email}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Position">${item.jobTitle}</liferay-ui:search-container-column-text>
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
<button name="associate" type="button" class="btn btn-primary"
onClick='<%=renderResponse.getNamespace() + "promoteAdminUsers();"%>'>Promote
selected</button>
<aui:input name="addUserIds" type="hidden" />
<aui:input name="currentUsername" type="hidden"
value="<%=currentUsername%>" />
<aui:input name="currentGroupId" type="hidden"
value="<%=currentGroupId%>" />
</aui:form>
<aui:script>
Liferay.provide(
window,
'<portlet:namespace />promoteAdminUsers',
function() {
var addUserIds = Liferay.Util.listCheckedExcept(document.<portlet:namespace />fm, '<portlet:namespace />allRowIds');
if (addUserIds && confirm("Are you sure you want to promote Administrator to the selected user(s)?")) {
document.<portlet:namespace />fm.<portlet:namespace />addUserIds.value = addUserIds;
submitForm(document.<portlet:namespace />fm, '<portlet:actionURL name="promoteAdminUsers"></portlet:actionURL>');
} else {
}
},
['liferay-util-list-fields']
);
</aui:script>

@ -0,0 +1,119 @@
<%@include file="../init.jsp"%>
<%
String portletURLString = PortalUtil.getCurrentURL(request);
RowChecker rowChecker = new RowChecker(renderResponse);
String currentUsername = Utils.getCurrentUser(request).getUsername();
GCubeTeam theFarm = (GCubeTeam) request.getAttribute("theFarm");
pageContext.setAttribute("theFarm", theFarm);
Group group = (Group) GroupLocalServiceUtil.getGroup(PortalUtil.getScopeGroupId(request));
long currentGroupId = group.getGroupId();
String currentURL = PortalUtil.getCurrentURL(request);
//this is the list to be working on manage
List<GCubeUser> siteUsers = Utils.getRegularFarmMembers(theFarm.getTeamId(), theFarm.getGroupId());
pageContext.setAttribute("logoURL", renderRequest.getAttribute("companyLogoURL"));
pageContext.setAttribute("theFarmName", theFarm.getTeamName());
%>
<a class="btn btn-link btn-large no-padding" href="farm-dashboard"><i
class="icon icon-angle-left"></i>&nbsp;Back to manage Farm Administrators</a>
<div style="text-align: center; padding-bottom: 15px;">
<table>
<tr>
<c:if test="${not empty logoURL}">
<td>
<div class="logo-circular"
style="background-image: url('${logoURL}');
background-size: cover; "></div>
</td>
</c:if>
<td><p
style="font-size: 1.5em; padding-top: 12px; padding-left: 5px;">${theFarmName}
</p></td>
</tr>
</table>
</div>
<p class="lead">Users currently associated to ${theFarmName} that can be promoted as Administrators:</p>
<liferay-portlet:renderURL varImpl="iteratorURL">
</liferay-portlet:renderURL>
<%
String orderByCol = ParamUtil.getString(request, "orderByCol");
String orderByType = ParamUtil.getString(request, "orderByType");
String sortingOrder = orderByType;
//Logic for toggle asc and desc
if (orderByType.equals("desc"))
orderByType = "asc";
else
orderByType = "desc";
if (Validator.isNull(orderByType)) {
orderByType = "asc";
}
%>
<aui:form action="<%=portletURLString%>" method="post" name="fm">
<liferay-ui:search-container var="searchContainer" delta="5"
deltaConfigurable="true"
emptyResultsMessage="Sorry. There are no users to display."
iteratorURL="<%=iteratorURL%>" rowChecker="<%=rowChecker%>"
orderByType="<%=orderByType%>">
<liferay-ui:search-container-results>
<%
int totalUsers = siteUsers.size();
List<GCubeUser> sortableUsers = ListUtil.subList(siteUsers, searchContainer.getStart(),
searchContainer.getEnd());
if (Validator.isNotNull(orderByCol)) {
Collections.sort(sortableUsers, new UserComparator());
if (sortingOrder.equalsIgnoreCase("desc"))
Collections.reverse(sortableUsers);
}
pageContext.setAttribute("results", sortableUsers);
pageContext.setAttribute("total", totalUsers);
%>
</liferay-ui:search-container-results>
<liferay-ui:search-container-row
className="org.gcube.vomanagement.usermanagement.model.GCubeUser"
modelVar="item" keyProperty="userId">
<liferay-ui:search-container-column-text orderable="true" name="Name">${item.fullname}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Email">${item.email}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Position">${item.jobTitle}</liferay-ui:search-container-column-text>
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
<button name="associate" type="button" class="btn btn-primary"
onClick='<%=renderResponse.getNamespace() + "promoteAdminUsers();"%>'>Promote
selected</button>
<aui:input name="addUserIds" type="hidden" />
<aui:input name="currentUsername" type="hidden"
value="<%=currentUsername%>" />
<aui:input name="currentGroupId" type="hidden"
value="<%=currentGroupId%>" />
</aui:form>
<aui:script>
Liferay.provide(
window,
'<portlet:namespace />promoteAdminUsers',
function() {
var addUserIds = Liferay.Util.listCheckedExcept(document.<portlet:namespace />fm, '<portlet:namespace />allRowIds');
if (addUserIds && confirm("Are you sure you want to promote Administrator to the selected user(s)?")) {
document.<portlet:namespace />fm.<portlet:namespace />addUserIds.value = addUserIds;
submitForm(document.<portlet:namespace />fm, '<portlet:actionURL name="promoteAdminUsers"></portlet:actionURL>');
} else {
}
},
['liferay-util-list-fields']
);
</aui:script>

@ -0,0 +1,106 @@
<%@include file="../init.jsp"%>
<%
Boolean operationFinished = (Boolean) request.getAttribute("operationFinished");
if (!operationFinished) {
Team selectedAssociation = (Team) renderRequest.getAttribute("selectedAssociation");
pageContext.setAttribute("selectedAssociation", selectedAssociation);
List<Company> companies = (List<Company> ) renderRequest.getAttribute("companies");
pageContext.setAttribute("companies", companies);
String vreName = (String) renderRequest.getAttribute("vreName");
pageContext.setAttribute("vreName", vreName);
RowChecker rowChecker = new RowChecker(renderResponse);
String portletURLString = PortalUtil.getCurrentURL(request);
String currentGroupId = PortalUtil.getScopeGroupId(request)+"";
%>
<p class="lead">
Select the companies to associate to ${selectedAssociation.name} (${selectedAssociation.description}):
</p>
<liferay-portlet:renderURL varImpl="iteratorURL">
</liferay-portlet:renderURL>
<%
String orderByCol = ParamUtil.getString(request, "orderByCol");
String orderByType = ParamUtil.getString(request, "orderByType");
String sortingOrder = orderByType;
//Logic for toggle asc and desc
if (orderByType.equals("desc"))
orderByType = "asc";
else
orderByType = "desc";
if (Validator.isNull(orderByType)) {
orderByType = "asc";
}
%>
<aui:form action="<%=portletURLString%>" method="post" name="fm">
<liferay-ui:search-container var="searchContainer" delta="100"
deltaConfigurable="true"
emptyResultsMessage="Sorry. There are no companies to display."
iteratorURL="<%=iteratorURL%>" rowChecker="<%=rowChecker%>"
orderByType="<%=orderByType%>">
<liferay-ui:search-container-results>
<%
int totalCompanies = companies.size();
List<Company> sortableCompanies = ListUtil.subList(companies, searchContainer.getStart(),
searchContainer.getEnd());
if (Validator.isNotNull(orderByCol)) {
Collections.sort(sortableCompanies, new CompanyComparator());
if (sortingOrder.equalsIgnoreCase("desc"))
Collections.reverse(sortableCompanies);
}
pageContext.setAttribute("results", sortableCompanies);
pageContext.setAttribute("total", totalCompanies);
%>
</liferay-ui:search-container-results>
<liferay-ui:search-container-row
className="org.gcube.portlets.user.performfish.bean.Company"
modelVar="item" keyProperty="companyId">
<liferay-ui:search-container-column-text orderable="true" name="Name">${item.name}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Id">${item.companyId}</liferay-ui:search-container-column-text>
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
<button name="delete" type="button" icon="icon-delete" class="btn btn-primary"
onClick='<%=renderResponse.getNamespace() + "associateCompanies();"%>'>Associate
selected</button>
<aui:input name="associateCompanyIds" type="hidden" />
<aui:input name="currentGroupId" type="hidden"
value="<%=currentGroupId%>" />
<aui:input name="selectedAssociationId" type="hidden"
value="${selectedAssociation.teamId}" />
</aui:form>
<aui:script>
Liferay.provide(
window,
'<portlet:namespace />associateCompanies',
function() {
var associateCompanyIds = Liferay.Util.listCheckedExcept(document.<portlet:namespace />fm, '<portlet:namespace />allRowIds');
if (associateCompanyIds && confirm("Are you sure you want to associate the selected company(ies) to ${selectedAssociation.name}?")) {
document.<portlet:namespace />fm.<portlet:namespace />associateCompanyIds.value = associateCompanyIds;
submitForm(document.<portlet:namespace />fm, '<portlet:actionURL name="associateCompanies"></portlet:actionURL>');
} else {
}
},
['liferay-util-list-fields']
);
</aui:script>
<% } //end if (operationOK != null && operationOK.compareTo("") != 0) {
else {
%>
<% if (operationFinished) {
out.println("Operation performed correctly.");
}%>
<% } %>

@ -0,0 +1,62 @@
<%@include file="../init.jsp"%>
<%
GCubeTeam asso = (GCubeTeam) renderRequest.getAttribute("theAssociation");
pageContext.setAttribute("theAssociation", asso);
String associationLogoURL = (String) renderRequest.getAttribute("associationLogoURL");
pageContext.setAttribute("logoURL", associationLogoURL);
LinkedHashMap<Company, List<Farm>> associationCompanies = (LinkedHashMap<Company, List<Farm>>) renderRequest
.getAttribute("associationCompanies");
pageContext.setAttribute("associationCompanies", associationCompanies);
%>
<div style="text-align: left; width: 100%;">
<div style="text-align: right;">
<div>
<c:if test="${not empty logoURL}">
<img src="${logoURL}"
style="width: 48px; float: right; padding: 10px;">
</c:if>
<h1 style="color: #317eac; padding-left: 5px;">${theAssociation.teamName}</h1>
</div>
<div style="margin-top: -15px;">
<p class="lead" style="color: #317eac; padding-left: 5px;">${theAssociation.description}</p>
</div>
</div>
<div style="width: 100%; text-align: left;">
<c:forEach var="company" items="${associationCompanies}">
<div
style="font-size: 1.2em; margin-top: 10px; padding: 5px; border-bottom: 1px solid #CCC;">
<table id="theTable" class="display">
<tbody>
<tr>
<td><span style="font-size: 1.5em; color: black;">${company.key.name}</span></td>
<td><img src="${company.key.imageUrl}"
style="width: 32px; padding-left: 10px;"></td>
</tr>
</tbody>
</table>
</div>
<c:if test="${not empty company.value}">
<table id="theFarmsTable" class="paleBlueRows">
<thead>
<tr>
<th>Farm name</th>
<th>Farm location</th>
<th>Last form submitted</th>
</tr>
</thead>
<tbody>
<c:forEach var="farm" items="${company.value}">
<tr>
<td><b>${farm.name}</b></td>
<td>${farm.location}</td>
<td><fmt:formatDate type="date" dateStyle = "long"
value="${farm.dateLastActivity}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</c:if>
</c:forEach>
</div>
</div>

@ -0,0 +1,125 @@
<%@include file="../init.jsp"%>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<%
LinkedHashMap<Farm, List<ExternalFile>> companyFiles = (LinkedHashMap<Farm, List<ExternalFile>>) renderRequest
.getAttribute("companyPrivateFiles");
pageContext.setAttribute("companyFiles", companyFiles);
pageContext.setAttribute("logoURL", renderRequest.getAttribute("companyLogoURL"));
String portletURLString = PortalUtil.getCurrentURL(request);
RowChecker rowChecker = new RowChecker(renderResponse);
String currentUsername = Utils.getCurrentUser(request).getUsername();
GCubeTeam theCompany = (GCubeTeam) request.getAttribute("theCompany");
pageContext.setAttribute("theCompanyName", theCompany.getTeamName());
Group group = (Group) GroupLocalServiceUtil.getGroup(PortalUtil.getScopeGroupId(request));
long currentGroupId = group.getGroupId();
String currentURL = PortalUtil.getCurrentURL(request);
%>
<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')}" />
<div style="text-align: center; padding-bottom: 15px;">
<table>
<tr>
<c:if test="${not empty logoURL}">
<td>
<div class="logo-circular"
style="background-image: url('${logoURL}');
background-size: cover; "></div>
</td>
</c:if>
<td><p
style="font-size: 1.5em; padding-top: 12px; padding-left: 5px;">${theCompanyName}
Private Repository Content</p></td>
</tr>
</table>
</div>
<div style="width: 100%; text-align: left;">
<portlet:actionURL var="displayVersionsURL" name="displayVersions"></portlet:actionURL>
<c:choose>
<c:when test="${empty companyFiles}">
<p style="font-size: 1.2em; padding-top: 12px; padding-left: 5px;">The
repository is empty at the moment.</p>
</c:when>
<c:otherwise>
<!-- FOR EACH FARM -->
<form action="${displayVersionsURL}" method="post" id="form_versions"
name="fm">
<c:forEach var="farm" items="${companyFiles}">
<p
style="font-size: 1.2em; padding-bottom: 5px; border-bottom: 1px solid #CCC;">
Repository of
<c:out value="${farm.key.name}" />
</p>
<c:if test="${not empty farm.value}">
<table id="example" class="display">
<tbody>
<thead>
<th>Sel.</th>
<th></th>
<th>Name</th>
<th><span style="margin-left: 10px; font-size: 1.1em;">Uploaded
by</span></th>
<th><span style="margin-left: 10px; font-size: 1.1em;">Last
Updated (UTC)</span></th>
</thead>
<!-- FOR EACH FARM FILE -->
<c:forEach var="file" items="${farm.value}">
<tr>
<portlet:resourceURL var="downloadFileURL">
<portlet:param name="fileToDownloadId" value="${file.id}" />
</portlet:resourceURL>
<%
ExternalFile item = (ExternalFile) pageContext.getAttribute("file");
String iconHTML = IconsManager.getMDIconTextualName(item.getName()).getHtml();
String fullName = Utils.getUserByUsername(item.getLastUpdatedBy()).getFullname();
String userProfileLink = Utils.getUserProfileLink(item.getLastUpdatedBy());
Date lastUpdated = new Date(item.getLastModificationTime().getTimeInMillis());
pageContext.setAttribute("lastUpdated", lastUpdated);
%>
<td><input type="radio" name="fileItem" value="${file.id}"
id="${downloadFileURL}" style="margin: 4px 5px 10px;"></td>
<td><%=iconHTML%></td>
<td><span style="font-size: 1.1em;"><a
href="javascript:downloadItem('${downloadFileURL}');"
title="Download latest version of ${file.name}">${file.name}</a></span></td>
<td><span style="margin-left: 10px; font-size: 1.1em;"><a
href="<%=userProfileLink%>" target="_blank"><%=fullName%></a></span></td>
<td><span
style="margin-left: 10px; font-size: 1.1em; color: #666;"><fmt:formatDate
type="both" dateStyle="medium" timeStyle="short"
value="${lastUpdated}" /></span></td>
</tr>
</c:forEach>
</tbody>
</table>
</c:if>
<c:if test="${empty farm.value}">
<p style="font-size: 1.2em; padding-top: 12px; padding-left: 5px;">The
repository of ${farm.key.name} is empty at the moment.</p>
</c:if>
</c:forEach>
<div style="padding: 15px 0;">
<button id="downloadButton" type="button" class="btn btn-primary"
onClick="downloadItem(getSelectedRadioFileId());">Download
latest version</button>
<portlet:renderURL var="showVersionsURL">
<portlet:param name="jspPage"
value="/html/farmrepository/show_all_versions.jsp" />
</portlet:renderURL>
<button class="btn" type="button" onClick="validateForm()">See
all versions</button>
</div>
</form>
</c:otherwise>
</c:choose>
</div>

@ -0,0 +1,92 @@
<%@include file="../init.jsp"%>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<%
String selectedItemId = (String) request.getAttribute("itemId");
String selectedItemName = (String) request.getAttribute("itemName");
pageContext.setAttribute("selectedItemName",selectedItemName);
pageContext.setAttribute("selectedItemId",selectedItemId);
Group group = (Group) GroupLocalServiceUtil.getGroup(PortalUtil.getScopeGroupId(request));
long currentGroupId = group.getGroupId();
String currentURL = PortalUtil.getCurrentURL(request);
pageContext.setAttribute("currentURL",currentURL);
List<WorkspaceVersion> fileVersions = (List<WorkspaceVersion>) renderRequest.getAttribute("versions");
if (fileVersions != null)
Collections.reverse(fileVersions);
pageContext.setAttribute("fileVersions", fileVersions);
String portletURLString = PortalUtil.getCurrentURL(request);
RowChecker rowChecker = new RowChecker(renderResponse);
String currentUsername = Utils.getCurrentUser(request).getUsername();
PortletURL portletURL = renderResponse.createRenderURL();
String iconHTML = IconsManager.getMDIconTextualName(selectedItemName).getHtml();
%>
<a class="btn btn-link btn-large no-padding" href="javascript: history.back();"><i
class="icon icon-angle-left"></i>&nbsp;Back to Private Repository Content</a>
<p class="lead">Available versions for: <strong>${selectedItemName}</strong></p>
<table id="example" class="display">
<tbody>
<thead>
<th colspan="2">
Version Number</th>
<th><span style="margin-left: 10px; font-size: 1.1em;">Created by
</span></th>
<th><span style="margin-left: 10px; font-size: 1.1em;">Created date (UTC)</span></th>
<th><span style="margin-left: 10px; font-size: 1.1em;">Current</span></th>
</thead>
<c:forEach var="file" items="${fileVersions}">
<tr>
<%
WorkspaceVersion version = (WorkspaceVersion) pageContext.getAttribute("file");
Date created = new Date(version.getCreated().getTimeInMillis());
pageContext.setAttribute("created", created);
String fullName = "";
String userProfileLink = "";
if (version.getUser() != null) {
fullName = Utils.getUserByUsername(version.getUser()).getFullname();
userProfileLink = Utils.getUserProfileLink(version.getUser());
}
pageContext.setAttribute("fullName", fullName);
pageContext.setAttribute("userProfileLink", userProfileLink);
%>
<portlet:resourceURL var="downloadVersionURL">
<portlet:param name="versionDownloadItemId" value="${selectedItemId}" />
<portlet:param name="versionDownloadName" value="${file.name}" />
</portlet:resourceURL>
<td><%=iconHTML%></td>
<td><span style="font-size: 1.1em;"><a
href="javascript:downloadVersion('${downloadVersionURL}');"
title="Download version ${file.name}">${file.name}</a></span></td>
<td><span style="margin-left: 10px; font-size: 1.1em;"><a
href="<%=userProfileLink%>" target="_blank"><%=fullName%></a></span></td>
<td><span
style="margin-left: 10px; font-size: 1.1em; color: #666;"><fmt:formatDate
type="both" dateStyle="medium" timeStyle="short"
value="${created}" /></span></td>
<td><span style="margin-left: 10px; font-size: 1.1em;">${file.currentVersion}</span></td>
</tr>
</c:forEach>
</tbody>
</table>
<aui:script>
Liferay.provide(
window,
'<portlet:namespace />associateCompanyUsers',
function() {
var addUserIds = Liferay.Util.listCheckedExcept(document.<portlet:namespace />fm, '<portlet:namespace />allRowIds');
if (addUserIds && confirm("Are you sure you want to associate the selected users to this company?")) {
document.<portlet:namespace />fm.<portlet:namespace />addUserIds.value = addUserIds;
submitForm(document.<portlet:namespace />fm, '<portlet:actionURL name="associateCompanyUsers"></portlet:actionURL>');
} else {
}
},
['liferay-util-list-fields']
);
</aui:script>

@ -0,0 +1,107 @@
<%@page import="org.apache.tika.sax.ToTextContentHandler"%>
<%@include file="../init.jsp"%>
<p class="lead">Administrators currently associated to <%= team.getName() %>:</p>
<liferay-portlet:renderURL varImpl="iteratorURL">
</liferay-portlet:renderURL>
<%
String orderByCol = ParamUtil.getString(request, "orderByCol");
String orderByType = ParamUtil.getString(request, "orderByType");
String sortingOrder = orderByType;
//Logic for toggle asc and desc
if (orderByType.equals("desc"))
orderByType = "asc";
else
orderByType = "desc";
if (Validator.isNull(orderByType)) {
orderByType = "asc";
}
%>
<aui:form action="<%=portletURLString%>" method="post" name="fm">
<liferay-ui:search-container var="searchContainer" delta="5"
deltaConfigurable="true"
emptyResultsMessage="Sorry. There are no users to display."
iteratorURL="<%=iteratorURL%>" rowChecker="<%=rowChecker%>"
orderByType="<%=orderByType%>">
<liferay-ui:search-container-results>
<%
int totalUsers = admins.size();
List<CompanyMember> sortableUsers = ListUtil.subList(admins, searchContainer.getStart(),
searchContainer.getEnd());
if (Validator.isNotNull(orderByCol)) {
Collections.sort(sortableUsers, new CompanyMemberComparator());
if (sortingOrder.equalsIgnoreCase("desc"))
Collections.reverse(sortableUsers);
}
pageContext.setAttribute("results", sortableUsers);
pageContext.setAttribute("total", totalUsers);
%>
</liferay-ui:search-container-results>
<liferay-ui:search-container-row
className="org.gcube.portlets.user.performfish.bean.CompanyMember"
modelVar="item" keyProperty="userId">
<liferay-ui:search-container-column-text orderable="true" name="Name">${item.fullname}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Email">${item.email}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Job Title">${item.jobTitle}</liferay-ui:search-container-column-text>
<c:set var="FarmAdministrator"></c:set>
<c:if test="${item.admin}">
<c:set var="FarmAdministrator">(Farm Administrator)</c:set>
</c:if>
<liferay-ui:search-container-column-text name="Farms"> ${item.associatedFarmNames} ${FarmAdministrator} </liferay-ui:search-container-column-text>
<portlet:actionURL name="removeFarmUsers" var="removeFarmUsersURL">
<portlet:param name="currentUsername" value="<%= currentUsername %>" />
<portlet:param name="currentGroupId" value="${currentGroupId}" />
<portlet:param name="companyUserId" value="${item.userId}" />
<portlet:param name="companyId" value="<%= Long.toString(team.getTeamId()) %>" />
</portlet:actionURL>
<%
final String hrefFix = "location.href='" + removeFarmUsersURL .toString()+"'";
%>
<liferay-ui:search-container-column-button name="Remove from Farms"
href="<%=hrefFix%>" />
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
<button name="delete" type="button" icon="icon-delete"
class="btn btn-warning"
onClick='<%=renderResponse.getNamespace() + "removeAdministratorRoleFromUsers();"%>'>Remove Administrator role from selected</button>
<aui:input name="removeUserIds" type="hidden" />
<aui:input name="teamId" type="hidden" value="<%= team.getTeamId() %>"/>
<aui:input name="currentUsername" type="hidden" value="<%= currentUsername %>"/>
<aui:input name="currentGroupId" type="hidden" value="<%= currentGroupId %>"/>
<input id="totalUsers" name="no" type="hidden" value="<%= admins.size() %>"/>
</aui:form>
<aui:script>
Liferay.provide(
window,
'<portlet:namespace />removeAdministratorRoleFromUsers',
function() {
var removeUserIds = Liferay.Util.listCheckedExcept(document.<portlet:namespace />fm, '<portlet:namespace />allRowIds');
var array = removeUserIds.split(',');
var totalUsers = document.getElementById('totalUsers');
if (array.length == totalUsers.value) {
alert("Forbidden: You are trying removing the role from all the users of the company, at least one must have it.")
return;
}
if (removeUserIds && confirm("Are you sure you want to remove the Administrator role from the selected users?")) {
document.<portlet:namespace />fm.<portlet:namespace />removeUserIds.value = removeUserIds;
submitForm(document.<portlet:namespace />fm, '<portlet:actionURL name="removeAdministratorRoleFromUsers"></portlet:actionURL>');
} else {
}
},
['liferay-util-list-fields']
);
</aui:script>

@ -0,0 +1,107 @@
<%@include file="../init.jsp"%>
<p class="lead">
Users currently associated to
<%= team.getName() %>:
</p>
<liferay-portlet:renderURL varImpl="iteratorURL">
</liferay-portlet:renderURL>
<%
String orderByCol = ParamUtil.getString(request, "orderByCol");
String orderByType = ParamUtil.getString(request, "orderByType");
String sortingOrder = orderByType;
//Logic for toggle asc and desc
if (orderByType.equals("desc"))
orderByType = "asc";
else
orderByType = "desc";
if (Validator.isNull(orderByType)) {
orderByType = "asc";
}
%>
<c:set var="currentGroupId"><%=currentGroupId %></c:set>
<aui:form action="<%=portletURLString%>" method="post" name="fm">
<liferay-ui:search-container var="searchContainer" delta="5"
deltaConfigurable="true"
emptyResultsMessage="Sorry. There are no users to display."
iteratorURL="<%=iteratorURL%>" rowChecker="<%=rowChecker%>"
orderByType="<%=orderByType%>">
<liferay-ui:search-container-results>
<%
int totalUsers = teamUsers.size();
List<CompanyMember> sortableUsers = ListUtil.subList(teamUsers, searchContainer.getStart(),
searchContainer.getEnd());
if (Validator.isNotNull(orderByCol)) {
Collections.sort(sortableUsers, new CompanyMemberComparator());
if (sortingOrder.equalsIgnoreCase("desc"))
Collections.reverse(sortableUsers);
}
pageContext.setAttribute("results", sortableUsers);
pageContext.setAttribute("total", totalUsers);
%>
</liferay-ui:search-container-results>
<liferay-ui:search-container-row
className="org.gcube.portlets.user.performfish.bean.CompanyMember"
modelVar="item" keyProperty="username">
<liferay-ui:search-container-column-text orderable="true" name="Name">${item.fullname}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Email">${item.email}</liferay-ui:search-container-column-text>
<c:set var="FarmAdministrator"></c:set>
<c:if test="${item.admin}">
<c:set var="FarmAdministrator">(Farm Administrator)</c:set>
</c:if>
<liferay-ui:search-container-column-text name="Farms"> ${item.associatedFarmNames} ${FarmAdministrator} </liferay-ui:search-container-column-text>
<portlet:actionURL name="removeFarmUsers" var="removeFarmUsersURL">
<portlet:param name="currentUsername" value="<%= currentUsername %>" />
<portlet:param name="currentGroupId" value="${currentGroupId}" />
<portlet:param name="companyUserId" value="${item.userId}" />
<portlet:param name="companyId" value="<%= Long.toString(team.getTeamId()) %>" />
</portlet:actionURL>
<%
final String hrefFix = "location.href='" + removeFarmUsersURL .toString()+"'";
%>
<liferay-ui:search-container-column-button name="Remove from Farms"
href="<%=hrefFix%>" />
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
<button name="delete" type="button" icon="icon-delete"
class="btn btn-warning"
onClick='<%=renderResponse.getNamespace() + "removeCompanUsers();"%>'>Remove
from Company</button>
<aui:input name="removeUserIds" type="hidden" />
<aui:input name="teamId" type="hidden" value="<%= team.getTeamId() %>" />
<aui:input name="currentUsername" type="hidden"
value="<%= currentUsername %>" />
<aui:input name="currentGroupId" type="hidden"
value="<%= currentGroupId %>" />
</aui:form>
<aui:script>
Liferay.provide(
window,
'<portlet:namespace />removeCompanUsers',
function() {
var removeUserIds = Liferay.Util.listCheckedExcept(document.<portlet:namespace />fm, '<portlet:namespace />allRowIds');
if (removeUserIds && confirm("Are you sure you want to remove the selected users from this company?")) {
document.<portlet:namespace />fm.<portlet:namespace />removeUserIds.value = removeUserIds;
submitForm(document.<portlet:namespace />fm, '<portlet:actionURL name="removeCompanUsers"></portlet:actionURL>');
} else {
}
},
['liferay-util-list-fields']
);
</aui:script>

@ -0,0 +1,85 @@
<%@include file="../init.jsp"%>
<p class="lead">Users currently associated to <%= farm.getName() %>:</p>
<liferay-portlet:renderURL varImpl="iteratorURL">
</liferay-portlet:renderURL>
<%
String orderByCol = ParamUtil.getString(request, "orderByCol");
String orderByType = ParamUtil.getString(request, "orderByType");
String sortingOrder = orderByType;
//Logic for toggle asc and desc
if (orderByType.equals("desc"))
orderByType = "asc";
else
orderByType = "desc";
if (Validator.isNull(orderByType)) {
orderByType = "asc";
}
%>
<aui:form action="<%=portletURLString%>" method="post" name="fm">
<liferay-ui:search-container var="searchContainer" delta="5"
deltaConfigurable="true"
emptyResultsMessage="Sorry. There are no users to display."
iteratorURL="<%=iteratorURL%>" rowChecker="<%=rowChecker%>"
orderByType="<%=orderByType%>">
<liferay-ui:search-container-results>
<%
int totalUsers = teamUsers.size();
List<GCubeUser> sortableUsers = ListUtil.subList(teamUsers, searchContainer.getStart(),
searchContainer.getEnd());
if (Validator.isNotNull(orderByCol)) {
Collections.sort(sortableUsers, new UserComparator());
if (sortingOrder.equalsIgnoreCase("desc"))
Collections.reverse(sortableUsers);
}
pageContext.setAttribute("results", sortableUsers);
pageContext.setAttribute("total", totalUsers);
%>
</liferay-ui:search-container-results>
<liferay-ui:search-container-row
className="org.gcube.vomanagement.usermanagement.model.GCubeUser"
modelVar="item" keyProperty="username">
<liferay-ui:search-container-column-text orderable="true" name="Name">${item.fullname}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Email">${item.email}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Position">${item.jobTitle}</liferay-ui:search-container-column-text>
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
<button name="delete" type="button" icon="icon-delete"
class="btn btn-warning"
onClick='<%=renderResponse.getNamespace() + "removeFarmUsers();"%>'>Remove
selected</button>
<aui:input name="removeUserIds" type="hidden" />
<aui:input name="farmId" type="hidden" value="<%= farm.getTeamId() %>"/>
<aui:input name="currentUsername" type="hidden" value="<%= currentUsername %>"/>
<aui:input name="currentGroupId" type="hidden" value="<%= currentGroupId %>"/>
</aui:form>
<aui:script>
Liferay.provide(
window,
'<portlet:namespace />removeFarmUsers',
function() {
var removeUserIds = Liferay.Util.listCheckedExcept(document.<portlet:namespace />fm, '<portlet:namespace />allRowIds');
if (removeUserIds && confirm("Are you sure you want to remove the selected users from this Farm?")) {
document.<portlet:namespace />fm.<portlet:namespace />removeUserIds.value = removeUserIds;
submitForm(document.<portlet:namespace />fm, '<portlet:actionURL name="removeFarmUsers"></portlet:actionURL>');
} else {
}
},
['liferay-util-list-fields']
);
</aui:script>

@ -0,0 +1,91 @@
<%@page import="org.apache.tika.sax.ToTextContentHandler"%>
<%@include file="../init.jsp"%>
<p class="lead">Administrators currently associated to <%= theFarm.getName() %>:</p>
<liferay-portlet:renderURL varImpl="iteratorURL">
</liferay-portlet:renderURL>
<%
String orderByCol = ParamUtil.getString(request, "orderByCol");
String orderByType = ParamUtil.getString(request, "orderByType");
String sortingOrder = orderByType;
//Logic for toggle asc and desc
if (orderByType.equals("desc"))
orderByType = "asc";
else
orderByType = "desc";
if (Validator.isNull(orderByType)) {
orderByType = "asc";
}
%>
<aui:form action="<%=portletURLString%>" method="post" name="fm">
<liferay-ui:search-container var="searchContainer" delta="5"
deltaConfigurable="true"
emptyResultsMessage="Sorry. There are no users to display."
iteratorURL="<%=iteratorURL%>" rowChecker="<%=rowChecker%>"
orderByType="<%=orderByType%>">
<liferay-ui:search-container-results>
<%
int totalUsers = admins.size();
List<GCubeUser> sortableUsers = ListUtil.subList(admins, searchContainer.getStart(),
searchContainer.getEnd());
if (Validator.isNotNull(orderByCol)) {
Collections.sort(sortableUsers, new UserComparator());
if (sortingOrder.equalsIgnoreCase("desc"))
Collections.reverse(sortableUsers);
}
pageContext.setAttribute("results", sortableUsers);
pageContext.setAttribute("total", totalUsers);
%>
</liferay-ui:search-container-results>
<liferay-ui:search-container-row
className="org.gcube.vomanagement.usermanagement.model.GCubeUser"
modelVar="item" keyProperty="userId">
<liferay-ui:search-container-column-text orderable="true" name="Name">${item.fullname}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Email">${item.email}</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="Position">${item.jobTitle}</liferay-ui:search-container-column-text>
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
<button name="delete" type="button" icon="icon-delete"
class="btn btn-warning"
onClick='<%=renderResponse.getNamespace() + "removeAdministratorRoleFromUsers();"%>'>Remove Administrator role from selected</button>
<aui:input name="removeUserIds" type="hidden" />
<aui:input name="teamId" type="hidden" value="<%= theFarm.getTeamId() %>"/>
<aui:input name="currentUsername" type="hidden" value="<%= currentUsername %>"/>
<aui:input name="currentGroupId" type="hidden" value="<%= currentGroupId %>"/>
<input id="totalUsers" name="no" type="hidden" value="<%= admins.size() %>"/>
</aui:form>
<aui:script>
Liferay.provide(
window,
'<portlet:namespace />removeAdministratorRoleFromUsers',
function() {
var removeUserIds = Liferay.Util.listCheckedExcept(document.<portlet:namespace />fm, '<portlet:namespace />allRowIds');
var array = removeUserIds.split(',');
var totalUsers = document.getElementById('totalUsers');
if (array.length == totalUsers.value) {
alert("Forbidden: You are trying removing the role from all the users of the company, at least one must have it.")
return;
}
if (removeUserIds && confirm("Are you sure you want to remove the Administrator role from the selected users?")) {
document.<portlet:namespace />fm.<portlet:namespace />removeUserIds.value = removeUserIds;
submitForm(document.<portlet:namespace />fm, '<portlet:actionURL name="removeAdministratorRoleFromUsers"></portlet:actionURL>');
} else {
}
},
['liferay-util-list-fields']
);
</aui:script>

@ -0,0 +1,47 @@
<%@include file="../init.jsp"%>
<%@ page import="com.liferay.portal.kernel.util.Constants"%>
<%@ page import="org.gcube.portlets.user.performfish.EmptyFormsDocumentsDisplay"%>
<liferay-portlet:actionURL portletConfiguration="true"
var="configurationURL" />
<p class="lead">Here you should enter the FolderId of the shared folder where the documents are located and whether it shows
Hatchery, Pre-ongrowing or Grow out documents.</p>
<%
String selectedPhase = GetterUtil.getString(portletPreferences.getValue(PFISHConstants.PHASE_PREFERENCE_ATTR_NAME, StringPool.BLANK));
String folderId = GetterUtil.getString(portletPreferences.getValue(EmptyFormsDocumentsDisplay.FOLDERID_PREFERENCE_ATTR_NAME, StringPool.BLANK));
pageContext.setAttribute("SHOW_HATCHERY", PFISHConstants.SHOW_HATCHERY);
pageContext.setAttribute("SHOW_PRE_ONGROWING", PFISHConstants.SHOW_PRE_ONGROWING);
pageContext.setAttribute("SHOW_GROW_OUT", PFISHConstants.SHOW_GROW_OUT);
%>
<aui:form action="<%=configurationURL%>" method="post" name="fm">
<aui:input name="<%=Constants.CMD%>" type="hidden"
value="<%=Constants.UPDATE%>" />
<aui:input name="preferences--folderId--" type="text"
cssClass="text long-field" showRequiredLabel="true" label="Folder Id"
inlineField="true" inlineLabel="left"
placeholder="The Id of the folder containing the files to display"
helpMessage="The Id of the folder containing the files to display"
value="<%=folderId%>" required="true">
</aui:input>
<aui:input
checked="<%= selectedPhase.equalsIgnoreCase(PFISHConstants.SHOW_HATCHERY) %>"
label="Hatchery" name="preferences--phase--" type="radio"
value="${SHOW_HATCHERY}"
helpMessage="By selecting this the portlet will show only files pertaining to Hatchery" />
<aui:input
checked="<%= selectedPhase.equalsIgnoreCase(PFISHConstants.SHOW_PRE_ONGROWING) %>"
label="Pre-ongrowing" name="preferences--phase--" type="radio"
value="${SHOW_PRE_ONGROWING}"
helpMessage="By selecting this the portlet will show only files pertaining to Pre-ongrowing" />
<aui:input
checked="<%= selectedPhase.equalsIgnoreCase(PFISHConstants.SHOW_GROW_OUT) %>"
label="Grow out" name="preferences--phase--" type="radio"
value="${SHOW_GROW_OUT}"
helpMessage="By selecting this the portlet will show only files pertaining to Grow out" />
<aui:button type="submit" value="Submit Preference" />
</aui:form>

@ -0,0 +1,146 @@
<%@include file="../init.jsp"%>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<%
List<ExternalFile> theSheets = (List<ExternalFile>) renderRequest.getAttribute("thefiles");
List<String> theSheetNames = (List<String>) renderRequest.getAttribute("theSheetNames");
pageContext.setAttribute("theSheetNames", theSheetNames);
pageContext.setAttribute("theSheets", theSheets);
List<ExternalFile> theInstructions = (List<ExternalFile>) renderRequest.getAttribute("theInstructions");
pageContext.setAttribute("theInstructions", theInstructions);
String selectedPhase = GetterUtil.getString(portletPreferences.getValue(PFISHConstants.PHASE_PREFERENCE_ATTR_NAME, StringPool.BLANK));
pageContext.setAttribute("selectedPhase", selectedPhase);
GCubeTeam theFarm = (GCubeTeam) request.getAttribute("theFarm");
pageContext.setAttribute("theFarm", theFarm);
%>
<c:if test="${not empty theFarm }">
<div class="row-fluid">
<div class="span6" style="border-right: 1px solid #ccc;">
<div style="width: 100%; text-align: left;">
<p style="font-size: 1.2em; padding-top: 12px; padding-left: 5px;">Empty
forms <span style="font-size: 1em;" class="hidden-desktop"> (Click on the file names to download)</span></p>
<c:choose>
<c:when test="${empty theSheets}">
<p style="font-size: 1.2em; padding-top: 12px; padding-left: 5px;">The
empty forms repository is empty at the moment. Please contact the
Managers</p>
</c:when>
<c:otherwise>
<table class="display">
<tbody>
<c:forEach var="file" items="${theSheets}">
<tr>
<portlet:resourceURL var="downloadFileURL">
<portlet:param name="fileToDownloadId" value="${file.id}" />
</portlet:resourceURL>
<%
WorkspaceItem item = (WorkspaceItem) pageContext.getAttribute("file");
String iconHTML = IconsManager.getMDIconTextualName(item.getName()).getHtml();
%>
<td><%=iconHTML%></td>
<td><span style="font-size: 1.1em; padding: 15px 10px; "><a
href="javascript:downloadItem('${downloadFileURL}');"
title="Download ${file.name}">${file.name}</a></span></td>
<td><a style="margin-right: 10px; "class="btn btn-primary btn-small visible-desktop"
href="javascript:downloadItem('${downloadFileURL}');">Download</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</c:otherwise>
</c:choose>
</div>
<div style="width: 100%; text-align: left;">
<p style="font-size: 1.2em; padding-top: 12px; padding-left: 5px;">Instructions:</p>
<c:choose>
<c:when test="${empty theSheets}">
<p style="font-size: 1.2em; padding-top: 12px; padding-left: 5px;">There
are no instructions at the moment. Please contact the Managers</p>
</c:when>
<c:otherwise>
<table class="display">
<tbody>
<c:forEach var="file" items="${theInstructions}">
<tr>
<portlet:resourceURL var="downloadFileURL">
<portlet:param name="fileToDownloadId" value="${file.id}" />
</portlet:resourceURL>
<%
WorkspaceItem item = (WorkspaceItem) pageContext.getAttribute("file");
String iconHTML = IconsManager.getMDIconTextualName(item.getName()).getHtml();
%>
<td><%=iconHTML%></td>
<td><span style="font-size: 1.1em; padding: 15px;"><a
href="javascript:downloadItem('${downloadFileURL}');"
title="Download ${file.name}">${file.name}</a></span></td>
<td><a class="btn btn-small visible-desktop"
href="javascript:downloadItem('${downloadFileURL}');">Download</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</c:otherwise>
</c:choose>
</div>
</div>
<div class="span6">
<portlet:resourceURL var="uploadFileURL" id="uploadFiles" />
<script
src="<%=request.getContextPath()%>/js/jquery.uploadfile.min.js"></script>
<script>
$(document).ready(function(){
var uploadObj = $("#multipleupload");
$("#multipleupload").uploadFile({
url:"<%=uploadFileURL.toString()%>",
multiple : false,
dragDrop : true,
sequential : true,
sequentialCount : 10,
maxFileSize: 50*1024*1024,
allowedTypes:"xlsx",
uploadErrorStr: "Upload not allowed: wrong file name, see note below.",
showStatusAfterSuccess: false,
fileName : "myfile",
onSubmit:function(files) {
var valideFormNamesLength = valideFormNames.length;
for (var i = 0; i < valideFormNamesLength; i++) {
if (valideFormNames[i] == files[0]) {
console.log("File name is OK: " + files[0]);
return true;
}
}
console.log("File name is wrong: " + files[0]);
return false;
},
onSuccess : function(files, data, xhr, pd) {
var content = JSON.parse(data);
console.log("content.uri=" + content.urlEncoded);
Liferay.fire('validateUserData',{
urlEncoded: content.urlEncoded,
fileName: content.fileName,
selectedPhase: '${selectedPhase}'
});
}
});
});
</script>
<div id="multipleupload" style="width:100%; height: 100px;">Select file to attach</div>
<div style="font-size: 1em; padding: 15px; margin-top: 75px; width: 90%;"><strong>Note:</strong>
files having different name from the original will not be accepted for submission. <button class="btn btn-primary" onClick="showFileNameWarningFromDOM(true);"><strong>?</strong></button></div>
<div class="alert alert-block" id="fileNamesExplain" style="display:none;">
<button type="button" class="close" data-dismiss="alert" onClick="showFileNameWarningFromDOM(false);">&times;</button>
<h4>Accepted file names are the following:</h4>
<ul>
<c:forEach var="file" items="${theSheets}">
<li>${file.name}</li>
</c:forEach>
</ul>
</div>
<script>
var valideFormNames = ${theSheetNames};
</script>
</div>
</div>
</c:if>

@ -0,0 +1,8 @@
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<div class="alert alert-error">
<h4>You are not authorised</h4>
It seems you don't have the permission to use this application. <strong>You must be an Administrator of this company to use this application.</strong>
</div>

@ -0,0 +1,8 @@
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<div class="alert alert-error">
<h4>You are not authorised</h4>
It seems you don't have the permission to use this application. <strong>You must be an Administrator of this farm to use this application.</strong>
</div>

@ -0,0 +1,8 @@
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<div class="alert alert-error">
<h4>You are not authorised</h4>
It seems you don't have the permission to use this application. <strong>You must belong to one association to use this application.</strong>
</div>

@ -0,0 +1,8 @@
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<div class="alert alert-error">
<h4>You are not authorised</h4>
It seems you don't have the permission to use this application. <strong>You must belong to one company to use this application.</strong>
</div>

@ -0,0 +1,8 @@
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<div class="alert alert-error">
<h4>You are not authorised</h4>
It seems you don't have the permission to use this application. <strong>You are not associated to any farm of the company.</strong>
</div>

@ -0,0 +1,9 @@
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<div class="alert alert-info">
<h4>Please select the farm you wish to operate</h4>
<strong>You are assigned to more than one company
Farm. You can work on one farm at a time.</strong>
</div>

@ -0,0 +1,8 @@
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<div class="alert alert-error">
<h4>There is an issue in your autorisations</h4>
It seems you belong to more than one company. <strong>You must belong to one company only to use this application.</strong>
</div>

@ -0,0 +1,9 @@
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<div class="alert alert-info">
<h4>Please select the farm you wish to operate</h4>
<strong>You are assigned to more than one company
Farm. You can work on one farm at a time.</strong>
</div>

@ -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">
We're sorry
<%=currentUser.getFirstName()%>. There was an error performing this operation. A Farm with the entered name may exists already, please choose antoher name or request support at <a href="https://support.d4science.org" target="_blank">https://support.d4science.org</a>
</p>
<a class="btn btn-large btn-primary" href="${normalState}"><i
class="icon icon-angle-left"></i>&nbsp;Close</a>
<div

@ -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">
We're sorry
<%=currentUser.getFirstName()%>. There was an error performing this operation. Try again, if the error occurs again please report this issue to <a href="https://support.d4science.org" target="_blank">https://support.d4science.org</a>
</p>
<a class="btn btn-large btn-primary" href="${normalState}"><i
class="icon icon-angle-left"></i>&nbsp;Close</a>
<div

@ -0,0 +1,44 @@
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<%@include file="../init.jsp"%>
<%
List<GCubeTeam> theFarms = (List<GCubeTeam>) request.getAttribute("theFarms");
pageContext.setAttribute("theFarms", theFarms);
%>
<script>
function setFarm(theFarmid) {
var ENCODED_PARAM = 'ZmFybUlk';
window.location.search = ENCODED_PARAM+'=' + theFarmid;
}
</script>
<div style="width: 100%; text-align: left; color: #3B5998;">
<table id="example" class="display">
<thead>
<th>Select</th>
<th><span style="margin-left: 25px; font-size: 1.1em;">Farm
Name</span></th>
<th><span style="margin-left: 10px; font-size: 1.1em;">Creation
Date (UTC)</span></th>
</thead>
<tbody>
<c:forEach var="farm" items="${theFarms}">
<%
GCubeTeam theFarm = (GCubeTeam) pageContext.getAttribute("farm");
String encodedFarmId = Utils.maskId(theFarm.getTeamId());
pageContext.setAttribute("encodedFarmId", encodedFarmId);
%>
<tr>
<td><button class="btn btn-primary"
onClick="setFarm('${encodedFarmId}');">Select</button></td>
<td><span
style="margin-left: 25px; font-size: 1.1em; color: #666;">${farm.teamName}</span></td>
<td><span
style="margin-left: 10px; font-size: 1.1em; color: #666;"><fmt:formatDate
type="both" dateStyle="medium" timeStyle="short"
value="${farm.createdate}" /></span></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>

@ -0,0 +1,27 @@
<%@include file="../init.jsp"%>
<%@ page import="com.liferay.portal.kernel.util.Constants" %>
<liferay-portlet:actionURL portletConfiguration="true"
var="configurationURL" />
<p class="lead">Here you can customise the documents (whether
Hatchery, Pre-ongrowing, Grow out or all three) this portlet will have
to show.</p>
<%
String selectedPhase = GetterUtil.getString(portletPreferences.getValue("phase", StringPool.BLANK));
pageContext.setAttribute("SHOW_ALL_PHASES", PFISHConstants.SHOW_ALL_PHASES);
pageContext.setAttribute("SHOW_HATCHERY", PFISHConstants.SHOW_HATCHERY);
pageContext.setAttribute("SHOW_PRE_ONGROWING", PFISHConstants.SHOW_PRE_ONGROWING);
pageContext.setAttribute("SHOW_GROW_OUT", PFISHConstants.SHOW_GROW_OUT);
%>
<aui:form action="<%=configurationURL%>" method="post" name="fm">
<aui:input name="<%=Constants.CMD%>" type="hidden"
value="<%=Constants.UPDATE%>" />
<aui:input checked="<%= selectedPhase.equalsIgnoreCase(PFISHConstants.SHOW_HATCHERY) %>" label="Hatchery" name="preferences--phase--" type="radio" value="${SHOW_HATCHERY}" helpMessage="By selecting this the portlet will show only files pertaining to Hatchery"/>
<aui:input checked="<%= selectedPhase.equalsIgnoreCase(PFISHConstants.SHOW_PRE_ONGROWING) %>" label="Pre-ongrowing" name="preferences--phase--" type="radio" value="${SHOW_PRE_ONGROWING}" helpMessage="By selecting this the portlet will show only files pertaining to Pre-ongrowing"/>
<aui:input checked="<%= selectedPhase.equalsIgnoreCase(PFISHConstants.SHOW_GROW_OUT) %>" label="Grow out" name="preferences--phase--" type="radio" value="${SHOW_GROW_OUT}" helpMessage="By selecting this the portlet will show only files pertaining to Grow out"/>
<aui:input checked="<%= selectedPhase.equalsIgnoreCase(PFISHConstants.SHOW_ALL_PHASES) %>" label="All of the 3 above" name="preferences--phase--" type="radio" value="${SHOW_ALL_PHASES}" helpMessage="By selecting this the portlet will show every file of the phases above"/>
<aui:button type="submit" value="Submit Preference"/>
</aui:form>

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save