Francesco Mangiacrapa 5 years ago
commit 0caf09e0e2

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/performfish-analytics-portlet-0.0.1-SNAPSHOT/WEB-INF/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/performfish-analytics-portlet-0.0.1-SNAPSHOT/WEB-INF/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"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" 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.7">
<attributes>
<attribute name="owner.project.facets" value="java"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/performfish-analytics-portlet-0.0.1-SNAPSHOT/WEB-INF/classes"/>
</classpath>

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>performfish-analytics-portlet</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
<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>com.google.gdt.eclipse.core.webAppProjectValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.google.gwt.eclipse.core.gwtProjectValidator</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>org.eclipse.wst.jsdt.core.jsNature</nature>
<nature>com.google.gwt.eclipse.core.gwtNature</nature>
</natures>
</projectDescription>

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/webapp"/>
<classpathentry 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,2 @@
eclipse.preferences.version=1
filesCopiedToWebInfLib=

@ -0,0 +1,5 @@
eclipse.preferences.version=1
jarsExcludedFromWebInfLib=
lastWarOutDir=/home/francesco-mangiacrapa/wseclipseluna/performfish-analytics-portlet/target
warSrcDir=src/main/webapp
warSrcDirIsOutput=false

@ -0,0 +1,2 @@
eclipse.preferences.version=1
entryPointModules=

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

@ -0,0 +1,8 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.compliance=1.7
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.source=1.7

@ -0,0 +1,3 @@
eclipse.preferences.version=1
org.eclipse.jpt.core.platform=eclipselink2_4
org.eclipse.jpt.jpa.core.discoverAnnotatedClasses=true

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

@ -0,0 +1,4 @@
activeProfiles=
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-analytics-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="context-root" value="performfish-analytics-portlet"/>
<property name="java-output-path" value="/performfish-analytics-portlet/target/performfish-analytics-portlet-0.0.1-SNAPSHOT/WEB-INF/classes"/>
</wb-module>
</project-modules>

@ -0,0 +1,7 @@
<root>
<facet id="jpt.jpa">
<node name="libprov">
<attribute name="provider-id" value="jpa-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="3.0"/>
<installed facet="wst.jsdt.web" version="1.0"/>
<installed facet="jpt.jpa" version="2.0"/>
<installed facet="liferay.portlet" version="6.0"/>
<installed facet="java" version="1.7"/>
</faceted-project>

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

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

@ -0,0 +1 @@
{"ide":{"scriptPaths":[]},"plugins":{"aui":{},"liferay":{},"yui":{}},"libs":["ecma5","browser"]}

@ -0,0 +1,335 @@
<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/xsd/maven-4.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</groupId>
<artifactId>performfish-analytics-portlet</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Maven Archetype for GWT</name>
<scm>
<connection>scm:svn:http://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/admin/${project.artifactId}</connection>
<developerConnection>scm:https://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/admin/${project.artifactId}</developerConnection>
<url>http://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/admin/${project.artifactId}</url>
</scm>
<properties>
<!-- Convenience property to set the GWT version -->
<gwt.version>2.7.0</gwt.version>
<distroDirectory>distro</distroDirectory>
<!-- GWT needs at least java 1.6 -->
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<webappDirectory>${project.build.directory}/${project.build.finalName}</webappDirectory>
<additionalparam>-Xdoclint:none</additionalparam>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<repositories>
<!-- USED BY ECLIPSELINK -->
<repository>
<id>eclipselink</id>
<url>http://maven.research-infrastructures.eu:8081/nexus/content/repositories/eclipselink/</url>
</repository>
</repositories>
<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>
<!-- Google Web Toolkit (GWT) -->
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-user</artifactId>
<version>${gwt.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-dev</artifactId>
<version>${gwt.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-servlet</artifactId>
<version>${gwt.version}</version>
<scope>provided</scope>
</dependency>
<!-- Eclipselink dependencies -->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<scope>compile</scope>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.gcube.common</groupId> -->
<!-- <artifactId>workspace-task-executor-library</artifactId> -->
<!-- <version>[0.0.1-SNAPSHOT, 2.0.0-SNAPSHOT)</version> -->
<!-- </dependency> -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.17</version>
</dependency>
<!-- H2 Database -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.170</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.github.gwtbootstrap</groupId>
<artifactId>gwt-bootstrap</artifactId>
<version>2.3.2.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-client</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>common-authorization</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.14.8</version>
</dependency>
<!-- FWS -->
<dependency>
<groupId>org.gcube.resources.discovery</groupId>
<artifactId>ic-client</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-scope-maps</artifactId>
<scope>compile</scope>
</dependency>
<!-- END FWS -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-encryption</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.portal</groupId>
<artifactId>custom-portal-handler</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.portal</groupId>
<artifactId>client-context-library</artifactId>
<version>[1.0.0-SNAPSHOT,)</version>
<scope>compile</scope>
</dependency>
<!-- PORTAL MANAGER -->
<dependency>
<groupId>org.gcube.common.portal</groupId>
<artifactId>portal-manager</artifactId>
<scope>provided</scope>
</dependency>
<!-- User Management Core -->
<dependency>
<groupId>org.gcube.dvos</groupId>
<artifactId>usermanagement-core</artifactId>
<scope>provided</scope>
</dependency>
<!-- LOGGER -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.liferay.portal</groupId>
<artifactId>portal-service</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.portlet</groupId>
<artifactId>portlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- Generate compiled stuff in the folder used for developing mode -->
<outputDirectory>${webappDirectory}/WEB-INF/classes</outputDirectory>
<plugins>
<!-- GWT Maven Plugin -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>gwt-maven-plugin</artifactId>
<version>${gwt.version}</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<!-- <goal>test</goal> -->
</goals>
</execution>
</executions>
<!-- Plugin configuration. There are many available options, see gwt-maven-plugin
documentation at codehaus.org -->
<configuration>
<runTarget>PerformFishAnalytics.html</runTarget>
<hostedWebapp>${webappDirectory}</hostedWebapp>
</configuration>
</plugin>
<!-- Copy static web files before executing gwt:run -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>exploded</goal>
</goals>
</execution>
</executions>
<configuration>
<webappDirectory>${webappDirectory}</webappDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</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>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>copy-profile</id>
<phase>install</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>target</outputDirectory>
<resources>
<resource>
<directory>${distroDirectory}</directory>
<filtering>true</filtering>
<includes>
<include>profile.xml</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='PerformFishAnalytics'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User' />
<!-- Inherit the default GWT style sheet. You can change -->
<!-- the theme of your GWT application by uncommenting -->
<!-- any one of the following lines. -->
<inherits name='com.google.gwt.user.theme.standard.Standard' />
<inherits name="com.github.gwtbootstrap.Bootstrap" />
<!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
<!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/> -->
<!-- Other module inherits -->
<!-- Specify the app entry point class. -->
<entry-point
class='org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalytics' />
<!-- Specify the paths for translatable code -->
<source path='client' />
<source path='shared' />
</module>

@ -0,0 +1,57 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client;
/**
* The Enum DataMinerAlgorithms.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Feb 8, 2019
*/
public enum DataMinerAlgorithms {
DEA_CHART("DEA_CHART", "DEA_CHART"),
SCATTER("SCATTER", "SCATTER"),
SPEEDOMETER("SPEEDOMETER","SPEEDOMETER"),
BOXPLOT("BOXPLOT","BOXPLOT"),
DEA_ANALYSIS("DEA_ANALYSIS", "DEA_ANALYSIS"),
CORRELATION("CORRELATION", "CORRELATION");
String id;
String name;
/**
* Instantiates a new data miner algorithms.
*
* @param id the id
* @param name the name
*/
DataMinerAlgorithms(String id, String name){
this.id = id;
this.name = name;
}
/**
* Gets the id.
*
* @return the id
*/
public String getId() {
return id;
}
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return name;
}
}

@ -0,0 +1,20 @@
package org.gcube.portlets.user.performfishanalytics.client;
import org.gcube.portlets.user.performfishanalytics.client.controllers.PerformFishAnalyticsController;
import com.google.gwt.core.client.EntryPoint;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class PerformFishAnalytics implements EntryPoint {
/**
* This is the entry point method.
*/
public void onModuleLoad() {
new PerformFishAnalyticsController();
}
}

@ -0,0 +1,46 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client;
/**
* The Class PerformFishAnalyticsConstant.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 30, 2019
*/
public class PerformFishAnalyticsConstant {
public static final String FARMID_PARAM = "farmid";
public static final String BATCHTYPE_PARAM = "batchtype";
// PERFORM-FISH SERVICE KEYS
public static final String BATCHES_TABLE_INTERNAL = "BatchesTable_internal";
public static final String BATCHES_TABLE = "BatchesTable";
// PARAMETERS TO CALL DATAMINER
public static final String DATA_INPUTS = "DataInputs";
public static final String DM_SCALEP_PARAM = "scaleP";
public static final String DM_BATCHTYPE_PARAM = "batchtype";
public static final String DM_CHARTTYPE_PARAM = "charttype";
public static final String DM_FARMFILE_PARAM = "farmFile";
public static final String DM_FOCUS_PARAM = "focus";
public static final String DM_INPUT_KPI_PARAM = "inputKPI";
public static final String DM_OUTPUT_KPI_PARAM = "outputKPI";
public static final int CSV_BATCHES_TABLE_MINIMUM_SIZE = 4;
public static final String PERFORM_FISH_AREA_PARAM = "area";
public static final String PERFORM_FISH_QUARTER_PARAM = "quarter";
public static final String PERFORM_FISH_PERIOD_PARAM = "period";
public static final String PERFORM_FISH_FARMID_PARAM = "farmid";
public static final String PERFORM_FISH_BATCH_TYPE_PARAM = "batch_type";
public static final String PERFORM_FISH_SPECIES_ID_PARAM = "speciesid";
public static final String DM_FOCUS_ID_ALL_VALUE = "ALL";
public static enum POPULATION_LEVEL{BATCH, FARM};
}

@ -0,0 +1,97 @@
package org.gcube.portlets.user.performfishanalytics.client;
import java.util.List;
import java.util.Map;
import org.gcube.portlets.user.performfishanalytics.shared.OutputFile;
import org.gcube.portlets.user.performfishanalytics.shared.PopulationType;
import org.gcube.portlets.user.performfishanalytics.shared.csv.CSVFile;
import org.gcube.portlets.user.performfishanalytics.shared.dataminer.DataMinerResponse;
import org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishInitParameter;
import org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishResponse;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
/**
* The client side stub for the RPC service.
*/
@RemoteServiceRelativePath("performfish")
public interface PerformFishAnalyticsService extends RemoteService {
/**
* @param populationName
* @return
* @throws Exception
*/
List<PopulationType> getListPopulationType(String populationName)
throws Exception;
/**
* @param populationTypeId
* @return
* @throws Exception
*/
PopulationType getPopulationTypeWithListKPI(String populationTypeId)
throws Exception;
/**
* @param initParams
* @return
* @throws Exception
*/
PerformFishInitParameter decryptAndValidParameters(
PerformFishInitParameter initParams)
throws Exception;
/**
* @param mapParameters
* @return
* @throws Exception
*/
PerformFishResponse submitRequestToPerformFishService(Map<String, List<String>> mapParameters) throws Exception;
DataMinerResponse callingDataMinerPerformFishCorrelationAnalysis(
PerformFishResponse result, Map<String, List<String>> mapParameters) throws Exception;
/**
* @param file
* @return
* @throws Exception
*/
String getImageFile(OutputFile file)
throws Exception;
/**
* @param file
* @return
* @throws Exception
*/
CSVFile readCSVFile(String URL)
throws Exception;
/**
* @param file
* @return
* @throws Exception
*/
CSVFile getCSVFile(OutputFile file, boolean deleteAfter)
throws Exception;
/**
* @param mapParameters
* @return
* @throws Exception
*/
DataMinerResponse callingDataMinerPerformFishAnalysis(
Map<String, List<String>> mapParameters)
throws Exception;
/**
* @param farmID
* @return
* @throws Exception
*/
boolean checkGrantToAccessFarmID(String farmID)
throws Exception;
}

@ -0,0 +1,80 @@
package org.gcube.portlets.user.performfishanalytics.client;
import java.util.List;
import java.util.Map;
import org.gcube.portlets.user.performfishanalytics.shared.OutputFile;
import org.gcube.portlets.user.performfishanalytics.shared.PopulationType;
import org.gcube.portlets.user.performfishanalytics.shared.csv.CSVFile;
import org.gcube.portlets.user.performfishanalytics.shared.dataminer.DataMinerResponse;
import org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishInitParameter;
import org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishResponse;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface PerformFishAnalyticsServiceAsync
{
/**
* Utility class to get the RPC Async interface from client-side code
*/
public static final class Util
{
private static PerformFishAnalyticsServiceAsync instance;
public static final PerformFishAnalyticsServiceAsync getInstance()
{
if ( instance == null )
{
instance = (PerformFishAnalyticsServiceAsync) GWT.create( PerformFishAnalyticsService.class );
}
return instance;
}
private Util()
{
// Utility class should not be instantiated
}
}
void getListPopulationType(
String populationName, AsyncCallback<List<PopulationType>> callback);
void getPopulationTypeWithListKPI(
String populationTypeId, AsyncCallback<PopulationType> callback);
void decryptAndValidParameters(
PerformFishInitParameter initParams,
AsyncCallback<PerformFishInitParameter> callback);
void submitRequestToPerformFishService(
Map<String, List<String>> mapParameters,
AsyncCallback<PerformFishResponse> callback);
void callingDataMinerPerformFishCorrelationAnalysis(
PerformFishResponse result, Map<String, List<String>> mapParameters,
AsyncCallback<DataMinerResponse> callback);
void getImageFile(OutputFile file, AsyncCallback<String> callback);
void readCSVFile(String URL, AsyncCallback<CSVFile> callback);
void getCSVFile(
OutputFile file, boolean deleteAfter, AsyncCallback<CSVFile> callback);
void callingDataMinerPerformFishAnalysis(
Map<String, List<String>> mapParameters,
AsyncCallback<DataMinerResponse> callback);
void checkGrantToAccessFarmID(String farmID, AsyncCallback<Boolean> callback);
}

@ -0,0 +1,720 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.controllers;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.gcube.portlets.user.performfishanalytics.client.DataMinerAlgorithms;
import org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsConstant;
import org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsConstant.POPULATION_LEVEL;
import org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsServiceAsync;
import org.gcube.portlets.user.performfishanalytics.client.event.AddedBatchIdEvent;
import org.gcube.portlets.user.performfishanalytics.client.event.AddedBatchIdEventHandler;
import org.gcube.portlets.user.performfishanalytics.client.event.CallAlgorithmEvent;
import org.gcube.portlets.user.performfishanalytics.client.event.CallAlgorithmEventHandler;
import org.gcube.portlets.user.performfishanalytics.client.event.LoadPopulationTypeEvent;
import org.gcube.portlets.user.performfishanalytics.client.event.LoadPopulationTypeEventHandler;
import org.gcube.portlets.user.performfishanalytics.client.event.PerformFishFieldFormChangedEvent;
import org.gcube.portlets.user.performfishanalytics.client.event.PerformFishFieldFormChangedEventHandler;
import org.gcube.portlets.user.performfishanalytics.client.event.SelectedKPIEvent;
import org.gcube.portlets.user.performfishanalytics.client.event.SelectedKPIEventHandler;
import org.gcube.portlets.user.performfishanalytics.client.event.SelectedPopulationTypeEvent;
import org.gcube.portlets.user.performfishanalytics.client.event.SelectedPopulationTypeEventHandler;
import org.gcube.portlets.user.performfishanalytics.client.event.SubmitRequestEvent;
import org.gcube.portlets.user.performfishanalytics.client.event.SubmitRequestEventHandler;
import org.gcube.portlets.user.performfishanalytics.client.view.LoaderIcon;
import org.gcube.portlets.user.performfishanalytics.client.viewbinder.AnalyticsPanelResult;
import org.gcube.portlets.user.performfishanalytics.client.viewbinder.ShowResult;
import org.gcube.portlets.user.performfishanalytics.client.viewbinder.SubmitRequestPanel;
import org.gcube.portlets.user.performfishanalytics.shared.KPI;
import org.gcube.portlets.user.performfishanalytics.shared.OutputFile;
import org.gcube.portlets.user.performfishanalytics.shared.csv.CSVFile;
import org.gcube.portlets.user.performfishanalytics.shared.dataminer.DataMinerResponse;
import org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishInitParameter;
import org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishResponse;
import com.github.gwtbootstrap.client.ui.Alert;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.Modal;
import com.github.gwtbootstrap.client.ui.Tab;
import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.github.gwtbootstrap.client.ui.constants.ButtonType;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* The Class PerformFishAnalyticsController.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jan 16, 2019
*/
public class PerformFishAnalyticsController {
/**
*
*/
public final static HandlerManager eventBus = new HandlerManager(null);
private PerformFishAnalyticsViewController viewController;
private PerformFishInitParameter decryptParameters;
/**
* Instantiates a new perform fish analytics controller.
*/
public PerformFishAnalyticsController() {
registerHandlers();
viewController = new PerformFishAnalyticsViewController();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
final String batchtypeParam = Window.Location.getParameter(PerformFishAnalyticsConstant.BATCHTYPE_PARAM);
final String farmidParam = Window.Location.getParameter(PerformFishAnalyticsConstant.FARMID_PARAM);
if(batchtypeParam==null || batchtypeParam.isEmpty()){
Window.alert("You must pass a valid '"+PerformFishAnalyticsConstant.BATCHTYPE_PARAM+"' param");
return;
}
if(farmidParam==null || farmidParam.isEmpty()){
Window.alert("You must pass a valid '"+PerformFishAnalyticsConstant.FARMID_PARAM+"' param");
return;
}
PerformFishInitParameter initParams = new PerformFishInitParameter();
initParams.addParameter(PerformFishAnalyticsConstant.BATCHTYPE_PARAM, batchtypeParam);
initParams.addParameter(PerformFishAnalyticsConstant.FARMID_PARAM, farmidParam);
PerformFishAnalyticsServiceAsync.Util.getInstance().decryptAndValidParameters(initParams, new AsyncCallback<PerformFishInitParameter>() {
@Override
public void onSuccess(PerformFishInitParameter result) {
decryptParameters = result;
eventBus.fireEvent(new LoadPopulationTypeEvent(POPULATION_LEVEL.BATCH.name(), null));
}
@Override
public void onFailure(Throwable caught) {
Window.alert(caught.getMessage());
}
});
}
});
}
/**
* Register handlers.
*/
private void registerHandlers() {
eventBus.addHandler(LoadPopulationTypeEvent.TYPE, new LoadPopulationTypeEventHandler() {
@Override
public void onLoadPopulationType(
LoadPopulationTypeEvent loadPopulationEvent) {
viewController.loadPopulationTypeForLevelAndBatchType(loadPopulationEvent.getPopulationName(), decryptParameters);
}
});
eventBus.addHandler(CallAlgorithmEvent.TYPE, new CallAlgorithmEventHandler() {
@Override
public void onCall(CallAlgorithmEvent callAlgorithmEvent) {
callAlgorithm(callAlgorithmEvent.getAlgorithm(), callAlgorithmEvent.getFocusID(), callAlgorithmEvent.getInputKPI(), callAlgorithmEvent.getOutputKPI());
}
});
eventBus.addHandler(SelectedPopulationTypeEvent.TYPE, new SelectedPopulationTypeEventHandler() {
@Override
public void onSelectedPopulationType(
SelectedPopulationTypeEvent selectedPopulationTypeEvent) {
viewController.setRootPopulationTypeForKPIs(selectedPopulationTypeEvent.getSelectedPopulationType());
}
});
eventBus.addHandler(SelectedKPIEvent.TYPE, new SelectedKPIEventHandler() {
@Override
public void onSelectedKPI(SelectedKPIEvent selectedKPI) {
viewController.manageKPI(selectedKPI.getKpi(), selectedKPI.isChecked(), selectedKPI.getSelectedPopulationType());
int selectedKPIsSize = viewController.getSelectedKPIs().size();
viewController.manageAlgorithmsSubmit(selectedKPIsSize);
}
});
eventBus.addHandler(PerformFishFieldFormChangedEvent.TYPE, new PerformFishFieldFormChangedEventHandler() {
@Override
public void onFieldFormChanged(
PerformFishFieldFormChangedEvent performFishFieldFormChangedEvent) {
viewController.setReloadPerformFishServiceData(true);
boolean isValidForm = viewController.validatePerformFishInputFields();
if(isValidForm){
viewController.hideErrors();
final Map<String, List<String>> mapParameters = new HashMap<String, List<String>>();
String farmId = decryptParameters.getParameters().get(PerformFishAnalyticsConstant.FARMID_PARAM);
String batchType = viewController.getForm().getBatchType();
String species = viewController.getForm().getSpecies();
List<String> listArea = viewController.getForm().getArea();
List<String> listPeriod = viewController.getForm().getPeriod();
List<String> listQuarter = viewController.getForm().getQuarter();
mapParameters.put(PerformFishAnalyticsConstant.PERFORM_FISH_FARMID_PARAM, Arrays.asList(farmId));
mapParameters.put(PerformFishAnalyticsConstant.PERFORM_FISH_BATCH_TYPE_PARAM, Arrays.asList(batchType));
mapParameters.put(PerformFishAnalyticsConstant.PERFORM_FISH_SPECIES_ID_PARAM, Arrays.asList(species));
if(!listArea.isEmpty()){
mapParameters.put(PerformFishAnalyticsConstant.PERFORM_FISH_AREA_PARAM, listArea);
}
if(!listPeriod.isEmpty()){
mapParameters.put(PerformFishAnalyticsConstant.PERFORM_FISH_PERIOD_PARAM, listPeriod);
}
if(!listQuarter.isEmpty()){
mapParameters.put(PerformFishAnalyticsConstant.PERFORM_FISH_QUARTER_PARAM, listQuarter);
}
final Modal modal = new Modal(true);
modal.setCloseVisible(false);
modal.hide(false);
final VerticalPanel vp = new VerticalPanel();
LoaderIcon loader = new LoaderIcon("Submitting request to perform-fish service...");
vp.add(loader);
loader.show(true);
modal.add(vp);
PerformFishAnalyticsServiceAsync.Util.getInstance().submitRequestToPerformFishService(mapParameters, new AsyncCallback<PerformFishResponse>() {
@Override
public void onFailure(Throwable caught) {
modal.hide();
Window.alert(caught.getMessage());
// Map<String, String> map = new HashMap<String, String>();
// map.put(PerformFishAnalyticsConstant.BATCHES_TABLE, "https://data.d4science.org/shub/d26ce359-ec85-44a5-84f6-50cc9ce05f03");
// map.put(PerformFishAnalyticsConstant.BATCHES_TABLE_INTERNAL, "https://data1-d.d4science.org/shub/E_WERuV1JhandFcWdUN0tUK2xtRVB3Tm9XT3AyLzlaWUVsVW9ZM2diRVU0V2wxWDNYUFlYVVhhQlU4K0FvV3h1Tg==");
// callDataMinerServiceForChartTypeCorrelation(new PerformFishResponse(map, null));
}
@Override
public void onSuccess(PerformFishResponse performFishResponse) {
modal.hide();
viewController.managePerformFishServiceResponse(performFishResponse, mapParameters, POPULATION_LEVEL.BATCH);
// Window.alert("FAKE ON-SUCCESS");
// Map<String, String> map = new HashMap<String, String>();
// map.put(PerformFishAnalyticsConstant.BATCHES_TABLE, "https://data.d4science.org/shub/d26ce359-ec85-44a5-84f6-50cc9ce05f03");
// map.put(PerformFishAnalyticsConstant.BATCHES_TABLE_INTERNAL, "https://data1-d.d4science.org/shub/E_WERuV1JhandFcWdUN0tUK2xtRVB3Tm9XT3AyLzlaWUVsVW9ZM2diRVU0V2wxWDNYUFlYVVhhQlU4K0FvV3h1Tg==");
// callDataMinerServiceForChartTypeCorrelation(new PerformFishResponse(map, null));
}
});
modal.show();
}else{
//IF IT IS NOT A VALID FORM WE NEED TO DISABLE DATAMINER REQUESTS
viewController.enableAllAlgorithmsSubmits(false);
}
}
});
eventBus.addHandler(AddedBatchIdEvent.TYPE, new AddedBatchIdEventHandler() {
@Override
public void onAddedBatchId(AddedBatchIdEvent checkValidBatchIdEvent) {
viewController.validateBatchIdSelection();
//viewController.resyncSelectedKPIs();
}
});
eventBus.addHandler(SubmitRequestEvent.TYPE, new SubmitRequestEventHandler() {
@Override
public void onSubmitRequest(SubmitRequestEvent submitRequestEvent) {
boolean isValidBatchId = viewController.validateBatchIdSelection();
boolean isValidKPI = viewController.validateKPIFields();
List<KPI> selectedKPI = viewController.getSelectedKPIs();
viewController.manageAlgorithmsSubmit(selectedKPI.size());
if(isValidBatchId && isValidKPI){
switch (submitRequestEvent.getChartType()) {
case BOXPLOT:
//UNARY
callAlgorithm(submitRequestEvent.getChartType(), viewController.getSelectedBatchID().get(0), selectedKPI, null);
break;
case SCATTER:
if(selectedKPI.size()==2)
callAlgorithm(submitRequestEvent.getChartType(), viewController.getSelectedBatchID().get(0), selectedKPI, null);
else
Window.alert("Something seems wrong... You must select exactly two KPIs to execute the "+submitRequestEvent.getChartType());
break;
case CORRELATION:
callDataMinerServiceForChartTypeCorrelation(viewController.getPerformFishResponse(), viewController.getRequestMapParameters());
break;
case SPEEDOMETER:
//UNARY
callAlgorithm(submitRequestEvent.getChartType(), viewController.getSelectedBatchID().get(0), selectedKPI, selectedKPI);
break;
default:
break;
}
}
return;
}
});
}
/**
* Call data miner service for chart type correlation.
*
* @param performFishResponse the perform fish response
* @param performFishRequestParameters the perform fish request parameters
*/
private void callDataMinerServiceForChartTypeCorrelation(final PerformFishResponse performFishResponse, final Map<String, List<String>> performFishRequestParameters) {
GWT.log("Read perform fish response: "+performFishResponse);
String batchTableURL = performFishResponse.getMapParameters().get(PerformFishAnalyticsConstant.BATCHES_TABLE);
if(batchTableURL==null || batchTableURL.isEmpty())
Window.alert("Something seems wrong. No batches tables matching with parameter "+PerformFishAnalyticsConstant.BATCHES_TABLE+" returned from service");
final Map<String, List<String>> mapParameters = new HashMap<String, List<String>>();
StringBuilder dataInputsFormatter = new StringBuilder();
dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_SCALEP_PARAM+"=BATCH;");
String theBatchType = viewController.getForm().getBatchType();
theBatchType = theBatchType.replace("_CLOSED_BATCHES", ""); //REMOVING SUFFIX _CLOSED_BATCHES FOR DATAMINER CALL
dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_BATCHTYPE_PARAM+"="+theBatchType+";");
dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_CHARTTYPE_PARAM+"="+ DataMinerAlgorithms.CORRELATION+";");
dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_FARMFILE_PARAM+"="+batchTableURL+";");
dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_FOCUS_PARAM+"=ID;");
String kpiCodes = "";
for (KPI kpi : viewController.getSelectedKPIs()) {
kpiCodes+=kpi.getCode()+"|";
}
//remove last |
kpiCodes = kpiCodes.substring(0, kpiCodes.length()-1);
dataInputsFormatter.append("inputKPI="+kpiCodes+";");
//dataInputsFormatter.append("outputKPI=;");
String dataInParameters = dataInputsFormatter.toString();
GWT.log("Calling DM service with client input parameters: "+dataInParameters);
mapParameters.put(PerformFishAnalyticsConstant.DATA_INPUTS, Arrays.asList(dataInParameters));
// final Modal modal = new Modal(true);
// modal.setCloseVisible(false);
// modal.hide(false);
final SubmitRequestPanel submitRequestPanel = new SubmitRequestPanel("");
submitRequestPanel.showLoader(true, "Submitting "+DataMinerAlgorithms.CORRELATION.getName()+" request to DM Service...");
String tabTitle = DataMinerAlgorithms.CORRELATION.getName().substring(0,1).toUpperCase()+DataMinerAlgorithms.CORRELATION.getName().toLowerCase().substring(1, DataMinerAlgorithms.CORRELATION.getName().length()); //CAMEL CASE
final Tab tab = viewController.createTab(submitRequestPanel, tabTitle+" #"+(viewController.currentNumberOfTab()+1));
PerformFishAnalyticsServiceAsync.Util.getInstance().callingDataMinerPerformFishCorrelationAnalysis(performFishResponse, mapParameters, new AsyncCallback<DataMinerResponse>() {
@Override
public void onSuccess(DataMinerResponse dmResponse) {
submitRequestPanel.showLoader(false, null);
viewController.noSpinner(tab);
final AnalyticsPanelResult analyticsPanelResult = new AnalyticsPanelResult();
analyticsPanelResult.addSelectedAreas(performFishRequestParameters.get(PerformFishAnalyticsConstant.PERFORM_FISH_AREA_PARAM));
analyticsPanelResult.addSelectedKPIs(viewController.getSelectedKPIs());
analyticsPanelResult.addListBatchIds(viewController.getListBatchesID());
analyticsPanelResult.addParameters(PerformFishAnalyticsConstant.DATA_INPUTS, mapParameters, viewController.getForm().getBatchType());
analyticsPanelResult.addResults(dmResponse);
submitRequestPanel.addWidget(analyticsPanelResult);
//viewController.geTabPanelView().addResult(resultPanel, "Analysis #"+(viewController.geTabPanelView().countTab()+1));
//modal.hide();
}
@Override
public void onFailure(Throwable caught) {
GWT.log(caught.toString());
submitRequestPanel.showLoader(false, null);
viewController.noSpinner(tab);
Alert error = new Alert(caught.getMessage());
error.setClose(false);
error.setType(AlertType.ERROR);
submitRequestPanel.addWidget(error);
Button butt = new Button("OK");
butt.setType(ButtonType.INFO);
//butt.getElement().getStyle().setProperty("text-align", "center");
butt.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
//modal.hide();
}
});
submitRequestPanel.addWidget(butt);
}
});
//modal.show();
}
/**
* Creating new TAB and calling DM algorithm.
*
* @param algorithm the algorithm
* @param focusID the focus id
* @param inputKPI the input kpi
* @param outputKPI the output kpi
*/
private void callAlgorithm(DataMinerAlgorithms algorithm, String focusID, List<KPI> inputKPI, final List<KPI> outputKPI){
List<String> listBatchID = viewController.getSelectedBatchID();
if(listBatchID==null || listBatchID.size()==0)
Window.alert("Something seems wrong, no selected BatchID, try again");
SubmitRequestPanel submitRequestPanel = new SubmitRequestPanel("");
//submitRequestPanel.getElement().addClassName("ext-horizontal-panel");
String tabTitle = algorithm.getName().substring(0,1).toUpperCase()+algorithm.getName().toLowerCase().substring(1, algorithm.getName().length()); //CAMEL CASE
Tab tab = viewController.createTab(submitRequestPanel, tabTitle+" #"+(viewController.currentNumberOfTab()+1));
switch (algorithm) {
case BOXPLOT:
case SPEEDOMETER:
//submitRequestPanel.setTheTitle(title);
for (KPI kpi : inputKPI) {
String title = "KPI: "+kpi.getName();
HTML toBigTitle = new HTML(title);
toBigTitle.getElement().addClassName("to-big-title");
submitRequestPanel.addWidget(toBigTitle);
HorizontalPanel hp = new HorizontalPanel();
hp.getElement().addClassName("ext-horizontal-panel");
callDataMinerServiceForChart(viewController.getPerformFishResponse(), POPULATION_LEVEL.BATCH, Arrays.asList(kpi), Arrays.asList(kpi), algorithm, focusID, hp, tab);
//resultPanel.add(hp);
submitRequestPanel.addWidget(hp);
}
break;
case SCATTER:
if(inputKPI.get(0)==null || inputKPI.get(1)==null){
submitRequestPanel.setTheTitle("Something seems wrong, one or more of the selected KPIs are not valid. Please try again");
return;
// Window.alert("Something seems wrong, no selected BatchID, try again");
}
String titleScatter = "KPI: "+inputKPI.get(0).getName() +" vs "+inputKPI.get(1).getName();
submitRequestPanel.setTheTitle(titleScatter);
default:
callDataMinerServiceForChart(viewController.getPerformFishResponse(), POPULATION_LEVEL.BATCH, inputKPI, outputKPI, algorithm, focusID, submitRequestPanel.getContainerPanel(), tab);
}
}
/**
* Call data miner service for chart.
*
* @param performFishResponse the perform fish response
* @param scalePValue the scale p value
* @param inputKPI the input kpi
* @param outputKPI the output kpi
* @param chartType the chart type
* @param focusID the focus id
* @param panelContainer the panel
* @param tab
*/
private void callDataMinerServiceForChart(PerformFishResponse performFishResponse, POPULATION_LEVEL scalePValue, final List<KPI> inputKPI, final List<KPI> outputKPI, final DataMinerAlgorithms chartType, final String focusID, final ComplexPanel panelContainer, final Tab tab) {
GWT.log("Read perform fish response: "+performFishResponse);
String batchTableURL = performFishResponse.getMapParameters().get(PerformFishAnalyticsConstant.BATCHES_TABLE);
if(batchTableURL==null || batchTableURL.isEmpty())
Window.alert("Something seems wrong. No batches tables matching with parameter "+PerformFishAnalyticsConstant.BATCHES_TABLE+" returned from service");
StringBuilder dataInputsFormatter = new StringBuilder();
dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_SCALEP_PARAM+"="+scalePValue.name()+";");
String theBatchType = viewController.getForm().getBatchType();
theBatchType = theBatchType.replace("_CLOSED_BATCHES", ""); //REMOVING SUFFIX _CLOSED_BATCHES FOR DATAMINER CALL
dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_BATCHTYPE_PARAM+"="+theBatchType+";");
dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_CHARTTYPE_PARAM+"="+ chartType +";");
dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_FARMFILE_PARAM+"="+batchTableURL+";");
dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_FOCUS_PARAM+"="+focusID+";");
//dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_FOCUS_PARAM+"=ID;");
if(inputKPI!=null && inputKPI.size()>0){
String kpiCodes = "";
for (KPI kpi : inputKPI) {
kpiCodes+=kpi.getCode()+"|";
}
//remove last |
kpiCodes = kpiCodes.substring(0, kpiCodes.length()-1);
GWT.log("Input KPICodes: "+kpiCodes);
//ADDING KPIs code
dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_INPUT_KPI_PARAM+"="+kpiCodes+";");
}
if(outputKPI!=null && outputKPI.size()>0){
String kpiCodes = "";
for (KPI kpi : outputKPI) {
kpiCodes+=kpi.getCode()+"|";
}
//remove last |
kpiCodes = kpiCodes.substring(0, kpiCodes.length()-1);
GWT.log("Output KPICodes: "+kpiCodes);
//ADDING KPIs code
dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_OUTPUT_KPI_PARAM+"="+kpiCodes+";");
}
String dataInParameters = dataInputsFormatter.toString();
GWT.log("Calling DM service with client input parameters: "+dataInParameters);
Map<String, List<String>> mapParameters = new HashMap<String, List<String>>();
mapParameters.put(PerformFishAnalyticsConstant.DATA_INPUTS, Arrays.asList(dataInParameters));
final LoaderIcon loaderIcon = new LoaderIcon("Submitting request to "+chartType+" Analysis...");
loaderIcon.setVisible(true);
panelContainer.setVisible(true);
panelContainer.add(loaderIcon);
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
loaderIcon.setFocus(true);
}});
PerformFishAnalyticsServiceAsync.Util.getInstance().callingDataMinerPerformFishAnalysis(mapParameters, new AsyncCallback<DataMinerResponse>() {
@Override
public void onSuccess(DataMinerResponse dmResponse) {
viewController.noSpinner(tab);
loaderIcon.setVisible(false);
//field_unary_algorithm.setVisible(true);
GWT.log("I'm displaying: "+dmResponse);
displayOutputFilesAsStaticEntities(dmResponse, chartType, inputKPI, outputKPI, focusID, panelContainer, false);
}
@Override
public void onFailure(Throwable caught) {
viewController.noSpinner(tab);
loaderIcon.setVisible(false);
displayOutputFilesAsStaticEntities(null, chartType, inputKPI, outputKPI, focusID, panelContainer, true);
}
});
}
/**
* Display output files as static entities.
*
* @param dmResponse the dm response
* @param chartType the chart type
* @param inputKPIs the input kp is
* @param outputKPIs the output kp is
* @param focusID the focus id
* @param container the container
* @param displayError the display error
*/
private void displayOutputFilesAsStaticEntities(DataMinerResponse dmResponse, final DataMinerAlgorithms chartType, List<KPI> inputKPIs, List<KPI> outputKPIs, final String focusID, final Panel container, boolean displayError){
String title = displayError?"No results ":"";
/*title+=chartType;
title+=inputKPIs.size()>1?" [Input KPIs: ":" [Input KPI: ";
for (KPI kpi : inputKPIs) {
title+=" "+kpi.getName()+",";
}
title = title.substring(0,title.length()-1)+"]";
if(outputKPIs!=null && outputKPIs.size()>0){
title+=inputKPIs.size()>1?" [Output KPIs: ":" [Output KPI: ";
for (KPI kpi : outputKPIs) {
title+=" "+kpi.getName()+",";
}
title = title.substring(0,title.length()-1)+"]";
}*/
//title+= " Focus "+focusID;
if(displayError){
Alert alert = new Alert(title);
alert.setType(AlertType.ERROR);
alert.setClose(false);
alert.getElement().getStyle().setMargin(10, Unit.PX);
container.add(alert);
return;
}
final String toTitle = title;
for (final OutputFile outputFile : dmResponse.getListOutput()) {
switch (outputFile.getDataType()) {
case IMAGE:
PerformFishAnalyticsServiceAsync.Util.getInstance().getImageFile(outputFile, new AsyncCallback<String>() {
@Override
public void onFailure(Throwable caught) {
//showAlert(caught.getMessage(), AlertType.ERROR, true, uib_vp_deanalanlysis_request_container);
Window.alert(caught.getMessage());
}
@Override
public void onSuccess(String base64Content) {
//String title = toTitle;
// switch (chartType) {
// case BOXPLOT:
// break;
// case SPEEDOMETER:
// title+= " BATCH ID: "+focusID;
// break;
// default:
// break;
// }
String title = toTitle;
switch (chartType) {
case BOXPLOT:
title = chartType.getName()+" - on all batches<br>";
title += "Blue dots indicate the selected batch(es): "+focusID;
break;
case CORRELATION:
break;
case DEA_ANALYSIS:
break;
case SCATTER:
break;
case SPEEDOMETER:
title = "Speedometer<br>";
title+= "Selected BATCH ID: "+focusID+"<br>";
title+= "Normalized with respect to all batches in the VRE";
break;
case DEA_CHART:
break;
}
ShowResult showResult = new ShowResult(title);
showResult.showImage(base64Content);
container.add(showResult);
}
});
break;
case CSV:
PerformFishAnalyticsServiceAsync.Util.getInstance().getCSVFile(outputFile, true, new AsyncCallback<CSVFile>() {
@Override
public void onFailure(Throwable caught) {
//showAlert(caught.getMessage(), AlertType.ERROR, true, uib_vp_deanalanlysis_request_container);
Window.alert(caught.getMessage());
}
@Override
public void onSuccess(CSVFile result) {
GWT.log("Displaying: "+result);
// String title = toTitle;
// switch (chartType) {
// case BOXPLOT:
// title+= " Statistics on all data";
// break;
// case SPEEDOMETER:
// title+= " BATCH ID: "+focusID;
// break;
// default:
// break;
// }
String title = toTitle;
switch (chartType) {
case BOXPLOT:
if(result.getFileName().contains("_user")){
title = "My Batch(es)";
}else{
title = "All batches in the VRE (including mine)";
}
break;
case CORRELATION:
break;
case DEA_ANALYSIS:
break;
case SCATTER:
break;
case SPEEDOMETER:
break;
case DEA_CHART:
break;
}
ShowResult showResult = new ShowResult(title);
showResult.showCSVFile(result);
container.add(showResult);
}
});
break;
default:
break;
}
}
}
}

@ -0,0 +1,491 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.controllers;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsConstant;
import org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsConstant.POPULATION_LEVEL;
import org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsServiceAsync;
import org.gcube.portlets.user.performfishanalytics.client.view.BaseDockLayoutPanel;
import org.gcube.portlets.user.performfishanalytics.client.view.BodyPanel;
import org.gcube.portlets.user.performfishanalytics.client.view.CustomTreeModel;
import org.gcube.portlets.user.performfishanalytics.client.view.HeaderPanel;
import org.gcube.portlets.user.performfishanalytics.client.viewbinder.BatchIDAndListKPIView;
import org.gcube.portlets.user.performfishanalytics.client.viewbinder.PerformFishAnalitycsFormView;
import org.gcube.portlets.user.performfishanalytics.client.viewbinder.PortletTitle;
import org.gcube.portlets.user.performfishanalytics.client.viewbinder.RecapSubmitPage;
import org.gcube.portlets.user.performfishanalytics.client.viewbinder.TabPanelView;
import org.gcube.portlets.user.performfishanalytics.shared.KPI;
import org.gcube.portlets.user.performfishanalytics.shared.Population;
import org.gcube.portlets.user.performfishanalytics.shared.PopulationType;
import org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishInitParameter;
import org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishResponse;
import com.github.gwtbootstrap.client.ui.ControlGroup;
import com.github.gwtbootstrap.client.ui.ListBox;
import com.github.gwtbootstrap.client.ui.Tab;
import com.github.gwtbootstrap.client.ui.constants.ControlGroupType;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.cellview.client.CellTree;
import com.google.gwt.user.cellview.client.TreeNode;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* The Class PerformFishAnalyticsViewController.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jan 16, 2019
*/
public class PerformFishAnalyticsViewController {
/**
*
*/
public static final String PERFORM_FISH_ANALYTICS_DIV = "perform-fish-analytics";
private BaseDockLayoutPanel baseDockLayoutPanel;
private HeaderPanel headerPage;
private BodyPanel bodyPage;
private BatchIDAndListKPIView batchIDAndListKPI;
private PerformFishAnalitycsFormView form;
private Population selectedPopulation;
private CustomTreeModel customTreeModel;
private CellTree tree;
private VerticalPanel westPanel;
private VerticalPanel estPanel;
private RecapSubmitPage recapPage;
private TabPanelView tabPanel;
private VerticalPanel rootPanel;
private boolean reloadPerformFishServiceData = true;
/**
* Instantiates a new perform fish analytics view controller.
*/
public PerformFishAnalyticsViewController() {
initLayout();
form = new PerformFishAnalitycsFormView();
//customTreeModel = new CustomTreeModel();
customTreeModel = new CustomTreeModel();
batchIDAndListKPI = new BatchIDAndListKPIView();
tree = new CellTree(customTreeModel, null);
//tree.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
westPanel.add(form);
estPanel.add(recapPage);
//bodyPage.add(form);
//tree.setWidth("600px");
//tree.setSize("600px", "800px");
batchIDAndListKPI.add(tree);
bodyPage.add(batchIDAndListKPI);
}
/**
* Inits the layout.
*/
private void initLayout(){
rootPanel = new VerticalPanel();
headerPage = new HeaderPanel();
bodyPage = new BodyPanel();
baseDockLayoutPanel = new BaseDockLayoutPanel(Unit.PX);
headerPage.showLoading(true, "Loading Data....");
westPanel = new VerticalPanel();
estPanel = new VerticalPanel();
recapPage = new RecapSubmitPage();
tabPanel = new TabPanelView();
headerPage.add(new PortletTitle("PerformFISH Statistical Analysis"));
//baseDockLayoutPanel.addNorth(headerPage, 60);
baseDockLayoutPanel.addWest(westPanel, 600);
baseDockLayoutPanel.addEast(estPanel, 500);
baseDockLayoutPanel.add(bodyPage);
tabPanel.getTabCreateRequestPanel().add(baseDockLayoutPanel);
rootPanel.add(headerPage);
rootPanel.add(tabPanel);
RootPanel.get(PERFORM_FISH_ANALYTICS_DIV).add(rootPanel);
}
/**
* Creates the tab.
*
* @param w the w
* @param tabTitle the tab title
* @return the tab
*/
public Tab createTab(Widget w, String tabTitle){
return tabPanel.addAsTab(w, tabTitle, true);
}
/**
* No spinner.
*
* @param tab the tab
*/
public void noSpinner(Tab tab){
tabPanel.setNoSpinner(tab);
}
/**
* Current number of tab.
*
* @return the int
*/
public int currentNumberOfTab(){
return tabPanel.countTab();
}
/**
* Gets the base panel.
*
* @return the basePanel
*/
public BaseDockLayoutPanel getBasePanel() {
return baseDockLayoutPanel;
}
/**
* Load population type for population name.
*
* @param populationName the population name
* @param decryptParameters the decrypt parameters
*/
public void loadPopulationTypeForLevelAndBatchType(final String populationName, final PerformFishInitParameter decryptParameters){
PerformFishAnalyticsServiceAsync.Util.getInstance().getListPopulationType(populationName, new AsyncCallback<List<PopulationType>>() {
@Override
public void onSuccess(List<PopulationType> result) {
headerPage.showLoading(false);
if(result.size()>0){
String passedBatchType = decryptParameters.getParameters().get(PerformFishAnalyticsConstant.BATCHTYPE_PARAM);
for (PopulationType populationType : result) {
if(populationType.getName().compareToIgnoreCase(passedBatchType)==0){
GWT.log("Found the passed batch type: "+populationType);
selectedPopulation = result.get(0).getPopulation();
form.addPopulationTypes(populationName, Arrays.asList(populationType), selectedPopulation);
}
}
}else{
Window.alert("No batch type found for level: "+populationName);
}
}
@Override
public void onFailure(Throwable caught) {
headerPage.showLoading(false);
String error = "Error on getting Population Type for population: "+populationName;
GWT.log(caught.getLocalizedMessage());
Window.alert(error);
}
});
}
/**
* Sets the root population type for kp is.
*
* @param rootPopulationType the new root population type for kp is
*/
public void setRootPopulationTypeForKPIs(final PopulationType rootPopulationType) {
GWT.log("Set root: "+rootPopulationType);
//customTreeModel.addChildrenListKPI(rootPopulationType.getListKPI());
PerformFishAnalyticsServiceAsync.Util.getInstance().getPopulationTypeWithListKPI(rootPopulationType.getId(), new AsyncCallback<PopulationType>() {
@Override
public void onFailure(Throwable caught) {
Window.alert("Error on loading KPIs for population type: "+rootPopulationType.getName());
}
@Override
public void onSuccess(PopulationType result) {
TreeNode rootNode = tree.getRootTreeNode();
customTreeModel.setNewBatchType(result);
// Open the first playlist by default.
TreeNode firstPlaylist = rootNode.setChildOpen(0, true);
//firstPlaylist.setChildOpen(0, true);
//IT SHOULD BE AN EVENT
recapPage.removeAllSelected();
}
});
}
/**
* Manage kpi.
*
* @param kpi the kpi
* @param checked the checked
* @param selectedPopulationType the selected population type
*/
public void manageKPI(KPI kpi, boolean checked, PopulationType selectedPopulationType) {
recapPage.manageKPI(kpi, checked);
}
/**
* Manage algorithms submit.
*
* @param selectedKPIsSize the selected kp is size
*/
public void manageAlgorithmsSubmit(int selectedKPIsSize) {
recapPage.activeAllAlgorithms(false);
if(selectedKPIsSize>0){
if(selectedKPIsSize==1){
recapPage.activeBoxPlot(true);
recapPage.activeSpeedometer(true);
}else if(selectedKPIsSize==2){
recapPage.activeAllAlgorithms(true);
}else{
//IS GREATER THAN 2
recapPage.activeAllAlgorithms(true);
recapPage.activeScatterPlot(false);
}
}
}
/**
* Enable all algorithms submits.
*
* @param bool the bool
*/
public void enableAllAlgorithmsSubmits(boolean bool){
recapPage.activeAllAlgorithms(bool);
}
/**
* Manage perform fish service response.
*
* @param performFishResponse the perform fish response
* @param mapParameters the map parameters
* @param populationLevel the population level
*/
public void managePerformFishServiceResponse(
PerformFishResponse performFishResponse,
Map<String, List<String>> mapParameters, POPULATION_LEVEL populationLevel) {
batchIDAndListKPI.managePerformFishServiceResponse(performFishResponse, mapParameters, populationLevel);
}
/**
* Gets the perform fish response.
*
* @return the perform fish response
*/
public PerformFishResponse getPerformFishResponse() {
return batchIDAndListKPI.getPerformFishResponse();
}
/**
* Gets the map parameters.
*
* @return the map parameters
*/
public Map<String, List<String>> getRequestMapParameters() {
return batchIDAndListKPI.getMapParameters();
}
/**
* Validate kpi fields.
*
* @return true, if successful
*/
public boolean validateKPIFields() {
bodyPage.hideError();
List<KPI> selectedKPIs = recapPage.getSelectedKPIs();
if(selectedKPIs.size()<1){
bodyPage.showError("You must select at least 1 KPI");
//recapPage.setError("You must select a KPI");
return false;
}
if(selectedKPIs.size()>10){
bodyPage.showError("You must select 10 KPI at most");
//recapPage.setError("You must select a KPI");
return false;
}
return true;
}
/**
* Validate batch id selection.
*
* @return true, if successful
*/
public boolean validateBatchIdSelection() {
ControlGroup cg_batch_id = batchIDAndListKPI.getControlGroupBatchID();
ListBox uib_list_batch_id = batchIDAndListKPI.getListBoxBatchId();
cg_batch_id.setType(ControlGroupType.NONE);
//CHECK THE FOCUS ID VALUE
String batchID = uib_list_batch_id.getSelectedItemText();
if(batchID==null || batchID.isEmpty()){
/*String msgError = "Could not execute a valid Analysis.";
List<String> selectedAreas = form.getArea();
if(selectedAreas==null || selectedAreas.isEmpty()){
msgError+=" Please select another parameters computation";
}else{
msgError+=" Select at least the Area of your FARM";
}
cg_batch_id.setType(ControlGroupType.ERROR);
batchIDAndListKPI.showError(msgError, true);
return false;*/
String msgError = "Could not find valid data. Please change the selection (Areas, Periods and so on) parameters";
cg_batch_id.setType(ControlGroupType.ERROR);
batchIDAndListKPI.showError(msgError, true);
return false;
}
//batchIDAndListKPI.showSelectionOK("Batch ID selection is valid", closable);
return true;
}
/**
* Validate perform fish input fields.
*
* @return true, if successful
*/
public boolean validatePerformFishInputFields() {
return form.validateForm();
}
/**
* Resync selected kp is.
*/
public void resyncSelectedKPIs() {
//customTreeModel.resync(getSelectedKPIs());
}
/**
* Gets the form.
*
* @return the form
*/
public PerformFishAnalitycsFormView getForm() {
return form;
}
/**
* Hide errors.
*/
public void hideErrors(){
bodyPage.hideError();
form.hideError(null, true);
}
/**
* Gets the selected kp is.
*
* @return the selected kp is
*/
public List<KPI> getSelectedKPIs(){
return recapPage.getSelectedKPIs();
}
/**
* Checks if is reload perform fish service data.
*
* @return true, if is reload perform fish service data
*/
public boolean isReloadPerformFishServiceData() {
return reloadPerformFishServiceData;
}
/**
* Sets the reload perform fish service data.
*
* @param reloadPerformFishServiceData the new reload perform fish service data
*/
public void setReloadPerformFishServiceData(boolean reloadPerformFishServiceData) {
this.reloadPerformFishServiceData = reloadPerformFishServiceData;
}
/**
* Gets the selected batch id.
*
* @return the selected batch id
*/
public List<String> getSelectedBatchID() {
return batchIDAndListKPI.getSelectedBatchID();
}
/**
* Gets the list batches id.
*
* @return the list batches id
*/
public List<String> getListBatchesID() {
return batchIDAndListKPI.getAllBatchesID();
}
}

@ -0,0 +1,152 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.dialog;
import org.gcube.portlets.user.performfishanalytics.client.resources.Icons;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* The Class DialogConfirm.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Feb 19, 2015
*/
public class DialogConfirm extends DialogBox implements ClickHandler {
private DockPanel dock = new DockPanel();
private Button yesButton;
private VerticalPanel vpContainer;
private ImageResource loading = Icons.ICONS.loading();
private HorizontalPanel hpButtons = new HorizontalPanel();
private Button noButton;
/**
* Instantiates a new dialog confirm.
*
* @param img the img
* @param caption the caption
* @param text the text
*/
public DialogConfirm(Image img, String caption, String text) {
getElement().setClassName("gwt-DialogBoxNew");
dock.setSpacing(4);
dock.setWidth("100%");
setText(caption);
// setHeading(caption);
yesButton = new Button("Yes");
noButton = new Button("No", this);
noButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
hide();
}
});
vpContainer = new VerticalPanel();
vpContainer.getElement().getStyle().setMargin(20.0, Unit.PX);
vpContainer.add(new HTML(text));
hpButtons = new HorizontalPanel();
hpButtons.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
// hpButtons.getElement().getStyle().setMarginTop(20.0, Unit.PX);
hpButtons.setSpacing(3);
yesButton.getElement().getStyle().setMarginRight(20.0, Unit.PX);
hpButtons.add(yesButton);
hpButtons.add(noButton);
dock.add(hpButtons, DockPanel.SOUTH);
dock.setCellHorizontalAlignment(hpButtons, DockPanel.ALIGN_CENTER);
if (img != null)
dock.add(img, DockPanel.WEST);
dock.add(vpContainer, DockPanel.CENTER);
setWidget(dock);
// add(dock);
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event
* .dom.client.ClickEvent)
*/
@Override
public void onClick(ClickEvent event) {
// hide();
}
/**
* Loader.
*
* @param message the message
*/
public void loader(String message){
try{
dock.remove(hpButtons);
}catch(Exception e){}
vpContainer.clear();
HorizontalPanel hpMask = new HorizontalPanel();
hpMask.add(new Image(loading));
HTML html = new HTML(message);
html.getElement().getStyle().setMarginLeft(5, Unit.PX);
hpMask.add(html);
vpContainer.add(hpMask);
}
/**
* Adds the to center panel.
*
* @param w the w
*/
public void addToCenterPanel(Widget w) {
vpContainer.add(w);
}
/**
* Gets the dock.
*
* @return the dock
*/
public DockPanel getDock() {
return dock;
}
/**
* Gets the yes button.
*
* @return the yes button
*/
public Button getYesButton() {
return yesButton;
}
/**
* Gets the no button.
*
* @return the no button
*/
public Button getNoButton() {
return noButton;
}
}

@ -0,0 +1,81 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.dialog;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;
// TODO: Auto-generated Javadoc
/**
* The Class DialogResult.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jan 19, 2018
*/
public class DialogResult extends DialogBox implements ClickHandler {
/** The dock. */
private DockPanel dock = new DockPanel();
/** The close button. */
private Button closeButton;
/**
* Instantiates a new dialog result.
*
* @param img the img
* @param title the title
* @param msg the msg
*/
public DialogResult(Image img, String title, String msg) {
getElement().setClassName("gwt-DialogBoxNew");
setText(title);
closeButton = new Button("Close", this);
dock.setSpacing(4);
dock.setWidth("100%");
dock.add(new HTML(msg), DockPanel.CENTER);
dock.add(closeButton, DockPanel.SOUTH);
if(img!=null)
dock.add(img, DockPanel.WEST);
dock.setCellHorizontalAlignment(closeButton, DockPanel.ALIGN_RIGHT);
setWidget(dock);
}
/**
* Gets the close button.
*
* @return the closeButton
*/
public Button getCloseButton() {
return closeButton;
}
/* (non-Javadoc)
* @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent)
*/
@Override
public void onClick(ClickEvent event) {
hide();
}
/**
* Adds the to center panel.
*
* @param w the w
*/
public void addToCenterPanel(Widget w){
dock.add(w, DockPanel.CENTER);
}
}

@ -0,0 +1,164 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.dialog;
import org.gcube.portlets.user.performfishanalytics.client.resources.Icons;
import com.github.gwtbootstrap.client.ui.Alert;
import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* The Class PanelConfirmBuilder.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Mar 13, 2018
*/
public abstract class PanelConfirmBuilder {
private DockPanel dock = new DockPanel();
private Button yesButton;
private VerticalPanel vpContainer;
private ImageResource loading = Icons.ICONS.loading();
private HorizontalPanel hpButtons = new HorizontalPanel();
private Button noButton;
/**
* On click no button.
*/
public abstract void onClickNoButton();
/**
* On click yes button.
*/
public abstract void onClickYesButton();
/**
* Instantiates a new panel confirm builder.
*
* @param img the img
* @param caption the caption
* @param text the text
*/
public PanelConfirmBuilder(Image img, String caption, String text, AlertType type) {
dock.setSpacing(4);
dock.setWidth("100%");
// setHeading(caption);
yesButton = new Button("Yes");
yesButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
onClickYesButton();
}
});
noButton = new Button("No");
noButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
onClickNoButton();
}
});
vpContainer = new VerticalPanel();
vpContainer.getElement().getStyle().setMargin(20.0, Unit.PX);
Alert txt = new Alert(text);
txt.setType(type);
txt.setClose(false);
vpContainer.add(txt);
hpButtons = new HorizontalPanel();
hpButtons.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
// hpButtons.getElement().getStyle().setMarginTop(20.0, Unit.PX);
hpButtons.setSpacing(3);
yesButton.getElement().getStyle().setMarginRight(20.0, Unit.PX);
hpButtons.add(yesButton);
hpButtons.add(noButton);
dock.add(hpButtons, DockPanel.SOUTH);
dock.setCellHorizontalAlignment(hpButtons, DockPanel.ALIGN_CENTER);
if (img != null)
dock.add(img, DockPanel.WEST);
dock.add(vpContainer, DockPanel.CENTER);
// add(dock);
}
/**
* Loader.
*
* @param message the message
*/
public void loader(String message){
try{
dock.remove(hpButtons);
}catch(Exception e){}
vpContainer.clear();
HorizontalPanel hpMask = new HorizontalPanel();
hpMask.add(new Image(loading));
HTML html = new HTML(message);
html.getElement().getStyle().setMarginLeft(5, Unit.PX);
hpMask.add(html);
vpContainer.add(hpMask);
}
/**
* Adds the to center panel.
*
* @param w the w
*/
public void addToCenterPanel(Widget w) {
vpContainer.add(w);
}
/**
* Gets the dock.
*
* @return the dock
*/
public DockPanel getPanel() {
return dock;
}
/**
* Gets the yes button.
*
* @return the yes button
*/
public Button getYesButton() {
return yesButton;
}
/**
* Gets the no button.
*
* @return the no button
*/
public Button getNoButton() {
return noButton;
}
}

@ -0,0 +1,38 @@
package org.gcube.portlets.user.performfishanalytics.client.event;
import com.google.gwt.event.shared.GwtEvent;
/**
* The Class AddedBatchIdEvent.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Feb 28, 2019
*/
public class AddedBatchIdEvent extends GwtEvent<AddedBatchIdEventHandler> {
public static Type<AddedBatchIdEventHandler> TYPE = new Type<AddedBatchIdEventHandler>();
/**
* Instantiates a new added batch id event.
*/
public AddedBatchIdEvent() {
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#getAssociatedType()
*/
@Override
public Type<AddedBatchIdEventHandler> getAssociatedType() {
return TYPE;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared.EventHandler)
*/
@Override
protected void dispatch(AddedBatchIdEventHandler handler) {
handler.onAddedBatchId(this);
}
}

@ -0,0 +1,21 @@
package org.gcube.portlets.user.performfishanalytics.client.event;
import com.google.gwt.event.shared.EventHandler;
/**
* The Interface AddedBatchIdEventHandler.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Feb 28, 2019
*/
public interface AddedBatchIdEventHandler extends EventHandler {
/**
* On added batch id.
*
* @param checkValidBatchIdEvent the check valid batch id event
*/
void onAddedBatchId(AddedBatchIdEvent checkValidBatchIdEvent);
}

@ -0,0 +1,96 @@
package org.gcube.portlets.user.performfishanalytics.client.event;
import java.util.List;
import org.gcube.portlets.user.performfishanalytics.client.DataMinerAlgorithms;
import org.gcube.portlets.user.performfishanalytics.shared.KPI;
import com.google.gwt.event.shared.GwtEvent;
/**
* The Class CallAlgorithmEvent.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Mar 5, 2019
*/
public class CallAlgorithmEvent extends GwtEvent<CallAlgorithmEventHandler> {
public static Type<CallAlgorithmEventHandler> TYPE = new Type<CallAlgorithmEventHandler>();
private DataMinerAlgorithms algorithm;
private String focusID;
private List<KPI> inputKPI;
private List<KPI> outputKPI;
/**
* Instantiates a new call algorithm event.
*
* @param algorithm the algorithm
* @param focusID the focus id
* @param inputKPI the input kpi
* @param outputKPI the output kpi
*/
public CallAlgorithmEvent(DataMinerAlgorithms algorithm, String focusID, List<KPI> inputKPI, final List<KPI> outputKPI) {
this.algorithm = algorithm;
this.focusID = focusID;
this.inputKPI = inputKPI;
this.outputKPI = outputKPI;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#getAssociatedType()
*/
@Override
public Type<CallAlgorithmEventHandler> getAssociatedType() {
return TYPE;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared.EventHandler)
*/
@Override
protected void dispatch(CallAlgorithmEventHandler handler) {
handler.onCall(this);
}
/**
* @return the algorithm
*/
public DataMinerAlgorithms getAlgorithm() {
return algorithm;
}
/**
* @return the focusID
*/
public String getFocusID() {
return focusID;
}
/**
* @return the inputKPI
*/
public List<KPI> getInputKPI() {
return inputKPI;
}
/**
* @return the outputKPI
*/
public List<KPI> getOutputKPI() {
return outputKPI;
}
}

@ -0,0 +1,22 @@
package org.gcube.portlets.user.performfishanalytics.client.event;
import com.google.gwt.event.shared.EventHandler;
/**
* The Interface CallAlgorithmEventHandler.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Mar 5, 2019
*/
public interface CallAlgorithmEventHandler extends EventHandler {
/**
* On call.
*
* @param callAlgorithmEvent the call algorithm event
*/
void onCall(CallAlgorithmEvent callAlgorithmEvent);
}

@ -0,0 +1,68 @@
package org.gcube.portlets.user.performfishanalytics.client.event;
import org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishInitParameter;
import com.google.gwt.event.shared.GwtEvent;
/**
* The Class LoadPopulationTypeEvent.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 22, 2019
*/
public class LoadPopulationTypeEvent extends GwtEvent<LoadPopulationTypeEventHandler> {
public static Type<LoadPopulationTypeEventHandler> TYPE = new Type<LoadPopulationTypeEventHandler>();
private String populationName;
private PerformFishInitParameter initParameters;
/**
* Instantiates a new load population type event.
*
* @param populationName the population name
* @param result
*/
public LoadPopulationTypeEvent(String populationName, PerformFishInitParameter result) {
if(populationName==null)
this.populationName = "BATCH";
this.populationName = populationName;
this.initParameters = result;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#getAssociatedType()
*/
@Override
public Type<LoadPopulationTypeEventHandler> getAssociatedType() {
return TYPE;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared.EventHandler)
*/
@Override
protected void dispatch(LoadPopulationTypeEventHandler handler) {
handler.onLoadPopulationType(this);
}
/**
* @return the initParameters
*/
public PerformFishInitParameter getInitParameters() {
return initParameters;
}
/**
* Gets the population name.
*
* @return the populationName
*/
public String getPopulationName() {
return populationName;
}
}

@ -0,0 +1,21 @@
package org.gcube.portlets.user.performfishanalytics.client.event;
import com.google.gwt.event.shared.EventHandler;
/**
* The Interface LoadPopulationTypeEventHandler.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 16, 2019
*/
public interface LoadPopulationTypeEventHandler extends EventHandler {
/**
* On load population type.
*
* @param loadPopulationEvent the load population event
*/
void onLoadPopulationType(LoadPopulationTypeEvent loadPopulationEvent);
}

@ -0,0 +1,63 @@
package org.gcube.portlets.user.performfishanalytics.client.event;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.user.client.ui.Widget;
/**
* The Class PerformFishFieldFormChangedEvent.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Feb 27, 2019
*/
public class PerformFishFieldFormChangedEvent extends GwtEvent<PerformFishFieldFormChangedEventHandler> {
public static Type<PerformFishFieldFormChangedEventHandler> TYPE = new Type<PerformFishFieldFormChangedEventHandler>();
private Widget sourceWidget;
/**
* Instantiates a new perform fish field form changed event.
*
* @param sourceWidget the source widget
*/
public PerformFishFieldFormChangedEvent(Widget sourceWidget) {
this.sourceWidget = sourceWidget;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#getAssociatedType()
*/
@Override
public Type<PerformFishFieldFormChangedEventHandler> getAssociatedType() {
return TYPE;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared.EventHandler)
*/
/**
* Dispatch.
*
* @param handler the handler
*/
@Override
protected void dispatch(PerformFishFieldFormChangedEventHandler handler) {
handler.onFieldFormChanged(this);
}
/**
* Gets the source widget.
*
* @return the sourceWidget
*/
public Widget getSourceWidget() {
return sourceWidget;
}
}

@ -0,0 +1,21 @@
package org.gcube.portlets.user.performfishanalytics.client.event;
import com.google.gwt.event.shared.EventHandler;
/**
* The Interface PerformFishFieldFormChangedEventHandler.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Feb 27, 2019
*/
public interface PerformFishFieldFormChangedEventHandler extends EventHandler {
/**
* On field form changed.
*
* @param performFishFieldFormChangedEvent the perform fish field form changed event
*/
void onFieldFormChanged(
PerformFishFieldFormChangedEvent performFishFieldFormChangedEvent);
}

@ -0,0 +1,84 @@
package org.gcube.portlets.user.performfishanalytics.client.event;
import org.gcube.portlets.user.performfishanalytics.shared.KPI;
import org.gcube.portlets.user.performfishanalytics.shared.PopulationType;
import com.google.gwt.event.shared.GwtEvent;
/**
* The Class SelectedKPIEvent.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 22, 2019
*/
public class SelectedKPIEvent extends GwtEvent<SelectedKPIEventHandler> {
public static Type<SelectedKPIEventHandler> TYPE = new Type<SelectedKPIEventHandler>();
private PopulationType selectedPopulationType;
private KPI kpi;
private boolean checked;
/**
* Instantiates a new selected population type event.
*
* @param selectedPopulationType the selected population type
* @param theKPI the the kpi
* @param checked the checked
*/
public SelectedKPIEvent(PopulationType selectedPopulationType, KPI theKPI, boolean checked) {
this.selectedPopulationType = selectedPopulationType;
this.kpi = theKPI;
this.checked = checked;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#getAssociatedType()
*/
@Override
public Type<SelectedKPIEventHandler> getAssociatedType() {
return TYPE;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared.EventHandler)
*/
@Override
protected void dispatch(SelectedKPIEventHandler handler) {
handler.onSelectedKPI(this);
}
/**
* Gets the kpi.
*
* @return the kpi
*/
public KPI getKpi() {
return kpi;
}
/**
* Gets the selected population type.
*
* @return the selectedPopulationType
*/
public PopulationType getSelectedPopulationType() {
return selectedPopulationType;
}
/**
* Checks if is checked.
*
* @return the checked
*/
public boolean isChecked() {
return checked;
}
}

@ -0,0 +1,20 @@
package org.gcube.portlets.user.performfishanalytics.client.event;
import com.google.gwt.event.shared.EventHandler;
/**
* The Interface SelectedPopulationTypeEventHandler.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 18, 2019
*/
public interface SelectedKPIEventHandler extends EventHandler {
/**
* On selected kpi.
*
* @param selectedKPI the selected kpi
*/
void onSelectedKPI(SelectedKPIEvent selectedKPI);
}

@ -0,0 +1,55 @@
package org.gcube.portlets.user.performfishanalytics.client.event;
import org.gcube.portlets.user.performfishanalytics.shared.PopulationType;
import com.google.gwt.event.shared.GwtEvent;
/**
* The Class SelectedPopulationTypeEvent.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 18, 2019
*/
public class SelectedPopulationTypeEvent extends GwtEvent<SelectedPopulationTypeEventHandler> {
public static Type<SelectedPopulationTypeEventHandler> TYPE = new Type<SelectedPopulationTypeEventHandler>();
private PopulationType selectedPopulationType;
/**
* Instantiates a new selected population type event.
*
* @param selectedPopulationType the selected population type
*/
public SelectedPopulationTypeEvent(PopulationType selectedPopulationType) {
this.selectedPopulationType = selectedPopulationType;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#getAssociatedType()
*/
@Override
public Type<SelectedPopulationTypeEventHandler> getAssociatedType() {
return TYPE;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared.EventHandler)
*/
@Override
protected void dispatch(SelectedPopulationTypeEventHandler handler) {
handler.onSelectedPopulationType(this);
}
/**
* Gets the selected population type.
*
* @return the selectedPopulationType
*/
public PopulationType getSelectedPopulationType() {
return selectedPopulationType;
}
}

@ -0,0 +1,22 @@
package org.gcube.portlets.user.performfishanalytics.client.event;
import com.google.gwt.event.shared.EventHandler;
/**
* The Interface SelectedPopulationTypeEventHandler.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 18, 2019
*/
public interface SelectedPopulationTypeEventHandler extends EventHandler {
/**
* On selected population type.
*
* @param selectedPopulationTypeEvent the selected population type event
*/
void onSelectedPopulationType(
SelectedPopulationTypeEvent selectedPopulationTypeEvent);
}

@ -0,0 +1,57 @@
package org.gcube.portlets.user.performfishanalytics.client.event;
import org.gcube.portlets.user.performfishanalytics.client.DataMinerAlgorithms;
import com.google.gwt.event.shared.GwtEvent;
/**
* The Class SubmitRequestEvent.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Feb 27, 2019
*/
public class SubmitRequestEvent extends GwtEvent<SubmitRequestEventHandler> {
public static Type<SubmitRequestEventHandler> TYPE = new Type<SubmitRequestEventHandler>();
private DataMinerAlgorithms chartType;
/**
* Instantiates a new submit request event.
*
* @param chartType the chart type
*/
public SubmitRequestEvent(DataMinerAlgorithms chartType) {
this.chartType = chartType;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#getAssociatedType()
*/
@Override
public Type<SubmitRequestEventHandler> getAssociatedType() {
return TYPE;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared.EventHandler)
*/
@Override
protected void dispatch(SubmitRequestEventHandler handler) {
handler.onSubmitRequest(this);
}
/**
* Gets the chart type.
*
* @return the chartType
*/
public DataMinerAlgorithms getChartType() {
return chartType;
}
}

@ -0,0 +1,21 @@
package org.gcube.portlets.user.performfishanalytics.client.event;
import com.google.gwt.event.shared.EventHandler;
/**
* The Interface SubmitRequestEventHandler.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 22, 2019
*/
public interface SubmitRequestEventHandler extends EventHandler {
/**
* On submit request.
*
* @param submitRequestEvent the submit request event
*/
void onSubmitRequest(SubmitRequestEvent submitRequestEvent);
}

@ -0,0 +1,76 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.resources;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
/**
* The Interface Icons.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 16, 2019
*/
public interface Icons extends ClientBundle {
public static final Icons ICONS = GWT.create(Icons.class);
/**
* Loading.
*
* @return the image resource
*/
@Source("loading4.gif")
ImageResource loading();
/**
* Top.
*
* @return the image resource
*/
@Source("top.png")
ImageResource top();
/**
* Maven.
*
* @return the image resource
*/
@Source("maven.png")
ImageResource maven();
/**
* Wiki.
*
* @return the image resource
*/
@Source("wiki.png")
ImageResource wiki();
/**
* Javadoc.
*
* @return the image resource
*/
@Source("javadoc.png")
ImageResource javadoc();
/**
* Download.
*
* @return the image resource
*/
@Source("download.png")
ImageResource download();
/**
* Github.
*
* @return the image resource
*/
@Source("github.png")
ImageResource github();
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 856 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 725 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 847 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 205 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 987 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 179 B

@ -0,0 +1,116 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.view;
import org.gcube.portlets.user.performfishanalytics.client.controllers.PerformFishAnalyticsViewController;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.ScrollEvent;
import com.google.gwt.user.client.Window.ScrollHandler;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.RootPanel;
/**
* The Class RootPanel.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 16, 2019
*/
public class BaseDockLayoutPanel extends DockLayoutPanel{
/**
* Instantiates a new root panel.
*
* @param unit the unit
*/
public BaseDockLayoutPanel(Unit unit) {
super(unit);
instanceHandlers();
}
/**
* Instance handlers.
*/
private void instanceHandlers() {
ScrollHandler scrollHandler = new Window.ScrollHandler() {
@Override
public void onWindowScroll(ScrollEvent event) {
// GWT.log("Scroll top: "+event.getScrollTop());
int scroll = event.getScrollTop();
int left = Window.getScrollLeft();
int height = Window.getClientHeight();
setNewPosition(scroll, left, height);
}
};
// Window.addResizeHandler(new ResizeHandler() {
//
// @Override
// public void onResize(ResizeEvent event) {
// int scroll = Window.getScrollTop();
// int left = Window.getScrollLeft();
// int height = Window.getClientHeight();
//// GWT.log("onResize height: "+Window.getClientHeight());
// setNewPosition(scroll, left, height);
// }
// });
Window.addResizeHandler(new ResizeHandler() {
@Override
public void onResize(ResizeEvent event) {
GWT.log("onWindowResized width: "+event.getWidth()+" height: "+event.getHeight());
updateSize();
}
});
updateSize();
}
/**
* Sets the new position.
*
* @param scrollTop the scroll top
* @param left the left
* @param height the height
*/
private void setNewPosition(int scrollTop, int left, int height){
if(scrollTop>400){
// GWT.log("height: "+height +" scrollTop: "+scrollTop);
scrollTop= scrollTop>0?scrollTop:1;
height = height>0?height:1;
int newPosition = scrollTop+height;
}
}
/**
* Update window size
*/
public void updateSize(){
RootPanel rootPanelArea = RootPanel.get(PerformFishAnalyticsViewController.PERFORM_FISH_ANALYTICS_DIV);
int topBorder = rootPanelArea.getAbsoluteTop();
int leftBorder = rootPanelArea.getAbsoluteLeft();
int footer = 85; //footer is bottombar + sponsor
int rootHeight = Window.getClientHeight() - topBorder - 4 - footer;// - ((footer == null)?0:(footer.getOffsetHeight()-15));
// if (rootHeight < 550)
// rootHeight = 550;
rootHeight+= 2000;
int rootWidth = Window.getClientWidth() - 2* leftBorder; //- rightScrollBar;
GWT.log("New workspace dimension Height: "+rootHeight+" Width: "+rootWidth);
setHeight(rootHeight+"px");
setWidth(rootWidth+"px");
}
}

@ -0,0 +1,100 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.view;
import com.github.gwtbootstrap.client.ui.Alert;
import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* The Class BodyPage.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Feb 19, 2015
*/
public class BodyPanel extends VerticalPanel{
private LoaderIcon loader = new LoaderIcon();
private FlowPanel panelError = new FlowPanel();
/**
* Instantiates a new body page.
*/
public BodyPanel() {
this.init();
add(panelError);
}
/**
* Inits the.
*/
private void init(){
add(loader);
loader.setVisible(false);
}
/**
* Sets the loading.
*
* @param bool the bool
* @param text the text
*/
public void setLoading(boolean bool, String text){
loader.setVisible(bool);
loader.setText(text);
}
/**
* Reset.
*/
public void reset() {
this.clear();
this.init();
}
/**
* Show error.
*
* @param txt the txt
*/
public void showError(String txt) {
panelError.clear();
panelError.setVisible(true);
Alert msg = new Alert(txt);
msg.setAnimation(true);
msg.setClose(false);
msg.setType(AlertType.ERROR);
panelError.add(msg);
}
/**
* Hide error.
*/
public void hideError(){
panelError.setVisible(false);
}
/**
* Show message.
*
* @param txt the txt
*/
public void showMessage(String txt) {
FlowPanel panel = new FlowPanel();
String html = "<div style=\"color:blue\">";
if(txt!=null && txt.length()>0)
html+=txt;
// panel.add(new HTML(label));
else
html+="No data";
// panel.add(new HTML("No data"));
html+="</div>";
panel.add(new HTML(html));
add(panel);
}
}

@ -0,0 +1,308 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.view;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.gcube.portlets.user.performfishanalytics.client.controllers.PerformFishAnalyticsController;
import org.gcube.portlets.user.performfishanalytics.client.event.SelectedKPIEvent;
import org.gcube.portlets.user.performfishanalytics.client.view.util.ExtendedCheckboxCell;
import org.gcube.portlets.user.performfishanalytics.shared.KPI;
import org.gcube.portlets.user.performfishanalytics.shared.PopulationType;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.CompositeCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.HasCell;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.TreeViewModel;
/**
* The model that defines the nodes in the tree.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Feb 28, 2019
*/
public class CopyOfCustomTreeModel implements TreeViewModel {
// private final List<PopulationType> kpis = new
// ArrayList<PopulationType>();
/**
* This selection model is shared across all leaf nodes. A selection model
* can also be shared across all nodes in the tree, or each set of child
* nodes can have its own instance. This gives you flexibility to determine
* how nodes are selected.
*/
private ListDataProvider<KPI> populationTypeProvider = new ListDataProvider<KPI>();
private ListDataProvider<KPI> kpiProvider = new ListDataProvider<KPI>();
private MultiSelectionModel<KPI> multiSelectionModel = new MultiSelectionModel<KPI>(kpiProvider);
private List<CompositeCell<KPI>> listKPIAdded = new ArrayList<CompositeCell<KPI>>();
private Map<String, ExtendedCheckboxCell> mapCheckBoxCell = new HashMap<String, ExtendedCheckboxCell>();
//private List<HasCell<KPI, ?>> hasCells;
//private ListDataProvider<KPI> kpiProvider;
//private Cell<KPI> kpiCell;
// private ListDataProvider<KPI> dataProvider = new ListDataProvider<KPI>();
/**
* Instantiates a new custom tree model.
*/
public CopyOfCustomTreeModel() {
//init();
multiSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
public void onSelectionChange(SelectionChangeEvent event) {
GWT.log("Selected: " + multiSelectionModel.getSelectedSet());
}
});
}
/**
* Resync.
*
* @param selectedKPI the selected kpi
*/
public void resync(List<KPI> selectedKPI){
for (KPI kpi : selectedKPI) {
ExtendedCheckboxCell checkBoxCell = mapCheckBoxCell.get(kpi.getId());
GWT.log("Checkbox is: "+checkBoxCell);
if(checkBoxCell!=null){
GWT.log("Resetting checked");
checkBoxCell.setChecked(true);
}
}
}
/**
* Builds the kpi cell.
*
* @return the composite cell
*/
public CompositeCell<KPI> buildKPICell() {
// Construct a composite cell for contacts that includes a checkbox.
ArrayList<HasCell<KPI, ?>> hasCells = new ArrayList<HasCell<KPI, ?>>();
HasCell<KPI, Boolean> checkBoxCell = new HasCell<KPI, Boolean>() {
private ExtendedCheckboxCell cell = new ExtendedCheckboxCell(true, true);
public Cell<Boolean> getCell() {
return cell;
}
public FieldUpdater<KPI, Boolean> getFieldUpdater() {
return new FieldUpdater<KPI, Boolean>() {
@Override
public void update(int index, KPI object, Boolean value) {
// TODO Auto-generated method stub
GWT.log("Checked: "+object.getName() + " value: "+value);
PerformFishAnalyticsController.eventBus.fireEvent(new SelectedKPIEvent(null, object, value));
if(value.booleanValue())
mapCheckBoxCell.put(object.getId(), cell);
else
mapCheckBoxCell.remove(object.getId());
// cell.set(value);
// dataGrid.redraw();
}
};
}
public Boolean getValue(KPI object) {
return multiSelectionModel.isSelected(object);
}
};
hasCells.add(checkBoxCell);
hasCells.add(new HasCell<KPI, KPI>() {
private KPICell cell = new KPICell(null);
public Cell<KPI> getCell() {
return cell;
}
public FieldUpdater<KPI, KPI> getFieldUpdater() {
return null;
}
public KPI getValue(KPI object) {
return object;
}
});
CompositeCell<KPI> kpiCell = new CompositeCell<KPI>(hasCells) {
@Override
public void render(Context context, KPI value, SafeHtmlBuilder sb) {
if(value.isLeaf()){
sb.appendHtmlConstant("<table style=\"color:#0066cc;\"><tbody><tr>");
super.render(context, value, sb);
sb.appendHtmlConstant("</tr></tbody></table>");
}else{
sb.appendHtmlConstant("<table><tbody><tr>");
sb.appendHtmlConstant(value.getName());
sb.appendHtmlConstant("</tr></tbody></table>");
}
}
@Override
protected Element getContainerElement(Element parent) {
// Return the first TR element in the table.
if(parent!=null){
if(parent.getFirstChildElement()!=null){
if(parent.getFirstChildElement().getFirstChildElement()!=null){
return parent.getFirstChildElement().getFirstChildElement().getFirstChildElement();
}
}
}
return null;
}
@Override
protected <X> void render(
Context context, KPI value, SafeHtmlBuilder sb,
HasCell<KPI, X> hasCell) {
Cell<X> cell = hasCell.getCell();
sb.appendHtmlConstant("<td>");
cell.render(context, hasCell.getValue(value), sb);
sb.appendHtmlConstant("</td>");
}
};
return kpiCell;
}
/**
* Sets the new batch type.
*
* @param populationType the new new batch type
*/
public void setNewBatchType(PopulationType populationType) {
//GWT.log("Displayng KPI for: " + populationType.toString());
if (this.populationTypeProvider != null) {
//removing all data from base data provider
this.populationTypeProvider.getList().clear();
this.populationTypeProvider.getList().addAll(populationType.getListKPI());
}
}
/**
* Get the {@link NodeInfo} that provides the children of the specified
* value.
*
* @param <T> the generic type
* @param value the value
* @return the node info
*/
public <T> NodeInfo<?> getNodeInfo(T value) {
GWT.log("Get Node Info fired: " + value);
if (value == null) {
// LEVEL 0.
// We passed null as the root value. Create a fake root KPIs
PopulationType rootKPI = new PopulationType("", "KPIs", "", "", null);
rootKPI.setListKPI(rootKPI.getListKPI());
ListDataProvider<PopulationType> rootProvider = new ListDataProvider<PopulationType>();
rootProvider.getList().add(rootKPI);
Cell<PopulationType> cell = new AbstractCell<PopulationType>() {
@Override
public void render(
com.google.gwt.cell.client.Cell.Context context,
PopulationType value, SafeHtmlBuilder sb) {
GWT.log("Rendering Root: " + value + " KPIs: " +
value.getListKPI());
// sb.appendHtmlConstant(" ROOT ");
sb.appendEscaped(value.getName());
}
};
// Return a node info that pairs the data provider and the cell.
return new DefaultNodeInfo<PopulationType>(rootProvider, cell);
}
else if (value instanceof PopulationType) {
// LEVEL 1.
// We want the children of PopulationType. Getting its list of KPI.
// List<KPI> listOfKpi = ((PopulationType) value).getListKPI();
GWT.log("PopulationType listOfKpi: " + populationTypeProvider.getList());
//return new DefaultNodeInfo<KPI>(populationTypeProvider, kpiCell, multiSelectionModel, null);
CompositeCell<KPI> kpiCell = buildKPICell();
listKPIAdded.add(kpiCell);
return new DefaultNodeInfo<KPI>(populationTypeProvider, kpiCell);
}
else if (value instanceof KPI) {
// LEVEL 2 - LEAF.
// We want the children of the KPI. Return them.
List<KPI> listOfKpi = ((KPI) value).getListKPI();
GWT.log("KPI type listOfKpi: " + listOfKpi.toString());
ListDataProvider<KPI> localProvider = new ListDataProvider<KPI>(listOfKpi);
kpiProvider.getList().addAll(listOfKpi);
// kpiProvider.
// multiSelectionModel.
CompositeCell<KPI> kpiCell = buildKPICell();
listKPIAdded.add(kpiCell);
return new DefaultNodeInfo<KPI>(localProvider, kpiCell);
}
return null;
}
/**
* Check if the specified value represents a leaf node. Leaf nodes cannot be
* opened.
*
* @param value the value
* @return true, if is leaf
*/
public boolean isLeaf(Object value) {
if(value==null)
return false;
// The leaf nodes are the songs, which are Strings.
if (value instanceof KPI) {
KPI toKPI = (KPI) value;
return toKPI.isLeaf();
}
return false;
}
}

@ -0,0 +1,281 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.view;
import java.util.ArrayList;
import java.util.List;
import org.gcube.portlets.user.performfishanalytics.client.controllers.PerformFishAnalyticsController;
import org.gcube.portlets.user.performfishanalytics.client.event.SelectedKPIEvent;
import org.gcube.portlets.user.performfishanalytics.shared.KPI;
import org.gcube.portlets.user.performfishanalytics.shared.PopulationType;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.CompositeCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.HasCell;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.TreeViewModel;
/**
* The model that defines the nodes in the tree.
*/
public class Copy_2_of_CustomTreeModel implements TreeViewModel {
// private final List<PopulationType> kpis = new
// ArrayList<PopulationType>();
/**
* This selection model is shared across all leaf nodes. A selection model
* can also be shared across all nodes in the tree, or each set of child
* nodes can have its own instance. This gives you flexibility to determine
* how nodes are selected.
*/
private final MultiSelectionModel<KPI> multiSelectionModel =
new MultiSelectionModel<KPI>();
private ListDataProvider<PopulationType> rootProvider =
new ListDataProvider<PopulationType>();
private ListDataProvider<KPI> populationTypeProvider =
new ListDataProvider<KPI>();
private ListDataProvider<KPI> kpiProvider = new ListDataProvider<KPI>();
private Cell<KPI> kpiCell;
// private ListDataProvider<KPI> dataProvider = new ListDataProvider<KPI>();
public Copy_2_of_CustomTreeModel() {
init();
multiSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
public void onSelectionChange(SelectionChangeEvent event) {
GWT.log("Selected: " + multiSelectionModel.getSelectedSet());
}
});
}
public void init() {
// Construct a composite cell for contacts that includes a checkbox.
final List<HasCell<KPI, ?>> hasCells = new ArrayList<HasCell<KPI, ?>>();
hasCells.add(new HasCell<KPI, Boolean>() {
private CheckboxCell cell = new CheckboxCell(true, false);
public Cell<Boolean> getCell() {
return cell;
}
public FieldUpdater<KPI, Boolean> getFieldUpdater() {
return new FieldUpdater<KPI, Boolean>() {
@Override
public void update(int index, KPI object, Boolean value) {
// TODO Auto-generated method stub
GWT.log("Checked: "+object.getName() + " value: "+value);
PerformFishAnalyticsController.eventBus.fireEvent(new SelectedKPIEvent(null, object, value));
}
};
}
public Boolean getValue(KPI object) {
return multiSelectionModel.isSelected(object);
}
});
hasCells.add(new HasCell<KPI, KPI>() {
private KPICell cell = new KPICell(null);
public Cell<KPI> getCell() {
return cell;
}
public FieldUpdater<KPI, KPI> getFieldUpdater() {
return null;
}
public KPI getValue(KPI object) {
return object;
}
});
kpiCell = new CompositeCell<KPI>(hasCells) {
@Override
public void render(Context context, KPI value, SafeHtmlBuilder sb) {
sb.appendHtmlConstant("<table><tbody><tr>");
super.render(context, value, sb);
sb.appendHtmlConstant("</tr></tbody></table>");
/*if(value.isLeaf()){
sb.appendHtmlConstant("<table style=\"color:#0066cc;\"><tbody><tr>");
//hasCells.get(0).getCell().render(context, value.getClass(), sb);
//super.render(context, value, sb);
sb.appendHtmlConstant("</tr></tbody></table>");
}else{
sb.appendHtmlConstant("<table><tbody><tr>");
//sb.appendHtmlConstant(value.getName());
//superrender(context, value, sb);
sb.appendHtmlConstant("</tr></tbody></table>");
}*/
}
@Override
protected Element getContainerElement(Element parent) {
// Return the first TR element in the table.
return parent.getFirstChildElement().getFirstChildElement().getFirstChildElement();
}
@Override
protected <X> void render(
Context context, KPI value, SafeHtmlBuilder sb,
HasCell<KPI, X> hasCell) {
Cell<X> cell = hasCell.getCell();
sb.appendHtmlConstant("<td>");
cell.render(context, hasCell.getValue(value), sb);
sb.appendHtmlConstant("</td>");
}
};
}
public void setNewPopulationType(PopulationType populationType) {
GWT.log("Displayng KPI for: " + populationType.toString());
// dataProvider.getList().clear();
// dataProvider.setList(list);
// dataProvider.refresh();
if (this.populationTypeProvider != null) {
// this.kpis.clear();
this.populationTypeProvider.getList().clear();
this.populationTypeProvider.getList().addAll(
populationType.getListKPI());
}
// fillFirstRootLevel(populationType.getListKPI());
//
// this.getNodeInfo(populationType);
}
// private void fillFirstRootLevel(List<KPI> listKPI){
// kpis.clear();
// PopulationType rootKPI = new PopulationType("", "KPIs","","",null);
// rootKPI.setListKPI(rootKPI.getListKPI());
// kpis.add(rootKPI);
// //rootProvider.refresh();
// }
/**
* Get the {@link NodeInfo} that provides the children of the specified
* value.
*/
public <T> NodeInfo<?> getNodeInfo(T value) {
GWT.log("Get Node Info fired: " + value);
if (value == null) {
// LEVEL 0.
// We passed null as the root value. Return the composers.
// Create a data provider that contains the list of composers.
// PopulationType root = fillFirstRootLevel(null);
// Create a cell to display a composer.
PopulationType rootKPI =
new PopulationType("", "KPIs", "", "", null);
rootKPI.setListKPI(rootKPI.getListKPI());
rootProvider.getList().add(rootKPI);
Cell<PopulationType> cell = new AbstractCell<PopulationType>() {
@Override
public void render(
com.google.gwt.cell.client.Cell.Context context,
PopulationType value, SafeHtmlBuilder sb) {
GWT.log("Rendering Root: " + value + " KPIs: " +
value.getListKPI());
// sb.appendHtmlConstant(" ROOT ");
sb.appendEscaped(value.getName());
}
};
// Return a node info that pairs the data provider and the cell.
return new DefaultNodeInfo<PopulationType>(rootProvider, cell);
}
else if (value instanceof PopulationType) {
// LEVEL 1.
// We want the children of PopulationType. Getting its list of KPI.
// List<KPI> listOfKpi = ((PopulationType) value).getListKPI();
GWT.log("PopulationType listOfKpi: " + populationTypeProvider.getList());
// populationTypeProvider = new ListDataProvider<KPI>(listOfKpi);
// Cell<KPI> cell = new AbstractCell<KPI>() {
//
// @Override
// public void render(
// com.google.gwt.cell.client.Cell.Context context, KPI value,
// SafeHtmlBuilder sb) {
//
// GWT.log("Rendering PopulationType: " + value);
// if (value != null) {
// sb.appendHtmlConstant(" ");
// sb.appendEscaped(value.getName());
// }
// }
// };
return new DefaultNodeInfo<KPI>(populationTypeProvider, kpiCell);
}
else if (value instanceof KPI) {
// LEVEL 2 - LEAF.
// We want the children of the KPI. Return them.
List<KPI> listOfKpi = ((KPI) value).getListKPI();
if (listOfKpi != null) {
GWT.log("KPI type listOfKpi: " + listOfKpi.toString());
kpiProvider = new ListDataProvider<KPI>(((KPI) value).getListKPI());
// Cell<KPI> cell = new AbstractCell<KPI>() {
//
// @Override
// public void render(
// com.google.gwt.cell.client.Cell.Context context,
// KPI value, SafeHtmlBuilder sb) {
//
// GWT.log("Rendering KPI: " + value);
// if (value != null) {
// sb.appendHtmlConstant(" ---- ");
// sb.appendEscaped(value.getName());
// }
// }
// };
return new DefaultNodeInfo<KPI>(
kpiProvider, kpiCell, multiSelectionModel, null);
}
}
return null;
}
/**
* Check if the specified value represents a leaf node. Leaf nodes cannot be
* opened.
*/
public boolean isLeaf(Object value) {
// The leaf nodes are the songs, which are Strings.
if (value instanceof KPI) {
KPI toKPI = (KPI) value;
return toKPI.isLeaf();
}
return false;
}
}

@ -0,0 +1,225 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.view;
import java.util.ArrayList;
import java.util.List;
import org.gcube.portlets.user.performfishanalytics.client.controllers.PerformFishAnalyticsController;
import org.gcube.portlets.user.performfishanalytics.client.event.SelectedKPIEvent;
import org.gcube.portlets.user.performfishanalytics.shared.KPI;
import org.gcube.portlets.user.performfishanalytics.shared.PopulationType;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.CompositeCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.HasCell;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.view.client.TreeViewModel;
/**
* The model that defines the nodes in the tree.
*/
public class CustomTreeModel implements TreeViewModel {
// private final List<PopulationType> kpis = new
// ArrayList<PopulationType>();
/**
* This selection model is shared across all leaf nodes. A selection model
* can also be shared across all nodes in the tree, or each set of child
* nodes can have its own instance. This gives you flexibility to determine
* how nodes are selected.
*/
private final SingleSelectionModel<KPI> multiSelectionModel = new SingleSelectionModel<KPI>();
private ListDataProvider<KPI> populationTypeProvider = new ListDataProvider<KPI>();
private Cell<KPI> kpiCell;
// private ListDataProvider<KPI> dataProvider = new ListDataProvider<KPI>();
public CustomTreeModel() {
init();
multiSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
public void onSelectionChange(SelectionChangeEvent event) {
GWT.log("Selected: " + multiSelectionModel.getSelectedSet());
}
});
}
public void init() {
// Construct a composite cell for contacts that includes a checkbox.
List<HasCell<KPI, ?>> hasCells = new ArrayList<HasCell<KPI, ?>>();
hasCells.add(new HasCell<KPI, Boolean>() {
private CheckboxCell cell = new CheckboxCell(true, true);
public Cell<Boolean> getCell() {
return cell;
}
public FieldUpdater<KPI, Boolean> getFieldUpdater() {
return new FieldUpdater<KPI, Boolean>() {
@Override
public void update(int index, KPI object, Boolean value) {
// TODO Auto-generated method stub
GWT.log("Checked: "+object.getName() + " value: "+value);
PerformFishAnalyticsController.eventBus.fireEvent(new SelectedKPIEvent(null, object, value));
// cell.set(value);
// dataGrid.redraw();
}
};
}
public Boolean getValue(KPI object) {
return multiSelectionModel.isSelected(object);
}
});
hasCells.add(new HasCell<KPI, KPI>() {
private KPICell cell = new KPICell(null);
public Cell<KPI> getCell() {
return cell;
}
public FieldUpdater<KPI, KPI> getFieldUpdater() {
return null;
}
public KPI getValue(KPI object) {
return object;
}
});
kpiCell = new CompositeCell<KPI>(hasCells) {
@Override
public void render(Context context, KPI value, SafeHtmlBuilder sb) {
if(value.isLeaf()){
sb.appendHtmlConstant("<table style=\"color:#0066cc;\"><tbody><tr>");
super.render(context, value, sb);
sb.appendHtmlConstant("</tr></tbody></table>");
}else{
sb.appendHtmlConstant("<table><tbody><tr>");
sb.appendHtmlConstant(value.getName());
sb.appendHtmlConstant("</tr></tbody></table>");
}
}
@Override
protected Element getContainerElement(Element parent) {
// Return the first TR element in the table.
return parent.getFirstChildElement().getFirstChildElement().getFirstChildElement();
}
@Override
protected <X> void render(
Context context, KPI value, SafeHtmlBuilder sb,
HasCell<KPI, X> hasCell) {
Cell<X> cell = hasCell.getCell();
sb.appendHtmlConstant("<td>");
cell.render(context, hasCell.getValue(value), sb);
sb.appendHtmlConstant("</td>");
}
};
}
public void setNewBatchType(PopulationType populationType) {
//GWT.log("Displayng KPI for: " + populationType.toString());
if (this.populationTypeProvider != null) {
//removing all data from base data provider
this.populationTypeProvider.getList().clear();
this.populationTypeProvider.getList().addAll(populationType.getListKPI());
}
}
/**
* Get the {@link NodeInfo} that provides the children of the specified
* value.
*/
public <T> NodeInfo<?> getNodeInfo(T value) {
GWT.log("Get Node Info fired: " + value);
if (value == null) {
// LEVEL 0.
// We passed null as the root value. Create a fake root KPIs
PopulationType rootKPI = new PopulationType("", "KPIs", "", "", null);
rootKPI.setListKPI(rootKPI.getListKPI());
ListDataProvider<PopulationType> rootProvider = new ListDataProvider<PopulationType>();
rootProvider.getList().add(rootKPI);
Cell<PopulationType> cell = new AbstractCell<PopulationType>() {
@Override
public void render(
com.google.gwt.cell.client.Cell.Context context,
PopulationType value, SafeHtmlBuilder sb) {
GWT.log("Rendering Root: " + value + " KPIs: " +
value.getListKPI());
// sb.appendHtmlConstant(" ROOT ");
sb.appendEscaped(value.getName());
}
};
// Return a node info that pairs the data provider and the cell.
return new DefaultNodeInfo<PopulationType>(rootProvider, cell);
}
else if (value instanceof PopulationType) {
// LEVEL 1.
// We want the children of PopulationType. Getting its list of KPI.
// List<KPI> listOfKpi = ((PopulationType) value).getListKPI();
//GWT.log("PopulationType listOfKpi: " + populationTypeProvider.getList());
//return new DefaultNodeInfo<KPI>(populationTypeProvider, kpiCell, multiSelectionModel, null);
return new DefaultNodeInfo<KPI>(populationTypeProvider, kpiCell);
}
else if (value instanceof KPI) {
// LEVEL 2 - LEAF.
// We want the children of the KPI. Return them.
List<KPI> listOfKpi = ((KPI) value).getListKPI();
//GWT.log("KPI type listOfKpi: " + listOfKpi.toString());
ListDataProvider<KPI> kpiProvider = new ListDataProvider<KPI>(listOfKpi);
return new DefaultNodeInfo<KPI>(kpiProvider, kpiCell);
}
return null;
}
/**
* Check if the specified value represents a leaf node. Leaf nodes cannot be
* opened.
*/
public boolean isLeaf(Object value) {
// The leaf nodes are the songs, which are Strings.
if (value instanceof KPI) {
KPI toKPI = (KPI) value;
return toKPI.isLeaf();
}
return false;
}
}

@ -0,0 +1,79 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.view;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.FlowPanel;
/**
* The Class HeaderPage.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 16, 2019
*/
public class HeaderPanel extends FlowPanel {
private LoaderIcon loading = new LoaderIcon();
/**
* Instantiates a new header page.
*/
public HeaderPanel(){
init();
}
/**
* Inits the.
*/
public void init(){
this.clear();
initIconLoading();
}
/**
* Inits the icon loading.
*/
private void initIconLoading() {
loading.setTitle("Loading");
loading.setVisible(false);
add(loading);
}
/**
* Show loading.
*
* @param visible the visible
* @param text the text
*/
public void showLoading(boolean visible, String text){
loading.setVisible(visible);
loading.setText(text);
}
/**
* Show loading.
*
* @param visible the visible
*/
public void showLoading(boolean visible){
showLoading(visible, "");
}
/**
* Adds the title.
*
* @param header the header
* @param size the size
*/
public void addTitle(String header, double size){
getElement().setId("HeaderPage");
//pageTemplate.addTitle(header, "release", 2);
getElement().getStyle().setMarginLeft(5, Unit.PX);
getElement().getStyle().setMarginRight(5, Unit.PX);
// getElement().setAttribute("margin-right", "5px");
}
}

@ -0,0 +1,61 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.view;
import org.gcube.portlets.user.performfishanalytics.shared.KPI;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
/**
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Jan 18, 2019
*/
public class KPICell extends AbstractCell<KPI> {
/**
* The html of the image used for contacts.
*/
private String imageHtml;
public KPICell(ImageResource image) {
if (image == null)
return;
this.imageHtml = AbstractImagePrototype.create(image).getHTML();
}
/*
* (non-Javadoc)
* @see
* com.google.gwt.cell.client.AbstractCell#render(com.google.gwt.cell.client
* .Cell.Context, java.lang.Object,
* com.google.gwt.safehtml.shared.SafeHtmlBuilder)
*/
@Override
public void render(
com.google.gwt.cell.client.Cell.Context context, KPI value,
SafeHtmlBuilder sb) {
// Value can be null, so do a null check..
if (value == null) {
return;
}
sb.appendHtmlConstant("<table>");
// Add the contact image.
sb.appendHtmlConstant("<tr>");
// sb.appendHtmlConstant("<td rowspan='3'>");
// sb.appendHtmlConstant(imageHtml);
// sb.appendHtmlConstant("</td>");
// Add the name and address.
sb.appendHtmlConstant("<td style='font-size:95%;'>");
sb.appendEscaped(value.getName());
sb.appendHtmlConstant("</td></tr>");
// sb.appendEscaped(value.getAddress());
sb.appendHtmlConstant("</table>");
}
}

@ -0,0 +1,65 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.view;
import org.gcube.portlets.user.performfishanalytics.client.resources.Icons;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
/**
* The Class LoaderIcon.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Feb 19, 2015
*/
public class LoaderIcon extends FocusPanel{
private Image imgLoading = new Image(Icons.ICONS.loading());
private HTML txtLoading = new HTML("");
private HorizontalPanel hp = new HorizontalPanel();
/**
* Instantiates a new loader icon.
*
* @param txtHTML the txt html
*/
public LoaderIcon(String txtHTML) {
this();
setText(txtHTML);
}
/**
* Instantiates a new loader icon.
*/
public LoaderIcon() {
setStyleName("marginTop20");
hp.add(imgLoading);
hp.add(txtLoading);
add(hp);
}
/**
* Sets the text.
*
* @param txtHTML the new text
*/
public void setText(String txtHTML){
txtLoading.setHTML("<span style=\"margin-left:5px; vertical-align:middle;\">"+txtHTML+"</span>");
}
/**
* Show.
*
* @param bool the bool
*/
public void show(boolean bool){
this.setVisible(bool);
}
}

@ -0,0 +1,68 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.view.totest;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.CellTree;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.TreeViewModel;
import com.google.gwt.view.client.TreeViewModel.DefaultNodeInfo;
/**
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Mar 4, 2019
*/
public class CellTreeExample implements EntryPoint {
/**
* The model that defines the nodes in the tree.
*/
private static class CustomTreeModel implements TreeViewModel {
/**
* Get the {@link NodeInfo} that provides the children of the specified
* value.
*/
public <T> NodeInfo<?> getNodeInfo(T value) {
/*
* Create some data in a data provider. Use the parent value as a prefix
* for the next level.
*/
ListDataProvider<String> dataProvider = new ListDataProvider<String>();
for (int i = 0; i < 2; i++) {
dataProvider.getList().add(value + "." + String.valueOf(i));
}
// Return a node info that pairs the data with a cell.
return new DefaultNodeInfo<String>(dataProvider, new TextCell());
}
/**
* Check if the specified value represents a leaf node. Leaf nodes cannot be
* opened.
*/
public boolean isLeaf(Object value) {
// The maximum length of a value is ten characters.
return value.toString().length() > 10;
}
}
public void onModuleLoad() {
// Create a model for the tree.
TreeViewModel model = new CustomTreeModel();
/*
* Create the tree using the model. We specify the default value of the
* hidden root node as "Item 1".
*/
CellTree tree = new CellTree(model, "Item 1");
// Add the tree to the root layout panel.
RootLayoutPanel.get().add(tree);
}
}

@ -0,0 +1,122 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.view.totest;
import java.util.List;
import org.gcube.portlets.user.performfishanalytics.client.controllers.PerformFishAnalyticsController;
import org.gcube.portlets.user.performfishanalytics.client.event.SelectedKPIEvent;
import org.gcube.portlets.user.performfishanalytics.client.view.KPICell;
import org.gcube.portlets.user.performfishanalytics.shared.KPI;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.CompositeCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.HasCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.view.client.SingleSelectionModel;
/**
* The Class LeafCell.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Mar 4, 2019
*/
public class LeafCell extends CompositeCell<KPI> {
private final SingleSelectionModel<KPI> multiSelectionModel =
new SingleSelectionModel<KPI>();
private List<HasCell<KPI, ?>> hasCells;
/**
* @param hasCells
*/
public LeafCell(List<HasCell<KPI, ?>> hasCells) {
super(hasCells);
this.hasCells = hasCells;
hasCells.add(new HasCell<KPI, Boolean>() {
private CheckboxCell cell = new CheckboxCell(true, true);
public Cell<Boolean> getCell() {
return cell;
}
public FieldUpdater<KPI, Boolean> getFieldUpdater() {
return new FieldUpdater<KPI, Boolean>() {
@Override
public void update(int index, KPI object, Boolean value) {
// TODO Auto-generated method stub
GWT.log("Checked: " + object.getName() + " value: " +
value);
PerformFishAnalyticsController.eventBus.fireEvent(new SelectedKPIEvent(
null, object, value));
// cell.set(value);
// dataGrid.redraw();
}
};
}
public Boolean getValue(KPI object) {
return multiSelectionModel.isSelected(object);
}
});
hasCells.add(new HasCell<KPI, KPI>() {
private KPICell cell = new KPICell(null);
public Cell<KPI> getCell() {
return cell;
}
public FieldUpdater<KPI, KPI> getFieldUpdater() {
return null;
}
public KPI getValue(KPI object) {
return object;
}
});
// TODO Auto-generated constructor stub
}
@Override
public void render(Context context, KPI value, SafeHtmlBuilder sb) {
sb.appendHtmlConstant("<table><tbody><tr>");
sb.appendHtmlConstant(value.getName());
sb.appendHtmlConstant("</tr></tbody></table>");
}
@Override
protected Element getContainerElement(Element parent) {
// Return the first TR element in the table.
return parent.getFirstChildElement().getFirstChildElement().getFirstChildElement();
}
@Override
protected <X> void render(
Context context, KPI value, SafeHtmlBuilder sb, HasCell<KPI, X> hasCell) {
Cell<X> cell = hasCell.getCell();
sb.appendHtmlConstant("<td>");
cell.render(context, hasCell.getValue(value), sb);
sb.appendHtmlConstant("</td>");
}
}

@ -0,0 +1,111 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.view.totest;
import java.util.ArrayList;
import java.util.List;
import org.gcube.portlets.user.performfishanalytics.client.view.KPICell;
import org.gcube.portlets.user.performfishanalytics.shared.KPI;
import org.gcube.portlets.user.performfishanalytics.shared.PopulationType;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.HasCell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.TreeViewModel;
/**
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Mar 4, 2019
*/
public class NewCustomTreeModel implements TreeViewModel {
private ListDataProvider<KPI> populationTypeProvider = new ListDataProvider<KPI>();
public void setNewBatchType(PopulationType populationType) {
//GWT.log("Displayng KPI for: " + populationType.toString());
if (this.populationTypeProvider != null) {
//removing all data from base data provider
this.populationTypeProvider.getList().clear();
this.populationTypeProvider.getList().addAll(populationType.getListKPI());
}
}
/**
* Get the {@link NodeInfo} that provides the children of the specified
* value.
*/
public <T> NodeInfo<?> getNodeInfo(T value) {
GWT.log("Get Node Info fired: " + value);
if (value == null) {
// LEVEL 0.
// We passed null as the root value. Create a fake root KPIs
PopulationType rootKPI = new PopulationType("", "KPIs", "", "", null);
rootKPI.setListKPI(rootKPI.getListKPI());
ListDataProvider<String> dataProvider = new ListDataProvider<String>();
dataProvider.getList().add("KPIs");
TextCell textCell = new TextCell();
return new DefaultNodeInfo<String>(dataProvider, textCell);
}
else if (value instanceof PopulationType) {
// LEVEL 1.
// We want the children of PopulationType. Getting its list of KPI.
//
//PopulationTypeCell populatioCell = new PopulationTypeCell(null);
// ListDataProvider<KPI> dataProvider = new ListDataProvider<KPI>();
// dataProvider.getList().addAll(listOfKpi);
//List<KPI> listOfKpi = ((PopulationType) value).getListKPI();
KPICell kpi = new KPICell(null);
PopulationType populationType = (PopulationType) value;
GWT.log("populationType: "+populationType);
List<KPI> listOfKpi = populationType.getListKPI();
populationTypeProvider.getList().addAll(listOfKpi);
return new DefaultNodeInfo<KPI>(populationTypeProvider, kpi);
}
else if (value instanceof KPI) {
// LEVEL 2 - LEAF.
// We want the children of the KPI. Return them.
KPI kpiValue = (KPI) value;
List<KPI> listOfKpi = kpiValue.getListKPI();
//populationTypeProvider.getList().addAll(listOfKpi);
//GWT.log("KPI type listOfKpi: " + listOfKpi.toString());
ListDataProvider<KPI> kpiProvider = new ListDataProvider<KPI>(listOfKpi);
AbstractCell<KPI> cell = null;
if(kpiValue.isLeaf()){
List<HasCell<KPI, ?>> hasCells = new ArrayList<HasCell<KPI, ?>>();
cell = new LeafCell(hasCells);
}else{
cell = new KPICell(null);
}
return new DefaultNodeInfo<KPI>(kpiProvider, cell);
}
return null;
}
/**
* Check if the specified value represents a leaf node. Leaf nodes cannot be
* opened.
*/
public boolean isLeaf(Object value) {
// The leaf nodes are the songs, which are Strings.
if (value instanceof KPI) {
KPI toKPI = (KPI) value;
return toKPI.isLeaf();
}
return false;
}
}

@ -0,0 +1,60 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.view.totest;
import org.gcube.portlets.user.performfishanalytics.shared.PopulationType;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
/**
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Jan 18, 2019
*/
public class PopulationTypeCell extends AbstractCell<PopulationType> {
/**
* The html of the image used for contacts.
*/
private String imageHtml;
public PopulationTypeCell(ImageResource image) {
if (image == null)
return;
this.imageHtml = AbstractImagePrototype.create(image).getHTML();
}
/*
* (non-Javadoc)
* @see
* com.google.gwt.cell.client.AbstractCell#render(com.google.gwt.cell.client
* .Cell.Context, java.lang.Object,
* com.google.gwt.safehtml.shared.SafeHtmlBuilder)
*/
@Override
public void render(
com.google.gwt.cell.client.Cell.Context context, PopulationType value,
SafeHtmlBuilder sb) {
// Value can be null, so do a null check..
if (value == null) {
return;
}
sb.appendHtmlConstant("<table>");
// Add the contact image.
sb.appendHtmlConstant("<tr>");
// sb.appendHtmlConstant("<td rowspan='3'>");
// sb.appendHtmlConstant(imageHtml);
// sb.appendHtmlConstant("</td>");
// Add the name and address.
sb.appendHtmlConstant("<td style='font-size:95%;'>");
sb.appendEscaped(value.getName());
sb.appendHtmlConstant("</td></tr>");
// sb.appendEscaped(value.getAddress());
sb.appendHtmlConstant("</table>");
}
}

@ -0,0 +1,54 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.view.util;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jan 29, 2019
*/
public class CorrelationValueToColourUtil {
private static Map<String, String> map = new HashMap<String, String>();
private static String RED_RGB = "#FF442D";
private static String LIGHT_BLUE_RGB = "#ADD8E6";
private static String YELLOW_RGB = "#E6DF00";
public static Map<String, String> getMap(){
if(map.isEmpty()){
map.put("Significant positive correlation", RED_RGB); //red;
map.put("Significant negative correlation", LIGHT_BLUE_RGB); //light blue;
map.put("Non-significant correlation", YELLOW_RGB);
}
return map;
}
public static String getRGBColor(String value){
try{
Float correlation = Float.parseFloat(value);
if(correlation>=0.6)
return RED_RGB;
else if(correlation<=-0.6){
return LIGHT_BLUE_RGB;
}else if(correlation<0.6 && correlation>-0.6){
return YELLOW_RGB;
}
return value;
}catch(Exception e){
return value;
}
}
}

@ -0,0 +1,173 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.view.util;
import com.google.gwt.cell.client.AbstractEditableCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.BrowserEvents;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
/**
* The Class ExtendedCheckboxCell.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Feb 28, 2019
*/
/**
* A {@link Cell} used to render a checkbox. The value of the checkbox may be
* toggled using the ENTER key as well as via mouse click.
*/
public class ExtendedCheckboxCell extends AbstractEditableCell<Boolean, Boolean> {
/**
* An html string representation of a checked input box.
*/
private static final SafeHtml INPUT_CHECKED = SafeHtmlUtils.fromSafeConstant("<input type=\"checkbox\" tabindex=\"-1\" checked/>");
/**
* An html string representation of an unchecked input box.
*/
private static final SafeHtml INPUT_UNCHECKED = SafeHtmlUtils.fromSafeConstant("<input type=\"checkbox\" tabindex=\"-1\"/>");
private final boolean dependsOnSelection;
private final boolean handlesSelection;
private InputElement input;
/**
* Construct a new {@link CheckboxCell}.
*/
public ExtendedCheckboxCell() {
this(false);
}
/**
* Construct a new {@link CheckboxCell} that optionally controls selection.
*
* @param isSelectBox true if the cell controls the selection state
* @deprecated use {@link #CheckboxCell(boolean, boolean)} instead
*/
@Deprecated
public ExtendedCheckboxCell(boolean isSelectBox) {
this(isSelectBox, isSelectBox);
}
/**
* Construct a new {@link CheckboxCell} that optionally controls selection.
*
* @param dependsOnSelection true if the cell depends on the selection state
* @param handlesSelection true if the cell modifies the selection state
*/
public ExtendedCheckboxCell(boolean dependsOnSelection, boolean handlesSelection) {
super(BrowserEvents.CHANGE, BrowserEvents.KEYDOWN);
this.dependsOnSelection = dependsOnSelection;
this.handlesSelection = handlesSelection;
}
/* (non-Javadoc)
* @see com.google.gwt.cell.client.AbstractCell#dependsOnSelection()
*/
@Override
public boolean dependsOnSelection() {
return dependsOnSelection;
}
/* (non-Javadoc)
* @see com.google.gwt.cell.client.AbstractCell#handlesSelection()
*/
@Override
public boolean handlesSelection() {
return handlesSelection;
}
/* (non-Javadoc)
* @see com.google.gwt.cell.client.AbstractEditableCell#isEditing(com.google.gwt.cell.client.Cell.Context, com.google.gwt.dom.client.Element, java.lang.Object)
*/
@Override
public boolean isEditing(Context context, Element parent, Boolean value) {
// A checkbox is never in "edit mode". There is no intermediate state
// between checked and unchecked.
return false;
}
/* (non-Javadoc)
* @see com.google.gwt.cell.client.AbstractCell#onBrowserEvent(com.google.gwt.cell.client.Cell.Context, com.google.gwt.dom.client.Element, java.lang.Object, com.google.gwt.dom.client.NativeEvent, com.google.gwt.cell.client.ValueUpdater)
*/
@Override
public void onBrowserEvent(Context context, Element parent, Boolean value,
NativeEvent event, ValueUpdater<Boolean> valueUpdater) {
String type = event.getType();
boolean enterPressed = BrowserEvents.KEYDOWN.equals(type)
&& event.getKeyCode() == KeyCodes.KEY_ENTER;
if (BrowserEvents.CHANGE.equals(type) || enterPressed) {
input = parent.getFirstChild().cast();
Boolean isChecked = input.isChecked();
/*
* Toggle the value if the enter key was pressed and the cell handles
* selection or doesn't depend on selection. If the cell depends on
* selection but doesn't handle selection, then ignore the enter key and
* let the SelectionEventManager determine which keys will trigger a
* change.
*/
if (enterPressed && (handlesSelection() || !dependsOnSelection())) {
isChecked = !isChecked;
input.setChecked(isChecked);
}
/*
* Save the new value. However, if the cell depends on the selection, then
* do not save the value because we can get into an inconsistent state.
*/
if (value != isChecked && !dependsOnSelection()) {
setViewData(context.getKey(), isChecked);
} else {
clearViewData(context.getKey());
}
if (valueUpdater != null) {
valueUpdater.update(isChecked);
}
}
}
/* (non-Javadoc)
* @see com.google.gwt.cell.client.AbstractCell#render(com.google.gwt.cell.client.Cell.Context, java.lang.Object, com.google.gwt.safehtml.shared.SafeHtmlBuilder)
*/
@Override
public void render(Context context, Boolean value, SafeHtmlBuilder sb) {
// Get the view data.
Object key = context.getKey();
Boolean viewData = getViewData(key);
if (viewData != null && viewData.equals(value)) {
clearViewData(key);
viewData = null;
}
if (value != null && (viewData != null ? viewData : value)) {
sb.append(INPUT_CHECKED);
} else {
sb.append(INPUT_UNCHECKED);
}
}
/**
* Sets the checked.
*
* @param value the new checked
*/
public void setChecked(Boolean value){
input.setChecked(value);
}
}

@ -0,0 +1,104 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<ui:style>
.paddingLeft {
padding-left: 10px;
}
</ui:style>
<g:HTMLPanel ui:field="field_html_panel" addStyleNames="the_margin">
<g:VerticalPanel ui:field="field_parameters">
<g:VerticalPanel ui:field="field_parameters_container"
addStyleNames="the_margin_top_bottom">
<b:Label text="Parameters"></b:Label>
</g:VerticalPanel>
</g:VerticalPanel>
<g:VerticalPanel ui:field="field_results"
addStyleNames="the_margin_top_bottom">
<b:Label text="CORRELATION Matrix"></b:Label>
<g:HorizontalPanel addStyleNames="the_margin_top">
<g:Label ui:field="uib_label_focus_id">Focus ID</g:Label>
<b:ControlGroup ui:field="cg_focus_id_correlation">
<b:Controls>
<b:ListBox name="Select Focus ID" b:id="field_list_focus_id_correlation"
ui:field="field_list_focus_id_correlation" multipleSelect="false"
addStyleNames="the_margin_left">
</b:ListBox>
</b:Controls>
</b:ControlGroup>
</g:HorizontalPanel>
<g:VerticalPanel ui:field="uib_vp_correlation_results_container"
addStyleNames="the_margin_left">
</g:VerticalPanel>
<g:VerticalPanel ui:field="field_deanalanlysis_algorithm_request"
addStyleNames="the_margin_top_bottom" visible="false">
<b:Label text="DEA ANALYSIS Request"></b:Label>
<g:HorizontalPanel ui:field="uib_vp_deanalanlysis_request_container"
addStyleNames="the_margin_top_bottom the_margin_left">
<g:Label>Input KPI</g:Label>
<b:ControlGroup ui:field="cg_list_dea_input_kpi">
<b:Controls>
<b:InputAddOn>
<b:ListBox ui:field="list_dea_input_kpi"
multipleSelect="true" addStyleNames="the_margin_left the_select_custom"
height="100px">
</b:ListBox>
<b:appendWidget>
<b:CheckBox ui:field="uib_check_all_input_kpi"
title="Select/Unselect All" />
</b:appendWidget>
</b:InputAddOn>
</b:Controls>
</b:ControlGroup>
<g:Label addStyleNames="the_margin_left" styleName="{style.paddingLeft}">Output
KPI</g:Label>
<b:ControlGroup ui:field="cg_list_dea_output_kpi">
<b:Controls>
<b:InputAddOn>
<b:ListBox addStyleNames="the_margin_left the_select_custom"
ui:field="list_dea_output_kpi" multipleSelect="true" height="100px">
</b:ListBox>
<b:appendWidget>
<b:CheckBox ui:field="uib_check_all_output_kpi"
title="Select/Unselect All" />
</b:appendWidget>
</b:InputAddOn>
</b:Controls>
</b:ControlGroup>
<b:Button type="DEFAULT" text="Submit DEA Analysis Request"
ui:field="button_dea_analys_request" addStyleNames="the_margin_left">
</b:Button>
</g:HorizontalPanel>
</g:VerticalPanel>
<g:VerticalPanel ui:field="field_unary_algorithm"
addStyleNames="the_margin_top_bottom" visible="false">
<b:Label text="BOXPLOT and SPEEDOMETER Results" type="INFO"></b:Label>
<g:VerticalPanel ui:field="field_unary_algorithm_container"
addStyleNames="the_margin">
</g:VerticalPanel>
</g:VerticalPanel>
<g:VerticalPanel ui:field="field_binary_algorithm"
addStyleNames="the_margin_top_bottom" visible="false">
<b:Label text="SCATTER and DEA_CHART Results" type="INFO"></b:Label>
<g:VerticalPanel ui:field="field_binary_algorithm_container"
addStyleNames="the_margin">
</g:VerticalPanel>
</g:VerticalPanel>
<g:VerticalPanel ui:field="uib_vp_deanalanlysis_algorithm"
addStyleNames="the_margin_top_bottom" visible="false">
<b:Label text="DEA ANALYSIS Results" type="INFO"></b:Label>
<g:VerticalPanel ui:field="uib_vp_deanalanlysis_algorithm_container"
addStyleNames="the_margin">
</g:VerticalPanel>
</g:VerticalPanel>
</g:VerticalPanel>
</g:HTMLPanel>
</ui:UiBinder>

@ -0,0 +1,300 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.viewbinder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsConstant;
import org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsConstant.POPULATION_LEVEL;
import org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsServiceAsync;
import org.gcube.portlets.user.performfishanalytics.client.controllers.PerformFishAnalyticsController;
import org.gcube.portlets.user.performfishanalytics.client.event.AddedBatchIdEvent;
import org.gcube.portlets.user.performfishanalytics.client.view.LoaderIcon;
import org.gcube.portlets.user.performfishanalytics.shared.csv.CSVFile;
import org.gcube.portlets.user.performfishanalytics.shared.csv.CSVRow;
import org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishResponse;
import com.github.gwtbootstrap.client.ui.Alert;
import com.github.gwtbootstrap.client.ui.ControlGroup;
import com.github.gwtbootstrap.client.ui.ListBox;
import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* The Class BatchIDAndListKPIView.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Feb 28, 2019
*/
public class BatchIDAndListKPIView extends Composite {
private static BatchIDAndListKPIViewUiBinder uiBinder =
GWT.create(BatchIDAndListKPIViewUiBinder.class);
/**
* The Interface BatchIDAndListKPIViewUiBinder.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Feb 28, 2019
*/
interface BatchIDAndListKPIViewUiBinder
extends UiBinder<Widget, BatchIDAndListKPIView> {
}
@UiField
VerticalPanel the_panel_container;
@UiField
ListBox uib_list_batch_id;
@UiField
HorizontalPanel the_panel_error;
@UiField
ControlGroup cg_batch_id;
private PerformFishResponse performFishResponse;
private Map<String, List<String>> mapParameters;
private List<String> listBatchesID = new ArrayList<String>();
/**
* Instantiates a new batch id and list kpi view.
*/
public BatchIDAndListKPIView() {
initWidget(uiBinder.createAndBindUi(this));
uib_list_batch_id.setEnabled(false);
}
/**
* Adds the.
*
* @param w the w
*/
public void add(Widget w){
the_panel_container.add(w);
}
public List<String> getAllBatchesID(){
return listBatchesID;
}
/**
* Gets the selected.
*
* @param listBox the list box
* @return the selected
*/
private List<String> getSelected(ListBox listBox){
if(listBox==null)
listBox = uib_list_batch_id;
List<String> selected = new ArrayList<String>();
for (int i=0; i<listBox.getItemCount(); i++) {
if (listBox.isItemSelected(i)) {
selected.add(listBox.getItemText(i));
}
}
return selected;
}
/**
* Gets the selected batch id.
*
* @return the selected batch id
*/
public List<String> getSelectedBatchID(){
return getSelected(uib_list_batch_id);
}
/**
* Manage perform fish service response.
*
* @param performFishResponse the perform fish response
* @param mapParameters the map parameters
* @param level the level
*/
public void managePerformFishServiceResponse(
PerformFishResponse performFishResponse,
Map<String, List<String>> mapParameters, final POPULATION_LEVEL level) {
this.performFishResponse = performFishResponse;
this.mapParameters = mapParameters;
GWT.log("PerformFish Response: "+performFishResponse);
String fileURL = performFishResponse.getMapParameters().get(PerformFishAnalyticsConstant.BATCHES_TABLE_INTERNAL);
GWT.log("BatchesTable_internal is: "+fileURL);
//Resetting batch ID and panel error after calling Perform Fish Service
uib_list_batch_id.clear();
the_panel_error.clear();
listBatchesID.clear();
//Managing the Perform Fish Service Response
if(fileURL==null){
showAlert("No select found for "+PerformFishAnalyticsConstant.BATCHES_TABLE_INTERNAL, AlertType.ERROR, false, the_panel_error);
}else{
final LoaderIcon loader = new LoaderIcon("Loading Values...");
the_panel_container.insert(loader, 1);
//field_list_focus_id_dea.setEnabled(false);
uib_list_batch_id.setEnabled(false);
PerformFishAnalyticsServiceAsync.Util.getInstance().readCSVFile(fileURL, new AsyncCallback<CSVFile>() {
@Override
public void onFailure(Throwable caught) {
loader.setVisible(false);
the_panel_container.remove(loader);
Window.alert(caught.getMessage());
}
@Override
public void onSuccess(CSVFile result) {
loader.setVisible(false);
the_panel_container.remove(loader);
if(result==null){
showAlert("No value found for "+PerformFishAnalyticsConstant.BATCHES_TABLE_INTERNAL, AlertType.ERROR, false, the_panel_error);
return;
}
//field_list_focus_id_dea.setEnabled(true);
uib_list_batch_id.setEnabled(true);
//IT CAN BE "BATCH", "FARM", etc.
String theScalePParamValue = level.name();
int indexOfTheScaleValue = result.getHeaderRow().getListValues().indexOf(theScalePParamValue);
if(indexOfTheScaleValue>-1){
List<CSVRow> rows = result.getValueRows();
if(rows==null || rows.isEmpty()){
PerformFishAnalyticsController.eventBus.fireEvent(new AddedBatchIdEvent());
return;
}
for (CSVRow row : rows) {
String valuePerScaleP = row.getListValues().get(indexOfTheScaleValue);
//field_list_focus_id_dea.addItem(valuePerScaleP, valuePerScaleP);
uib_list_batch_id.addItem(valuePerScaleP, valuePerScaleP);
listBatchesID.add(valuePerScaleP);
}
uib_list_batch_id.addItem(PerformFishAnalyticsConstant.DM_FOCUS_ID_ALL_VALUE, PerformFishAnalyticsConstant.DM_FOCUS_ID_ALL_VALUE);
listBatchesID.add(PerformFishAnalyticsConstant.DM_FOCUS_ID_ALL_VALUE);
PerformFishAnalyticsController.eventBus.fireEvent(new AddedBatchIdEvent());
}
}
});
}
}
/**
* Show alert.
*
* @param error the error
* @param type the type
* @param closable the closable
* @param panel the panel
*/
private void showAlert(String error, AlertType type, boolean closable, ComplexPanel panel){
panel.clear();
Alert alert = new Alert(error);
alert.setType(type);
alert.setClose(closable);
alert.getElement().getStyle().setMargin(10, Unit.PX);
panel.add(alert);
}
/**
* Show error.
*
* @param error the error
* @param closable the closable
*/
public void showError(String error, boolean closable){
showAlert(error, AlertType.ERROR, closable, the_panel_error);
}
/**
* Show selection ok.
*
* @param msg the msg
* @param closable the closable
*/
public void showSelectionOK(String msg, boolean closable){
showAlert(msg, AlertType.INFO, closable, the_panel_error);
}
/**
* Gets the control group batch id.
*
* @return the control group batch id
*/
public ControlGroup getControlGroupBatchID() {
return cg_batch_id;
}
/**
* Gets the list box batch id.
*
* @return the list box batch id
*/
public ListBox getListBoxBatchId() {
return uib_list_batch_id;
}
/**
* @return the performFishResponse
*/
public PerformFishResponse getPerformFishResponse() {
return performFishResponse;
}
/**
* @return the mapParameters
*/
public Map<String, List<String>> getMapParameters() {
return mapParameters;
}
}

@ -0,0 +1,23 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<ui:style>
</ui:style>
<g:HTMLPanel>
<g:VerticalPanel ui:field="the_panel_container">
<g:HorizontalPanel addStyleNames="the_margin_top">
<g:Label ui:field="uib_label_batch_id">BATCH ID</g:Label>
<b:ControlGroup ui:field="cg_batch_id">
<b:Controls>
<b:ListBox name="Select BATCH ID" b:id="uib_list_batch_id"
ui:field="uib_list_batch_id" multipleSelect="false"
addStyleNames="the_margin_left">
</b:ListBox>
</b:Controls>
</b:ControlGroup>
</g:HorizontalPanel>
<g:HorizontalPanel ui:field="the_panel_error"></g:HorizontalPanel>
</g:VerticalPanel>
</g:HTMLPanel>
</ui:UiBinder>

@ -0,0 +1,500 @@
package org.gcube.portlets.user.performfishanalytics.client.viewbinder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.gcube.portlets.user.performfishanalytics.client.controllers.PerformFishAnalyticsController;
import org.gcube.portlets.user.performfishanalytics.client.event.LoadPopulationTypeEvent;
import org.gcube.portlets.user.performfishanalytics.client.event.PerformFishFieldFormChangedEvent;
import org.gcube.portlets.user.performfishanalytics.client.event.SelectedPopulationTypeEvent;
import org.gcube.portlets.user.performfishanalytics.shared.Area;
import org.gcube.portlets.user.performfishanalytics.shared.Period;
import org.gcube.portlets.user.performfishanalytics.shared.Population;
import org.gcube.portlets.user.performfishanalytics.shared.PopulationType;
import org.gcube.portlets.user.performfishanalytics.shared.Quarter;
import org.gcube.portlets.user.performfishanalytics.shared.Species;
import com.github.gwtbootstrap.client.ui.Alert;
import com.github.gwtbootstrap.client.ui.CheckBox;
import com.github.gwtbootstrap.client.ui.ControlGroup;
import com.github.gwtbootstrap.client.ui.ListBox;
import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.github.gwtbootstrap.client.ui.constants.ControlGroupType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.DomEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* The Class PerformFishAnalitycsFormView.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 22, 2019
*/
public class PerformFishAnalitycsFormView extends Composite {
/** The ui binder. */
private static PerformFishAnalitycsFormViewUiBinder uiBinder =
GWT.create(PerformFishAnalitycsFormViewUiBinder.class);
/**
* The Interface CreateFolderConfigurationToThreddsSyncUiBinder.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Feb 14,
* 2018
*/
interface PerformFishAnalitycsFormViewUiBinder
extends UiBinder<Widget, PerformFishAnalitycsFormView> {
}
/** The pager. */
// @UiField
// Pager pager;
@UiField
public ListBox field_select_population;
@UiField
protected ListBox field_select_population_type;
@UiField
ListBox field_select_species;
@UiField
ListBox field_select_quarter;
@UiField
ListBox field_select_area;
@UiField
ListBox field_select_period;
@UiField
ControlGroup cg_select_population;
@UiField
ControlGroup cg_select_population_type;
@UiField
ControlGroup cg_select_species;
@UiField
ControlGroup cg_select_quarter;
@UiField
ControlGroup cg_select_area;
@UiField
ControlGroup cg_select_period;
@UiField
VerticalPanel errorPanel;
@UiField
CheckBox uib_check_all_period;
@UiField
CheckBox uib_check_all_area;
@UiField
CheckBox uib_check_all_quarter;
// @UiField
// Fieldset fieldset_add_catalogue_bean;
/** The folder id. */
private String folderId;
private Map<String, List<PopulationType>> mapPopulation =
new HashMap<String, List<PopulationType>>();
private Map<String, PopulationType> mapPopulationType =
new HashMap<String, PopulationType>();
/**
* Instantiates a new perform fish analitycs form view.
*/
public PerformFishAnalitycsFormView() {
initWidget(uiBinder.createAndBindUi(this));
field_select_population.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
// String scope = field_select_scope.getSelectedItemText();
String value = field_select_population.getSelectedValue();
GWT.log("Selected POPULATION: " + value);
PerformFishAnalyticsController.eventBus.fireEvent(new LoadPopulationTypeEvent(value, null));
//PerformFishAnalyticsController.eventBus.fireEvent(new PerformFishFieldFormChangedEvent(field_select_population));
}
});
field_select_population_type.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
String populatioTypeSelected = field_select_population_type.getSelectedValue();
GWT.log("Selected population type: " + populatioTypeSelected);
PopulationType opt = mapPopulationType.get(populatioTypeSelected);
PerformFishAnalyticsController.eventBus.fireEvent(new SelectedPopulationTypeEvent(opt));
fillSpecies(opt.getListSpecies());
fillQuarter(opt.getListQuarter());
fillArea(opt.getListArea());
fillPeriod(opt.getListPeriod());
PerformFishAnalyticsController.eventBus.fireEvent(new PerformFishFieldFormChangedEvent(field_select_population_type));
}
});
field_select_period.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
hideError(cg_select_period, false);
PerformFishAnalyticsController.eventBus.fireEvent(new PerformFishFieldFormChangedEvent(field_select_period));
}
});
field_select_quarter.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
hideError(cg_select_quarter, false);
PerformFishAnalyticsController.eventBus.fireEvent(new PerformFishFieldFormChangedEvent(field_select_quarter));
}
});
field_select_area.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
hideError(cg_select_area, false);
PerformFishAnalyticsController.eventBus.fireEvent(new PerformFishFieldFormChangedEvent(field_select_area));
}
});
uib_check_all_period.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
boolean isChecked = uib_check_all_period.getValue();
selectAllFields(field_select_period, isChecked);
}
});
uib_check_all_quarter.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
boolean isChecked = uib_check_all_quarter.getValue();
selectAllFields(field_select_quarter, isChecked);
}
});
uib_check_all_area.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
boolean isChecked = uib_check_all_area.getValue();
selectAllFields(field_select_area, isChecked);
}
});
}
/**
* Select all fields.
*
* @param listBox the list box
* @param selected the selected
*/
private void selectAllFields(ListBox listBox, boolean selected){
for (int i=0; i<listBox.getItemCount(); i++) {
listBox.setItemSelected(i, selected);
}
PerformFishAnalyticsController.eventBus.fireEvent(new PerformFishFieldFormChangedEvent(listBox));
}
/**
* Fill population type.
*
* @param populationName
* the population name
* @param result
* the result
* @param population
* the population
*/
public void addPopulationTypes(
String populationName, List<PopulationType> result,
Population population) {
mapPopulation.put(populationName, result);
fillPopulationType(populationName, result, population);
}
/**
* Fill species.
*
* @param listSpecies
* the list species
*/
private void fillSpecies(List<Species> listSpecies) {
field_select_species.clear();
if (listSpecies != null && listSpecies.size() > 0) {
field_select_species.setEnabled(true);
for (Species species : listSpecies) {
field_select_species.addItem(species.getName(), species.getId());
}
}
else {
field_select_species.setEnabled(false);
}
}
/**
* Fill area.
*
* @param listArea
* the list area
*/
private void fillArea(List<Area> listArea) {
field_select_area.clear();
if (listArea != null && listArea.size() > 0) {
field_select_area.setEnabled(true);
for (Area area : listArea) {
field_select_area.addItem(area.getName(), area.getId());
}
}
else {
field_select_area.setEnabled(false);
}
}
/**
* Fill period.
*
* @param listPeriod
* the list period
*/
private void fillPeriod(List<Period> listPeriod) {
field_select_period.clear();
if (listPeriod != null && listPeriod.size() > 0) {
field_select_period.setEnabled(true);
for (Period period : listPeriod) {
field_select_period.addItem(period.getName(), period.getId());
}
}
else {
field_select_period.setEnabled(false);
}
}
/**
* Fill quarter.
*
* @param listQuarter
* the list quarter
*/
private void fillQuarter(List<Quarter> listQuarter) {
field_select_quarter.clear();
if (listQuarter != null && listQuarter.size() > 0) {
field_select_quarter.setEnabled(true);
for (Quarter quarter : listQuarter) {
field_select_quarter.addItem(quarter.getName(), quarter.getId());
}
}
else {
field_select_quarter.setEnabled(false);
}
}
/**
* Fill population type.
*
* @param populationName
* the population name
* @param result
* the result
* @param population
* the population
*/
private void fillPopulationType(
String populationName, List<PopulationType> result,
Population population) {
field_select_population_type.clear();
if (result != null && result.size() > 0) {
field_select_population_type.setEnabled(true);
mapPopulationType.clear();
for (PopulationType popType : result) {
field_select_population_type.addItem(
popType.getName(), popType.getId());
mapPopulationType.put(popType.getId(), popType);
// if(thCatalogueBean.isDefault()){
// field_select_catalogue_name.setSelectedValue(thCatalogueBean.getName());
// }
}
// field_select_population_type.setSelectedValue(thCatalogueBean.getName());
field_select_population_type.setSelectedValue(result.get(0).getName());
DomEvent.fireNativeEvent(
Document.get().createChangeEvent(),
field_select_population_type);
field_select_population.addItem(
population.getName(), population.getId());
}
}
/**
* Validate form.
*
* @return true, if successful
*/
public boolean validateForm() {
cg_select_quarter.setType(ControlGroupType.NONE);
cg_select_area.setType(ControlGroupType.NONE);
cg_select_period.setType(ControlGroupType.NONE);
errorPanel.setVisible(false);
// cg_remote_path.setType(ControlGroupType.NONE);
if (field_select_quarter.getItemCount()>0 && field_select_quarter.getSelectedIndex() == -1) {
cg_select_quarter.setType(ControlGroupType.ERROR);
showError("You must select a Quarter");
return false;
}
if (field_select_area.getItemCount()>0 && field_select_area.getSelectedIndex() == -1) {
cg_select_area.setType(ControlGroupType.ERROR);
showError("You must select an Area");
return false;
}
if (field_select_period.getItemCount()>0 && field_select_period.getSelectedIndex() == -1) {
cg_select_period.setType(ControlGroupType.ERROR);
showError("You must select a Period");
return false;
}
return true;
}
/**
* Show error.
*
* @param txt the txt
*/
public void showError(String txt) {
errorPanel.clear();
errorPanel.setVisible(true);
Alert msg = new Alert(txt);
msg.setAnimation(true);
msg.setClose(false);
msg.setType(AlertType.ERROR);
errorPanel.add(msg);
}
/**
* Hide error.
*
* @param cgroup the cgroup
* @param forceHide the force hide
*/
public void hideError(ControlGroup cgroup, boolean forceHide){
if(forceHide){
cg_select_quarter.setType(ControlGroupType.NONE);
cg_select_area.setType(ControlGroupType.NONE);
cg_select_period.setType(ControlGroupType.NONE);
errorPanel.setVisible(false);
}
if(cgroup!=null){
cgroup.setType(ControlGroupType.NONE);
}
errorPanel.setVisible(false);
}
/**
* Gets the batch type.
*
* @return the batch type
*/
public String getBatchType(){
return field_select_population_type.getSelectedItemText();
}
/**
* Gets the sel level.
*
* @return the sel level
*/
public String getLevel(){
return field_select_population.getSelectedItemText();
}
/**
* Gets the species.
*
* @return the species
*/
public String getSpecies(){
return field_select_species.getSelectedItemText();
}
/**
* Gets the quarter.
*
* @return the quarter
*/
public List<String> getQuarter(){
return getSelected(field_select_quarter);
}
/**
* Gets the area.
*
* @return the area
*/
public List<String> getArea(){
return getSelected(field_select_area);
}
/**
* Gets the period.
*
* @return the period
*/
public List<String> getPeriod(){
return getSelected(field_select_period);
}
/**
* Gets the selected.
*
* @param listBox the list box
* @return the selected
*/
private List<String> getSelected(ListBox listBox){
List<String> selected = new ArrayList<String>();
for (int i=0; i<listBox.getItemCount(); i++) {
if (listBox.isItemSelected(i)) {
selected.add(listBox.getItemText(i));
}
}
return selected;
}
}

@ -0,0 +1,99 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<ui:style>
.noBorder {
border: 0px;
}
.marginToError {
margin-left: 180px;
}
</ui:style>
<g:HTMLPanel>
<g:HTMLPanel ui:field="form_unit_fields">
<g:VerticalPanel ui:field="errorPanel" styleName="{style.marginToError}">
</g:VerticalPanel>
<b:Form type="HORIZONTAL">
<b:Fieldset styleName="{style.noBorder}">
<b:ControlGroup ui:field="cg_select_population_type">
<b:ControlLabel for="cl_select_population_type">Batch Type</b:ControlLabel>
<b:Controls>
<b:ListBox name="Select a Population Type..." b:id="field_select_population_type"
ui:field="field_select_population_type" addStyleNames="the_select_custom">
</b:ListBox>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup ui:field="cg_select_population">
<b:ControlLabel for="cl_select_population">Level</b:ControlLabel>
<b:Controls>
<b:ListBox name="Select a Population..." b:id="field_select_population"
ui:field="field_select_population" addStyleNames="the_select_custom">
</b:ListBox>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup ui:field="cg_select_species">
<b:ControlLabel for="cl_select_species">Species</b:ControlLabel>
<b:Controls>
<b:ListBox name="Select Species..." b:id="field_select_species"
ui:field="field_select_species" addStyleNames="the_select_custom">
</b:ListBox>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup ui:field="cg_select_quarter">
<b:ControlLabel for="cl_select_quarter">Quarter</b:ControlLabel>
<b:Controls>
<b:InputAddOn>
<b:ListBox name="Select Quarter..." b:id="field_select_quarter"
ui:field="field_select_quarter" multipleSelect="true"
addStyleNames="the_select_custom">
</b:ListBox>
<b:appendWidget>
<b:CheckBox ui:field="uib_check_all_quarter" title="Select/Unselect All" />
</b:appendWidget>
</b:InputAddOn>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup ui:field="cg_select_area">
<b:ControlLabel for="cl_select_area">Area</b:ControlLabel>
<b:Controls>
<b:InputAddOn>
<b:ListBox name="Select Area..." b:id="field_select_area"
ui:field="field_select_area" multipleSelect="true"
addStyleNames="the_select_custom">
</b:ListBox>
<b:appendWidget>
<b:CheckBox ui:field="uib_check_all_area" title="Select/Unselect All"/>
</b:appendWidget>
</b:InputAddOn>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup ui:field="cg_select_period">
<b:ControlLabel for="cl_select_period">Period</b:ControlLabel>
<b:Controls>
<b:InputAddOn>
<b:ListBox name="Select Period..." b:id="field_select_period"
ui:field="field_select_period" multipleSelect="true"
addStyleNames="the_select_custom">
</b:ListBox>
<b:appendWidget>
<b:CheckBox ui:field="uib_check_all_period" title="Select/Unselect All" />
</b:appendWidget>
</b:InputAddOn>
</b:Controls>
</b:ControlGroup>
</b:Fieldset>
</b:Form>
</g:HTMLPanel>
<!-- <b:Pager left="Older" right="Submit Request" aligned="true" ui:field="pager"
/> -->
</g:HTMLPanel>
</ui:UiBinder>

@ -0,0 +1,45 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.viewbinder;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
/**
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Jan 21, 2019
*/
public class PortletTitle extends Composite {
private static PortletTitleUiBinder uiBinder =
GWT.create(PortletTitleUiBinder.class);
@UiField
HTML thePageHeader;
interface PortletTitleUiBinder extends UiBinder<Widget, PortletTitle> {
}
/**
* Because this class has a default constructor, it can be used as a binder
* template. In other words, it can be used in other *.ui.xml files as
* follows: <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
* xmlns:g="urn:import:**user's package**">
* <g:**UserClassName**>Hello!</g:**UserClassName> </ui:UiBinder> Note that
* depending on the widget that is used, it may be necessary to implement
* HasHTML instead of HasText.
*/
public PortletTitle(String title) {
initWidget(uiBinder.createAndBindUi(this));
thePageHeader.setText(title);
}
public void setText(String text) {
}
}

@ -0,0 +1,18 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<ui:style>
.pageHeaderStyle {
border: 0px;
padding-bottom: 9px;
margin: 20px 0 30px;
border-bottom: 1px solid #eee;
font-size: 20px;
font-weight: bold;
margin: 20px;
}
</ui:style>
<g:HTMLPanel>
<g:HTML ui:field="thePageHeader" styleName="{style.pageHeaderStyle}"></g:HTML>
</g:HTMLPanel>
</ui:UiBinder>

@ -0,0 +1,297 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.viewbinder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.gcube.portlets.user.performfishanalytics.client.DataMinerAlgorithms;
import org.gcube.portlets.user.performfishanalytics.client.controllers.PerformFishAnalyticsController;
import org.gcube.portlets.user.performfishanalytics.client.event.SubmitRequestEvent;
import org.gcube.portlets.user.performfishanalytics.shared.KPI;
import com.github.gwtbootstrap.client.ui.Alert;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.Label;
import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.github.gwtbootstrap.client.ui.constants.LabelType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* The Class RecapSubmitPage.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jan 21, 2019
*/
public class RecapSubmitPage extends Composite {
private static RecapSubmitPageUiBinder uiBinder =
GWT.create(RecapSubmitPageUiBinder.class);
@UiField
Button uib_butt_descriptive_statistics;
@UiField
Button uib_butt_speedometer;
@UiField
Button uib_butt_scatter_plot;
@UiField
Button uib_butt_correlation_analysis;
@UiField
VerticalPanel recapPanel;
@UiField
VerticalPanel errorPanelSubmit;
private HashMap<String, KPI> mapSelected = new HashMap<String, KPI>();
private HashMap<String, Label> mapLabel = new HashMap<String, Label>();
/**
* The Interface RecapSubmitPageUiBinder.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 22, 2019
*/
interface RecapSubmitPageUiBinder extends UiBinder<Widget, RecapSubmitPage> {
}
/**
* Because this class has a default constructor, it can
* be used as a binder template. In other words, it can be used in other
* *.ui.xml files as follows:
* <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
* xmlns:g="urn:import:**user's package**">
* <g:**UserClassName**>Hello!</g:**UserClassName>
* </ui:UiBinder>
* Note that depending on the widget that is used, it may be necessary to
* implement HasHTML instead of HasText.
*/
public RecapSubmitPage() {
initWidget(uiBinder.createAndBindUi(this));
uib_butt_descriptive_statistics.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
DataMinerAlgorithms chartType = DataMinerAlgorithms.valueOf(uib_butt_descriptive_statistics.getName());
PerformFishAnalyticsController.eventBus.fireEvent(new SubmitRequestEvent(chartType));
}
});
uib_butt_speedometer.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
DataMinerAlgorithms chartType = DataMinerAlgorithms.valueOf(uib_butt_speedometer.getName());
PerformFishAnalyticsController.eventBus.fireEvent(new SubmitRequestEvent(chartType));
}
});
uib_butt_scatter_plot.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
DataMinerAlgorithms chartType = DataMinerAlgorithms.valueOf(uib_butt_scatter_plot.getName());
PerformFishAnalyticsController.eventBus.fireEvent(new SubmitRequestEvent(chartType));
}
});
uib_butt_correlation_analysis.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
DataMinerAlgorithms chartType = DataMinerAlgorithms.valueOf(uib_butt_correlation_analysis.getName());
PerformFishAnalyticsController.eventBus.fireEvent(new SubmitRequestEvent(chartType));
}
});
}
/**
* Active box plot.
*
* @param active the active
*/
public void activeBoxPlot(boolean active){
uib_butt_descriptive_statistics.setEnabled(active);
}
/**
* Active speedometer.
*
* @param active the active
*/
public void activeSpeedometer(boolean active){
uib_butt_speedometer.setEnabled(active);
}
/**
* Active correlation analysis.
*
* @param active the active
*/
public void activeCorrelationAnalysis(boolean active){
uib_butt_correlation_analysis.setEnabled(active);
}
/**
* Active scatter plot.
*
* @param active the active
*/
public void activeScatterPlot(boolean active){
uib_butt_scatter_plot.setEnabled(active);
}
/**
* Active all algorithms.
*
* @param active the active
*/
public void activeAllAlgorithms(boolean active) {
activeScatterPlot(active);
activeSpeedometer(active);
activeCorrelationAnalysis(active);
activeBoxPlot(active);
}
/**
* Manage kpi.
*
* @param kpi the kpi
* @param checked the checked
*/
public void manageKPI(KPI kpi, boolean checked){
if(kpi==null)
return;
KPI existingKPI = mapSelected.get(kpi.getId());
if(existingKPI==null){
if(checked){
addSelected(kpi);
}
}else{ //already selected. Is is checked or unchecked?
if(!checked){
//removing it only if unchecked
removeSelected(existingKPI);
}
}
}
/**
* Removes the all selected.
*/
public void removeAllSelected(){
Set<String> keySet = mapSelected.keySet();
for (String key : keySet) {
KPI kpi = mapSelected.get(key);
GWT.log("Removing key: "+kpi);
removeSelected(kpi);
}
mapSelected.clear();
}
/**
* Adds the selected.
*
* @param kpi the kpi
*/
private void addSelected(KPI kpi){
errorPanelSubmit.clear();
Label label = new Label(kpi.getName());
label.setType(LabelType.INFO);
recapPanel.add(label);
mapSelected.put(kpi.getId(), kpi);
mapLabel.put(kpi.getId(), label);
}
/**
* Removes the selected.
*
* @param kpi the kpi
*/
private void removeSelected(KPI kpi){
Label label = mapLabel.get(kpi.getId());
mapSelected.remove(kpi.getId());
try{
recapPanel.remove(label);
}catch(Exception e){
}
//mapSelected.remove(kpi.getId());
}
/**
* Gets the selected kp is.
*
* @return the selected kp is
*/
public List<KPI> getSelectedKPIs(){
errorPanelSubmit.clear();
List<KPI> selectedKPI = new ArrayList<KPI>();
Set<String> keySet = mapSelected.keySet();
for (String key : keySet) {
KPI kpi = mapSelected.get(key);
selectedKPI.add(kpi);
}
return selectedKPI;
}
/**
* Sets the error.
*
* @param txt the new error
*/
public void setError(String txt) {
Alert msg = new Alert(txt);
msg.setAnimation(true);
msg.setClose(false);
msg.setType(AlertType.ERROR);
errorPanelSubmit.add(msg);
}
}

@ -0,0 +1,29 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<ui:style>
/* Add CSS here. See the GWT docs on UI Binder for more details */
.thetitle {
font-weight: bold;
font-size: 18px;
}
.theMarginTop50 {
margin-top: 50px;
}
</ui:style>
<g:HTMLPanel>
<g:VerticalPanel ui:field="recapPanel">
<g:Label styleName="{style.thetitle}">
Selected KPIs
</g:Label>
</g:VerticalPanel>
<g:VerticalPanel ui:field="errorPanelSubmit">
</g:VerticalPanel>
<g:VerticalPanel styleName="{style.theMarginTop50}">
<b:Button ui:field="uib_butt_descriptive_statistics" text="Descriptive Statistics" name="BOXPLOT" addStyleNames="the_margin_top" enabled="false"></b:Button>
<b:Button ui:field="uib_butt_speedometer" text="Speedometer" name="SPEEDOMETER" addStyleNames="the_margin_top" enabled="false"></b:Button>
<b:Button ui:field="uib_butt_scatter_plot" text="Scatter Plot" name="SCATTER" addStyleNames="the_margin_top" enabled="false"></b:Button>
<b:Button ui:field="uib_butt_correlation_analysis" text="Correlation Analysis" name="CORRELATION" addStyleNames="the_margin_top" enabled="false"></b:Button>
</g:VerticalPanel>
</g:HTMLPanel>
</ui:UiBinder>

@ -0,0 +1,104 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.viewbinder;
import org.gcube.portlets.user.performfishanalytics.shared.csv.CSVFile;
import org.gcube.portlets.user.performfishanalytics.shared.csv.CSVRow;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.TextAlign;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* The Class ShowResult.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jan 24, 2019
*/
public class ShowResult extends Composite {
private static ShowResultUiBinder uiBinder =
GWT.create(ShowResultUiBinder.class);
/**
* The Interface ShowResultUiBinder.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Feb 1, 2019
*/
interface ShowResultUiBinder extends UiBinder<Widget, ShowResult> {
}
@UiField
HTML theTitle;
@UiField
HTMLPanel theContent;
/**
* Instantiates a new show result.
*
* @param title the title
* @param content the content
*/
public ShowResult(String title) {
initWidget(uiBinder.createAndBindUi(this));
theTitle.getElement().addClassName("theSubTitle");
theTitle.getElement().getStyle().setTextAlign(TextAlign.CENTER);
theTitle.setHTML(title);
}
/**
* Show image.
*
* @param base64Content the base64 content
*/
public void showImage(String base64Content){
theContent.add(new HTMLPanel(base64Content));
}
/**
* Show csv file.
*
* @param csvFile the csv file
*/
public void showCSVFile(CSVFile csvFile){
final FlexTable flexTable = new FlexTable();
flexTable.setStyleName("simpletable");
flexTable.getElement().getStyle().setMarginLeft(30, Unit.PX);
flexTable.getElement().getStyle().setMarginRight(30, Unit.PX);
CSVRow headerRow = csvFile.getHeaderRow();
for (int i=0; i<headerRow.getListValues().size(); i++) {
String headerValue = headerRow.getListValues().get(i);
flexTable.setWidget(0, i,new HTML(headerValue));
}
for (int i=0; i<csvFile.getValueRows().size(); i++) {
CSVRow row = csvFile.getValueRows().get(i);
for (int j=0; j<row.getListValues().size(); j++) {
String rowValue = row.getListValues().get(j);
flexTable.setWidget(i+1, j,new HTML(rowValue));
}
}
theContent.add(flexTable);
}
}

@ -0,0 +1,11 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<g:HTMLPanel>
<g:VerticalPanel>
<g:HTML ui:field="theTitle">
</g:HTML>
<g:HTMLPanel ui:field="theContent"></g:HTMLPanel>
</g:VerticalPanel>
</g:HTMLPanel>
</ui:UiBinder>

@ -0,0 +1,119 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.viewbinder;
import org.gcube.portlets.user.performfishanalytics.client.view.LoaderIcon;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.TextAlign;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* The Class SubmitRequestPanel.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Mar 4, 2019
*/
public class SubmitRequestPanel extends Composite {
private static SubmitRequestPanelPanelUiBinder uiBinder =
GWT.create(SubmitRequestPanelPanelUiBinder.class);
/**
* The Interface SubmitPerformFishRequestPanelUiBinder.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 22, 2019
*/
interface SubmitRequestPanelPanelUiBinder
extends UiBinder<Widget, SubmitRequestPanel> {
}
@UiField
HTML theTitle;
@UiField
HTMLPanel containerPanel;
LoaderIcon loader;
/**
* Because this class has a default constructor, it can
* be used as a binder template. In other words, it can be used in other
* *.ui.xml files as follows:
* <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
* xmlns:g="urn:import:**user's package**">
* <g:**UserClassName**>Hello!</g:**UserClassName>
* </ui:UiBinder>
* Note that depending on the widget that is used, it may be necessary to
* implement HasHTML instead of HasText.
*
* @param title the title
*/
public SubmitRequestPanel(String title) {
initWidget(uiBinder.createAndBindUi(this));
theTitle.getElement().addClassName("to-big-title");
theTitle.getElement().getStyle().setTextAlign(TextAlign.CENTER);
setTheTitle(title);
}
/**
* Sets the the title.
*
* @param title the new the title
*/
public void setTheTitle(String title) {
if(title!=null)
theTitle.setHTML(title);
else
theTitle.setHTML("");
}
/**
* Gets the panel.
*
* @return the panel
*/
public HTMLPanel getContainerPanel(){
return containerPanel;
}
/**
* Adds the.
*
* @param bool the bool
* @param txtHTML the txt html
*/
public void showLoader(boolean bool, String txtHTML) {
if(bool){
loader = new LoaderIcon(txtHTML);
containerPanel.add(loader);
}else{
try{
containerPanel.remove(loader);
}catch(Exception e){
}
}
}
/**
* Adds the widget.
*
* @param child the child
*/
public void addWidget(Widget child){
containerPanel.add(child);
}
}

@ -0,0 +1,16 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui">
<ui:style>
/* Add CSS here. See the GWT docs on UI Binder for more details */
.important {
font-weight: bold;
}
</ui:style>
<g:VerticalPanel addStyleNames="the-minimun-height">
<g:HTML ui:field="theTitle">
</g:HTML>
<g:HTMLPanel ui:field="containerPanel" addStyleNames="ext-margin-container"></g:HTMLPanel>
</g:VerticalPanel>
</ui:UiBinder>

@ -0,0 +1,185 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.client.viewbinder;
import java.util.ArrayList;
import java.util.List;
import com.github.gwtbootstrap.client.ui.Tab;
import com.github.gwtbootstrap.client.ui.TabPanel;
import com.github.gwtbootstrap.client.ui.TabPanel.ShowEvent;
import com.github.gwtbootstrap.client.ui.TabPanel.ShowEvent.Handler;
import com.github.gwtbootstrap.client.ui.constants.IconType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
/**
* The Class TabPanelView.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jan 29, 2019
*/
public class TabPanelView extends Composite {
private static TabPanelViewUiBinder uiBinder =
GWT.create(TabPanelViewUiBinder.class);
/**
* The Interface TabPanelViewUiBinder.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 29, 2019
*/
interface TabPanelViewUiBinder extends UiBinder<Widget, TabPanelView> {
}
@UiField
Tab field_create_analytics_request;
@UiField
TabPanel field_base_tabpanel;
private List<Tab> results = new ArrayList<Tab>();
/**
* Because this class has a default constructor, it can
* be used as a binder template. In other words, it can be used in other
* *.ui.xml files as follows:
* <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
* xmlns:g="urn:import:**user's package**">
* <g:**UserClassName**>Hello!</g:**UserClassName>
* </ui:UiBinder>
* Note that depending on the widget that is used, it may be necessary to
* implement HasHTML instead of HasText.
*/
public TabPanelView() {
initWidget(uiBinder.createAndBindUi(this));
field_base_tabpanel.addShowHandler(new Handler() {
@Override
public void onShow(ShowEvent showEvent) {
GWT.log("Showing: "+showEvent.toString());
}
});
field_create_analytics_request.asWidget().addAttachHandler(new AttachEvent.Handler() {
@Override
public void onAttachOrDetach(AttachEvent event) {
//field_create_analytics_request.asWidget().getElement().getFirstChildElement().getStyle().setBackgroundColor("#F0F8FF");
}
});
}
/**
* Gets the tab create request panel.
*
* @return the tab create request panel
*/
public Tab getTabCreateRequestPanel(){
return field_create_analytics_request;
}
/**
* Adds the create request panel.
*
* @param w the w
*/
public void addCreateRequestPanel(Widget w){
field_create_analytics_request.add(w);
}
/**
* Adds the as tab.
*
* @param w the w
* @param tabTitle the tab title
* @param spinner the spinner
* @return the tab
*/
public Tab addAsTab(Widget w, String tabTitle, boolean spinner){
// field_create_analytics_request.setActive(false);
Tab tab = new Tab();
if(!spinner)
tab.setIcon(IconType.BAR_CHART);
else{
tab.setCustomIconStyle("icon-rotate-right icon-spin");
}
field_base_tabpanel.add(tab);
tab.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
}
});
//tab.setActive(true);
tab.setHeading(tabTitle);
results.add(tab);
tab.add(w);
activeTabPanels(false);
field_base_tabpanel.selectTab(results.size());
return tab;
// tab.setActive(true);
}
/**
* Active tab panels.
*
* @param bool the bool
*/
private void activeTabPanels(boolean bool){
for (Tab tabLink : results) {
tabLink.setActive(false);
}
}
/**
* Count tab.
*
* @return the int
*/
public int countTab(){
return results.size();
}
/**
* Sets the no spinner.
*
* @param tab the new no spinner
*/
public void setNoSpinner(Tab tab) {
tab.asTabLink().getAnchor().setIcon(IconType.BAR_CHART);
try{
tab.asTabLink().getAnchor().removeStyleName("icon-spin");
Element anchorElem = tab.asTabLink().getAnchor().asWidget().getElement();
anchorElem.getFirstChildElement().removeClassName("icon-spin");
}catch(Exception e){
//silent
}
}
}

@ -0,0 +1,15 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<ui:style>
/* Add CSS here. See the GWT docs on UI Binder for more details */
.background-tab {
background-color: #E5E5E5;
}
</ui:style>
<b:TabPanel tabPosition="above" ui:field="field_base_tabpanel">
<b:Tab heading="Create Analitycs Request" active="true"
ui:field="field_create_analytics_request" icon="TASKS">
</b:Tab>
</b:TabPanel>
</ui:UiBinder>

@ -0,0 +1,50 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.portlet;
import java.io.IOException;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.gcube.common.portal.PortalContext;
/**
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jan 15, 2019
*/
public class PerformFishAnalyticsPortlet extends GenericPortlet{
/**
* JSP folder name
*/
public static final String JSP_FOLDER = "/WEB-INF/jsp/";
/**
*
*/
public static final String VIEW_JSP = JSP_FOLDER + "PerformFishAnalyticsPortlet_view.jsp";
/**
* Do view.
*
* @param request .
* @param response .
* @throws PortletException .
* @throws IOException .
*/
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
System.out.println("LOADING ********* FROM "+VIEW_JSP);
// Invoke the JSP to render
PortalContext.setUserInSession(request);
PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(VIEW_JSP);
rd.include(request,response);
}
}

@ -0,0 +1,931 @@
package org.gcube.portlets.user.performfishanalytics.server;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.persistence.EntityManagerFactory;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.gcube.common.portal.PortalContext;
import org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsConstant;
import org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsService;
import org.gcube.portlets.user.performfishanalytics.server.database.EntityManagerFactoryCreator;
import org.gcube.portlets.user.performfishanalytics.server.persistence.GenericPersistenceDaoBuilder;
import org.gcube.portlets.user.performfishanalytics.server.util.ContextUtil;
import org.gcube.portlets.user.performfishanalytics.server.util.DataMinerUtil;
import org.gcube.portlets.user.performfishanalytics.server.util.DatabaseUtil;
import org.gcube.portlets.user.performfishanalytics.server.util.GsonUtil;
import org.gcube.portlets.user.performfishanalytics.server.util.HttpCallerUtil;
import org.gcube.portlets.user.performfishanalytics.server.util.PortalContextInfo;
import org.gcube.portlets.user.performfishanalytics.server.util.ServiceParameters;
import org.gcube.portlets.user.performfishanalytics.server.util.csv.CSVReader;
import org.gcube.portlets.user.performfishanalytics.server.util.csv.CSVWriter;
import org.gcube.portlets.user.performfishanalytics.server.util.dataminer.DMServiceResponse;
import org.gcube.portlets.user.performfishanalytics.server.util.dataminer.DataMinerOutputData;
import org.gcube.portlets.user.performfishanalytics.server.util.tozipview.ZipExtractorUtil;
import org.gcube.portlets.user.performfishanalytics.shared.FileContentType;
import org.gcube.portlets.user.performfishanalytics.shared.KPI;
import org.gcube.portlets.user.performfishanalytics.shared.OutputFile;
import org.gcube.portlets.user.performfishanalytics.shared.Population;
import org.gcube.portlets.user.performfishanalytics.shared.PopulationType;
import org.gcube.portlets.user.performfishanalytics.shared.csv.CSVFile;
import org.gcube.portlets.user.performfishanalytics.shared.csv.CSVRow;
import org.gcube.portlets.user.performfishanalytics.shared.dataminer.DataMinerResponse;
import org.gcube.portlets.user.performfishanalytics.shared.exceptions.SessionExpired;
import org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishInitParameter;
import org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishResponse;
import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager;
import org.gcube.vomanagement.usermanagement.model.GCubeGroup;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
/**
* The server side implementation of the RPC service.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 16, 2019
*/
@SuppressWarnings("serial")
public class PerformFishAnalyticsServiceImpl extends RemoteServiceServlet
implements PerformFishAnalyticsService {
protected static Logger log = LoggerFactory.getLogger(PerformFishAnalyticsServiceImpl.class);
private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy 'at' HH:mm:ss-SSS z");
/**
* Gets the DB factory.
*
* @return the DB factory
* @throws Exception
* the exception
*/
private EntityManagerFactory getDBFactory()
throws Exception {
if(ContextUtil.isSessionExpired(this.getThreadLocalRequest()))
throw new SessionExpired("The session is expired");
//PortalContextInfo pContext = ContextUtil.getPortalContext(this.getThreadLocalRequest());
EntityManagerFactoryCreator.instanceLocalMode();
EntityManagerFactory dbFactory = EntityManagerFactoryCreator.getEntityManagerFactory();
new DatabaseUtil().fillDatabaseIfEmpty(dbFactory, this.getThreadLocalRequest().getServletContext());
return dbFactory;
}
/* (non-Javadoc)
* @see javax.servlet.GenericServlet#destroy()
*/
@Override
public void destroy() {
super.destroy();
try{
log.info("Closing DB Factory");
EntityManagerFactoryCreator.instanceLocalMode();
EntityManagerFactory dbFactory = EntityManagerFactoryCreator.getEntityManagerFactory();
dbFactory.close();
// String dbFolderPath = EntityManagerFactoryCreator.getPersistenceFolderPath();
// FileUtil.deleteDirectoryRecursion(new File(dbFolderPath).toPath());
log.info("DB Factory closed correctly");
}catch(Exception e){
log.info("Error occurred on closing the DB Factory: ",e);
}
}
/**
* Gets the list population type.
*
* @param populationName
* the population name
* @return the list population type
* @throws Exception
* the exception
*/
@Override
public List<PopulationType> getListPopulationType(String populationName) throws Exception {
log.info("Getting PopulationType for populationName: "+populationName);
if(ContextUtil.isSessionExpired(this.getThreadLocalRequest()))
throw new SessionExpired("The session is expired");
try{
EntityManagerFactory dbFactory = getDBFactory();
GenericPersistenceDaoBuilder<Population> builderPopulation =
new GenericPersistenceDaoBuilder<Population>(
dbFactory, Population.class.getSimpleName());
List<Population> listPopulation = builderPopulation.getPersistenceEntity().getList();
List<PopulationType> listPopulationType;
for (Population population : listPopulation) {
if (population.getName().equalsIgnoreCase(populationName)) {
listPopulationType = population.getListPopulationType();
if(log.isDebugEnabled()){
for (PopulationType populationType : listPopulationType) {
log.debug(populationType.toString());
}
}
List<PopulationType> listPopulationTypeDTO = ToAvoidIndirectSerialization.toGWTSerializable(listPopulationType, population, true);
log.info("Returning "+listPopulationTypeDTO.size()+ " type/s for population name: "+populationName);
return listPopulationTypeDTO;
}
}
// NO POPULATION TYPES
log.info("No population type found for population name: "+populationName);
return new ArrayList<PopulationType>();
}catch(Exception e){
log.error("Error on loading types of Population for population name: "+populationName, e);
throw new Exception("Error on loading types of Population for population name: "+populationName);
}
}
/* (non-Javadoc)
* @see org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsService#getPopulationTypeWithListKPI(java.lang.String)
*/
@Override
public PopulationType getPopulationTypeWithListKPI(String populationTypeId) throws Exception{
log.info("Getting PopulationType with its list of KPI for id: "+populationTypeId);
if(ContextUtil.isSessionExpired(this.getThreadLocalRequest()))
throw new SessionExpired("The session is expired");
try{
EntityManagerFactory dbFactory = getDBFactory();
GenericPersistenceDaoBuilder<PopulationType> builderPopulationType =
new GenericPersistenceDaoBuilder<PopulationType>(
dbFactory, PopulationType.class.getSimpleName());
Map<String, String> filterMap = new HashMap<String, String>();
filterMap.put("id",populationTypeId);
List<PopulationType> listPopType = builderPopulationType.getPersistenceEntity().getList(filterMap, -1, -1);
if(listPopType==null || listPopType.isEmpty())
throw new Exception("No population type found for id: "+populationTypeId);
//BUILDING HIERARCHICAL LIST OF KPI
PopulationType selectedPopType = listPopType.get(0);
List<KPI> listGWTKPI = new ArrayList<KPI>(selectedPopType.getListKPI().size());
for (KPI toKPI : selectedPopType.getListKPI()) {
KPI gwtKPI = convert(toKPI);
gwtKPI.setPopulationType(selectedPopType);//I'm setting population type only at first level
//gwtKPI.setLeaf(toKPI.getListKPI()==null || toKPI.getListKPI().isEmpty());
listGWTKPI.add(gwtKPI);
}
List<PopulationType> listPopulationTypeDTO = ToAvoidIndirectSerialization.toGWTSerializable(listPopType, null, false);
PopulationType toReturn = listPopulationTypeDTO.get(0);
toReturn.setListKPI(listGWTKPI);
if(log.isDebugEnabled()){
for (KPI kpi : toReturn.getListKPI()) {
log.debug(kpi.toString());
}
}
log.info("Returning type "+toReturn.getName()+" having list of KPI count: "+toReturn.getListKPI().size());
return toReturn;
}catch(Exception e){
log.error("Error on loading list of KPI for popluation type with id: "+populationTypeId, e);
throw new Exception("Error on loading list of KPI for popluation type with id: "+populationTypeId);
}
}
/**
* Convert.
*
* @param kpi the kpi
* @return the kpi
*/
private KPI convert(KPI kpi){
if(kpi.getListKPI()==null){
log.trace("LEAF "+kpi);
return getGWTKPI(kpi, null);
}
KPI gwtKPI = getGWTKPI(kpi, null);
log.trace("Converted: "+gwtKPI);
for (KPI kpiChild : kpi.getListKPI()) {
KPI convertedChild = convert(kpiChild);
if(gwtKPI.getListKPI()==null){
List<KPI> listKPI = new ArrayList<KPI>();
gwtKPI.setListKPI(listKPI);
}
gwtKPI.getListKPI().add(convertedChild);
}
log.trace("Filled children of: "+gwtKPI.getName());
if(gwtKPI.getListKPI()!=null){
for (KPI chKPI : gwtKPI.getListKPI()) {
log.trace("\t"+chKPI);
}
}
return gwtKPI;
}
/**
* Gets the gwtkpi.
*
* @param toKPI the to kpi
* @param populationType the population type
* @return the gwtkpi
*/
private KPI getGWTKPI(KPI toKPI, PopulationType populationType){
KPI gwtKPI = new KPI(toKPI.getId(),toKPI.getCode(),toKPI.getName(),toKPI.getDescription(), null,populationType,toKPI.getDeepIndex());
gwtKPI.setLeaf(toKPI.getListKPI()==null || toKPI.getListKPI().isEmpty());
return gwtKPI;
}
/**
* Check grant to access farm id.
*
* @param farmID the farm id
* @return true, if successful
* @throws Exception the exception
*/
@Override
public boolean checkGrantToAccessFarmID(String farmID) throws Exception{
if(ContextUtil.isSessionExpired(this.getThreadLocalRequest()))
throw new SessionExpired("The session is expired");
log.info("Checking the rights to access the farmID {} for current user",farmID);
if(ContextUtil.isWithinPortal()){
GCubeUser currentUser = PortalContext.getConfiguration().getCurrentUser(this.getThreadLocalRequest());
long userId = currentUser.getUserId();
log.info("User {} has the userId {}",currentUser.getUsername(), userId);
long farmId = -1;
try{
farmId = Long.parseLong(farmID);
}catch(Exception e){
log.error("Error parsing the farmID "+farmID+" as long", e);
}
log.debug("Parsed FARM_ID as long is: "+farmId);
if(farmId == -1){
throw new Exception("Your input farm ID seems to be not valid. Please contact the D4Science support");
}
List<GCubeGroup> groups = new LiferayGroupManager().listGroupsByUser(userId);
log.info("Groups retrieved from LR are: ",groups);
for (GCubeGroup g : groups) {
log.debug("Checking the group id: ",g.getGroupId());
if (g.getGroupId() == farmId)
log.info("GCubeGroup matching the FARM_ID {} found!",farmId);
return true;
}
log.info("GCubeGroup matching the FARM_ID {} NOT found!",farmId);
return false;
}else{
//IN TEST MODE NOT CHECKING NOTHING
log.info("I'm in testing mode, grant the rights to access the farmID {} for current user",farmID);
return true;
}
}
public static void main(String[] args) {
String farmID = "aaaa";
long farmId = -1;
try{
farmId = Long.parseLong(farmID);
}catch(Exception e){
System.out.println("Error parsing the farmID "+farmID+" as long");
}
System.out.println(farmId);
}
/**
* Decrypt and valid parameters.
*
* @param initParams the init params
* @return the perform fish init parameter
* @throws Exception the exception
*/
@Override
public PerformFishInitParameter decryptAndValidParameters(PerformFishInitParameter initParams) throws Exception{
Map<String, String> inputParameters = initParams.getParameters();
try{
log.info("Decrypting init parameters: "+inputParameters);
Set<String> keyParameters = inputParameters.keySet();
PerformFishInitParameter decrypted = new PerformFishInitParameter();
//TODO UNCOMMENT THIS FOR RELEASE
/*if(!ContextUtil.isWithinPortal()){
return initParams;
}
for (String key : keyParameters) {
String decParam = StringEncrypter.getEncrypter().decrypt(initParams.getParameters().get(key));
decrypted.addParameter(key, decParam);
}
//HERE WE CAN VALIDATE THE FARM_ID
PortalContextInfo pContext = ContextUtil.getPortalContext(this.getThreadLocalRequest());
pContext.getUsername();
log.info("Returning decrypted params: "+decrypted.toString());
return decrypted;*/
}catch(Exception e){
log.error("Error on decripting your init parameters: "+initParams.toString(), e);
throw new Exception("Error on decripting your init parameters: "+initParams.toString());
}
String farmID = inputParameters.get(PerformFishAnalyticsConstant.FARMID_PARAM);
boolean grantAccess = checkGrantToAccessFarmID(farmID);
if(!grantAccess)
throw new Exception("You have not rights to access to this FARM. You does not belong to it.");
return initParams;
}
/* (non-Javadoc)
* @see org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsService#submitRequestToPerformFishService(java.util.Map)
*/
@Override
public PerformFishResponse submitRequestToPerformFishService(Map<String, List<String>> mapParameters) throws Exception{
log.info("Submitting request with parameters: "+mapParameters);
ServiceParameters performFishService = null;
try{
performFishService = ContextUtil.getPerformFishService(this.getThreadLocalRequest());
}catch (Exception e) {
log.error("Error on getting the perform fish service from IS: "+performFishService, e);
throw new Exception("Error on getting the perform fish service from IS: "+performFishService+" Please contact the suport");
}
String serviceURL = performFishService.getUrl() + "/performance";
log.debug("Calling service: "+serviceURL);
HttpCallerUtil httpCaller = new HttpCallerUtil(serviceURL, null, null);
String gCubeToken = ContextUtil.getPortalContext(this.getThreadLocalRequest()).getUserToken();
//mapParameters.put("gcube-token", Arrays.asList(ContextUtil.getPortalContext(this.getThreadLocalRequest()).getUserToken()));
String response;
try {
Date startTime = getCurrentTimeToDate(System.currentTimeMillis());
log.debug("The request to perform-fish performed just now {}", dateFormat.format(startTime));
response = httpCaller.callGet(null, mapParameters, gCubeToken);
Date endTime = getCurrentTimeToDate(System.currentTimeMillis());
log.info("The response is: "+response +" with status: "+httpCaller.getStatusCode());
log.info("The perform-fish response returned just now {}. Response returned in {} "+ TimeUnit.MILLISECONDS.toString(), dateFormat.format(endTime), getDateDiff(startTime, endTime, TimeUnit.MILLISECONDS));
if(response==null)
throw new Exception("The response is null");
Map<String, String> theResponseParams = GsonUtil.toMap(response);
log.debug("The response was converted into map: "+theResponseParams);
UUID respSessionID = UUID.randomUUID();
//ContextUtil.getPerformFishService(UUID.randomUUID());
return new PerformFishResponse(theResponseParams, respSessionID.toString());
}
catch (Exception e) {
log.error("Error interacting with the service: "+performFishService.getUrl() +" with parameters: "+mapParameters, e);
throw new Exception("There was an error interacting with the "+ContextUtil.PERFORM_SERVICE+" in this VRE ("
+ ContextUtil.getPortalContext(this.getThreadLocalRequest()).getCurrentScope()+ ")"
+ ". Please report this issue at www.d4science.org/contact-us");
}
}
/**
* Gets the current time to date.
*
* @param currentTime the current time
* @return the current time to date
*/
private Date getCurrentTimeToDate(long currentTime) {
return new Date(currentTime);
//return dateFormat.format(resultdate);
}
/**
* Get a diff between two dates.
*
* @param date1 the oldest date
* @param date2 the newest date
* @param timeUnit the unit in which you want the diff
* @return the diff value, in the provided unit
*/
public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
long diffInMillies = date2.getTime() - date1.getTime();
return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
}
/* (non-Javadoc)
* @see org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsService#callingDataMinerPerformFishCorrelationAnalysis(org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishResponse, java.util.Map)
*/
@Override
public DataMinerResponse callingDataMinerPerformFishCorrelationAnalysis(PerformFishResponse peformFishReponse, Map<String, List<String>> mapParameters) throws Exception{
log.info("Validating Perform-Fish service response...");
String URLToBatchesTable = peformFishReponse.getMapParameters().get(PerformFishAnalyticsConstant.BATCHES_TABLE);
if(URLToBatchesTable==null || URLToBatchesTable.isEmpty())
throw new Exception("Something seems "+PerformFishAnalyticsConstant.BATCHES_TABLE+ " is null or emty");
//Checking that the perform-fish PerformFishAnalyticsConstant.BATCHES_TABLE has at least 1 row
CSVFile csvFile = readCSVFile(URLToBatchesTable);
log.info("CSVFile read from {} - {}", URLToBatchesTable, csvFile);
if(csvFile==null || csvFile.getValueRows() == null || csvFile.getValueRows().size()<PerformFishAnalyticsConstant.CSV_BATCHES_TABLE_MINIMUM_SIZE){
log.warn("The "+PerformFishAnalyticsConstant.BATCHES_TABLE+" CSV rows are"+csvFile.getValueRows()+". It is less than "+PerformFishAnalyticsConstant.CSV_BATCHES_TABLE_MINIMUM_SIZE);
throw new Exception("Your request does not produce enough data for the analysis, please change your selection and try again");
}
log.info("Calling the DM service with client parameters: "+mapParameters.toString());
PortalContextInfo pContext = ContextUtil.getPortalContext(this.getThreadLocalRequest());
Map<String, List<String>> dmRequestParameters = new HashMap<String, List<String>>();
dmRequestParameters.put("request", Arrays.asList("Execute"));
dmRequestParameters.put("service", Arrays.asList("WPS"));
dmRequestParameters.put("Version", Arrays.asList("1.0.0"));
//dmRequestParameters.put("gcube-token", Arrays.asList(pContext.getUserToken()));
dmRequestParameters.put("lang", Arrays.asList("en-US"));
dmRequestParameters.put("Identifier", Arrays.asList("org.gcube.dataanalysis.wps.statisticalmanager.synchserver.mappedclasses.transducerers.PERFORMFISH_ANALYSIS"));
ServiceParameters dataMinerService = ContextUtil.getDataMinerService(this.getThreadLocalRequest());
log.info("Found DM service: "+dataMinerService.getUrl() + " int this scope: "+pContext.getCurrentScope());
// if(!ContextUtil.isWithinPortal()){
// dataMinerService = new ServiceParameters("http://dataminer-prototypes.d4science.org/wps/WebProcessingService", null, null, dmRequestParameters);
// log.info("I'm in TEST MODE replacing it with HARD CODED: "+dataMinerService);
// }
dataMinerService.setProperties(dmRequestParameters);
//Addding client parameters to DM service request
dmRequestParameters.putAll(mapParameters);
DMServiceResponse dmResponse = null;
String response;
try{
response = new HttpCallerUtil(dataMinerService.getUrl(), null, null).performGETRequestWithRetry(dmRequestParameters, pContext.getUserToken(), 5);
if(response==null){
log.error("The presponse returned is null");
throw new Exception("The presponse returned is null");
}
dmResponse = DataMinerUtil.parseResult(dataMinerService.getUrl(), response);
}catch(Exception e){
throw new Exception("The service did not produce any result. Change your selection and try again.");
}
if(dmResponse == null || dmResponse.isWithError())
throw new Exception("The response returned by DM service contains an Exception Status. (The call is: "+dmResponse.getHttpRequestURL()+"). Please report this issue at www.d4science.org/contact-us");
try{
DataMinerOutputData toDMOutputData = null;
List<DataMinerOutputData> listOut = dmResponse.getListDMOutputData();
for (DataMinerOutputData dataMinerOutputData : listOut) {
//I'm using this specific output data of DM
if(dataMinerOutputData.getFileDescription().contains("outputCharts")){
log.info("The output: "+dataMinerOutputData.getFileDescription()+ " with: "+dataMinerOutputData.getMimeType()+" is the candidate to unzip");
toDMOutputData = dataMinerOutputData;
break;
}
}
if(toDMOutputData==null || toDMOutputData.getPublicURL()==null)
throw new Exception("The response returned by DM service does not contain a file to unzip with name: 'outputCharts'. Please report this issue at www.d4science.org/contact-us");
String theZipFileURL = toDMOutputData.getPublicURL();
log.info("I'm using the file: "+theZipFileURL);
FileContentType filter = FileContentType.CSV;
ZipExtractorUtil zipExt = new ZipExtractorUtil(theZipFileURL, Arrays.asList(filter));
List<OutputFile> output = zipExt.getOutputFiles();
log.info("Extracted output of type {} as list {}: ",filter,output);
output = manageOutputsForPerformFishAnalysis(output);
log.info("Managed output of type {} as list {}: ",filter,output);
DataMinerResponse theDMResponse = new DataMinerResponse(peformFishReponse, output);
log.debug("Returning {}",theDMResponse);
return theDMResponse;
}catch(Exception e){
log.error("There was an error extracting the DataMiner response from your request: ", e);
throw new Exception("The service did not produce any result. Change your request and try again.");
}
}
/* (non-Javadoc)
* @see org.gcube.portlets.user.performfishanalytics.client.PerformFishAnalyticsService#callingDataMinerPerformFishAnalysis(org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishResponse, java.util.Map)
*/
@Override
public DataMinerResponse callingDataMinerPerformFishAnalysis(Map<String, List<String>> mapParameters) throws Exception{
log.info("Calling the DM service with client parameters: "+mapParameters.toString());
PortalContextInfo pContext = ContextUtil.getPortalContext(this.getThreadLocalRequest());
Map<String, List<String>> dmRequestParameters = new HashMap<String, List<String>>();
dmRequestParameters.put("request", Arrays.asList("Execute"));
dmRequestParameters.put("service", Arrays.asList("WPS"));
dmRequestParameters.put("Version", Arrays.asList("1.0.0"));
//dmRequestParameters.put("gcube-token", Arrays.asList(pContext.getUserToken()));
dmRequestParameters.put("lang", Arrays.asList("en-US"));
dmRequestParameters.put("Identifier", Arrays.asList("org.gcube.dataanalysis.wps.statisticalmanager.synchserver.mappedclasses.transducerers.PERFORMFISH_ANALYSIS"));
ServiceParameters dataMinerService = ContextUtil.getDataMinerService(this.getThreadLocalRequest());
log.info("Found DM service: "+dataMinerService.getUrl() + " int this scope: "+ContextUtil.getPortalContext(this.getThreadLocalRequest()).getCurrentScope());
dataMinerService.setProperties(dmRequestParameters);
//Addding client parameters to DM service request
dmRequestParameters.putAll(mapParameters);
DMServiceResponse dmResponse = null;
String response;
try{
response = new HttpCallerUtil(dataMinerService.getUrl(), null, null).performGETRequestWithRetry(dmRequestParameters, pContext.getUserToken(), 5);
if(response==null){
log.error("The presponse returned is null");
throw new Exception("The presponse returned is null");
}
dmResponse = DataMinerUtil.parseResult(dataMinerService.getUrl(), response);
}catch(Exception e){
throw new Exception("The service did not produce any result. Change your selection and try again.");
}
if(dmResponse == null || dmResponse.isWithError())
throw new Exception("The response returned by DM service contains an Exception Status. (The call is: "+dmResponse.getHttpRequestURL()+"). Please report this issue at www.d4science.org/contact-us");
try{
DataMinerOutputData toDMOutputData = null;
List<DataMinerOutputData> listOut = dmResponse.getListDMOutputData();
for (DataMinerOutputData dataMinerOutputData : listOut) {
//I'm using this specific output data of DM
if(dataMinerOutputData.getFileDescription().contains("outputCharts")){
log.info("The output: "+dataMinerOutputData.getFileDescription()+ " with: "+dataMinerOutputData.getMimeType()+" is the candidate to unzip");
toDMOutputData = dataMinerOutputData;
break;
}
}
if(toDMOutputData==null || toDMOutputData.getPublicURL()==null)
throw new Exception("The response returned by DM service does not contain a file to unzip with name: 'outputCharts'. Please report this issue at www.d4science.org/contact-us");
String theZipFileURL = toDMOutputData.getPublicURL();
log.info("I'm using the file: "+theZipFileURL);
FileContentType filter = null;
ZipExtractorUtil zipExt = new ZipExtractorUtil(theZipFileURL, null);
List<OutputFile> output = zipExt.getOutputFiles();
log.info("Extracted output of type {} as list {}: ",filter,output);
DataMinerResponse theDMResponse = new DataMinerResponse(null, output);
log.debug("Returning {}",theDMResponse);
return theDMResponse;
}catch(Exception e){
log.error("There was an error extracting the DataMiner response from your request: ", e);
throw new Exception("The service did not produce any result. Change your request and try again.");
}
}
/**
* Manage outputs for perform fish analysis.
*
* @param output the output
* @return the list
*/
public List<OutputFile> manageOutputsForPerformFishAnalysis(List<OutputFile> output) {
OutputFile theOutputFile = null;
try {
Map<String, List<String>> theLegendMap = new HashMap<String, List<String>>();
for (OutputFile outputFile : output) {
log.trace("outputFile: {}", outputFile.getName());
if(outputFile.getName().toLowerCase().contains("legend") && outputFile.getDataType().equals(FileContentType.CSV)){
log.debug("Found legend file: {}", outputFile.getName());
CSVFile theLegendFile = getCSVFile(outputFile, false);
List<CSVRow> rows = theLegendFile.getValueRows();
//CREATING FROM *_legend_* CSV
//THE LEGEND WITH FIRST VALUE AS KEY AND REMAINING VALUES AS PROPERTIES
for (CSVRow csvRow : rows) {
theLegendMap.put(csvRow.getListValues().get(0), csvRow.getListValues().subList(1, csvRow.getListValues().size()));
}
break;
}
}
if(theLegendMap.size()>0){
log.info("Legend created as {}", theLegendMap.toString());
for (OutputFile outputFile : output) {
//THE FILE MUST NOT CONTAINT *_legend_* IN THE NAME
if(!outputFile.getName().toLowerCase().contains("legend") && outputFile.getDataType().equals(FileContentType.CSV)){
CSVFile theCorrelationFile = getCSVFile(outputFile, true);
try{
theOutputFile = createCSVWithLegendValues(theCorrelationFile, theLegendMap);
}catch(Exception e){
log.warn("Error thrown creating the CSV File with legend returning the original output file {}", outputFile);
theOutputFile = outputFile;
}
break;
}
}
}else{
log.warn("The Legend file not found returning the original output files {}", output);
return output;
}
return Arrays.asList(theOutputFile);
}catch (Exception e) {
log.warn("Error occured managing the CSV File returing the original files extracted form .zip {}", output);
return output;
}
}
/**
* Creates the csv with legend values.
*
* @param theCorrelationFile the the correlation file
* @param theLegendMap the the legend map
* @return the output file
* @throws Exception the exception
*/
private OutputFile createCSVWithLegendValues(CSVFile theCorrelationFile, Map<String, List<String>> theLegendMap) throws Exception{
CSVWriter cswWriter = null;
try{
CSVRow headerRow = theCorrelationFile.getHeaderRow();
java.nio.file.Path path = Files.createTempFile("With_Legend_"+theCorrelationFile.getFileName(), ".csv");
log.debug("Created temp file: {}", path.getFileName());
File tempFile = path.toFile();
cswWriter = new CSVWriter(tempFile);
StringBuilder lineBuilder = new StringBuilder();
for (String headerValue : headerRow.getListValues()) {
if(theLegendMap.containsKey(headerValue)){
List<String> legendValue = theLegendMap.get(headerValue);
for (String value : legendValue) {
lineBuilder.append(value);
lineBuilder.append(",");
}
}else{
lineBuilder.append(headerValue);
lineBuilder.append(",");
}
}
String headerLine = lineBuilder.toString();
headerLine = removeLastChar(headerLine);
log.debug("Writed header line: {}", headerLine);
cswWriter.writeCSVLine(headerLine);
for (CSVRow cswRow : theCorrelationFile.getValueRows()) {
lineBuilder = new StringBuilder();
for (String csvValue : cswRow.getListValues()) {
if(theLegendMap.containsKey(csvValue)){
List<String> legendValue = theLegendMap.get(csvValue);
for (String value : legendValue) {
lineBuilder.append(value);
lineBuilder.append(",");
}
}else{
lineBuilder.append(csvValue);
lineBuilder.append(",");
}
}
String csvLine = lineBuilder.toString();
csvLine = removeLastChar(csvLine);
log.debug("Writed line: {}", csvLine);
cswWriter.writeCSVLine(csvLine);
}
OutputFile output = new OutputFile();
output.setDataType(FileContentType.CSV);
output.setName(tempFile.getName());
output.setServerLocation(tempFile.getAbsolutePath());
return output;
}catch(Exception e){
log.info("Error on creating CSV File with legend: ", e);
throw new Exception("Error on creating CSV File with legend");
}finally{
try{
if(cswWriter!=null)
cswWriter.closeWriter();
}catch(Exception e){
//silent
}
}
}
/**
* Removes the last char.
*
* @param str the str
* @return the string
*/
private static String removeLastChar(String str) {
if(str==null || str.length()<1)
return str;
return str.substring(0, str.length() - 1);
}
/**
* Gets the CSV file.
*
* @param file the file
* @param deleteAfter the delete after
* @return the CSV file
* @throws Exception the exception
*/
@Override
public CSVFile getCSVFile(OutputFile file, boolean deleteAfter) throws Exception{
File theFile = null;
try{
if(file==null || file.getServerLocation()==null || file.getServerLocation().isEmpty()){
throw new Exception("Invalid image file null");
}
theFile = new File(file.getServerLocation());
CSVReader reader = new CSVReader(theFile);
CSVFile csvFile = reader.getCsvFile();
csvFile.setFileName(file.getName());
return csvFile;
}catch(Exception e){
log.error("There was an error extracting getting the CSV file: "+file.getName(), e);
throw new Exception("There was an error extracting getting the CSV file: "+file.getName()
+ ". Please report this issue at www.d4science.org/contact-us");
}finally{
//delete the file;
if(theFile!=null && deleteAfter){
try{
Files.deleteIfExists(theFile.toPath());
}catch(Exception e){
//silent
}
}
}
}
/**
* Gets the CSV file.
*
* @param theFileURL the the file url
* @return the CSV file
* @throws Exception the exception
*/
@Override
public CSVFile readCSVFile(String theFileURL) throws Exception{
log.info("Trying to read a csv file from URL: {}",theFileURL);
File theFile = null;
if(theFileURL==null){
throw new Exception("Invalid file URL. It is null");
}
URL theURL;
try{
theURL = new URL(theFileURL);
log.debug("URL: {} created correclty",theURL.toString());
}catch(MalformedURLException e){
log.error("There input URL "+theFileURL+" is malformed URL", e);
throw new Exception("There input URL "+theFileURL+" is malformed URL"
+ ". Please report this issue at www.d4science.org/contact-us");
}
try{
theFile = ZipExtractorUtil.createTempFile("CVS_FILE_"+UUID.randomUUID(), ".csv", copyToByteArray(theURL));
CSVReader reader = new CSVReader(theFile);
return reader.getCsvFile();
}catch(Exception e){
log.error("There was an error getting the CSV file from URL "+theURL.getRef(), e);
throw new Exception("There was an error getting the CSV file: "+theURL.getRef()
+ ". Please report this issue at www.d4science.org/contact-us");
}
}
/**
* Copy to byte array.
*
* @param url the url
* @return the byte[]
* @throws Exception the exception
*/
public byte[] copyToByteArray(URL url) throws Exception{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
return baos.toByteArray();
}
catch (IOException e) {
log.error("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
throw new Exception("Copy to byte array error");
}
finally {
if (is != null) {
try{
is.close();
baos.close();
}catch(Exception e){
//silent
}
}
}
}
/**
* Gets the image file.
*
* @param file the file
* @return the image file
* @throws Exception the exception
*/
@Override
public String getImageFile(OutputFile file) throws Exception{
File theFile = null;
try{
if(file==null || file.getServerLocation()==null || file.getServerLocation().isEmpty()){
throw new Exception("Invalid image file null");
}
theFile = new File(file.getServerLocation());
byte[] imageContent = Files.readAllBytes(theFile.toPath());
// System.out.println("<img src='data:image/png;base64," + DatatypeConverter.printBase64Binary(imageInByte) + "'></img>");
return "<img src='data:image/png;base64," + DatatypeConverter.printBase64Binary(imageContent) + "'></img>";
}catch(Exception e){
log.error("There was an error getting the image file: "+file.getName(), e);
throw new Exception("There was an error getting the image file: "+file.getName()
+ ". Please report this issue at www.d4science.org/contact-us");
}finally{
//delete the file;
if(theFile!=null){
try{
Files.deleteIfExists(theFile.toPath());
}catch(Exception e){
//silent
}
}
}
}
}

@ -0,0 +1,154 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.server;
import java.util.ArrayList;
import java.util.List;
import org.gcube.portlets.user.performfishanalytics.shared.Area;
import org.gcube.portlets.user.performfishanalytics.shared.KPI;
import org.gcube.portlets.user.performfishanalytics.shared.Period;
import org.gcube.portlets.user.performfishanalytics.shared.Population;
import org.gcube.portlets.user.performfishanalytics.shared.PopulationType;
import org.gcube.portlets.user.performfishanalytics.shared.PopulationTypeProperties;
import org.gcube.portlets.user.performfishanalytics.shared.Quarter;
import org.gcube.portlets.user.performfishanalytics.shared.ReferencePopulationType;
import org.gcube.portlets.user.performfishanalytics.shared.Species;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class ToAvoidIndirectSerialization.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 22, 2019
*/
public class ToAvoidIndirectSerialization {
protected static Logger log = LoggerFactory.getLogger(ToAvoidIndirectSerialization.class);
//TO FIX Type 'org.eclipse.persistence.indirection.IndirectList'
//was not included in the set of types which can be serialized
//by this SerializationPolicy or its Class object could not be loaded.
//For security purposes, this type will not be serialized.: instance = {IndirectList: not instantiated}
/**
* To gwt serializable.
*
* @param listPopulationType the list population type
* @param population the population
* @param fetchProperties the fetch properties
* @return the list
*/
@SuppressWarnings("unchecked")
public static List<PopulationType> toGWTSerializable(List<PopulationType> listPopulationType, Population population, boolean fetchProperties){
if(listPopulationType==null)
return new ArrayList<PopulationType>(1);
List<PopulationType> gwtSerializableList = new ArrayList<PopulationType>(listPopulationType.size());
for (PopulationType populationType : listPopulationType){
log.trace("Converting Population Type: "+populationType);
if(fetchProperties){
List<Species> listSpecies = populationType.getListSpecies();
populationType.setListSpecies((List<Species>) toListPopulationProperties(listSpecies, null));
List<Quarter> listQuarter = populationType.getListQuarter();
populationType.setListQuarter((List<Quarter>) toListPopulationProperties(listQuarter, null));
List<Area> listArea = populationType.getListArea();
populationType.setListArea((List<Area>) toListPopulationProperties(listArea, null));
List<Period> listPeriod = populationType.getListPeriod();
populationType.setListPeriod((List<Period>) toListPopulationProperties(listPeriod, null));
}else{
populationType.setListSpecies(null);
populationType.setListQuarter(null);
populationType.setListArea(null);
populationType.setListPeriod(null);
}
populationType.setListKPI(null);
populationType.setPopulation(population);
gwtSerializableList.add(populationType);
}
if(population!=null)
population.setListPopulationType(gwtSerializableList);
return gwtSerializableList;
}
/**
* Sets the population types.
*
* @param list the list
* @param type the type
* @return the list<? extends reference population type>
*/
public static List<? extends ReferencePopulationType> setPopulationTypes(List<? extends ReferencePopulationType> list, PopulationType type){
if(list==null)
return null;
for (ReferencePopulationType refencePopulationType : list) {
refencePopulationType.setPopulationType(type);
}
return list;
}
/**
* To list population properties.
*
* @param list the list
* @param type the type
* @return the list<? extends population type properties>
*/
public static List<? extends PopulationTypeProperties> toListPopulationProperties(List<? extends PopulationTypeProperties> list, PopulationType type){
List<PopulationTypeProperties> listGWT = new ArrayList<PopulationTypeProperties>();
for (PopulationTypeProperties populationTypeProperties : list) {
PopulationTypeProperties pop = toPopulationProperties(populationTypeProperties, type);
listGWT.add(pop);
}
return listGWT;
}
/**
* To population properties.
*
* @param <T> the generic type
* @param object the object
* @param type the type
* @return the t
*/
@SuppressWarnings("unchecked")
public static <T extends PopulationTypeProperties> T toPopulationProperties(T object, PopulationType type){
if(object instanceof Area){
return (T) new Area(object.getId(), object.getName(), object.getDescription(), type);
}else if(object instanceof Species){
return (T) new Species(object.getId(), object.getName(), object.getDescription(), type);
}else if(object instanceof Quarter){
return (T) new Quarter(object.getId(), object.getName(), object.getDescription(), type);
}else if(object instanceof Period){
return (T) new Period(object.getId(), object.getName(), object.getDescription(), type);
}else if(object instanceof KPI){
KPI toKPI = (KPI) object;
KPI gwtKPI = new KPI(toKPI.getId(),toKPI.getCode(),toKPI.getName(),toKPI.getDescription(), null,type,toKPI.getDeepIndex());
gwtKPI.setLeaf(toKPI.getListKPI()==null || toKPI.getListKPI().isEmpty());
return (T) gwtKPI;
}
return null;
}
}

@ -0,0 +1,176 @@
package org.gcube.portlets.user.performfishanalytics.server.database;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.eclipse.persistence.jpa.PersistenceProvider;
import org.gcube.portlets.user.performfishanalytics.server.util.ServiceParameters;
import org.gcube.portlets.user.performfishanalytics.shared.exceptions.SessionExpired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class EntityManagerFactoryCreator is a Singleton.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Feb 20, 2015
*/
public class EntityManagerFactoryCreator {
public static final String PERFORM_FISH_ANALYTICS_DB_ENDPOINT_NAME = "PerformFISH-AnalyticsDB";
public static final String PERFORM_FISH_ANALYTICS_PERSISTENCE_FACTORY = "PERFORMFISH_ANALYTICS_PERSISTENCE_FACTORY";
public static Logger log = LoggerFactory.getLogger(EntityManagerFactoryCreator.class);
protected static final String PROPERTY_CATALINA_HOME = "catalina.home";
protected static final String CATALINA_HOME = "CATALINA_HOME";
private static EntityManagerFactory factoryPerformFishAnalytics;
private static ServiceParameters dbParameters;
private static EntityManagerFactoryCreator INSTANCE;
/**
* Gets the instance local mode.
*
* @return the instance local mode
* @throws Exception the exception
*/
public static synchronized EntityManagerFactoryCreator instanceLocalMode() throws Exception{
if(INSTANCE==null){
try{
//INSTANCE = new EntityManagerFactoryCreator(scope);
factoryPerformFishAnalytics = createEntityManagerFactoryLocalMode();
}catch(Exception e){
log.warn("EntityManagerFactory created in TEST MODE");
}
}
return INSTANCE;
}
/**
* Gets the entity manager factory.
*
* @return the entity manager factory
*/
public static synchronized EntityManagerFactory getEntityManagerFactory(){
if (factoryPerformFishAnalytics == null){
log.info("EntityManagerFactory is null, creating..");
factoryPerformFishAnalytics = createEntityManagerFactory();
}
else if(!factoryPerformFishAnalytics.isOpen()){
log.info("EntityManagerFactory is not open, closing and creating..");
factoryPerformFishAnalytics.close();
factoryPerformFishAnalytics = createEntityManagerFactory();
}
log.info("Returning EntityManagerFactory");
return factoryPerformFishAnalytics;
}
/**
* Creates the entity manager factory.
*
* @return the entity manager factory
*/
private static EntityManagerFactory createEntityManagerFactory() {
Map<String, String> properties = new HashMap<String, String>();
EntityManagerFactory emf = null;
try {
properties.put("javax.persistence.jdbc.url", "jdbc:h2://"+dbParameters.getUrl());
properties.put("javax.persistence.jdbc.user", dbParameters.getUser());
properties.put("javax.persistence.jdbc.password", dbParameters.getPassword());
log.debug("Instancing new Entity Manager using properties: "+properties);
emf = Persistence.createEntityManagerFactory(PERFORM_FISH_ANALYTICS_PERSISTENCE_FACTORY, properties);
} catch (Exception e) {
log.error("error on get createEntityManagerFactory " + e, e);
}
// emf = Persistence.createEntityManagerFactory("jpablogPUnit");
// logger.info("created entity manager factory on: "+ properties.get(JAVAX_PERSISTENCE_JDBC_URL));
return emf;
}
/**
* Creates the entity manager factory test mode.
*
* @return the entity manager factory
*/
private static EntityManagerFactory createEntityManagerFactoryLocalMode(){
Map<String, String> properties = new HashMap<String, String>();
EntityManagerFactory emf = null;
try {
String jdbcURL = getJDBCConnectionUrl(true);
log.info("JDBC URL IS: "+jdbcURL);
properties.put("javax.persistence.jdbc.url", jdbcURL);
// properties.put("javax.persistence.jdbc.user", "postgres");
// properties.put("javax.persistence.jdbc.password", "8gridsphere1");
//emf = Persistence.createEntityManagerFactory(PERFORM_FISH_ANALYTICS_PERSISTENCE_FACTORY, properties);
emf = new PersistenceProvider().createEntityManagerFactory(PERFORM_FISH_ANALYTICS_PERSISTENCE_FACTORY, properties);
log.info("DB created at persistence.jdbc.url: "+jdbcURL+" isOpen? "+emf.isOpen());
} catch (Exception e) {
log.error("error on get createEntityManagerFactory " + e, e);
}
return emf;
}
/**
* Gets the tomcat folder.
*
* @return the tomcat folder
* @throws Exception the exception
*/
public static String getTomcatFolder() throws Exception{
String catalinaHome = System.getenv(CATALINA_HOME) != null ? System.getenv(CATALINA_HOME) : System.getProperty(PROPERTY_CATALINA_HOME);
if(catalinaHome == null || catalinaHome.isEmpty()){
log.error("****\n\n\nCATALINA_HOME ENVIROMENT NOT FOUND - RETURNED / PATH \n\n\n*****");
throw new Exception(CATALINA_HOME +" not found in the ENVIRONMENT");
}
return catalinaHome;
}
/**
* Gets the JDBC connection url.
*
* @param localMode the local mode
* @return the JDBC connection url
* @throws SessionExpired the session expired
* @throws Exception the exception
*/
public static String getJDBCConnectionUrl(boolean localMode) throws SessionExpired, Exception{
if(localMode){
log.warn("LOCAL MODE ACTIVED");
return "jdbc:h2:"+getPersistenceFolderPath()+"/H2AnalyticsDB;create=true";
}
throw new Exception("Only JDBC local mode is working");
}
/**
* Gets the persistence folder path.
*
* @return the persistence folder path
* @throws Exception the exception
*/
public static String getPersistenceFolderPath() throws Exception{
String tomcatFolder = getTomcatFolder();
tomcatFolder = tomcatFolder.endsWith("/") ? tomcatFolder.substring(0, tomcatFolder.length()-1) : tomcatFolder;
return String.format("%s/%s/%s", getTomcatFolder(), "persistence", "PerformFISH");
}
}

@ -0,0 +1,81 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.server.database;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.gcube.portlets.user.performfishanalytics.shared.exceptions.DatabaseServiceException;
/**
* The Interface JavaPersistenceHandler.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 11, 2019
* @param <T> the generic type
*/
public interface JavaPersistenceHandler<T> {
/**
* Gets the criteria builder.
*
* @return the criteria builder
* @throws DatabaseServiceException the database service exception
*/
public CriteriaBuilder getCriteriaBuilder() throws DatabaseServiceException;
/**
* Gets the entity manager factory.
*
* @return the entity manager factory
*/
public EntityManagerFactory getEntityManagerFactory();
/**
* Creates the new manager.
*
* @return the entity manager
* @throws DatabaseServiceException the database service exception
*/
public EntityManager createNewManager() throws DatabaseServiceException;
/**
* Execute criteria query.
*
* @param criteriaQuery the criteria query
* @return the list
* @throws DatabaseServiceException the database service exception
*/
@SuppressWarnings({ "unchecked" })
public List<T> executeCriteriaQuery(CriteriaQuery<Object> criteriaQuery)
throws DatabaseServiceException;
/**
* Execute typed query.
*
* @param cq the cq
* @param startIndex the start index
* @param offset the offset
* @return the list
* @throws DatabaseServiceException the database service exception
*/
public List<T> executeTypedQuery(CriteriaQuery<Object> cq, int startIndex,
int offset) throws DatabaseServiceException;
/**
* Root from.
*
* @param cq the cq
* @return the root
*/
public abstract Root<T> rootFrom(CriteriaQuery<Object> cq);
}

@ -0,0 +1,361 @@
package org.gcube.portlets.user.performfishanalytics.server.persistence;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.gcube.portlets.user.performfishanalytics.server.database.JavaPersistenceHandler;
import org.gcube.portlets.user.performfishanalytics.shared.GenericDao;
import org.gcube.portlets.user.performfishanalytics.shared.exceptions.DatabaseServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class AbstractPersistence.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 11, 2019
* @param <T> the generic type
*/
public abstract class AbstractPersistence<T extends GenericDao> implements JavaPersistenceHandler<T>{
protected Logger log = LoggerFactory.getLogger(AbstractPersistence.class);
protected EntityManagerFactory entityManagerFactory;
private String tableName;
/**
* Instantiates a new abstract persistence.
*
* @param factory the factory
* @param tableName the table name
*/
AbstractPersistence(EntityManagerFactory factory, String tableName){
this.entityManagerFactory = factory;
this.tableName = tableName;
}
/**
* Gets the entity manager factory.
*
* @return the entity manager factory
*/
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
/**
* Creates the new manager.
*
* @return the entity manager
* @throws DatabaseServiceException the database service exception
*/
public EntityManager createNewManager() throws DatabaseServiceException{
try{
if(entityManagerFactory!=null)
return entityManagerFactory.createEntityManager();
}catch (Exception e) {
log.error("An error occurred in create new entity manager ",e);
e.printStackTrace();
throw new DatabaseServiceException("An error occurred in create new entity manager");
}
return null;
}
/**
* Insert.
*
* @param item the item
* @return true, if successful
* @throws DatabaseServiceException the database service exception
*/
public boolean insert(T item) throws DatabaseServiceException{
EntityManager em = createNewManager();
try {
em.getTransaction().begin();
em.persist(item);
em.getTransaction().commit();
} catch (Exception e) {
log.error("Error in insert: "+e.getMessage(), e);
}
finally {
if (em.getTransaction().isActive())
em.getTransaction().rollback();
em.close();
}
return true;
}
/**
* Update.
*
* @param item the item
* @return the t
* @throws DatabaseServiceException the database service exception
*/
public T update(T item) throws DatabaseServiceException{
EntityManager em = createNewManager();
try {
em.getTransaction().begin();
item = em.merge(item);
em.getTransaction().commit();
} catch (Exception e) {
log.error("Error in update: "+e.getMessage(), e);
}
finally {
if (em.getTransaction().isActive())
em.getTransaction().rollback();
em.close();
}
return item;
}
/**
* Removes the.
*
* @param item the item
* @param transaction the transaction
* @return true, if successful
* @throws DatabaseServiceException the database service exception
*/
public boolean remove(T item, boolean transaction) throws DatabaseServiceException {
EntityManager em = createNewManager();
try {
if(transaction){
em.getTransaction().begin();
em.remove(item);
em.getTransaction().commit();
}
else
em.remove(item);
} catch (Exception e) {
log.error("Error in remove: "+e.getMessage(), e);
}
finally {
if (em.getTransaction().isActive())
em.getTransaction().rollback();
em.close();
}
return true;
}
/**
* Gets the list.
*
* @return the list
* @throws DatabaseServiceException the database service exception
*/
public List<T> getList() throws DatabaseServiceException {
EntityManager em = createNewManager();
List<T> listT = new ArrayList<T>();
try {
Query query = em.createQuery("select t from "+tableName+" t");
listT = query.getResultList();
} catch (Exception e) {
log.error("Error during getList for table: " + tableName, e);
throw new DatabaseServiceException("Error during getList for table: " + tableName);
} finally {
em.close();
}
return listT;
}
/**
* Count items.
*
* @return the int
* @throws DatabaseServiceException the database service exception
*/
public int countItems() throws DatabaseServiceException {
return getList().size();
}
/**
* Removes the all.
*
* @return the int
* @throws DatabaseServiceException the database service exception
*/
public int removeAll() throws DatabaseServiceException {
EntityManager em = createNewManager();
int removed = 0;
try {
em.getTransaction().begin();
removed = em.createQuery("DELETE FROM "+tableName).executeUpdate();
em.getTransaction().commit();
log.info("DELETED FROM "+tableName+" " + removed +" item/s");
} catch (Exception e) {
log.error("Error in removeAll: " + e.getMessage(), e);
} finally {
em.close();
}
return removed;
}
/**
* Gets the item by primary key.
*
* @param id the id
* @return the item by primary key
* @throws DatabaseServiceException the database service exception
*/
public T getItemByPrimaryKey(Integer id) throws DatabaseServiceException {
log.debug("getItemByKey id: "+id);
EntityManager em = createNewManager();
T theObject = null;
try {
theObject = (T) em.getReference(theObject.getClass(), id);
} finally {
em.close();
}
log.debug("Returning row: "+theObject);
return theObject;
}
/**
* Gets the criteria builder.
*
* @return the criteria builder
* @throws DatabaseServiceException the database service exception
*/
public CriteriaBuilder getCriteriaBuilder() throws DatabaseServiceException {
return createNewManager().getCriteriaBuilder();
}
/**
* Execute criteria query.
*
* @param criteriaQuery the criteria query
* @return the list
* @throws DatabaseServiceException the database service exception
*/
public List<T> executeCriteriaQuery(CriteriaQuery<Object> criteriaQuery) throws DatabaseServiceException{
EntityManager em = createNewManager();
List<T> listOBJ = new ArrayList<T>();
try {
Query query = em.createQuery(criteriaQuery);
listOBJ = query.getResultList();
} finally {
em.close();
}
return listOBJ;
}
/**
* Gets the list.
*
* @param filterMap the filter map
* @param startIndex the start index. You must pass -1 if you do not want to use 'startIndex'
* @param offset the offset. You must pass -1 if you do not want to use 'offset'
* @return the list
* @throws DatabaseServiceException the database service exception
*/
public List<T> getList(Map<String, String> filterMap, int startIndex, int offset) throws DatabaseServiceException{
EntityManager em = createNewManager();
List<T> listOBJ = new ArrayList<T>();
try {
String queryString = "select t from "+tableName+" t";
if(filterMap!=null && filterMap.size()>0){
queryString+=" where";
for (String param : filterMap.keySet()) {
String value = filterMap.get(param);
queryString+=" t."+param+"="+"'"+value+"'";
queryString+="AND";
}
queryString = queryString.substring(0, queryString.lastIndexOf("AND"));
}
Query query = em.createQuery(queryString);
if(startIndex>-1)
query.setFirstResult(startIndex);
if(offset>-1)
query.setMaxResults(offset);
listOBJ = query.getResultList();
} finally {
em.close();
}
return listOBJ;
}
/**
* Root from.
*
* @param cq the cq
* @return the root
*/
public abstract Root<T> rootFrom(CriteriaQuery<Object> cq);
/**
* Gets the list.
*
* @param startIndex the start index
* @param offset the offset
* @return the list
* @throws DatabaseServiceException the database service exception
*/
public abstract List<T> getList(int startIndex, int offset) throws DatabaseServiceException;
/**
* Execute typed query.
*
* @param cq the cq
* @param startIndex the start index
* @param offset the offset
* @return the list
* @throws DatabaseServiceException the database service exception
*/
public abstract List<T> executeTypedQuery(CriteriaQuery<Object> cq, int startIndex, int offset) throws DatabaseServiceException;
/**
* Delete item by id field.
*
* @param idField the id field
* @return the int
* @throws DatabaseServiceException the database service exception
*/
public abstract int deleteItemByIdField(String idField) throws DatabaseServiceException;
}

@ -0,0 +1,78 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.server.persistence;
import java.util.List;
import javax.persistence.EntityManagerFactory;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.gcube.portlets.user.performfishanalytics.shared.GenericDao;
import org.gcube.portlets.user.performfishanalytics.shared.exceptions.DatabaseServiceException;
/**
* The Class GenericPersistence.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 11, 2019
* @param <T> the generic type
*/
public class GenericPersistence<T extends GenericDao> extends AbstractPersistence<T>{
/**
* Instantiates a new generic persistence.
*
* @param factory the factory
* @param tableName the table name
*/
GenericPersistence(EntityManagerFactory factory, String tableName) {
super(factory, tableName);
}
/* (non-Javadoc)
* @see org.gcube.portlets.user.performfishanalytics.server.persistence.AbstractPersistence#rootFrom(javax.persistence.criteria.CriteriaQuery)
*/
@Override
public Root rootFrom(CriteriaQuery cq) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.gcube.portlets.user.performfishanalytics.server.persistence.AbstractPersistence#getList(int, int)
*/
@Override
public List getList(int startIndex, int offset)
throws DatabaseServiceException {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.gcube.portlets.user.performfishanalytics.server.persistence.AbstractPersistence#executeTypedQuery(javax.persistence.criteria.CriteriaQuery, int, int)
*/
@Override
public List executeTypedQuery(CriteriaQuery cq, int startIndex, int offset)
throws DatabaseServiceException {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.gcube.portlets.user.performfishanalytics.server.persistence.AbstractPersistence#deleteItemByIdField(java.lang.String)
*/
@Override
public int deleteItemByIdField(String idField)
throws DatabaseServiceException {
// TODO Auto-generated method stub
return 0;
}
}

@ -0,0 +1,51 @@
package org.gcube.portlets.user.performfishanalytics.server.persistence;
import javax.persistence.EntityManagerFactory;
import lombok.Getter;
import lombok.ToString;
import org.gcube.portlets.user.performfishanalytics.shared.GenericDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Gets the persistence entity.
*
* @return the persistence entity
*/
@Getter
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@ToString
public class GenericPersistenceDaoBuilder<T extends GenericDao> {
public static Logger logger = LoggerFactory.getLogger(GenericPersistenceDaoBuilder.class);
private EntityManagerFactory factory;
private String tableName;
private GenericPersistence<T> persistenceEntity;
/**
* Instantiates a new dao generci builder manager.
*
* @param emFactory the em factory
* @param tableName the table name
*/
public GenericPersistenceDaoBuilder(EntityManagerFactory emFactory, String tableName) {
this.factory = emFactory;
this.tableName = tableName;
instance();
}
/**
* Instance.
*/
private void instance(){
this.persistenceEntity = new GenericPersistence<T>(factory, tableName);
}
}

@ -0,0 +1,46 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.server.persistence;
import javax.persistence.PostRemove;
import org.gcube.portlets.user.performfishanalytics.shared.Population;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The listener interface for receiving packageEntity events.
* The class that is interested in processing a packageEntity
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's <code>addPackageEntityListener<code> method. When
* the packageEntity event occurs, that object's appropriate
* method is invoked.
*
* @see PackageEntityEvent
*/
public class PopulationEntityListener {
protected static Logger logger = LoggerFactory.getLogger(PopulationEntityListener.class);
/**
* On post remove.
*
* @param entity the entity
*/
@PostRemove void onPostRemove(Population entity) {
// System.out.println("onPostRemove "+entity);
logger.trace("onPostRemove Package: "+entity.getInternalId());
decrementPackages(entity);
}
/**
* Decrement packages.
*
* @param pck the pck
*/
private void decrementPackages(Population pck){
}
}

@ -0,0 +1,202 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.server.util;
import javax.persistence.EntityManagerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.gcube.common.portal.PortalContext;
import org.gcube.portlets.user.performfishanalytics.server.database.EntityManagerFactoryCreator;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.liferay.portal.service.UserLocalServiceUtil;
/**
* The Class WsUtil.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 11, 2019
*/
public class ContextUtil {
protected static Logger log = LoggerFactory.getLogger(ContextUtil.class);
public static final String PERFORM_SERVICE = "perform-service";
protected static final String PERFORM_FISH_SERVICE_ATTRIBUTE = "PERFORM_FISH_SERVICE";
protected static final String PERFORM_FISH_RESPONSE_ATTRIBUTE = "PERFORM_FISH_RESPONSE";
protected static final String DATAMINER_SERVICE_ATTRIBUTE = "DATAMINER_SERVICE";
public static String SERVICE_ENDPOINT_CATEGORY = "DataAnalysis";
public static String SERVICE_ENDPOINT_NAME = "DataMiner";
/**
* Checks if is within portal.
*
* @return true if you're running into the portal, false if in development
*/
public static boolean isWithinPortal() {
try {
UserLocalServiceUtil.getService();
return true;
}
catch (Exception ex) {
log.trace("Development Mode ON");
return false;
}
}
/**
* Gets the portal context.
*
* @param httpServletRequest the http servlet request
* @return the portal context
*/
public static PortalContextInfo getPortalContext(HttpServletRequest httpServletRequest){
PortalContext pContext = PortalContext.getConfiguration();
//USER
GCubeUser user = pContext.getCurrentUser(httpServletRequest);
String username = user.getUsername();
String fullName = user.getFullname();
String email = user.getEmail();
String avatarID = user.getUserAvatarId();
String avatarURL = user.getUserAvatarURL();
//SESSION
String currentScope = pContext.getCurrentScope(httpServletRequest);
String userToken = pContext.getCurrentUserToken(httpServletRequest);
long currGroupId = pContext.getCurrentGroupId(httpServletRequest);
return new PortalContextInfo(username, fullName, email, avatarID, avatarURL, currentScope, userToken, currGroupId);
}
/**
* Gets the portal context.
*
* @param httpServletRequest the http servlet request
* @param overrideScope the override scope
* @return the portal context
*/
public static PortalContextInfo getPortalContext(HttpServletRequest httpServletRequest, String overrideScope){
PortalContextInfo info = getPortalContext(httpServletRequest);
info.setCurrentScope(overrideScope);
return info;
}
/**
* Checks if is session expired.
*
* @param httpServletRequest the http servlet request
* @return true, if is session expired
* @throws Exception the exception
*/
public static boolean isSessionExpired(HttpServletRequest httpServletRequest) throws Exception {
log.trace("workspace session validating...");
return PortalContext.getConfiguration().getCurrentUser(httpServletRequest)==null;
}
/**
* Gets the entity factory.
*
* @param request the request
* @return the entity factory
* @throws Exception the exception
*/
private EntityManagerFactory getEntityFactory(HttpServletRequest request) throws Exception{
PortalContextInfo pContext = getPortalContext(request);
EntityManagerFactoryCreator.instanceLocalMode();
return EntityManagerFactoryCreator.getEntityManagerFactory();
}
/**
* Gets the perform fish service.
*
* @param httpServletRequest the http servlet request
* @return the perform fish service
* @throws Exception the exception
*/
public static ServiceParameters getPerformFishService(HttpServletRequest httpServletRequest) throws Exception
{
PortalContextInfo pContext = getPortalContext(httpServletRequest);
log.trace("PortalContextInfo: "+pContext);
HttpSession session = httpServletRequest.getSession();
ServiceParameters performFishService = (ServiceParameters) session.getAttribute(PERFORM_FISH_SERVICE_ATTRIBUTE);
if (performFishService == null){
log.info("Initializing the "+PERFORM_FISH_SERVICE_ATTRIBUTE+"...");
GcoreEndpointReader gcoreEndPointReader = new GcoreEndpointReader(pContext.getCurrentScope(), PERFORM_SERVICE, "Application", "org.gcube.application.perform.service.PerformService");
performFishService = new ServiceParameters(gcoreEndPointReader.getEndpointValue(), null, null, null);
log.debug("Instancied peform-fish service: "+performFishService);
session.setAttribute(PERFORM_FISH_SERVICE_ATTRIBUTE, performFishService);
}
return performFishService;
}
/**
* Save perform fish response.
*
* @param httpServletRequest the http servlet request
* @return the service parameters
* @throws Exception the exception
*/
public static ServiceParameters savePerformFishResponse(HttpServletRequest httpServletRequest) throws Exception
{
PortalContextInfo pContext = getPortalContext(httpServletRequest);
log.trace("PortalContextInfo: "+pContext);
HttpSession session = httpServletRequest.getSession();
ServiceParameters performFishService = (ServiceParameters) session.getAttribute(PERFORM_FISH_RESPONSE_ATTRIBUTE);
if (performFishService == null){
log.info("Initializing the "+PERFORM_FISH_SERVICE_ATTRIBUTE+"...");
GcoreEndpointReader gcoreEndPointReader = new GcoreEndpointReader(pContext.getCurrentScope(), PERFORM_SERVICE, "Application", "org.gcube.application.perform.service.PerformService");
performFishService = new ServiceParameters(gcoreEndPointReader.getEndpointValue(), null, null, null);
log.debug("Instancied peform-fish service: "+performFishService);
session.setAttribute(PERFORM_FISH_SERVICE_ATTRIBUTE, performFishService);
}
return performFishService;
}
/**
* Gets the data miner service.
*
* @param httpServletRequest the http servlet request
* @return the data miner service
* @throws Exception the exception
*/
public static ServiceParameters getDataMinerService(HttpServletRequest httpServletRequest) throws Exception {
PortalContextInfo pContext = getPortalContext(httpServletRequest);
log.trace("PortalContextInfo: "+pContext);
HttpSession session = httpServletRequest.getSession();
ServiceParameters dataminerService = (ServiceParameters) session.getAttribute(DATAMINER_SERVICE_ATTRIBUTE);
if (dataminerService == null){
log.info("Initializing the "+DATAMINER_SERVICE_ATTRIBUTE+"...");
ServiceEndpointReader reader = new ServiceEndpointReader(pContext.getCurrentScope(), SERVICE_ENDPOINT_NAME, SERVICE_ENDPOINT_CATEGORY);
dataminerService = reader.readResource(false);
log.debug("Instancied dataminer-service: "+dataminerService);
session.setAttribute(DATAMINER_SERVICE_ATTRIBUTE, dataminerService);
}
return dataminerService;
}
}

@ -0,0 +1,46 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.server.util;
import java.io.InputStream;
import java.util.List;
import org.gcube.portlets.user.performfishanalytics.server.util.dataminer.DMServiceResponse;
import org.gcube.portlets.user.performfishanalytics.server.util.dataminer.DataMinerOutputData;
import org.gcube.portlets.user.performfishanalytics.server.util.xml.WPSParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* The Class DataMinerUtil.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jan 23, 2019
*/
public class DataMinerUtil {
public static String XML_RESULT_ROOT_EXCEPTION = "wps:ExceptionReport";
protected static Logger log = LoggerFactory.getLogger(DataMinerUtil.class);
public static DMServiceResponse parseResult(String httpRequestURL, String xml) throws Exception {
InputStream wpsResponseStream = WPSParserUtil.stringToInputStream(xml);
Document doc = WPSParserUtil.inputStreamToW3CDocument(wpsResponseStream);
Element root = doc.getDocumentElement();
String rootName = root.getNodeName();
log.info("Root name: "+rootName);
if(root.getNodeName().compareToIgnoreCase(XML_RESULT_ROOT_EXCEPTION) == 0){
return new DMServiceResponse(true, httpRequestURL, xml, null);
}else {
List<DataMinerOutputData> listResponse = WPSParserUtil.getListDataMinerOutputDataFromWPSResponse(doc);
return new DMServiceResponse(false, httpRequestURL, xml, listResponse);
}
}
}

@ -0,0 +1,58 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.server.util;
import java.util.List;
import javax.persistence.EntityManagerFactory;
import javax.servlet.ServletContext;
import org.gcube.portlets.user.performfishanalytics.server.persistence.GenericPersistenceDaoBuilder;
import org.gcube.portlets.user.performfishanalytics.server.util.database.FillDatabasePerBatchType;
import org.gcube.portlets.user.performfishanalytics.shared.Population;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class DatabaseUtil.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jan 22, 2019
*/
public class DatabaseUtil {
protected static Logger log = LoggerFactory.getLogger(DatabaseUtil.class);
/**
*
*/
public DatabaseUtil() {
}
/**
* Fill database if empty.
*
* @param dbFactory the db factory
* @param context the context
* @throws Exception the exception
*/
public void fillDatabaseIfEmpty(EntityManagerFactory dbFactory, ServletContext context) throws Exception{
GenericPersistenceDaoBuilder<Population> builderPopulation =
new GenericPersistenceDaoBuilder<Population>(
dbFactory, Population.class.getSimpleName());
List<Population> listPopulation = builderPopulation.getPersistenceEntity().getList();
if(listPopulation.size()==0){
log.info("The DB is empty filling it:");
FillDatabasePerBatchType.fillDatabase(dbFactory, context);
log.info("The DB was filled, printing it:");
FillDatabasePerBatchType.printDatabaseData(dbFactory);
}else{
log.info("The DB is filled, no action performed");
}
}
}

@ -0,0 +1,46 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.server.util;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class FileUtil.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Feb 4, 2019
*/
public class FileUtil {
protected static Logger log = LoggerFactory.getLogger(FileUtil.class);
/**
* Delete directory recursion.
*
* @param path the path
* @throws IOException Signals that an I/O exception has occurred.
*/
public static void deleteDirectoryRecursion(Path path) throws IOException {
if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) {
try (DirectoryStream<Path> entries = Files.newDirectoryStream(path)) {
for (Path entry : entries) {
deleteDirectoryRecursion(entry);
}
}
}
log.info("Deleting File/Directory: %s", path.getFileName());
Files.delete(path);
}
}

@ -0,0 +1,157 @@
package org.gcube.portlets.user.performfishanalytics.server.util;
import static org.gcube.resources.discovery.icclient.ICFactory.client;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.util.List;
import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class GcoreEndpointReader.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 23, 2019
*/
public class GcoreEndpointReader {
private String serviceName = "CkanConnector";
private String serviceClass = "DataAccess";
private String endpointEntryName;
private static final Logger log = LoggerFactory.getLogger(GcoreEndpointReader.class);
private String endpointValue;
/**
* Instantiates a new gcore endpoint reader.
*
* @param scope the scope
* @param serviceName the service name
* @param serviceClass the service class
* @param endpointEntryName the endpoint entry name
* @throws Exception the exception
*/
public GcoreEndpointReader(String scope, String serviceName, String serviceClass, String endpointEntryName) throws Exception {
this.serviceClass = serviceClass;
this.serviceName = serviceName;
this.endpointEntryName = endpointEntryName;
String callerProviderScope = ScopeProvider.instance.get();
try{
log.info("set scope "+scope);
ScopeProvider.instance.set(scope);
SimpleQuery query = queryFor(GCoreEndpoint.class);
query.addCondition(String.format("$resource/Profile/ServiceClass/text() eq '%s'",serviceClass));
//query.addCondition("$resource/Profile/DeploymentData/Status/text() eq 'ready'");
query.addCondition(String.format("$resource/Profile/ServiceName/text() eq '%s'",serviceName));
if(this.endpointEntryName!=null)
query.setResult("$resource/Profile/AccessPoint/RunningInstanceInterfaces//Endpoint[@EntryName/string() eq \""+endpointEntryName+"\"]/text()");
log.debug("submitting quey "+query.toString());
DiscoveryClient<String> client = client();
List<String> endpoints = client.submit(query);
if (endpoints == null || endpoints.isEmpty()) throw new Exception("Cannot retrieve the GCoreEndpoint serviceName: "+serviceName +", serviceClass: " +serviceClass +", endpointEntryName: "+endpointEntryName+", in scope: "+scope);
this.endpointValue = endpoints.get(0);
if(endpointValue==null)
throw new Exception("Endpoint:"+endpointEntryName+", is null for serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+scope);
log.info("found the GCoreEndpoint with serviceName: "+serviceName +", serviceClass: " +serviceClass +", endpointEntryName: "+endpointEntryName+", in the scope: "+scope);
/*Group<Endpoint> accessPoints = se.profile().endpoints();
if(accessPoints.size()==0) throw new Exception("Endpoint in serviceName serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+scope +" not found");
Endpoint ep = accessPoints.iterator().next();
String epName = ep.name();
System.out.println(epName);*/
}catch(Exception e){
String error = "An error occurred during GCoreEndpoint discovery, serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+scope +".";
log.error(error, e);
throw new Exception(error);
}finally{
log.info("scope provider reset");
ScopeProvider.instance.set(callerProviderScope);
}
}
/**
* Gets the endpoint entry name.
*
* @return the endpointEntryName
*/
public String getEndpointEntryName() {
return endpointEntryName;
}
/**
* Gets the endpoint value.
*
* @return the endpointValue
*/
public String getEndpointValue() {
return endpointValue;
}
/**
* Gets the service class.
*
* @return the serviceClass
*/
public String getServiceClass() {
return serviceClass;
}
/**
* Gets the service name.
*
* @return the serviceName
*/
public String getServiceName() {
return serviceName;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("GcoreEndpointReader [serviceName=");
builder.append(serviceName);
builder.append(", serviceClass=");
builder.append(serviceClass);
builder.append(", endpointEntryName=");
builder.append(endpointEntryName);
builder.append(", endpointValue=");
builder.append(endpointValue);
builder.append("]");
return builder.toString();
}
}

@ -0,0 +1,64 @@
/**
*
*/
package org.gcube.portlets.user.performfishanalytics.server.util;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
/**
* The Class GsonUtil.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 23, 2019
*/
public class GsonUtil {
public static final Logger log = LoggerFactory.getLogger(GsonUtil.class);
/**
* To map.
*
* @param json the json
* @return the map
*/
public static Map<String, String> toMap(String json){
log.debug("Converting JSON: "+json);
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(json, type);
log.debug("Converted as map: "+myMap);
//FOR GWT SERIALIZATION
Map<String,String> theGWTMap = new HashMap<String, String>(myMap.size());
theGWTMap.putAll(myMap);
return theGWTMap;
}
/**
* Checks if is valid json.
*
* @param json the json
* @return true, if is valid json
*/
public static boolean isValidJson(String json){
try{
JsonParser parser = new JsonParser();
parser.parse(json);
log.debug("The input json "+json+" is valid");
return true;
}catch(Exception e){
log.error("The input json "+json+" is not valid");
return false;
}
}
}

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

Loading…
Cancel
Save