commit 0caf09e0e26cb25ae59b77e1955f49a5dc3de216 Author: Francesco Mangiacrapa Date: Wed Mar 6 10:55:10 2019 +0000 copied from private git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/user/performfish-analytics-portlet@178488 82a268e6-3cf1-43bd-a215-b396298e98cf diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..cc0364b --- /dev/null +++ b/.classpath @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..8771b7a --- /dev/null +++ b/.project @@ -0,0 +1,53 @@ + + + performfish-analytics-portlet + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + com.google.gdt.eclipse.core.webAppProjectValidator + + + + + com.google.gwt.eclipse.core.gwtProjectValidator + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + com.google.gwt.eclipse.core.gwtNature + + diff --git a/.settings/.jsdtscope b/.settings/.jsdtscope new file mode 100644 index 0000000..b72a6a4 --- /dev/null +++ b/.settings/.jsdtscope @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/.settings/com.google.appengine.eclipse.core.prefs b/.settings/com.google.appengine.eclipse.core.prefs new file mode 100644 index 0000000..82c36af --- /dev/null +++ b/.settings/com.google.appengine.eclipse.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +filesCopiedToWebInfLib= diff --git a/.settings/com.google.gdt.eclipse.core.prefs b/.settings/com.google.gdt.eclipse.core.prefs new file mode 100644 index 0000000..c1b9544 --- /dev/null +++ b/.settings/com.google.gdt.eclipse.core.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +jarsExcludedFromWebInfLib= +lastWarOutDir=/home/francesco-mangiacrapa/wseclipseluna/performfish-analytics-portlet/target +warSrcDir=src/main/webapp +warSrcDirIsOutput=false diff --git a/.settings/com.google.gwt.eclipse.core.prefs b/.settings/com.google.gwt.eclipse.core.prefs new file mode 100644 index 0000000..f23a752 --- /dev/null +++ b/.settings/com.google.gwt.eclipse.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +entryPointModules= diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..29abf99 --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -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/=UTF-8 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..443e085 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -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 diff --git a/.settings/org.eclipse.jpt.core.prefs b/.settings/org.eclipse.jpt.core.prefs new file mode 100644 index 0000000..6caac22 --- /dev/null +++ b/.settings/org.eclipse.jpt.core.prefs @@ -0,0 +1,3 @@ +eclipse.preferences.version=1 +org.eclipse.jpt.core.platform=eclipselink2_4 +org.eclipse.jpt.jpa.core.discoverAnnotatedClasses=true diff --git a/.settings/org.eclipse.jst.jsp.core.prefs b/.settings/org.eclipse.jst.jsp.core.prefs new file mode 100644 index 0000000..3a5c98d --- /dev/null +++ b/.settings/org.eclipse.jst.jsp.core.prefs @@ -0,0 +1,3 @@ +eclipse.preferences.version=1 +validateFragments=false +validation.use-project-settings=true diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..8eb97c6 --- /dev/null +++ b/.settings/org.eclipse.wst.common.component @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/.settings/org.eclipse.wst.common.project.facet.core.prefs.xml b/.settings/org.eclipse.wst.common.project.facet.core.prefs.xml new file mode 100644 index 0000000..7961132 --- /dev/null +++ b/.settings/org.eclipse.wst.common.project.facet.core.prefs.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/.settings/org.eclipse.wst.common.project.facet.core.xml b/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..ba1ece6 --- /dev/null +++ b/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.container b/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.name b/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/.settings/org.eclipse.wst.validation.prefs b/.settings/org.eclipse.wst.validation.prefs new file mode 100644 index 0000000..04cad8c --- /dev/null +++ b/.settings/org.eclipse.wst.validation.prefs @@ -0,0 +1,2 @@ +disabled=06target +eclipse.preferences.version=1 diff --git a/.tern-project b/.tern-project new file mode 100644 index 0000000..a185ba0 --- /dev/null +++ b/.tern-project @@ -0,0 +1 @@ +{"ide":{"scriptPaths":[]},"plugins":{"aui":{},"liferay":{},"yui":{}},"libs":["ecma5","browser"]} \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..6a989bb --- /dev/null +++ b/pom.xml @@ -0,0 +1,335 @@ + + 4.0.0 + + maven-parent + org.gcube.tools + 1.0.0 + + + + org.gcube.portlets.user + performfish-analytics-portlet + war + 0.0.1-SNAPSHOT + Maven Archetype for GWT + + + scm:svn:http://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/admin/${project.artifactId} + scm:https://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/admin/${project.artifactId} + http://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/admin/${project.artifactId} + + + + 2.7.0 + distro + + 1.7 + 1.8 + ${project.build.directory}/${project.build.finalName} + -Xdoclint:none + UTF-8 + UTF-8 + + + + + + eclipselink + http://maven.research-infrastructures.eu:8081/nexus/content/repositories/eclipselink/ + + + + + + + org.gcube.distribution + maven-portal-bom + LATEST + pom + import + + + + + + + + + + com.google.gwt + gwt-user + ${gwt.version} + provided + + + + com.google.gwt + gwt-dev + ${gwt.version} + provided + + + + com.google.gwt + gwt-servlet + ${gwt.version} + provided + + + + org.eclipse.persistence + eclipselink + 2.6.6 + compile + + + + com.google.code.gson + gson + 2.8.5 + compile + + + + commons-httpclient + commons-httpclient + compile + + + + + + + + + + org.apache.commons + commons-compress + 1.17 + + + + + + com.h2database + h2 + 1.3.170 + compile + + + + com.github.gwtbootstrap + gwt-bootstrap + 2.3.2.0 + compile + + + + org.gcube.common + authorization-client + + + org.gcube.common + common-authorization + + + + org.projectlombok + lombok + 1.14.8 + + + + + org.gcube.resources.discovery + ic-client + compile + + + + org.gcube.core + common-scope-maps + compile + + + + + commons-io + commons-io + compile + + + + org.gcube.core + common-encryption + compile + + + + org.gcube.portal + custom-portal-handler + compile + + + + org.gcube.portal + client-context-library + [1.0.0-SNAPSHOT,) + compile + + + + + org.gcube.common.portal + portal-manager + provided + + + + + org.gcube.dvos + usermanagement-core + provided + + + + + + log4j + log4j + provided + + + org.slf4j + slf4j-log4j12 + compile + + + org.slf4j + slf4j-api + compile + + + + com.liferay.portal + portal-service + provided + + + javax.portlet + portlet-api + provided + + + + junit + junit + 4.11 + test + + + + + + ${webappDirectory}/WEB-INF/classes + + + + + + org.codehaus.mojo + gwt-maven-plugin + ${gwt.version} + + + + compile + + + + + + + PerformFishAnalytics.html + ${webappDirectory} + + + + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + + compile + + exploded + + + + + ${webappDirectory} + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + org.apache.maven.plugins + maven-assembly-plugin + 2.2 + + + ${distroDirectory}/descriptor.xml + + + + + servicearchive + install + + single + + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.5 + + + copy-profile + install + + copy-resources + + + target + + + ${distroDirectory} + true + + profile.xml + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/PerformFishAnalytics.gwt.xml b/src/main/java/org/gcube/portlets/user/performfishanalytics/PerformFishAnalytics.gwt.xml new file mode 100644 index 0000000..5fe5123 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/PerformFishAnalytics.gwt.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/DataMinerAlgorithms.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/DataMinerAlgorithms.java new file mode 100644 index 0000000..43a16d7 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/DataMinerAlgorithms.java @@ -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; + } + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/PerformFishAnalytics.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/PerformFishAnalytics.java new file mode 100644 index 0000000..6883abe --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/PerformFishAnalytics.java @@ -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 onModuleLoad(). + */ +public class PerformFishAnalytics implements EntryPoint { + + /** + * This is the entry point method. + */ + public void onModuleLoad() { + + new PerformFishAnalyticsController(); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/PerformFishAnalyticsConstant.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/PerformFishAnalyticsConstant.java new file mode 100644 index 0000000..fb1a77f --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/PerformFishAnalyticsConstant.java @@ -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}; + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/PerformFishAnalyticsService.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/PerformFishAnalyticsService.java new file mode 100644 index 0000000..e1c0a72 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/PerformFishAnalyticsService.java @@ -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 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> mapParameters) throws Exception; + + DataMinerResponse callingDataMinerPerformFishCorrelationAnalysis( + PerformFishResponse result, Map> 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> mapParameters) + throws Exception; + + /** + * @param farmID + * @return + * @throws Exception + */ + boolean checkGrantToAccessFarmID(String farmID) + throws Exception; +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/PerformFishAnalyticsServiceAsync.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/PerformFishAnalyticsServiceAsync.java new file mode 100644 index 0000000..64485d7 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/PerformFishAnalyticsServiceAsync.java @@ -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> callback); + + + void getPopulationTypeWithListKPI( + String populationTypeId, AsyncCallback callback); + + + void decryptAndValidParameters( + PerformFishInitParameter initParams, + AsyncCallback callback); + + + void submitRequestToPerformFishService( + Map> mapParameters, + AsyncCallback callback); + + + void callingDataMinerPerformFishCorrelationAnalysis( + PerformFishResponse result, Map> mapParameters, + AsyncCallback callback); + + + void getImageFile(OutputFile file, AsyncCallback callback); + + + void readCSVFile(String URL, AsyncCallback callback); + + void getCSVFile( + OutputFile file, boolean deleteAfter, AsyncCallback callback); + + + void callingDataMinerPerformFishAnalysis( + Map> mapParameters, + AsyncCallback callback); + + + void checkGrantToAccessFarmID(String farmID, AsyncCallback callback); +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/controllers/PerformFishAnalyticsController.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/controllers/PerformFishAnalyticsController.java new file mode 100644 index 0000000..9ffe928 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/controllers/PerformFishAnalyticsController.java @@ -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() { + + @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> mapParameters = new HashMap>(); + + String farmId = decryptParameters.getParameters().get(PerformFishAnalyticsConstant.FARMID_PARAM); + String batchType = viewController.getForm().getBatchType(); + String species = viewController.getForm().getSpecies(); + List listArea = viewController.getForm().getArea(); + List listPeriod = viewController.getForm().getPeriod(); + List 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() { + + @Override + public void onFailure(Throwable caught) { + modal.hide(); + Window.alert(caught.getMessage()); + // Map map = new HashMap(); + // 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 map = new HashMap(); + // 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 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> 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> mapParameters = new HashMap>(); + + 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() { + + @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 inputKPI, final List outputKPI){ + + List 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 inputKPI, final List 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> mapParameters = new HashMap>(); + 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() { + + @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 inputKPIs, List 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() { + + @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
"; + title += "Blue dots indicate the selected batch(es): "+focusID; + break; + case CORRELATION: + break; + case DEA_ANALYSIS: + break; + case SCATTER: + break; + case SPEEDOMETER: + title = "Speedometer
"; + title+= "Selected BATCH ID: "+focusID+"
"; + 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() { + + @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; + } + + } + + } + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/controllers/PerformFishAnalyticsViewController.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/controllers/PerformFishAnalyticsViewController.java new file mode 100644 index 0000000..9bd1f6c --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/controllers/PerformFishAnalyticsViewController.java @@ -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>() { + + @Override + public void onSuccess(List 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() { + + @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> 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> getRequestMapParameters() { + + return batchIDAndListKPI.getMapParameters(); + } + + + /** + * Validate kpi fields. + * + * @return true, if successful + */ + public boolean validateKPIFields() { + + bodyPage.hideError(); + List 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 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 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 getSelectedBatchID() { + + return batchIDAndListKPI.getSelectedBatchID(); + + } + + + /** + * Gets the list batches id. + * + * @return the list batches id + */ + public List getListBatchesID() { + + return batchIDAndListKPI.getAllBatchesID(); + } + + + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/dialog/DialogConfirm.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/dialog/DialogConfirm.java new file mode 100644 index 0000000..d61e53c --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/dialog/DialogConfirm.java @@ -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; + } +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/dialog/DialogResult.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/dialog/DialogResult.java new file mode 100644 index 0000000..dfc9ce9 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/dialog/DialogResult.java @@ -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); + } +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/dialog/PanelConfirmBuilder.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/dialog/PanelConfirmBuilder.java new file mode 100644 index 0000000..d8c8983 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/dialog/PanelConfirmBuilder.java @@ -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; + } +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/AddedBatchIdEvent.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/AddedBatchIdEvent.java new file mode 100644 index 0000000..4ec5e88 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/AddedBatchIdEvent.java @@ -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 { + public static Type TYPE = new Type(); + + + /** + * Instantiates a new added batch id event. + */ + public AddedBatchIdEvent() { + + } + + /* (non-Javadoc) + * @see com.google.gwt.event.shared.GwtEvent#getAssociatedType() + */ + @Override + public Type 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); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/AddedBatchIdEventHandler.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/AddedBatchIdEventHandler.java new file mode 100644 index 0000000..d520d74 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/AddedBatchIdEventHandler.java @@ -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); +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/CallAlgorithmEvent.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/CallAlgorithmEvent.java new file mode 100644 index 0000000..a41ce5a --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/CallAlgorithmEvent.java @@ -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 { + public static Type TYPE = new Type(); + private DataMinerAlgorithms algorithm; + private String focusID; + private List inputKPI; + private List 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 inputKPI, final List 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 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 getInputKPI() { + + return inputKPI; + } + + + /** + * @return the outputKPI + */ + public List getOutputKPI() { + + return outputKPI; + } + + + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/CallAlgorithmEventHandler.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/CallAlgorithmEventHandler.java new file mode 100644 index 0000000..4ed9c3a --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/CallAlgorithmEventHandler.java @@ -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); +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/LoadPopulationTypeEvent.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/LoadPopulationTypeEvent.java new file mode 100644 index 0000000..dd8fa55 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/LoadPopulationTypeEvent.java @@ -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 { + public static Type TYPE = new Type(); + 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 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; + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/LoadPopulationTypeEventHandler.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/LoadPopulationTypeEventHandler.java new file mode 100644 index 0000000..dbdc8bd --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/LoadPopulationTypeEventHandler.java @@ -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); +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/PerformFishFieldFormChangedEvent.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/PerformFishFieldFormChangedEvent.java new file mode 100644 index 0000000..bd28544 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/PerformFishFieldFormChangedEvent.java @@ -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 { + public static Type TYPE = new Type(); + + 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 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; + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/PerformFishFieldFormChangedEventHandler.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/PerformFishFieldFormChangedEventHandler.java new file mode 100644 index 0000000..70fbea0 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/PerformFishFieldFormChangedEventHandler.java @@ -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); +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SelectedKPIEvent.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SelectedKPIEvent.java new file mode 100644 index 0000000..8671de8 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SelectedKPIEvent.java @@ -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 { + public static Type TYPE = new Type(); + 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 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; + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SelectedKPIEventHandler.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SelectedKPIEventHandler.java new file mode 100644 index 0000000..c56765e --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SelectedKPIEventHandler.java @@ -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); +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SelectedPopulationTypeEvent.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SelectedPopulationTypeEvent.java new file mode 100644 index 0000000..4d60449 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SelectedPopulationTypeEvent.java @@ -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 { + public static Type TYPE = new Type(); + 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 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; + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SelectedPopulationTypeEventHandler.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SelectedPopulationTypeEventHandler.java new file mode 100644 index 0000000..142f803 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SelectedPopulationTypeEventHandler.java @@ -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); +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SubmitRequestEvent.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SubmitRequestEvent.java new file mode 100644 index 0000000..0ad6383 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SubmitRequestEvent.java @@ -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 { + public static Type TYPE = new Type(); + 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 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; + } + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SubmitRequestEventHandler.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SubmitRequestEventHandler.java new file mode 100644 index 0000000..ece1e6e --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/event/SubmitRequestEventHandler.java @@ -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); +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/Icons.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/Icons.java new file mode 100644 index 0000000..4def083 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/Icons.java @@ -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(); +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/download.png b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/download.png new file mode 100644 index 0000000..aef1826 Binary files /dev/null and b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/download.png differ diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/github.png b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/github.png new file mode 100644 index 0000000..718712c Binary files /dev/null and b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/github.png differ diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/javadoc.png b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/javadoc.png new file mode 100644 index 0000000..0dbffcf Binary files /dev/null and b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/javadoc.png differ diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/loading.gif b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/loading.gif new file mode 100644 index 0000000..9cb298e Binary files /dev/null and b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/loading.gif differ diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/loading2.gif b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/loading2.gif new file mode 100644 index 0000000..06bff8b Binary files /dev/null and b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/loading2.gif differ diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/loading3.gif b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/loading3.gif new file mode 100644 index 0000000..27f0eee Binary files /dev/null and b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/loading3.gif differ diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/loading4.gif b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/loading4.gif new file mode 100644 index 0000000..be36c0a Binary files /dev/null and b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/loading4.gif differ diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/maven.png b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/maven.png new file mode 100644 index 0000000..a659f45 Binary files /dev/null and b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/maven.png differ diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/top.png b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/top.png new file mode 100644 index 0000000..3de9a44 Binary files /dev/null and b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/top.png differ diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/wiki.png b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/wiki.png new file mode 100644 index 0000000..44ed899 Binary files /dev/null and b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/resources/wiki.png differ diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/BaseDockLayoutPanel.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/BaseDockLayoutPanel.java new file mode 100644 index 0000000..4e2ba86 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/BaseDockLayoutPanel.java @@ -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"); + + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/BodyPanel.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/BodyPanel.java new file mode 100644 index 0000000..bad0254 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/BodyPanel.java @@ -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 = "
"; + if(txt!=null && txt.length()>0) + html+=txt; +// panel.add(new HTML(label)); + else + html+="No data"; +// panel.add(new HTML("No data")); + html+="
"; + + panel.add(new HTML(html)); + add(panel); + + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/CopyOfCustomTreeModel.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/CopyOfCustomTreeModel.java new file mode 100644 index 0000000..f893b6f --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/CopyOfCustomTreeModel.java @@ -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 kpis = new + // ArrayList(); + /** + * 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 populationTypeProvider = new ListDataProvider(); + private ListDataProvider kpiProvider = new ListDataProvider(); + private MultiSelectionModel multiSelectionModel = new MultiSelectionModel(kpiProvider); + private List> listKPIAdded = new ArrayList>(); + private Map mapCheckBoxCell = new HashMap(); + //private List> hasCells; + //private ListDataProvider kpiProvider; + //private Cell kpiCell; + + + // private ListDataProvider dataProvider = new ListDataProvider(); + /** + * 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 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 buildKPICell() { + + // Construct a composite cell for contacts that includes a checkbox. + ArrayList> hasCells = new ArrayList>(); + + HasCell checkBoxCell = new HasCell() { + + private ExtendedCheckboxCell cell = new ExtendedCheckboxCell(true, true); + + public Cell getCell() { + + return cell; + } + + public FieldUpdater getFieldUpdater() { + + return new FieldUpdater() { + + @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() { + + private KPICell cell = new KPICell(null); + + public Cell getCell() { + + return cell; + } + + public FieldUpdater getFieldUpdater() { + + return null; + } + + public KPI getValue(KPI object) { + + return object; + } + }); + + CompositeCell kpiCell = new CompositeCell(hasCells) { + + @Override + public void render(Context context, KPI value, SafeHtmlBuilder sb) { + + if(value.isLeaf()){ + sb.appendHtmlConstant(""); + super.render(context, value, sb); + sb.appendHtmlConstant("
"); + }else{ + sb.appendHtmlConstant(""); + sb.appendHtmlConstant(value.getName()); + sb.appendHtmlConstant("
"); + } + } + + @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 void render( + Context context, KPI value, SafeHtmlBuilder sb, + HasCell hasCell) { + + Cell cell = hasCell.getCell(); + sb.appendHtmlConstant(""); + cell.render(context, hasCell.getValue(value), sb); + sb.appendHtmlConstant(""); + + } + }; + + 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 the generic type + * @param value the value + * @return the node info + */ + public 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 rootProvider = new ListDataProvider(); + rootProvider.getList().add(rootKPI); + Cell cell = new AbstractCell() { + + @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(rootProvider, cell); + } + else if (value instanceof PopulationType) { + // LEVEL 1. + // We want the children of PopulationType. Getting its list of KPI. + // List listOfKpi = ((PopulationType) value).getListKPI(); + GWT.log("PopulationType listOfKpi: " + populationTypeProvider.getList()); + //return new DefaultNodeInfo(populationTypeProvider, kpiCell, multiSelectionModel, null); + CompositeCell kpiCell = buildKPICell(); + listKPIAdded.add(kpiCell); + return new DefaultNodeInfo(populationTypeProvider, kpiCell); + + } + else if (value instanceof KPI) { + // LEVEL 2 - LEAF. + // We want the children of the KPI. Return them. + List listOfKpi = ((KPI) value).getListKPI(); + GWT.log("KPI type listOfKpi: " + listOfKpi.toString()); + ListDataProvider localProvider = new ListDataProvider(listOfKpi); + + kpiProvider.getList().addAll(listOfKpi); +// kpiProvider. +// multiSelectionModel. + CompositeCell kpiCell = buildKPICell(); + listKPIAdded.add(kpiCell); + return new DefaultNodeInfo(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; + } + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/Copy_2_of_CustomTreeModel.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/Copy_2_of_CustomTreeModel.java new file mode 100644 index 0000000..c6be7b1 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/Copy_2_of_CustomTreeModel.java @@ -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 kpis = new + // ArrayList(); + /** + * 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 multiSelectionModel = + new MultiSelectionModel(); + private ListDataProvider rootProvider = + new ListDataProvider(); + private ListDataProvider populationTypeProvider = + new ListDataProvider(); + private ListDataProvider kpiProvider = new ListDataProvider(); + + private Cell kpiCell; + + // private ListDataProvider dataProvider = new ListDataProvider(); + 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> hasCells = new ArrayList>(); + hasCells.add(new HasCell() { + + private CheckboxCell cell = new CheckboxCell(true, false); + + public Cell getCell() { + + return cell; + } + + public FieldUpdater getFieldUpdater() { + + return new FieldUpdater() { + + @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() { + + private KPICell cell = new KPICell(null); + + public Cell getCell() { + + return cell; + } + + public FieldUpdater getFieldUpdater() { + + return null; + } + + public KPI getValue(KPI object) { + + return object; + } + }); + + kpiCell = new CompositeCell(hasCells) { + + @Override + public void render(Context context, KPI value, SafeHtmlBuilder sb) { + + sb.appendHtmlConstant(""); + super.render(context, value, sb); + sb.appendHtmlConstant("
"); + + /*if(value.isLeaf()){ + sb.appendHtmlConstant(""); + //hasCells.get(0).getCell().render(context, value.getClass(), sb); + //super.render(context, value, sb); + sb.appendHtmlConstant("
"); + }else{ + sb.appendHtmlConstant(""); + //sb.appendHtmlConstant(value.getName()); + //superrender(context, value, sb); + sb.appendHtmlConstant("
"); + }*/ + } + + @Override + protected Element getContainerElement(Element parent) { + + // Return the first TR element in the table. + return parent.getFirstChildElement().getFirstChildElement().getFirstChildElement(); + } + + @Override + protected void render( + Context context, KPI value, SafeHtmlBuilder sb, + HasCell hasCell) { + + Cell cell = hasCell.getCell(); + sb.appendHtmlConstant(""); + cell.render(context, hasCell.getValue(value), sb); + sb.appendHtmlConstant(""); + } + }; + } + + 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 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 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 cell = new AbstractCell() { + + @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(rootProvider, cell); + } + else if (value instanceof PopulationType) { + // LEVEL 1. + // We want the children of PopulationType. Getting its list of KPI. + // List listOfKpi = ((PopulationType) value).getListKPI(); + GWT.log("PopulationType listOfKpi: " + populationTypeProvider.getList()); + // populationTypeProvider = new ListDataProvider(listOfKpi); +// Cell cell = new AbstractCell() { +// +// @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(populationTypeProvider, kpiCell); + } + else if (value instanceof KPI) { + // LEVEL 2 - LEAF. + // We want the children of the KPI. Return them. + List listOfKpi = ((KPI) value).getListKPI(); + if (listOfKpi != null) { + GWT.log("KPI type listOfKpi: " + listOfKpi.toString()); + kpiProvider = new ListDataProvider(((KPI) value).getListKPI()); +// Cell cell = new AbstractCell() { +// +// @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( + 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; + } + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/CustomTreeModel.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/CustomTreeModel.java new file mode 100644 index 0000000..5eb0af0 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/CustomTreeModel.java @@ -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 kpis = new + // ArrayList(); + /** + * 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 multiSelectionModel = new SingleSelectionModel(); + private ListDataProvider populationTypeProvider = new ListDataProvider(); + private Cell kpiCell; + + // private ListDataProvider dataProvider = new ListDataProvider(); + 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> hasCells = new ArrayList>(); + hasCells.add(new HasCell() { + + private CheckboxCell cell = new CheckboxCell(true, true); + + public Cell getCell() { + + return cell; + } + + public FieldUpdater getFieldUpdater() { + + return new FieldUpdater() { + + @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() { + + private KPICell cell = new KPICell(null); + + public Cell getCell() { + + return cell; + } + + public FieldUpdater getFieldUpdater() { + + return null; + } + + public KPI getValue(KPI object) { + + return object; + } + }); + + kpiCell = new CompositeCell(hasCells) { + + @Override + public void render(Context context, KPI value, SafeHtmlBuilder sb) { + + if(value.isLeaf()){ + sb.appendHtmlConstant(""); + super.render(context, value, sb); + sb.appendHtmlConstant("
"); + }else{ + sb.appendHtmlConstant(""); + sb.appendHtmlConstant(value.getName()); + sb.appendHtmlConstant("
"); + } + } + + @Override + protected Element getContainerElement(Element parent) { + + // Return the first TR element in the table. + return parent.getFirstChildElement().getFirstChildElement().getFirstChildElement(); + } + + @Override + protected void render( + Context context, KPI value, SafeHtmlBuilder sb, + HasCell hasCell) { + + Cell cell = hasCell.getCell(); + sb.appendHtmlConstant(""); + cell.render(context, hasCell.getValue(value), sb); + sb.appendHtmlConstant(""); + + } + }; + } + + 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 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 rootProvider = new ListDataProvider(); + rootProvider.getList().add(rootKPI); + Cell cell = new AbstractCell() { + + @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(rootProvider, cell); + } + else if (value instanceof PopulationType) { + // LEVEL 1. + // We want the children of PopulationType. Getting its list of KPI. + // List listOfKpi = ((PopulationType) value).getListKPI(); + //GWT.log("PopulationType listOfKpi: " + populationTypeProvider.getList()); + //return new DefaultNodeInfo(populationTypeProvider, kpiCell, multiSelectionModel, null); + return new DefaultNodeInfo(populationTypeProvider, kpiCell); + + } + else if (value instanceof KPI) { + // LEVEL 2 - LEAF. + // We want the children of the KPI. Return them. + List listOfKpi = ((KPI) value).getListKPI(); + //GWT.log("KPI type listOfKpi: " + listOfKpi.toString()); + ListDataProvider kpiProvider = new ListDataProvider(listOfKpi); + return new DefaultNodeInfo(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; + } + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/HeaderPanel.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/HeaderPanel.java new file mode 100644 index 0000000..3d1d8ee --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/HeaderPanel.java @@ -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"); + } + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/KPICell.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/KPICell.java new file mode 100644 index 0000000..9bc7d56 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/KPICell.java @@ -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 { + + /** + * 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(""); + // Add the contact image. + sb.appendHtmlConstant(""); + // sb.appendHtmlConstant(""); + // Add the name and address. + sb.appendHtmlConstant(""); + // sb.appendEscaped(value.getAddress()); + sb.appendHtmlConstant("
"); + // sb.appendHtmlConstant(imageHtml); + // sb.appendHtmlConstant(""); + sb.appendEscaped(value.getName()); + sb.appendHtmlConstant("
"); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/LoaderIcon.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/LoaderIcon.java new file mode 100644 index 0000000..de4e449 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/LoaderIcon.java @@ -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(""+txtHTML+""); + } + + /** + * Show. + * + * @param bool the bool + */ + public void show(boolean bool){ + this.setVisible(bool); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/totest/CellTreeExample.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/totest/CellTreeExample.java new file mode 100644 index 0000000..e9376c6 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/totest/CellTreeExample.java @@ -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 NodeInfo getNodeInfo(T value) { + /* + * Create some data in a data provider. Use the parent value as a prefix + * for the next level. + */ + ListDataProvider dataProvider = new ListDataProvider(); + 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(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); + } + } \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/totest/LeafCell.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/totest/LeafCell.java new file mode 100644 index 0000000..90aa464 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/totest/LeafCell.java @@ -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 { + + private final SingleSelectionModel multiSelectionModel = + new SingleSelectionModel(); + private List> hasCells; + + /** + * @param hasCells + */ + public LeafCell(List> hasCells) { + + super(hasCells); + this.hasCells = hasCells; + + hasCells.add(new HasCell() { + + private CheckboxCell cell = new CheckboxCell(true, true); + + public Cell getCell() { + + return cell; + } + + public FieldUpdater getFieldUpdater() { + + return new FieldUpdater() { + + @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() { + + private KPICell cell = new KPICell(null); + + public Cell getCell() { + + return cell; + } + + public FieldUpdater 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(""); + sb.appendHtmlConstant(value.getName()); + sb.appendHtmlConstant("
"); + } + + @Override + protected Element getContainerElement(Element parent) { + + // Return the first TR element in the table. + return parent.getFirstChildElement().getFirstChildElement().getFirstChildElement(); + } + + @Override + protected void render( + Context context, KPI value, SafeHtmlBuilder sb, HasCell hasCell) { + + Cell cell = hasCell.getCell(); + sb.appendHtmlConstant(""); + cell.render(context, hasCell.getValue(value), sb); + sb.appendHtmlConstant(""); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/totest/NewCustomTreeModel.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/totest/NewCustomTreeModel.java new file mode 100644 index 0000000..fb8536c --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/totest/NewCustomTreeModel.java @@ -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 populationTypeProvider = new ListDataProvider(); + + 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 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 dataProvider = new ListDataProvider(); + dataProvider.getList().add("KPIs"); + TextCell textCell = new TextCell(); + return new DefaultNodeInfo(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 dataProvider = new ListDataProvider(); +// dataProvider.getList().addAll(listOfKpi); + //List listOfKpi = ((PopulationType) value).getListKPI(); + KPICell kpi = new KPICell(null); + PopulationType populationType = (PopulationType) value; + GWT.log("populationType: "+populationType); + List listOfKpi = populationType.getListKPI(); + populationTypeProvider.getList().addAll(listOfKpi); + return new DefaultNodeInfo(populationTypeProvider, kpi); + + } + else if (value instanceof KPI) { + // LEVEL 2 - LEAF. + // We want the children of the KPI. Return them. + KPI kpiValue = (KPI) value; + List listOfKpi = kpiValue.getListKPI(); + //populationTypeProvider.getList().addAll(listOfKpi); + //GWT.log("KPI type listOfKpi: " + listOfKpi.toString()); + ListDataProvider kpiProvider = new ListDataProvider(listOfKpi); + AbstractCell cell = null; + if(kpiValue.isLeaf()){ + List> hasCells = new ArrayList>(); + cell = new LeafCell(hasCells); + }else{ + cell = new KPICell(null); + } + + return new DefaultNodeInfo(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; + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/totest/PopulationTypeCell.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/totest/PopulationTypeCell.java new file mode 100644 index 0000000..5490723 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/totest/PopulationTypeCell.java @@ -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 { + + /** + * 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(""); + // Add the contact image. + sb.appendHtmlConstant(""); + // sb.appendHtmlConstant(""); + // Add the name and address. + sb.appendHtmlConstant(""); + // sb.appendEscaped(value.getAddress()); + sb.appendHtmlConstant("
"); + // sb.appendHtmlConstant(imageHtml); + // sb.appendHtmlConstant(""); + sb.appendEscaped(value.getName()); + sb.appendHtmlConstant("
"); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/util/CorrelationValueToColourUtil.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/util/CorrelationValueToColourUtil.java new file mode 100644 index 0000000..e7913ca --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/util/CorrelationValueToColourUtil.java @@ -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 map = new HashMap(); + + private static String RED_RGB = "#FF442D"; + private static String LIGHT_BLUE_RGB = "#ADD8E6"; + private static String YELLOW_RGB = "#E6DF00"; + + public static Map 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; + } + + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/util/ExtendedCheckboxCell.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/util/ExtendedCheckboxCell.java new file mode 100644 index 0000000..5aa11ab --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/view/util/ExtendedCheckboxCell.java @@ -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 { + + /** + * An html string representation of a checked input box. + */ + private static final SafeHtml INPUT_CHECKED = SafeHtmlUtils.fromSafeConstant(""); + + /** + * An html string representation of an unchecked input box. + */ + private static final SafeHtml INPUT_UNCHECKED = SafeHtmlUtils.fromSafeConstant(""); + + 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 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); + } +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/AnalyticsPanelResult.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/AnalyticsPanelResult.java new file mode 100644 index 0000000..2aac04d --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/AnalyticsPanelResult.java @@ -0,0 +1,1000 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.client.viewbinder; + +import java.util.ArrayList; +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.PerformFishAnalyticsServiceAsync; +import org.gcube.portlets.user.performfishanalytics.client.controllers.PerformFishAnalyticsController; +import org.gcube.portlets.user.performfishanalytics.client.event.CallAlgorithmEvent; +import org.gcube.portlets.user.performfishanalytics.client.view.LoaderIcon; +import org.gcube.portlets.user.performfishanalytics.client.view.util.CorrelationValueToColourUtil; +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.csv.CSVRow; +import org.gcube.portlets.user.performfishanalytics.shared.dataminer.DataMinerResponse; + +import com.github.gwtbootstrap.client.ui.Alert; +import com.github.gwtbootstrap.client.ui.Button; +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.ButtonType; +import com.github.gwtbootstrap.client.ui.constants.ControlGroupType; +import com.github.gwtbootstrap.client.ui.constants.IconType; +import com.github.gwtbootstrap.client.ui.resources.ButtonSize; +import com.google.gwt.core.client.GWT; +import com.google.gwt.core.client.Scheduler; +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.logical.shared.AttachEvent; +import com.google.gwt.uibinder.client.UiBinder; +import com.google.gwt.uibinder.client.UiField; +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.FlexTable; +import com.google.gwt.user.client.ui.HTML; +import com.google.gwt.user.client.ui.HTMLPanel; +import com.google.gwt.user.client.ui.HorizontalPanel; +import com.google.gwt.user.client.ui.Label; +import com.google.gwt.user.client.ui.Panel; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; + + +/** + * The Class AnalyticsPanelResult. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 29, 2019 + */ +public class AnalyticsPanelResult extends Composite { + + /** + * + */ + + + private static AnalyticsPanelResultUiBinder uiBinder = + GWT.create(AnalyticsPanelResultUiBinder.class); + + /** + * The Interface AnalyticsPanelResultUiBinder. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 30, 2019 + */ + interface AnalyticsPanelResultUiBinder + extends UiBinder { + } + + @UiField + HTMLPanel field_html_panel; + + @UiField + VerticalPanel field_parameters_container; + + @UiField + VerticalPanel uib_vp_correlation_results_container; + + @UiField + VerticalPanel field_unary_algorithm_container; + + @UiField + VerticalPanel field_binary_algorithm; + + @UiField + VerticalPanel field_binary_algorithm_container; + + @UiField + VerticalPanel field_unary_algorithm; + + @UiField + ControlGroup cg_list_dea_input_kpi; + + @UiField + ControlGroup cg_list_dea_output_kpi; + + @UiField + ListBox list_dea_input_kpi; + + @UiField + ListBox list_dea_output_kpi; + + @UiField + Label uib_label_focus_id; + +// @UiField +// ControlGroup cg_focus_id_dea; + + @UiField + HorizontalPanel uib_vp_deanalanlysis_request_container; + + @UiField + ControlGroup cg_focus_id_correlation; + +// @UiField +// ListBox field_list_focus_id_dea; + + @UiField + VerticalPanel uib_vp_deanalanlysis_algorithm; + + @UiField + VerticalPanel uib_vp_deanalanlysis_algorithm_container; + + @UiField + ListBox field_list_focus_id_correlation; + + @UiField + Button button_dea_analys_request; + + @UiField + CheckBox uib_check_all_input_kpi; + + @UiField + CheckBox uib_check_all_output_kpi; + + private Map dataInputParameters; + + private DataMinerResponse dmResponse; + + private Map> kpiMapPointers = new HashMap>(); + + private List selectedKPIs; + + private List selectedAreas; + + /** + * 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: + * + * Hello! + * + * Note that depending on the widget that is used, it may be necessary to + * implement HasHTML instead of HasText. + */ + public AnalyticsPanelResult() { + + initWidget(uiBinder.createAndBindUi(this)); + + button_dea_analys_request.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + + cg_list_dea_input_kpi.setType(ControlGroupType.NONE); + cg_list_dea_output_kpi.setType(ControlGroupType.NONE); + + if(list_dea_input_kpi.getSelectedIndex()==-1){ + showAlert("You must select at least one Input KPI", AlertType.ERROR, true, uib_vp_deanalanlysis_request_container); + cg_list_dea_input_kpi.setType(ControlGroupType.ERROR); + return; + } + + if(list_dea_output_kpi.getSelectedIndex()==-1){ + showAlert("You must select at least one Output KPI", AlertType.ERROR, true, uib_vp_deanalanlysis_request_container); + cg_list_dea_output_kpi.setType(ControlGroupType.ERROR); + return; + } + + List inputKPINames = getSelected(list_dea_input_kpi); + List outputKPINames = getSelected(list_dea_output_kpi); + callDeaAnalysis(inputKPINames, outputKPINames, button_dea_analys_request); + } + }); + + uib_check_all_input_kpi.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + + boolean isChecked = uib_check_all_input_kpi.getValue(); + selectAllFields(list_dea_input_kpi, isChecked); + } + }); + + uib_check_all_output_kpi.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + + boolean isChecked = uib_check_all_output_kpi.getValue(); + selectAllFields(list_dea_output_kpi, 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 getSelected(ListBox listBox){ + List selected = new ArrayList(); + for (int i=0; i listAreas) { + + this.selectedAreas = listAreas; + + } + + + /** + * Gets the data miner response. + * + * @return the data miner response + */ + public DataMinerResponse getDataMinerResponse(){ + return dmResponse; + } + + + + /** + * Gets the data input parameters. + * + * @return the data input parameters + */ + public Map getDataInputParameters() { + + return dataInputParameters; + } + + /** + * 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){ + Alert alert = new Alert(error); + alert.setType(type); + alert.setClose(closable); + alert.getElement().getStyle().setMargin(10, Unit.PX); + panel.add(alert); + } + + + /** + * Adds the selected kp is. + * + * @param selectedKPIs the selected kp is + */ + public void addSelectedKPIs(List selectedKPIs) { + + this.selectedKPIs = selectedKPIs; + + } + + + /** + * Gets the KPI for name. + * + * @param name the name + * @return the KPI for name + */ + public KPI getKPIForName(String name){ + + System.out.println("Selected KPIs: "+selectedKPIs); + String purgedName = name.replaceAll("\\%", "").trim(); + for (KPI kpi : selectedKPIs) { + String purgedKPIName = kpi.getName().replaceAll("\\%", "").trim(); + if(purgedKPIName.compareToIgnoreCase(purgedName)==0) + return kpi; + } + + return null; + } + + /** + * Adds the parameters. + * + * @param keyToGet the key to get + * @param parameters the parameters + * @param toShowBatchTypeValue label to show batch type value + */ + public void addParameters(String keyToGet, Map> parameters, String toShowBatchTypeValue) { + + + final FlexTable flexTable = new FlexTable(); + flexTable.setStyleName("colgrouptable"); + + try{ + List dataInputs = parameters.get(keyToGet); + + if(dataInputs==null || dataInputs.isEmpty()) + return; + + dataInputParameters = new HashMap(); + + String theDataInputs = dataInputs.get(0); + String[] splittedParams = theDataInputs.split(";"); + + for (String splitParam : splittedParams) { + try{ + String[] keyvalue = splitParam.split("="); + dataInputParameters.put(keyvalue[0], keyvalue[1]); + }catch(Exception e){ + + } + } + + flexTable.setWidget(0, 0, new HTML(dataInputParameters.get(PerformFishAnalyticsConstant.DM_SCALEP_PARAM))); + flexTable.setWidget(1, 0, new HTML(toShowBatchTypeValue)); + + String KPINames = ""; + for (KPI kpi: selectedKPIs) { + KPINames+=kpi.getName() +", "; + } + KPINames = KPINames.substring(0, KPINames.length()-2); + flexTable.setWidget(2,0, new HTML(KPINames)); + + fillDeaListBoxes(); + + //CHANGING LABEL TEXT TO SCAPE_PARAM + uib_label_focus_id.setText(dataInputParameters.get(PerformFishAnalyticsConstant.DM_SCALEP_PARAM) + " ID"); + + }catch(Exception e){ + //silent + } + + field_parameters_container.add(flexTable); + } + + + /** + * Fill dea list boxes. + */ + private void fillDeaListBoxes(){ + + for (KPI kpi: selectedKPIs) { + list_dea_input_kpi.addItem(kpi.getName()); + list_dea_output_kpi.addItem(kpi.getName()); + } + } + + + /** + * Adds the list batch ids. + * + * @param listBatchesID the list batches id + */ + public void addListBatchIds(List listBatchesID){ + for (String batchID : listBatchesID) { + field_list_focus_id_correlation.addItem(batchID, batchID); + } + } + + /** + * Adds the results. + * + * @param dmResponse the dm response + */ + public void addResults(DataMinerResponse dmResponse) { + this.dmResponse = dmResponse; + + for (final OutputFile outputFile : dmResponse.getListOutput()) { + + switch (outputFile.getDataType()) { + case IMAGE: + PerformFishAnalyticsServiceAsync.Util.getInstance().getImageFile(outputFile, new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + showAlert(caught.getMessage(), AlertType.ERROR, true, uib_vp_correlation_results_container); + + } + + @Override + public void onSuccess(String base64Content) { + ShowResult showResult = new ShowResult(outputFile.getName()); + showResult.showImage(base64Content); + uib_vp_correlation_results_container.add(showResult); + + } + }); + break; + case CSV: + + //CORRELATION MATRIX + PerformFishAnalyticsServiceAsync.Util.getInstance().getCSVFile(outputFile, true, new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + showAlert(caught.getMessage(), AlertType.ERROR, true, uib_vp_correlation_results_container); + + } + + @Override + public void onSuccess(CSVFile result) { + + GWT.log("Displaying: "+result); + HorizontalPanel hp = new HorizontalPanel(); + final FlexTable flexTable = new FlexTable(); + flexTable.setStyleName("fixedtable"); + flexTable.getElement().getStyle().setMarginBottom(10, Unit.PX); + + flexTable.setWidget(0, 0,new Label("")); + + CSVRow headerRow = result.getHeaderRow(); + //HEADER + for (int i=1; i 0 + }else{ + KPI columnKPI = getKPIForName(headerRow.getListValues().get(columnIndex)); + //Here the first index is the KPI name + KPI rowKPI = getKPIForName(row.getListValues().get(0)); + fillKPIReferenceForIndex(rowIndex, columnIndex, Arrays.asList(columnKPI, rowKPI)); + button.setText(" "); + button.setIcon(IconType.COMPASS); + button.setSize(ButtonSize.LARGE); + + button.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + + //callScatterAndDeaChart(rowIndex, columnIndex, button); + callScatter(rowIndex, columnIndex, button); + } + }); + } + + button.setType(ButtonType.LINK); + //APPLYING STYLE ONLY ON INTERNAL VALUES OF CSV + if(j>0) + button.getElement().getStyle().setColor("#000"); + + button.addAttachHandler(new AttachEvent.Handler() { + + @Override + public void onAttachOrDetach(AttachEvent event) { + if(theColor.startsWith("#")){ + GWT.log("Setting backgrounf color: "+theColor); + button.getElement().getParentElement().getStyle().setBackgroundColor(theColor); + } + } + }); + + flexTable.setWidget(rowIndex, j,button); + } + + } + + hp.add(flexTable); + + final FlexTable flexLegend = new FlexTable(); + flexLegend.setStyleName("simpletable"); + //flexLegend.getElement().getStyle().setBorderWidth(0, Unit.PX); + Map map = CorrelationValueToColourUtil.getMap(); + flexLegend.setWidget(0, 0, new Label("Legend")); + flexLegend.setWidget(0, 1, new HTML("")); + int i = 1; + for (String key : map.keySet()) { + final String rgbColor = map.get(key); + final HTML theLegendColor = new HTML(""); + flexLegend.setWidget(i, 0, theLegendColor); + flexLegend.setWidget(i, 1, new HTML(key)); + theLegendColor.addAttachHandler(new AttachEvent.Handler() { + + @Override + public void onAttachOrDetach(AttachEvent event) { + theLegendColor.getElement().getParentElement().getStyle().setBackgroundColor(rgbColor); + } + }); + + i++; + } + + flexLegend.getElement().getStyle().setMarginLeft(15, Unit.PX); + hp.add(flexLegend); + uib_vp_correlation_results_container.insert(hp,0); + } + }); + break; + + default: + break; + } + + } + } + + /** + * Fill kpi reference for index. + * + * @param rowIndex the row index + * @param columnIndex the column index + * @param listKPI the list kpi + */ + private void fillKPIReferenceForIndex(int rowIndex, int columnIndex, List listKPI){ + + String key = rowIndex+","+columnIndex; + kpiMapPointers.put(key, listKPI); + +// String kpiNames = ""; +// if(listKPI!=null && listKPI.size()>0){ +// for (KPI kpi : listKPI) { +// +// if(kpi!=null){ +// kpiNames+=" "+kpi.getName() +";"; +// }else +// GWT.log("KPI NULL for "+key); +// +// +// } +// GWT.log("FILLING kpiMapPointers with key: "+key +" and value: "+kpiNames); +// }else +// GWT.log("FILLING kpiMapPointers with key: "+key +" and value: "+listKPI); + + } + + /** + * Gets the KPI for indexes. + * + * @param rowIndex the row index + * @param columnIndex the column index + * @return the KPI for indexes + */ + public List getKPIForIndexes(int rowIndex, int columnIndex){ + String key = rowIndex+","+columnIndex; + return kpiMapPointers.get(key); + } + + + /** + * Call box plot and speedo meter. + * + * @param rowIndex the row index + * @param columnIndex the column index + * @param button the button + */ + private void callBoxPlotAndSpeedoMeter(int rowIndex, int columnIndex, Button button){ + + String focusID = checkValidFocusID(); + + if(focusID==null) + return; + + GWT.log("Called BoxPlotAndSpeedoMeter at rowIndex: "+rowIndex +", columnIndex: "+columnIndex); + HorizontalPanel hp = new HorizontalPanel(); + hp.getElement().addClassName("ext-horizontal-panel"); + HorizontalPanel boxPlot = new HorizontalPanel(); + HorizontalPanel speedometer = new HorizontalPanel(); + hp.add(boxPlot); + hp.add(speedometer); + //hp.getElement().addClassName("ext-horizontal-panel"); + field_unary_algorithm_container.add(hp); + //KPI selectKPI = getKPIForName(button.getText()); + List selectedKPI = getKPIForIndexes(rowIndex, columnIndex); + GWT.log("Selected KPI: "+selectedKPI); + field_unary_algorithm.setVisible(true); + callDataMinerServiceForChart(dataInputParameters, selectedKPI, null, DataMinerAlgorithms.BOXPLOT, focusID, boxPlot); + callDataMinerServiceForChart(dataInputParameters, selectedKPI, null, DataMinerAlgorithms.SPEEDOMETER, focusID, speedometer); + } + + + /** + * Check valid focus id. + * + * @return the FocusID if it is valid, null otherwise. + */ + public String checkValidFocusID(){ + + cg_focus_id_correlation.setType(ControlGroupType.NONE); + + //CHECK THE FOCUS ID VALUE + String focusID = field_list_focus_id_correlation.getSelectedItemText(); + + if(focusID==null || focusID.isEmpty()){ + + String msgError = "Could not execute a valid Analysis."; + + if(selectedAreas==null || selectedAreas.isEmpty()){ + msgError+=" Please select another parameters computation"; + }else{ + msgError+=" Select at least the Area of your FARM"; + } + + showAlert(msgError, AlertType.ERROR, true, uib_vp_correlation_results_container); + cg_focus_id_correlation.setType(ControlGroupType.ERROR); + return null; + } + + return focusID; + } + + + /** + * Call scatter and dea chart. + * + * @param rowIndex the row index + * @param columnIndex the column index + * @param button the button + */ + private void callScatterAndDeaChart(int rowIndex, int columnIndex, Button button){ + + String focusID = checkValidFocusID(); + + if(focusID==null) + return; + + GWT.log("Called ScatterAndDeaChart at rowIndex: "+rowIndex +", columnIndex: "+columnIndex); + HorizontalPanel hp = new HorizontalPanel(); + hp.getElement().addClassName("ext-horizontal-panel"); + HorizontalPanel scatter = new HorizontalPanel(); + HorizontalPanel deaChart = new HorizontalPanel(); + hp.add(scatter); + hp.add(deaChart); + //hp.getElement().addClassName("ext-horizontal-panel"); + field_binary_algorithm_container.add(hp); + List selectedKPI = getKPIForIndexes(rowIndex, columnIndex); + GWT.log("Selected KPI: "+selectedKPI); + field_binary_algorithm.setVisible(true); + callDataMinerServiceForChart(dataInputParameters, selectedKPI, null, DataMinerAlgorithms.SCATTER, focusID, scatter); + callDataMinerServiceForChart(dataInputParameters, selectedKPI, null, DataMinerAlgorithms.DEA_CHART, focusID, deaChart); + } + + + /** + * Call scatter. + * + * @param rowIndex the row index + * @param columnIndex the column index + * @param button the button + */ + private void callScatter(int rowIndex, int columnIndex, Button button){ + + String focusID = checkValidFocusID(); + + if(focusID==null) + return; + + GWT.log("Called ScatterChart at rowIndex: "+rowIndex +", columnIndex: "+columnIndex); + List selectedKPI = getKPIForIndexes(rowIndex, columnIndex); + GWT.log("Selected KPI: "+selectedKPI); + PerformFishAnalyticsController.eventBus.fireEvent(new CallAlgorithmEvent(DataMinerAlgorithms.SCATTER, focusID, selectedKPI, null)); + } + + + /** + * Call dea analysis. + * + * @param inputKPINames the input kpi names + * @param outputKPINames the output kpi names + * @param button the button + */ + private void callDeaAnalysis(List inputKPINames, List outputKPINames, Button button){ + + HorizontalPanel hp = new HorizontalPanel(); + hp.getElement().addClassName("ext-horizontal-panel"); + HorizontalPanel deaAnalysis = new HorizontalPanel(); + hp.add(deaAnalysis); + //hp.getElement().addClassName("ext-horizontal-panel"); + uib_vp_deanalanlysis_algorithm_container.add(hp); + + List inputKPI = new ArrayList(); + for (String kpiName : inputKPINames) { + inputKPI.add(getKPIForName(kpiName)); + } + + List outputKPI = new ArrayList(); + for (String kpiName : outputKPINames) { + outputKPI.add(getKPIForName(kpiName)); + } + + + GWT.log("Calling Dea Analysys... with input: "+inputKPI+" and output: "+outputKPI); + uib_vp_deanalanlysis_algorithm.setVisible(true); + callDataMinerServiceForChart(dataInputParameters, inputKPI, outputKPI, DataMinerAlgorithms.DEA_ANALYSIS, "ID", deaAnalysis); + } + + + /** + * 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 inputKPIs, List 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() { + + @Override + public void onFailure(Throwable caught) { + showAlert(caught.getMessage(), AlertType.ERROR, true, uib_vp_deanalanlysis_request_container); + + } + + @Override + public void onSuccess(String base64Content) { + + String title = toTitle; + switch (chartType) { + case BOXPLOT: + break; + case SPEEDOMETER: + title+= " "+uib_label_focus_id.getText()+": "+focusID; + break; + default: + break; + } + + + ShowResult showResult = new ShowResult(title); + showResult.showImage(base64Content); + container.add(showResult); + + } + }); + break; + case CSV: + PerformFishAnalyticsServiceAsync.Util.getInstance().getCSVFile(outputFile, true, new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + showAlert(caught.getMessage(), AlertType.ERROR, true, uib_vp_deanalanlysis_request_container); + } + + @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+= " "+uib_label_focus_id.getText()+": "+focusID; + break; + default: + break; + } + + ShowResult showResult = new ShowResult(title); + showResult.showCSVFile(result); + container.add(showResult); + } + }); + break; + + default: + break; + } + + } + + } + + /** + * Call data miner service for chart. + * + * @param dataInputParameters the data input parameters + * @param inputKPI the input kpi + * @param outputKPI the output kpi + * @param chartType the chart type + * @param focusID the focus id + * @param panel the panel + */ + private void callDataMinerServiceForChart(Map dataInputParameters, final List inputKPI, final List outputKPI, final DataMinerAlgorithms chartType, final String focusID, final ComplexPanel panel) { + + GWT.log("Call DM wiht Selected KPI: "+inputKPI); + StringBuilder dataInputsFormatter = new StringBuilder(); + String scalePValue = dataInputParameters.get(PerformFishAnalyticsConstant.DM_SCALEP_PARAM); + dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_SCALEP_PARAM+"="+scalePValue+";"); + dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_BATCHTYPE_PARAM+"="+dataInputParameters.get(PerformFishAnalyticsConstant.DM_BATCHTYPE_PARAM)+";"); + dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_CHARTTYPE_PARAM+"="+chartType+";"); + dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_FARMFILE_PARAM+"="+dataInputParameters.get(PerformFishAnalyticsConstant.DM_FARMFILE_PARAM)+";"); + + + 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+";"); + + } + + dataInputsFormatter.append(PerformFishAnalyticsConstant.DM_FOCUS_PARAM+"="+focusID+";"); + + String dataInParameters = dataInputsFormatter.toString(); + GWT.log("Calling DM service with client input parameters: "+dataInParameters); + + Map> mapParameters = new HashMap>(); + mapParameters.put(PerformFishAnalyticsConstant.DATA_INPUTS, Arrays.asList(dataInParameters)); + + final LoaderIcon loaderIcon = new LoaderIcon("Submitting request to "+chartType+" Analysis..."); + loaderIcon.setVisible(true); + panel.setVisible(true); + panel.add(loaderIcon); + Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { + @Override + public void execute() { + loaderIcon.setFocus(true); + }}); + + PerformFishAnalyticsServiceAsync.Util.getInstance().callingDataMinerPerformFishAnalysis(mapParameters, new AsyncCallback() { + + @Override + public void onSuccess(DataMinerResponse dmResponse) { + loaderIcon.setVisible(false); + //field_unary_algorithm.setVisible(true); + GWT.log("I'm displaying: "+dmResponse); + displayOutputFilesAsStaticEntities(dmResponse, chartType, inputKPI, outputKPI, focusID, panel, false); + } + + @Override + public void onFailure(Throwable caught) { + loaderIcon.setVisible(false); + displayOutputFilesAsStaticEntities(dmResponse, chartType, inputKPI, outputKPI, focusID, panel, true); + + } + }); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/AnalyticsPanelResult.ui.xml b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/AnalyticsPanelResult.ui.xml new file mode 100644 index 0000000..7f773b4 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/AnalyticsPanelResult.ui.xml @@ -0,0 +1,104 @@ + + + + .paddingLeft { + padding-left: 10px; + } + + + + + + + + + + + + + + Focus ID + + + + + + + + + + + + + + Input KPI + + + + + + + + + + + + Output + KPI + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/BatchIDAndListKPIView.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/BatchIDAndListKPIView.java new file mode 100644 index 0000000..cd2d4e0 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/BatchIDAndListKPIView.java @@ -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 { + } + + @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> mapParameters; + + + private List listBatchesID = new ArrayList(); + + + /** + * 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 getAllBatchesID(){ + return listBatchesID; + } + + + /** + * Gets the selected. + * + * @param listBox the list box + * @return the selected + */ + private List getSelected(ListBox listBox){ + + if(listBox==null) + listBox = uib_list_batch_id; + + List selected = new ArrayList(); + for (int i=0; i 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> 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() { + + @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 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> getMapParameters() { + + return mapParameters; + } + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/BatchIDAndListKPIView.ui.xml b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/BatchIDAndListKPIView.ui.xml new file mode 100644 index 0000000..f250ef4 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/BatchIDAndListKPIView.ui.xml @@ -0,0 +1,23 @@ + + + + + + + + + BATCH ID + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/PerformFishAnalitycsFormView.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/PerformFishAnalitycsFormView.java new file mode 100644 index 0000000..f4e7d38 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/PerformFishAnalitycsFormView.java @@ -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 { + } + /** 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> mapPopulation = + new HashMap>(); + private Map mapPopulationType = + new HashMap(); + + + /** + * 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 result, + Population population) { + + mapPopulation.put(populationName, result); + fillPopulationType(populationName, result, population); + } + + /** + * Fill species. + * + * @param listSpecies + * the list species + */ + private void fillSpecies(List 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 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 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 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 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 getQuarter(){ + return getSelected(field_select_quarter); + } + + /** + * Gets the area. + * + * @return the area + */ + public List getArea(){ + return getSelected(field_select_area); + } + + /** + * Gets the period. + * + * @return the period + */ + public List getPeriod(){ + return getSelected(field_select_period); + } + + + /** + * Gets the selected. + * + * @param listBox the list box + * @return the selected + */ + private List getSelected(ListBox listBox){ + List selected = new ArrayList(); + for (int i=0; i + + + .noBorder { + border: 0px; + } + + .marginToError { + margin-left: 180px; + } + + + + + + + + + + Batch Type + + + + + + + + Level + + + + + + + + Species + + + + + + + + Quarter + + + + + + + + + + + + + Area + + + + + + + + + + + + + + Period + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/PortletTitle.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/PortletTitle.java new file mode 100644 index 0000000..d8e00a5 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/PortletTitle.java @@ -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 { + } + + /** + * 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: + * Hello! 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) { + + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/PortletTitle.ui.xml b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/PortletTitle.ui.xml new file mode 100644 index 0000000..90bbb20 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/PortletTitle.ui.xml @@ -0,0 +1,18 @@ + + + + .pageHeaderStyle { + border: 0px; + padding-bottom: 9px; + margin: 20px 0 30px; + border-bottom: 1px solid #eee; + font-size: 20px; + font-weight: bold; + margin: 20px; + } + + + + + \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/RecapSubmitPage.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/RecapSubmitPage.java new file mode 100644 index 0000000..5da7ba4 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/RecapSubmitPage.java @@ -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 mapSelected = new HashMap(); + private HashMap mapLabel = new HashMap(); + + /** + * The Interface RecapSubmitPageUiBinder. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 22, 2019 + */ + interface RecapSubmitPageUiBinder extends UiBinder { + } + + /** + * 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: + * + * Hello! + * + * 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 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 getSelectedKPIs(){ + + errorPanelSubmit.clear(); + + List selectedKPI = new ArrayList(); + Set 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); + } + + + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/RecapSubmitPage.ui.xml b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/RecapSubmitPage.ui.xml new file mode 100644 index 0000000..75706ea --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/RecapSubmitPage.ui.xml @@ -0,0 +1,29 @@ + + + + /* Add CSS here. See the GWT docs on UI Binder for more details */ + .thetitle { + font-weight: bold; + font-size: 18px; + } + .theMarginTop50 { + margin-top: 50px; + } + + + + + Selected KPIs + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/ShowResult.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/ShowResult.java new file mode 100644 index 0000000..2468620 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/ShowResult.java @@ -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 { + } + + @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 + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/SubmitRequestPanel.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/SubmitRequestPanel.java new file mode 100644 index 0000000..c900f1b --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/SubmitRequestPanel.java @@ -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 { + } + + @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: + * + * Hello! + * + * 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); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/SubmitRequestPanel.ui.xml b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/SubmitRequestPanel.ui.xml new file mode 100644 index 0000000..b15f71f --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/SubmitRequestPanel.ui.xml @@ -0,0 +1,16 @@ + + + + /* Add CSS here. See the GWT docs on UI Binder for more details */ + .important { + font-weight: bold; + } + + + + + + + + \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/TabPanelView.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/TabPanelView.java new file mode 100644 index 0000000..26136d1 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/TabPanelView.java @@ -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 { + } + + @UiField + Tab field_create_analytics_request; + + @UiField + TabPanel field_base_tabpanel; + + + private List results = new ArrayList(); + + + /** + * 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: + * + * Hello! + * + * 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 + } + + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/TabPanelView.ui.xml b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/TabPanelView.ui.xml new file mode 100644 index 0000000..c85eee0 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/client/viewbinder/TabPanelView.ui.xml @@ -0,0 +1,15 @@ + + + + /* Add CSS here. See the GWT docs on UI Binder for more details */ + .background-tab { + background-color: #E5E5E5; + } + + + + + + \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/portlet/PerformFishAnalyticsPortlet.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/portlet/PerformFishAnalyticsPortlet.java new file mode 100644 index 0000000..685be10 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/portlet/PerformFishAnalyticsPortlet.java @@ -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); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/PerformFishAnalyticsServiceImpl.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/PerformFishAnalyticsServiceImpl.java new file mode 100644 index 0000000..5f7f6bf --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/PerformFishAnalyticsServiceImpl.java @@ -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 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 builderPopulation = + new GenericPersistenceDaoBuilder( + dbFactory, Population.class.getSimpleName()); + List listPopulation = builderPopulation.getPersistenceEntity().getList(); + List 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 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(); + }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 builderPopulationType = + new GenericPersistenceDaoBuilder( + dbFactory, PopulationType.class.getSimpleName()); + + Map filterMap = new HashMap(); + filterMap.put("id",populationTypeId); + List 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 listGWTKPI = new ArrayList(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 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 listKPI = new ArrayList(); + 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 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 inputParameters = initParams.getParameters(); + + try{ + log.info("Decrypting init parameters: "+inputParameters); + Set 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> 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 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> 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()> dmRequestParameters = new HashMap>(); + 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 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 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> mapParameters) throws Exception{ + + log.info("Calling the DM service with client parameters: "+mapParameters.toString()); + + PortalContextInfo pContext = ContextUtil.getPortalContext(this.getThreadLocalRequest()); + + Map> dmRequestParameters = new HashMap>(); + 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 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 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 manageOutputsForPerformFishAnalysis(List output) { + + OutputFile theOutputFile = null; + try { + + Map> theLegendMap = new HashMap>(); + + 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 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> 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 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 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(""); + + return ""; + }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 + } + } + } + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/ToAvoidIndirectSerialization.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/ToAvoidIndirectSerialization.java new file mode 100644 index 0000000..f2a0b23 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/ToAvoidIndirectSerialization.java @@ -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 toGWTSerializable(List listPopulationType, Population population, boolean fetchProperties){ + + if(listPopulationType==null) + return new ArrayList(1); + + List gwtSerializableList = new ArrayList(listPopulationType.size()); + for (PopulationType populationType : listPopulationType){ + log.trace("Converting Population Type: "+populationType); + + if(fetchProperties){ + + List listSpecies = populationType.getListSpecies(); + populationType.setListSpecies((List) toListPopulationProperties(listSpecies, null)); + + List listQuarter = populationType.getListQuarter(); + populationType.setListQuarter((List) toListPopulationProperties(listQuarter, null)); + + List listArea = populationType.getListArea(); + populationType.setListArea((List) toListPopulationProperties(listArea, null)); + + List listPeriod = populationType.getListPeriod(); + populationType.setListPeriod((List) 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 + */ + public static List setPopulationTypes(List 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 + */ + public static List toListPopulationProperties(List list, PopulationType type){ + + List listGWT = new ArrayList(); + for (PopulationTypeProperties populationTypeProperties : list) { + PopulationTypeProperties pop = toPopulationProperties(populationTypeProperties, type); + listGWT.add(pop); + } + + return listGWT; + + } + + /** + * To population properties. + * + * @param the generic type + * @param object the object + * @param type the type + * @return the t + */ + @SuppressWarnings("unchecked") + public static 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; + + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/database/EntityManagerFactoryCreator.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/database/EntityManagerFactoryCreator.java new file mode 100644 index 0000000..7e9dbbb --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/database/EntityManagerFactoryCreator.java @@ -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 properties = new HashMap(); + 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 properties = new HashMap(); + 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"); + + } + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/database/JavaPersistenceHandler.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/database/JavaPersistenceHandler.java new file mode 100644 index 0000000..6716a60 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/database/JavaPersistenceHandler.java @@ -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 the generic type + */ +public interface JavaPersistenceHandler { + + /** + * 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 executeCriteriaQuery(CriteriaQuery 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 executeTypedQuery(CriteriaQuery cq, int startIndex, + int offset) throws DatabaseServiceException; + + /** + * Root from. + * + * @param cq the cq + * @return the root + */ + public abstract Root rootFrom(CriteriaQuery cq); + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/persistence/AbstractPersistence.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/persistence/AbstractPersistence.java new file mode 100644 index 0000000..86cf477 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/persistence/AbstractPersistence.java @@ -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 the generic type + */ +public abstract class AbstractPersistence implements JavaPersistenceHandler{ + + 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 getList() throws DatabaseServiceException { + EntityManager em = createNewManager(); + List listT = new ArrayList(); + 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 executeCriteriaQuery(CriteriaQuery criteriaQuery) throws DatabaseServiceException{ + EntityManager em = createNewManager(); + List listOBJ = new ArrayList(); + 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 getList(Map filterMap, int startIndex, int offset) throws DatabaseServiceException{ + + EntityManager em = createNewManager(); + List listOBJ = new ArrayList(); + 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 rootFrom(CriteriaQuery 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 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 executeTypedQuery(CriteriaQuery 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; + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/persistence/GenericPersistence.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/persistence/GenericPersistence.java new file mode 100644 index 0000000..01f6a1c --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/persistence/GenericPersistence.java @@ -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 the generic type + */ +public class GenericPersistence extends AbstractPersistence{ + + /** + * 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; + } + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/persistence/GenericPersistenceDaoBuilder.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/persistence/GenericPersistenceDaoBuilder.java new file mode 100644 index 0000000..4a261ce --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/persistence/GenericPersistenceDaoBuilder.java @@ -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 { + + public static Logger logger = LoggerFactory.getLogger(GenericPersistenceDaoBuilder.class); + + private EntityManagerFactory factory; + private String tableName; + private GenericPersistence 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(factory, tableName); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/persistence/PopulationEntityListener.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/persistence/PopulationEntityListener.java new file mode 100644 index 0000000..5c1e6d9 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/persistence/PopulationEntityListener.java @@ -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 addPackageEntityListener 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){ + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/ContextUtil.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/ContextUtil.java new file mode 100644 index 0000000..fa00ec0 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/ContextUtil.java @@ -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; + + } + + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/DataMinerUtil.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/DataMinerUtil.java new file mode 100644 index 0000000..0d7121b --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/DataMinerUtil.java @@ -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 listResponse = WPSParserUtil.getListDataMinerOutputDataFromWPSResponse(doc); + return new DMServiceResponse(false, httpRequestURL, xml, listResponse); + } + + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/DatabaseUtil.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/DatabaseUtil.java new file mode 100644 index 0000000..5af1997 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/DatabaseUtil.java @@ -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 builderPopulation = + new GenericPersistenceDaoBuilder( + dbFactory, Population.class.getSimpleName()); + List 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"); + } + + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/FileUtil.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/FileUtil.java new file mode 100644 index 0000000..ab219d9 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/FileUtil.java @@ -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 entries = Files.newDirectoryStream(path)) { + for (Path entry : entries) { + deleteDirectoryRecursion(entry); + } + } + } + log.info("Deleting File/Directory: %s", path.getFileName()); + Files.delete(path); + + + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/GcoreEndpointReader.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/GcoreEndpointReader.java new file mode 100644 index 0000000..92a89b2 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/GcoreEndpointReader.java @@ -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 client = client(); + List 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 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(); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/GsonUtil.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/GsonUtil.java new file mode 100644 index 0000000..a3eeba9 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/GsonUtil.java @@ -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 toMap(String json){ + log.debug("Converting JSON: "+json); + Gson gson = new Gson(); + Type type = new TypeToken>(){}.getType(); + Map myMap = gson.fromJson(json, type); + log.debug("Converted as map: "+myMap); + //FOR GWT SERIALIZATION + Map theGWTMap = new HashMap(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; + } + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/HttpCallerUtil.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/HttpCallerUtil.java new file mode 100644 index 0000000..674e6e8 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/HttpCallerUtil.java @@ -0,0 +1,335 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import org.apache.commons.httpclient.Credentials; +import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; +import org.apache.commons.httpclient.UsernamePasswordCredentials; +import org.apache.commons.httpclient.auth.AuthScope; +import org.apache.commons.httpclient.methods.ByteArrayRequestEntity; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.params.HttpMethodParams; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * The Class HttpCallerUtil. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 23, 2019 + */ +public class HttpCallerUtil { + + public static final Logger log = LoggerFactory.getLogger(HttpCallerUtil.class); + + public static final int TIME_OUT_REQUESTS = 5*60*1000; //5minutes + + private String serviceURL = ""; + private HttpClient httpClient = null; + private String username = ""; + private String password = ""; + private int statusCode; + private boolean callError = false; + private String fullUrl; + + + /** + * Instantiates a new http caller util. + * + * @param httpRequestURL the http request url + * @param user the user + * @param password the password + */ + public HttpCallerUtil(String httpRequestURL, String user, String password) { + this.serviceURL = httpRequestURL; + this.username = user; + this.password = password; + MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); + connectionManager.getParams().setSoTimeout(TIME_OUT_REQUESTS); + this.httpClient = new HttpClient(connectionManager); + + if(username!=null && password!=null){ + this.username = user; + this.password = password; + Credentials defaultcreds = new UsernamePasswordCredentials(user, password); + httpClient.getState().setCredentials(AuthScope.ANY, defaultcreds); + } + + } + + + /** + * Call get. + * + * @param urlMethod the url method + * @param parameters the parameters + * @param gcubeToken the gcube token + * @return the string + * @throws Exception the exception + */ + public String callGet(String urlMethod, Map> parameters, String gcubeToken) throws Exception { + + // Create an instance of HttpClient. + HttpClient client = new HttpClient(); + String query = parameters!=null && !parameters.isEmpty()?UrlEncoderUtil.encodeQuery(parameters):null; + this.fullUrl = serviceURL; + + if(urlMethod!=null) + this.fullUrl += "/"+urlMethod; + + if(query!=null) + this.fullUrl += "?"+query; + + log.info("call get .... " + fullUrl); + // Create a method instance. + GetMethod method = new GetMethod(fullUrl); + if(gcubeToken!=null) + method.addRequestHeader(new Header("gcube-token", gcubeToken)); + // Provide custom retry handler is necessary + method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); + + try { + // Execute the method. + statusCode = client.executeMethod(method); + log.info("Status code is: " + statusCode); + + if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) { + log.error("Method failed: " + method.getStatusLine()); + method.releaseConnection(); + throw new Exception("Method failed: " + method.getStatusLine()); + } + + // Read the response body. + byte[] responseBody = method.getResponseBody(); + // Deal with the response. + // Use caution: ensure correct character encoding and is not binary data + return new String(responseBody); + + } catch (HttpException e) { + log.error("Fatal protocol violation: " + e.getMessage()); + throw new Exception("Fatal protocol violation: " + e.getMessage()); + } catch (IOException e) { + log.error("Fatal transport error: " + e.getMessage()); + throw new Exception("Fatal transport violation: " + e.getMessage()); + } finally { + // Release the connection. + method.releaseConnection(); + } + } + + + /** + * Call post. + * + * @param urlMethod the url method + * @param body the body + * @param contentType the content type + * @return the string + * @throws Exception the exception + */ + public String callPost(String urlMethod, String body, String contentType) throws Exception { + + // Create a method instance. + PostMethod method = new PostMethod(this.serviceURL + "/" + urlMethod); + method.setRequestHeader("Content-type", contentType); + log.trace("call post .... " + this.serviceURL + "/" + urlMethod); + log.debug(" call post body.... " + body); + // System.out.println("post body .... " + body); + + method.setRequestEntity(new ByteArrayRequestEntity(body.getBytes())); + // Provide custom retry handler is necessary + // method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false)); + byte[] responseBody = null; + try { + // Execute the method. + int statusCode = httpClient.executeMethod(method); + + if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) { + log.error("Method failed: " + method.getStatusLine()+"; Response bpdy: "+method.getResponseBody()); + method.releaseConnection(); + throw new Exception("Method failed: " + method.getStatusLine()+"; Response body: "+new String(method.getResponseBody())); + } + // Read the response body. + responseBody = method.getResponseBody(); + } catch (HttpException e) { + log.error("Fatal protocol violation: ", e); + method.releaseConnection(); + throw new Exception("Fatal protocol violation: " + e.getMessage()); + } catch (Exception e) { + log.error("Fatal transport error: ", e); + method.releaseConnection(); + throw new Exception("Fatal transport error: " + e.getMessage()); + }finally{ + method.releaseConnection(); + } + + return new String(responseBody); + } + + + /** + * Perform get request with retry. + * + * @param mapParameters the map parameters + * @param gcubeToken the gcube token + * @param maxAttempts the max attempts. Maximun number of retry if the response is not OK (status 200) or ACCEPTED (status 202) + * @return the body response as string + * @throws Exception the exception + */ + public String performGETRequestWithRetry(Map> mapParameters, String gcubeToken, int maxAttempts) throws Exception{ + log.info("Calling Service: {} with maximun number of attempts: {}", serviceURL, maxAttempts); + HttpCallerUtil httpCaller = new HttpCallerUtil(serviceURL, null, null); + try { + String response = null; + int attempt = 0; + do{ + attempt++; + log.info("Submitting request number "+attempt+ " to service: "+serviceURL); + try{ + response = httpCaller.callGet(null, mapParameters, gcubeToken); + }catch(Exception e){ + log.warn("Attempt number "+attempt+" just thrown error contacting the service: "+serviceURL +" with parameters: "+mapParameters); + int timeToSleep = 3000*attempt; + log.info("Now sleeping for "+timeToSleep+"ms"); + Thread.sleep(timeToSleep); + } + }while (attemptmaxAttempts){ + throw new Exception("The service is not available at: "+serviceURL+" passing the parameters: "+mapParameters+". Number of retry performed: "+attempt); + } + +// if(response==null){ +// log.error("Response is null calling the service: "+httpRequestURL +" with parameters: "+mapParameters); +// throw new Exception("The service did not produce any result. The response is null"); +// } + + log.trace("The response is: "+response); + return response; + } + catch (Exception e) { + String error = "Error interacting with the DM service: "+serviceURL +" with parameters: "+mapParameters; + log.error(error, e); + throw new Exception(error); + } + } + + /** + * Gets the urlservice. + * + * @return the urlservice + */ + public String getUrlservice() { + return serviceURL; + } + + /** + * Sets the urlservice. + * + * @param urlservice the new urlservice + */ + public void setUrlservice(String urlservice) { + this.serviceURL = urlservice; + } + + /** + * Gets the client. + * + * @return the client + */ + public HttpClient getClient() { + return httpClient; + } + + /** + * Sets the client. + * + * @param client the new client + */ + public void setClient(HttpClient client) { + this.httpClient = client; + } + + /** + * Gets the username. + * + * @return the username + */ + public String getUsername() { + return username; + } + + /** + * Sets the username. + * + * @param username the new username + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * Gets the password. + * + * @return the password + */ + public String getPassword() { + return password; + } + + /** + * Sets the password. + * + * @param password the new password + */ + public void setPassword(String password) { + this.password = password; + } + + + /** + * Gets the status code. + * + * @return the statusCode + */ + public int getStatusCode() { + + return statusCode; + } + + + /** + * Checks if is call error. + * + * @return the callError + */ + public boolean isCallError() { + + return callError; + } + + + /** + * Gets the full url. + * + * @return the fullUrl + */ + public String getFullUrl() { + + return fullUrl; + } + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/PortalContextInfo.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/PortalContextInfo.java new file mode 100644 index 0000000..1a20883 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/PortalContextInfo.java @@ -0,0 +1,247 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util; + +import java.io.Serializable; + + +/** + * The Class PortalContextInfo. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Nov 25, 2016 + */ +public class PortalContextInfo implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 5003662885627052222L; + private String username; + private String userFullName; + private String userEmail; + private String userAvatarID; + private String userAvatarURL; + private String currentScope; + private String userToken; + private long currGroupId; + + + /** + * + */ + public PortalContextInfo() { + } + + + /** + * Instantiates a new portal context info. + * + * @param username the username + * @param userFullName the user full name + * @param userEmail the user email + * @param userAvatarID the user avatar id + * @param userAvatarURL the user avatar url + * @param currentScope the current scope + * @param userToken the user token + * @param currGroupId the curr group id + */ + public PortalContextInfo(String username, String userFullName, String userEmail, String userAvatarID, String userAvatarURL, String currentScope, String userToken, long currGroupId) { + this.username = username; + this.userFullName = userFullName; + this.userEmail = userEmail; + this.userAvatarID = userAvatarID; + this.userAvatarURL = userAvatarURL; + this.currentScope = currentScope; + this.userToken = userToken; + this.currGroupId = currGroupId; + + } + + /** + * @return the username + */ + public String getUsername() { + + return username; + } + + /** + * @return the userFullName + */ + public String getUserFullName() { + + return userFullName; + } + + + + /** + * @return the userEmail + */ + public String getUserEmail() { + + return userEmail; + } + + + + /** + * @return the userAvatarID + */ + public String getUserAvatarID() { + + return userAvatarID; + } + + + + /** + * @return the userAvatarURL + */ + public String getUserAvatarURL() { + + return userAvatarURL; + } + + + + /** + * @return the currentScope + */ + public String getCurrentScope() { + + return currentScope; + } + + + + /** + * @return the userToken + */ + public String getUserToken() { + + return userToken; + } + + + + /** + * @return the currGroupId + */ + public long getCurrGroupId() { + + return currGroupId; + } + + + + /** + * @param username the username to set + */ + public void setUsername(String username) { + + this.username = username; + } + + + + /** + * @param userFullName the userFullName to set + */ + public void setUserFullName(String userFullName) { + + this.userFullName = userFullName; + } + + + + /** + * @param userEmail the userEmail to set + */ + public void setUserEmail(String userEmail) { + + this.userEmail = userEmail; + } + + + + /** + * @param userAvatarID the userAvatarID to set + */ + public void setUserAvatarID(String userAvatarID) { + + this.userAvatarID = userAvatarID; + } + + + + /** + * @param userAvatarURL the userAvatarURL to set + */ + public void setUserAvatarURL(String userAvatarURL) { + + this.userAvatarURL = userAvatarURL; + } + + + + /** + * @param currentScope the currentScope to set + */ + public void setCurrentScope(String currentScope) { + + this.currentScope = currentScope; + } + + + + /** + * @param userToken the userToken to set + */ + public void setUserToken(String userToken) { + + this.userToken = userToken; + } + + + + /** + * @param currGroupId the currGroupId to set + */ + public void setCurrGroupId(long currGroupId) { + + this.currGroupId = currGroupId; + } + + + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("PortalContextInfo [username="); + builder.append(username); + builder.append(", userFullName="); + builder.append(userFullName); + builder.append(", userEmail="); + builder.append(userEmail); + builder.append(", userAvatarID="); + builder.append(userAvatarID); + builder.append(", userAvatarURL="); + builder.append(userAvatarURL); + builder.append(", currentScope="); + builder.append(currentScope); + builder.append(", userToken="); + builder.append("XXX-HIDDEN-TOKEN"); + builder.append(", currGroupId="); + builder.append(currGroupId); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/ResetOnCloseInputStream.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/ResetOnCloseInputStream.java new file mode 100644 index 0000000..f470c12 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/ResetOnCloseInputStream.java @@ -0,0 +1,37 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util; + +import java.io.IOException; +import java.io.InputStream; + + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 23, 2019 + */ +public class ResetOnCloseInputStream extends InputStream { + + private final InputStream decorated; + + public ResetOnCloseInputStream(InputStream anInputStream) { + if (!anInputStream.markSupported()) { + throw new IllegalArgumentException("marking not supported"); + } + + anInputStream.mark( 1 << 24); // magic constant: BEWARE + decorated = anInputStream; + } + + @Override + public void close() throws IOException { + decorated.reset(); + } + + @Override + public int read() throws IOException { + return decorated.read(); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/ServiceEndpointReader.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/ServiceEndpointReader.java new file mode 100644 index 0000000..0b602ea --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/ServiceEndpointReader.java @@ -0,0 +1,221 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util; + +import static org.gcube.resources.discovery.icclient.ICFactory.clientFor; +import static org.gcube.resources.discovery.icclient.ICFactory.queryFor; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.gcube.common.encryption.StringEncrypter; +import org.gcube.common.resources.gcore.ServiceEndpoint; +import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint; +import org.gcube.common.resources.gcore.ServiceEndpoint.Property; +import org.gcube.common.resources.gcore.utils.Group; +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 ServiceEndpointReader. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 22, 2019 + */ +public class ServiceEndpointReader { + + public static final Logger logger = LoggerFactory.getLogger(ServiceEndpointReader.class); + + public ServiceParameters serverParameters; + + private String scope; + + private String profileName; + + private String profileCategory; + + + /** + * Instantiates a new service endpoint reader. + * + * @param scope the scope + * @param profileName the profile name + * @param profileCategory the profile category + */ + public ServiceEndpointReader(String scope, String profileName, String profileCategory) { + this.scope = scope; + this.profileName = profileName; + this.profileCategory = profileCategory; + } + + /** + * Read resource. + * + * @param decrypt the decrypt + * @return the server parameters + * @throws Exception the exception + */ + public ServiceParameters readResource(boolean decrypt) throws Exception { + + if(this.scope==null) + throw new Exception("scope is null"); + + if(this.profileName==null) + throw new Exception("profileName is null"); + + try{ + logger.info("Trying to read Service Endpoint with Profile/Name: "+profileName+", scope: "+scope); + + ScopeProvider.instance.set(this.scope); + logger.info("scope provider set instance: "+this.scope); + + SimpleQuery query = queryFor(ServiceEndpoint.class); + query.addCondition("$resource/Profile/Name/string() eq '"+profileName+"'");{ + + if(profileCategory!=null) + logger.info("Added condition Profile/Category: "+profileCategory); + query.addCondition("$resource/Profile/Category/string() eq '"+profileCategory+"'"); + } + + DiscoveryClient client = clientFor(ServiceEndpoint.class); + + List r = client.submit(query); + if (r == null || r.isEmpty()) throw new Exception("Cannot retrieve the runtime resource: "+profileName); + + ServiceEndpoint se = r.get(0); //the first + if(se.profile()==null) + throw new Exception("IS profile is null for Profile/Name: "+profileName); + + Group accessPoints = se.profile().accessPoints(); + if(accessPoints.size()==0) throw new Exception("Accesspoint in resource Profile/Name: "+profileName+" not found"); + + serverParameters = new ServiceParameters(); + + AccessPoint ap = accessPoints.iterator().next(); + serverParameters.setUrl(ap.address()); + serverParameters.setUser(ap.username()); //username + + String decryptedPassword = ""; + + if(decrypt) + decryptedPassword = StringEncrypter.getEncrypter().decrypt(ap.password()); + else + decryptedPassword = ap.password(); + + serverParameters.setPassword(decryptedPassword); //password + + Group properties = ap.properties(); + + if(properties.size()==0){ + logger.warn("Properties in resource Profile/Name "+profileName+" not found! returning"); + return serverParameters; + } + + Iterator iter = properties.iterator(); + + Map> mapProperties = new HashMap>(); + while (iter.hasNext()) { + Property prop = iter.next(); + mapProperties.put(prop.name(), Arrays.asList(prop.value())); + } + + serverParameters.setProperties(mapProperties); + + return serverParameters; + + }catch (Exception e) { + String error = "Sorry, an error occurred on reading parameters in Runtime Reosurces, resource Profile/Name "+profileName+" scope: "+scope; + logger.error(error,e); + throw new Exception(error); + } + + } + + + /** + * Gets the profile name. + * + * @return the profileName + */ + public String getProfileName() { + + return profileName; + } + + + /** + * Gets the profile category. + * + * @return the profileCategory + */ + public String getProfileCategory() { + + return profileCategory; + } + + /** + * Gets the scope. + * + * @return the scope + */ + public String getScope() { + return scope; + } + + /** + * Gets the server parameters. + * + * @return the server parameters + */ + public ServiceParameters getServerParameters() { + return serverParameters; + } + + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("ServiceEndpointReader [serverParameters="); + builder.append(serverParameters); + builder.append(", scope="); + builder.append(scope); + builder.append(", profileName="); + builder.append(profileName); + builder.append(", profileCategory="); + builder.append(profileCategory); + builder.append("]"); + return builder.toString(); + } + + + public static String SERVICE_ENDPOINT_CATEGORY = "DataAnalysis"; + public static String SERVICE_ENDPOINT_NAME = "DataMiner"; + /** + * The main method. + * + * @param args the arguments + */ + public static void main(String[] args) { + ServiceEndpointReader reader = new ServiceEndpointReader("/gcube/preprod/preVRE", SERVICE_ENDPOINT_NAME, SERVICE_ENDPOINT_CATEGORY); + + try { + System.out.println(reader.readResource(true)); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/ServiceParameters.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/ServiceParameters.java new file mode 100644 index 0000000..328f57f --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/ServiceParameters.java @@ -0,0 +1,133 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util; + +import java.util.List; +import java.util.Map; + + +/** + * The Class ServiceParameters. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 23, 2019 + */ +public class ServiceParameters { + + protected String url; + protected String user; + protected String password; + protected Map> properties; + + + /** + * Instantiates a new service parameters. + */ + public ServiceParameters(){} + + + /** + * Instantiates a new service parameters. + * + * @param url the url + * @param user the user + * @param password the password + * @param properties the properties + */ + public ServiceParameters(String url, String user, String password, Map> properties) { + this.url = url; + this.user = user; + this.password = password; + this.properties = properties; + } + + /** + * Gets the url. + * + * @return the url + */ + public String getUrl() { + return url; + } + + /** + * Sets the url. + * + * @param url the new url + */ + public void setUrl(String url) { + this.url = url; + } + + /** + * Gets the user. + * + * @return the user + */ + public String getUser() { + return user; + } + + /** + * Sets the user. + * + * @param user the new user + */ + public void setUser(String user) { + this.user = user; + } + + /** + * Gets the password. + * + * @return the password + */ + public String getPassword() { + return password; + } + + /** + * Sets the password. + * + * @param password the new password + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * @return the properties + */ + public Map> getProperties() { + + return properties; + } + + /** + * @param properties the properties to set + */ + public void setProperties(Map> properties) { + + this.properties = properties; + } + + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("ServiceParameters [url="); + builder.append(url); + builder.append(", user="); + builder.append(user); + builder.append(", properties="); + builder.append(properties); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/UrlEncoderUtil.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/UrlEncoderUtil.java new file mode 100644 index 0000000..8c4074e --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/UrlEncoderUtil.java @@ -0,0 +1,95 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.List; +import java.util.Map; + +import org.apache.log4j.Logger; + +/** + * The Class UrlEncoderUtil. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Feb 19, 2015 + */ +public class UrlEncoderUtil { + + public static String charset = "UTF-8"; + + public static Logger logger = Logger.getLogger(UrlEncoderUtil.class); + +// /** +// * Encode query. +// * +// * @param parameters the parameters +// * @return the string +// */ +// public static String encodeQuery(String... parameters){ +// +// String query = ""; +// for (String string : parameters) { +// +// try { +// query+=URLEncoder.encode(string, charset)+"&"; +// } catch (UnsupportedEncodingException e) { +// logger.error(e); +// return query; +// } +// +// } +// return removeLastChar(query); +// } + + + /** + * Encode query. + * + * @param parameters the parameters + * @return the string + */ + public static String encodeQuery(Map> parameters){ + + String query = ""; + + if(parameters==null) + return query; + + for (String key : parameters.keySet()) { + + try { + for (String value : parameters.get(key)) { + query+=String.format(key+"=%s", URLEncoder.encode(value, charset))+"&"; + } + } catch (UnsupportedEncodingException e) { + logger.error(e); + return query; + } + + } + + return removeLastChar(query); + + } + + /** + * Removes the last char. + * + * @param string the string + * @return the string + */ + public static String removeLastChar(String string){ + + if(string == null) + return null; + + if(string.length()>0) + return string.substring(0, string.length()-1); + + return string; + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/csv/CSVReader.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/csv/CSVReader.java new file mode 100644 index 0000000..c52c4d6 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/csv/CSVReader.java @@ -0,0 +1,192 @@ +/** + * + */ + +package org.gcube.portlets.user.performfishanalytics.server.util.csv; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +import org.gcube.portlets.user.performfishanalytics.shared.csv.CSVFile; +import org.gcube.portlets.user.performfishanalytics.shared.csv.CSVRow; + +/** + * The Class CSVReader. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 29, 2019 + */ +public class CSVReader { + + private static final char DEFAULT_SEPARATOR = ','; + private static final char DEFAULT_QUOTE = '"'; + private File file; + private CSVFile csvFile; + + /** + * Instantiates a new CSV reader. + * + * @param file the file + * @throws FileNotFoundException the file not found exception + */ + public CSVReader(File file) throws FileNotFoundException { + + this.file = file; + this.csvFile = new CSVFile(); + readCSV(file); + } + + /** + * Read csv. + * + * @param file the file + * @throws FileNotFoundException the file not found exception + */ + private void readCSV(File file) throws FileNotFoundException { + + Scanner scanner = new Scanner(file); + int i = 0; + while (scanner.hasNext()) { + CSVRow csvRow = new CSVRow(); + List line = parseLine(scanner.nextLine()); + csvRow.setListValues(line); + + if(i==0){ + csvFile.setHeaderRow(csvRow); + }else{ + csvFile.addRow(csvRow); + } + i++; + + } + scanner.close(); + } + + /** + * Parses the line. + * + * @param cvsLine the cvs line + * @return the list + */ + public static List parseLine(String cvsLine) { + + return parseLine(cvsLine, DEFAULT_SEPARATOR, DEFAULT_QUOTE); + } + + /** + * Parses the line. + * + * @param cvsLine the cvs line + * @param separators the separators + * @return the list + */ + public static List parseLine(String cvsLine, char separators) { + + return parseLine(cvsLine, separators, DEFAULT_QUOTE); + } + + /** + * Parses the line. + * + * @param cvsLine the cvs line + * @param separators the separators + * @param customQuote the custom quote + * @return the list + */ + private static List parseLine(String cvsLine, char separators, char customQuote) { + + List result = new ArrayList<>(); + // if empty, return! + if (cvsLine == null && cvsLine.isEmpty()) { + return result; + } + if (customQuote == ' ') { + customQuote = DEFAULT_QUOTE; + } + if (separators == ' ') { + separators = DEFAULT_SEPARATOR; + } + StringBuffer curVal = new StringBuffer(); + boolean inQuotes = false; + boolean startCollectChar = false; + boolean doubleQuotesInColumn = false; + char[] chars = cvsLine.toCharArray(); + for (char ch : chars) { + if (inQuotes) { + startCollectChar = true; + if (ch == customQuote) { + inQuotes = false; + doubleQuotesInColumn = false; + } + else { + // Fixed : allow "" in custom quote enclosed + if (ch == '\"') { + if (!doubleQuotesInColumn) { + curVal.append(ch); + doubleQuotesInColumn = true; + } + } + else { + curVal.append(ch); + } + } + } + else { + if (ch == customQuote) { + inQuotes = true; + // Fixed : allow "" in empty quote enclosed + if (chars[0] != '"' && customQuote == '\"') { + curVal.append('"'); + } + // double quotes in column will hit this! + if (startCollectChar) { + curVal.append('"'); + } + } + else if (ch == separators) { + result.add(curVal.toString()); + curVal = new StringBuffer(); + startCollectChar = false; + } + else if (ch == '\r') { + // ignore LF characters + continue; + } + else if (ch == '\n') { + // the end, break! + break; + } + else { + curVal.append(ch); + } + } + } + result.add(curVal.toString()); + return result; + } + + + /** + * Gets the csv file. + * + * @return the csvFile + */ + public CSVFile getCsvFile() { + + return csvFile; + } + + + /** + * Gets the file. + * + * @return the file + */ + public File getFile() { + + return file; + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/csv/CSVWriter.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/csv/CSVWriter.java new file mode 100644 index 0000000..61f3b7a --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/csv/CSVWriter.java @@ -0,0 +1,55 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util.csv; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; + + +/** + * The Class CSVWriter. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 30, 2019 + */ +public class CSVWriter { + + private PrintWriter reportPrintWriter; + + /** + * Instantiates a new CSV writer. + * + * @param tempFile the temp file + * @throws IOException Signals that an I/O exception has occurred. + */ + public CSVWriter(File tempFile) throws IOException { + + FileWriter reportWriter = new FileWriter(tempFile, true); + BufferedWriter reportBW = new BufferedWriter(reportWriter); + reportPrintWriter = new PrintWriter(reportBW); + } + + /** + * Write csv line. + * + * @param newline the newline + */ + public void writeCSVLine(String newline){ + + reportPrintWriter.println(newline); + } + + /** + * Close writer. + */ + public void closeWriter(){ + + if(reportPrintWriter!=null) + reportPrintWriter.close(); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/FillDatabasePerBatchType.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/FillDatabasePerBatchType.java new file mode 100644 index 0000000..f51371f --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/FillDatabasePerBatchType.java @@ -0,0 +1,460 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util.database; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +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.csv.CSVReader; +import org.gcube.portlets.user.performfishanalytics.server.util.database.data.AreaData; +import org.gcube.portlets.user.performfishanalytics.server.util.database.data.KPIBatchTypeData; +import org.gcube.portlets.user.performfishanalytics.server.util.database.data.PeriodData; +import org.gcube.portlets.user.performfishanalytics.server.util.database.data.QuarterData; +import org.gcube.portlets.user.performfishanalytics.server.util.database.data.SpeciesData; +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.Quarter; +import org.gcube.portlets.user.performfishanalytics.shared.Species; +import org.gcube.portlets.user.performfishanalytics.shared.csv.CSVFile; +import org.gcube.portlets.user.performfishanalytics.shared.csv.CSVRow; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * The Class FillDatabasePerBatchType. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Feb 27, 2019 + */ +public class FillDatabasePerBatchType { + + /** + * + */ + public static final String RELATIVE_PATH_TO_BATCH_KPI = "BATCH/KPI"; + protected static Logger log = LoggerFactory.getLogger(FillDatabasePerBatchType.class); + + + /** + * The Enum BATCH_LEVEL. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Feb 27, 2019 + */ + public static enum BATCH_LEVEL{ + PRE_ONGROWING, + PRE_ONGROWING_CLOSED_BATCHES, + HATCHERY_INDIVIDUAL, + HATCHERY_INDIVIDUAL_CLOSED_BATCHES, + GROW_OUT_INDIVIDUAL, + GROW_OUT_INDIVIDUAL_CLOSED_BATCHES, + GROW_OUT_AGGREGATED, + GROW_OUT_AGGREGATED_CLOSED_BATCHES + } + + /** + * Prints the database data. + * + * @param entityManagerFactory the entity manager factory + * @throws Exception the exception + */ + public static void printDatabaseData(EntityManagerFactory entityManagerFactory) throws Exception { + + GenericPersistenceDaoBuilder builderPopulation = new GenericPersistenceDaoBuilder(entityManagerFactory, "Population"); + + for(Population population: builderPopulation.getPersistenceEntity().getList()){ + log.debug("\n\n#### Population: "+population.getName()); + for (PopulationType populationType : population.getListPopulationType()) { + log.debug("\t*PopulationType: "+populationType.getName() +" Type: "+populationType.getType()); + + log.debug("\t**has Species: "+populationType.getListSpecies().size()); + for (Species species : populationType.getListSpecies()) { + log.debug("\t\t"+species.getName()); + } + + log.debug("\t**has Quarter: "+populationType.getListQuarter().size()); + for (Quarter quarter : populationType.getListQuarter()) { + log.debug("\t\t"+quarter.getName()); + } + + log.debug("\t**has Area: "+populationType.getListArea().size()); + for (Area area : populationType.getListArea()) { + log.debug("\t\t"+area.getName()); + } + + log.debug("\t**has Period: "+populationType.getListPeriod().size()); + for (Period period : populationType.getListPeriod()) { + log.debug("\t\t"+period.getName()); + } + log.debug("\t**has KPIs: "+populationType.getListKPI().size()); + for (KPI kpi : populationType.getListKPI()) { + printKPIs(kpi); + } + } + } + } + + /** + * Prints the kp is. + * + * @param kpi the kpi + * @param level the level + */ + public static void printKPIs(KPI kpi, int level){ + if(kpi==null) + return; + + log.debug(String.format("\t%"+level*5+"d|KPI: %s, %s",level, kpi.getCode(), kpi.getName())); + //log.debug("LIST KPI ARE: "+listKPI); + level++; + if(kpi.getListKPI()==null){ + //log.debug("[LEAF: "+kpi.getName()+"]"); + //I'm a LEAF + return; + } + for (KPI kpiChild : kpi.getListKPI()) { + printKPIs(kpiChild, kpiChild.getDeepIndex()); + } + } + + + /** + * Prints the kp is. + * + * @param kpi the kpi + */ + public static void printKPIs(KPI kpi){ + if(kpi==null || kpi.getListKPI()==null) + return; + + log.debug(String.format("\t%"+kpi.getDeepIndex()*5+"d|KPI: %s, %s",kpi.getDeepIndex(), kpi.getCode(), kpi.getName())); + for (KPI kpiChild : kpi.getListKPI()) { + printKPIs(kpiChild, kpiChild.getDeepIndex()); + } + } + + + /** + * Fill database. + * + * @param entityManagerFactory the entity manager factory + * @param context the context + * @throws Exception the exception + */ + public static void fillDatabase(EntityManagerFactory entityManagerFactory, ServletContext context) throws Exception{ + + //INSERT POPULATION - BATCH + Population batchPopulation = new Population(java.util.UUID.randomUUID().toString(), "BATCH", "BATCH", "BATCH Description", null); + + List listBatchLevels = loadKPIForBatchLevelFromResource(context); + + //FILLING BATCH LEVEL/POPULATIONS + for (PopulationType batchType : listBatchLevels) { + + batchType.setPopulation(batchPopulation); + + if(batchType.getName().equals(BATCH_LEVEL.PRE_ONGROWING.name()) || batchType.getName().equals(BATCH_LEVEL.PRE_ONGROWING_CLOSED_BATCHES.name())){ + + //Species + batchType.setListSpecies(SpeciesData.getListSpecies(batchType)); + //Areas + batchType.setListArea(AreaData.getListArea(batchType)); + //Periods + batchType.setListPeriod(PeriodData.getListPeriods(batchType)); + + }else if(batchType.getName().equals(BATCH_LEVEL.HATCHERY_INDIVIDUAL.name()) || batchType.getName().equals(BATCH_LEVEL.HATCHERY_INDIVIDUAL_CLOSED_BATCHES.name())){ + + //Species + batchType.setListSpecies(SpeciesData.getListSpecies(batchType)); + //Periods + batchType.setListPeriod(PeriodData.getListPeriods(batchType)); + + }else if(batchType.getName().equals(BATCH_LEVEL.GROW_OUT_INDIVIDUAL.name()) || batchType.getName().equals(BATCH_LEVEL.GROW_OUT_INDIVIDUAL_CLOSED_BATCHES.name())){ + + //Species + batchType.setListSpecies(SpeciesData.getListSpecies(batchType)); + //Quarters + batchType.setListQuarter(QuarterData.getListQuarter(batchType)); + //Areas + batchType.setListArea(AreaData.getListArea(batchType)); + + }else if(batchType.getName().equals(BATCH_LEVEL.GROW_OUT_AGGREGATED_CLOSED_BATCHES.name())){ + + //Species + batchType.setListSpecies(SpeciesData.getListSpecies(batchType)); + //Quarters + batchType.setListQuarter(QuarterData.getListQuarter(batchType)); + //Areas + batchType.setListArea(AreaData.getListArea(batchType)); + + } + + } + + //INSERTING BATCH LEVEL/POPULATIONS + GenericPersistenceDaoBuilder builderPopulation = new GenericPersistenceDaoBuilder(entityManagerFactory, "Population"); + batchPopulation.setListPopulationType(new ArrayList(listBatchLevels)); + builderPopulation.getPersistenceEntity().insert(batchPopulation); + } + + /** + * Builds the populations. + * + * @return the list + */ + public static List buildPopulations(){ + Population popFarm = new Population(java.util.UUID.randomUUID().toString(), "FARM", "FARM", "FARM Description", null); + Population popBatch = new Population(java.util.UUID.randomUUID().toString(), "BATCH", "BATCH", "BATCH Description", null); + return Arrays.asList(popFarm, popBatch); + } + + + /** + * Builds the population type. + * + * @param type the type + * @param description the description + * @param poulation the poulation + * @return the population type + */ + public static PopulationType buildPopulationType(String type, String description, Population poulation){ + + return new PopulationType(java.util.UUID.randomUUID().toString(), type, type, description, poulation); + } + + + /** + * Creates the batch type. + * + * @param fileName the file name + * @param reader the reader + * @return the population type + * @throws Exception the exception + */ + private static PopulationType createBatchType(String fileName, CSVReader reader) throws Exception{ + + Population batchPopulation = null; + String batchTypeName = fileName.substring(0, fileName.lastIndexOf(".")); + PopulationType batchType = buildPopulationType(batchTypeName, batchTypeName+" description", batchPopulation); + + CSVFile csvFile = reader.getCsvFile(); + List rootListKPI = new ArrayList(); + //Map kpiMap = new HashMap(); + int rowIndex = 0; + //KPI[] lastDeepLevel = new KPI[10]; +// lastDeepLevel[0] = null; + for (CSVRow csvRow : csvFile.getValueRows()) { + List rowValues = csvRow.getListValues(); + String kpiCode = ""; + int levelIndex = 0; + String kpiName = null; + log.trace("Reading row values: {} ",rowValues); + log.trace("Row index: {} ",rowIndex); + //Looping on row values + for (int j = 0; j < rowValues.size(); j++) { + String value = rowValues.get(j); + log.trace("\tColumn index: {} ",j); + //first column I'm expecting the KPI code if exists + if(j==0){ + kpiCode = value; + log.trace("\tKPI code: {} ",kpiCode); + }else if(value!=null && !value.isEmpty()){ + levelIndex = j; + kpiName = value; + } + } + + + PopulationType populationType = null; + ArrayList descendants = null; + //DIRECT CHILD OF POPULATION (i.e. "BATCH") + if(levelIndex==1){ + populationType = batchType; + } + + KPI toAdd = KPIBatchTypeData.buildKPI(kpiCode, kpiName, kpiName + " description", descendants, populationType, levelIndex); + log.debug("\t Created: {} ",toAdd); + //lastDeepLevel[levelIndex-1] = toAdd; + + if(levelIndex==1){ + //ADDING TO ROOT LIST + rootListKPI.add(toAdd); +// } +// else if(levelIndex==2){ +// //ADDING TO SECOND LEVEL +// KPI lastRootKPI = rootListKPI.get(rootListKPI.size()-1); +// addAsDescendant(lastRootKPI, toAdd); + }else{ + KPI lastRootKPI = rootListKPI.get(rootListKPI.size()-1); + //ADDING TO 3 LEVEL onwards + KPI lastDescendant = getLastDescendantAtIndex(lastRootKPI, levelIndex-1); + addAsDescendant(lastDescendant, toAdd); + } + + rowIndex++; + } + + batchType.setListKPI(rootListKPI); + + return batchType; + } + + /** + * Gets the last descendant at index. + * + * @param kpi the kpi + * @param levelIndex the level index + * @return the last descendant at index + */ + private static KPI getLastDescendantAtIndex(KPI kpi, int levelIndex){ + + if(kpi.getDeepIndex()==levelIndex) + return kpi; + + KPI lastKPI = kpi.getListKPI().get(kpi.getListKPI().size()-1); + return getLastDescendantAtIndex(lastKPI, levelIndex); + + } + + /** + * Adds the as descendant. + * + * @param parent the parent + * @param toAdd the to add + * @return the kpi + */ + private static KPI addAsDescendant(KPI parent, KPI toAdd){ + if(parent==null){ + return null; + } + List asDescendants = parent.getListKPI(); + if(asDescendants==null){ + asDescendants = new ArrayList(); + } + asDescendants.add(toAdd); + parent.setListKPI(asDescendants); + return parent; + } + + /** + * List files for folder. + * + * @param folder the folder + * @param files the files + */ + private static void listFilesForFolder(final File folder, List files) { + for (final File fileEntry : folder.listFiles()) { + if (fileEntry.isDirectory()) { + listFilesForFolder(fileEntry, files); + } else { + files.add(fileEntry); + System.out.println(fileEntry.getName()); + } + } + } + + + /** + * Load kpi for batch level from resource. + * + * @param context the context + * @return the list + */ + private static List loadKPIForBatchLevelFromResource(ServletContext context){ + + String kpiFolder = null; + List batchTypes = null; + try{ + + String relKPIFolder = String.format("/WEB-INF/classes/%s", RELATIVE_PATH_TO_BATCH_KPI); + + if(context==null){ + log.warn("ECLIPSE MODE ACTIVES ADDING USER DIRECTORY"); + String workingDir = System.getProperty("user.dir"); + kpiFolder = String.format(workingDir+"/%s/%s", "src/main/resources", RELATIVE_PATH_TO_BATCH_KPI); + }else{ + log.info("Getting real path of {}",relKPIFolder); + kpiFolder = context.getRealPath(relKPIFolder); + } + + log.info("KPI base folder is: {}",kpiFolder); + List listFile = new ArrayList(); + listFilesForFolder(new File(kpiFolder), listFile); + log.info("### Loading KPIs from path: {}",kpiFolder); + batchTypes = new ArrayList(); + for (File file : listFile) { + try{ + log.info("Reading the csv: "+file.getName()); + CSVReader reader = new CSVReader(file); + batchTypes.add(createBatchType(file.getName(), reader)); + }catch(Exception e){ + e.printStackTrace(); + } + } + if(log.isDebugEnabled()){ + for (PopulationType populationType : batchTypes) { + log.info("****Batch {}",populationType); + log.debug("\t**has KPIs: "+populationType.getListKPI().size()); + for (KPI kpi : populationType.getListKPI()) { + printKPIs(kpi); + } + } + } + + log.info("### Procedure to load the KPIs from path "+kpiFolder+" terminated correctly"); + }catch(Exception e){ + log.error("Error on loading KPI from path: {}",kpiFolder, e); + } + + return batchTypes; + } + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(String[] args) { + + try{ + String kpiFolder = String.format("%s/src/main/resources/BATCH/KPI", System.getProperty("user.dir")); + log.info("KPI base folder is: {}",kpiFolder); + List listFile = new ArrayList(); + listFilesForFolder(new File(kpiFolder), listFile); + log.info("### Starting populating the DB: "); + List batchTypes = new ArrayList(); + for (File file : listFile) { + try{ + log.info("Reading the csv: "+file.getName()); + CSVReader reader = new CSVReader(file); + batchTypes.add(createBatchType(file.getName(), reader)); + }catch(Exception e){ + e.printStackTrace(); + } + } + + for (PopulationType populationType : batchTypes) { + log.info("****Batch {}",populationType); + log.debug("\t**has KPIs: "+populationType.getListKPI().size()); + for (KPI kpi : populationType.getListKPI()) { + printKPIs(kpi); + } + } + + log.info("### Procedure to populate the DB terminated"); + }catch(Exception e){ + } + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/AreaData.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/AreaData.java new file mode 100644 index 0000000..dd8cfdc --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/AreaData.java @@ -0,0 +1,36 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util.database.data; + +import java.util.ArrayList; +import java.util.List; + +import org.gcube.portlets.user.performfishanalytics.shared.Area; +import org.gcube.portlets.user.performfishanalytics.shared.PopulationType; + + +/** + * The Class AreaData. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 15, 2019 + */ +public class AreaData { + + /** + * Gets the list area. + * + * @param batchType the batch type + * @return the list area + */ + public static ArrayList getListArea(PopulationType batchType){ + + List listArea = new ArrayList(); + listArea.add(new Area(java.util.UUID.randomUUID().toString(), "Zone 0", "", batchType)); + listArea.add(new Area(java.util.UUID.randomUUID().toString(), "Zone 1", "", batchType)); + listArea.add(new Area(java.util.UUID.randomUUID().toString(), "Zone 2", "", batchType)); + listArea.add(new Area(java.util.UUID.randomUUID().toString(), "Zone 3", "", batchType)); + return (ArrayList) listArea; + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/KPIBatchTypeData.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/KPIBatchTypeData.java new file mode 100644 index 0000000..12a8f34 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/KPIBatchTypeData.java @@ -0,0 +1,750 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util.database.data; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.gcube.portlets.user.performfishanalytics.shared.KPI; +import org.gcube.portlets.user.performfishanalytics.shared.PopulationType; + + +/** + * The Class BatchPopulationData. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 15, 2019 + */ +public class KPIBatchTypeData { + + + /** + * Builds the kpi. + * + * @param code the code + * @param value the value + * @param description the description + * @param descendants the descendants + * @param populationType the population type + * @param deepIndex the deep index + * @return the kpi + */ + public static KPI buildKPI(String code, String value, String description, ArrayList descendants, PopulationType populationType, int deepIndex){ + return new KPI(java.util.UUID.randomUUID().toString(), code, value, description, descendants, populationType, deepIndex); + } + + + /** + * Gets the pre on growing kp is. + * + * @param batchType the batch type + * @return the pre on growing kp is + */ + public static List getPreOnGrowingKPIs(PopulationType batchType){ + /* + //LEVEL 3 + KPI P1 = buildKPI("P1", "Deformed fish %", "", null,null, 3); + //LEVEL 2 + KPI Deformedfish = buildKPI("", "Deformed fish", "", new ArrayList(Arrays.asList(P1)), null, 2); + + //LEVEL 3 + KPI P2 = buildKPI("P2", "Discarded slow grower fish %", "", null, null, 3); + //LEVEL 2 + KPI Discardedslowgrowerfish = buildKPI("", "Discarded slow grower fish", "", new ArrayList(Arrays.asList(P2)), null, 2); + + //LEVEL 3 + KPI P3 = buildKPI("P3", "Mortalities - total %", "", null, null, 2); + //LEVEL 2 + KPI Mortalitiestotal = buildKPI("", "Mortalities - total", "", new ArrayList(Arrays.asList(P3)), null, 2); + + //LEVEL 1 + KPI PregrowTotalProductivityKPIs = buildKPI("", "Pre-grow Total Productivity KPIs", "", new ArrayList(Arrays.asList(Deformedfish, Discardedslowgrowerfish, Mortalitiestotal)), batchType, 1); + + + //LEVEL 3 + KPI P4 = buildKPI("P4", "Specific Growth Rate (SGR) (% day^-1)", "", null,null, 3); + //LEVEL 2 + KPI SpecificGrowthRateSGR = buildKPI("", "Specific Growth Rate (SGR)", "", new ArrayList(Arrays.asList(P4)), null, 2); + + KPI FishGrowtKPIs = buildKPI("", "Fish Growth KPIs", "", new ArrayList(Arrays.asList(SpecificGrowthRateSGR)), batchType, 1); + + + //LEVEL 3 + KPI P4 = buildKPI("P4", "Specific Growth Rate (SGR) (% day^-1)", "", null,null, 3); + //LEVEL 2 + KPI SpecificGrowthRateSGR = buildKPI("", "Specific Growth Rate (SGR)", "", new ArrayList(Arrays.asList(P4)), null, 2); + + KPI FishGrowtKPIs = buildKPI("", "Fish Growth KPIs", "", new ArrayList(Arrays.asList(SpecificGrowthRateSGR)), batchType, 1); + */ + return null; + } + + + + /** + * OK + * Gets the list kpi for hatcher y_ individual. + * + * @param batchType the batch type + * @return the list kpi for hatcher y_ individual + */ + public static KPI getHatcheryTotalProductivityKPIsHATCHERY_INDIVIDUAL(PopulationType batchType){ + + //LEVEL 3 + KPI H1 = buildKPI("H1", "Weaned fish (%)", "", null, null, 3); + //LEVEL 2 + KPI Weanedfish = buildKPI("", "Weaned fish", "", new ArrayList(Arrays.asList(H1)), null, 2); + + //LEVEL 3 + KPI H2_1_1 = buildKPI("H2_1_1", "Discarded fish for head deformities - at 1200dd (%)", "", null, null, 3); + KPI H2_1_2 = buildKPI("H2_1_2", "Discarded fish for head deformities - at 1800dd (%)", "", null, null, 3); + KPI H2_1_3 = buildKPI("H2_1_3", "Discarded fish for head deformities - at 2400dd (%)", "", null, null, 3); + KPI H2_2_1 = buildKPI("H2_2_1", "Discarded fish for spinal deformities - at 1200dd (%)", "", null, null, 3); + KPI H2_2_2 = buildKPI("H2_2_2", "Discarded fish for spinal deformities - at 1800dd (%)", "", null, null, 3); + KPI H2_2_3 = buildKPI("H2_2_3", "Discarded fish for spinal deformities - at 2400dd (%)", "", null, null, 3); + KPI H2_3_1 = buildKPI("H2_3_1", "Discarded fish for fin deformities - at 1200dd (%)", "", null, null, 3); + KPI H2_3_2 = buildKPI("H2_3_2", "Discarded fish for fin deformities - at 1800dd (%)", "", null, null, 3); + KPI H2_3_3 = buildKPI("H2_3_3", "Discarded fish for fin deformities - at 2400dd (%)", "", null, null, 3); + KPI H7 = buildKPI("H7", "Head deformities (at 2400dd) %", "", null, null, 3); + // LEVEL 2 + KPI Discardeddeformedfish = + buildKPI("","Discarded deformed fish","",new ArrayList(Arrays.asList( + H7, H2_1_1, H2_1_2, H2_1_3, H2_2_1, H2_2_2, H2_2_3, H2_3_1,H2_3_2, H2_3_3, H7)), null, 2); + + + //LEVEL 3 + KPI H3_1 = buildKPI("H3_1", "Discarded slow grower fish - at 1200dd (%)", "", null, null, 3); + KPI H3_2 = buildKPI("H3_2", "Discarded slow grower fish - at 1800dd (%)", "", null, null, 3); + KPI H3_3 = buildKPI("H3_3", "Discarded slow grower fish - at 2400dd (%)", "", null, null, 3); + //LEVEL 2 + KPI Discardedslowgrowerfish = buildKPI("", "Discarded slow grower fish", "", new ArrayList(Arrays.asList(H3_1, H3_2, H3_3)), null, 2); + + + //LEVEL 3 + KPI H4 = buildKPI("H4", "Fish produced - at 2400dd (%)", "", null, null, 3); + //LEVEL 2 + KPI FishProduced = buildKPI("", "Fish produced", "", new ArrayList(Arrays.asList(H4)), null, 2); + + + //LEVEL 3 + KPI H5_1_1 = buildKPI("H5_1_1", "Number fish/FTE employees in 2018", "", null, null, 3); + KPI H5_1_2 = buildKPI("H5_1_2", "Number fish/FTE employees in 2019", "", null, null, 3); + KPI H5_1_3 = buildKPI("H5_1_3", "Number fish/FTE employees in 2020", "", null, null, 3); + //LEVEL 2 + KPI FishproducedperFTEemployees = buildKPI("", "Fish produced per FTE employees", "", new ArrayList(Arrays.asList(H5_1_1, H5_1_2, H5_1_3)), null, 2); + + + //LEVEL 3 + KPI H6_1 = buildKPI("H6_1", "Survival estimation - at 1200dd (%)", "", null, null, 3); + KPI H6_2 = buildKPI("H6_2", "Survival estimation - at 1800dd (%)", "", null, null, 3); + KPI H6_3 = buildKPI("H6_3", "Survival estimation - at 2400dd (%)", "", null, null, 3); + //LEVEL 2 + KPI Survivalestimation = buildKPI("", "Survival estimation", "", new ArrayList(Arrays.asList(H6_1, H6_2, H6_3)), null, 2); + + + //LEVEL 3 + KPI H15_1 = buildKPI("H15_1", "Vaccinated fish against P. damselae - at 2400dd (%)", "", null, null, 3); + KPI H15_2 = buildKPI("H15_2", "Vaccinated fish against V. anguillarum - at 2400dd (%)", "", null, null, 3); + KPI H15_3 = buildKPI("H15_3", "Vaccinated fish against Betanodavirus - at 2400dd (%)", "", null, null, 3); + //LEVEL 2 + KPI Vaccinatedfishbydisease = buildKPI("", "Vaccinated fish by disease", "", new ArrayList(Arrays.asList(H15_1, H15_2, H15_3)), null, 2); + + + //LEVEL 1 + KPI Deformities = buildKPI("", "Hatchery Total Productivity KPIs", "", new ArrayList(Arrays.asList( + Weanedfish, Discardeddeformedfish, Discardedslowgrowerfish, FishProduced, FishproducedperFTEemployees, Survivalestimation, Vaccinatedfishbydisease)), batchType, 1); + + return Deformities; + } + + + + /** + * + * OK + * Gets the fish deformities kp isfor hatcher y_ individual. + * + * @param batchType the batch type + * @return the fish deformities kp isfor hatcher y_ individual + */ + public static KPI getFishDeformitiesKPIsforHATCHERY_INDIVIDUAL(PopulationType batchType){ + + //LEVEL 3 + KPI H7_1 = buildKPI("H7_1", "Alive fish with head deformities - at 2400dd (%)", "", null, null, 3); + KPI H7_2 = buildKPI("H7_2", "Alive fish with head deformities - at end of weaning (%)", "", null, null, 3); + //LEVEL 2 + KPI Headdeformities = buildKPI("", "Head deformities", "", new ArrayList(Arrays.asList(H7_1, H7_2)), null, 2); + + //LEVEL 3 + KPI H8 = buildKPI("H8", "Alive fish with spinal deformities - at 2400dd (%)", "", null, null, 3); + KPI H8_1 = buildKPI("H8_1", "Alive fish with spinal deformities - at end of weaning (%)", "", null, null, 3); + //LEVEL 2 + KPI Spinaldeformities = buildKPI("", "Spinal deformities", "", new ArrayList(Arrays.asList(H8, H8_1)), null, 2); + + //LEVEL 3 + KPI H9 = buildKPI("H9", "Alive fish with fin deformities - at 2400dd (%)", "", null, null, 3); + KPI H9_1 = buildKPI("H9_1", "Alive fish with fin deformities - at end of weaning (%)", "", null, null, 3); + //LEVEL 2 + KPI Findeformities = buildKPI("", "Fin deformities", "", new ArrayList(Arrays.asList(H9, H9_1)), null, 2); + + //LEVEL 3 + KPI H10 = buildKPI("H10", "Swim bladder non inflation - at 500dd (%)", "", null, null, 3); + //LEVEL 2 + KPI Swimbladdernoninflation = buildKPI("", "Swim bladder non inflation", "", new ArrayList(Arrays.asList(H10)), null, 2); + + //LEVEL 1 + KPI Deformities = buildKPI("", "Fish Deformities KPIs", "", new ArrayList(Arrays.asList( + Headdeformities, Spinaldeformities, Findeformities, Swimbladdernoninflation)), batchType, 1); + + return Deformities; + } + + + /** + * OK + * Gets the fish growth kp isfor hatcher y_ individual. + * + * @param batchType the batch type + * @return the fish growth kp isfor hatcher y_ individual + */ + public static KPI getFishGrowthKPIsforHATCHERY_INDIVIDUAL(PopulationType batchType){ + + //LEVEL 3 + KPI H11_1 = buildKPI("H11_1", "Average body weight (BW) - at weaning (g)", "", null, null, 3); + KPI H11_2 = buildKPI("H11_2", "Average body weight (BW) - at 1200dd (g)", "", null, null, 3); + KPI H11_3 = buildKPI("H11_3", "Average body weight (BW) - at 1800dd (g)", "", null, null, 3); + KPI H11_4 = buildKPI("H11_4", "Average body weight (BW) - at 2400dd (g)", "", null, null, 3); + //LEVEL 2 + KPI AverageBodyWeightABW = buildKPI("", "Average Body Weight (ABW)", "", new ArrayList(Arrays.asList(H11_1, H11_2, H11_3, H11_4)), null, 2); + + + //LEVEL 3 + KPI H12_1 = buildKPI("H12_1", "Specific Growth Rate (SGR) - at 1200dd (% day^-1)", "", null, null, 3); + KPI H12_2 = buildKPI("H12_2", "Specific Growth Rate (SGR) - at 1800dd (% day^-1)", "", null, null, 3); + KPI H12_3 = buildKPI("H12_3", "Specific Growth Rate (SGR) - at 2400dd (% day^-1)", "", null, null, 3); + //LEVEL 2 + KPI SpecificGrowthRateSGR = buildKPI("", "Specific Growth Rate (SGR)", "", new ArrayList(Arrays.asList(H12_1, H12_2, H12_3)), null, 2); + + + KPI FishGrowthKPIs = buildKPI("", "Fish Growth KPIs", "", new ArrayList(Arrays.asList( + AverageBodyWeightABW, SpecificGrowthRateSGR)), batchType, 1); + + return FishGrowthKPIs; + } + + + + /** + * Gets the live feed requirement kp isfor hatcher y_ individual. + * + * @param batchType the batch type + * @return the live feed requirement kp isfor hatcher y_ individual + */ + public static KPI getLiveFeedRequirementKPIsforHATCHERY_INDIVIDUAL(PopulationType batchType){ + + //LEVEL 3 + KPI H13 = buildKPI("H13", "Artemia requirement - at 2400dd (Kg of Artemia/million fish)", "", null, null, 3); + //LEVEL 2 + KPI Artemiarequirement = buildKPI("", "Artemia requirement", "", new ArrayList(Arrays.asList(H13)), null, 2); + + //LEVEL 3 + KPI H14 = buildKPI("H14", "Rotifers requirement - at 2400dd (Billions rotifer/million fish)", "", null, null, 3); + + //LEVEL 2 + KPI Rotiferrequirement = buildKPI("", "Rotifer requirement", "", new ArrayList(Arrays.asList(H14)), null, 2); + + KPI FishGrowthKPIs = buildKPI("", "Live Feed Requirement KPIs", "", new ArrayList(Arrays.asList( + Artemiarequirement, Rotiferrequirement)), batchType, 1); + + return FishGrowthKPIs; + } + + + /** + * Gets the losses. + * + * @param batchType the batch type + * @return the losses + */ + public static KPI getLosses(PopulationType batchType){ + //LEVEL 3 - G1 + KPI G1 = buildKPI("G1", "Mortalities - Total (at harvest) %", "", null, null, 3); + KPI G1_1 = buildKPI("G1_1", "Mortalities - Total (Stocking-50g) %", "", null, null, 3); + KPI G1_2 = buildKPI("G1_2", "Mortalities - Total (50g-150g) %", "", null, null, 3); + KPI G1_3 = buildKPI("G1_3", "Mortalities - Total (150g-250g) %", "", null, null, 3); + KPI G1_4 = buildKPI("G1_4", "Mortalities - Total (250g-400g) %", "", null, null, 3); + KPI G1_5 = buildKPI("G1_5", "Mortalities - Total (400g-800g-final harvest) %", "", null, null, 3); + //LEVEL 2 - G1 + KPI Mortality_Total = buildKPI("", "Mortality - Total", "", new ArrayList(Arrays.asList(G1, G1_1, G1_2, G1_3, G1_4, G1_5)), null, 2); + + //LEVEL 3 - G2 + KPI G2 = buildKPI("G2", "Mortalities - by disease Total (at harvest) %", "", null, null, 3); + KPI G2_1 = buildKPI("G2_1", "Mortalities - by disease (Stocking-50g) %", "", null, null, 3); + KPI G2_2 = buildKPI("G2_2", "Mortalities - by disease (50g-150g) %", "", null, null, 3); + KPI G2_3 = buildKPI("G2_3", "Mortalities - by disease (150g-250g) %", "", null, null, 3); + KPI G2_4 = buildKPI("G2_4", "Mortalities - by disease (250g-400g) %", "", null, null, 3); + KPI G2_5 = buildKPI("G2_5", "Mortalities - by disease (400g-800g-final harvest) %", "", null, null, 3); + + + //LEVEL 2 - G2 + KPI Mortality_by_disease = buildKPI("", "Mortality by disease", "", new ArrayList(Arrays.asList(G2, G2_1, G2_2, G2_3, G2_4, G2_5)), null, 2); + + //LEVEL 2 + KPI G3 = buildKPI("G3", "Mortalities first 3 days after transport and stocking %", "", null, null, 2); + KPI G4 = buildKPI("G4", "Mortalities first 10 days after transport and stocking %", "", null, null, 2); + KPI G5 = buildKPI("G5", "Unaccounted losses %", "", null, null, 2); + KPI G6 = buildKPI("G3", "Total losses %", "", null, null, 2); + KPI G7 = buildKPI("G7", "Discarded fish at slaughter %", "", null, null, 2); + + //LEVEL 1 - Losses + KPI Losses = buildKPI("", "Losses", "", new ArrayList(Arrays.asList(Mortality_Total, Mortality_by_disease, G3, G4, G5, G6, G7)), batchType, 1); + + return Losses; + } + + + /** + * Gets the treatments for grow out individual. + * + * @param batchType the batch type + * @return the treatments for grow out individual + */ + public static KPI getTreatmentsForGrowOutIndividual(PopulationType batchType){ + //LEVEL 2 - G8_X and G9 and G10 + KPI G8_1 = buildKPI("G8_1", "Vaccinated fish by disease (P. damselae) %", "", null, null, 2); + KPI G8_2 = buildKPI("G8_2", "Vaccinated fish by disease (V. Anguillarum) %", "", null, null, 2); + KPI G8_3 = buildKPI("G8_3", "Vaccinated fish by disease (Betanodavirus) %", "", null, null, 2); + KPI G9 = buildKPI("G9", "Number of antiparasitic treatments", "", null, null, 2); + KPI G10 = buildKPI("G10", "Number of antibiotic treatments", "", null, null, 2); + + //LEVEL 1 - Treatments + KPI Treatments = buildKPI("", "Treatments", "", new ArrayList(Arrays.asList(G8_1, G8_2, G8_3, G9, G10)), batchType, 1); + + return Treatments; + } + + + /** + * Gets the growth for grow out individual. + * + * @param batchType the batch type + * @return the growth for grow out individual + */ + public static KPI getGrowthForGrowOutIndividual(PopulationType batchType){ + //########## Growth + //LEVEL 3 - G13_X + KPI G13_1 = buildKPI("G13_1", "Specific growth rate (SGR) (50g-150g) %", "", null, null, 3); + KPI G13_2 = buildKPI("G13_2", "Specific growth rate (SGR) (150g-250g) %", "", null, null, 3); + KPI G13_3 = buildKPI("G13_3", "Specific growth rate (SGR) (250g-400g) %", "", null, null, 3); + KPI G13_4 = buildKPI("G13_4", "Specific growth rate (SGR) (400g-800g) %", "", null, null, 3); + //LEVEL 2 - G13_X + KPI Specific_growth_rate = buildKPI("", "Specific growth rate", "", new ArrayList(Arrays.asList(G13_1, G13_2, G13_3, G13_4)), null, 2); + + //LEVEL 3 - G14_X + KPI G14_1 = buildKPI("G14_1", "Grams per day (GPD) (50g-150g) %", "", null, null, 3); + KPI G14_2 = buildKPI("G14_2", "Grams per day (GPD) (150g-250g) %", "", null, null, 3); + KPI G14_3 = buildKPI("G14_3", "Grams per day (GPD) (250g-400g) %", "", null, null, 3); + KPI G14_4 = buildKPI("G14_4", "Grams per day (GPD) (400g-800g) %", "", null, null, 3); + //LEVEL 2 - G14_X + KPI Grams_per_day = buildKPI("", "Grams per day", "", new ArrayList(Arrays.asList(G14_1, G14_2, G14_3, G14_4)), null, 2); + + //LEVEL 3 - G15_X + KPI G15_1 = buildKPI("G15_1", "Thermal Growth Coefficient (TGC) (50g-150g) %", "", null, null, 3); + KPI G15_2 = buildKPI("G15_2", "Thermal Growth Coefficient (TGC) (150g-250g) %", "", null, null, 3); + KPI G15_3 = buildKPI("G15_3", "Thermal Growth Coefficient (TGC) (250g-400g) %", "", null, null, 3); + KPI G15_4 = buildKPI("G15_4", "Thermal Growth Coefficient (TGC) (400g-800g) %", "", null, null, 3); + //LEVEL 2 - G15_X + KPI Thermal_Growth = buildKPI("", "Thermal Growth", "", new ArrayList(Arrays.asList(G15_1, G15_2, G15_3, G15_4)), null, 2); + + //LEVEL 1 + KPI Growth = buildKPI("", "Growth", "", new ArrayList(Arrays.asList(Specific_growth_rate, Grams_per_day, Thermal_Growth)), batchType, 1); + + return Growth; + } + + + /** + * Gets the efficiency. + * + * @param batchType the batch type + * @return the efficiency + */ + public static KPI getEfficiency(PopulationType batchType){ + //########## Efficiency + //LEVEL 3 - G16_X + KPI G16_1 = buildKPI("G16_1", "Feed Conversion Ratio (FCR) (50g-150g) %", "", null, null, 3); + KPI G16_2 = buildKPI("G16_2", "Feed Conversion Ratio (FCR) (150g-250g) %", "", null, null, 3); + KPI G16_3 = buildKPI("G16_3", "Feed Conversion Ratio (FCR) (250g-400g) %", "", null, null, 3); + KPI G16_4 = buildKPI("G16_4", "Feed Conversion Ratio (FCR) (400g-800g-final harvest) %", "", null, null, 3); + KPI G16 = buildKPI("G16", "Feed Conversion Ratio (FCR) (harvest) %", "", null, null, 3); + //LEVEL 2 - G16_X + KPI Feed_Conversion_Ratio = buildKPI("", "Feed Conversion Ratio", "", new ArrayList(Arrays.asList(G16_1, G16_2, G16_3, G16_4, G16)), null, 2); + + //LEVEL 3 - G17_X + KPI G17_1 = buildKPI("G17_1", "Biological Feed Conversion Ratio (FCRBIO) (50g-150g) %", "", null, null, 3); + KPI G17_2 = buildKPI("G17_2", "Biological Feed Conversion Ratio (FCRBIO) (150g-250g) %", "", null, null, 3); + KPI G17_3 = buildKPI("G17_3", "Biological Feed Conversion Ratio (FCRBIO) (250g-400g) %", "", null, null, 3); + KPI G17_4 = buildKPI("G17_4", "Feed Conversion Ratio (FCR) (400g-800g-final harvest) %", "", null, null, 3); + //LEVEL 2 - G14_X + KPI Biological_Feed_Conversion_Ratio = buildKPI("", "Biological Feed Conversion Ratio", "", new ArrayList(Arrays.asList(G17_1, G17_2, G17_3, G17_4)), null, 2); + + //LEVEL 3 - G18_X + KPI G18_1 = buildKPI("G18_1", "Feed Intake (FI) (50g-150g) %", "", null, null, 3); + KPI G18_2 = buildKPI("G18_2", "Feed Intake (FI) (150g-250g) %", "", null, null, 3); + KPI G18_3 = buildKPI("G18_3", "Feed Intake (FI) (250g-400g) %", "", null, null, 3); + KPI G18_4 = buildKPI("G18_4", "Feed Intake (FI) (400g-800g-final harvest) %", "", null, null, 3); + //LEVEL 2 - G18_X + KPI Feed_Intake = buildKPI("", "Feed Intake", "", new ArrayList(Arrays.asList(G18_1, G18_2, G18_3, G18_4)), null, 2); + + //LEVEL 2 - G19 + KPI Stocking_density = buildKPI("G19", "Stocking density", "",null, null, 2); + + //LEVEL 1 + KPI Efficiency = buildKPI("", "Efficiency", "", new ArrayList(Arrays.asList(Feed_Conversion_Ratio, Biological_Feed_Conversion_Ratio, Feed_Intake, Stocking_density)), batchType, 1); + + return Efficiency; + } + + + + + /** + * Gets the productivity. + * + * @param batchType the batch type + * @return the productivity + */ + public static KPI getProductivityForHATCHERY_INDIVIDUAL(PopulationType batchType){ + //LEVEL 2 - H1 + KPI H1 = buildKPI("H1", "Weaned fish %", "",null, null, 2); + + //LEVEL 3 H4 and H5_1_X + KPI H5_1_1 = buildKPI("H5_1_1", "Fish produced per FTE employees (at 2400dd) % in 2018", "", null, null, 3); + KPI H5_1_2 = buildKPI("H5_1_2", "Fish produced per FTE employees (at 2400dd) % in 2019", "", null, null, 3); + KPI H5_1_3 = buildKPI("H5_1_3", "Fish produced per FTE employees (at 2400dd) % in 2020", "", null, null, 3); + KPI H4 = buildKPI("H4", "Fish produced (at the end of cycle) %", "", null, null, 3); + //LEVEL 2 - Produced_fish + KPI Produced_fish = buildKPI("", "Produced fish", "", new ArrayList(Arrays.asList(H5_1_1, H5_1_2, H5_1_3, H4)), null, 2); + + KPI H13 = buildKPI("H13", "Artemia requirement (at the end of weaning)", "",null, null, 2); + KPI H14 = buildKPI("H14", "Rotifer requirement (at the end of weaning)", "",null, null, 2); + + //LEVEL 1 + KPI Productivity = buildKPI("", "Productivity", "", new ArrayList(Arrays.asList(H1, Produced_fish, H13, H14)), batchType, 1); + + return Productivity; + } + + + /** + * Gets the growth for hatchery individual. + * + * @param batchType the batch type + * @return the growth for hatchery individual + */ + public static KPI getGrowthForHATCHERY_INDIVIDUAL(PopulationType batchType){ + + //LEVEL 3 - H11_X + KPI H11_1 = buildKPI("H11_1", "Average Body Weight (ABW) at end of weaning", "", null, null, 3); + KPI H11_2 = buildKPI("H11_2", "Average Body Weight (ABW) at 1200dd", "", null, null, 3); + KPI H11_3 = buildKPI("H11_3", "Average Body Weight (ABW) at 1800dd", "", null, null, 3); + KPI H11_4 = buildKPI("H11_4", "Average Body Weight (ABW) at 2400dd", "", null, null, 3); + //LEVEL 2 - Body_weight + KPI Body_weight = buildKPI("", "Body weight", "", new ArrayList(Arrays.asList(H11_1, H11_2, H11_3, H11_4)), null, 2); + + //LEVEL 3 - H12_X + KPI H12_1 = buildKPI("H12_1", "Specific Growth Rate (SGR) at 1200dd", "", null, null, 3); + KPI H12_2 = buildKPI("H12_2", "Specific Growth Rate (SGR) at 1800dd", "", null, null, 3); + KPI H12_3 = buildKPI("H12_3", "Specific Growth Rate (SGR) at 2400dd", "", null, null, 3); + //LEVEL 2 - Specific_growth_rate + KPI Specific_growth_rate = buildKPI("", "Specific growth rate", "", new ArrayList(Arrays.asList(H12_1, H12_2, H12_3)), null, 2); + + //LEVEL 1 + KPI Growth = buildKPI("", "Growth", "", new ArrayList(Arrays.asList(Body_weight, Specific_growth_rate)), batchType, 1); + + return Growth; + } + + + /** + * Gets the survival discard rates. + * + * @param batchType the batch type + * @return the survival discard rates + */ + public static KPI getSurvivalDiscardRatesForHATCHERY_INDIVIDUAL(PopulationType batchType){ + //LEVEL 3 - H3_X + KPI H3_1 = buildKPI("H3_1", "Discarded slow grower fish % at 1200dd", "", null, null, 3); + KPI H3_2 = buildKPI("H3_2", "Discarded slow grower fish % at 1800dd", "", null, null, 3); + KPI H3_3 = buildKPI("H3_3", "Discarded slow grower fish % at 2400dd", "", null, null, 3); + //LEVEL 2 - Discarded + KPI Discarded = buildKPI("", "Discarded", "", new ArrayList(Arrays.asList(H3_1, H3_2, H3_3)), null, 2); + + //LEVEL 3 - H12_X + KPI H6_1 = buildKPI("H6_1", "Survival estimation % at 1200dd", "", null, null, 3); + KPI H6_2 = buildKPI("H6_2", "Survival estimation % at 1800dd", "", null, null, 3); + KPI H6_3 = buildKPI("H6_3", "Survival estimation % at 2400dd", "", null, null, 3); + //LEVEL 2 - Survival + KPI Survival = buildKPI("", "Survival", "", new ArrayList(Arrays.asList(H6_1, H6_2, H6_3)), null, 2); + + //LEVEL 1 + KPI Survival_Discard_rates = buildKPI("", "Survival/Discard rates", "", new ArrayList(Arrays.asList(Discarded, Survival)), batchType, 1); + + return Survival_Discard_rates; + } + + + /** + * Gets the treatments for hatchery individual. + * + * @param batchType the batch type + * @return the treatments for hatchery individual + */ + public static KPI getTreatmentsForHATCHERY_INDIVIDUAL(PopulationType batchType){ + //LEVEL 3 - H15_X + KPI H15_1 = buildKPI("H15_1", "Vaccinated fish by disease (at 2400dd) % against P. Damselae", "", null, null, 2); + KPI H15_2 = buildKPI("H15_2", "Vaccinated fish by disease (at 2400dd) % against V. Anguillarum", "", null, null, 2); + KPI H15_3 = buildKPI("H15_3", "Vaccinated fish by disease (at 2400dd) % against Betanodavirus", "", null, null, 2); + //LEVEL 2 - Discarded + KPI Treatments = buildKPI("", "Treatments", "", new ArrayList(Arrays.asList(H15_1, H15_2, H15_3)), batchType, 1); + + return Treatments; + } + + + /** + * Gets the deformities for hatcher y_ aggregated. + * + * @param batchType the batch type + * @return the deformities for hatcher y_ aggregated + */ + public static KPI getDeformitiesForHATCHERY_AGGREGATED(PopulationType batchType) { + + //LEVEL 3 - H7 and H2_1_3 + KPI H7 = buildKPI("H7", "Head deformities (at 2400dd) %", "", null, null, 3); + KPI H2_1_3 = buildKPI("H2_1_3", "ead deformed fish % at 2400dd", "", null, null, 3); + //LEVEL 2 - Head + KPI Head = buildKPI("", "Head", "", new ArrayList(Arrays.asList(H7, H2_1_3)), null, 2); + + //LEVEL 3 - H8 and H2_2_3 + KPI H8 = buildKPI("H8", "Spinal deformities (at 2400dd) %", "", null, null, 3); + KPI H2_2_3 = buildKPI("H2_2_3", "Spinal deformed fish % at 2400dd", "", null, null, 3); + + //LEVEL 2 - Spinal + KPI Spinal = buildKPI("", "Spinal", "", new ArrayList(Arrays.asList(H8, H2_2_3)), null, 2); + + //LEVEL 3 - H9 and H2_3_3 + KPI H9 = buildKPI("H9", "Fin deformities (at 2400dd) %", "", null, null, 3); + KPI H2_3_3 = buildKPI("H2_3_3", "Fin deformed fish % at 2400dd", "", null, null, 3); + //LEVEL 2 - G18_X + KPI Fin = buildKPI("", "Fin", "", new ArrayList(Arrays.asList(H9, H2_3_3)), null, 2); + + //LEVEL 2 - H10 + KPI H10 = buildKPI("H10", "Swim bladder non inflation (at 500dd)", "",null, null, 2); + + //LEVEL 1 + KPI Deformities = buildKPI("", "Deformities", "", new ArrayList(Arrays.asList(Head, Spinal, Fin, H10)), batchType, 1); + + return Deformities; + } + + + /** + * Gets the productivity for hatcher y_ aggregated. + * + * @param batchType the batch type + * @return the productivity for hatcher y_ aggregated + */ + public static KPI getProductivityForHATCHERY_AGGREGATED(PopulationType batchType) { + + //LEVEL 2 - H1 + KPI H1 = buildKPI("H1", "Weaned fish %", "",null, null, 2); + + //LEVEL 3 H4 and H5_1_X + KPI H4 = buildKPI("H4", "Fish produced at 2400dd %", "", null, null, 3); + KPI H5_1_1 = buildKPI("H5_1_1", "Fish produced per FTE employees (at 2400dd) % in 2018", "", null, null, 3); + KPI H5_1_2 = buildKPI("H5_1_2", "Fish produced per FTE employees (at 2400dd) % in 2019", "", null, null, 3); + KPI H5_1_3 = buildKPI("H5_1_3", "Fish produced per FTE employees (at 2400dd) % in 2020", "", null, null, 3); + //LEVEL 2 - Produced_fish + KPI Produced_fish = buildKPI("", "Produced fish", "", new ArrayList(Arrays.asList(H4, H5_1_1, H5_1_2, H5_1_3)), null, 2); + + KPI H13 = buildKPI("H13", "Artemia requirement (at the end of weaning)", "",null, null, 2); + KPI H14 = buildKPI("H14", "Rotifer requirement (at the end of weaning)", "",null, null, 2); + + //LEVEL 1 + KPI Productivity = buildKPI("", "Productivity", "", new ArrayList(Arrays.asList(H1, Produced_fish, H13, H14)), batchType, 1); + + return Productivity; + } + + + /** + * Gets the survival discard rates for hatcher y_ aggregated. + * + * @param batchType the batch type + * @return the survival discard rates for hatcher y_ aggregated + */ + public static KPI getSurvivalDiscardRatesForHATCHERY_AGGREGATED(PopulationType batchType) { + + //LEVEL 3 - H3_3 + KPI H3_3 = buildKPI("H3_3", "Discarded slow grower fish % at 2400dd", "", null, null, 3); + //LEVEL 2 - Discarded + KPI Discarded = buildKPI("", "Discarded", "", new ArrayList(Arrays.asList(H3_3)), null, 2); + + //LEVEL 3 - H6 + KPI H6 = buildKPI("H6", "Survival estimation % at 2400dd", "", null, null, 3); + //LEVEL 2 - Survival + KPI Survival = buildKPI("", "Survival", "", new ArrayList(Arrays.asList(H6)), null, 2); + + //LEVEL 1 + KPI Survival_Discard_rates = buildKPI("", "Survival/Discard rates", "", new ArrayList(Arrays.asList(Discarded, Survival)), batchType, 1); + + return Survival_Discard_rates; + } + + + /** + * Gets the treatments for hatcher y_ aggregated. + * + * @param batchType the batch type + * @return the treatments for hatcher y_ aggregated + */ + public static KPI getTreatmentsForHATCHERY_AGGREGATED(PopulationType batchType) { + + //LEVEL 3 - H15_X + KPI H15_1 = buildKPI("H15_1", "Vaccinated fish by disease (at 2400dd) % against P. Damselae", "", null, null, 2); + KPI H15_2 = buildKPI("H15_2", "Vaccinated fish by disease (at 2400dd) % against V. Anguillarum", "", null, null, 2); + KPI H15_3 = buildKPI("H15_3", "Vaccinated fish by disease (at 2400dd) % against Betanodavirus", "", null, null, 2); + //LEVEL 2 - Discarded + KPI Treatments = buildKPI("", "Treatments", "", new ArrayList(Arrays.asList(H15_1, H15_2, H15_3)), batchType, 1); + + return Treatments; + } + + + + /** + * Gets the losses for gro w_ ou t_ aggregated. + * + * @param batchType the batch type + * @return the losses for gro w_ ou t_ aggregated + */ + public static KPI getLossesForGROW_OUT_AGGREGATED(PopulationType batchType) { + + //LEVEL 3 - G1_X + KPI G1 = buildKPI("G1", "Mortalities - Total (at harvest) %", "", null, null, 3); + KPI G1_1 = buildKPI("G1_1", "Mortalities - Total (Stocking-150g) %", "", null, null, 3); + KPI G1_4 = buildKPI("G1_4", "Mortalities - Total (150g-400g) %", "", null, null, 3); + KPI G1_5 = buildKPI("G1_5", "Mortalities - Total (400g-800g-final harvest) %", "", null, null, 3); + //LEVEL 2 - G1 + KPI Mortality_Total = buildKPI("", "Mortality - Total", "", new ArrayList(Arrays.asList(G1, G1_1, G1_4, G1_5)), null, 2); + + //LEVEL 3 - G2 + KPI G2 = buildKPI("G2", "Mortalities - by disease Total (at harvest) %", "", null, null, 3); + KPI G2_1 = buildKPI("G2_1", "Mortalities - by disease (Stocking-150g) %", "", null, null, 3); + KPI G2_4 = buildKPI("G2_4", "Mortalities - by disease (250g-400g) %", "", null, null, 3); + KPI G2_5 = buildKPI("G2_5", "Mortalities - by disease (400g-800g-final harvest) %", "", null, null, 3); + + //LEVEL 2 - G2 + KPI Mortality_by_disease = buildKPI("", "Mortality by disease", "", new ArrayList(Arrays.asList(G2, G2_1, G2_4, G2_5)), null, 2); + + //LEVEL 2 + KPI G3 = buildKPI("G3", "Mortalities first 3 days after transport and stocking %", "", null, null, 2); + KPI G4 = buildKPI("G4", "Mortalities first 10 days after transport and stocking %", "", null, null, 2); + KPI G5 = buildKPI("G5", "Unaccounted losses %", "", null, null, 2); + KPI G6 = buildKPI("G3", "Total losses %", "", null, null, 2); + KPI G7 = buildKPI("G7", "Discarded fish at slaughter %", "", null, null, 2); + + //LEVEL 1 - Losses + KPI Losses = buildKPI("", "Losses", "", new ArrayList(Arrays.asList(Mortality_Total, Mortality_by_disease, G3, G4, G5, G6, G7)), batchType, 1); + + return Losses; + } + + + /** + * Gets the treatments for gro w_ ou t_ aggregated. + * + * @param batchType the batch type + * @return the treatments for gro w_ ou t_ aggregated + */ + public static KPI getTreatmentsForGROW_OUT_AGGREGATED(PopulationType batchType) { + + //LEVEL 3 - G8_X + KPI G8_1 = buildKPI("G8_1", "Vaccinated fish by disease (P. damselae) %", "", null, null, 2); + KPI G8_2 = buildKPI("G8_2", "Vaccinated fish by disease (V. Anguillarum) %", "", null, null, 2); + KPI G8_3 = buildKPI("G8_3", "Vaccinated fish by disease (Betanodavirus) %", "", null, null, 2); + //LEVEL 2 - Treatments + KPI Treatments = buildKPI("", "Treatments", "", new ArrayList(Arrays.asList(G8_1, G8_2, G8_3)), batchType, 1); + + return Treatments; + } + + + /** + * Gets the growth for gro w_ ou t_ aggregated. + * + * @param batchType the batch type + * @return the growth for gro w_ ou t_ aggregated + */ + public static KPI getGrowthForGROW_OUT_AGGREGATED(PopulationType batchType) { + + //LEVEL 3 - G13_X + KPI G13_3 = buildKPI("G13_3", "Specific growth rate (SGR) (150g-400g) %", "", null, null, 3); + KPI G13_4 = buildKPI("G13_4", "Specific growth rate (SGR) (400g-800g) %", "", null, null, 3); + //LEVEL 2 - pecific growth rate + KPI Body_weight = buildKPI("", "Specific growth rate", "", new ArrayList(Arrays.asList(G13_3, G13_4)), null, 2); + + //LEVEL 3 - G14_X + KPI G14_3 = buildKPI("G14_3", "Grams per day (GPD) (150g-400g) %", "", null, null, 3); + KPI G14_4 = buildKPI("G14_4", "Grams per day (GPD) (400g-800g) %", "", null, null, 3); + //LEVEL 2 - Specific_growth_rate + KPI Grams_per_day = buildKPI("", "Grams per day", "", new ArrayList(Arrays.asList(G14_3, G14_4)), null, 2); + + //LEVEL 1 + KPI Growth = buildKPI("", "Growth", "", new ArrayList(Arrays.asList(Body_weight, Grams_per_day)), batchType, 1); + + return Growth; + + } + + + /** + * Gets the efficiency for gro w_ ou t_ aggregated. + * + * @param batchType the batch type + * @return the efficiency for gro w_ ou t_ aggregated + */ + public static KPI getEfficiencyForGROW_OUT_AGGREGATED(PopulationType batchType) { + + //########## Efficiency + //LEVEL 3 - G16_X + KPI G16_3 = buildKPI("G16_3", "Feed Conversion Ratio (FCR) (150g-400g) %", "", null, null, 3); + KPI G16_4 = buildKPI("G16_4", "Feed Conversion Ratio (FCR) (400g-800g-final harvest) %", "", null, null, 3); + KPI G16 = buildKPI("G16", "Feed Conversion Ratio (FCR) (harvest) %", "", null, null, 3); + //LEVEL 2 - G16_X + KPI Feed_Conversion_Ratio = buildKPI("", "Feed Conversion Ratio", "", new ArrayList(Arrays.asList(G16_3, G16_4, G16)), null, 2); + + //LEVEL 3 - G17_X + KPI G17_3 = buildKPI("G17_3", "Biological Feed Conversion Ratio (FCRBIO) (150g-400g) %", "", null, null, 3); + KPI G17_4 = buildKPI("G17_4", "Biological Feed Conversion Ratio (FCRBIO) (400g-800g-final harvest) %", "", null, null, 3); + //LEVEL 2 - G14_X + KPI Biological_Feed_Conversion_Ratio = buildKPI("", "Biological Feed Conversion Ratio", "", new ArrayList(Arrays.asList(G17_3, G17_4)), null, 2); + + //LEVEL 3 - G18_X + KPI G18_3 = buildKPI("G18_3", "Feed Intake (FI) (150g-400g) %", "", null, null, 3); + KPI G18_4 = buildKPI("G18_4", "Feed Intake (FI) (400g-800g-final harvest) %", "", null, null, 3); + //LEVEL 2 - G18_X + KPI Feed_Intake = buildKPI("", "Feed Intake", "", new ArrayList(Arrays.asList(G18_3, G18_4)), null, 2); + + //LEVEL 2 - G19 + KPI Stocking_density = buildKPI("G19", "Stocking density", "",null, null, 2); + + //LEVEL 1 + KPI Efficiency = buildKPI("", "Efficiency", "", new ArrayList(Arrays.asList(Feed_Conversion_Ratio, Biological_Feed_Conversion_Ratio, Feed_Intake, Stocking_density)), batchType, 1); + + return Efficiency; + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/PeriodData.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/PeriodData.java new file mode 100644 index 0000000..bbdd269 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/PeriodData.java @@ -0,0 +1,49 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util.database.data; + +import java.util.ArrayList; +import java.util.List; + +import org.gcube.portlets.user.performfishanalytics.server.util.database.FillDatabasePerBatchType.BATCH_LEVEL; +import org.gcube.portlets.user.performfishanalytics.shared.Period; +import org.gcube.portlets.user.performfishanalytics.shared.PopulationType; + + + +/** + * The Class PeriodData. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 15, 2019 + */ +public class PeriodData { + + + /** + * Gets the list periods. + * + * @param batchType the batch type + * @return the list periods + */ + public static ArrayList getListPeriods(PopulationType batchType){ + + List listPeriod = new ArrayList(); + if(batchType.getName().startsWith(BATCH_LEVEL.PRE_ONGROWING.name()) || batchType.getName().startsWith(BATCH_LEVEL.PRE_ONGROWING_CLOSED_BATCHES.name())){ + listPeriod.add(new Period(java.util.UUID.randomUUID().toString(), "early", "", batchType)); + listPeriod.add(new Period(java.util.UUID.randomUUID().toString(), "natural", "", batchType)); + listPeriod.add(new Period(java.util.UUID.randomUUID().toString(), "late", "", batchType)); + }else if(batchType.getName().startsWith(BATCH_LEVEL.HATCHERY_INDIVIDUAL.name()) || batchType.getName().startsWith(BATCH_LEVEL.HATCHERY_INDIVIDUAL_CLOSED_BATCHES.name())){ + listPeriod.add(new Period(java.util.UUID.randomUUID().toString(), "natural", "", batchType)); + listPeriod.add(new Period(java.util.UUID.randomUUID().toString(), "late", "", batchType)); + listPeriod.add(new Period(java.util.UUID.randomUUID().toString(), "early", "", batchType)); + }else{ + listPeriod.add(new Period(java.util.UUID.randomUUID().toString(), "Early", "", batchType)); + listPeriod.add(new Period(java.util.UUID.randomUUID().toString(), "Natural", "", batchType)); + listPeriod.add(new Period(java.util.UUID.randomUUID().toString(), "Late", "", batchType)); + } + + return (ArrayList) listPeriod; + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/QuarterData.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/QuarterData.java new file mode 100644 index 0000000..016dae4 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/QuarterData.java @@ -0,0 +1,53 @@ +/** + * + */ + +package org.gcube.portlets.user.performfishanalytics.server.util.database.data; + +import java.util.ArrayList; +import java.util.List; + +import org.gcube.portlets.user.performfishanalytics.server.util.database.FillDatabasePerBatchType.BATCH_LEVEL; +import org.gcube.portlets.user.performfishanalytics.shared.PopulationType; +import org.gcube.portlets.user.performfishanalytics.shared.Quarter; + +/** + * The Class QuarterData. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Jan 15, 2019 + */ +public class QuarterData { + + /** + * Gets the list quarter. + * + * @param batchType + * the batch type + * @return the list quarter + */ + public static ArrayList getListQuarter(PopulationType batchType) { + + List listQuarter = new ArrayList(); + if (batchType.getName().startsWith(BATCH_LEVEL.GROW_OUT_AGGREGATED.name() )|| batchType.getName().startsWith(BATCH_LEVEL.GROW_OUT_AGGREGATED_CLOSED_BATCHES.name())) { + listQuarter.add(new Quarter( + java.util.UUID.randomUUID().toString(), "1st quarter", "", batchType)); + listQuarter.add(new Quarter( + java.util.UUID.randomUUID().toString(), "2nd quarter", "", batchType)); + listQuarter.add(new Quarter( + java.util.UUID.randomUUID().toString(), "3rd quarter", "", batchType)); + listQuarter.add(new Quarter( + java.util.UUID.randomUUID().toString(), "4th quarter", "", batchType)); + } + else { + listQuarter.add(new Quarter( + java.util.UUID.randomUUID().toString(), "1", "", batchType)); + listQuarter.add(new Quarter( + java.util.UUID.randomUUID().toString(), "2", "", batchType)); + listQuarter.add(new Quarter( + java.util.UUID.randomUUID().toString(), "3", "", batchType)); + listQuarter.add(new Quarter( + java.util.UUID.randomUUID().toString(), "4", "", batchType)); + } + return (ArrayList) listQuarter; + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/SpeciesData.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/SpeciesData.java new file mode 100644 index 0000000..e52bfee --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/database/data/SpeciesData.java @@ -0,0 +1,45 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util.database.data; + +import java.util.ArrayList; +import java.util.List; + +import org.gcube.portlets.user.performfishanalytics.server.util.database.FillDatabasePerBatchType.BATCH_LEVEL; +import org.gcube.portlets.user.performfishanalytics.shared.PopulationType; +import org.gcube.portlets.user.performfishanalytics.shared.Species; + + +/** + * The Class SpeciesData. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 17, 2019 + */ +public class SpeciesData { + + + /** + * Gets the list species. + * + * @param batchType the batch type + * @return the list species + */ + public static ArrayList getListSpecies(PopulationType batchType){ + + List listSpecies = new ArrayList(); + if(batchType.getName().startsWith(BATCH_LEVEL.PRE_ONGROWING.name()) || batchType.getName().startsWith(BATCH_LEVEL.PRE_ONGROWING_CLOSED_BATCHES.name())){ + + listSpecies.add(new Species(java.util.UUID.randomUUID().toString(), "S. aurata", "", batchType)); + listSpecies.add(new Species(java.util.UUID.randomUUID().toString(), "D. labrax", "", batchType)); + + }else{ + + listSpecies.add(new Species(java.util.UUID.randomUUID().toString(), "S.aurata", "", batchType)); + listSpecies.add(new Species(java.util.UUID.randomUUID().toString(), "D.labrax", "", batchType)); + } + + return (ArrayList) listSpecies; + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/dataminer/DMServiceResponse.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/dataminer/DMServiceResponse.java new file mode 100644 index 0000000..5ea922c --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/dataminer/DMServiceResponse.java @@ -0,0 +1,143 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util.dataminer; + +import java.util.List; + + +/** + * The Class DMResponse. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 24, 2019 + */ +public class DMServiceResponse { + + private boolean withError; + private String httpRequestURL; + private String bodyResponse; + private List listDMOutputData; + + + /** + * Instantiates a new DM service response. + * + * @param withError the with error + * @param httpRequestURL the http request url + * @param bodyResponse the body response + * @param listDMOutputData the list dm output data + */ + public DMServiceResponse(boolean withError, String httpRequestURL, String bodyResponse, List listDMOutputData) { + this.httpRequestURL = httpRequestURL; + this.withError = withError; + this.bodyResponse = bodyResponse; + this.listDMOutputData = listDMOutputData; + } + + + + /** + * @return the withError + */ + public boolean isWithError() { + + return withError; + } + + + + /** + * @return the httpRequestURL + */ + public String getHttpRequestURL() { + + return httpRequestURL; + } + + + + /** + * @return the bodyResponse + */ + public String getBodyResponse() { + + return bodyResponse; + } + + + + /** + * @return the listDMOutputData + */ + public List getListDMOutputData() { + + return listDMOutputData; + } + + + + /** + * @param withError the withError to set + */ + public void setWithError(boolean withError) { + + this.withError = withError; + } + + + + /** + * @param httpRequestURL the httpRequestURL to set + */ + public void setHttpRequestURL(String httpRequestURL) { + + this.httpRequestURL = httpRequestURL; + } + + + + /** + * @param bodyResponse the bodyResponse to set + */ + public void setBodyResponse(String bodyResponse) { + + this.bodyResponse = bodyResponse; + } + + + + /** + * @param listDMOutputData the listDMOutputData to set + */ + public void setListDMOutputData(List listDMOutputData) { + + this.listDMOutputData = listDMOutputData; + } + + + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("DMServiceResponse [withError="); + builder.append(withError); + builder.append(", httpRequestURL="); + builder.append(httpRequestURL); + builder.append(", bodyResponse="); + builder.append(bodyResponse); + builder.append(", listDMOutputData="); + builder.append(listDMOutputData); + builder.append("]"); + return builder.toString(); + } + + + + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/dataminer/DataMinerOutputData.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/dataminer/DataMinerOutputData.java new file mode 100644 index 0000000..2e93282 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/dataminer/DataMinerOutputData.java @@ -0,0 +1,161 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util.dataminer; + +import java.util.Map; + + +/** + * The Class DataMinerOutputData. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 24, 2019 + */ +public class DataMinerOutputData { + + private String fileDescription; + private String mimeType; + private String publicURL; + private Map dataMinerOutputData; + + /** + * Instantiates a new data miner output data. + */ + public DataMinerOutputData(){ + + } + + + /** + * Instantiates a new data miner output data. + * + * @param fileDescription the file description + * @param mimeType the mime type + * @param publicURL the public url + * @param dataMinerOutputData the data miner output data + */ + public DataMinerOutputData( + String fileDescription, String mimeType, String publicURL, + Map dataMinerOutputData) { + + super(); + this.fileDescription = fileDescription; + this.mimeType = mimeType; + this.publicURL = publicURL; + this.dataMinerOutputData = dataMinerOutputData; + } + + + + + /** + * Gets the file description. + * + * @return the fileDescription + */ + public String getFileDescription() { + + return fileDescription; + } + + + /** + * Gets the mime type. + * + * @return the mimeType + */ + public String getMimeType() { + + return mimeType; + } + + + /** + * Gets the public url. + * + * @return the publicURL + */ + public String getPublicURL() { + + return publicURL; + } + + + /** + * Gets the data miner output data. + * + * @return the dataMinerOutputData + */ + public Map getDataMinerOutputData() { + + return dataMinerOutputData; + } + + + /** + * Sets the file description. + * + * @param fileDescription the fileDescription to set + */ + public void setFileDescription(String fileDescription) { + + this.fileDescription = fileDescription; + } + + + /** + * Sets the mime type. + * + * @param mimeType the mimeType to set + */ + public void setMimeType(String mimeType) { + + this.mimeType = mimeType; + } + + + /** + * Sets the public url. + * + * @param publicURL the publicURL to set + */ + public void setPublicURL(String publicURL) { + + this.publicURL = publicURL; + } + + + /** + * Sets the data miner output data. + * + * @param dataMinerOutputData the dataMinerOutputData to set + */ + public void setDataMinerOutputData(Map dataMinerOutputData) { + + this.dataMinerOutputData = dataMinerOutputData; + } + + + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("DataMinerOutputData [fileDescription="); + builder.append(fileDescription); + builder.append(", mimeType="); + builder.append(mimeType); + builder.append(", publicURL="); + builder.append(publicURL); + builder.append(", dataMinerOutputData="); + builder.append(dataMinerOutputData); + builder.append("]"); + return builder.toString(); + } + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/tozipview/ZipExtractorUtil.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/tozipview/ZipExtractorUtil.java new file mode 100644 index 0000000..345a0bf --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/tozipview/ZipExtractorUtil.java @@ -0,0 +1,133 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util.tozipview; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; + +import javax.imageio.ImageIO; + +import org.apache.commons.compress.archivers.ArchiveEntry; +import org.apache.commons.compress.archivers.ArchiveInputStream; +import org.apache.commons.compress.archivers.ArchiveStreamFactory; +import org.apache.commons.io.IOUtils; +import org.apache.commons.io.output.ByteArrayOutputStream; +import org.gcube.portlets.user.performfishanalytics.shared.FileContentType; +import org.gcube.portlets.user.performfishanalytics.shared.OutputFile; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * The Class ZipExtractorUtil. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 24, 2019 + */ +public class ZipExtractorUtil { + + protected static Logger log = LoggerFactory.getLogger(ZipExtractorUtil.class); + + private List files = new ArrayList(); + + + /** + * Instantiates a new zip extractor util. + * + * @param theZipFileURL the the zip file url + * @param filter the filter. Extracts only the file of kind {@link FileContentType} passed as filter + * @throws Exception the exception + */ + public ZipExtractorUtil(String theZipFileURL, List filter) throws Exception{ + + log.info("Extracting with filter: "+filter); + + InputStream is = new URL(theZipFileURL).openConnection().getInputStream(); + + try (ArchiveInputStream input = new ArchiveStreamFactory() + .createArchiveInputStream(new BufferedInputStream(is, 1024*64))){ + ArchiveEntry entry; + while ((entry = input.getNextEntry()) != null) { + if(!entry.isDirectory()){ + try { + + String entirePath = entry.getName(); + String name = entirePath.replaceAll("(.*/)*(.*)", "$2"); + String parentPath = entirePath.replaceAll("(.*/)*(.*)", "$1"); + log.debug("read the file with entire path "+entirePath+", name "+name+", parentPath "+parentPath); + OutputFile file = new OutputFile(); + file.setName(name); + try{ + ByteArrayOutputStream cachedBytes = new ByteArrayOutputStream(); + IOUtils.copy(input, cachedBytes); + ByteArrayInputStream inputNew = new ByteArrayInputStream(cachedBytes.toByteArray()); + if(ImageIO.read(inputNew) == null){ + log.info("ImageIO of the file "+name+" is null. It is NOT an image"); + + if(name.endsWith("csv")){ + file.setDataType(FileContentType.CSV); + }else{ + file.setDataType(FileContentType.UNKNOWN); + } + + }else{ + file.setDataType(FileContentType.IMAGE); +// String encodedString = Base64.getEncoder().encodeToString(cachedBytes.toByteArray()); +// log.info("\n\nfile "+name+" as base64 is: "+encodedString); + } + + if(filter==null || filter.size() == 0 || filter.contains(file.getDataType())){ + File tempFile = createTempFile(file.getName(), "", cachedBytes.toByteArray()); + file.setServerLocation(tempFile.getAbsolutePath()); + files.add(file); + log.debug("Files extracted now are: {}",files); + } + + }catch(Exception e){ + log.info("extracting error ",e); + } + }catch(Exception e) { + log.warn("error getting file {}",entry.getName(),e); + } + } + + } + } + } + + /** + * Creates the temp file. + * + * @param fileName the file name + * @param extension the extension + * @param data the data + * @return the file + * @throws IOException Signals that an I/O exception has occurred. + */ + public static File createTempFile(String fileName, String extension, byte[] data) throws IOException { + // Since Java 1.7 Files and Path API simplify operations on files + java.nio.file.Path path = Files.createTempFile(fileName, extension); + File file = path.toFile(); + // writing sample data + Files.write(path, data); + log.info("Created the Temp File: "+file.getAbsolutePath()); + return file; + } + + /** + * Gets the output files. + * + * @return the output files + */ + public List getOutputFiles(){ + return files; + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/xml/NamespaceContextMap.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/xml/NamespaceContextMap.java new file mode 100644 index 0000000..f3d9081 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/xml/NamespaceContextMap.java @@ -0,0 +1,195 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util.xml; + +/** + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * @May 7, 2013 + * + */ +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.xml.XMLConstants; +import javax.xml.namespace.NamespaceContext; + + +/** + * The Class NamespaceContextMap. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 22, 2016 + */ +public final class NamespaceContextMap implements NamespaceContext { + + private final Map prefixMap; + private final Map> nsMap; + + /** + * Constructor that takes a map of XML prefix-namespaceURI values. A + * defensive copy is made of the map. An IllegalArgumentException will be + * thrown if the map attempts to remap the standard prefixes defined in the + * NamespaceContext contract. + * + * @param prefixMappings + * a map of prefix:namespaceURI values + */ + public NamespaceContextMap(Map prefixMappings) { + prefixMap = createPrefixMap(prefixMappings); + nsMap = createNamespaceMap(prefixMap); + } + + /** + * Convenience constructor. + * + * @param mappingPairs + * pairs of prefix-namespaceURI values + */ + public NamespaceContextMap(String... mappingPairs) { + this(toMap(mappingPairs)); + } + + /** + * To map. + * + * @param mappingPairs the mapping pairs + * @return the map + */ + private static Map toMap(String... mappingPairs) { + Map prefixMappings = new HashMap( + mappingPairs.length / 2); + for (int i = 0; i < mappingPairs.length; i++) { + prefixMappings.put(mappingPairs[i], mappingPairs[++i]); + } + return prefixMappings; + } + + /** + * Creates the prefix map. + * + * @param prefixMappings the prefix mappings + * @return the map + */ + private Map createPrefixMap( + Map prefixMappings) { + Map prefixMap = new HashMap( + prefixMappings); + addConstant(prefixMap, XMLConstants.XML_NS_PREFIX, + XMLConstants.XML_NS_URI); + addConstant(prefixMap, XMLConstants.XMLNS_ATTRIBUTE, + XMLConstants.XMLNS_ATTRIBUTE_NS_URI); + return Collections.unmodifiableMap(prefixMap); + } + + /** + * Adds the constant. + * + * @param prefixMap the prefix map + * @param prefix the prefix + * @param nsURI the ns uri + */ + private void addConstant(Map prefixMap, String prefix, + String nsURI) { + String previous = prefixMap.put(prefix, nsURI); + if (previous != null && !previous.equals(nsURI)) { + throw new IllegalArgumentException(prefix + " -> " + previous + + "; see NamespaceContext contract"); + } + } + + /** + * Creates the namespace map. + * + * @param prefixMap the prefix map + * @return the map + */ + private Map> createNamespaceMap( + Map prefixMap) { + Map> nsMap = new HashMap>(); + for (Map.Entry entry : prefixMap.entrySet()) { + String nsURI = entry.getValue(); + Set prefixes = nsMap.get(nsURI); + if (prefixes == null) { + prefixes = new HashSet(); + nsMap.put(nsURI, prefixes); + } + prefixes.add(entry.getKey()); + } + for (Map.Entry> entry : nsMap.entrySet()) { + Set readOnly = Collections + .unmodifiableSet(entry.getValue()); + entry.setValue(readOnly); + } + return nsMap; + } + + /* (non-Javadoc) + * @see javax.xml.namespace.NamespaceContext#getNamespaceURI(java.lang.String) + */ + @Override + public String getNamespaceURI(String prefix) { + checkNotNull(prefix); + String nsURI = prefixMap.get(prefix); + return nsURI == null ? XMLConstants.NULL_NS_URI : nsURI; + } + + /* (non-Javadoc) + * @see javax.xml.namespace.NamespaceContext#getPrefix(java.lang.String) + */ + @Override + public String getPrefix(String namespaceURI) { + checkNotNull(namespaceURI); + Set set = nsMap.get(namespaceURI); + return set == null ? null : set.iterator().next(); + } + + /* (non-Javadoc) + * @see javax.xml.namespace.NamespaceContext#getPrefixes(java.lang.String) + */ + @Override + public Iterator getPrefixes(String namespaceURI) { + checkNotNull(namespaceURI); + Set set = nsMap.get(namespaceURI); + return set.iterator(); + } + + /** + * Check not null. + * + * @param value the value + */ + private void checkNotNull(String value) { + if (value == null) { + throw new IllegalArgumentException("null"); + } + } + + /** + * Gets the map. + * + * @return an unmodifiable map of the mappings in the form + * prefix-namespaceURI + */ + public Map getMap() { + return prefixMap; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("NamespaceContextMap [prefixMap="); + builder.append(prefixMap); + builder.append(", nsMap="); + builder.append(nsMap); + builder.append("]"); + return builder.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/xml/WPSParserUtil.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/xml/WPSParserUtil.java new file mode 100644 index 0000000..4173eb2 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/server/util/xml/WPSParserUtil.java @@ -0,0 +1,201 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server.util.xml; + +import java.io.BufferedInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathFactory; + +import org.apache.commons.io.IOUtils; +import org.gcube.portlets.user.performfishanalytics.server.util.dataminer.DataMinerOutputData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + + +/** + * The Class WPSParserUtil. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 24, 2019 + */ +public class WPSParserUtil { + + protected static Logger log = LoggerFactory.getLogger(WPSParserUtil.class); + + /** + * Gets the text from x path expression. + * + * @param context the context + * @param source the source + * @param xpathExpression the xpath expression + * @return the text from x path expression + */ + public static List getTextFromXPathExpression(NamespaceContextMap context, InputStream source, String xpathExpression){ + + List list = new ArrayList(); + try { + + XPath xpath = XPathFactory.newInstance().newXPath(); + xpath.setNamespaceContext(context); + XPathExpression xPathExpression = xpath.compile(xpathExpression); + InputSource inputSource = new InputSource(source); + +// System.out.println(xml); +// System.out.println(xpathExpression); +// System.out.println(inputSource.toString()); + + NodeList nodes = (NodeList) xPathExpression.evaluate(inputSource, XPathConstants.NODESET); + + for (int i = 0; i getTextFromXPathExpression(NamespaceContextMap context, String source, String xpathExpression){ + + List list = new ArrayList(); + try { + + XPath xpath = XPathFactory.newInstance().newXPath(); + xpath.setNamespaceContext(context); + XPathExpression xPathExpression = xpath.compile(xpathExpression); + InputSource inputSource = new InputSource(IOUtils.toInputStream(source)); + + NodeList nodes = (NodeList) xPathExpression.evaluate(inputSource, XPathConstants.NODESET); + + for (int i = 0; i getListDataMinerOutputDataFromWPSResponse(Document doc) { + + List listOutput = new ArrayList(); + + // list + NodeList nodes = doc.getElementsByTagName("ogr:Result"); + log.info("ogr:Result are: " + nodes.getLength()); + for (int i = 0; i < nodes.getLength(); i++) { + Element mdMetadata = (Element) nodes.item(i); + + DataMinerOutputData dmOutput = new DataMinerOutputData(); + Map map = new HashMap(); + + String tagSearch = "d4science:Data"; + NodeList nodeList = mdMetadata.getElementsByTagName(tagSearch); + if(nodeList==null || nodeList.getLength()==0 || nodeList.item(0)==null){ + log.info("not found "+tagSearch); + }else{ + dmOutput.setPublicURL(nodeList.item(0).getTextContent()); + map.put(tagSearch, nodeList.item(0).getTextContent()); + } + + tagSearch = "d4science:Description"; + nodeList = mdMetadata.getElementsByTagName(tagSearch); + if(nodeList==null || nodeList.getLength()==0 || nodeList.item(0)==null){ + log.info("not found "+tagSearch); + }else{ + dmOutput.setFileDescription(nodeList.item(0).getTextContent()); + map.put(tagSearch, nodeList.item(0).getTextContent()); + } + + tagSearch = "d4science:MimeType"; + nodeList = mdMetadata.getElementsByTagName(tagSearch); + if(nodeList==null || nodeList.getLength()==0 || nodeList.item(0)==null){ + log.info("not found "+tagSearch); + }else{ + dmOutput.setMimeType(nodeList.item(0).getTextContent()); + map.put(tagSearch, nodeList.item(0).getTextContent()); + } + + dmOutput.setDataMinerOutputData(map); + listOutput.add(dmOutput); + + + } + return listOutput; + } + + + + /** + * Input stream to w3 c document. + * + * @param getRecordsResponse the get records response + * @return the document + * @throws Exception the exception + */ + public static Document inputStreamToW3CDocument(InputStream getRecordsResponse) throws Exception{ + + try { + BufferedInputStream bis = new BufferedInputStream(getRecordsResponse); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setValidating(false); + DocumentBuilder db = dbf.newDocumentBuilder(); + return db.parse(bis); + } + catch (Exception e) { + log.error("Error converting input stream to W3C document", e); + throw new Exception(e); + } + } + + /** + * String to input stream. + * + * @param text the text + * @return the input stream + */ + public static InputStream stringToInputStream(String text){ + return IOUtils.toInputStream(text); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Area.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Area.java new file mode 100644 index 0000000..ae383d6 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Area.java @@ -0,0 +1,175 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.shared; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import org.eclipse.persistence.annotations.CascadeOnDelete; + + +/** + * The Class Area. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 11, 2019 + */ +@Entity +@CascadeOnDelete +public class Area implements GenericDao, ReferencePopulationType, PopulationTypeProperties, Serializable{ + + /** + * + */ + private static final long serialVersionUID = 970775589404463528L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int internalId; //PRIMARY KEY + + private String id; + private String name; + private String description; + + @CascadeOnDelete + private PopulationType populationType; + + + public Area() { + + } + + + /** + * Instantiates a new area. + * + * @param id the id + * @param name the name + * @param description the description + * @param populationType the population type + */ + public Area(String id, String name, String description, PopulationType populationType) { + + this.id = id; + this.name = name; + this.description = description; + this.populationType = populationType; + } + + + /** + * @return the id + */ + public String getId() { + + return id; + } + + + + /** + * @return the name + */ + public String getName() { + + return name; + } + + + + /** + * @return the description + */ + public String getDescription() { + + return description; + } + + + + /** + * @return the populationType + */ + public PopulationType getPopulationType() { + + return populationType; + } + + + + /** + * @param id the id to set + */ + public void setId(String id) { + + this.id = id; + } + + + + /** + * @param name the name to set + */ + public void setName(String name) { + + this.name = name; + } + + + + /** + * @param description the description to set + */ + public void setDescription(String description) { + + this.description = description; + } + + + + /** + * @param populationType the populationType to set + */ + public void setPopulationType(PopulationType populationType) { + + this.populationType = populationType; + } + + /* (non-Javadoc) + * @see org.gcube.portlets.user.performfishanalytics.shared.PopulationTypeProperties#getInternalId() + */ + @Override + public int getInternalId() { + + return internalId; + } + + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("Area [internalId="); + builder.append(internalId); + builder.append(", id="); + builder.append(id); + builder.append(", name="); + builder.append(name); + builder.append(", description="); + builder.append(description); + builder.append("]"); + return builder.toString(); + } + + + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/FileContentType.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/FileContentType.java new file mode 100644 index 0000000..5c22f41 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/FileContentType.java @@ -0,0 +1,18 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.shared; + + +/** + * The Enum FileContentType. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 24, 2019 + */ +public enum FileContentType { + + CSV, + IMAGE, + UNKNOWN +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/GenericDao.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/GenericDao.java new file mode 100644 index 0000000..9663ea7 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/GenericDao.java @@ -0,0 +1,15 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.shared; + + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 11, 2019 + */ +public interface GenericDao { + + public String getId(); +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/KPI.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/KPI.java new file mode 100644 index 0000000..08232c9 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/KPI.java @@ -0,0 +1,280 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.shared; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.OrderColumn; +import javax.persistence.Transient; + +import org.eclipse.persistence.annotations.CascadeOnDelete; + + +/** + * The Class KPI. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 11, 2019 + */ +@Entity +@CascadeOnDelete +public class KPI implements GenericDao, Comparable, ReferencePopulationType, PopulationTypeProperties, Serializable{ + + /** + * + */ + private static final long serialVersionUID = -7903059379223156950L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int internalId; //PRIMARY KEY + + private String id; + private String code; + private String name; + + private String description; + + //THESE ARE THE DESCENDANT + @OneToMany(cascade=CascadeType.PERSIST, fetch=FetchType.LAZY) + @OrderColumn + private List listKPI = new ArrayList(); + + private int deepIndex = -1; + + //HERE STORE ONLY THE DIRECT CHILD OF POPULATION_TYPE, THAT IS THE FIRST LEVEL OF KPIs + @CascadeOnDelete + private PopulationType populationType; + + @Transient + private boolean isLeaf = false; + + + /** + * Instantiates a new kpi. + */ + public KPI() { + } + + /** + * Instantiates a new kpi. + * + * @param id the id + * @param code the code + * @param name the name + * @param description the description + * @param listKPI the list kpi + * @param populationType the population type + * @param deepIndex the deep index + */ + public KPI( + String id, String code, String name, String description, + ArrayList listKPI, PopulationType populationType, int deepIndex) { + + super(); + this.id = id; + this.code = code; + this.name = name; + this.description = description; + this.listKPI = listKPI; + this.populationType = populationType; + this.deepIndex = deepIndex; + } + + + /** + * @return the internalId + */ + public int getInternalId() { + + return internalId; + } + + + /** + * @return the id + */ + public String getId() { + + return id; + } + + + /** + * @return the code + */ + public String getCode() { + + return code; + } + + + /** + * @return the name + */ + public String getName() { + + return name; + } + + + /** + * @return the description + */ + public String getDescription() { + + return description; + } + + + /** + * @return the listKPI + */ + public List getListKPI() { + + return listKPI; + } + + + /** + * @return the deepIndex + */ + public int getDeepIndex() { + + return deepIndex; + } + + + /** + * @return the populationType + */ + public PopulationType getPopulationType() { + + return populationType; + } + + + /** + * @param id the id to set + */ + public void setId(String id) { + + this.id = id; + } + + + /** + * @param code the code to set + */ + public void setCode(String code) { + + this.code = code; + } + + + /** + * @param name the name to set + */ + public void setName(String name) { + + this.name = name; + } + + + /** + * @param description the description to set + */ + public void setDescription(String description) { + + this.description = description; + } + + + /** + * @param listKPI the listKPI to set + */ + public void setListKPI(List listKPI) { + + this.listKPI = listKPI; + } + + + /** + * @param deepIndex the deepIndex to set + */ + public void setDeepIndex(int deepIndex) { + + this.deepIndex = deepIndex; + } + + + /** + * @param populationType the populationType to set + */ + public void setPopulationType(PopulationType populationType) { + + this.populationType = populationType; + } + + /* (non-Javadoc) + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(KPI o) { + return deepIndex - o.getDeepIndex(); + } + + /** + * @return the isLeaf + */ + public boolean isLeaf() { + + return isLeaf; + } + + + /** + * @param isLeaf the isLeaf to set + */ + public void setLeaf(boolean isLeaf) { + + this.isLeaf = isLeaf; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("KPI [internalId="); + builder.append(internalId); + builder.append(", id="); + builder.append(id); + builder.append(", code="); + builder.append(code); + builder.append(", name="); + builder.append(name); + builder.append(", description="); + builder.append(description); + builder.append(", deepIndex="); + builder.append(deepIndex); + builder.append(", isLeaf="); + builder.append(isLeaf); + builder.append("]"); + return builder.toString(); + } +} + + diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/OutputFile.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/OutputFile.java new file mode 100644 index 0000000..19e72f5 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/OutputFile.java @@ -0,0 +1,104 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.shared; + +import java.io.Serializable; + + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 24, 2019 + */ +public class OutputFile implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 8312729240987548992L; + + FileContentType dataType; + String serverLocation; + String name; + + /** + * + */ + public OutputFile() { + + } + + + /** + * @return the dataType + */ + public FileContentType getDataType() { + + return dataType; + } + + + /** + * @return the serverLocation + */ + public String getServerLocation() { + + return serverLocation; + } + + + /** + * @return the name + */ + public String getName() { + + return name; + } + + + /** + * @param dataType the dataType to set + */ + public void setDataType(FileContentType dataType) { + + this.dataType = dataType; + } + + + /** + * @param serverLocation the serverLocation to set + */ + public void setServerLocation(String serverLocation) { + + this.serverLocation = serverLocation; + } + + + /** + * @param name the name to set + */ + public void setName(String name) { + + this.name = name; + } + + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("OutputFile [dataType="); + builder.append(dataType); + builder.append(", serverLocation="); + builder.append(serverLocation); + builder.append(", name="); + builder.append(name); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Period.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Period.java new file mode 100644 index 0000000..708a96f --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Period.java @@ -0,0 +1,181 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.shared; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import org.eclipse.persistence.annotations.CascadeOnDelete; + + +/** + * The Class Period. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 11, 2019 + */ +@Entity +@CascadeOnDelete +public class Period implements GenericDao, ReferencePopulationType, PopulationTypeProperties, Serializable{ + + /** + * + */ + private static final long serialVersionUID = 6926793952225228858L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int internalId; //PRIMARY KEY + + private String id; + private String name; + + private String description; + +// @ManyToMany(mappedBy="listPeriod") +// private List listPopulationType = new ArrayList(); + + @CascadeOnDelete + private PopulationType populationType; + + + + /** + * + */ + public Period() { + } + + + /** + * Instantiates a new period. + * + * @param id the id + * @param name the name + * @param description the description + * @param populationType the population type + */ + public Period(String id, String name, String description, PopulationType populationType) { + + super(); + this.id = id; + this.name = name; + this.description = description; + this.populationType = populationType; + } + + /** + * @return the id + */ + public String getId() { + + return id; + } + + + + /** + * @return the name + */ + public String getName() { + + return name; + } + + + + /** + * @return the description + */ + public String getDescription() { + + return description; + } + + + + /** + * @return the populationType + */ + public PopulationType getPopulationType() { + + return populationType; + } + + + + /** + * @param id the id to set + */ + public void setId(String id) { + + this.id = id; + } + + + + /** + * @param name the name to set + */ + public void setName(String name) { + + this.name = name; + } + + + + /** + * @param description the description to set + */ + public void setDescription(String description) { + + this.description = description; + } + + + + /** + * @param populationType the populationType to set + */ + public void setPopulationType(PopulationType populationType) { + + this.populationType = populationType; + } + + /** + * @return the internalId + */ + public int getInternalId() { + + return internalId; + } + + + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("Period [internalId="); + builder.append(internalId); + builder.append(", id="); + builder.append(id); + builder.append(", name="); + builder.append(name); + builder.append(", description="); + builder.append(description); + builder.append("]"); + return builder.toString(); + } + + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Population.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Population.java new file mode 100644 index 0000000..0afd271 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Population.java @@ -0,0 +1,221 @@ +/** + * + */ + +package org.gcube.portlets.user.performfishanalytics.shared; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Lob; +import javax.persistence.OneToMany; +import javax.persistence.OrderColumn; + +import org.eclipse.persistence.annotations.CascadeOnDelete; + + +/** + * The Class Population. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 17, 2019 + */ +@Entity +@CascadeOnDelete +public class Population implements GenericDao, Serializable { + + /** + * + */ + private static final long serialVersionUID = 1919520988595801648L; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int internalId; // PRIMARY KEY + private String id; + private String name; + private String level; + @Lob + private String description; + + @OneToMany(mappedBy = "population", orphanRemoval = true, cascade = CascadeType.PERSIST, fetch = FetchType.EAGER) + @CascadeOnDelete + @OrderColumn + private List listPopulationType = new ArrayList(); + + /** + * Instantiates a new population. + */ + public Population() { + + } + + /** + * Instantiates a new population. + * + * @param id + * the id + * @param name + * the name + * @param level + * the level + * @param description + * the description + * @param listPopulationType + * the list population type + */ + public Population( + String id, String name, String level, String description, + ArrayList listPopulationType) { + + super(); + this.id = id; + this.name = name; + this.level = level; + this.description = description; + this.listPopulationType = listPopulationType; + } + + /** + * Gets the internal id. + * + * @return the internalId + */ + public int getInternalId() { + + return internalId; + } + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + + return id; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + + return name; + } + + /** + * Gets the level. + * + * @return the level + */ + public String getLevel() { + + return level; + } + + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + + return description; + } + + /** + * Gets the list population type. + * + * @return the listPopulationType + */ + public List getListPopulationType() { + + return listPopulationType; + } + + /** + * Sets the id. + * + * @param id + * the id to set + */ + public void setId(String id) { + + this.id = id; + } + + /** + * Sets the name. + * + * @param name + * the name to set + */ + public void setName(String name) { + + this.name = name; + } + + /** + * Sets the level. + * + * @param level + * the level to set + */ + public void setLevel(String level) { + + this.level = level; + } + + /** + * Sets the description. + * + * @param description + * the description to set + */ + public void setDescription(String description) { + + this.description = description; + } + + /** + * Sets the list population type. + * + * @param listPopulationType + * the listPopulationType to set + */ + public void setListPopulationType(List listPopulationType) { + + this.listPopulationType = listPopulationType; + } + + /* + * (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("Population [internalId="); + builder.append(internalId); + builder.append(", id="); + builder.append(id); + builder.append(", name="); + builder.append(name); + builder.append(", level="); + builder.append(level); + builder.append(", description="); + builder.append(description); + builder.append("]"); + return builder.toString(); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/PopulationType.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/PopulationType.java new file mode 100644 index 0000000..c0d7445 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/PopulationType.java @@ -0,0 +1,385 @@ +/** + * + */ + +package org.gcube.portlets.user.performfishanalytics.shared; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Lob; +import javax.persistence.OneToMany; +import javax.persistence.OrderColumn; + +import org.eclipse.persistence.annotations.CascadeOnDelete; + +/** + * The Class PopulationType. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Jan 11, 2019 + */ +@Entity +@CascadeOnDelete +public class PopulationType implements GenericDao, Serializable { + + /** + * + */ + private static final long serialVersionUID = -1053734960180011850L; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int internalId; // PRIMARY KEY + private String id; + private String name; + private String type; + @Lob + private String description; + @CascadeOnDelete + private Population population; + + @OneToMany(mappedBy = "populationType", orphanRemoval = true, cascade = CascadeType.PERSIST, fetch = FetchType.LAZY) + @CascadeOnDelete + @OrderColumn + private List listSpecies = new ArrayList(); + + @OneToMany(mappedBy = "populationType", orphanRemoval = true, cascade = CascadeType.PERSIST, fetch = FetchType.LAZY) + @CascadeOnDelete + @OrderColumn + private List listQuarter = new ArrayList(); + + @OneToMany(mappedBy = "populationType", orphanRemoval = true, cascade = CascadeType.PERSIST, fetch = FetchType.LAZY) + @CascadeOnDelete + @OrderColumn + private List listArea = new ArrayList(); + + @OneToMany(mappedBy = "populationType", orphanRemoval = true, cascade = CascadeType.PERSIST, fetch = FetchType.LAZY) + @CascadeOnDelete + @OrderColumn + private List listPeriod = new ArrayList(); + + @OneToMany(mappedBy = "populationType", orphanRemoval = true, cascade = CascadeType.PERSIST, fetch = FetchType.EAGER) + @CascadeOnDelete + @OrderColumn + private List listKPI = new ArrayList(); + + /** + * Instantiates a new population type. + */ + public PopulationType() { + + } + + /** + * Instantiates a new population type. + * + * @param id + * the id + * @param name + * the name + * @param type + * the type + * @param description + * the description + * @param population + * the population + */ + public PopulationType( + String id, String name, String type, String description, + Population population) { + + this.id = id; + this.name = name; + this.type = type; + this.description = description; + this.population = population; + } + + /** + * Instantiates a new population type. + * + * @param id + * the id + * @param name + * the name + * @param type + * the type + * @param description + * the description + * @param population + * the population + * @param listQuarter + * the list quarter + * @param listArea + * the list area + * @param listPeriod + * the list period + * @param listKPI + * the list kpi + */ + public PopulationType( + String id, String name, String type, String description, + Population population, ArrayList listQuarter, + ArrayList listArea, ArrayList listPeriod, + ArrayList listKPI) { + + super(); + this.id = id; + this.name = name; + this.type = type; + this.description = description; + this.population = population; + this.listQuarter = listQuarter; + this.listArea = listArea; + this.listPeriod = listPeriod; + this.listKPI = listKPI; + } + + /* + * (non-Javadoc) + * @see + * org.gcube.portlets.user.performfishanalytics.shared.dao.GenericDao#getId + * () + */ + @Override + public String getId() { + + return id; + } + + /** + * Gets the internal id. + * + * @return the internalId + */ + public int getInternalId() { + + return internalId; + } + + /** + * Sets the id. + * + * @param id + * the id to set + */ + public void setId(String id) { + + this.id = id; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + + return name; + } + + /** + * Gets the type. + * + * @return the type + */ + public String getType() { + + return type; + } + + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + + return description; + } + + /** + * Gets the population. + * + * @return the population + */ + public Population getPopulation() { + + return population; + } + + /** + * Gets the list quarter. + * + * @return the listQuarter + */ + public List getListQuarter() { + + return listQuarter; + } + + /** + * Gets the list area. + * + * @return the listArea + */ + public List getListArea() { + + return listArea; + } + + /** + * Gets the list period. + * + * @return the listPeriod + */ + public List getListPeriod() { + + return listPeriod; + } + + /** + * Gets the list kpi. + * + * @return the listKPI + */ + public List getListKPI() { + + return listKPI; + } + + /** + * Gets the list species. + * + * @return the listSpecies + */ + public List getListSpecies() { + + return listSpecies; + } + + /** + * Sets the name. + * + * @param name + * the name to set + */ + public void setName(String name) { + + this.name = name; + } + + /** + * Sets the type. + * + * @param type + * the type to set + */ + public void setType(String type) { + + this.type = type; + } + + /** + * Sets the description. + * + * @param description + * the description to set + */ + public void setDescription(String description) { + + this.description = description; + } + + /** + * Sets the population. + * + * @param population + * the population to set + */ + public void setPopulation(Population population) { + + this.population = population; + } + + /** + * Sets the list quarter. + * + * @param listQuarter + * the listQuarter to set + */ + public void setListQuarter(List listQuarter) { + + this.listQuarter = listQuarter; + } + + /** + * Sets the list area. + * + * @param listArea + * the listArea to set + */ + public void setListArea(List listArea) { + + this.listArea = listArea; + } + + /** + * Sets the list period. + * + * @param listPeriod + * the listPeriod to set + */ + public void setListPeriod(List listPeriod) { + + this.listPeriod = listPeriod; + } + + /** + * Sets the list kpi. + * + * @param listKPI + * the listKPI to set + */ + public void setListKPI(List listKPI) { + + this.listKPI = listKPI; + } + + /** + * Sets the list species. + * + * @param listSpecies + * the listSpecies to set + */ + public void setListSpecies(List listSpecies) { + + this.listSpecies = listSpecies; + } + + /* + * (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("PopulationType [id="); + builder.append(id); + builder.append(", name="); + builder.append(name); + builder.append(", type="); + builder.append(type); + builder.append(", description="); + builder.append(description); + builder.append("]"); + return builder.toString(); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/PopulationTypeProperties.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/PopulationTypeProperties.java new file mode 100644 index 0000000..1dea9c6 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/PopulationTypeProperties.java @@ -0,0 +1,28 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.shared; + + +/** + * The Interface PopulationTypeProperties. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 17, 2019 + */ +public interface PopulationTypeProperties { + + public int getInternalId(); + + public String getId(); + + public String getName(); + + public String getDescription(); + + public void setId(String id); + + public void setName(String name); + + public void setDescription(String description); +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Quarter.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Quarter.java new file mode 100644 index 0000000..3b29c88 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Quarter.java @@ -0,0 +1,181 @@ +/** + * + */ + +package org.gcube.portlets.user.performfishanalytics.shared; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import org.eclipse.persistence.annotations.CascadeOnDelete; + +/** + * The Class Quarter. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Jan 11, 2019 + */ +@Entity +@CascadeOnDelete +public class Quarter implements GenericDao, ReferencePopulationType, PopulationTypeProperties, Serializable { + + /** + * + */ + private static final long serialVersionUID = -4234722040817405025L; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int internalId; // PRIMARY KEY + private String id; + private String name; + private String description; + + @CascadeOnDelete + private PopulationType populationType; + + /** + * Instantiates a new quarter. + */ + public Quarter() { + + // TODO Auto-generated constructor stub + } + + /** + * Instantiates a new quarter. + * + * @param id + * the id + * @param name + * the name + * @param description + * the description + * @param populationType + * the population type + */ + public Quarter( + String id, String name, String description, + PopulationType populationType) { + + this.id = id; + this.name = name; + this.description = description; + this.populationType = populationType; + } + + /** + * Gets the internal id. + * + * @return the internalId + */ + public int getInternalId() { + + return internalId; + } + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + + return id; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + + return name; + } + + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + + return description; + } + + /** + * Gets the population type. + * + * @return the populationType + */ + public PopulationType getPopulationType() { + + return populationType; + } + + /* (non-Javadoc) + * @see org.gcube.portlets.user.performfishanalytics.shared.RefencePopulationType#setPopulationType(org.gcube.portlets.user.performfishanalytics.shared.PopulationType) + */ + @Override + public void setPopulationType(PopulationType populationType) { + + this.populationType = populationType; + + } + + + /* (non-Javadoc) + * @see org.gcube.portlets.user.performfishanalytics.shared.PopulationTypeProperties#setId(java.lang.String) + */ + public void setId(String id) { + + this.id = id; + } + + + /** + * Sets the description. + * + * @param description the description to set + */ + public void setDescription(String description) { + + this.description = description; + } + + + /** + * Sets the name. + * + * @param name the name to set + */ + public void setName(String name) { + + this.name = name; + } + + + /* + * (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("Quarter [internalId="); + builder.append(internalId); + builder.append(", id="); + builder.append(id); + builder.append(", name="); + builder.append(name); + builder.append(", description="); + builder.append(description); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/ReferencePopulationType.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/ReferencePopulationType.java new file mode 100644 index 0000000..22d56be --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/ReferencePopulationType.java @@ -0,0 +1,17 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.shared; + + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 17, 2019 + */ +public interface ReferencePopulationType { + + public void setPopulationType(PopulationType population); + + public PopulationType getPopulationType(); +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Species.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Species.java new file mode 100644 index 0000000..1c46bf0 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/Species.java @@ -0,0 +1,162 @@ +/** + * + */ + +package org.gcube.portlets.user.performfishanalytics.shared; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import org.eclipse.persistence.annotations.CascadeOnDelete; + +/** + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Jan 17, 2019 + */ +@Entity +@CascadeOnDelete +public class Species implements GenericDao, ReferencePopulationType, PopulationTypeProperties, Serializable { + + /** + * + */ + private static final long serialVersionUID = 5501396332502088292L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int internalId; // PRIMARY KEY + private String id; + private String name; + private String description; + + @CascadeOnDelete + private PopulationType populationType; + + /** + * Instantiates a new species. + */ + public Species() { + + // TODO Auto-generated constructor stub + } + + /** + * Instantiates a new species. + * + * @param id the id + * @param name the name + * @param description the description + * @param populationType the population type + */ + public Species( + String id, String name, String description, + PopulationType populationType) { + + super(); + this.id = id; + this.name = name; + this.description = description; + this.populationType = populationType; + } + + + + /** + * @return the internalId + */ + public int getInternalId() { + + return internalId; + } + + /** + * @return the id + */ + public String getId() { + + return id; + } + + /** + * @return the name + */ + public String getName() { + + return name; + } + + /** + * @return the description + */ + public String getDescription() { + + return description; + } + + /** + * @return the populationType + */ + public PopulationType getPopulationType() { + + return populationType; + } + + /** + * @param id + * the id to set + */ + public void setId(String id) { + + this.id = id; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + + this.name = name; + } + + /** + * @param description + * the description to set + */ + public void setDescription(String description) { + + this.description = description; + } + + /** + * @param populationType + * the populationType to set + */ + public void setPopulationType(PopulationType populationType) { + + this.populationType = populationType; + } + + /* + * (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("Species [internalId="); + builder.append(internalId); + builder.append(", id="); + builder.append(id); + builder.append(", name="); + builder.append(name); + builder.append(", description="); + builder.append(description); + builder.append("]"); + return builder.toString(); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/csv/CSVFile.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/csv/CSVFile.java new file mode 100644 index 0000000..de8b8e9 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/csv/CSVFile.java @@ -0,0 +1,133 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.shared.csv; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + + +/** + * The Class CSVFile. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 29, 2019 + */ +public class CSVFile implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 6408321963787244600L; + private CSVRow headerRow; + private List valueRows; + private String fileName; + + /** + * Instantiates a new CSV file. + */ + public CSVFile(){ + + } + + + /** + * Instantiates a new csv file. + * + * @param headerRow the header row + * @param valueRows the value rows + */ + public CSVFile(String fileName, CSVRow headerRow, List valueRows) { + this.fileName = fileName; + this.headerRow = headerRow; + this.valueRows = valueRows; + } + + + /** + * Gets the header row. + * + * @return the headerRow + */ + public CSVRow getHeaderRow() { + + return headerRow; + } + + + /** + * Gets the value rows. + * + * @return the valueRows + */ + public List getValueRows() { + + return valueRows; + } + + + /** + * Sets the header row. + * + * @param headerRow the headerRow to set + */ + public void setHeaderRow(CSVRow headerRow) { + + this.headerRow = headerRow; + } + + + + /** + * Adds the row. + * + * @param csvRow the csv row + */ + public void addRow(CSVRow csvRow) { + + if(this.valueRows==null) + this.valueRows = new ArrayList(); + + this.valueRows.add(csvRow); + } + + /** + * @return the fileName + */ + public String getFileName() { + + return fileName; + } + + + + /** + * @param fileName the fileName to set + */ + public void setFileName(String fileName) { + + this.fileName = fileName; + } + + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("CSVFile [headerRow="); + builder.append(headerRow); + builder.append(", valueRows="); + builder.append(valueRows); + builder.append(", fileName="); + builder.append(fileName); + builder.append("]"); + return builder.toString(); + } + + + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/csv/CSVRow.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/csv/CSVRow.java new file mode 100644 index 0000000..338321c --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/csv/CSVRow.java @@ -0,0 +1,67 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.shared.csv; + +import java.io.Serializable; +import java.util.List; + + +/** + * The Class CSVRow. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 29, 2019 + */ +public class CSVRow implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 6254861811998867626L; + + private List listValues; + + /** + * Instantiates a new CSV row. + */ + public CSVRow(){ + + } + + + /** + * Gets the list values. + * + * @return the listValues + */ + public List getListValues() { + + return listValues; + } + + + + /** + * @param listValues the listValues to set + */ + public void setListValues(List listValues) { + + this.listValues = listValues; + } + + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("CSVRow [listValues="); + builder.append(listValues); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/dataminer/DataMinerResponse.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/dataminer/DataMinerResponse.java new file mode 100644 index 0000000..c7a0f91 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/dataminer/DataMinerResponse.java @@ -0,0 +1,108 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.shared.dataminer; + +import java.io.Serializable; +import java.util.List; + +import org.gcube.portlets.user.performfishanalytics.shared.OutputFile; +import org.gcube.portlets.user.performfishanalytics.shared.performfishservice.PerformFishResponse; + + +/** + * The Class DataMinerResponse. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 29, 2019 + */ +public class DataMinerResponse implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 5553199389404083085L; + private PerformFishResponse peformFishReponse; + private List listOutput; + + /** + * Instantiates a new data miner response. + */ + DataMinerResponse(){ + + } + + + /** + * Instantiates a new data miner response. + * + * @param peformFishReponse the peform fish reponse + * @param listOutput the list output + */ + public DataMinerResponse( + PerformFishResponse peformFishReponse, List listOutput) { + + this.peformFishReponse = peformFishReponse; + this.listOutput = listOutput; + } + + + /** + * Gets the peform fish reponse. + * + * @return the peformFishReponse + */ + public PerformFishResponse getPeformFishReponse() { + + return peformFishReponse; + } + + + /** + * Gets the list output. + * + * @return the listOutput + */ + public List getListOutput() { + + return listOutput; + } + + + /** + * Sets the peform fish reponse. + * + * @param peformFishReponse the peformFishReponse to set + */ + public void setPeformFishReponse(PerformFishResponse peformFishReponse) { + + this.peformFishReponse = peformFishReponse; + } + + + /** + * Sets the list output. + * + * @param listOutput the listOutput to set + */ + public void setListOutput(List listOutput) { + + this.listOutput = listOutput; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("DataMinerResponse [peformFishReponse="); + builder.append(peformFishReponse); + builder.append(", listOutput="); + builder.append(listOutput); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/exceptions/DatabaseServiceException.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/exceptions/DatabaseServiceException.java new file mode 100644 index 0000000..6d960d9 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/exceptions/DatabaseServiceException.java @@ -0,0 +1,30 @@ +package org.gcube.portlets.user.performfishanalytics.shared.exceptions; + +/** + * The Class DatabaseServiceException. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Feb 19, 2015 + */ +public class DatabaseServiceException extends Exception { + + + /** + * + */ + private static final long serialVersionUID = 7883813468540671226L; + + /** + * Instantiates a new database service exception. + */ + public DatabaseServiceException(){} + + /** + * Instantiates a new database service exception. + * + * @param message the message + */ + public DatabaseServiceException(String message) { + super(message); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/exceptions/SessionExpired.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/exceptions/SessionExpired.java new file mode 100644 index 0000000..bbcf183 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/exceptions/SessionExpired.java @@ -0,0 +1,34 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.shared.exceptions; + +/** + * The Class SessionExpired. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Jan 11, 2019 + */ +public class SessionExpired extends Exception { + + /** + * + */ + private static final long serialVersionUID = 756417673620945244L; + + /** + * Instantiates a new session expired. + */ + public SessionExpired() { + + } + + /** + * Instantiates a new session expired. + * + * @param arg0 the arg0 + */ + public SessionExpired(String arg0){ + super(arg0); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/performfishservice/PerformFishInitParameter.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/performfishservice/PerformFishInitParameter.java new file mode 100644 index 0000000..adad20c --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/performfishservice/PerformFishInitParameter.java @@ -0,0 +1,60 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.shared.performfishservice; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 22, 2019 + */ +public class PerformFishInitParameter implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = -1197595803048727741L; + + + private Map parameters = new HashMap(); + + /** + * + */ + public PerformFishInitParameter() { + } + + + public void addParameter(String key, String value){ + if(parameters==null) + parameters = new HashMap(); + parameters.put(key, value); + } + + /** + * @return the parameters + */ + public Map getParameters() { + + return parameters; + } + + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("PerformFishInitParameter [parameters="); + builder.append(parameters); + builder.append("]"); + return builder.toString(); + } +} diff --git a/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/performfishservice/PerformFishResponse.java b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/performfishservice/PerformFishResponse.java new file mode 100644 index 0000000..fbb9c20 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/performfishanalytics/shared/performfishservice/PerformFishResponse.java @@ -0,0 +1,105 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.shared.performfishservice; + +import java.io.Serializable; +import java.util.Map; + + +/** + * The Class PerformFishResponse. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 29, 2019 + */ +public class PerformFishResponse implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 6064068032560730872L; + + private Map mapParameters; + private String respSessionId; + + + /** + * Instantiates a new perform fish response. + */ + public PerformFishResponse() { + } + + /** + * Instantiates a new perform fish response. + * + * @param mapParameters the map parameters + * @param respSessionId the resp session id + */ + public PerformFishResponse( + Map mapParameters, String respSessionId) { + + super(); + this.mapParameters = mapParameters; + this.respSessionId = respSessionId; + } + + + /** + * Gets the map parameters. + * + * @return the mapParameters + */ + public Map getMapParameters() { + + return mapParameters; + } + + + /** + * Gets the resp session id. + * + * @return the respSessionId + */ + public String getRespSessionId() { + + return respSessionId; + } + + + /** + * Sets the map parameters. + * + * @param mapParameters the mapParameters to set + */ + public void setMapParameters(Map mapParameters) { + + this.mapParameters = mapParameters; + } + + + /** + * Sets the resp session id. + * + * @param respSessionId the respSessionId to set + */ + public void setRespSessionId(String respSessionId) { + + this.respSessionId = respSessionId; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("PerformFishResponse [mapParameters="); + builder.append(mapParameters); + builder.append(", respSessionId="); + builder.append(respSessionId); + builder.append("]"); + return builder.toString(); + } +} diff --git a/src/main/resources/BATCH/KPI/GROW_OUT_AGGREGATED_CLOSED_BATCHES.csv b/src/main/resources/BATCH/KPI/GROW_OUT_AGGREGATED_CLOSED_BATCHES.csv new file mode 100644 index 0000000..c87e1eb --- /dev/null +++ b/src/main/resources/BATCH/KPI/GROW_OUT_AGGREGATED_CLOSED_BATCHES.csv @@ -0,0 +1,23 @@ +KPI CODE,KPI NAME – LEVEL 1,KPI NAME – LEVEL 2,KPI NAME – LEVEL 3 +,Dependency on treatments KPIs +,,G9,,,Total number of antiparasitic treatments +,,G10,,,Total number of antibiotic treatments +,,G11,,,Amount of active compounds - antiparasitic +,,G12,,,Amount of active compounds - antibiotic +,Grow-out Productivity KPIs +,,G20,,,Biomass produced per number of FTE employees +,,G21,,,Biomass produced per volumes of sea water used +,Environmental KPIs +,,Preservation of biodiversity and habitats KPIs +G22,,,Oxygen depletion persistence days +G23,,,Escapes - Number of episodes +G24,,,Escapes - Estimated number of escaped fish (confidential ISAB) +G25,,,Endangered marine mammals +,,Use of resources +G28,,,Marine space use for farming +G29,,,Land use +G30,,,Freshwater use +G31,,,Energy used +G32,,,Fuel (Diesel) used for transport +G33,,,Fuel (Diesel) used for other uses +G35,,,Use of renewable energy diff --git a/src/main/resources/BATCH/KPI/GROW_OUT_INDIVIDUAL.csv b/src/main/resources/BATCH/KPI/GROW_OUT_INDIVIDUAL.csv new file mode 100644 index 0000000..074af11 --- /dev/null +++ b/src/main/resources/BATCH/KPI/GROW_OUT_INDIVIDUAL.csv @@ -0,0 +1,93 @@ +KPI CODE,KPI NAME – LEVEL 1,KPI NAME – LEVEL 2,KPI NAME – LEVEL 3 +,Fish Losses KPIs +,,Mortalities - total +G1_1,,,Mortalities - Stocking-50g (%) +G1_2,,,Mortalities - 50-150g (%) +G1_3,,,Mortalities - 150-250g (%) +G1_4,,,Mortalities - 250-400g (%) +G1_5,,,Mortalities - 400-800/harvested batches (%) +G1,,,Mortalities - Total - Stocking-harvest (%) +,,Mortalities – by disease +G2_1,,,Mortalities - by disease - Stocking-50g (%) +G2_2,,,Mortalities - by disease - 50-150g (%) +G2_3,,,Mortalities - by disease - 150-250g (%) +G2_4,,,Mortalities - by disease - 250-400g (%) +G2_5,,,Mortalities - by disease - 400-800/harvested batches (%) +G2,,,Mortalities - by disease - Total - Stocking-harvest (%) +,,Mortalities first 10 days after transport and stocking +G4,,,Mortalities first 10 days after transport and stocking - at day 10 (%) +,,Unaccounted losses +G5,,,Unaccounted losses - at harvest (%) +,,Total losses +G6,,,Total losses - at harvest (%) +,,Discarded fish at slaughter +G7,,,Discarded fish at slaughter (%) +,Dependency on treatments KPIs +,,Number of antiparasitic treatments (total) +G9,,,Total number of antiparasitic treatments - at harvest (n) +,,Number of antibiotic treatments (total) +G10,,,Total number of antibiotic treatments - at harvest (n) +,Fish Growth KPIs +,,Specific Growth Rate (SGR) +G13_1,,,Specific Growth Rate (SGR) - Stocking-50g (% day^-1) +G13_2,,,Specific Growth Rate (SGR) - 150-250gr (% day^-1) +G13_3,,,Specific Growth Rate (SGR) - 250-400g (% day^-1) +G13_4,,,Specific Growth Rate (SGR) - 400-800/harvested batches (% day^-1) +G13_5,,,Specific Growth Rate (SGR) Stocking-harvest (% day-1 ) +,,Grams per day (GPD) +G14_6,,,Grams per day (GPD) - Stocking-50g (g day^-1) +G14_1,,,Grams per day (GPD) - 50-150g (g day^-1) +G14_2,,,Grams per day (GPD) - 150-250gr (g day^-1) +G14_3,,,Grams per day (GPD) - 250-400g (g day^-1) +G14_4,,,Grams per day (GPD- 400-800/harvested batches (g day^-1) +G14_5,,,Grams per day (GPD) Total - Stocking-harvest (g day^-1) +,,Thermal Growth Coefficient (TGC) +G15_6,,,Thermal Growth Coefficient (TGC) - Stocking-50g (g/degree days) +G15_1,,,Thermal Growth Coefficient (TGC) - 50-150g (g/degree days) +G15_2,,,Thermal Growth Coefficient (TGC) - 150-250gr (g/degree days) +G15_3,,,Thermal Growth Coefficient (TGC) - 250-400g (g/degree days) +G15_4,,,Thermal Growth Coefficient (TGC) - 400-800/harvested batches (g/degree days) +G15_5,,,Thermal Growth Coefficient (TGC) - Total - Stocking-harvest (g/degree days) +,Feed Efficiency KPIs +,,Feed Conversion Ratio (FCR) +G16_5,,,Feed Conversion Ratio (FCR) - Stocking-50g +G16_1,,,Feed Conversion Ratio (FCR) - 50-150g +G16_2,,,Feed Conversion Ratio (FCR) - 150-250g +G16_3,,,Feed Conversion Ratio (FCR) - 250-400g +G16_4,,,Feed Conversion Ratio (FCR) - 400-800/harvested batches +G16,,,Feed Conversion Ratio (FCR) Total - Stocking-harvest +,,Biological Feed Conversion Ratio (FCRBIO) +G17_5,,,Biological Feed Conversion Ratio (FCRBIO) - Stocking-50g +G17_1,,,Biological Feed Conversion Ratio (FCRBio) - 50-150g +G17_2,,,Biological Feed Conversion Ratio (FCRBio) - 150-250g +G17_3,,,Biological Feed Conversion Ratio (FCRBio) - 250-400g +G17_4,,,Biological Feed Conversion Ratio (FCRBio) - 400-800/harvested batches +G17_6,,,Biological Feed Conversion Ratio (FCRBIO) Total - Stocking-harvest +,Fish Welfare KPIs +,,Mortalities - total +G1_1,,,Mortalities - Stocking-50g (%) +G1_2,,,Mortalities - 50-150g (%) +G1_3,,,Mortalities - 150-250g (%) +G1_4,,,Mortalities - 250-400g (%) +G1_5,,,Mortalities - 400-800/harvested batches (%) +G1,,,Mortalities - Total - Stocking-harvest (%) +,,Mortalities first 3 days after transport and stocking +G3,,,Mortalities first 3 days after transport and stocking - at day 3 (%) +,,Mortalities first 10 days after transport and stocking +G4,,,Mortalities first 10 days after transport and stocking - at day 10 (%) +,,Vaccinated fish – by disease +G8_1,,,Vaccinated fish - against P. damselae - at stocking (%) +G8_2,,,Vaccinated fish - against V. anguillarum - at stocking (%) +G8_3,,,Vaccinated fish - against Betanodavirus - at stocking (%) +,,Number of antiparasitic treatments (total) +G9,,,Total number of antiparasitic treatments - at harvest (n) +,,Number of antibiotic treatments (total) +G10,,,Total number of antibiotic treatments - at harvest (n) +,,Feed Intake (FI) +G18_5,,,Feed Intake (FI) - Stocking-50g (g fish^-1 day^-1) +G18_1,,,Feed Intake (FI) - 50-150g (g fish^-1 day^-1) +G18_2,,,Feed Intake (FI) - 150-250g (g fish^-1 day^-1) +G18_3,,,Feed Intake (FI) - 250-400g (g fish^-1 day^-1) +G18_4,,,Feed Intake (FI) - 400-800/harvested batches (g fish^-1 day^-1) +,,Stocking density +G19,,,Stocking density at harvest (Kg/m^3) diff --git a/src/main/resources/BATCH/KPI/GROW_OUT_INDIVIDUAL_CLOSED_BATCHES.csv b/src/main/resources/BATCH/KPI/GROW_OUT_INDIVIDUAL_CLOSED_BATCHES.csv new file mode 100644 index 0000000..074af11 --- /dev/null +++ b/src/main/resources/BATCH/KPI/GROW_OUT_INDIVIDUAL_CLOSED_BATCHES.csv @@ -0,0 +1,93 @@ +KPI CODE,KPI NAME – LEVEL 1,KPI NAME – LEVEL 2,KPI NAME – LEVEL 3 +,Fish Losses KPIs +,,Mortalities - total +G1_1,,,Mortalities - Stocking-50g (%) +G1_2,,,Mortalities - 50-150g (%) +G1_3,,,Mortalities - 150-250g (%) +G1_4,,,Mortalities - 250-400g (%) +G1_5,,,Mortalities - 400-800/harvested batches (%) +G1,,,Mortalities - Total - Stocking-harvest (%) +,,Mortalities – by disease +G2_1,,,Mortalities - by disease - Stocking-50g (%) +G2_2,,,Mortalities - by disease - 50-150g (%) +G2_3,,,Mortalities - by disease - 150-250g (%) +G2_4,,,Mortalities - by disease - 250-400g (%) +G2_5,,,Mortalities - by disease - 400-800/harvested batches (%) +G2,,,Mortalities - by disease - Total - Stocking-harvest (%) +,,Mortalities first 10 days after transport and stocking +G4,,,Mortalities first 10 days after transport and stocking - at day 10 (%) +,,Unaccounted losses +G5,,,Unaccounted losses - at harvest (%) +,,Total losses +G6,,,Total losses - at harvest (%) +,,Discarded fish at slaughter +G7,,,Discarded fish at slaughter (%) +,Dependency on treatments KPIs +,,Number of antiparasitic treatments (total) +G9,,,Total number of antiparasitic treatments - at harvest (n) +,,Number of antibiotic treatments (total) +G10,,,Total number of antibiotic treatments - at harvest (n) +,Fish Growth KPIs +,,Specific Growth Rate (SGR) +G13_1,,,Specific Growth Rate (SGR) - Stocking-50g (% day^-1) +G13_2,,,Specific Growth Rate (SGR) - 150-250gr (% day^-1) +G13_3,,,Specific Growth Rate (SGR) - 250-400g (% day^-1) +G13_4,,,Specific Growth Rate (SGR) - 400-800/harvested batches (% day^-1) +G13_5,,,Specific Growth Rate (SGR) Stocking-harvest (% day-1 ) +,,Grams per day (GPD) +G14_6,,,Grams per day (GPD) - Stocking-50g (g day^-1) +G14_1,,,Grams per day (GPD) - 50-150g (g day^-1) +G14_2,,,Grams per day (GPD) - 150-250gr (g day^-1) +G14_3,,,Grams per day (GPD) - 250-400g (g day^-1) +G14_4,,,Grams per day (GPD- 400-800/harvested batches (g day^-1) +G14_5,,,Grams per day (GPD) Total - Stocking-harvest (g day^-1) +,,Thermal Growth Coefficient (TGC) +G15_6,,,Thermal Growth Coefficient (TGC) - Stocking-50g (g/degree days) +G15_1,,,Thermal Growth Coefficient (TGC) - 50-150g (g/degree days) +G15_2,,,Thermal Growth Coefficient (TGC) - 150-250gr (g/degree days) +G15_3,,,Thermal Growth Coefficient (TGC) - 250-400g (g/degree days) +G15_4,,,Thermal Growth Coefficient (TGC) - 400-800/harvested batches (g/degree days) +G15_5,,,Thermal Growth Coefficient (TGC) - Total - Stocking-harvest (g/degree days) +,Feed Efficiency KPIs +,,Feed Conversion Ratio (FCR) +G16_5,,,Feed Conversion Ratio (FCR) - Stocking-50g +G16_1,,,Feed Conversion Ratio (FCR) - 50-150g +G16_2,,,Feed Conversion Ratio (FCR) - 150-250g +G16_3,,,Feed Conversion Ratio (FCR) - 250-400g +G16_4,,,Feed Conversion Ratio (FCR) - 400-800/harvested batches +G16,,,Feed Conversion Ratio (FCR) Total - Stocking-harvest +,,Biological Feed Conversion Ratio (FCRBIO) +G17_5,,,Biological Feed Conversion Ratio (FCRBIO) - Stocking-50g +G17_1,,,Biological Feed Conversion Ratio (FCRBio) - 50-150g +G17_2,,,Biological Feed Conversion Ratio (FCRBio) - 150-250g +G17_3,,,Biological Feed Conversion Ratio (FCRBio) - 250-400g +G17_4,,,Biological Feed Conversion Ratio (FCRBio) - 400-800/harvested batches +G17_6,,,Biological Feed Conversion Ratio (FCRBIO) Total - Stocking-harvest +,Fish Welfare KPIs +,,Mortalities - total +G1_1,,,Mortalities - Stocking-50g (%) +G1_2,,,Mortalities - 50-150g (%) +G1_3,,,Mortalities - 150-250g (%) +G1_4,,,Mortalities - 250-400g (%) +G1_5,,,Mortalities - 400-800/harvested batches (%) +G1,,,Mortalities - Total - Stocking-harvest (%) +,,Mortalities first 3 days after transport and stocking +G3,,,Mortalities first 3 days after transport and stocking - at day 3 (%) +,,Mortalities first 10 days after transport and stocking +G4,,,Mortalities first 10 days after transport and stocking - at day 10 (%) +,,Vaccinated fish – by disease +G8_1,,,Vaccinated fish - against P. damselae - at stocking (%) +G8_2,,,Vaccinated fish - against V. anguillarum - at stocking (%) +G8_3,,,Vaccinated fish - against Betanodavirus - at stocking (%) +,,Number of antiparasitic treatments (total) +G9,,,Total number of antiparasitic treatments - at harvest (n) +,,Number of antibiotic treatments (total) +G10,,,Total number of antibiotic treatments - at harvest (n) +,,Feed Intake (FI) +G18_5,,,Feed Intake (FI) - Stocking-50g (g fish^-1 day^-1) +G18_1,,,Feed Intake (FI) - 50-150g (g fish^-1 day^-1) +G18_2,,,Feed Intake (FI) - 150-250g (g fish^-1 day^-1) +G18_3,,,Feed Intake (FI) - 250-400g (g fish^-1 day^-1) +G18_4,,,Feed Intake (FI) - 400-800/harvested batches (g fish^-1 day^-1) +,,Stocking density +G19,,,Stocking density at harvest (Kg/m^3) diff --git a/src/main/resources/BATCH/KPI/HATCHERY_INDIVIDUAL.csv b/src/main/resources/BATCH/KPI/HATCHERY_INDIVIDUAL.csv new file mode 100644 index 0000000..306ca40 --- /dev/null +++ b/src/main/resources/BATCH/KPI/HATCHERY_INDIVIDUAL.csv @@ -0,0 +1,60 @@ +KPI CODE,KPI NAME – LEVEL 1,KPI NAME – LEVEL 2,KPI NAME – LEVEL 3 +,Hatchery Total Productivity KPIs +,,Weaned fish +H1,,,Weaned fish (%) +,,Discarded deformed fish +H2_1_1,,,Discarded fish for head deformities - at 1200dd (%) +H2_1_2,,,Discarded fish for head deformities - at 1800dd (%) +H2_1_3,,,Discarded fish for head deformities - at 2400dd (%) +H2_2_1,,,Discarded fish for spinal deformities - at 1200dd (%) +H2_2_2,,,Discarded fish for spinal deformities - at 1800dd (%) +H2_2_3,,,Discarded fish for spinal deformities - at 2400dd (%) +H2_3_1,,,Discarded fish for fin deformities - at 1200dd (%) +H2_3_2,,,Discarded fish for fin deformities - at 1800dd (%) +H2_3_3,,,Discarded fish for fin deformities - at 2400dd (%) +H7,,,Total discarded deformed fish - at 2400dd (%) +,,Discarded slow grower fish +H3_1,,,Discarded slow grower fish - at 1200dd (%) +H3_2,,,Discarded slow grower fish - at 1800dd (%) +H3_3,,,Discarded slow grower fish - at 2400dd (%) +,,Fish produced +H4,,,Fish produced - at 2400dd (%) +,,Fish produced per FTE employees +H5_1_1,,,Number fish/FTE employees in 2018 +H5_1_2,,,Number fish/FTE employees in 2019 +H5_1_3,,,Number fish/FTE employees in 2020 +,,Survival estimation +H6_1,,,Survival estimation - at 1200dd (%) +H6_2,,,Survival estimation - at 1800dd (%) +H6_3,,,Survival estimation - at 2400 dd (%) +,,Vaccinated fish by disease +H15_1,,,Vaccinated fish against P. damselae - at 2400dd (%) +H15_2,,,Vaccinated fish against V. anguillarum - at 2400dd (%) +H15_3,,,Vaccinated fish against Betanodavirus - at 2400dd (%) +,Fish Deformities KPIs +,,Head deformities +H7_1,,,Alive fish with head deformities - at 2400dd (%) +H7_2,,,Alive fish with head deformities - at end of weaning (%) +,,Spinal deformities +H8,,,Alive fish with spinal deformities - at 2400dd (%) +H8_1,,,Alive fish with spinal deformities - at end of weaning (%) +,,Fin deformities +H9,,,Alive fish with fin deformities - at 2400dd (%) +H9_1,,,Alive fish with fin deformities - at end of weaning (%) +,,Swim bladder non inflation +H10,,,Swim bladder non inflation - at 500dd (%) +,Fish Growth KPIs +,,Average Body Weight (ABW) +H11_1,,,Average body weight (BW) - at weaning (g) +H11_2,,,Average body weight (BW) - at 1200dd (g) +H11_3,,,Average body weight (BW) - at 1800dd (g) +H11_4,,,Average body weight (BW) - at 2400dd (g) +,,Specific Growth Rate (SGR) +H12_1,,,Specific Growth Rate (SGR) - at 1200dd (% day^-1) +H12_2,,,Specific Growth Rate (SGR) - at 1800dd (% day^-1) +H12_3,,,Specific Growth Rate (SGR) - at 2400dd (% day^-1) +,Live Feed Requirement KPIs +,,Artemia requirement +H13,,,Artemia requirement - at 2400dd (Kg of Artemia/million fish) +,,Rotifer requirement +H14,,,Rotifers requirement - at 2400dd (Billions rotifer/million fish) diff --git a/src/main/resources/BATCH/KPI/HATCHERY_INDIVIDUAL_CLOSED_BATCHES.csv b/src/main/resources/BATCH/KPI/HATCHERY_INDIVIDUAL_CLOSED_BATCHES.csv new file mode 100644 index 0000000..4ff6df0 --- /dev/null +++ b/src/main/resources/BATCH/KPI/HATCHERY_INDIVIDUAL_CLOSED_BATCHES.csv @@ -0,0 +1,60 @@ +KPI CODE,KPI NAME – LEVEL 1,KPI NAME – LEVEL 2,KPI NAME – LEVEL 3 +,Hatchery Total Productivity KPIs +,,Weaned fish +H1,,,Weaned fish (%) +,,Discarded deformed fish +H2_1_1,,,Discarded fish for head deformities - at 1200dd (%) +H2_1_2,,,Discarded fish for head deformities - at 1800dd (%) +H2_1_3,,,Discarded fish for head deformities - at 2400dd (%) +H2_2_1,,,Discarded fish for spinal deformities - at 1200dd (%) +H2_2_2,,,Discarded fish for spinal deformities - at 1800dd (%) +H2_2_3,,,Discarded fish for spinal deformities - at 2400dd (%) +H2_3_1,,,Discarded fish for fin deformities - at 1200dd (%) +H2_3_2,,,Discarded fish for fin deformities - at 1800dd (%) +H2_3_3,,,Discarded fish for fin deformities - at 2400dd (%) +H7,,,Total discarded deformed fish - at 2400dd (%) +,,Discarded slow grower fish +H3_1,,,Discarded slow grower fish - at 1200dd (%) +H3_2,,,Discarded slow grower fish - at 1800dd (%) +H3_3,,,Discarded slow grower fish - at 2400dd (%) +,,Fish produced +H4,,,Fish produced - at 2400dd (%) +,,Fish produced per FTE employees +H5_1_1,,,Number fish/FTE employees in 2016 +H5_1_2,,,Number fish/FTE employees in 2017 +H5_1_3,,,Number fish/FTE employees in 2018 +,,Survival estimation +H6_1,,,Survival estimation - at 1200dd (%) +H6_2,,,Survival estimation - at 1800dd (%) +H6_3,,,Survival estimation - at 2400 dd (%) +,,Vaccinated fish by disease +H15_1,,,Vaccinated fish against P. damselae - at 2400dd (%) +H15_2,,,Vaccinated fish against V. anguillarum - at 2400dd (%) +H15_3,,,Vaccinated fish against Betanodavirus - at 2400dd (%) +,Fish Deformities KPIs +,,Head deformities +H7_1,,,Alive fish with head deformities - at 2400dd (%) +H7_2,,,Alive fish with head deformities - at end of weaning (%) +,,Spinal deformities +H8,,,Alive fish with spinal deformities - at 2400dd (%) +H8_1,,,Alive fish with spinal deformities - at end of weaning (%) +,,Fin deformities +H9,,,Alive fish with fin deformities - at 2400dd (%) +H9_1,,,Alive fish with fin deformities - at end of weaning (%) +,,Swim bladder non inflation +H10,,,Swim bladder non inflation - at 500dd (%) +,Fish Growth KPIs +,,Average Body Weight (ABW) +H11_1,,,Average body weight (BW) - at weaning (g) +H11_2,,,Average body weight (BW) - at 1200dd (g) +H11_3,,,Average body weight (BW) - at 1800dd (g) +H11_4,,,Average body weight (BW) - at 2400dd (g) +,,Specific Growth Rate (SGR) +H12_1,,,Specific Growth Rate (SGR) - at 1200dd (% day^-1) +H12_2,,,Specific Growth Rate (SGR) - at 1800dd (% day^-1) +H12_3,,,Specific Growth Rate (SGR) - at 2400dd (% day^-1) +,Live Feed Requirement KPIs +,,Artemia requirement +H13,,,Artemia requirement - at 2400dd (Kg of Artemia/million fish) +,,Rotifer requirement +H14,,,Rotifers requirement - at 2400dd (Billions rotifer/million fish) diff --git a/src/main/resources/BATCH/KPI/PRE_ONGROWING.csv b/src/main/resources/BATCH/KPI/PRE_ONGROWING.csv new file mode 100644 index 0000000..dcf0f29 --- /dev/null +++ b/src/main/resources/BATCH/KPI/PRE_ONGROWING.csv @@ -0,0 +1,14 @@ +KPI CODE,KPI NAME – LEVEL 1,KPI NAME – LEVEL 2,KPI NAME – LEVEL 3 +,Pre-grow Total Productivity KPIs,, +,,Deformed fish, +P1,,,Deformed fish (%) +,,Discarded slow grower fish, +P2,,,Discarded slow grower fish (%) +,,Mortalities - total, +P3,,,Mortalities - total (%) +,Fish Growth KPIs,, +,,Specific Growth Rate (SGR), +P4,,,Specific Growth Rate (SGR) (% day^-1) +,Feed Efficiency KPIs,, +,,Feed Conversion Ratio (FCR) , +P5,,,Feed Conversion Ratio (FCR) diff --git a/src/main/resources/BATCH/KPI/PRE_ONGROWING_CLOSED_BATCHES.csv b/src/main/resources/BATCH/KPI/PRE_ONGROWING_CLOSED_BATCHES.csv new file mode 100644 index 0000000..dcf0f29 --- /dev/null +++ b/src/main/resources/BATCH/KPI/PRE_ONGROWING_CLOSED_BATCHES.csv @@ -0,0 +1,14 @@ +KPI CODE,KPI NAME – LEVEL 1,KPI NAME – LEVEL 2,KPI NAME – LEVEL 3 +,Pre-grow Total Productivity KPIs,, +,,Deformed fish, +P1,,,Deformed fish (%) +,,Discarded slow grower fish, +P2,,,Discarded slow grower fish (%) +,,Mortalities - total, +P3,,,Mortalities - total (%) +,Fish Growth KPIs,, +,,Specific Growth Rate (SGR), +P4,,,Specific Growth Rate (SGR) (% day^-1) +,Feed Efficiency KPIs,, +,,Feed Conversion Ratio (FCR) , +P5,,,Feed Conversion Ratio (FCR) diff --git a/src/main/resources/KPI-FORMAT.csv b/src/main/resources/KPI-FORMAT.csv new file mode 100644 index 0000000..aa15182 --- /dev/null +++ b/src/main/resources/KPI-FORMAT.csv @@ -0,0 +1 @@ +KPI CODE,KPI NAME – LEVEL 1,KPI NAME – LEVEL 2,KPI NAME – LEVEL 3,….,KPI NAME – LEVEL N diff --git a/src/main/resources/META-INF/persistence.xml b/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000..a5ee3d2 --- /dev/null +++ b/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,23 @@ + + + + org.gcube.portlets.user.performfishanalytics.shared.Population + org.gcube.portlets.user.performfishanalytics.shared.PopulationType + org.gcube.portlets.user.performfishanalytics.shared.Species + org.gcube.portlets.user.performfishanalytics.shared.Quarter + org.gcube.portlets.user.performfishanalytics.shared.Area + org.gcube.portlets.user.performfishanalytics.shared.Period + org.gcube.portlets.user.performfishanalytics.shared.KPI + + + + + + + + diff --git a/src/main/resources/org/gcube/portlets/user/performfishanalytics/PerformFishAnalytics.gwt.xml b/src/main/resources/org/gcube/portlets/user/performfishanalytics/PerformFishAnalytics.gwt.xml new file mode 100644 index 0000000..5fe5123 --- /dev/null +++ b/src/main/resources/org/gcube/portlets/user/performfishanalytics/PerformFishAnalytics.gwt.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/webapp/PerformFishAnalytics.css b/src/main/webapp/PerformFishAnalytics.css new file mode 100644 index 0000000..8ebbb77 --- /dev/null +++ b/src/main/webapp/PerformFishAnalytics.css @@ -0,0 +1,172 @@ +/** Add css rules here for your application. */ +/** Most GWT widgets already have a style name defined */ +.gwt-DialogBox { + width: 400px; +} + +.dialogVPanel { + margin: 5px; +} + +.serverResponseLabelError { + color: red; +} + +/** Set ids using widget.getElement().setId("idOfElement") */ +#closeButton { + margin: 15px 6px 6px; +} +/** JUST to override the gwt-boostrap body */ +body { + padding: 0px !important; +} + +/** Add css rules here for your application. */ +.modal-result div.modal-body { + position: relative; + max-height: 900px !important; + padding: 15px; + overflow-y: auto; + width: 1024px; + margin: 0 auto; +} + +table.simpletable { + font-family: verdana, arial, sans-serif; + font-size: 10px; + /*color:#333333; + border-width: 1px; + border-color: #999999; + */ + border-collapse: separate; + border-spacing: 2px; + border: 1px solid #e3e3e3; + margin-top: 20px; + background-color: #FFF; + /* margin: 5px 0 0 10px; */ + text-align: center; +} + +table.simpletable colgroup { + /* width: 30%; */ /* background-color: #D3E1F1; */ + +} + +table.simpletable td { + padding: 5px; +} + +table.colgrouptable { + font-family: verdana, arial, sans-serif; + font-size: 10px; + /*color:#333333; + border-width: 1px; + border-color: #999999; + */ + border-collapse: collapse; + border-spacing: 0px; + border: 1px solid #e3e3e3; + margin-top: 20px; + background-color: #FFF; + margin: 5px 0 0 10px; +} + +table.colgrouptable colgroup { + background-color: #D3E1F1; +} + +table.colgrouptable td { + padding: 5px; +} + +.theSubTitle { + font-weight: bold; + font-size: 12px; + margin-top: 20px; + margin-left: 10px; + margin-right: 10px; +} + +table.ext-horizontal-panel { + border-collapse: separate; + border-spacing: 5px; + padding: 10px; + border: 1px solid #e3e3e3; + background-color: #FFF; + margin: 0 auto; +} + +.the_margin { + margin-left: 20px; + margin-right: 20px; +} + +.the_margin_top_bottom { + margin-top: 10px; + margin-bottom: 10px; +} + +.no_border_margin_top { + border: 0px; + margin-top: 20px; +} + +.the_margin_left { + margin-left: 10px !important; +} + +.the_margin_bottom { + margin-bottom: 10px; +} + +.the_margin_top { + margin-top: 10px; +} + +.the_select_custom { + width: 360px !important; +} + +.the_select_custom option { + margin-top: 3px !important; +} + +table.fixedtable { + font-family: verdana, arial, sans-serif; + font-size: 10px; + border-collapse: separate; + border-spacing: 2px; + border: 1px solid #e3e3e3; + margin-top: 20px; + background-color: #FFF; + text-align: center; + table-layout: fixed; +} + +table.fixedtable td { + padding: 2px; +} + +table.fixedtable td { + overflow: hidden; + width: 200px !important; +} + +.to-big-title { + font-weight: bold; + font-size: 18px; + margin-top: 20px; + margin-left: 10px; + margin-right: 10px; + text-align: center; +} + +.the-minimun-height{ + min-height: 300px; +} + +.ext-margin-container{ + + margin-left: 20px; + +} diff --git a/src/main/webapp/PerformFishAnalytics.html b/src/main/webapp/PerformFishAnalytics.html new file mode 100644 index 0000000..daddcc5 --- /dev/null +++ b/src/main/webapp/PerformFishAnalytics.html @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + +Web Application Starter Project + + + + + + + + + + + + + + + + + + +
+ + diff --git a/src/main/webapp/WEB-INF/jsp/PerformFishAnalyticsPortlet_view.jsp b/src/main/webapp/WEB-INF/jsp/PerformFishAnalyticsPortlet_view.jsp new file mode 100644 index 0000000..d8242c9 --- /dev/null +++ b/src/main/webapp/WEB-INF/jsp/PerformFishAnalyticsPortlet_view.jsp @@ -0,0 +1,26 @@ +<%@page contentType="text/html"%> +<%@page pageEncoding="UTF-8"%> + +<%-- Uncomment below lines to add portlet taglibs to jsp +<%@ page import="javax.portlet.*"%> +<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%> + + +--%> + + +<%-- href="<%=request.getContextPath()%>/resources/css/gxt-all.css" --%> + + + + + + + + +
\ No newline at end of file diff --git a/src/main/webapp/WEB-INF/liferay-display.xml b/src/main/webapp/WEB-INF/liferay-display.xml new file mode 100644 index 0000000..e76c775 --- /dev/null +++ b/src/main/webapp/WEB-INF/liferay-display.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/liferay-plugin-package.properties b/src/main/webapp/WEB-INF/liferay-plugin-package.properties new file mode 100644 index 0000000..ce53f58 --- /dev/null +++ b/src/main/webapp/WEB-INF/liferay-plugin-package.properties @@ -0,0 +1,9 @@ +name=PerformFishAnalyticsPortlet +module-group-id=liferay +module-incremental-version=2 +tags= +short-description= +change-log= +page-url=http://www.gcube-system.org +author=gCube +licenses=EUPL \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/liferay-portlet.xml b/src/main/webapp/WEB-INF/liferay-portlet.xml new file mode 100644 index 0000000..85db078 --- /dev/null +++ b/src/main/webapp/WEB-INF/liferay-portlet.xml @@ -0,0 +1,11 @@ + + + + + + PerformFishAnalyticsPortlet + false + false + false + + \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/portlet.xml b/src/main/webapp/WEB-INF/portlet.xml new file mode 100644 index 0000000..24cd64f --- /dev/null +++ b/src/main/webapp/WEB-INF/portlet.xml @@ -0,0 +1,21 @@ + + + + PerformFishAnalyticsPortlet + + PerformFishAnalyticsPortlet + org.gcube.portlets.user.performfishanalytics.portlet.PerformFishAnalyticsPortlet + 0 + + text/html + VIEW + + + PerformFishAnalyticsPortlet + PerformFishAnalyticsPortlet + + + diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..b49d246 --- /dev/null +++ b/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,23 @@ + + + + + + performFishAnalyticsServlet + org.gcube.portlets.user.performfishanalytics.server.PerformFishAnalyticsServiceImpl + + + + performFishAnalyticsServlet + /PerformFishAnalytics/performfish + + + + + PerformFishAnalytics.html + + + diff --git a/src/test/java/database/PrintDatabasePerBatchType.java b/src/test/java/database/PrintDatabasePerBatchType.java new file mode 100644 index 0000000..fee2bd1 --- /dev/null +++ b/src/test/java/database/PrintDatabasePerBatchType.java @@ -0,0 +1,128 @@ +/** + * + */ +package database; + +import javax.persistence.EntityManagerFactory; + +import org.gcube.portlets.user.performfishanalytics.server.database.EntityManagerFactoryCreator; +import org.gcube.portlets.user.performfishanalytics.server.persistence.GenericPersistenceDaoBuilder; +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.Quarter; +import org.gcube.portlets.user.performfishanalytics.shared.Species; + + +/** + * The Class FillDatabasePerBatchType. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 14, 2019 + */ +public class PrintDatabasePerBatchType { + + + /** + * The main method. + * + * @param args the arguments + * @throws Exception the exception + */ + public static void main(String[] args) throws Exception { + System.out.println("START!"); + System.out.println("\nPRINTING DB DATA:"); + printDatabaseData(); + System.out.println("\nDB DATA PRINTED!"); + + System.out.println("\n\nEND!"); + } + + public static void printDatabaseData() throws Exception { + + EntityManagerFactoryCreator.instanceLocalMode(); + EntityManagerFactory entityManagerFactory = EntityManagerFactoryCreator.getEntityManagerFactory(); + + GenericPersistenceDaoBuilder builderPopulation = new GenericPersistenceDaoBuilder(entityManagerFactory, "Population"); + + for(Population population: builderPopulation.getPersistenceEntity().getList()){ + System.out.println("\n\n#### Population: "+population.getName()); + for (PopulationType populationType : population.getListPopulationType()) { + System.out.println("\n\t*PopulationType: "+populationType.getName() +" Type: "+populationType.getType()); + + System.out.println("\t**has Species: "+populationType.getListSpecies().size()); + for (Species species : populationType.getListSpecies()) { + System.out.println("\t\t"+species.getName()); + } + + System.out.println("\t**has Quarter: "+populationType.getListQuarter().size()); + for (Quarter quarter : populationType.getListQuarter()) { + System.out.println("\t\t"+quarter.getName()); + } + + System.out.println("\t**has Area: "+populationType.getListArea().size()); + for (Area area : populationType.getListArea()) { + System.out.println("\t\t"+area.getName()); + } + + System.out.println("\t**has Period: "+populationType.getListPeriod().size()); + for (Period period : populationType.getListPeriod()) { + System.out.println("\t\t"+period.getName()); + } + System.out.println("\t**has KPIs: "+populationType.getListKPI().size()); + for (KPI kpi : populationType.getListKPI()) { + printKPIs(kpi); + } + } + } + + entityManagerFactory.close(); + } + + +// public static void printKPIs(List listKPI, int level){ +// if(listKPI==null || listKPI.isEmpty()) +// return; +// +// //System.out.println("LIST KPI ARE: "+listKPI); +// level++; +// for (KPI kpi : listKPI) { +// +// //System.out.println("\t|%"+level*10+"d|KPI: "+kpi.getCode() +" Value: "+kpi.getValue()); +// System.out.println(String.format("\t%"+level*5+"d|KPI: %s, %s",level, kpi.getCode(), kpi.getValue())); +// } +// +// printKPIs(kpi.getListKPI(), level); +// } + + public static void printKPIs(KPI kpi, int level){ + if(kpi==null) + return; + + System.out.println(String.format("\t%"+level*5+"d|KPI: %s, %s",level, kpi.getCode(), kpi.getName())); + //System.out.println("LIST KPI ARE: "+listKPI); + level++; + if(kpi.getListKPI()==null){ + //System.out.println("[LEAF: "+kpi.getName()+"]"); + //I'm a LEAF + return; + } + for (KPI kpiChild : kpi.getListKPI()) { + printKPIs(kpiChild, kpiChild.getDeepIndex()); + } + } + + + public static void printKPIs(KPI kpi){ + if(kpi==null || kpi.getListKPI()==null) + return; + + System.out.println(String.format("\t%"+kpi.getDeepIndex()*5+"d|KPI: %s, %s",kpi.getDeepIndex(), kpi.getCode(), kpi.getName())); + for (KPI kpiChild : kpi.getListKPI()) { + printKPIs(kpiChild, kpiChild.getDeepIndex()); + } + } + +} diff --git a/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestDBConfiguration.java b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestDBConfiguration.java new file mode 100644 index 0000000..152ff41 --- /dev/null +++ b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestDBConfiguration.java @@ -0,0 +1,30 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server; + +import java.io.File; + +import org.gcube.portlets.user.performfishanalytics.server.database.EntityManagerFactoryCreator; +import org.gcube.portlets.user.performfishanalytics.server.util.FileUtil; + + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Feb 4, 2019 + */ +public class TestDBConfiguration { + + public static void main(String[] args) throws Exception { + String path = EntityManagerFactoryCreator.getPersistenceFolderPath(); + + String connectionURL = EntityManagerFactoryCreator.getJDBCConnectionUrl(true); + //String path = /home/francesco-mangiacrapa/Portal-Bundle-3.0.0-3.2.0/tomcat-6.0.29/persistence/PerformFISH" + System.out.println(path); + System.out.println(connectionURL); + + FileUtil.deleteDirectoryRecursion(new File(path).toPath()); + + } +} diff --git a/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestEntityManagerFactory.java b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestEntityManagerFactory.java new file mode 100644 index 0000000..83ca4e5 --- /dev/null +++ b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestEntityManagerFactory.java @@ -0,0 +1,45 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server; + + +import javax.persistence.EntityManagerFactory; + +import org.gcube.portlets.user.performfishanalytics.server.database.EntityManagerFactoryCreator; +import org.gcube.portlets.user.performfishanalytics.server.persistence.GenericPersistenceDaoBuilder; +import org.gcube.portlets.user.performfishanalytics.shared.Population; +import org.gcube.portlets.user.performfishanalytics.shared.exceptions.DatabaseServiceException; +import org.junit.Before; +import org.junit.Test; + + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 11, 2019 + */ +public class TestEntityManagerFactory { + + EntityManagerFactory entityManagerFactory; + //EntityManager em; + + @Before + public void instanceFactory() throws Exception{ + EntityManagerFactoryCreator mng = EntityManagerFactoryCreator.instanceLocalMode(); + entityManagerFactory = mng.getEntityManagerFactory(); + //em = entityManagerFactory.createEntityManager(); + } + + @Test + public void init() throws DatabaseServiceException{ + + GenericPersistenceDaoBuilder builderPopulation = new GenericPersistenceDaoBuilder(entityManagerFactory, "Population"); + for (int i = 0; i < 10; i++) { + builderPopulation.getPersistenceEntity().insert(new Population("id"+i, "name"+i, "level"+i, "description"+i, null)); + } + + System.out.println("Init done"); + + } +} diff --git a/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestFillDatabase.java b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestFillDatabase.java new file mode 100644 index 0000000..afad138 --- /dev/null +++ b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestFillDatabase.java @@ -0,0 +1,33 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server; + +import javax.persistence.EntityManagerFactory; + +import org.gcube.portlets.user.performfishanalytics.server.database.EntityManagerFactoryCreator; +import org.gcube.portlets.user.performfishanalytics.server.util.DatabaseUtil; + + +/** + * The Class TestFillDatabase. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Feb 12, 2019 + */ +public class TestFillDatabase { + + /** + * The main method. + * + * @param args the arguments + * @throws Exception the exception + */ + public static void main(String[] args) throws Exception { + EntityManagerFactoryCreator mng = EntityManagerFactoryCreator.instanceLocalMode(); + EntityManagerFactory entityManagerFactory = mng.getEntityManagerFactory(); + + new DatabaseUtil().fillDatabaseIfEmpty(entityManagerFactory, null); + + } +} diff --git a/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestGcoreEndpointReader.java b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestGcoreEndpointReader.java new file mode 100644 index 0000000..19e982e --- /dev/null +++ b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestGcoreEndpointReader.java @@ -0,0 +1,34 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server; + +import org.gcube.portlets.user.performfishanalytics.server.util.GcoreEndpointReader; + + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 23, 2019 + */ +public class TestGcoreEndpointReader { + + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(String[] args) { + + try { + + GcoreEndpointReader reader = new GcoreEndpointReader("/gcube/preprod/preVRE", "perform-service", "Application", "org.gcube.application.perform.service.PerformService"); + System.out.println(reader); + } + catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +} diff --git a/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestManageCorrelationOutput.java b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestManageCorrelationOutput.java new file mode 100644 index 0000000..fd0ba03 --- /dev/null +++ b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestManageCorrelationOutput.java @@ -0,0 +1,86 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server; + +import java.util.ArrayList; +import java.util.List; + +import org.gcube.portlets.user.performfishanalytics.shared.FileContentType; +import org.gcube.portlets.user.performfishanalytics.shared.KPI; +import org.gcube.portlets.user.performfishanalytics.shared.OutputFile; + + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 30, 2019 + */ +public class TestManageCorrelationOutput { + + static String csvFile = "correlation_matrix_1.csv600998991800871270"; + static String csvFilePATH = "/tmp/correlation_matrix_1.csv600998991800871270"; + static String csvLegend = "correlation_matrix_legend_1.csv8236429741829427362"; + static String csvLegendPath = "/tmp/correlation_matrix_legend_1.csv8236429741829427362"; + + public static void main(String[] args) { + + OutputFile outputFile = new OutputFile(); + outputFile.setDataType(FileContentType.CSV); + outputFile.setName(csvFile); + outputFile.setServerLocation(csvFilePATH); + + + OutputFile outputLegend = new OutputFile(); + outputLegend.setDataType(FileContentType.CSV); + outputLegend.setName(csvLegend); + outputLegend.setServerLocation(csvLegendPath); + + + OutputFile output3 = new OutputFile(); + output3.setDataType(FileContentType.IMAGE); + output3.setName("fakeFile"); + output3.setServerLocation("/tmp/dropbox-antifreeze-V90v2S"); + + + //new PerformFishAnalyticsServiceImpl().manageOutputsForPerformFishAnalysis(Arrays.asList(outputFile, outputLegend, output3)); + +// String id, String code, String name, String description, +// ArrayList listKPI, PopulationType populationType, int deepIndex +// + List listKPI = new ArrayList(); + KPI kpi1 = new KPI(); + kpi1.setCode("P3"); + kpi1.setName("Mortalities - total %"); + listKPI.add(kpi1); + + KPI kpi2 = new KPI(); + kpi2.setCode("P4"); + kpi2.setName("Specific Growth Rate (SGR) %"); + + listKPI.add(kpi2); + + System.out.println(getCodeKPIForName("Specific Growth Rate (SGR) %",listKPI)); + + } + + /** + * Gets the code kpi for name. + * + * @param name the name + * @return the code kpi for name + */ + public static String getCodeKPIForName(String name, List selectedKPIs){ + + System.out.println("Selected KPIs: "+selectedKPIs); + String purgedName = name.replaceAll("\\%", "").trim(); + for (KPI kpi : selectedKPIs) { + String purgedKPIName = kpi.getName().replaceAll("\\%", "").trim(); + if(purgedKPIName.compareToIgnoreCase(purgedName)==0) + return kpi.getCode(); + } + + return null; + } + +} diff --git a/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestReadCSVFromURL.java b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestReadCSVFromURL.java new file mode 100644 index 0000000..e2f750e --- /dev/null +++ b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestReadCSVFromURL.java @@ -0,0 +1,23 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server; + +import org.gcube.portlets.user.performfishanalytics.shared.csv.CSVFile; + + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 30, 2019 + */ +public class TestReadCSVFromURL { + + private static final String URL_TO_CVS_FILE = "http://data-d.d4science.org/Q2RZOW5MaXA2UEdFMW4wK2tYMHo3cjV1UTNFbEFGMWpHbWJQNStIS0N6Yz0-VLT"; + + public static void main(String[] args) throws Exception { + + CSVFile theCSVFile = new PerformFishAnalyticsServiceImpl().readCSVFile(URL_TO_CVS_FILE); + System.out.println(theCSVFile); + } +} diff --git a/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestRecursion.java b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestRecursion.java new file mode 100644 index 0000000..f3f3045 --- /dev/null +++ b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestRecursion.java @@ -0,0 +1,111 @@ +/** + * + */ + +package org.gcube.portlets.user.performfishanalytics.server; + +import java.util.ArrayList; +import java.util.List; + +import org.gcube.portlets.user.performfishanalytics.server.util.database.data.KPIBatchTypeData; +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 database.PrintDatabasePerBatchType; + +/** + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Jan 18, 2019 + */ +public class TestRecursion { + + public static void main(String[] args) { + + PopulationType batchType_GROW_OUT_INDIVIDUAL = + buildPopulationType( + "GROW_OUT_INDIVIDUAL", "GROW_OUT_INDIVIDUAL DESRIPTION", null); + KPI Losses = KPIBatchTypeData.getLosses(batchType_GROW_OUT_INDIVIDUAL); + KPI TreatmentsForGrowOut = + KPIBatchTypeData.getTreatmentsForGrowOutIndividual(batchType_GROW_OUT_INDIVIDUAL); + ArrayList listKPI = new ArrayList(); + listKPI.add(Losses); + listKPI.add(TreatmentsForGrowOut); + System.out.println("Converting START"); + List listGWTKPI = new ArrayList(listKPI.size()); + for (KPI toKPI : listKPI) { + KPI gwtKPI = convert(toKPI); + // gwtKPI.setLeaf(toKPI.getListKPI()==null || + // toKPI.getListKPI().isEmpty()); + listGWTKPI.add(gwtKPI); + } + System.out.println("PRINTING START"); + for (KPI kpi : listGWTKPI) { + PrintDatabasePerBatchType.printKPIs(kpi, kpi.getDeepIndex()); + } + } + + public static KPI convert(KPI kpi) { + + if (kpi.getListKPI() == null) { + System.out.println("LEAF " + kpi); + return getGWTKPI(kpi, null); + } + KPI gwtKPI = getGWTKPI(kpi, null); + System.out.println("Converted: " + gwtKPI); + for (KPI kpiChild : kpi.getListKPI()) { + KPI convertedChild = convert(kpiChild); + if (gwtKPI.getListKPI() == null) { + List listKPI = new ArrayList(); + gwtKPI.setListKPI(listKPI); + } + gwtKPI.getListKPI().add(convertedChild); + } + System.out.println("Filled children of: " + gwtKPI.getName()); + if (gwtKPI.getListKPI() != null) { + for (KPI chKPI : gwtKPI.getListKPI()) { + System.out.println("\t" + chKPI); + } + } + return gwtKPI; + } + + /** + * Gets the gwtkpi. + * + * @param toKPI + * the to kpi + * @param populationType + * the population type + * @return the gwtkpi + */ + public static 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; + } + + /** + * Builds the population type. + * + * @param type + * the type + * @param description + * the description + * @param poulation + * the poulation + * @return the population type + */ + public static PopulationType buildPopulationType( + String type, String description, Population poulation) { + + return new PopulationType( + java.util.UUID.randomUUID().toString(), type, type, description, + poulation); + } +} diff --git a/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestRetryGetRequest.java b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestRetryGetRequest.java new file mode 100644 index 0000000..656fb99 --- /dev/null +++ b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestRetryGetRequest.java @@ -0,0 +1,31 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server; + +import org.gcube.portlets.user.performfishanalytics.server.util.HttpCallerUtil; + + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Feb 7, 2019 + */ +public class TestRetryGetRequest { + + + private static String serviceURL = "http://thepincopallinourl"; + + public static void main(String[] args) { + + try { + HttpCallerUtil httpCaller = new HttpCallerUtil(serviceURL, null, null); + + httpCaller.performGETRequestWithRetry(null, null, 5); + } + catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +} diff --git a/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestWPSResponseParser.java b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestWPSResponseParser.java new file mode 100644 index 0000000..5db5001 --- /dev/null +++ b/src/test/java/org/gcube/portlets/user/performfishanalytics/server/TestWPSResponseParser.java @@ -0,0 +1,89 @@ +/** + * + */ +package org.gcube.portlets.user.performfishanalytics.server; + +import java.io.InputStream; + +import org.apache.commons.io.IOUtils; +import org.gcube.portlets.user.performfishanalytics.server.util.DataMinerUtil; +import org.gcube.portlets.user.performfishanalytics.server.util.dataminer.DMServiceResponse; +import org.gcube.portlets.user.performfishanalytics.server.util.xml.WPSParserUtil; + + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 24, 2019 + */ +public class TestWPSResponseParser { + + /** + * The main method. + * + * @param args the arguments + * @throws Exception + */ + public static void main(String[] args) throws Exception { + +// HashMap mappings = new HashMap(); +//// mappings.put("xmlns", "http://www.opengis.net/sld"); +// mappings.put("wps", "http://www.opengis.net/wps/1.0.0"); +// mappings.put("xsi", "http://www.w3.org/2001/XMLSchema-instance"); +// mappings.put("ows", "http://www.opengis.net/ows/1.1"); +// mappings.put("lang", "en-US"); +// mappings.put("ogr", "http://ogr.maptools.org/"); +// mappings.put("gml", "http://www.opengis.net/gml"); +// mappings.put("d4science", "http://www.d4science.org"); +// mappings.put(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI); +// NamespaceContextMap context = new NamespaceContextMap(mappings); + + InputStream wpsResponseStream = WPSParserUtil.class.getResourceAsStream("WebProcessingService.xml"); + String wpsRS = IOUtils.toString(wpsResponseStream); + DMServiceResponse resp = DataMinerUtil.parseResult(null, wpsRS); + + System.out.println(resp); + + //System.out.println(wpsRS); + + //String xpathExpression = "//sld:UserStyle[sld:IsDefault=1]/sld:Name"; //FIND DEFAULT STYLE NAME + + //String xpathExpression = "//wps:ProcessOutputs/wps:Output/wps:Data/wps:ComplexData/ogr:FeatureCollection/gml:featureMember/ogr:Result"; + + //List listWPSResult = XpathParserUtil.getTextFromXPathExpression(context, wpsRS, xpathExpression); + +// Document doc = WPSParserUtil.inputStreamToW3CDocument(wpsResponseStream); +// List listResponse = WPSParserUtil.getListDataMinerOutputDataFromWPSResponse(doc); +// +// for (DataMinerOutputData dataMinerOutputData : listResponse) { +// System.out.println(dataMinerOutputData); +// } + +// for (String result : listWPSResult) { +// System.out.println("Result: "+result); +// } + + +// LinkedHashMap exclusiveStyles = new LinkedHashMap(); +// +// //DEFAULT STYLE IS FOUND +// if(listWPSResult.size()>0 || !listWPSResult.get(0).isEmpty()){ +// +// String defaultStyle = listWPSResult.get(0); +// exclusiveStyles.put(defaultStyle, defaultStyle); +// } +// +// xpathExpression = "//sld:UserStyle/sld:Name"; //FIND OTHER STYLES NAMES AND ADD INTO LIST +// List allStyles = XpathParserUtil.getTextFromXPathExpression(context, wpsResponse, xpathExpression); +// +// for (String style : allStyles) { +// exclusiveStyles.put(style, style); +// } +// +// listStylesNames.addAll(exclusiveStyles.keySet()); +// +// +// for (String string : listStylesNames) { +// System.out.println("style: "+string); + } +} diff --git a/src/test/resources/WebProcessingService.xml b/src/test/resources/WebProcessingService.xml new file mode 100644 index 0000000..42bcadb --- /dev/null +++ b/src/test/resources/WebProcessingService.xml @@ -0,0 +1,34 @@ + + + + org.gcube.dataanalysis.wps.statisticalmanager.synchserver.mappedclasses.transducerers.PERFORMFISH_ANALYSIS + PERFORMFISH_ANALYSIS + + + Process successful + + + + non_deterministic_output + NonDeterministicOutput + + + + + + http://data.d4science.org/cEhyd3ZDQ0pkeFd5dUc0YnV2REpmeFpUand4d09aR0JHbWJQNStIS0N6Yz0-VLT + Log of the computation + text/csv + + + http://data.d4science.org/cEhyd3ZDQ0pkeFd5dUc0YnV2REpmKzdWYU5FOXp3bGxHbWJQNStIS0N6Yz0-VLT + outputCharts + application/d4science + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/org/gcube/portlets/user/performfishanalytics/PerformFishAnalyticsJUnit.gwt.xml b/src/test/resources/org/gcube/portlets/user/performfishanalytics/PerformFishAnalyticsJUnit.gwt.xml new file mode 100644 index 0000000..287ccec --- /dev/null +++ b/src/test/resources/org/gcube/portlets/user/performfishanalytics/PerformFishAnalyticsJUnit.gwt.xml @@ -0,0 +1,9 @@ + + + + + + + + +