branch from private

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/widgets/workspace-uploader@119338 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Francesco Mangiacrapa 2015-10-02 09:46:32 +00:00
commit b2863f4c41
88 changed files with 8213 additions and 0 deletions

38
.classpath Normal file
View File

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

53
.project Normal file
View File

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>workspace-uploader-TRUNK</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.google.gdt.eclipse.core.webAppProjectValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.google.gwt.eclipse.core.gwtProjectValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
<nature>com.google.gwt.eclipse.core.gwtNature</nature>
</natures>
</projectDescription>

13
.settings/.jsdtscope Normal file
View File

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

View File

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

View File

@ -0,0 +1,5 @@
eclipse.preferences.version=1
jarsExcludedFromWebInfLib=
lastWarOutDir=/home/francesco-mangiacrapa/wseclipseluna/workspace-uploader-TRUNK/target/workspace-uploader-1.0.0-SNAPSHOT
warSrcDir=src/main/webapp
warSrcDirIsOutput=false

View File

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

View File

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

View File

@ -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

View File

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

View File

@ -0,0 +1,4 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

View File

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

View File

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

View File

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

View File

@ -0,0 +1 @@
Window

View File

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

1
.tern-project Normal file
View File

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

0
distro/INSTALL Normal file
View File

7
distro/LICENSE Normal file
View File

@ -0,0 +1,7 @@
gCube System - License
------------------------------------------------------------
The gCube/gCore software is licensed as Free Open Source software conveying to the EUPL (http://ec.europa.eu/idabc/eupl).
The software and documentation is provided by its authors/distributors "as is" and no expressed or
implied warranty is given for its use, quality or fitness for a particular case.

4
distro/MAINTAINERS Normal file
View File

@ -0,0 +1,4 @@
Mantainers
-------
* Francesco Mangiacrapa (francesco.mangiacrapa@isti.cnr.it), CNR Pisa, Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo"

44
distro/README Normal file
View File

@ -0,0 +1,44 @@
The gCube System - WorkspacePortlet
------------------------------------------------------------
This work has been partially supported by the following European projects: DILIGENT (FP6-2003-IST-2),
D4Science (FP7-INFRA-2007-1.2.2), D4Science-II (FP7-INFRA-2008-1.2.2), iMarine (FP7-INFRASTRUCTURES-2011-2),
and EUBrazilOpenBio (FP7-ICT-2011-EU-Brazil), Parthenos (H2020-INFRADEV-1-2014-1), BlueBridge (H2020-EINFRA-2015-1)
Authors
-------
* Francesco Mangiacrapa (francesco.mangiacrapa@isti.cnr.it), CNR Pisa,
Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo".
Version and Release Date
------------------------
v. 6.8.0 July 2015
Description
-----------
The Workspace Uploader
Download information
--------------------
Source code is available from SVN:
Binaries can be downloaded from:
n/a
Documentation
-------------
Documentation is available on-line from the Projects Documentation Wiki:
Licensing
---------
This software is licensed under the terms you may find in the file named "LICENSE" in this directory.

6
distro/changelog.xml Normal file
View File

@ -0,0 +1,6 @@
<ReleaseNotes>
<Changeset component="org.gcube.portlets-widgets.workspace-uploader.1-0-0"
date="2015-08-07">
<Change>first release</Change>
</Changeset>
</ReleaseNotes>

48
distro/descriptor.xml Normal file
View File

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

25
distro/profile.xml Normal file
View File

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

1
distro/svnpath.txt Normal file
View File

@ -0,0 +1 @@
${scm.url}

305
pom.xml Normal file
View File

@ -0,0 +1,305 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>maven-parent</artifactId>
<groupId>org.gcube.tools</groupId>
<version>1.0.0</version>
<relativePath />
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.gcube.portlets.widgets</groupId>
<artifactId>workspace-uploader</artifactId>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>Workspace Uploader Widget</name>
<scm>
<connection>scm:svn:http://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/widgets/${project.artifactId}</connection>
<developerConnection>scm:https://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/widgets/${project.artifactId}</developerConnection>
<url>http://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/widgets/${project.artifactId}</url>
</scm>
<properties>
<!-- Convenience property to set the GWT version -->
<gwtVersion>2.7.0</gwtVersion>
<distroDirectory>distro</distroDirectory>
<!-- GWT needs at least java 1.6 -->
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<webappDirectory>${project.build.directory}/${project.build.finalName}</webappDirectory>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>maven-portal-bom</artifactId>
<version>LATEST</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<profiles>
<profile>
<id>localRun</id>
<dependencies>
<dependency>
<groupId>xerces</groupId>
<artifactId>xerces</artifactId>
<version>2.4.0</version>
</dependency>
</dependencies>
</profile>
</profiles>
<dependencies>
<!-- UNCOMMENT THIS TO RUN IN DEVO MODE -->
<!-- <dependency> -->
<!-- <groupId>xerces</groupId> -->
<!-- <artifactId>xerces</artifactId> -->
<!-- <version>2.4.0</version> -->
<!-- </dependency> -->
<!-- Google Web Toolkit (GWT) -->
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-user</artifactId>
<version>${gwtVersion}</version>
<scope>compile</scope>
</dependency>
<!-- Google Web Toolkit (GWT) -->
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-servlet</artifactId>
<version>${gwtVersion}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.portlets.user</groupId>
<artifactId>gcube-widgets</artifactId>
<scope>provided</scope>
</dependency>
<!-- FWS -->
<dependency>
<groupId>org.gcube.resources.discovery</groupId>
<artifactId>ic-client</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-scope-maps</artifactId>
<scope>compile</scope>
</dependency>
<!-- END FWS -->
<dependency>
<groupId>org.gcube.dvos</groupId>
<artifactId>usermanagement-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.portal</groupId>
<artifactId>custom-portal-handler</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.applicationsupportlayer</groupId>
<artifactId>aslcore</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.applicationsupportlayer</groupId>
<artifactId>accesslogger</artifactId>
<scope>provided</scope>
</dependency>
<!-- HOME LIBRARY -->
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>home-library-model</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>home-library-jcr</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>home-library</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>asm-all</artifactId>
<groupId>asm</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<scope>provided</scope>
</dependency>
<!-- LOGGER -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.portal</groupId>
<artifactId>social-networking-library</artifactId>
<version>[1.0.0-SNAPSHOT,2.0.0-SNAPSHOT)</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.applicationsupportlayer</groupId>
<artifactId>aslsocial</artifactId>
<scope>provided</scope>
</dependency>
<!-- PORTLET -->
<dependency>
<groupId>com.liferay.portal</groupId>
<artifactId>portal-service</artifactId>
<version>6.0.6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.portlet</groupId>
<artifactId>portlet-api</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<!-- Generate compiled stuff in the folder used for developing mode -->
<outputDirectory>${webappDirectory}/WEB-INF/classes</outputDirectory>
<plugins>
<!-- GWT Maven Plugin -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>gwt-maven-plugin</artifactId>
<version>${gwtVersion}</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<!-- <goal>test</goal> -->
</goals>
</execution>
</executions>
<!-- Plugin configuration. There are many available options, see gwt-maven-plugin
documentation at codehaus.org -->
<configuration>
<runTarget>WorkspacePortlet.html</runTarget>
<hostedWebapp>${webappDirectory}</hostedWebapp>
</configuration>
</plugin>
<!-- Copy static web files before executing gwt:run -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>exploded</goal>
</goals>
</execution>
</executions>
<configuration>
<webappDirectory>${webappDirectory}</webappDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<!-- SA Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2</version>
<configuration>
<descriptors>
<descriptor>${distroDirectory}/descriptor.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>servicearchive</id>
<phase>install</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>copy-profile</id>
<phase>install</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>target</outputDirectory>
<resources>
<resource>
<directory>${distroDirectory}</directory>
<filtering>true</filtering>
<includes>
<include>profile.xml</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

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

View File

@ -0,0 +1,57 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.client;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
/**
* The Class BaloonPanel.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Feb 25, 2015
*/
public class BaloonPanelUpload extends PopupPanel{
private boolean shouldHide = false;
/**
* @return the shouldHide
*/
public boolean isShouldHide() {
return shouldHide;
}
/**
* Instantiates a new baloon panel go top.
*
* @param baloonText the baloon text
* @param shouldHide true if the popup should be automatically hidden when the user clicks outside of it or the history token changes.
*/
public BaloonPanelUpload(ScrollPanel panel, boolean shouldHide) {
super(shouldHide);
this.shouldHide = shouldHide;
setAutoHideEnabled(shouldHide);
setStyleName("baloonGoTop");
// some sample widget will be content of the balloon
// HTML text = new HTML(baloonText);
setWidget(panel);
}
/* (non-Javadoc)
* @see com.google.gwt.user.client.ui.PopupPanel#show()
*/
@Override
public void show() {
super.show();
}
/* (non-Javadoc)
* @see com.google.gwt.user.client.ui.PopupPanel#hide()
*/
@Override
public void hide() {
super.hide();
}
}

View File

@ -0,0 +1,151 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.client;
import org.gcube.portlets.user.gcubewidgets.client.popup.GCubeDialog;
import org.gcube.portlets.widgets.workspaceuploader.client.resource.WorkspaceUploaderResources;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ScrollPanel;
/**
* The Class MyDialogBox.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 9, 2015
*/
@SuppressWarnings("deprecation")
public class ClosableDialog extends GCubeDialog {
private Image close = WorkspaceUploaderResources.getImageCloseWin();
private HorizontalPanel captionPanel = new HorizontalPanel();
private HTML title = new HTML("");
/**
* Instantiates a new my dialog box.
*
* @param panel the panel
* @param autoHide the auto hide
* @param modal the modal
*/
public ClosableDialog(ScrollPanel panel, boolean autoHide, boolean modal, String captionTitle) {
super(autoHide, modal);
init(captionTitle);
// super.setGlassEnabled(true);
// super.setAnimationEnabled(true);
setWidget(panel);
}
/**
* Instantiates a new my dialog box.
*
* @param panel the panel
* @param autoHide the auto hide
* @param modal the modal
*/
public ClosableDialog(boolean autoHide, boolean modal, String captionTitle) {
super(autoHide, modal);
init(captionTitle);
}
private void init(String captionTitle){
Element td = getCellElement(0, 1);
DOM.removeChild(td, (Element) td.getFirstChildElement());
DOM.appendChild(td, captionPanel.getElement());
captionPanel.setStyleName("ClosableDialogCaption");
title.setHTML(captionTitle);
captionPanel.add(title);
close.setStyleName("CloseButton");
captionPanel.add(close);
addStyleName("ClosableDialog");
}
/**
* Instantiates a new my dialog box.
*
* @param panel the panel
* @param autoHide the auto hide
*/
public ClosableDialog(ScrollPanel panel, boolean autoHide, String captionTitle) {
this(panel, autoHide, false, captionTitle);
}
/**
* Instantiates a new my dialog box.
*
* @param panel the panel
*/
public ClosableDialog(ScrollPanel panel) {
this(panel, false, "");
}
/* (non-Javadoc)
* @see com.google.gwt.user.client.ui.DialogBox#getHTML()
*/
@Override
public String getHTML() {
return this.title.getHTML();
}
/* (non-Javadoc)
* @see com.google.gwt.user.client.ui.DialogBox#getText()
*/
@Override
public String getText() {
return this.title.getText();
}
/* (non-Javadoc)
* @see com.google.gwt.user.client.ui.DialogBox#setHTML(java.lang.String)
*/
@Override
public void setHTML(String html) {
this.title.setHTML(html);
}
/* (non-Javadoc)
* @see com.google.gwt.user.client.ui.DialogBox#setText(java.lang.String)
*/
@Override
public void setText(String text) {
this.title.setText(text);
}
/* (non-Javadoc)
* @see com.google.gwt.user.client.ui.DialogBox#onPreviewNativeEvent(com.google.gwt.user.client.Event.NativePreviewEvent)
*/
@Override
protected void onPreviewNativeEvent(NativePreviewEvent event) {
NativeEvent nativeEvent = event.getNativeEvent();
if (!event.isCanceled() && (event.getTypeInt() == Event.ONCLICK)
&& isCloseEvent(nativeEvent)) {
this.hide();
}
super.onPreviewNativeEvent(event);
}
/**
* Checks if is close event.
*
* @param event the event
* @return true, if is close event
*/
private boolean isCloseEvent(NativeEvent event) {
return event.getEventTarget().equals(close.getElement());// compares
// equality
// of the
// underlying
// DOM
// elements
}
}

View File

@ -0,0 +1,32 @@
package org.gcube.portlets.widgets.workspaceuploader.client;
import com.google.gwt.core.client.GWT;
/**
* The Class ConstantsWorkspaceUploader.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 3, 2015
*/
public class ConstantsWorkspaceUploader {
public static final String WORKSPACE_UPLOADER_SERVLET = GWT.getModuleBaseURL() + "workspaceUploadServlet";
public static final String WORKSPACE_UPLOADER_SERVLET_STREAM = GWT.getModuleBaseURL() + "workspaceUploadServletStream";
public static final String SERVER_ERROR = "Sorry, an error has occurred on the server when";
public static final String TRY_AGAIN = "Try again";
// UPLOAD SERVLET PARAMETERS
public static final String IS_OVERWRITE = "isOverwrite";
public static final String UPLOAD_TYPE = "uploadType";
public static final String ID_FOLDER = "idFolder";
public static final String UPLOAD_FORM_ELEMENT = "uploadFormElement";
public static final String CLIENT_UPLOAD_KEYS = "client_upload_keys";
public static final String CANCEL_UPLOAD = "cancel_upload";
public static final String JSON_CLIENT_KEYS = "ClientKeys";
public static final String MY_UPLOADS = "My Uploads";
}

View File

@ -0,0 +1,70 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.client;
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.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.HasVerticalAlignment;
import com.google.gwt.user.client.ui.Image;
/**
* The Class DialogResult.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* @Apr 4, 2014
*/
public class DialogResult extends DialogBox implements ClickHandler {
/**
* Instantiates a new dialog result.
*
* @param img
* the img
* @param title
* the title
* @param msgTxt
* the msg txt
*/
public DialogResult(Image img, String title, String msgTxt) {
setText(title);
Button closeButton = new Button("Ok", this);
HTML msg = new HTML("<center>" + msgTxt + "</center>", true);
msg.getElement().getStyle().setPadding(10, Unit.PX);
DockPanel dock = new DockPanel();
dock.setSpacing(4);
dock.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
dock.getElement().getStyle().setBackgroundColor("#FFF");
dock.add(closeButton, DockPanel.SOUTH);
if (img != null)
dock.add(img, DockPanel.WEST);
dock.add(msg, DockPanel.CENTER);
dock.setCellHorizontalAlignment(closeButton, DockPanel.ALIGN_CENTER);
dock.setWidth("100%");
dock.setHeight("100%");
// setWidget(dock);
add(dock);
// setWidth("100%");
}
/*
* (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();
}
}

View File

@ -0,0 +1,41 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.client;
import com.google.gwt.core.shared.GWT;
/**
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 9, 2015
*/
public class StringUtil {
/**
* Puts ellipses in input strings that are longer than than maxCharacters. Shorter strings or
* null is returned unchanged.
* @param input the input string that may be subjected to shortening
* @param maxCharacters the maximum characters that are acceptable for the unshortended string. Must be at least 3, otherwise a string with ellipses is too long already.
* @param the number of characters that should appear after the ellipsis (0 or larger)
*/
public static String ellipsize(String input, int maxCharacters, int charactersAfterEllipsis) {
try{
if(maxCharacters < 3) {
throw new IllegalArgumentException("maxCharacters must be at least 3 because the ellipsis already take up 3 characters");
}
if(maxCharacters - 3 < charactersAfterEllipsis) {
throw new IllegalArgumentException("charactersAfterEllipsis must be less than maxCharacters-3");
}
if (input == null || input.length() < maxCharacters) {
return input;
}
return input.substring(0, maxCharacters - 3 - charactersAfterEllipsis) + "..." + input.substring(input.length() - charactersAfterEllipsis);
}catch(Exception e){
GWT.log(e.getMessage());
return input;
}
}
}

View File

@ -0,0 +1,106 @@
package org.gcube.portlets.widgets.workspaceuploader.client;
import org.gcube.portlets.widgets.workspaceuploader.client.uploader.DialogUpload;
import org.gcube.portlets.widgets.workspaceuploader.client.uploader.DialogUpload.UPLOAD_TYPE;
import org.gcube.portlets.widgets.workspaceuploader.client.uploader.MultipleDilaogUploadStream;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.ScriptInjector;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class WorkspaceUploader implements EntryPoint {
String headerTitle = "Upload in your Workspace";
String parentId;
private Button buttonUploader;
private Button buttonDirect;
public void onModuleLoad() {
boolean jQueryLoaded = isjQueryLoaded();
GWT.log("jQueryLoaded: "+jQueryLoaded);
GWT.log("Injected : http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js");
if (!jQueryLoaded) {
ScriptInjector.fromUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js")
.setWindow(ScriptInjector.TOP_WINDOW)
.inject();
}
// ScriptInjector.fromUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js")
// .setWindow(ScriptInjector.TOP_WINDOW)
// .inject();
buttonUploader = new Button("Upload in your Workspace");
buttonDirect = new Button("Upload (Stream) in your Workspace");
enableUpload(false);
WorkspaceUploaderServiceAsync.Util.getInstance().getWorkspaceId(
new AsyncCallback<String>() {
@Override
public void onSuccess(String result) {
if (result != null) {
parentId = result;
enableUpload(true);
} else {
Window.alert("An error occurred on recovering workspace, try again later");
enableUpload(false);
}
}
@Override
public void onFailure(Throwable caught) {
Window.alert("An error occurred on recovering workspace, try again later");
enableUpload(false);
}
});
buttonUploader.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
DialogUpload uploader = new DialogUpload(headerTitle, parentId, UPLOAD_TYPE.File);
uploader.center();
}
});
buttonDirect.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
MultipleDilaogUploadStream uploadStream = new MultipleDilaogUploadStream(headerTitle, parentId, org.gcube.portlets.widgets.workspaceuploader.client.uploader.DialogUploadStream.UPLOAD_TYPE.File);
uploadStream.center();
}
});
// RootPanel.get("workspace-uploader").add(buttonUploader);
RootPanel.get("workspace-uploader").add(buttonDirect);
}
private void enableUpload(boolean bool){
buttonUploader.setEnabled(bool);
buttonDirect.setEnabled(bool);
}
/**
* Checks if is j query loaded.
*
* @return true, if is j query loaded
*/
private native boolean isjQueryLoaded() /*-{
return (typeof $wnd['jQuery'] !== 'undefined');
}-*/;
}

View File

@ -0,0 +1,33 @@
package org.gcube.portlets.widgets.workspaceuploader.client;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem;
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("workspaceUploaderService")
public interface WorkspaceUploaderService extends RemoteService {
/**
* @param identifier
* @return
* @throws Exception
*/
WorkspaceUploaderItem getUploadStatus(String identifier) throws Exception;
/**
* @param parentId
* @param itemName
* @return
* @throws Exception
*/
String itemExistsInWorkpaceFolder(String parentId, String itemName) throws Exception;
/**
* @return
* @throws Exception
*/
String getWorkspaceId() throws Exception;
}

View File

@ -0,0 +1,74 @@
package org.gcube.portlets.widgets.workspaceuploader.client;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
* The Interface WorkspaceUploaderServiceAsync.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 4, 2015
*/
public interface WorkspaceUploaderServiceAsync
{
/**
* Gets the upload status.
*
* @param uploaderId the uploader id
* @param callback the callback
* @return the upload status
*/
void getUploadStatus(String uploaderId, AsyncCallback<WorkspaceUploaderItem> callback );
/**
* Item exists in workpace folder.
*
* @param parentId the parent id
* @param itemName the item name
* @param callback the callback
*/
void itemExistsInWorkpaceFolder(String parentId, String itemName, AsyncCallback<String> callback );
/**
* Utility class to get the RPC Async interface from client-side code.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 4, 2015
*/
public static final class Util
{
private static WorkspaceUploaderServiceAsync instance;
/**
* Gets the single instance of Util.
*
* @return single instance of Util
*/
public static final WorkspaceUploaderServiceAsync getInstance()
{
if ( instance == null )
{
instance = (WorkspaceUploaderServiceAsync) GWT.create( WorkspaceUploaderService.class );
}
return instance;
}
/**
* Instantiates a new util.
*/
private Util()
{
// Utility class should not be instantiated
}
}
void getWorkspaceId(AsyncCallback<String> callback);
}

View File

@ -0,0 +1,67 @@
package org.gcube.portlets.widgets.workspaceuploader.client.events;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.user.client.ui.HorizontalPanel;
/**
* The Class CancelUploadEvent.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 7, 2015
*/
public class CancelUploadEvent extends GwtEvent<CancelUploadEventHandler> {
public static Type<CancelUploadEventHandler> TYPE = new Type<CancelUploadEventHandler>();
private HorizontalPanel hp;
private String fileName;
private WorkspaceUploaderItem uploader;
/**
* @return the hp
*/
public HorizontalPanel getHp() {
return hp;
}
/**
* Instantiates a new cancel upload event.
*/
public CancelUploadEvent(WorkspaceUploaderItem uploader, HorizontalPanel hp, String fileName) {
this.uploader = uploader;
this.hp = hp;
this.fileName = fileName;
}
/**
* @return the uploader
*/
public WorkspaceUploaderItem getUploader() {
return uploader;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#getAssociatedType()
*/
@Override
public Type<CancelUploadEventHandler> getAssociatedType() {
return TYPE;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared.EventHandler)
*/
@Override
protected void dispatch(CancelUploadEventHandler handler) {
handler.onCancelUpload(this);
}
/**
* @return
*/
public String getFileName() {
return fileName;
}
}

View File

@ -0,0 +1,21 @@
package org.gcube.portlets.widgets.workspaceuploader.client.events;
import com.google.gwt.event.shared.EventHandler;
/**
* The Interface CancelUploadEventHandler.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 7, 2015
*/
public interface CancelUploadEventHandler extends EventHandler {
/**
* On cancel upload.
*
* @param deleteTimerEvent the delete timer event
*/
void onCancelUpload(CancelUploadEvent deleteTimerEvent);
}

View File

@ -0,0 +1,37 @@
package org.gcube.portlets.widgets.workspaceuploader.client.events;
import com.google.gwt.event.shared.GwtEvent;
/**
* The Class OpenMyUploadsEvent.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 30, 2015
*/
public class OpenMyUploadsEvent extends GwtEvent<OpenMyUploadsEventHandler> {
public static Type<OpenMyUploadsEventHandler> TYPE = new Type<OpenMyUploadsEventHandler>();
/**
* Instantiates a new open my uploads event.
*/
public OpenMyUploadsEvent() {
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#getAssociatedType()
*/
@Override
public Type<OpenMyUploadsEventHandler> getAssociatedType() {
return TYPE;
}
/* (non-Javadoc)
* @see com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared.EventHandler)
*/
@Override
protected void dispatch(OpenMyUploadsEventHandler handler) {
handler.onOpenMyUploads(this);
}
}

View File

@ -0,0 +1,19 @@
package org.gcube.portlets.widgets.workspaceuploader.client.events;
import com.google.gwt.event.shared.EventHandler;
/**
* The Interface OpenMyUploadsEventHandler.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Sep 30, 2015
*/
public interface OpenMyUploadsEventHandler extends EventHandler {
/**
* On open my uploads.
*
* @param openMyUploadsEvent
* the open my uploads event
*/
void onOpenMyUploads(OpenMyUploadsEvent openMyUploadsEvent);
}

View File

@ -0,0 +1,78 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.client.resource;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
/**
* The Interface WorkspaceUploaderIcons.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 24, 2015
*/
public interface WorkspaceUploaderIcons extends ClientBundle {
/**
* Loading.
*
* @return the image resource
*/
@Source("loader2.gif")
ImageResource loading();
/**
* Failed.
*
* @return the image resource
*/
@Source("failed.png")
ImageResource failed();
/**
* Completed.
*
* @return the image resource
*/
@Source("completed.gif")
ImageResource completed();
/**
* Cancel.
*
* @return the image resource
*/
@Source("cancel.png")
ImageResource cancel();
/**
* Cancel red.
*
* @return the image resource
*/
@Source("cancel_red.png")
ImageResource cancelRed();
/**
* Close win.
*
* @return the image resource
*/
@Source("closewindow.jpg")
ImageResource closeWin();
/**
* Wait icon.
*
* @return the image resource
*/
@Source("wait.png")
ImageResource waitIcon();
/**
* @return
*/
@Source("upload.gif")
ImageResource uploadIcon();
}

View File

@ -0,0 +1,93 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.client.resource;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Image;
/**
* The Class WorkspaceUploaderResources.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 24, 2015
*/
public class WorkspaceUploaderResources {
public static final WorkspaceUploaderIcons ICONS = GWT.create(WorkspaceUploaderIcons.class);
/**
* Gets the image loading.
*
* @return the image loading
*/
public static Image getImageLoading(){
return new Image(ICONS.loading());
}
/**
* Gets the image failed.
*
* @return the image failed
*/
public static Image getImageFailed(){
return new Image(ICONS.failed());
}
/**
* Gets the image completed.
*
* @return the image completed
*/
public static Image getImageCompleted(){
return new Image(ICONS.completed());
}
/**
* Gets the image cancel.
*
* @return the image cancel
*/
public static Image getImageCancel(){
return new Image(ICONS.cancel());
}
/**
* Gets the image cancel red.
*
* @return the image cancel red
*/
public static Image getImageCancelRed(){
return new Image(ICONS.cancelRed());
}
/**
* Gets the image close win.
*
* @return the image close win
*/
public static Image getImageCloseWin(){
return new Image(ICONS.closeWin());
}
/**
* Gets the image wait.
*
* @return the image wait
*/
public static Image getImageWait(){
return new Image(ICONS.waitIcon());
}
/**
* Gets the image upload.
*
* @return the image upload
*/
public static Image getImageUpload(){
return new Image(ICONS.uploadIcon());
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 779 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 639 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 741 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 541 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 655 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 400 B

View File

@ -0,0 +1,347 @@
package org.gcube.portlets.widgets.workspaceuploader.client.uploader;
import org.gcube.portlets.widgets.workspaceuploader.client.ConstantsWorkspaceUploader;
import org.gcube.portlets.widgets.workspaceuploader.client.DialogResult;
import org.gcube.portlets.widgets.workspaceuploader.client.WorkspaceUploaderServiceAsync;
import org.gcube.portlets.widgets.workspaceuploader.shared.HandlerResultMessage;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem;
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.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* The Class DialogUpload.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 24, 2015
*/
public class DialogUpload extends DialogBox {
private final FormPanel formPanel = new FormPanel();
private boolean isStatusCompleted = false;
private Button btnSubmit = new Button("Upload");
private Button btnCancel = new Button("Cancel");
private Hidden hiddenOverwrite = new Hidden(ConstantsWorkspaceUploader.IS_OVERWRITE,"false");
private FileUpload upload;
/**
* The Enum UPLOAD_TYPE.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 24, 2015
*/
public static enum UPLOAD_TYPE {File, Archive};
private HTML LOADING = new HTML("Upload starting...");
private String parentIdentifier = "";
private VerticalPanel panel;
private HorizontalPanel hpButtons;
private String clientUploadKey;
/**
* Instantiates a new dialog upload.
*
* @param headerTitle the header title
* @param parentId the parent id
* @param uploadType the upload type
*/
public DialogUpload(String headerTitle, final String parentId, UPLOAD_TYPE uploadType){
setText(headerTitle);
this.parentIdentifier = parentId;
formPanel.setAction(ConstantsWorkspaceUploader.WORKSPACE_UPLOADER_SERVLET);
formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
formPanel.setMethod(FormPanel.METHOD_POST);
formPanel.setWidth("auto");
// Create a panel to hold all of the form widgets.
panel = new VerticalPanel();
formPanel.setWidget(panel);
setModal(false);
upload = new FileUpload();
upload.setName(ConstantsWorkspaceUploader.UPLOAD_FORM_ELEMENT);
// Add hidden parameters
panel.add(new Hidden(ConstantsWorkspaceUploader.ID_FOLDER,parentId));
panel.add(new Hidden(ConstantsWorkspaceUploader.UPLOAD_TYPE,uploadType.toString()));
panel.add(hiddenOverwrite);
clientUploadKey = GenerateUUID.get(15, 16);
panel.add(new Hidden(ConstantsWorkspaceUploader.CLIENT_UPLOAD_KEYS,clientUploadKey));
panel.add(upload);
hpButtons = new HorizontalPanel();
hpButtons.getElement().getStyle().setMarginTop(10, Unit.PX);
hpButtons.getElement().getStyle().setMarginBottom(10, Unit.PX);
btnCancel.getElement().getStyle().setMarginLeft(10, Unit.PX);
hpButtons.add(btnSubmit);
hpButtons.add(btnCancel);
panel.add(hpButtons);
// handle the post
formPanel.addSubmitCompleteHandler(new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
GWT.log("onSubmitComplete");
hide();
isStatusCompleted = true;
String result = event.getResults();
if (result == null) {
removeLoading();
new DialogResult(null, "Error during upload", "An error occurred during file upload.").center();
return;
}
String strippedResult = new HTML(result).getText();
final HandlerResultMessage resultMessage = HandlerResultMessage.parseResult(strippedResult);
switch (resultMessage.getStatus()) {
case ERROR:
removeLoading();
GWT.log("Error during upload "+resultMessage.getMessage());
break;
case UNKNOWN:
removeLoading();
GWT.log("Error during upload "+resultMessage.getMessage());
break;
case WARN: {
GWT.log("Upload completed with warnings "+resultMessage.getMessage());
removeLoading();
break;
}
case OK: {
removeLoading();
UploaderMonitor.getInstance().pollWorkspaceUploaderId(resultMessage.getMessage());
/*Timer t = new Timer() {
public void run() {
GWT.log("Upload started with id: "+resultMessage.getMessage());
UploaderMonitor.getInstance().pollWorkspaceUploaderId(resultMessage.getMessage());
}
};
t.schedule(250);*/
}
}
}
});
formPanel.addSubmitHandler(new SubmitHandler() {
@Override
public void onSubmit(SubmitEvent event) {
GWT.log("SubmitEvent");
addLoading();
enableButtons(false);
WorkspaceUploaderItem fakeUploader = new WorkspaceUploaderItem(clientUploadKey);
fakeUploader.setClientUploadKey(clientUploadKey);
UploaderMonitor.getInstance().addNewSubmit(fakeUploader, upload.getFilename());
setVisible(false);
}
});
add(formPanel);
this.addListeners();
}
/**
* Adds the loading.
*/
private void addLoading(){
panel.add(LOADING);
}
/**
* Removes the loading.
*/
private void removeLoading(){
try{
panel.remove(LOADING);
}catch(Exception e){
}
}
/**
* Enable buttons.
*
* @param bool the bool
*/
private void enableButtons(boolean bool){
btnSubmit.setEnabled(bool);
btnCancel.setEnabled(bool);
}
/**
* Adds the listeners.
*/
private void addListeners() {
btnSubmit.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
GWT.log("btnSubmit click");
if (upload.getFilename()==null || !(upload.getFilename().length()>2)) {
GWT.log("No file specified ");
return;
}
/*
* TODO: recall: Some browser would write in fileUploadField.getValue() C:\fakepath\$fileName
*/
String normalizedFileName = upload.getFilename();
if (normalizedFileName.contains("\\")) {
normalizedFileName = normalizedFileName.substring(normalizedFileName.lastIndexOf("\\")+1); //remove C:\fakepath\ if exists
}
final String label = normalizedFileName;
WorkspaceUploaderServiceAsync.Util.getInstance().itemExistsInWorkpaceFolder(parentIdentifier, normalizedFileName, new AsyncCallback<String>() {
@Override
public void onSuccess(final String itemId) {
GWT.log("itemExistsInWorkpaceFolder: "+itemId);
//TODO HANDLE OWERWRITE
// if(itemId!=null){
//
// MessageBoxConfirm msg = new MessageBoxConfirm("Replace "+label+"?", label + " exists in folder "+parentName + ". Overwrite?");
//
//
// msg.getMessageBoxConfirm().addCallback(new Listener<MessageBoxEvent>() {
//
// public void handleEvent(MessageBoxEvent be) {
//
// //IF NOT CANCELLED
// String clickedButton = be.getButtonClicked().getItemId();
//
// if(clickedButton.equals(Dialog.YES)){
//
//// removeItemAndSubmitForm(itemId);
// updateItemSubmitForm(itemId);
// }
//
//
// }
// });
// }else
submitForm(); //ITEM does NOT EXIST SO SUBMIT FORM;
}
@Override
public void onFailure(Throwable caught) {
GWT.log("Sorry an error occurred on the server "+caught.getLocalizedMessage() + ". Please try again later");
Window.alert(caught.getMessage());
}
});
}
});
btnCancel.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
hide();
}
});
}
/**
* Submit form.
*/
public void submitForm(){
/*messageBoxWait = new MessageBoxWait(ConstantsExplorer.PROGRESS, ConstantsExplorer.SAVINGYOURFILE, fileUploadField.getValue());
//Progress bar for upload
final Timer t = new Timer()
{
public void run()
{
if (isStatusCompleted)
{
cancel();
messageBoxWait.getMessageBoxWait().close();
}
}
};
t.scheduleRepeating(500);*/
GWT.log("Form submit: "+formPanel.getAction());
formPanel.submit();
}
/**
* Removes the item and submit form.
*
* @param itemId the item id
*/
private void removeItemAndSubmitForm(String itemId){
/*
AppControllerExplorer.rpcWorkspaceService.removeItem(itemId, new AsyncCallback<Boolean>() {
@Override
public void onFailure(Throwable caught) {
Info.display("Error", caught.getMessage());
}
@Override
public void onSuccess(Boolean result) {
if(result){
hiddenOverwrite.setValue("true");
submitForm();
}
}
});*/
}
/**
* Update item submit form.
*
* @param itemId the item id
*/
private void updateItemSubmitForm(String itemId){
hiddenOverwrite.setValue("true");
submitForm();
}
/**
* Checks if is status completed.
*
* @return the isStatusCompleted
*/
public boolean isStatusCompleted() {
return isStatusCompleted;
}
}

View File

@ -0,0 +1,386 @@
package org.gcube.portlets.widgets.workspaceuploader.client.uploader;
import java.util.ArrayList;
import java.util.List;
import org.gcube.portlets.widgets.workspaceuploader.client.ClosableDialog;
import org.gcube.portlets.widgets.workspaceuploader.client.ConstantsWorkspaceUploader;
import org.gcube.portlets.widgets.workspaceuploader.client.DialogResult;
import org.gcube.portlets.widgets.workspaceuploader.client.WorkspaceUploaderServiceAsync;
import org.gcube.portlets.widgets.workspaceuploader.shared.HandlerResultMessage;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem;
import com.google.gwt.core.client.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.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* The Class DialogUploadStream.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 24, 2015
*/
public class DialogUploadStream extends ClosableDialog {
/**
*
*/
private DialogUploadStream INSTANCE = this;
// private boolean isStatusCompleted = false;
protected Button btnUpload = new Button("Upload");
// protected Button btnCancel = new Button("Cancel");
private Hidden hiddenOverwrite = new Hidden(ConstantsWorkspaceUploader.IS_OVERWRITE,"false");
protected final FormPanel formPanel = new FormPanel();
protected FileUpload fileUpload;
protected Hidden jsonClientKeys;
protected List<WorkspaceUploaderItem> fakeUploaders = new ArrayList<WorkspaceUploaderItem>();
/**
* The Enum UPLOAD_TYPE.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 11, 2015
*/
public static enum UPLOAD_TYPE {File, Archive};
private HTML LOADING = new HTML("Upload starting...");
protected String parentIdentifier = "";
protected VerticalPanel panel;
private HorizontalPanel hpButtons;
// private MonitorPanel monitorPanel;
protected String clientUploadKey;
private Anchor anchorMyUploads;
/**
* Instantiates a new dialog upload stream.
*
* @param headerTitle the header title
* @param parentId the parent id
* @param uploadType the upload type
*/
public DialogUploadStream(String headerTitle, final String parentId, UPLOAD_TYPE uploadType){
super(false, true, headerTitle);
// setText(headerTitle);
this.parentIdentifier = parentId;
this.addStyleName("fileInputUploader");
formPanel.setAction(ConstantsWorkspaceUploader.WORKSPACE_UPLOADER_SERVLET_STREAM);
formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
formPanel.setMethod(FormPanel.METHOD_POST);
formPanel.setWidth("auto");
// Create a panel to hold all of the form widgets.
panel = new VerticalPanel();
formPanel.setWidget(panel);
setModal(false);
fileUpload = new FileUpload();
fileUpload.setName(ConstantsWorkspaceUploader.UPLOAD_FORM_ELEMENT);
// Add hidden parameters
panel.add(new Hidden(ConstantsWorkspaceUploader.ID_FOLDER,parentId));
panel.add(new Hidden(ConstantsWorkspaceUploader.UPLOAD_TYPE,uploadType.toString()));
panel.add(hiddenOverwrite);
// clientUploadKey = GenerateUUID.get(15, 16);
initJsonClientKeys();
panel.add(jsonClientKeys);
panel.add(fileUpload);
hpButtons = new HorizontalPanel();
hpButtons.getElement().getStyle().setMarginTop(10, Unit.PX);
// hpButtons.getElement().getStyle().setMarginBottom(10, Unit.PX);
// btnCancel.getElement().getStyle().setMarginLeft(10, Unit.PX);
hpButtons.add(btnUpload);
// hpButtons.add(btnCancel);
panel.add(hpButtons);
HorizontalPanel hp = new HorizontalPanel();
hp.getElement().setId("hpID");
hp.getElement().getStyle().setWidth(100, Unit.PCT);
hp.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
hp.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
// vp.add(anchorMyUploads);
anchorMyUploads = new Anchor(ConstantsWorkspaceUploader.MY_UPLOADS);
anchorMyUploads.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
UploaderMonitor.getInstance().showMonitor();
}
});
hp.add(anchorMyUploads);
panel.add(hp);
add(formPanel);
}
protected void initJsonClientKeys(){
jsonClientKeys = new Hidden(ConstantsWorkspaceUploader.CLIENT_UPLOAD_KEYS,"");
}
/**
* Bind events.
*/
public void bindEvents(){
this.addHandlers();
this.addListeners();
}
/**
* Adds the handlers.
*/
protected void addHandlers() {
// handle the post
formPanel.addSubmitCompleteHandler(new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
GWT.log("onSubmitComplete");
hide();
// isStatusCompleted = true;
String result = event.getResults();
if (result == null) {
removeLoading();
new DialogResult(null, "Error during upload", "An error occurred during file upload.").center();
return;
}
String strippedResult = new HTML(result).getText();
final HandlerResultMessage resultMessage = HandlerResultMessage.parseResult(strippedResult);
switch (resultMessage.getStatus()) {
case ERROR:
removeLoading();
GWT.log("Error during upload "+resultMessage.getMessage());
break;
case UNKNOWN:
removeLoading();
GWT.log("Error during upload "+resultMessage.getMessage());
break;
case WARN: {
GWT.log("Upload completed with warnings "+resultMessage.getMessage());
removeLoading();
break;
}
case OK: {
// removeLoading();
// UploaderMonitor.getInstance().pollWorkspaceUploaderId(resultMessage.getMessage());
/*Timer t = new Timer() {
public void run() {
GWT.log("Upload started with id: "+resultMessage.getMessage());
UploaderMonitor.getInstance().pollWorkspaceUploaderId(resultMessage.getMessage());
}
};
t.schedule(250);*/
}
}
}
});
formPanel.addSubmitHandler(new SubmitHandler() {
@Override
public void onSubmit(SubmitEvent event) {
GWT.log("SubmitEvent");
addLoading();
enableButtons(false);
WorkspaceUploaderItem fakeUploader = new WorkspaceUploaderItem();
fakeUploader.setClientUploadKey(clientUploadKey);
UploaderMonitor.getInstance().addNewSubmit(fakeUploader, fileUpload.getFilename());
setVisible(false);
removeLoading();
UploaderMonitor.getInstance().pollWorkspaceUploaderId(clientUploadKey);
//WAITING 0.5 SEC TO FIRST UPDATES
new Timer() {
@Override
public void run() {
removeLoading();
UploaderMonitor.getInstance().pollWorkspaceUploaderId(clientUploadKey);
}
}.schedule(500);
}
});
}
/**
* Adds the loading.
*/
protected void addLoading(){
panel.add(LOADING);
}
/**
* Removes the loading.
*/
protected void removeLoading(){
try{
panel.remove(LOADING);
}catch(Exception e){
}
}
/**
* Enable buttons.
*
* @param bool the bool
*/
protected void enableButtons(boolean bool){
btnUpload.setEnabled(bool);
// btnCancel.setEnabled(bool);
// upload.setEnabled(bool);
}
/**
* Adds the listeners.
*/
protected void addListeners() {
btnUpload.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
GWT.log("btnSubmit click");
if (fileUpload.getFilename()==null || !(fileUpload.getFilename().length()>2)) {
GWT.log("No file specified ");
return;
}
GWT.log("fileUpload.getFilename() "+fileUpload.getFilename());
/*
* TODO: recall: Some browser would write in fileUploadField.getValue() C:\fakepath\$fileName
*/
String normalizedFileName = fileUpload.getFilename();
if (normalizedFileName.contains("\\")) {
normalizedFileName = normalizedFileName.substring(normalizedFileName.lastIndexOf("\\")+1); //remove C:\fakepath\ if exists
}
final String label = normalizedFileName;
WorkspaceUploaderServiceAsync.Util.getInstance().itemExistsInWorkpaceFolder(parentIdentifier, normalizedFileName, new AsyncCallback<String>() {
@Override
public void onSuccess(final String itemId) {
GWT.log("itemExistsInWorkpaceFolder: "+itemId);
if(itemId!=null){
// HANDLE OWERWRITE
if(Window.confirm(label + " exists in folder. Overwrite?")){
removeItemAndSubmitForm(itemId);
updateItemSubmitForm(itemId);
}
}else
submitForm(); //ITEM does NOT EXIST SO SUBMIT FORM;
}
@Override
public void onFailure(Throwable caught) {
GWT.log("Sorry an error occurred on the server "+caught.getLocalizedMessage() + ". Please try again later");
Window.alert(caught.getMessage());
}
});
}
});
// btnCancel.addClickHandler(new ClickHandler() {
//
// @Override
// public void onClick(ClickEvent event) {
// hide();
//
// }
// });
}
/**
* Submit form.
*/
public void submitForm(){
/*messageBoxWait = new MessageBoxWait(ConstantsExplorer.PROGRESS, ConstantsExplorer.SAVINGYOURFILE, fileUploadField.getValue());
//Progress bar for upload
final Timer t = new Timer()
{
public void run()
{
if (isStatusCompleted)
{
cancel();
messageBoxWait.getMessageBoxWait().close();
}
}
};
t.scheduleRepeating(500);*/
formPanel.submit();
}
/**
* Removes the item and submit form.
*
* @param itemId the item id
*/
protected void removeItemAndSubmitForm(String itemId){
/*
AppControllerExplorer.rpcWorkspaceService.removeItem(itemId, new AsyncCallback<Boolean>() {
@Override
public void onFailure(Throwable caught) {
Info.display("Error", caught.getMessage());
}
@Override
public void onSuccess(Boolean result) {
if(result){
hiddenOverwrite.setValue("true");
submitForm();
}
}
});*/
}
/**
* Update item submit form.
*
* @param itemId the item id
*/
protected void updateItemSubmitForm(String itemId){
hiddenOverwrite.setValue("true");
submitForm();
}
}

View File

@ -0,0 +1,72 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.client.uploader;
/**
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Aug 6, 2015
*/
public class GenerateUUID {
private static final char[] CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
/**
* Generate a random uuid of the specified length. Example: uuid(15) returns
* "VcydxgltxrVZSTV"
*
* @param len
* the desired number of characters
*/
public static String get(int len) {
return get(len, CHARS.length);
}
/**
* Generate a random uuid of the specified length, and radix. Examples:
* <ul>
* <li>uuid(8, 2) returns "01001010" (8 character ID, base=2)
* <li>uuid(8, 10) returns "47473046" (8 character ID, base=10)
* <li>uuid(8, 16) returns "098F4D35" (8 character ID, base=16)
* </ul>
*
* @param len
* the desired number of characters
* @param radix
* the number of allowable values for each character (must be <=
* 62)
*/
public static String get(int len, int radix) {
if (radix > CHARS.length) {
throw new IllegalArgumentException();
}
char[] uuid = new char[len];
// Compact form
for (int i = 0; i < len; i++) {
uuid[i] = CHARS[(int) (Math.random() * radix)];
}
return new String(uuid);
}
/**
* Generate a RFC4122, version 4 ID. Example:
* "92329D39-6F5C-4520-ABFC-AAB64544E172"
*/
public static String get() {
char[] uuid = new char[36];
int r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (int i = 0; i < 36; i++) {
if (uuid[i] == 0) {
r = (int) (Math.random() * 16);
uuid[i] = CHARS[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];
}
}
return new String(uuid);
}
}

View File

@ -0,0 +1,248 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.client.uploader;
import java.util.HashMap;
import java.util.Map;
import org.gcube.portlets.widgets.workspaceuploader.client.StringUtil;
import org.gcube.portlets.widgets.workspaceuploader.client.events.CancelUploadEvent;
import org.gcube.portlets.widgets.workspaceuploader.client.resource.WorkspaceUploaderResources;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem.UPLOAD_STATUS;
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.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.ClosingEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* The Class MonitorPanel.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 24, 2015
*/
public class MonitorPanel extends ScrollPanel{
private static final int MAX_CHARS = 50;
private VerticalPanel verticalPanel = new VerticalPanel();
private Map<String, WorkspaceUploaderItem> mapUploading = new HashMap<String, WorkspaceUploaderItem>();
// private Map<String, Timer> mapTimer = new HashMap<String, Timer>();
// private Map<String, DialogBox> mapDialog= new HashMap<String, DialogBox>();
private Map<String, HorizontalPanel> mapPanels = new HashMap<String, HorizontalPanel>();
private HandlerManager eventBus;
private HorizontalPanel hpNoUploads = new HorizontalPanel();
/**
* Instantiates a new monitor panel.
*
* @param eventBus the event bus
*/
public MonitorPanel(HandlerManager eventBus) {
this.eventBus = eventBus;
initPanelNoUploads();
addCloseHandler();
verticalPanel.getElement().getStyle().setMargin(5, Unit.PX);
add(verticalPanel);
verticalPanel.add(hpNoUploads);
// RootPanel.get("workspace-uploader").add(verticalPanel);
}
private void initPanelNoUploads(){
hpNoUploads = new HorizontalPanel();
hpNoUploads.addStyleName("noUploads");
hpNoUploads.add(new HTML("No Uploads"));
}
private void removeNoUploads(){
try{
verticalPanel.remove(hpNoUploads);
}catch(Exception e){
}
}
/**
* Update workspace uploder.
*
* @param uploader the uploader
*/
public void updateWorkspaceUploder(WorkspaceUploaderItem uploader){
mapUploading.put(uploader.getClientUploadKey(), uploader);
if(mapPanels.get(uploader.getClientUploadKey())!=null){
HorizontalPanel hp = mapPanels.get(uploader.getClientUploadKey());
updateInfo(hp, uploader);
}else{
HorizontalPanel hp = new HorizontalPanel();
updateInfo(hp, uploader);
mapPanels.put(uploader.getClientUploadKey(), hp);
verticalPanel.add(hp);
}
}
/**
* New workspace uploder.
*
* @param uploader the uploader
* @param fileName the file name
*/
public void newWorkspaceUploder(WorkspaceUploaderItem uploader, final String fileName){
removeNoUploads();
mapUploading.put(uploader.getClientUploadKey(), uploader);
HorizontalPanel hp = new HorizontalPanel();
HTML html = new HTML();
String text = "<div><img src='"+WorkspaceUploaderResources.getImageLoading().getUrl()+"'>";
String msg = StringUtil.ellipsize("Uploading "+fileName, MAX_CHARS, 0);
text+="<span style='margin-left:5px; vertical-align: top;'>"+msg+"</span>";
text+="</div>";
html.setHTML(text);
html.setTitle("Uploading "+fileName);
hp.add(html);
//TODO *************************************************REMOVE THIS
// hp.add(handleCancelUplad(uploader, hp));
mapPanels.put(uploader.getClientUploadKey(), hp);
verticalPanel.add(hp);
}
/**
* Handle cancel upload.
*
* @param uploader the uploader
* @param hp the hp
* @return the image
*/
private Image handleCancelUpload(final WorkspaceUploaderItem uploader, final HorizontalPanel hp){
Image cancel = WorkspaceUploaderResources.getImageCancel();
cancel.setTitle("Cancel upload");
cancel.addStyleName("cancel-upload");
cancel.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
GWT.log("Click cancel");
String fileName = uploader.getFile()!=null? uploader.getFile().getFileName(): "";
if(Window.confirm("Confirm cancel uploading "+fileName+"?")){
hp.clear();
HTML html = new HTML();
hp.add(html);
String text = "<div><img src='"+WorkspaceUploaderResources.getImageCancel().getUrl()+"'>";
String msg = StringUtil.ellipsize("Aborting upload: "+fileName, MAX_CHARS, 0);
text+="<span style='margin-left:5px; vertical-align: top;'>"+msg+"</span></div>";
html.setHTML(text);
eventBus.fireEvent(new CancelUploadEvent(uploader, hp, fileName));
}
}
});
return cancel;
}
/**
* Update info.
*
* @param hp the hp
* @param uploader the uploader
*/
private void updateInfo(HorizontalPanel hp, WorkspaceUploaderItem uploader){
hp.clear();
HTML html = new HTML();
hp.add(html);
String text;
switch(uploader.getUploadStatus()){
case COMPLETED:
text = "<div><img src='"+WorkspaceUploaderResources.getImageCompleted().getUrl()+"'>";
text+="<span style='margin-left:5px; vertical-align: top;'>"+StringUtil.ellipsize(uploader.getFile().getFileName()+" uploaded successfully!", MAX_CHARS, 0)+"</span></div>";
// GWT.log(text);
html.setHTML(text);
html.setTitle(uploader.getStatusDescription());
break;
case FAILED:
text = "<div><img src='"+WorkspaceUploaderResources.getImageFailed().getUrl()+"'>";
text+="<span style='margin-left:5px; vertical-align: top;'>"+StringUtil.ellipsize(uploader.getStatusDescription(), MAX_CHARS, 0)+"</span></div>";
// GWT.log(text);
html.setHTML(text);
html.setTitle(uploader.getStatusDescription());
break;
case IN_PROGRESS:
text = "<div><img src='"+WorkspaceUploaderResources.getImageUpload().getUrl()+"'>";
String msg = StringUtil.ellipsize(uploader.getUploadProgress().getLastEvent().getReadPercentage()+"% "+uploader.getFile().getFileName(), MAX_CHARS, 0);
text+="<span style='margin-left:5px; vertical-align: top;'>"+msg+"</span>";
text+="</div>";
// GWT.log(text);
html.setHTML(text);
html.setTitle(uploader.getStatusDescription());
if(uploader.getUploadProgress().getLastEvent().getReadPercentage()!=100)
hp.add(handleCancelUpload(uploader, hp));
break;
case WAIT:
text = "<div><img src='"+WorkspaceUploaderResources.getImageLoading().getUrl()+"'>";
String descr = "";
if(uploader.getFile()!=null && uploader.getFile().getFileName()!=null)
descr = uploader.getFile().getFileName();
else
descr = uploader.getStatusDescription();
text+="<span style='margin-left:5px; vertical-align: top;'>"+descr+"</span>";
text+="</div>";
// GWT.log(text);
html.setHTML(text);
// hp.add(handleCancelUplad(uploader, hp));
break;
}
}
/**
* Adds the close handler.
*/
private void addCloseHandler(){
Window.addWindowClosingHandler(new Window.ClosingHandler() {
@Override
public void onWindowClosing(ClosingEvent event) {
// GWT.log("Closing");
String msg = "";
for (String uploadKey : mapUploading.keySet()) {
WorkspaceUploaderItem uploader = mapUploading.get(uploadKey);
GWT.log("Closing uploder status: "+uploader.getFile().getFileName() +" status: "+uploader.getUploadStatus());
if(uploader.getUploadStatus().equals(UPLOAD_STATUS.WAIT) || uploader.getUploadStatus().equals(UPLOAD_STATUS.IN_PROGRESS))
msg+=uploader.getFile().getFileName()+";";
}
if(msg!=null && !msg.isEmpty()){
event.setMessage("Abort upload? "+msg);
}
}
});
Window.addCloseHandler(new CloseHandler<Window>() {
@Override
public void onClose(CloseEvent<Window> event) {
// Window.alert("bye bye Closed");
}
});
}
}

View File

@ -0,0 +1,327 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.client.uploader;
import java.util.ArrayList;
import java.util.List;
import org.gcube.portlets.widgets.workspaceuploader.client.ConstantsWorkspaceUploader;
import org.gcube.portlets.widgets.workspaceuploader.client.DialogResult;
import org.gcube.portlets.widgets.workspaceuploader.client.WorkspaceUploaderServiceAsync;
import org.gcube.portlets.widgets.workspaceuploader.shared.HandlerResultMessage;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploadFile;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem.UPLOAD_STATUS;
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.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;
import com.google.gwt.user.client.ui.HTML;
/**
* The Class MultipleDilaogUploadStream.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 11, 2015
*/
public class MultipleDilaogUploadStream extends DialogUploadStream{
private static final String FILE_DELEMITER = ";";
private String fileUploadID;
/**
* Instantiates a new multiple dilaog upload stream.
*
* @param headerTitle the header title
* @param parentId the parent id
* @param uploadType the upload type
*/
public MultipleDilaogUploadStream(String headerTitle, String parentId, UPLOAD_TYPE uploadType) {
super(headerTitle, parentId, uploadType);
fileUpload.getElement().setAttribute("multiple", "multiple");
fileUploadID = GenerateUUID.get(10, 16); //is tagID
fileUpload.getElement().setId(fileUploadID);
this.addHandlers();
this.addListeners();
}
/**
* Adds the listeners.
*/
@Override
protected void addListeners() {
btnUpload.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
GWT.log("btnSubmit click");
if (fileUpload.getFilename()==null || !(fileUpload.getFilename().length()>2)) {
GWT.log("No file specified ");
return;
}
String[] files = null;
String filesSelected = getFilesSelected(fileUploadID, FILE_DELEMITER);
GWT.log("getFilesSelected: "+filesSelected);
files = filesSelected.split(FILE_DELEMITER);
//NORMALIZE FILE NAMES
for (int i=0; i<files.length; i++) {
String normalizedFileName = files[i];
if (normalizedFileName.contains("\\")) {
files[i] = normalizedFileName.substring(normalizedFileName.lastIndexOf("\\")+1); //remove C:\fakepath\ if exists
}
}
//GENERATE NEW UPLOADERS
generateFakeUploaders(files, parentIdentifier);
GWT.log(fakeUploaders.toString());
String jsonKeys = createJsonKeyForFiles(fakeUploaders);
GWT.log(jsonKeys);
if(jsonKeys==null){
Window.alert("Sorry an error occurred during file/s submit. Try again");
return;
}
//ADD TO FORM PANEL
// initJsonClientKeys();
jsonClientKeys.setValue(jsonKeys);
//CASE 1 FILE
if(files.length==1){
/*
* TODO: recall: Some browser would write in fileUploadField.getValue() C:\fakepath\$fileName
*/
final String label = files[0];
WorkspaceUploaderServiceAsync.Util.getInstance().itemExistsInWorkpaceFolder(parentIdentifier, label, new AsyncCallback<String>() {
@Override
public void onSuccess(final String itemId) {
GWT.log("itemExistsInWorkpaceFolder: "+itemId);
if(itemId!=null){
// HANDLE OWERWRITE
if(Window.confirm(label + " exists in folder. Overwrite?")){
removeItemAndSubmitForm(itemId);
updateItemSubmitForm(itemId);
}
}else
submitForm(); //ITEM does NOT EXIST SO SUBMIT FORM;
}
@Override
public void onFailure(Throwable caught) {
GWT.log("Sorry an error occurred on the server "+caught.getLocalizedMessage() + ". Please try again later");
Window.alert(caught.getMessage());
}
});
}else
submitForm();
}
});
/*
btnCancel.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
hide();
}
});*/
}
/**
* Generate new upload client keys.
*
* @param nmb the nmb
* @return
*/
private void generateFakeUploaders(String[] files, String parentId){
fakeUploaders = new ArrayList<WorkspaceUploaderItem>(files.length);
for (int i = 0; i <files.length; i++){
WorkspaceUploaderItem fakeItem = new WorkspaceUploaderItem();
fakeItem.setClientUploadKey(GenerateUUID.get());
fakeItem.setUploadStatus(UPLOAD_STATUS.WAIT);
WorkspaceUploadFile fakeFile = new WorkspaceUploadFile();
fakeFile.setFileName(files[i]);
fakeFile.setParentId(parentId);
fakeItem.setFile(fakeFile);
fakeUploaders.add(fakeItem);
}
}
/* (non-Javadoc)
* @see org.gcube.portlets.widgets.workspaceuploader.client.uploader.DialogUploadStream#addHandlers()
*/
@Override
protected void addHandlers() {
// handle the post
formPanel.addSubmitCompleteHandler(new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
GWT.log("onSubmitComplete");
hide();
// isStatusCompleted = true;
String result = event.getResults();
if (result == null) {
removeLoading();
new DialogResult(null, "Error during upload", "An error occurred during file upload.").center();
return;
}
String strippedResult = new HTML(result).getText();
final HandlerResultMessage resultMessage = HandlerResultMessage.parseResult(strippedResult);
switch (resultMessage.getStatus()) {
case ERROR:
removeLoading();
GWT.log("Error during upload "+resultMessage.getMessage());
break;
case UNKNOWN:
removeLoading();
GWT.log("Error during upload "+resultMessage.getMessage());
break;
case WARN: {
GWT.log("Upload completed with warnings "+resultMessage.getMessage());
removeLoading();
break;
}
case OK: {
// removeLoading();
// UploaderMonitor.getInstance().pollWorkspaceUploaderId(resultMessage.getMessage());
/*Timer t = new Timer() {
public void run() {
GWT.log("Upload started with id: "+resultMessage.getMessage());
UploaderMonitor.getInstance().pollWorkspaceUploaderId(resultMessage.getMessage());
}
};
t.schedule(250);*/
}
}
}
});
formPanel.addSubmitHandler(new SubmitHandler() {
@Override
public void onSubmit(SubmitEvent event) {
GWT.log("SubmitEvent");
addLoading();
enableButtons(false);
for (final WorkspaceUploaderItem workspaceUploaderItem : fakeUploaders) {
UploaderMonitor.getInstance().addNewSubmit(workspaceUploaderItem, workspaceUploaderItem.getFile().getFileName());
setVisible(false);
removeLoading();
UploaderMonitor.getInstance().pollWorkspaceUploaderId(workspaceUploaderItem.getClientUploadKey());
//WAITING 0.1 SEC TO FIRST UPDATES
/*new Timer() {
@Override
public void run() {
removeLoading();
UploaderMonitor.getInstance().pollWorkspaceUploaderId(workspaceUploaderItem.getClientUploadKey());
}
}.schedule(100);*/
}
}
});
}
/**
* Creates the json key for files.
*
* @param files the files
* @param currentClientKeys
* @return the string
*/
protected String createJsonKeyForFiles(List<WorkspaceUploaderItem> fakeFiles){
try {
JSONObject productObj = new JSONObject();
JSONArray jsonArray = new JSONArray();
productObj.put(ConstantsWorkspaceUploader.JSON_CLIENT_KEYS, jsonArray);
for (int i=0; i<fakeFiles.size(); i++){
WorkspaceUploaderItem file = fakeFiles.get(i);
JSONObject obj = new JSONObject();
obj.put(file.getClientUploadKey(), new JSONString(file.getFile().getFileName()));
jsonArray.set(i, obj);
}
return productObj.toString();
}catch (Exception e) {
GWT.log("error "+e.getMessage());
return null;
}
}
/**
* Submit form.
*/
@Override
public void submitForm(){
formPanel.submit();
// for (final WorkspaceUploaderItem workspaceUploaderItem : fakeUploaders) {
//
// UploaderMonitor.getInstance().addNewSubmit(workspaceUploaderItem, workspaceUploaderItem.getFile().getFileName());
// setVisible(false);
// removeLoading();
//// UploaderMonitor.getInstance().pollWorkspaceUploaderId(workspaceUploaderItem.getClientUploadKey());
//
// //WAITING 0.1 SEC TO FIRST UPDATES
// /*new Timer() {
//
// @Override
// public void run() {
// removeLoading();
// UploaderMonitor.getInstance().pollWorkspaceUploaderId(workspaceUploaderItem.getClientUploadKey());
//
// }
// }.schedule(100);*/
// }
}
/**
* Gets the files selected.
* @param the tagID
* @param fileDelimiter the file delimiter
* @return the files selected
*/
public static native String getFilesSelected(final String tagId, final String fileDelimiter) /*-{
var count = $wnd.$("#"+tagId)[0].files.length;
console.log(count);
var out = "";
for (i = 0; i < count; i++) {
var file = $wnd.$("#"+tagId)[0].files[i];
// out += file.name + fileDelimiter + file.size + fileDelimiter;
out += file.name + fileDelimiter;
}
return out;
}-*/;
}

View File

@ -0,0 +1,221 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.client.uploader;
import java.util.HashMap;
import java.util.Map;
import org.gcube.portlets.widgets.workspaceuploader.client.ClosableDialog;
import org.gcube.portlets.widgets.workspaceuploader.client.ConstantsWorkspaceUploader;
import org.gcube.portlets.widgets.workspaceuploader.client.WorkspaceUploaderServiceAsync;
import org.gcube.portlets.widgets.workspaceuploader.client.events.CancelUploadEvent;
import org.gcube.portlets.widgets.workspaceuploader.client.events.CancelUploadEventHandler;
import org.gcube.portlets.widgets.workspaceuploader.client.resource.WorkspaceUploaderResources;
import org.gcube.portlets.widgets.workspaceuploader.shared.HandlerResultMessage;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem.UPLOAD_STATUS;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
/**
* The Class UploaderMonitor.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 7, 2015
*/
public class UploaderMonitor {
private static UploaderMonitor instance;
private final static HandlerManager eventBus = new HandlerManager(null);
private MonitorPanel monitorPanel = new MonitorPanel(eventBus);
private static Map<String, Timer> mapTimer = new HashMap<String, Timer>();
private ClosableDialog dialogUploadMonitor = new ClosableDialog(monitorPanel, false, ConstantsWorkspaceUploader.MY_UPLOADS);
/**
* Gets the single instance of UploaderMonitor.
*
* @return single instance of UploaderMonitor
*/
public static synchronized UploaderMonitor getInstance() {
if (instance == null){
instance = new UploaderMonitor();
bindEvents();
}
return instance;
}
/**
*
*/
private static void bindEvents() {
eventBus.addHandler(CancelUploadEvent.TYPE, new CancelUploadEventHandler() {
@Override
public void onCancelUpload(final CancelUploadEvent deleteTimerEvent) {
if(deleteTimerEvent.getUploader()==null)
return;
String clientKey = deleteTimerEvent.getUploader().getClientUploadKey();
Timer timer = mapTimer.get(clientKey);
GWT.log("Delete timer "+timer);
if(timer!=null && timer.isRunning()){
timer.cancel();
mapTimer.put(clientKey, null);
}
RequestBuilder request = new RequestBuilder(RequestBuilder.GET,
ConstantsWorkspaceUploader.WORKSPACE_UPLOADER_SERVLET_STREAM+"?"+ConstantsWorkspaceUploader.CLIENT_UPLOAD_KEYS+"="+clientKey+"&"+ConstantsWorkspaceUploader.CANCEL_UPLOAD+"=true");
try {
request.sendRequest(null, new RequestCallback() {
@SuppressWarnings("incomplete-switch")
@Override
public void onResponseReceived(Request request, Response response) {
String strippedResult = new HTML(response.getText()).getText();
final HandlerResultMessage resultMessage = HandlerResultMessage.parseResult(strippedResult);
switch (resultMessage.getStatus()) {
case ERROR: {
GWT.log("ERROR: Error during stop upload "+resultMessage.getMessage());
Window.alert("Sorry, An error occurred during upload abort!");
return;
}
case OK: {
HorizontalPanel hp = deleteTimerEvent.getHp();
if(hp!=null){
hp.clear();
HTML html = new HTML();
hp.add(html);
String text = "<div><img src='"+WorkspaceUploaderResources.getImageCancelRed().getUrl()+"'>";
text+="<span style='margin-left:5px; vertical-align: top;'>Upload "+deleteTimerEvent.getFileName()+ " aborted</span></div>";
html.setHTML(text);
deleteTimerEvent.getUploader().setUploadStatus(UPLOAD_STATUS.ABORTED);
}
// Timer timer = mapTimer.get(deleteTimerEvent.getClientUploadKey());
// GWT.log("Delete timer "+timer);
// if(timer!=null && timer.isRunning()){
// timer.cancel();
// mapTimer.put(deleteTimerEvent.getClientUploadKey(), null);
// }
//
// SubmitEvent submitEvent = mapSubmitEvent.get(deleteTimerEvent.getClientUploadKey());
// GWT.log("Delete SubmitEvent "+submitEvent);
// if(submitEvent!=null){
// submitEvent.cancel();
// mapSubmitEvent.put(deleteTimerEvent.getClientUploadKey(), null);
// }
// DialogBox dialog = mapDialog.get(deleteTimerEvent.getClientUploadKey());
// GWT.log("Delete dialog "+dialog);
// if(dialog!=null){
//// dialog.setVisible(true);
// dialog.hide();
// mapDialog.put(deleteTimerEvent.getClientUploadKey(), null);
// }
}
break;
}
}
@Override
public void onError(Request request, Throwable exception) {
GWT.log("ERROR: Error during stop upload "+exception.getMessage());
}
});
} catch (RequestException e) {
GWT.log("RequestException: Error during stop upload "+e.getMessage());
}
}
});
}
public void showMonitor(){
if(!dialogUploadMonitor.isShowing())
dialogUploadMonitor.center();
}
/**
* Adds the new submit.
*
* @param uploader the uploader
* @param fileName the file name
* @param event
* @param dialog
*/
public void addNewSubmit(WorkspaceUploaderItem uploader, String fileName){
if(!dialogUploadMonitor.isShowing())
dialogUploadMonitor.center();
monitorPanel.newWorkspaceUploder(uploader, fileName);
}
/**
* Poll workspace uploader id.
*
* @param uploaderId the uploader id
*/
public void pollWorkspaceUploaderId(final String uploaderId){
Timer timer = new Timer() {
@Override
public void run() {
WorkspaceUploaderServiceAsync.Util.getInstance().getUploadStatus(uploaderId, new AsyncCallback<WorkspaceUploaderItem>() {
@Override
public void onSuccess(WorkspaceUploaderItem result) {
// GWT.log("onSuccess: "+result.toString());
synchronized(this){
Timer tmn = mapTimer.get(uploaderId);
if(tmn!=null && tmn.isRunning()){
if(result.getUploadStatus().equals(UPLOAD_STATUS.COMPLETED)){
mapTimer.remove(tmn);
// new DialogResult(null, "Upload Completed!!", result.getStatusDescription()).center();
cancel();
}else if(result.getUploadStatus().equals(UPLOAD_STATUS.FAILED)){
mapTimer.remove(tmn);
// new DialogResult(null, "Upload Failed!!", result.getStatusDescription()).center();
cancel();
}
monitorPanel.updateWorkspaceUploder(result);
// GWT.log(result.toString());
}else{
GWT.log("Timer is null or already closed or completed");
cancel();
}
}
}
@Override
public void onFailure(Throwable caught) {
GWT.log("onFailure: "+caught.getMessage());
cancel();
}
});
}
};
mapTimer.put(uploaderId, timer);
timer.scheduleRepeating(2000);
}
}

View File

@ -0,0 +1,54 @@
package org.gcube.portlets.widgets.workspaceuploader.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.portal.custom.scopemanager.scopehelper.ScopeHelper;
/**
* The Class WorkspaceUploaderPortlet.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 6, 2015
*/
public class WorkspaceUploaderPortlet extends GenericPortlet{
/**
* JSP folder name
*/
public static final String JSP_FOLDER = "/WEB-INF/jsp/";
/**
*
*/
public static final String VIEW_JSP = JSP_FOLDER + "WorkspaceUploader_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);
ScopeHelper.setContext(request, ScopeHelper.USERNAME_ATTRIBUTE);
// request.setAttribute("fromportlet","true");
// Invoke the JSP to render
PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(VIEW_JSP);
rd.include(request,response);
}
}

View File

@ -0,0 +1,110 @@
/** Add css rules here for your application. */
/** Example rules used by the template application (remove for your app) */
h1 {
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
.sendButton {
display: block;
font-size: 16pt;
}
/** 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;
}
.cancel-upload {
margin-left: 5px;
cursor: pointer;
}
.baloonGoTop {
padding: 1px;
/* border: solid; */ /* border-width: 1px; */
/* border-color: rgb(200, 210, 240); */ /* border-radius: 15px; */
-webkit-border-top-left-radius: 15px;
-webkit-border-top-right-radius: 15px;
-moz-border-radius-topleft: 15px;
-moz-border-radius-topright: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
/* background-color: #0B3C9E; */
background-color: #F5F5F5;
/* color: #D2D2D2; */
font-family: verdana, arial;
font-size: 11px;
/* border: 1px;
border-color: gray; */ /* margin-left: 50%; */
margin-top: 200px;
/* opacity: 0.5; */
width: 300px;
height: 150px;
}
.ClosableDialogCaption {
width: 100%;
}
.ClosableDialog {
max-width: 600px;
/* min-width: 350px; */
}
.ClosableDialog .ClosableDialogCaption .gwt-HTML {
color: #19326C;
font-family: "HelveticaNeue-Light", "Helvetica Neue Light",
"Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-size: 15px;
font-weight: normal;
padding: 5px;
}
.CloseButton {
float: right;
cursor: pointer;
padding-top: 5px;
}
.fileInputUploader input {
background-color: #F2F2F2;
border: 1px solid #BBBBBB;
border-radius: 4px;
color: #464646;
cursor: pointer;
font-family: "Lucida Grande", Verdana, "Bitstream Vera Sans", Arial,
sans-serif;
font-size: 13px;
margin-top: 10px;
padding: 10px 15px;
min-width: 350px;
}
.noUploads{
min-width: 350px;
font-size: 15px;
font-family: "Lucida Grande", Verdana, "Bitstream Vera Sans", Arial,
sans-serif;
}
/* .baloonGoTop :HOVER { */
/* cursor: pointer; */
/* color: #FFF; */
/* } */

View File

@ -0,0 +1,130 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class StreamUtils.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 2, 2015
*/
public class StreamUtils {
public static Logger logger = LoggerFactory.getLogger(StreamUtils.class);
/**
* Stream2file.
*
* @param in the in
* @param prefix the prefix
* @param suffix the suffix
* @return the file
* @throws IOException Signals that an I/O exception has occurred.
*/
public static File stream2file(InputStream in, String prefix, String suffix) throws IOException {
final File tempFile = File.createTempFile(prefix, suffix);
logger.debug("Creating temp file: " + tempFile.getAbsolutePath());
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
logger.debug("Created temp file: " + tempFile.getAbsolutePath());
}catch (Exception e) {
// TODO: handle exception
}
return tempFile;
}
/**
* Stream2file recorder.
*
* @param in the in
* @param totalBytes the total bytes
* @param prefix the prefix
* @param suffix the suffix
* @return the file
* @throws IOException Signals that an I/O exception has occurred.
*/
public static File stream2fileRecorder(InputStream in, long totalBytes, String prefix, String suffix) throws IOException {
final File tempFile = File.createTempFile(prefix, suffix);
logger.debug("Created temp file: " + tempFile.getAbsolutePath());
tempFile.deleteOnExit();
/*UploadProgress uploadProgress = new UploadProgress();
//instanciate the progress listener
UploadProgressListener uploadProgressListener = new UploadProgressListener(uploadProgress);
UploadProgressInputStream inputStream = new UploadProgressInputStream(in, totalBytes);
inputStream.addListener(uploadProgressListener);*/
try (FileOutputStream out = new FileOutputStream(tempFile)) {
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}catch (Exception e) {
// TODO: handle exception
}
return tempFile;
}
/**
* Open input stream.
*
* @param file the file
* @return the file input stream
* @throws IOException Signals that an I/O exception has occurred.
*/
public static FileInputStream openInputStream(File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file
+ "' exists but is a directory");
}
if (file.canRead() == false) {
throw new IOException("File '" + file + "' cannot be read");
}
} else {
throw new FileNotFoundException("File '" + file
+ "' does not exist");
}
return new FileInputStream(file);
}
/**
* Delete temp file.
*
* @param file the file
* @return true, if successful
* @throws IOException Signals that an I/O exception has occurred.
*/
public static boolean deleteTempFile(File file) throws IOException{
if (file.exists()) {
String path = file.getAbsolutePath();
logger.debug("Deleting file: "+path);
boolean deleted = file.delete();
logger.debug("Deleted? "+deleted);
return deleted;
}else
throw new IOException("File '" + file
+ "' doesn't exist");
}
}

View File

@ -0,0 +1,556 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.server;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItemStream;
import org.gcube.common.homelibrary.home.exceptions.InternalErrorException;
import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder;
import org.gcube.common.homelibrary.home.workspace.WorkspaceItem;
import org.gcube.common.homelibrary.home.workspace.exceptions.InsufficientPrivilegesException;
import org.gcube.common.homelibrary.home.workspace.exceptions.ItemAlreadyExistException;
import org.gcube.common.homelibrary.home.workspace.exceptions.ItemNotFoundException;
import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException;
import org.gcube.common.homelibrary.home.workspace.exceptions.WrongDestinationException;
import org.gcube.common.homelibrary.home.workspace.exceptions.WrongItemTypeException;
import org.gcube.common.homelibrary.home.workspace.folder.FolderItem;
import org.gcube.common.homelibrary.home.workspace.folder.items.Report;
import org.gcube.common.homelibrary.home.workspace.folder.items.ReportTemplate;
import org.gcube.common.homelibrary.util.Extensions;
import org.gcube.common.homelibrary.util.WorkspaceUtil;
import org.gcube.portlets.widgets.workspaceuploader.client.ConstantsWorkspaceUploader;
import org.gcube.portlets.widgets.workspaceuploader.server.notification.NotificationsWorkspaceUploader;
import org.gcube.portlets.widgets.workspaceuploader.server.util.WsUtil;
import org.gcube.portlets.widgets.workspaceuploader.shared.HandlerResultMessage;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* @Jan 21, 2014
*
*/
public class WorkspaceUploadServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -7861878364437065019L;
protected static final String UTF_8 = "UTF-8";
public static final String UPLOAD_TYPE = ConstantsWorkspaceUploader.UPLOAD_TYPE;
public static final String ID_FOLDER = ConstantsWorkspaceUploader.ID_FOLDER;
public static final String UPLOAD_FORM_ELEMENT = ConstantsWorkspaceUploader.UPLOAD_FORM_ELEMENT;
public static final String CLIENT_UPLOAD_KEY = ConstantsWorkspaceUploader.CLIENT_UPLOAD_KEYS;
public static final String IS_OVERWRITE = ConstantsWorkspaceUploader.IS_OVERWRITE;
public static final String FILE = "File";
public static final String D4ST = Extensions.REPORT_TEMPLATE.getName(); //extension of Report Template type
public static final String D4SR = Extensions.REPORT.getName(); //extension of Report type
public static Logger logger = LoggerFactory.getLogger(WorkspaceUploadServlet.class);
/*private static String UPLOAD_LOCATION = System.getProperty("java.io.tmpdir");
@Override
public void init() throws ServletException {
try{
System.out.println(WorkspaceUploadServlet.class.getName()+" ready.");
logger.debug(WorkspaceUploadServlet.class.getName()+" ready.");
if (System.getenv("CATALINA_TMPDIR") != null && System.getenv("CATALINA_TMPDIR").compareTo("") != 0) {
UPLOAD_LOCATION = System.getenv("CATALINA_TMPDIR");
}
super.init();
}catch(Exception e){
e.printStackTrace();
}
}*/
/**
* {@inheritDoc}
*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// System.out.println("GET on LocalUploadServlet");
System.out.println("GET method in WorkspaceUploadServlet is running");
sendError(response, "Internal error: GET method not supported");
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("rawtypes")
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// System.out.println("POST on UploadServlet");
// logger.info("POST on UploadServlet");
//
// if (!ServletFileUpload.isMultipartContent(request)) {
// logger.error("ERROR: multipart request not found");
// sendError(response, "ERROR: multipart request not found");
// }
//
// String destinationId = null;
// String uploadType = null;
// boolean isOverwrite = false;
// String clientUploadKey = null;
// FileItemStream uploadItem = null;
//
// FileItemFactory factory = new DiskFileItemFactory();
// ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
//
// try {
//
// FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request);
//
// //GET FILE STREAM
// while (fileItemIterator.hasNext()) {
// FileItemStream item = fileItemIterator.next();
//
// if (item.isFormField() && ID_FOLDER.equals(item.getFieldName())){
// destinationId = Streams.asString(item.openStream());
// logger.debug("ID_FOLDER OK");
// }
//
// if (item.isFormField() && UPLOAD_TYPE.equals(item.getFieldName())){
// uploadType = Streams.asString(item.openStream());
// logger.debug("UPLOAD_TYPE OK");
// }
//
// if (item.isFormField() && IS_OVERWRITE.equals(item.getFieldName())){
// isOverwrite = Boolean.parseBoolean(Streams.asString(item.openStream()));
// logger.debug("IS_OVERWRITE OK");
// }
//
// if(item.isFormField() && CLIENT_UPLOAD_KEY.equals(item.getFieldName())){
// clientUploadKey = Streams.asString(item.openStream());
// logger.debug("CLIENT_UPLOAD_KEY OK");
// }
//
// //MUST BE THE LAST PARAMETER TRASMITTED
// if (UPLOAD_FORM_ELEMENT.equals(item.getFieldName())){
// logger.debug(UPLOAD_FORM_ELEMENT);
// uploadItem = item;
// break;
// }
// }
// uploadData(request, response, uploadItem, destinationId, uploadType, clientUploadKey, isOverwrite);
// } catch (FileUploadException e) {
// logger.error("Error processing request in upload servlet", e);
// sendError(response, "Internal error: Error during request processing");
// return;
// }
}
private void uploadData(HttpServletRequest request, HttpServletResponse response, FileItemStream uploadItem, String destinationId,String uploadType,String clientUploadKey, boolean isOverwrite) throws ServletException, IOException{
// String fileName = uploadItem.getName();
// logger.info("Upload servlet parameters: [fileName: "+fileName+ ", destinationId: "+destinationId +", uploadType: "+uploadType+", isOverwrite: "+isOverwrite+", clientUploadKey: "+clientUploadKey+"]");
//
// if (uploadType == null || uploadType.isEmpty()) {
// logger.error("Error processing request in upload servlet: No upload type found");
// sendError(response, "Internal error: No upload type found");
// return;
// }
//
// if(clientUploadKey==null || clientUploadKey.isEmpty()){
// logger.error("Error processing request in upload servlet: No client upload key found");
// sendError(response, "Internal error: No client upload key found");
// return;
// }
//
//
// Workspace wa = null;
// try {
// logger.debug("getWorkspace from HL");
// wa = WsUtil.getWorkspace(request.getSession());
// } catch (Exception e) {
// logger.error("Error during workspace retrieving", e);
// response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error processing request in upload servlet");
// return;
// }
//
// if (wa == null) {
// logger.error("Now workspace found in session");
// sendError(response, "Internal error: No workspace in session");
// return;
// }
//
// WorkspaceItem item;
// try {
// logger.debug("getWorkspace Item from HL");
// item = wa.getItem(destinationId);
// } catch (ItemNotFoundException e) {
// logger.error("Error, no destination folder found", e);
// sendError(response, "Internal error: No destination folder found");
// return;
// }
//
// if (item.getType() != WorkspaceItemType.FOLDER && item.getType() != WorkspaceItemType.SHARED_FOLDER) {
// logger.error("Error processing request in upload servlet: Wrong destination item");
// sendError(response, "Internal error: Wrong destination item");
// return;
// }
//
// WorkspaceFolder destinationFolder = (WorkspaceFolder) item;
//
// try {
// //we calculate an unique name for the current destination
// String itemName = "";
//
// logger.debug("getItemName from HL");
// if(!isOverwrite)
// itemName = WorkspaceUtil.getUniqueName(fileName, destinationFolder);
// else
// itemName = fileName;
//
// Long size = Long.parseLong(request.getHeader("Content-Length"));
// logger.debug("size: " + size + " bytes");
//
//
// //Create Item Uploader to read progress
// WorkspaceUploadFile wsUploadFile = new WorkspaceUploadFile(destinationFolder.getId(), itemName);
// String identifier = wsUploadFile.hashCode()+getRandom()+"";
// WorkspaceUploaderItem workspaceUploader = new WorkspaceUploaderItem(identifier);
// workspaceUploader.setUploadStatus(UPLOAD_STATUS.WAIT);
// workspaceUploader.setFile(wsUploadFile);
// workspaceUploader.setStatusDescription("Uploading "+itemName+" at 0%");
// workspaceUploader.setClientUploadKey(clientUploadKey);
//
// //instanciate the progress listener
// AbstractUploadProgressListener uploadProgressListener = new AbstractUploadProgressListener(request, new UploadProgress(), 0, 70);
// final UploadProgressInputStream inputStream = new UploadProgressInputStream(uploadItem.openStream(), size);
// inputStream.addListener(uploadProgressListener);
// workspaceUploader.setUploadProgress(uploadProgressListener.getUploadProgress());
// saveWorkspaceUploaderInSession(workspaceUploader, request.getSession());
//
// printStartTime();
// File file = StreamUtils.stream2file(inputStream, uploadItem.getName()+UUID.randomUUID(), ".tmp");
//
// logger.debug("getMimeType from HL");
// String contentType = MimeTypeUtil.getMimeType(itemName, StreamUtils.openInputStream(file));
// logger.debug("Content type (mime type): "+contentType + " unique name: "+itemName);
//
// String extension = FilenameUtils.getExtension(itemName);
// logger.debug("extension: "+extension);
//
// if(uploadType.compareTo(FILE)==0) {//IS FILE UPLOAD
//
// boolean isZipFile = MimeTypeUtil.isZipContentType(contentType);
//
// if(isZipFile && (extension.compareToIgnoreCase(D4ST)==0)){ //Create REPORT TEMPLATE
//
// String newItemName = itemName;
// logger.debug("createTemplate: "+newItemName);
// createTemplate(request.getSession(), wa, newItemName, file, destinationFolder, response, isOverwrite);
//
// }else if(isZipFile && (extension.compareToIgnoreCase(D4SR)==0)){ //Create REPORT
//
// String newItemName = itemName;
// logger.debug("createReport: "+newItemName);
// createReport(request.getSession(), wa, newItemName, file, destinationFolder, response, isOverwrite);
// }else{ //CREATE AN EXTERNAL FILE
//
// workspaceUploader = WorkspaceUploaderManager.uploadFile(request, workspaceUploader, wa, itemName, file, destinationFolder, contentType, isOverwrite, size);
//
// if(workspaceUploader==null)
// throw new Exception("Error when creating uploader, it is null!");
//
// sendMessage(response, workspaceUploader.getIdentifier());
// }
//
// }else {//IS ARCHIVE UPLOAD
//
// if (MimeTypeUtil.isZipContentType(contentType)){
// logger.debug("Unziping content");
// workspaceUploader = WorkspaceUploaderManager.uploadArchive(request, workspaceUploader, itemName, file, destinationFolder, size);
//
// if(workspaceUploader==null)
// throw new Exception("Error when creating uploader, it is null!");
//
// sendMessage(response, workspaceUploader.getIdentifier());
// } else{
// workspaceUploader = WorkspaceUploaderManager.uploadFile(request, workspaceUploader, wa, itemName, file, destinationFolder, contentType, isOverwrite, size);
//
// if(workspaceUploader==null)
// throw new Exception("Error when creating uploader, it is null!");
//
// sendMessage(response, workspaceUploader.getIdentifier());
// }
// }
//
//// file.delete();
// } catch (InsufficientPrivilegesException e) {
// logger.error("Error creating elements", e);
// sendError(response, "Internal error: Insufficient privileges");
// return;
// } catch (InternalErrorException e) {
// logger.error("Error creating elements", e);
// sendError(response, "Internal error: "+e.getMessage());
// return;
// } catch (ItemAlreadyExistException e) {
// logger.error("Error creating elements", e);
// sendError(response, "Internal error: An item with that name already exists");
// return;
// }catch (Exception e) {
// logger.error("Error creating elements", e);
// sendError(response, "Internal error: An error occurred on uploading the file, try again later");
// return;
// }
}
public static WorkspaceUploaderItem saveWorkspaceUploaderInSession(WorkspaceUploaderItem workspaceUploader, HttpSession httpSession) throws Exception {
if(workspaceUploader!=null){
try {
WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader);
return workspaceUploader;
} catch (Exception e) {
logger.error("Error during WorkspaceUploaderItem save in session workspace uploader: "+workspaceUploader,e);
throw new Exception("An error occurred during uploading. Try again");
}
}
throw new Exception("An error occurred during uploading. Workspace Uploader not found. Abort and try again");
}
/**
* Gets the random.
*
* @return the random
*/
private static int getRandom(){
Random randomGenerator = new Random();
return randomGenerator.nextInt(Integer.MAX_VALUE);
}
//TEST TIME
public static Long startTime = new Long(0);
//TEST TIME
public static Long printStartTime(){
startTime = System.currentTimeMillis();
logger.debug("Start time: "+startTime);
return startTime;
}
//TEST TIME
public static void printElapsedTime(long startTime){
Long endTime = System.currentTimeMillis() - startTime;
String time = String.format("%d msc %d sec", endTime, TimeUnit.MILLISECONDS.toSeconds(endTime));
logger.debug("Elapsed Time: "+time);
}
/**
*
* @param httpSession
* @param workspace
* @param itemId
* @param destinationFolderId
*/
public static void notifyUploadInSharedFolder(final HttpSession httpSession, final Workspace workspace, final String itemId, final String destinationFolderId, final boolean isOverwrite){
new Thread(){
public void run() {
WorkspaceItem sourceItem;
try {
sourceItem = workspace.getItem(itemId);
String sourceSharedId = sourceItem.getIdSharedFolder();
WorkspaceItem folderDestinationItem = workspace.getItem(destinationFolderId);
NotificationsWorkspaceUploader.checkSendNotifyChangedItemToShare(httpSession, sourceItem, sourceSharedId, folderDestinationItem,isOverwrite);
} catch (Exception e) {
logger.error("Error in notifyUploadInSharedFolder", e);
}
};
}.start();
}
private FolderItem overwriteItem(Workspace wa, String itemName, InputStream fileData, WorkspaceFolder destinationFolder){
FolderItem overwriteItem = null;
try {
logger.debug("case overwriting item.. "+itemName);
overwriteItem = (FolderItem) wa.find(itemName, destinationFolder.getId());
logger.debug("overwriteItem item was found, id is: "+overwriteItem.getId());
wa.updateItem(overwriteItem.getId(), fileData);
logger.debug("updateItem with id: "+overwriteItem.getId()+ ", is completed");
} catch (ItemNotFoundException e) {
logger.error("Error in createExternalFile, ItemNotFoundException", e);
} catch (WrongItemTypeException e) {
logger.error("Error in createExternalFile, WrongItemTypeException", e);
} catch (WorkspaceFolderNotFoundException e) {
logger.error("Error in createExternalFile, WorkspaceFolderNotFoundException", e);
} catch (WrongDestinationException e) {
logger.error("Error in createExternalFile, WrongDestinationException", e);
} catch (InsufficientPrivilegesException e) {
logger.error("Error in createExternalFile, InsufficientPrivilegesException", e);
} catch (ItemAlreadyExistException e) {
logger.error("Error in createExternalFile, ItemAlreadyExistException", e);
} catch (InternalErrorException e) {
logger.error("Error in createExternalFile, InternalErrorException", e);
}catch (Exception e) {
logger.error("Error in createExternalFile, Exception", e);
}
return overwriteItem;
}
private void createReport(HttpSession httpSession, Workspace wa, String itemName, File file, WorkspaceFolder destinationFolder, HttpServletResponse response, boolean isOverwrite) throws InsufficientPrivilegesException, ItemAlreadyExistException, InternalErrorException, IOException{
try {
Report report = null;
if(!isOverwrite){
itemName = WorkspaceUtil.getUniqueName(itemName, destinationFolder);
report = wa.createReport(itemName, "", Calendar.getInstance(), Calendar.getInstance(), "", "", "", 0, "", StreamUtils.openInputStream(file), destinationFolder.getId());
notifyUploadInSharedFolder(httpSession,wa,report.getId(),destinationFolder.getId(), isOverwrite);
sendMessage(response, "File "+report.getName()+" imported correctly in "+destinationFolder.getPath());
}
else{ //CASE OVERWRITE
FolderItem rep = overwriteItem(wa, itemName, StreamUtils.openInputStream(file), destinationFolder);
if(rep!=null){
notifyUploadInSharedFolder(httpSession,wa,rep.getId(),destinationFolder.getId(), isOverwrite);
sendMessage(response, "File "+rep.getName()+" imported correctly in "+destinationFolder.getPath());
}
else
sendError(response,"Internal error: Workspace Item Not Found");
}
} catch (WrongDestinationException e) {
logger.error("Error creating elements", e);
sendError(response, "Internal error: Wrong Destination");
} catch (WorkspaceFolderNotFoundException e) {
logger.error("Error creating elements", e);
sendError(response, "Internal error: Workspace Folder Not Found");
}finally{
try {
StreamUtils.deleteTempFile(file);
} catch (Exception e2) {
// TODO: handle exception
}
}
}
private void createTemplate(HttpSession httpSession, Workspace wa, String itemName, File file, WorkspaceFolder destinationFolder, HttpServletResponse response, boolean isOverwrite) throws InsufficientPrivilegesException, ItemAlreadyExistException, InternalErrorException, IOException{
try {
ReportTemplate template = null;
if(!isOverwrite){
itemName = WorkspaceUtil.getUniqueName(itemName, destinationFolder);
template = wa.createReportTemplate(itemName, "", Calendar.getInstance(), Calendar.getInstance(), "", "", 0, "", StreamUtils.openInputStream(file), destinationFolder.getId());
notifyUploadInSharedFolder(httpSession,wa,template.getId(),destinationFolder.getId(), isOverwrite);
sendMessage(response, "File "+template.getName()+" imported correctly in "+destinationFolder.getPath());
}else{ //CASE OVERWRITE
FolderItem rep = overwriteItem(wa, itemName, StreamUtils.openInputStream(file), destinationFolder);
if(rep!=null){
notifyUploadInSharedFolder(httpSession,wa,rep.getId(),destinationFolder.getId(), isOverwrite);
sendMessage(response, "File "+rep.getName()+" imported correctly in "+destinationFolder.getPath());
}
else
sendError(response,"Internal error: Workspace Item Not Found");
}
} catch (WrongDestinationException e) {
logger.error("Error creating elements", e);
sendError(response, "Internal error: Wrong Destination");
} catch (WorkspaceFolderNotFoundException e) {
logger.error("Error creating elements", e);
sendError(response, "Internal error: Workspace Folder Not Found");
}finally{
try {
StreamUtils.deleteTempFile(file);
} catch (Exception e2) {
// TODO: handle exception
}
}
}
protected void sendError(HttpServletResponse response, String message) throws IOException{
try {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
HandlerResultMessage resultMessage = HandlerResultMessage.errorResult(message);
response.getWriter().write(resultMessage.toString());
//5.6 Closure of Response Object:
//When a response is closed, the container must immediately flush all remaining content in the response buffer to the client
// response.flushBuffer();
} catch (IOException e){
logger.warn("IOException class name: "+e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage());
else
throw e; //Sending Exceptions
}
}
protected void sendMessage(HttpServletResponse response, String message) throws IOException{
try {
response.setStatus(HttpServletResponse.SC_ACCEPTED);
HandlerResultMessage resultMessage = HandlerResultMessage.okResult(message);
response.getWriter().write(resultMessage.toString());
//5.6 Closure of Response Object:
//When a response is closed, the container must immediately flush all remaining content in the response buffer to the client
// response.flushBuffer();
} catch (IOException e){
logger.warn("IOException class name: "+e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage());
else
throw e; //Sending Exceptions
}
}
protected void sendWarnMessage(HttpServletResponse response, String message) throws IOException{
try {
response.setStatus(HttpServletResponse.SC_ACCEPTED);
HandlerResultMessage resultMessage = HandlerResultMessage.warnResult(message);
response.getWriter().write(resultMessage.toString());
//5.6 Closure of Response Object:
//When a response is closed, the container must immediately flush all remaining content in the response buffer to the client
// response.flushBuffer();
} catch (IOException e){
logger.warn("IOException class name: "+e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage());
else
throw e; //Sending Exceptions
}
}
}

View File

@ -0,0 +1,974 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.server;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FilenameUtils;
import org.gcube.common.homelibary.model.items.type.WorkspaceItemType;
import org.gcube.common.homelibrary.home.exceptions.InternalErrorException;
import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder;
import org.gcube.common.homelibrary.home.workspace.WorkspaceItem;
import org.gcube.common.homelibrary.home.workspace.exceptions.InsufficientPrivilegesException;
import org.gcube.common.homelibrary.home.workspace.exceptions.ItemAlreadyExistException;
import org.gcube.common.homelibrary.home.workspace.exceptions.ItemNotFoundException;
import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException;
import org.gcube.common.homelibrary.home.workspace.exceptions.WrongDestinationException;
import org.gcube.common.homelibrary.home.workspace.exceptions.WrongItemTypeException;
import org.gcube.common.homelibrary.home.workspace.folder.FolderItem;
import org.gcube.common.homelibrary.home.workspace.folder.items.Report;
import org.gcube.common.homelibrary.home.workspace.folder.items.ReportTemplate;
import org.gcube.common.homelibrary.util.Extensions;
import org.gcube.common.homelibrary.util.MimeTypeUtil;
import org.gcube.common.homelibrary.util.WorkspaceUtil;
import org.gcube.portlets.widgets.workspaceuploader.client.ConstantsWorkspaceUploader;
import org.gcube.portlets.widgets.workspaceuploader.server.notification.NotificationsWorkspaceUploader;
import org.gcube.portlets.widgets.workspaceuploader.server.upload.AbstractUploadProgressListener;
import org.gcube.portlets.widgets.workspaceuploader.server.upload.MemoryUploadListener;
import org.gcube.portlets.widgets.workspaceuploader.server.upload.UploadCanceledException;
import org.gcube.portlets.widgets.workspaceuploader.server.upload.UploadProgressInputStream;
import org.gcube.portlets.widgets.workspaceuploader.server.upload.UploadProgressListener;
import org.gcube.portlets.widgets.workspaceuploader.server.upload.WorkspaceUploaderMng;
import org.gcube.portlets.widgets.workspaceuploader.server.util.WsUtil;
import org.gcube.portlets.widgets.workspaceuploader.shared.HandlerResultMessage;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploadFile;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem.UPLOAD_STATUS;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class WorkspaceUploadServletStream.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* @Jan 21, 2014
*/
public class WorkspaceUploadServletStream extends HttpServlet implements Servlet{
public static final String UNKNOWN_UNKNOWN = "unknown/unknown";
private static final long serialVersionUID = 1778008252774571216L;
protected static final String UTF_8 = "UTF-8";
public static final String UPLOAD_TYPE = ConstantsWorkspaceUploader.UPLOAD_TYPE;
public static final String ID_FOLDER = ConstantsWorkspaceUploader.ID_FOLDER;
public static final String UPLOAD_FORM_ELEMENT = ConstantsWorkspaceUploader.UPLOAD_FORM_ELEMENT;
public static final String CLIENT_UPLOAD_KEYS = ConstantsWorkspaceUploader.CLIENT_UPLOAD_KEYS;
public static final String JSON_CLIENT_KEYS = ConstantsWorkspaceUploader.JSON_CLIENT_KEYS;
public static final String IS_OVERWRITE = ConstantsWorkspaceUploader.IS_OVERWRITE;
public static final String CANCEL_UPLOAD = ConstantsWorkspaceUploader.CANCEL_UPLOAD;
public static final String FILE = "File";
public static final String D4ST = Extensions.REPORT_TEMPLATE.getName(); //extension of Report Template type
public static final String D4SR = Extensions.REPORT.getName(); //extension of Report type
public static Logger logger = LoggerFactory.getLogger(WorkspaceUploadServletStream.class);
private static boolean appEngine = false;
/*
* (non-Javadoc)
*
* @see javax.servlet.GenericServlet#init()
*/
@Override
public void init() throws ServletException {
super.init();
String appe = getInitParameter("appEngine");
if (appe != null) {
appEngine = "true".equalsIgnoreCase(appe);
} else {
appEngine = isAppEngine();
}
logger.debug("init: appEngine is "+appEngine);
}
/**
* {@inheritDoc}
*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.debug("GET method in "+WorkspaceUploadServletStream.class.getName()+" is running");
String clientUploadKey = request.getParameter(CLIENT_UPLOAD_KEYS);
if (clientUploadKey == null){
sendError(response, "Internal error: UPLOAD KEY NOT FOUND");
return;
}
logger.debug("GET method CLIENT_UPLOAD_KEY "+clientUploadKey);
boolean cancelUpload = Boolean.parseBoolean(request.getParameter(CANCEL_UPLOAD));
logger.debug("GET method CANCEL_UPLOAD "+cancelUpload);
if (cancelUpload) {
cancelUpload(request.getSession(), clientUploadKey);
sendMessage(response, "Upload abort: "+request.getParameter(CANCEL_UPLOAD));
}else
logger.debug(CANCEL_UPLOAD + " param not found");
// }else
// sendError(response, "Internal error: CANCEL_UPLOAD NOT FOUND");
return;
}
/**
* {@inheritDoc}
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("POST on UploadServlet");
logger.info("POST on UploadServlet");
if (!ServletFileUpload.isMultipartContent(request)) {
logger.error("ERROR: multipart request not found");
sendError(response, "ERROR: multipart request not found");
}
HttpSession session = request.getSession();
logger.debug("UPLOAD-SERVLET (" + session.getId() + ") new upload request received.");
String destinationId = null;
String uploadType = null;
boolean isOverwrite = false;
// String clientUploadKey = null;
FileItemStream uploadItem = null;
ArrayList<String> listClientUploadKeys = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
try {
/**
* An iterator to instances of <code>FileItemStream</code>
* parsed from the request, in the order that they were
*transmitted.
*/
FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request);
int uploadItemsCnt = 0;
//GET FILE STREAM
while (fileItemIterator.hasNext()) {
FileItemStream item = fileItemIterator.next();
if (item.isFormField() && ID_FOLDER.equals(item.getFieldName())){
destinationId = Streams.asString(item.openStream());
logger.debug("ID_FOLDER OK "+destinationId);
}
if (item.isFormField() && UPLOAD_TYPE.equals(item.getFieldName())){
uploadType = Streams.asString(item.openStream());
logger.debug("UPLOAD_TYPE OK " +uploadType);
}
if (item.isFormField() && IS_OVERWRITE.equals(item.getFieldName())){
isOverwrite = Boolean.parseBoolean(Streams.asString(item.openStream()));
logger.debug("IS_OVERWRITE OK "+ isOverwrite);
}
if(item.isFormField() && CLIENT_UPLOAD_KEYS.equals(item.getFieldName())){
String jsonClientUploadKey = Streams.asString(item.openStream());
logger.debug("CLIENT_UPLOAD_KEY OK "+jsonClientUploadKey);
LinkedHashMap<String, String> mapKeys = parseJSONClientUploadKeys(jsonClientUploadKey);
listClientUploadKeys = new ArrayList<String>(mapKeys.keySet());
removeListenersIfDone(session, listClientUploadKeys);
for (String clientUploadKey : listClientUploadKeys) {
String fileName = mapKeys.get(clientUploadKey);
WorkspaceUploaderItem workspaceUploader = createNewWorkspaceUploader(clientUploadKey,destinationId,mapKeys.get(clientUploadKey));
logger.debug("created "+workspaceUploader);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.WAIT, "Uploading "+fileName+" at 0%", request.getSession());
}
}
//MUST BE THE LAST PARAMETER TRASMITTED
if (UPLOAD_FORM_ELEMENT.equals(item.getFieldName())){
uploadItem = item;
logger.debug("UPLOAD_FORM_ELEMENT OK "+uploadItem.getName());
// break;
uploadData(request, response, uploadItem, destinationId, uploadType, listClientUploadKeys.get(uploadItemsCnt), isOverwrite);
uploadItemsCnt++;
}
}
} catch (FileUploadException e) {
logger.error("Error processing request in upload servlet", e);
sendError(response, "Internal error: Error during request processing");
return;
}
}
/**
* Removes the listener if done.
*
* @param session the session
* @param keys the keys
*/
private void removeListenersIfDone(HttpSession session, List<String> keys){
for (String key : keys) {
AbstractUploadProgressListener listener = getCurrentListener(session, key);
if (listener != null) {
logger.debug("Listener found");
if (listener.isCanceled() || listener.getPercentage() >= 100){
logger.debug("Listener isCanceled or 100%, removing");
removeCurrentListener(session, key);
}
}else
logger.debug("Session id: "+session.getId() +" - "+key+" - Listener not found");
}
}
/**
* Parses the json client upload keys.
*
* @param jsonClientUploadKeys the json client upload keys
* @return the linked hash map
* @throws FileUploadException the file upload exception
*/
@SuppressWarnings("rawtypes")
private static LinkedHashMap<String, String> parseJSONClientUploadKeys(final String jsonClientUploadKeys) throws FileUploadException{
JSONTokener tokener = new JSONTokener(jsonClientUploadKeys);
JSONObject root;
LinkedHashMap<String, String> keyFiles = null;
try {
root = new JSONObject(tokener);
JSONArray jsonArray = root.getJSONArray(JSON_CLIENT_KEYS);
keyFiles = new LinkedHashMap<String, String>(jsonArray.length());
logger.debug("jsonArray :"+jsonArray.toString());
for (int i=0; i<jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
logger.debug("object :"+object);
String key = (String) object.keys().next();
String value = object.getString(key);
logger.debug("key :"+key+", value: "+value);
keyFiles.put(key, value);
}
/*
JSONObject object = jsonArray.getJSONObject(0);
Iterator it = object.keys();
while(it.hasNext()){
String key = (String) it.next();
String value = object.getString(key);
logger.debug("key :"+key+", value: "+value);
keyFiles.put((String) key, value);
}
*/
} catch (JSONException e) {
logger.error("An error occurred during parsing file names: "+keyFiles, e);
throw new FileUploadException("An error occurred during parsing file names");
}
logger.debug("keyFiles: "+keyFiles);
return keyFiles;
}
/**
* Upload data.
*
* @param request the request
* @param response the response
* @param uploadItem the upload item
* @param destinationId the destination id
* @param uploadType the upload type
* @param clientUploadKey the client upload key
* @param isOverwrite the is overwrite
* @throws ServletException the servlet exception
* @throws IOException Signals that an I/O exception has occurred.
*/
private void uploadData(HttpServletRequest request, final HttpServletResponse response, final FileItemStream uploadItem, String destinationId,String uploadType,String clientUploadKey, boolean isOverwrite) throws ServletException, IOException{
String fileName = uploadItem.getName();
logger.info("Upload servlet parameters: [fileName: "+fileName+ ", destinationId: "+destinationId +", uploadType: "+uploadType+", isOverwrite: "+isOverwrite+", clientUploadKey: "+clientUploadKey+"]");
if (uploadType == null || uploadType.isEmpty()) {
logger.error("Error processing request in upload servlet for: "+fileName+". No upload type found");
sendError(response, "Internal error: No upload type found");
return;
}
if(clientUploadKey==null || clientUploadKey.isEmpty()){
logger.error("Error processing request in upload servlet for: "+fileName+". No client upload key found");
sendError(response, "Internal error: No client upload key found");
return;
}
//CLIENT UPLOAD IS THE KEY
// WorkspaceUploaderItem workspaceUploader = createNewWorkspaceUploader(clientUploadKey,destinationId,fileName);
// saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.WAIT, "Uploading "+fileName+" at 0%", request.getSession());
//RETRIVE WORKSPACE UPLOADER FROM SESSION
WorkspaceUploaderItem workspaceUploader = null;
try {
workspaceUploader = WsUtil.getWorkspaceUploaderInSession(request.getSession(), clientUploadKey);
} catch (Exception e) {
logger.error("Error during workspace uploader retrieving", e);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "An error occurred when uploading "+fileName+". Error processing request in upload servlet", request.getSession());
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error processing request in upload servlet");
return;
}
//TODO DEBUG REMOVE THIS
// saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "An error occurred when uploading "+fileName+". Error processing request in upload servlet", request.getSession());
// response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error processing request in upload servlet");
// return;
Workspace wa = null;
try {
logger.debug("getWorkspace from HL");
wa = WsUtil.getWorkspace(request.getSession());
} catch (Exception e) {
logger.error("Error during workspace retrieving", e);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "An error occurred when uploading "+fileName+". Error processing request in upload servlet", request.getSession());
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error processing request in upload servlet");
return;
}
if (wa == null) {
logger.error("Now workspace found in session");
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "An error occurred when uploading "+fileName+". No workspace in session", request.getSession());
sendError(response, "Internal error: No workspace in session");
return;
}
WorkspaceItem item;
try {
logger.debug("getWorkspace Item from HL");
item = wa.getItem(destinationId);
} catch (ItemNotFoundException e) {
logger.error("Error, no destination folder found", e);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "An error occurred when uploading "+fileName+". No destination folder found", request.getSession());
sendError(response, "Internal error: No destination folder found");
return;
}
if (item.getType() != WorkspaceItemType.FOLDER && item.getType() != WorkspaceItemType.SHARED_FOLDER) {
logger.error("Error processing request in upload servlet: Wrong destination item");
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "An error occurred when uploading "+fileName+". Wrong destination item", request.getSession());
sendError(response, "Internal error: Wrong destination item");
return;
}
final WorkspaceFolder destinationFolder = (WorkspaceFolder) item;
try {
//we calculate an unique name for the current destination
String itemName = "";
logger.debug("getItemName from HL");
if(!isOverwrite)
itemName = WorkspaceUtil.getUniqueName(fileName, destinationFolder);
else
itemName = fileName;
Long size = getContentLength(request);
logger.debug("size: " + size + " bytes");
String contentType = null; //It's set into HL
/*
String contentType = uploadItem.getContentType();
logger.debug("Content type (mime type): "+contentType + " unique name: "+itemName);
if(contentType==null || contentType.compareTo(UNKNOWN_UNKNOWN)==0){
logger.warn("Content Type not detected forcing to null");
contentType = null;
}
*/
String extension = FilenameUtils.getExtension(itemName);
logger.debug("extension: "+extension);
//CONFIRM DESTINATION FOLDER
workspaceUploader.getFile().setParentId(destinationFolder.getId());
//Create Item Uploader to read progress
// WorkspaceUploadFile wsUploadFile = new WorkspaceUploadFile(destinationFolder.getId(), itemName);
// workspaceUploader.setFile(wsUploadFile);
// workspaceUploader.setStatusDescription("Uploading "+itemName+" at 0%");
//instanciate the progress listener
final AbstractUploadProgressListener uploadProgressListener = createNewListener(request.getSession(), clientUploadKey);
final UploadProgressInputStream inputStream = new UploadProgressInputStream(uploadItem.openStream(), size);
inputStream.addListener(uploadProgressListener);
workspaceUploader.setUploadProgress(uploadProgressListener.getUploadProgress());
saveWorkspaceUploaderInSession(workspaceUploader, request.getSession());
if(uploadType.compareTo(FILE)==0) {//IS FILE UPLOAD
boolean isZipFile = MimeTypeUtil.isZipContentType(contentType);
if(isZipFile && (extension.compareToIgnoreCase(D4ST)==0)){ //Create REPORT TEMPLATE
String newItemName = itemName;
logger.debug("createTemplate: "+newItemName);
createTemplate(workspaceUploader, request.getSession(), wa, newItemName, inputStream, destinationFolder, response, isOverwrite);
}else if(isZipFile && (extension.compareToIgnoreCase(D4SR)==0)){ //Create REPORT
String newItemName = itemName;
logger.debug("createReport: "+newItemName);
createReport(workspaceUploader, request.getSession(), wa, newItemName, inputStream, destinationFolder, response, isOverwrite);
}else{ //CREATE AN EXTERNAL FILE
workspaceUploader = WorkspaceUploaderMng.uploadFile(workspaceUploader, request.getSession(), wa, itemName, inputStream, destinationFolder, contentType, isOverwrite, size);
if(workspaceUploader==null)
throw new Exception("Error when creating uploader, it is null!");
sendMessage(response, workspaceUploader.getIdentifier());
}
}else {//IS ARCHIVE UPLOAD
if (MimeTypeUtil.isZipContentType(contentType)){
logger.debug("Unziping content");
workspaceUploader = WorkspaceUploaderMng.uploadArchive(workspaceUploader, request.getSession(), itemName, inputStream, destinationFolder, size);
if(workspaceUploader==null)
throw new Exception("Error when creating uploader, it is null!");
sendMessage(response, workspaceUploader.getIdentifier());
} else{
workspaceUploader = WorkspaceUploaderMng.uploadFile(workspaceUploader, request.getSession(), wa, itemName, inputStream, destinationFolder, contentType, isOverwrite, size);
if(workspaceUploader==null)
throw new Exception("Error when creating uploader, it is null!");
sendMessage(response, workspaceUploader.getIdentifier());
}
}
// file.delete();
} catch (InsufficientPrivilegesException e) {
logger.error("Error creating elements", e);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "An error occurred when uploading. Insufficient privileges", request.getSession());
sendError(response, "Internal error: Insufficient privileges");
return;
} catch (InternalErrorException e) {
logger.error("Error creating elements", e);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "An error occurred when uploading:"+e.getMessage(), request.getSession());
sendError(response, "Internal error: "+e.getMessage());
return;
} catch (ItemAlreadyExistException e) {
logger.error("Error creating elements", e);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "An error occurred when uploading. An item with that name already exists", request.getSession());
sendError(response, "Internal error: An item with that name already exists");
return;
}catch (Exception e) {
logger.error("Error creating elements", e);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "An error occurred when uploading. "+e.getMessage(), request.getSession());
// sendError(response, "Internal error: An error occurred on uploading the file, try again later");
return;
}finally{
removeCurrentListener(request.getSession(), clientUploadKey);
}
}
/**
* Save workspace uploader status.
*
* @param workspaceUploader the workspace uploader
* @param status the status
* @param description the description
* @param session the session
* @return the workspace uploader item
*/
private synchronized WorkspaceUploaderItem saveWorkspaceUploaderStatus(WorkspaceUploaderItem workspaceUploader, UPLOAD_STATUS status, String description, HttpSession session){
workspaceUploader.setUploadStatus(status);
workspaceUploader.setStatusDescription(description);
try {
saveWorkspaceUploaderInSession(workspaceUploader, session);
} catch (Exception e) {
logger.error(e.getMessage());
}
return workspaceUploader;
}
/**
* Creates the new workspace uploader.
*
* @param clientUploadKey the client upload key
* @param folderParentId the folder parent id
* @param fileName the file name
* @return the workspace uploader item
*/
private WorkspaceUploaderItem createNewWorkspaceUploader(String clientUploadKey, String folderParentId, String fileName){
//CLIENT UPLOAD IS THE KEY
WorkspaceUploaderItem workspaceUploader = new WorkspaceUploaderItem(clientUploadKey);
workspaceUploader.setClientUploadKey(clientUploadKey);
//Create File
WorkspaceUploadFile wsUploadFile = new WorkspaceUploadFile(folderParentId, fileName);
workspaceUploader.setFile(wsUploadFile);
return workspaceUploader;
}
/**
* Gets the random.
*
* @return the random
*/
private static int getRandom(){
Random randomGenerator = new Random();
return randomGenerator.nextInt(Integer.MAX_VALUE);
}
/**
* Save workspace uploader in session.
*
* @param workspaceUploader the workspace uploader
* @param httpSession the http session
* @return the workspace uploader item
* @throws Exception the exception
*/
public static void saveWorkspaceUploaderInSession(WorkspaceUploaderItem workspaceUploader, HttpSession httpSession) throws Exception {
if(workspaceUploader!=null){
try {
WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader);
} catch (Exception e) {
logger.error("Error during WorkspaceUploaderItem save in session workspace uploader: "+workspaceUploader,e);
throw new Exception("An error occurred during uploading. Try again");
}
}else
throw new Exception("An error occurred during uploading. Workspace Uploader not found. Abort and try again");
}
//TEST TIME
/**
* Prints the start time.
*
* @return the long
*/
public static Long printStartTime(){
Long startTime = System.currentTimeMillis();
logger.debug("Start time: "+startTime);
return startTime;
}
//TEST TIME
/**
* Prints the elapsed time.
*
* @param startTime the start time
*/
public static void printElapsedTime(long startTime){
Long endTime = System.currentTimeMillis() - startTime;
String time = String.format("%d msc %d sec", endTime, TimeUnit.MILLISECONDS.toSeconds(endTime));
logger.debug("Elapsed Time: "+time);
}
/**
* Notify upload in shared folder.
*
* @param httpSession the http session
* @param workspace the workspace
* @param itemId the item id
* @param destinationFolderId the destination folder id
* @param isOverwrite the is overwrite
*/
public static void notifyUploadInSharedFolder(final HttpSession httpSession, final Workspace workspace, final String itemId, final String destinationFolderId, final boolean isOverwrite){
new Thread(){
public void run() {
WorkspaceItem sourceItem;
try {
sourceItem = workspace.getItem(itemId);
String sourceSharedId = sourceItem.getIdSharedFolder();
WorkspaceItem folderDestinationItem = workspace.getItem(destinationFolderId);
NotificationsWorkspaceUploader.checkSendNotifyChangedItemToShare(httpSession, sourceItem, sourceSharedId, folderDestinationItem,isOverwrite);
} catch (Exception e) {
logger.error("Error in notifyUploadInSharedFolder", e);
}
};
}.start();
}
/**
* Overwrite item.
*
* @param wa the wa
* @param itemName the item name
* @param fileData the file data
* @param destinationFolder the destination folder
* @return the folder item
*/
private FolderItem overwriteItem(Workspace wa, String itemName, InputStream fileData, WorkspaceFolder destinationFolder){
FolderItem overwriteItem = null;
try {
logger.debug("case overwriting item.. "+itemName);
overwriteItem = (FolderItem) wa.find(itemName, destinationFolder.getId());
logger.debug("overwriteItem item was found, id is: "+overwriteItem.getId());
wa.updateItem(overwriteItem.getId(), fileData);
logger.debug("updateItem with id: "+overwriteItem.getId()+ ", is completed");
} catch (ItemNotFoundException e) {
logger.error("Error in createExternalFile, ItemNotFoundException", e);
} catch (WrongItemTypeException e) {
logger.error("Error in createExternalFile, WrongItemTypeException", e);
} catch (WorkspaceFolderNotFoundException e) {
logger.error("Error in createExternalFile, WorkspaceFolderNotFoundException", e);
} catch (WrongDestinationException e) {
logger.error("Error in createExternalFile, WrongDestinationException", e);
} catch (InsufficientPrivilegesException e) {
logger.error("Error in createExternalFile, InsufficientPrivilegesException", e);
} catch (ItemAlreadyExistException e) {
logger.error("Error in createExternalFile, ItemAlreadyExistException", e);
} catch (InternalErrorException e) {
logger.error("Error in createExternalFile, InternalErrorException", e);
}catch (Exception e) {
logger.error("Error in createExternalFile, Exception", e);
}
return overwriteItem;
}
/**
* Creates the report.
*
* @param workspaceUploader the workspace uploader
* @param httpSession the http session
* @param wa the wa
* @param itemName the item name
* @param fileInputStream the file input stream
* @param destinationFolder the destination folder
* @param response the response
* @param isOverwrite the is overwrite
* @throws InsufficientPrivilegesException the insufficient privileges exception
* @throws ItemAlreadyExistException the item already exist exception
* @throws InternalErrorException the internal error exception
* @throws IOException Signals that an I/O exception has occurred.
*/
private void createReport(WorkspaceUploaderItem workspaceUploader, HttpSession httpSession, Workspace wa, String itemName, InputStream fileInputStream, WorkspaceFolder destinationFolder, HttpServletResponse response, boolean isOverwrite) throws InsufficientPrivilegesException, ItemAlreadyExistException, InternalErrorException, IOException{
try {
Report report = null;
if(!isOverwrite){
itemName = WorkspaceUtil.getUniqueName(itemName, destinationFolder);
report = wa.createReport(itemName, "", Calendar.getInstance(), Calendar.getInstance(), "", "", "", 0, "",fileInputStream, destinationFolder.getId());
notifyUploadInSharedFolder(httpSession,wa,report.getId(),destinationFolder.getId(), isOverwrite);
sendMessage(response, "File "+report.getName()+" imported correctly in "+destinationFolder.getPath());
}
else{ //CASE OVERWRITE
FolderItem rep = overwriteItem(wa, itemName, fileInputStream, destinationFolder);
if(rep!=null){
notifyUploadInSharedFolder(httpSession,wa,rep.getId(),destinationFolder.getId(), isOverwrite);
sendMessage(response, "File "+rep.getName()+" imported correctly in "+destinationFolder.getPath());
}
else
sendError(response,"Internal error: Workspace Item Not Found");
}
} catch (WrongDestinationException e) {
logger.error("Error creating elements", e);
workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED);
workspaceUploader.setStatusDescription("An error occurred when uploading. Wrong Destination");
sendError(response, "Internal error: Wrong Destination");
} catch (WorkspaceFolderNotFoundException e) {
logger.error("Error creating elements", e);
workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED);
workspaceUploader.setStatusDescription("An error occurred when uploading. Workspace Folder Not Found");
sendError(response, "Internal error: Workspace Folder Not Found");
}finally{
try {
// StreamUtils.deleteTempFile(file);
WsUtil.eraseWorkspaceUploaderInSession(httpSession, workspaceUploader.getIdentifier());
} catch (Exception e2) {
// TODO: handle exception
}
}
}
/**
* Creates the template.
*
* @param workspaceUploader the workspace uploader
* @param httpSession the http session
* @param wa the wa
* @param itemName the item name
* @param fileInputStream the file input stream
* @param destinationFolder the destination folder
* @param response the response
* @param isOverwrite the is overwrite
* @throws InsufficientPrivilegesException the insufficient privileges exception
* @throws ItemAlreadyExistException the item already exist exception
* @throws InternalErrorException the internal error exception
* @throws IOException Signals that an I/O exception has occurred.
*/
private void createTemplate(WorkspaceUploaderItem workspaceUploader, HttpSession httpSession, Workspace wa, String itemName, InputStream fileInputStream, WorkspaceFolder destinationFolder, HttpServletResponse response, boolean isOverwrite) throws InsufficientPrivilegesException, ItemAlreadyExistException, InternalErrorException, IOException{
try {
ReportTemplate template = null;
if(!isOverwrite){
itemName = WorkspaceUtil.getUniqueName(itemName, destinationFolder);
template = wa.createReportTemplate(itemName, "", Calendar.getInstance(), Calendar.getInstance(), "", "", 0, "", fileInputStream, destinationFolder.getId());
notifyUploadInSharedFolder(httpSession,wa,template.getId(),destinationFolder.getId(), isOverwrite);
sendMessage(response, "File "+template.getName()+" imported correctly in "+destinationFolder.getPath());
}else{ //CASE OVERWRITE
FolderItem rep = overwriteItem(wa, itemName, fileInputStream, destinationFolder);
if(rep!=null){
notifyUploadInSharedFolder(httpSession,wa,rep.getId(),destinationFolder.getId(), isOverwrite);
sendMessage(response, "File "+rep.getName()+" imported correctly in "+destinationFolder.getPath());
}
else
sendError(response,"Internal error: Workspace Item Not Found");
}
} catch (WrongDestinationException e) {
logger.error("Error creating elements", e);
workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED);
workspaceUploader.setStatusDescription("An error occurred when uploading. Wrong Destination");
sendError(response, "Internal error: Wrong Destination");
} catch (WorkspaceFolderNotFoundException e) {
logger.error("Error creating elements", e);
workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED);
workspaceUploader.setStatusDescription("An error occurred when uploading. Workspace Folder Not Found");
sendError(response, "Internal error: Workspace Folder Not Found");
}finally{
try {
// StreamUtils.deleteTempFile(fileInputStream);
WsUtil.eraseWorkspaceUploaderInSession(httpSession, workspaceUploader.getIdentifier());
} catch (Exception e2) {
// TODO: handle exception
}
}
}
/**
* Send error.
*
* @param response the response
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
protected void sendError(HttpServletResponse response, String message) throws IOException{
try {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
HandlerResultMessage resultMessage = HandlerResultMessage.errorResult(message);
response.getWriter().write(resultMessage.toString());
//5.6 Closure of Response Object:
//When a response is closed, the container must immediately flush all remaining content in the response buffer to the client
// response.flushBuffer();
} catch (IOException e){
logger.warn("IOException class name: "+e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage());
else
throw e; //Sending Exceptions
}
}
/**
* Send message.
*
* @param response the response
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
protected void sendMessage(HttpServletResponse response, String message) throws IOException{
try {
response.setStatus(HttpServletResponse.SC_ACCEPTED);
HandlerResultMessage resultMessage = HandlerResultMessage.okResult(message);
response.getWriter().write(resultMessage.toString());
//5.6 Closure of Response Object:
//When a response is closed, the container must immediately flush all remaining content in the response buffer to the client
// response.flushBuffer();
} catch (IOException e){
logger.warn("IOException class name: "+e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage());
else
throw e; //Sending Exceptions
}
}
/**
* Send warn message.
*
* @param response the response
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
protected void sendWarnMessage(HttpServletResponse response, String message) throws IOException{
try {
response.setStatus(HttpServletResponse.SC_ACCEPTED);
HandlerResultMessage resultMessage = HandlerResultMessage.warnResult(message);
response.getWriter().write(resultMessage.toString());
//5.6 Closure of Response Object:
//When a response is closed, the container must immediately flush all remaining content in the response buffer to the client
// response.flushBuffer();
} catch (IOException e){
logger.warn("IOException class name: "+e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage());
else
throw e; //Sending Exceptions
}
}
/**
* Mark the current upload process to be canceled.
*
* @param session the session
* @param clientUploadKey the client upload key
*/
public void cancelUpload(HttpSession session, String clientUploadKey) {
logger.debug("UPLOAD-SERVLET (" + session.getId()+ ") cancelling Upload: "+clientUploadKey);
AbstractUploadProgressListener listener = getCurrentListener(session, clientUploadKey);
if (listener != null && !listener.isCanceled()) {
logger.info("CancelUpload listener is "+listener.toString());
listener.setException(new UploadCanceledException());
}else
logger.info("Skipping cancel upload: listener is null or is cancel");
}
/**
* Get the listener active in this session.
*
* @param session the session
* @param clientUploadKey the client upload key
* @return the listener active
*/
protected AbstractUploadProgressListener getCurrentListener(HttpSession session, String clientUploadKey) {
if (isAppEngine()) {
return MemoryUploadListener.current(session.getId(), clientUploadKey);
} else {
return UploadProgressListener.current(session, clientUploadKey);
}
}
/**
* Just a method to detect whether the web container is running with
* appengine restrictions.
*
* @return true if the case of the application is running in appengine
*/
public boolean isAppEngine() {
return appEngine;
}
/**
* Create a new listener for this session.
*
* @param session the session
* @param clientUploadKey the client upload key
* @return the appropriate listener
*/
protected AbstractUploadProgressListener createNewListener(HttpSession session, String clientUploadKey) {
if (isAppEngine()) {
return new MemoryUploadListener(session, clientUploadKey, 0, 100);
} else {
return new UploadProgressListener(session, clientUploadKey, 0, 100);
}
}
/**
* Gets the content length.
*
* @param request the request
* @return the content length
*/
private long getContentLength(HttpServletRequest request) {
long size = -1;
try {
size = Long.parseLong(request
.getHeader(FileUploadBase.CONTENT_LENGTH));
} catch (NumberFormatException e) {
}
return size;
}
/**
* Remove the listener active in this session.
*
* @param session the session
* @param clientUploadKey the client upload key
*/
protected void removeCurrentListener(HttpSession session, String clientUploadKey) {
logger.debug("RemoveCurrentListener: "+clientUploadKey);
AbstractUploadProgressListener listener = getCurrentListener(session, clientUploadKey);
if (listener != null) {
logger.debug("Removing listener: "+listener.getClientUploadKey());
listener.remove();
}else
logger.warn("Listener "+clientUploadKey+ "is null");
}
/**
* The main method.
*
* @param args the arguments
*/
/*
public static void main(String[] args) {
try {
parseJSONClientUploadKeys("{\"ClientKeys\":[{\"3D6CAAEFF9241F6\":\"bookmarks.xml\"}, {\"69E9907A78AD20B\":\"WFS\"}]}");
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
}

View File

@ -0,0 +1,102 @@
package org.gcube.portlets.widgets.workspaceuploader.server;
import org.gcube.common.homelibary.model.items.type.WorkspaceItemType;
import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.WorkspaceItem;
import org.gcube.portlets.widgets.workspaceuploader.client.WorkspaceUploaderService;
import org.gcube.portlets.widgets.workspaceuploader.server.util.WsUtil;
import org.gcube.portlets.widgets.workspaceuploader.shared.UploadProgress;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem.UPLOAD_STATUS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
/**
* The server side implementation of the RPC service.
*/
@SuppressWarnings("serial")
public class WorkspaceUploaderServiceImpl extends RemoteServiceServlet implements WorkspaceUploaderService {
public static Logger logger = LoggerFactory.getLogger(WorkspaceUploaderServiceImpl.class);
@Override
public WorkspaceUploaderItem getUploadStatus(String identifier) throws Exception {
if (identifier == null || identifier.isEmpty()) {
String exception = "Invalid upload identifier, it is null or empty";
logger.error(exception);
throw new Exception(exception);
}
logger.trace("Get UploadStatus for id: "+identifier);
WorkspaceUploaderItem uploader = WsUtil.getWorkspaceUploaderInSession(getThreadLocalRequest().getSession(), identifier);
if (uploader == null) {
WorkspaceUploaderItem waitingUpload = new WorkspaceUploaderItem(identifier, null, UPLOAD_STATUS.WAIT, "Upload waiting..", new UploadProgress());
waitingUpload.setClientUploadKey(identifier);
return waitingUpload;
/*
String exception = "Item upload not found";
logger.error(exception);
throw new Exception(exception);*/
}
// getThreadIds();
logger.trace("returning uploader: "+uploader);
return uploader;
}
@Override
public String getWorkspaceId() throws Exception {
logger.trace("getWorkspaceId");
Workspace workspace;
try {
workspace = WsUtil.getWorkspace(getThreadLocalRequest().getSession());
if(workspace!=null)
return workspace.getRoot().getId();
} catch (Exception e) {
logger.error("Get workspace id error", e);
String error = "An error occurred getting root id";
throw new Exception(error);
}
return null;
}
/* (non-Javadoc)
* @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService#itemExistsInWorkpaceFolder(java.lang.String, java.lang.String)
*/
@Override
public String itemExistsInWorkpaceFolder(String parentId, String itemName) throws Exception {
logger.trace("get itemExistsInWorkpace by parentId: "+parentId);
try {
Workspace workspace = WsUtil.getWorkspace(getThreadLocalRequest().getSession());
WorkspaceItem wsItem = workspace.getItem(parentId); //GET PARENT
if(wsItem.getType().equals(WorkspaceItemType.FOLDER) || wsItem.getType().equals(WorkspaceItemType.SHARED_FOLDER)){
WorkspaceItem itemFound = workspace.find(itemName, parentId);
if(itemFound==null)
return null;
return itemFound.getId();
}
else
throw new Exception("Invalid Folder parent");
} catch (Exception e) {
String error = "Sorry an error occurred when searching item id, please refresh and try again";
logger.error(error, e);
throw new Exception(e.getMessage());
}
}
// protected void getThreadIds(){
// WorkspaceUploadServletStream.printAllThreadIds();
// }
}

View File

@ -0,0 +1,187 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.server.notification;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.gcube.common.homelibary.model.items.type.WorkspaceItemType;
import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.WorkspaceItem;
import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder;
import org.gcube.portlets.widgets.workspaceuploader.server.util.UserUtil;
import org.gcube.portlets.widgets.workspaceuploader.server.util.WsUtil;
import org.gcube.portlets.widgets.workspaceuploader.shared.ContactModel;
/**
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* @May 27, 2013
*
*/
public class NotificationsWorkspaceUploader {
protected static Logger logger = Logger.getLogger(NotificationsWorkspaceUploader.class);
/**
* Send a notification if an item is added or updated to sharing folder
* @param httpSession
* @param sourceItem
* @param sourceSharedId
* @param folderDestinationItem
*/
public static void checkSendNotifyChangedItemToShare(HttpSession httpSession, final WorkspaceItem sourceItem, final String sourceSharedId, final WorkspaceItem folderDestinationItem, boolean isOverwrite) {
logger.trace("checkSendNotifyAddItemToShare");
if(folderDestinationItem!=null){
try{
if(folderDestinationItem.isShared()){ //Notify Added Item To Sharing?
logger.trace("checkNotifyAddItemToShare source item: "+sourceItem.getName()+" sourceSharedId: "+sourceSharedId + " folder destination: "+folderDestinationItem.getName() + " folder destination shared folder id: "+folderDestinationItem.getIdSharedFolder());
//share condition is true if source shared folder is not null
boolean shareChangeCondition = sourceSharedId==null?false:true;
//System.out.println("shareChangeCondition add item: "+ shareChangeCondition);
logger.trace("shareChangeCondition add item: "+shareChangeCondition);
//if shareChangeCondition is true.. notifies added item to sharing
if(shareChangeCondition){
Workspace workspace = WsUtil.getWorkspace(httpSession);
List<ContactModel> listContacts = getListUserSharedByFolderSharedId(workspace, folderDestinationItem.getIdSharedFolder());
WorkspaceItem destinationSharedFolder = workspace.getItem(folderDestinationItem.getIdSharedFolder());
NotificationsWorkspaceUploaderProducer np = new NotificationsWorkspaceUploaderProducer(WsUtil.getAslSession(httpSession));
if(destinationSharedFolder instanceof WorkspaceSharedFolder){
//SWITCH BEETWEEN ADDED OR UPDATED
if(!isOverwrite)
np.notifyAddedItemToSharing(listContacts, sourceItem, (WorkspaceSharedFolder) destinationSharedFolder);
else
np.notifyUpdatedItemToSharing(listContacts, sourceItem, (WorkspaceSharedFolder) destinationSharedFolder);
logger.trace("The notifies was sent correctly");
}else
logger.trace("The notifies doesn't sent because "+destinationSharedFolder+ " is not instance of WorkspaceSharedFolder");
// np.notifyAddedItemToSharing(listContacts, (WorkspaceFolder) folderDestinationItem);
}
}
else
logger.trace("folder destination is not shared");
}catch (Exception e) {
logger.error("An error occurred in checkSendNotifyAddItemToShare ",e);
}
}else
logger.warn("The notifies is failure in checkSendNotifyAddItemToShare because folder destination item is null");
}
/**
*
* @param workspace
* @param idSharedFolder
* @return
* @throws Exception
*/
public static List<ContactModel> getListUserSharedByFolderSharedId(Workspace workspace, String idSharedFolder) throws Exception {
logger.trace("getListUserSharedByFolderSharedId "+ idSharedFolder);
try {
WorkspaceItem wsItem = workspace.getItem(idSharedFolder);
if(isASharedFolder(wsItem)){
WorkspaceSharedFolder wsFolder = (WorkspaceSharedFolder) wsItem;
List<String> listPortalLogin = wsFolder.getUsers();
ArrayList<ContactModel> users = new ArrayList<ContactModel>(listPortalLogin.size());
for (String login : listPortalLogin) {
users.add(new ContactModel(login, login, false, UserUtil.getUserFullName(login)));
}
return users;
}
else{
logger.info("the item with id: "+idSharedFolder+ " is not "+WorkspaceItemType.SHARED_FOLDER);
}
return new ArrayList<ContactModel>();
} catch (Exception e) {
logger.error("Error in getListUserSharedByItemId ", e);
throw new Exception(e.getMessage());
}
}
/**
*
* @param wsItem
* @return
*/
public static boolean isASharedFolder(WorkspaceItem wsItem){
if(wsItem!=null)
return wsItem.getType().equals(WorkspaceItemType.SHARED_FOLDER);
return false;
}
/**
*
* @param wsItem
* @return
*/
public static boolean isASharedFolderForId(HttpSession httpSession, String itemId){
if(itemId==null || itemId.isEmpty())
return false;
try {
Workspace workspace = WsUtil.getWorkspace(httpSession);
WorkspaceItem wsItem = workspace.getItem(itemId);
if(wsItem!=null)
return wsItem.getType().equals(WorkspaceItemType.SHARED_FOLDER);
return false;
} catch (Exception e) {
logger.error("An errror occurred in isASharedFolderForId", e);
return false;
}
}
/**
*
* @param itemId
* @param rootFolderSharedId
* @return
*/
public static boolean checkIsRootFolderShared(String itemId, String rootFolderSharedId) {
logger.trace("checkIsRootFolderShared between [itemid: "+itemId +", rootFolderSharedId: "+rootFolderSharedId+"]");
if(itemId==null)
return false;
if(rootFolderSharedId==null)
return false;
if(itemId.compareTo(rootFolderSharedId)==0)
return true;
return false;
}
}

View File

@ -0,0 +1,158 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.server.notification;
import java.util.List;
import org.apache.log4j.Logger;
import org.gcube.application.framework.core.session.ASLSession;
import org.gcube.applicationsupportlayer.social.NotificationsManager;
import org.gcube.common.homelibrary.home.workspace.WorkspaceItem;
import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.portlets.widgets.workspaceuploader.server.util.WsUtil;
import org.gcube.portlets.widgets.workspaceuploader.shared.ContactModel;
/**
* The Class NotificationsProducer.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 3, 2015
*/
public class NotificationsWorkspaceUploaderProducer {
protected ScopeBean scope;
protected static Logger logger = Logger.getLogger(NotificationsWorkspaceUploaderProducer.class);
protected NotificationsManager notificationsMng;
protected ASLSession aslSession;
protected String userId;
/**
* Instantiates a new notifications producer.
*
* @param aslSession the asl session
*/
public NotificationsWorkspaceUploaderProducer(ASLSession aslSession) {
this.notificationsMng = WsUtil.getNotificationManager(aslSession);
this.aslSession = aslSession;
this.userId = aslSession.getUsername();
}
/**
* Gets the notifications mng.
*
* @return the notifications mng
*/
public NotificationsManager getNotificationsMng() {
return notificationsMng;
}
/**
* Sets the notification mng.
*
* @param notificationMng the new notification mng
*/
public void setNotificationMng(NotificationsManager notificationMng) {
this.notificationsMng = notificationMng;
}
/**
* Gets the asl session.
*
* @return the asl session
*/
public ASLSession getAslSession() {
return aslSession;
}
/**
* Runs a new thread to notify the contacts passed in input.
*
* @param listContacts the list contacts
* @param workspaceItem the workspace item
* @param sharedFolder the shared folder
*/
public void notifyAddedItemToSharing(final List<ContactModel> listContacts, final WorkspaceItem workspaceItem, final WorkspaceSharedFolder sharedFolder) {
new Thread() {
@Override
public void run() {
// printContacts(listContacts);
logger.info("Send notifies added item in sharedfolder is running...");
//DEBUG
System.out.println("Send notifies added item in sharedfolder is running...");
for (ContactModel infoContactModel : listContacts) {
try{
//NOTIFIES ONLY THE USERS THAT ARE DIFFERENT FROM CURRENT USER
if(infoContactModel.getLogin().compareTo(userId)!=0){
logger.info("Sending notification to user "+infoContactModel.getLogin() +" added item "+workspaceItem.getName()+" in shared folder "+sharedFolder.getName());
boolean notify = notificationsMng.notifyAddedItem(infoContactModel.getLogin(), workspaceItem, sharedFolder);
if(!notify){
logger.error("An error occured when notify user: "+infoContactModel.getLogin());
}
}
}catch (Exception e) {
logger.error("An error occured in notifyAddedItemToSharing ", e);
}
}
logger.trace("notifies of added item in shared folder is completed");
}
}.start();
}
/**
* Runs a new thread to notify the contacts passed in input.
*
* @param listContacts the list contacts
* @param workspaceItem the workspace item
* @param sharedFolder the shared folder
*/
public void notifyUpdatedItemToSharing(final List<ContactModel> listContacts, final WorkspaceItem workspaceItem, final WorkspaceSharedFolder sharedFolder) {
new Thread() {
@Override
public void run() {
// printContacts(listContacts);
logger.info("Send notifies updated item in shared folder is running...");
for (ContactModel infoContactModel : listContacts) {
try{
//NOTIFIES ONLY THE USERS THAT ARE DIFFERENT FROM CURRENT USER
if(infoContactModel.getLogin().compareTo(userId)!=0){
logger.info("Sending notification to user "+infoContactModel.getLogin() +" updated item "+workspaceItem.getName()+" in shared folder "+sharedFolder.getName());
boolean notify = notificationsMng.notifyUpdatedItem(infoContactModel.getLogin(), workspaceItem, sharedFolder);
if(!notify){
logger.error("An error updated when notify user: "+infoContactModel.getLogin());
}
}
}catch (Exception e) {
logger.error("An error updated in notifyAddedItemToSharing ", e);
e.printStackTrace();
}
}
logger.trace("notifies of updated item in shared folder is completed");
}
}.start();
}
}

View File

@ -0,0 +1,259 @@
package org.gcube.portlets.widgets.workspaceuploader.server.upload;
import java.io.Serializable;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.ProgressListener;
import org.gcube.portlets.widgets.workspaceuploader.shared.UploadProgress;
import org.gcube.portlets.widgets.workspaceuploader.shared.event.UploadProgressChangeEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The listener interface for receiving uploadProgress events. The class that is
* interested in processing a uploadProgress event implements this interface,
* and the object created with that class is registered with a component using
* the component's <code>addUploadProgressListener<code> method. When
* the uploadProgress event occurs, that object's appropriate
* method is invoked.
*
* @see UploadProgressEvent
*/
public abstract class AbstractUploadProgressListener implements
ProgressListener, Serializable {
/**
*
*/
private static final long serialVersionUID = 9039352626573789199L;
private static final double COMPLETE_PERECENTAGE = 100d;
private int percentage = -1;
private UploadProgress uploadProgress;
private int percentageOffset = 0;
private double completePercentage = COMPLETE_PERECENTAGE;
private static Logger logger = LoggerFactory
.getLogger(AbstractUploadProgressListener.class);
protected RuntimeException exception = null;
protected boolean exceptionTrhown = false;
protected String sessionId;
public static AbstractUploadProgressListener current(String sessionId) {
throw new RuntimeException(
"Implement the static method 'current' in your customized class");
}
protected Long bytesRead = 0L, contentLength = 0L;
private String clientUploadKey;
// protected static HttpServletRequest request;
protected String sessionKey;
private HttpSession session;
/**
* Save itself in session or cache.
*/
public abstract void save();
/**
* Remove itself from session or cache.
*/
public abstract void remove();
/**
* Instantiates a new upload progress listener.
*
* @param request
* the request
* @param uploadProgress
* the upload progress
* @param percentageOffset
* the percentage offset
* @param completePercentage
* the complete percentage
*/
public AbstractUploadProgressListener(HttpSession session,
String clientUploadKey, int percentageOffset,
double completePercentage) {
this.sessionId = session.getId();
this.session = session;
this.clientUploadKey = clientUploadKey;
this.sessionKey = sessionId + ":" + clientUploadKey;
this.uploadProgress = new UploadProgress();
this.percentageOffset = percentageOffset;
this.completePercentage = completePercentage;
logger.debug("Session key: " + sessionKey);
save();
}
/**
* @return the session
*/
public HttpSession getSession() {
return session;
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.fileupload.ProgressListener#update(long, long,
* int)
*/
@Override
public void update(final long bytesRead, final long totalBytes, final int items) {
if (exceptionTrhown) {
return;
}
// If other request has set an exception, it is thrown so the
// commons-fileupload's
// parser stops and the connection is closed.
if (isCanceled()) {
String eName = exception.getClass().getName()
.replaceAll("^.+\\.", "");
logger.info(AbstractUploadProgressListener.class.getName() + " "
+ sessionKey + " The upload has been canceled after "
+ bytesRead + " bytes received, raising an exception ("
+ eName + ") to close the socket");
exceptionTrhown = true;
throw exception;
}
this.bytesRead = bytesRead;
this.contentLength = totalBytes;
int percentage = percentageOffset
+ ((int) Math.floor(((double) bytesRead / (double) totalBytes)
* completePercentage));
if (this.percentage == percentage)
return;
this.percentage = percentage;
UploadProgressChangeEvent event = new UploadProgressChangeEvent();
event.setReadPercentage(percentage);
event.setReadTime(System.currentTimeMillis());
// logger.trace("Updating percentage.. "+percentage);
synchronized (this.uploadProgress) {
// logger.trace("Adding event: "+event);
this.uploadProgress.add(event);
// this.uploadProgress.notifyAll();
}
}
/**
* @return the bytesRead
*/
public Long getBytesRead() {
return bytesRead;
}
/**
* @return the contentLength
*/
public Long getContentLength() {
return contentLength;
}
/**
* Gets the upload progress.
*
* @return the uploadProgress
*/
public UploadProgress getUploadProgress() {
return uploadProgress;
}
/**
* Get the exception.
*
* @return the exception
*/
public RuntimeException getException() {
return exception;
}
/**
* Return true if the process has been canceled due to an error or by the
* user.
*
* @return boolean
*/
public boolean isCanceled() {
return exception != null;
}
/**
* Set the exception which cancels the upload.
*
*/
public void setException(RuntimeException e) {
logger.info("Set RuntimeException to cancel upload");
exception = e;
save();
}
/**
* @return the percentage
*/
public int getPercentage() {
return percentage;
}
/**
* @return the clientUploadKey
*/
public String getClientUploadKey() {
return clientUploadKey;
}
/**
* Gets the session key.
*
* @param httpSessionId
* the http session id
* @param clientUploadKey
* the client upload key
* @return the session key
*/
public static String getSessionKey(String httpSessionId, String clientUploadKey) {
return httpSessionId + ":" + clientUploadKey;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AbstractUploadProgressListener [percentage=");
builder.append(percentage);
builder.append(", percentageOffset=");
builder.append(percentageOffset);
builder.append(", completePercentage=");
builder.append(completePercentage);
builder.append(", exception=");
builder.append(exception);
builder.append(", exceptionTrhown=");
builder.append(exceptionTrhown);
builder.append(", sessionId=");
builder.append(sessionId);
builder.append(", bytesRead=");
builder.append(bytesRead);
builder.append(", contentLength=");
builder.append(contentLength);
builder.append(", clientUploadKey=");
builder.append(clientUploadKey);
builder.append(", sessionKey=");
builder.append(sessionKey);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,109 @@
/*
* Copyright 2010 Manuel Carrasco Moñino. (manolo at apache/org)
* http://code.google.com/p/gwtupload
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.gcube.portlets.widgets.workspaceuploader.server.upload;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This File Upload Listener is used by Apache Commons File Upload to monitor
* the progress of the uploaded file.
*
* This Listener saves itself into a unique map in memory. It doesn't work when
* the application is deployed in cluster.
*
* It is thought to be used in systems where session objects are not updated
* until the request has finished.
*
* @author francesco-mangiacrapa
*
*/
public class MemoryUploadListener extends AbstractUploadProgressListener {
private static final long serialVersionUID = 2082376357722210169L;
private static final Map<String, MemoryUploadListener> listeners = new HashMap<String, MemoryUploadListener>();
private static Logger logger = LoggerFactory
.getLogger(MemoryUploadListener.class);
/**
* Instantiates a new memory upload listener.
*
* @param session
* the session
* @param clientUploadKey
* the client upload key
* @param percentageOffset
* the percentage offset
* @param completePercentage
* the complete percentage
*/
public MemoryUploadListener(HttpSession session, String clientUploadKey,
int percentageOffset, double completePercentage) {
super(session, clientUploadKey, percentageOffset, completePercentage);
}
/**
* Current.
*
* @param sessionId
* the session id
* @param clientUploadKey
* the client upload key
* @return the memory upload listener
*/
public static MemoryUploadListener current(String sessionId,
String clientUploadKey) {
String sessionKey = getSessionKey(sessionId, clientUploadKey);
MemoryUploadListener listener = listeners.get(sessionKey);
logger.debug(sessionKey + " get " + listener);
return listener;
}
/*
* (non-Javadoc)
*
* @see org.gcube.portlets.widgets.workspaceuploader.server.upload.
* AbstractUploadProgressListener#remove()
*/
public void remove() {
listeners.remove(sessionKey);
logger.info(sessionKey + " Remove " + this.toString());
current(sessionKey);
}
/*
* (non-Javadoc)
*
* @see org.gcube.portlets.widgets.workspaceuploader.server.upload.
* AbstractUploadProgressListener#save()
*/
public void save() {
listeners.put(sessionKey, this);
logger.debug(sessionKey + " Saved " + this.toString());
}
public String toString() {
return super.toString();
}
}

View File

@ -0,0 +1,29 @@
/*
* Copyright 2010 Manuel Carrasco Moñino. (manolo at apache/org)
* http://code.google.com/p/gwtupload
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.gcube.portlets.widgets.workspaceuploader.server.upload;
/**
* The Class UploadCanceledException.
* thrown when the client cancels the upload transfer.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 8, 2015
*/
public class UploadCanceledException extends RuntimeException {
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,96 @@
package org.gcube.portlets.widgets.workspaceuploader.server.upload;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.fileupload.ProgressListener;
/**
* The Class UploadProgressInputStream.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 1, 2015
*/
public final class UploadProgressInputStream extends FilterInputStream {
private List<ProgressListener> listeners;
private long bytesRead = 0;
private long totalBytes = 0;
/**
* Instantiates a new upload progress input stream.
*
* @param in the in
* @param totalBytes the total bytes
*/
public UploadProgressInputStream(final InputStream in, final long totalBytes) {
super(in);
this.totalBytes = totalBytes;
listeners = new ArrayList<ProgressListener>();
}
/**
* Adds the listener.
*
* @param listener the listener
*/
public void addListener(final ProgressListener listener) {
listeners.add(listener);
}
/* (non-Javadoc)
* @see java.io.FilterInputStream#read()
*/
@Override
public int read() throws IOException {
int b = super.read();
this.bytesRead++;
updateListeners(bytesRead, totalBytes);
return b;
}
/* (non-Javadoc)
* @see java.io.FilterInputStream#read(byte[])
*/
@Override
public int read(final byte b[]) throws IOException {
return read(b, 0, b.length);
}
/* (non-Javadoc)
* @see java.io.FilterInputStream#read(byte[], int, int)
*/
@Override
public int read(final byte b[], final int off, final int len) throws IOException {
int bytesRead = in.read(b, off, len);
this.bytesRead = this.bytesRead + bytesRead;
updateListeners(this.bytesRead, totalBytes);
return bytesRead;
}
/* (non-Javadoc)
* @see java.io.FilterInputStream#close()
*/
@Override
public void close() throws IOException {
super.close();
updateListeners(totalBytes, totalBytes);
}
/**
* Update listeners.
*
* @param bytesRead the bytes read
* @param totalBytes the total bytes
*/
private void updateListeners(final long bytesRead, final long totalBytes) {
for (ProgressListener listener : listeners)
listener.update(bytesRead, totalBytes, listeners.size());
}
}

View File

@ -0,0 +1,262 @@
/*
* Copyright 2010 Manuel Carrasco Moñino. (manolo at apache/org)
* http://code.google.com/p/gwtupload
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.gcube.portlets.widgets.workspaceuploader.server.upload;
import java.io.Serializable;
import java.util.Date;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is a File Upload Listener that is used by Apache Commons File Upload to
* monitor the progress of the uploaded file.
*
* This object and its attributes have to be serializable because Google
* App-Engine uses dataStore and memCache to store session objects.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Sep 8, 2015
*
*/
public class UploadProgressListener extends AbstractUploadProgressListener {
/**
*
*/
private static final long serialVersionUID = -7757392979344200978L;
private static Logger logger = LoggerFactory.getLogger(AbstractUploadProgressListener.class);
private static int noDataTimeout = 20000;
private static final int WATCHER_INTERVAL = 2000;
/**
* Sets the no data timeout.
*
* @param i
* the new no data timeout
*/
public static void setNoDataTimeout(int i) {
noDataTimeout = i;
}
/**
* A class which is executed in a new thread, so its able to detect when an
* upload process is frozen and sets an exception in order to be canceled.
* This doesn't work in Google application engine
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Sep 8,
* 2015
*/
public class TimeoutWatchDog extends Thread implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6958907286385617168L;
AbstractUploadProgressListener listener;
private long lastBytesRead = 0L;
private long lastData = (new Date()).getTime();
/**
* Instantiates a new timeout watch dog.
*
* @param l
* the l
*/
public TimeoutWatchDog(AbstractUploadProgressListener l) {
listener = l;
}
/**
* Cancel.
*/
public void cancel() {
listener = null;
}
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
Thread.sleep(WATCHER_INTERVAL);
} catch (InterruptedException e) {
if (listener != null) {
if (listener.getBytesRead() > 0
&& listener.getPercentage() >= 100
|| listener.isCanceled()) {
logger.debug(sessionKey
+ " TimeoutWatchDog: upload process has finished, stoping watcher");
listener = null;
} else {
// if (isFrozen()) {
// logger.info( sessionId +
// " TimeoutWatchDog: the recepcion seems frozen: " +
// listener.getBytesRead() + "/" +
// listener.getContentLength() + " bytes ("
// + listener.getPercentage() + "%) ");
// exception = new
// UploadTimeoutException("No new data received after "
// + noDataTimeout / 1000 + " seconds");
// } else {
run();
}
}
}
}
/**
* Checks if is frozen.
*
* @return true, if is frozen
*/
private boolean isFrozen() {
long now = (new Date()).getTime();
if (bytesRead > lastBytesRead) {
lastData = now;
lastBytesRead = bytesRead;
} else if (now - lastData > noDataTimeout) {
return true;
}
return false;
}
}
/**
* Current.
*
* @param request
* the request
* @param clientUploadKey
* the client upload key
* @return the abstract upload progress listener
*/
public static AbstractUploadProgressListener current(HttpSession session,
String clientUploadKey) {
String sessionKey = getSessionKey(session.getId(), clientUploadKey);
return (AbstractUploadProgressListener) session
.getAttribute(sessionKey);
}
private TimeoutWatchDog watcher = null;
/**
* Instantiates a new upload listener.
*
* @param request
* the request
* @param clientUploadKey
* the client upload key
* @param percentageOffset
* the percentage offset
* @param completePercentage
* the complete percentage
*/
public UploadProgressListener(HttpSession session, String clientUploadKey,
int percentageOffset, double completePercentage) {
super(session, clientUploadKey, percentageOffset, completePercentage);
startWatcher();
}
/*
* (non-Javadoc)
*
* @see gwtupload.server.AbstractUploadListener#remove()
*/
/**
* Removes the.
*/
public void remove() {
logger.debug(sessionKey + " removing: " + toString());
if (getSession() != null) {
getSession().removeAttribute(sessionKey);
logger.info("Removed from session: " + toString());
}
}
/*
* (non-Javadoc)
*
* @see gwtupload.server.AbstractUploadListener#save()
*/
/**
* Save.
*/
public void save() {
if (getSession() != null) {
getSession().setAttribute(sessionKey, this);
logger.info("Added in session: " + toString());
}
logger.debug(sessionKey + " save listener " + toString());
}
/*
* (non-Javadoc)
*
* @see gwtupload.server.AbstractUploadListener#update(long, long, int)
*/
@Override
public void update(long done, long total, int item) {
super.update(done, total, item);
if (getPercentage() >= 100) {
stopWatcher();
}
}
/**
* Start watcher.
*/
private void startWatcher() {
if (watcher == null) {
try {
watcher = new TimeoutWatchDog(this);
watcher.start();
} catch (Exception e) {
logger.error(sessionKey + " unable to create watchdog: "
+ e.getMessage());
}
}
}
/**
* Stop watcher.
*/
private void stopWatcher() {
if (watcher != null) {
watcher.cancel();
}
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("UploadProgressListener [watcher=");
builder.append(watcher);
builder.append(super.toString());
return builder.toString();
}
}

View File

@ -0,0 +1,292 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.server.upload;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.gcube.common.homelibrary.home.exceptions.InternalErrorException;
import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder;
import org.gcube.common.homelibrary.home.workspace.exceptions.InsufficientPrivilegesException;
import org.gcube.common.homelibrary.home.workspace.exceptions.ItemAlreadyExistException;
import org.gcube.common.homelibrary.home.workspace.exceptions.ItemNotFoundException;
import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException;
import org.gcube.common.homelibrary.home.workspace.exceptions.WrongDestinationException;
import org.gcube.common.homelibrary.home.workspace.exceptions.WrongItemTypeException;
import org.gcube.common.homelibrary.home.workspace.folder.FolderItem;
import org.gcube.portlets.widgets.workspaceuploader.server.util.WsUtil;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class WorkspaceUploaderManager.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 2, 2015
*/
public class WorkspaceUploaderManager {
public static Logger logger = LoggerFactory.getLogger(WorkspaceUploaderManager.class);
/**
* Instantiates a new workspace uploader manager.
*/
public WorkspaceUploaderManager() {
}
/**
* Creates the workspace uploader file.
*
* @param workspaceUploader the workspace uploader
* @param httpSession the http session
* @param isOvewrite the is ovewrite
* @param wa the wa
* @param uploadFile the upload file
* @param itemName the item name
* @param destinationFolder the destination folder
* @param contentType the content type
* @param totalBytes the total bytes
* @return the workspace uploader item
* @throws InternalErrorException the internal error exception
* @throws IOException Signals that an I/O exception has occurred.
*/
private static WorkspaceUploaderItem createWorkspaceUploaderFile(HttpServletRequest request, final WorkspaceUploaderItem workspaceUploader, final HttpSession httpSession, final boolean isOvewrite, final Workspace wa, final File uploadFile, final String itemName, final WorkspaceFolder destinationFolder, final String contentType, final long totalBytes) throws InternalErrorException, IOException{
logger.debug("Creating WorkspaceUploaderFile...");
// AbstractUploadProgressListener uploadProgressListener = new AbstractUploadProgressListener(request, new UploadProgress(), 70, 30);
// final UploadProgressInputStream inputStream = new UploadProgressInputStream(StreamUtils.openInputStream(uploadFile), totalBytes);
// inputStream.addListener(uploadProgressListener);
//
// workspaceUploader.setUploadProgress(uploadProgressListener.getUploadProgress());
//
// Thread th = new Thread(){
// public void run() {
//
// try {
// workspaceUploader.setUploadStatus(UPLOAD_STATUS.IN_PROGRESS);
// workspaceUploader.setStatusDescription("Uploading "+itemName);
// FolderItem createdItem = null;
//
// if(!isOvewrite){
// logger.debug("Calling HL createExternalFile - [itemName: "+itemName+", contentType: "+contentType+"]");
// createdItem = WorkspaceUtil.createExternalFile(destinationFolder, itemName, "", contentType, inputStream);
// }
// else{
// createdItem = overwriteItem(wa, itemName, inputStream, destinationFolder); //CASE OVERWRITE
// }
//
// if(createdItem!=null){
// WorkspaceUploadServlet.printElapsedTime(WorkspaceUploadServlet.startTime);
// logger.debug("HL file "+createdItem.getName() + " uploaded correctly");
// workspaceUploader.setUploadStatus(UPLOAD_STATUS.COMPLETED);
// workspaceUploader.setStatusDescription("File \""+createdItem.getName()+"\" uploaded correctly");
// WorkspaceUploadServlet.notifyUploadInSharedFolder(httpSession, wa, createdItem.getId(), createdItem.getParent().getId(), isOvewrite);
// }else{
// workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED);
// workspaceUploader.setStatusDescription("An error occurred when uploading \""+itemName + "\". Try again");
// }
// try {
// WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader);
// } catch (Exception e1) {
// logger.error("Error during WorkspaceUploaderItem session update: ",e1);
// }
// } catch (InsufficientPrivilegesException
// | ItemAlreadyExistException | InternalErrorException
// | IOException e) {
// logger.error("Error during upload: ",e);
// workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED);
// workspaceUploader.setStatusDescription("An error occurred when uploading "+itemName+": "+e.getMessage());
// try {
// WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader);
// } catch (Exception e1) {
// logger.error("Error during WorkspaceUploaderItem session update: ",e1);
// }
// } catch (ItemNotFoundException | WrongItemTypeException | WorkspaceFolderNotFoundException | WrongDestinationException e) {
// logger.error("Error during overwrite: ",e);
// workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED);
// workspaceUploader.setStatusDescription("An error occurred when uploading "+itemName+": "+e.getMessage());
// try {
// WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader);
// } catch (Exception e1) {
// logger.error("Error during WorkspaceUploaderItem session update: ",e1);
// }
// }finally{
// try {
// StreamUtils.deleteTempFile(uploadFile);
// WsUtil.eraseWorkspaceUploaderInSession(httpSession, workspaceUploader.getIdentifier());
// } catch (Exception e2) {
// }
// }
// };
// };
//
// logger.debug("start Thread uploading: "+workspaceUploader.getIdentifier());
// th.start();
// logger.debug("returning: "+workspaceUploader);
return workspaceUploader;
}
/**
* Creates the workspace uploader archive.
*
* @param workspaceUploader the workspace uploader
* @param httpSession the http session
* @param uploadFile the upload file
* @param itemName the item name
* @param destinationFolder the destination folder
* @param totalBytes the total bytes
* @return the workspace uploader item
* @throws InternalErrorException the internal error exception
* @throws IOException Signals that an I/O exception has occurred.
*/
private static WorkspaceUploaderItem createWorkspaceUploaderArchive(HttpServletRequest request, final WorkspaceUploaderItem workspaceUploader, final HttpSession httpSession, final File uploadFile, final String itemName, final WorkspaceFolder destinationFolder, final long totalBytes) throws InternalErrorException, IOException{
// AbstractUploadProgressListener uploadProgressListener = new AbstractUploadProgressListener(request, new UploadProgress(), 70, 30);
// final UploadProgressInputStream inputStream = new UploadProgressInputStream(StreamUtils.openInputStream(uploadFile), totalBytes);
// inputStream.addListener(uploadProgressListener);
//
// workspaceUploader.setUploadProgress(uploadProgressListener.getUploadProgress());
//
// Thread th = new Thread(){
// public void run() {
//
// logger.info("calling upload archive - [itemName: "+itemName+"]");
// try {
// workspaceUploader.setUploadStatus(UPLOAD_STATUS.IN_PROGRESS);
// UnzipUtil.unzip(destinationFolder, inputStream, itemName);
//
// logger.info("Archive "+itemName+ " imported correctly in "+destinationFolder.getPath());
// workspaceUploader.setUploadStatus(UPLOAD_STATUS.COMPLETED);
// workspaceUploader.setStatusDescription("Archive "+itemName+ " imported correctly in "+destinationFolder.getPath());
//
// try {
// WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader);
// } catch (Exception e1) {
// logger.error("Error during WorkspaceUploaderItem session update: ",e1);
// }
// } catch (InternalErrorException e) {
// logger.error("Error during uploading: ",e);
// workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED);
// workspaceUploader.setStatusDescription("An error occurred when uploading "+itemName+": "+e.getMessage());
// try {
// WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader);
// } catch (Exception e1) {
// logger.error("Error during WorkspaceUploaderItem session update: ",e1);
// }
// }finally{
// try {
// StreamUtils.deleteTempFile(uploadFile);
// WsUtil.eraseWorkspaceUploaderInSession(httpSession, workspaceUploader.getIdentifier());
// } catch (Exception e2) {
// // TODO: handle exception
// }
// }
// };
// };
//
// logger.debug("start Thread uploading: "+workspaceUploader.getIdentifier());
// th.start();
// logger.debug("returning: "+workspaceUploader);
return workspaceUploader;
}
/**
* Upload file.
*
* @param workspaceUploader the workspace uploader
* @param httpSession the http session
* @param wa the wa
* @param itemName the item name
* @param file the file
* @param destinationFolder the destination folder
* @param contentType the content type
* @param isOverwrite the is overwrite
* @param totolaBytes the totola bytes
* @return the workspace uploader item
* @throws Exception the exception
*/
public static WorkspaceUploaderItem uploadFile(HttpServletRequest request, WorkspaceUploaderItem workspaceUploader, Workspace wa, String itemName, File file, WorkspaceFolder destinationFolder, String contentType, boolean isOverwrite, long totolaBytes) throws Exception {
try {
return createWorkspaceUploaderFile(request, workspaceUploader, request.getSession(), isOverwrite, wa, file, itemName, destinationFolder, contentType, totolaBytes);
} catch (Exception e) {
logger.error("Error when uploading file to HL : ",e);
throw new Exception("An error occurred when uploading "+itemName+". Try again");
}
}
/**
* Upload archive.
*
* @param workspaceUploader the workspace uploader
* @param httpSession the http session
* @param itemName the item name
* @param file the file
* @param destinationFolder the destination folder
* @param totalBytes the total bytes
* @return the workspace uploader item
* @throws Exception the exception
*/
public static WorkspaceUploaderItem uploadArchive(HttpServletRequest request, WorkspaceUploaderItem workspaceUploader, String itemName, File file, WorkspaceFolder destinationFolder, long totalBytes) throws Exception {
try {
return createWorkspaceUploaderArchive(request, workspaceUploader, request.getSession(), file, itemName, destinationFolder, totalBytes);
} catch (Exception e) {
logger.error("Error when uploading Archive to HL creation: ",e);
throw new Exception("An error occurred when uploading "+itemName+". Try again");
}
}
/**
* Upload file status.
*
* @param httpSession the http session
* @param workspaceUploader the workspace uploader
* @return the workspace uploader item
* @throws Exception the exception
*/
public static WorkspaceUploaderItem uploadFileStatus(HttpSession httpSession, WorkspaceUploaderItem workspaceUploader) throws Exception {
return WsUtil.getWorkspaceUploaderInSession(httpSession, workspaceUploader.getIdentifier());
}
/**
* Overwrite item.
*
* @param wa the wa
* @param itemName the item name
* @param fileData the file data
* @param destinationFolder the destination folder
* @return the folder item
* @throws ItemNotFoundException the item not found exception
* @throws WrongItemTypeException the wrong item type exception
* @throws InternalErrorException the internal error exception
* @throws InsufficientPrivilegesException the insufficient privileges exception
* @throws WorkspaceFolderNotFoundException the workspace folder not found exception
* @throws ItemAlreadyExistException the item already exist exception
* @throws WrongDestinationException the wrong destination exception
*/
private static FolderItem overwriteItem(Workspace wa, String itemName, InputStream fileData, WorkspaceFolder destinationFolder) throws ItemNotFoundException, WrongItemTypeException, InternalErrorException, InsufficientPrivilegesException, WorkspaceFolderNotFoundException, ItemAlreadyExistException, WrongDestinationException{
FolderItem overwriteItem = null;
logger.debug("case overwriting item.. "+itemName);
overwriteItem = (FolderItem) wa.find(itemName, destinationFolder.getId());
logger.debug("overwriteItem item was found, id is: "+overwriteItem.getId());
wa.updateItem(overwriteItem.getId(), fileData);
logger.debug("updateItem with id: "+overwriteItem.getId()+ ", is completed");
return overwriteItem;
}
}

View File

@ -0,0 +1,268 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.server.upload;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpSession;
import org.gcube.common.homelibrary.home.exceptions.InternalErrorException;
import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder;
import org.gcube.common.homelibrary.home.workspace.exceptions.InsufficientPrivilegesException;
import org.gcube.common.homelibrary.home.workspace.exceptions.ItemAlreadyExistException;
import org.gcube.common.homelibrary.home.workspace.exceptions.ItemNotFoundException;
import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException;
import org.gcube.common.homelibrary.home.workspace.exceptions.WrongDestinationException;
import org.gcube.common.homelibrary.home.workspace.exceptions.WrongItemTypeException;
import org.gcube.common.homelibrary.home.workspace.folder.FolderItem;
import org.gcube.common.homelibrary.util.WorkspaceUtil;
import org.gcube.common.homelibrary.util.zip.UnzipUtil;
import org.gcube.portlets.widgets.workspaceuploader.server.WorkspaceUploadServletStream;
import org.gcube.portlets.widgets.workspaceuploader.server.util.WsUtil;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem.UPLOAD_STATUS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class WorkspaceUploaderManager.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 2, 2015
*/
public class WorkspaceUploaderMng {
public static Logger logger = LoggerFactory.getLogger(WorkspaceUploaderMng.class);
/**
* Instantiates a new workspace uploader manager.
*/
public WorkspaceUploaderMng() {
}
/**
* Creates the workspace uploader file.
*
* @param workspaceUploader the workspace uploader
* @param httpSession the http session
* @param isOvewrite the is ovewrite
* @param wa the wa
* @param uploadFile the upload file
* @param itemName the item name
* @param destinationFolder the destination folder
* @param contentType the content type
* @param totalBytes the total bytes
* @return the workspace uploader item
* @throws InternalErrorException the internal error exception
* @throws IOException Signals that an I/O exception has occurred.
*/
private static WorkspaceUploaderItem createWorkspaceUploaderFile(final WorkspaceUploaderItem workspaceUploader, final HttpSession httpSession, final boolean isOvewrite, final Workspace wa, final InputStream uploadFile, final String itemName, final WorkspaceFolder destinationFolder, final String contentType, final long totalBytes) throws InternalErrorException, IOException{
logger.debug("Creating WorkspaceUploaderFile...");
workspaceUploader.setUploadStatus(UPLOAD_STATUS.IN_PROGRESS);
workspaceUploader.setStatusDescription("Uploading "+itemName);
FolderItem createdItem = null;
try{
Long startTime = WorkspaceUploadServletStream.printStartTime();
if(!isOvewrite){
logger.debug("Calling HL createExternalFile - [itemName: "+itemName+", contentType: "+contentType+"]");
createdItem = WorkspaceUtil.createExternalFile(destinationFolder, itemName, "", contentType, uploadFile);
}
else{
createdItem = overwriteItem(wa, itemName, uploadFile, destinationFolder); //CASE OVERWRITE
}
if(createdItem!=null){
WorkspaceUploadServletStream.printElapsedTime(startTime);
logger.debug("HL file "+createdItem.getName() + " uploaded correctly in "+destinationFolder.getPath());
workspaceUploader.setUploadStatus(UPLOAD_STATUS.COMPLETED);
workspaceUploader.setStatusDescription("File \""+createdItem.getName()+"\" uploaded correctly");
WorkspaceUploadServletStream.notifyUploadInSharedFolder(httpSession, wa, createdItem.getId(), createdItem.getParent().getId(), isOvewrite);
}else{
workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED);
workspaceUploader.setStatusDescription("An error occurred when uploading \""+itemName + "\". Try again");
}
try {
WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader);
} catch (Exception e1) {
logger.error("Error during WorkspaceUploaderItem session update: ",e1);
}
} catch (InsufficientPrivilegesException
| ItemAlreadyExistException | InternalErrorException
| IOException e) {
logger.error("Error during upload: ",e);
workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED);
workspaceUploader.setStatusDescription("An error occurred when uploading "+itemName+": "+e.getMessage());
try {
WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader);
} catch (Exception e1) {
logger.error("Error during WorkspaceUploaderItem session update: ",e1);
}
} catch (ItemNotFoundException | WrongItemTypeException | WorkspaceFolderNotFoundException | WrongDestinationException e) {
logger.error("Error during overwrite: ",e);
workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED);
workspaceUploader.setStatusDescription("An error occurred when uploading "+itemName+": "+e.getMessage());
try {
WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader);
} catch (Exception e1) {
logger.error("Error during WorkspaceUploaderItem session update: ",e1);
}
}finally{
try {
// StreamUtils.deleteTempFile(uploadFile);
WsUtil.eraseWorkspaceUploaderInSession(httpSession, workspaceUploader.getIdentifier());
} catch (Exception e2) {
}
}
return workspaceUploader;
}
/**
* Creates the workspace uploader archive.
*
* @param workspaceUploader the workspace uploader
* @param httpSession the http session
* @param uploadFile the upload file
* @param itemName the item name
* @param destinationFolder the destination folder
* @param totalBytes the total bytes
* @return the workspace uploader item
* @throws InternalErrorException the internal error exception
* @throws IOException Signals that an I/O exception has occurred.
*/
private static WorkspaceUploaderItem createWorkspaceUploaderArchive(final WorkspaceUploaderItem workspaceUploader, final HttpSession httpSession, final InputStream uploadFile, final String itemName, final WorkspaceFolder destinationFolder, final long totalBytes) throws InternalErrorException, IOException{
logger.info("calling upload archive - [itemName: "+itemName+"]");
try {
workspaceUploader.setUploadStatus(UPLOAD_STATUS.IN_PROGRESS);
UnzipUtil.unzip(destinationFolder, uploadFile, itemName);
logger.info("Archive "+itemName+ " imported correctly in "+destinationFolder.getPath());
workspaceUploader.setUploadStatus(UPLOAD_STATUS.COMPLETED);
workspaceUploader.setStatusDescription("Archive "+itemName+ " imported correctly in "+destinationFolder.getPath());
try {
WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader);
} catch (Exception e1) {
logger.error("Error during WorkspaceUploaderItem session update: ",e1);
}
} catch (InternalErrorException e) {
logger.error("Error during uploading: ",e);
workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED);
workspaceUploader.setStatusDescription("An error occurred when uploading "+itemName+": "+e.getMessage());
try {
WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader);
} catch (Exception e1) {
logger.error("Error during WorkspaceUploaderItem session update: ",e1);
}
}finally{
try {
// StreamUtils.deleteTempFile(uploadFile);
WsUtil.eraseWorkspaceUploaderInSession(httpSession, workspaceUploader.getIdentifier());
} catch (Exception e2) {
// TODO: handle exception
}
}
return workspaceUploader;
}
/**
* Upload file.
*
* @param workspaceUploader the workspace uploader
* @param httpSession the http session
* @param wa the wa
* @param itemName the item name
* @param file the file
* @param destinationFolder the destination folder
* @param contentType the content type
* @param isOverwrite the is overwrite
* @param totolaBytes the totola bytes
* @return the workspace uploader item
* @throws Exception the exception
*/
public static WorkspaceUploaderItem uploadFile(WorkspaceUploaderItem workspaceUploader, HttpSession httpSession, Workspace wa, String itemName, InputStream file, WorkspaceFolder destinationFolder, String contentType, boolean isOverwrite, long totolaBytes) throws Exception {
try {
return createWorkspaceUploaderFile(workspaceUploader, httpSession, isOverwrite, wa, file, itemName, destinationFolder, contentType, totolaBytes);
} catch (Exception e) {
logger.error("Error when uploading file to HL : ",e);
throw new Exception("An error occurred when uploading "+itemName+". Try again");
}
}
/**
* Upload archive.
*
* @param workspaceUploader the workspace uploader
* @param httpSession the http session
* @param itemName the item name
* @param file the file
* @param destinationFolder the destination folder
* @param totalBytes the total bytes
* @return the workspace uploader item
* @throws Exception the exception
*/
public static WorkspaceUploaderItem uploadArchive(WorkspaceUploaderItem workspaceUploader, HttpSession httpSession, String itemName, InputStream file, WorkspaceFolder destinationFolder, long totalBytes) throws Exception {
try {
return createWorkspaceUploaderArchive(workspaceUploader, httpSession, file, itemName, destinationFolder, totalBytes);
} catch (Exception e) {
logger.error("Error when uploading Archive to HL creation: ",e);
throw new Exception("An error occurred when uploading "+itemName+". Try again");
}
}
/**
* Upload file status.
*
* @param httpSession the http session
* @param workspaceUploader the workspace uploader
* @return the workspace uploader item
* @throws Exception the exception
*/
public static WorkspaceUploaderItem uploadFileStatus(HttpSession httpSession, WorkspaceUploaderItem workspaceUploader) throws Exception {
return WsUtil.getWorkspaceUploaderInSession(httpSession, workspaceUploader.getIdentifier());
}
/**
* Overwrite item.
*
* @param wa the wa
* @param itemName the item name
* @param fileData the file data
* @param destinationFolder the destination folder
* @return the folder item
* @throws ItemNotFoundException the item not found exception
* @throws WrongItemTypeException the wrong item type exception
* @throws InternalErrorException the internal error exception
* @throws InsufficientPrivilegesException the insufficient privileges exception
* @throws WorkspaceFolderNotFoundException the workspace folder not found exception
* @throws ItemAlreadyExistException the item already exist exception
* @throws WrongDestinationException the wrong destination exception
*/
private static FolderItem overwriteItem(Workspace wa, String itemName, InputStream fileData, WorkspaceFolder destinationFolder) throws ItemNotFoundException, WrongItemTypeException, InternalErrorException, InsufficientPrivilegesException, WorkspaceFolderNotFoundException, ItemAlreadyExistException, WrongDestinationException{
FolderItem overwriteItem = null;
logger.debug("case overwriting item.. "+itemName);
overwriteItem = (FolderItem) wa.find(itemName, destinationFolder.getId());
logger.debug("overwriteItem item was found, id is: "+overwriteItem.getId());
wa.updateItem(overwriteItem.getId(), fileData);
logger.debug("updateItem with id: "+overwriteItem.getId()+ ", is completed");
return overwriteItem;
}
}

View File

@ -0,0 +1,144 @@
package org.gcube.portlets.widgets.workspaceuploader.server.util;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.gcube.portlets.widgets.workspaceuploader.shared.ContactModel;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.exception.UserManagementPortalException;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.exception.UserRetrievalFault;
import org.gcube.vomanagement.usermanagement.impl.liferay.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.UserModel;
/**
* The Class UserUtil.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 3, 2015
*/
public class UserUtil {
static UserManager um = new LiferayUserManager();
protected static Logger logger = Logger.getLogger(UserUtil.class);
/**
* Gets the user full name.
*
* @param portalLogin the portal login
* @return the user full name
*/
public static String getUserFullName(String portalLogin){
if(portalLogin==null)
return "";
if (WsUtil.isWithinPortal()) { //INTO PORTAL
UserModel curr = null;
try {
try {
curr = um.getUserByScreenName(portalLogin);
} catch (UserManagementSystemException e) {
logger.error("An error occurred in getUserFullName "+e,e);
} catch (UserRetrievalFault e) {
logger.error("An error occurred in getUserFullName "+e,e);
}
} catch (UserManagementPortalException ume) {
logger.error("An error occurred in getUserFullName "+ume,ume);
}catch (Exception e) {
logger.error("An error occurred in getUserFullName "+e,e);
logger.warn("Return portal login "+portalLogin);
return portalLogin;
}
if (curr != null){
// logger.trace("Return "+curr.getFullname() +" full name for: "+portalLogin);
return curr.getFullname();
}
}else{
logger.trace("DEVELOPEMENT MODE ON");
logger.trace("Returning "+WsUtil.TEST_USER_FULL_NAME +" full name for: "+portalLogin);
return WsUtil.TEST_USER_FULL_NAME;
}
logger.trace("Return portal login as full name for: "+portalLogin);
return portalLogin;
}
/**
* Gets the list login by info contact model.
*
* @param listContacts the list contacts
* @return the list login by info contact model
*/
public static List<String> getListLoginByInfoContactModel(List<ContactModel> listContacts){
List<String> listUsers = new ArrayList<String>();
for (ContactModel infoContactModel : listContacts) {
listUsers.add(infoContactModel.getLogin());
}
return listUsers;
}
/**
* Separate users names to comma.
*
* @param listContacts the list contacts
* @return the string
*/
public static String separateUsersNamesToComma(List<ContactModel> listContacts){
String users = "";
for (int i = 0; i < listContacts.size()-1; i++) {
users+= listContacts.get(i).getFullName() + ", ";
}
if(listContacts.size()>1)
users += listContacts.get(listContacts.size()-1).getFullName();
return users;
}
/**
* Separate full name to comma for portal login.
*
* @param listLogin the list login
* @return the string
*/
public static String separateFullNameToCommaForPortalLogin(List<String> listLogin){
String users = "";
logger.trace("SeparateFullNameToCommaForPortalLogin converting: "+listLogin);
//N-1 MEMBERS
for (int i = 0; i < listLogin.size()-1; i++) {
// logger.trace("Converting: "+i+") "+listLogin.get(i));
users+= getUserFullName(listLogin.get(i)) + ", ";
}
//LAST MEMBER
if(listLogin.size()>=1){
// logger.trace("Converting: "+(listLogin.size()-1)+") " +listLogin.get(listLogin.size()-1));
users += getUserFullName(listLogin.get(listLogin.size()-1));
}
logger.trace("SeparateFullNameToCommaForPortalLogin returning: "+users);
return users;
}
}

View File

@ -0,0 +1,283 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.server.util;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.gcube.application.framework.core.session.ASLSession;
import org.gcube.application.framework.core.session.SessionManager;
import org.gcube.applicationsupportlayer.social.ApplicationNotificationsManager;
import org.gcube.applicationsupportlayer.social.NotificationsManager;
import org.gcube.common.homelibrary.home.HomeLibrary;
import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException;
import org.gcube.common.homelibrary.home.exceptions.InternalErrorException;
import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.custom.scopemanager.scopehelper.ScopeHelper;
import org.gcube.portlets.widgets.workspaceuploader.server.WorkspaceUploadServletStream;
import org.gcube.portlets.widgets.workspaceuploader.server.notification.NotificationsWorkspaceUploaderProducer;
import org.gcube.portlets.widgets.workspaceuploader.shared.WorkspaceUploaderItem;
import com.liferay.portal.service.UserLocalServiceUtil;
/**
* The Class WsUtil.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* @Feb 18, 2014
*/
public class WsUtil {
public static final String USERNAME_ATTRIBUTE = ScopeHelper.USERNAME_ATTRIBUTE;
public static final String NOTIFICATION_MANAGER = "WORKSPACE_UPLOADER_NOTIFICATION_MANAGER";
public static final String NOTIFICATION_PRODUCER = "WORKSPACE_UPLOADER_NOTIFICATION_PRODUCER";
public static final String NOTIFICATION_PORTLET_CLASS_ID = WorkspaceUploadServletStream.class.getName(); //IN DEV
public static final String TEST_SCOPE = "/gcube/devsec";
public static String TEST_USER = "test.user";
public static String TEST_USER_FULL_NAME = "Test User";
protected static Logger logger = Logger.getLogger(WsUtil.class);
// public static boolean withoutPortal = false;
/**
* 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) {
logger.trace("Development Mode ON");
return false;
}
}
/**
* Gets the asl session.
*
* @param httpSession the http session
* @return the asl session
*/
public static ASLSession getAslSession(HttpSession httpSession)
{
String sessionID = httpSession.getId();
String user = (String) httpSession.getAttribute(USERNAME_ATTRIBUTE);
ASLSession session;
if (user == null) {
/*USE ANOTHER ACCOUNT (OTHERWHISE BY TEST_USER) FOR RUNNING
* COMMENT THIS IN DEVELOP ENVIROMENT (UNCOMMENT IN PRODUCTION)*/
user=TEST_USER;
if (!isWithinPortal()) { //DEV MODE
user = "francesco.mangiacrapa";
TEST_USER_FULL_NAME = "Francesco Mangiacrapa";
}
logger.warn("WORKSPACE PORTLET STARTING IN TEST MODE - NO USER FOUND - PORTLETS STARTING WITH FOLLOWING SETTINGS:");
logger.warn("session id: "+sessionID);
logger.warn("TEST_USER: "+user);
logger.warn("TEST_SCOPE: "+TEST_SCOPE);
logger.warn("USERNAME_ATTRIBUTE: "+USERNAME_ATTRIBUTE);
session = SessionManager.getInstance().getASLSession(sessionID, user);
session.setScope(TEST_SCOPE);
//MANDATORY FOR SOCIAL LIBRARY
session.setUserAvatarId(user + "Avatar");
session.setUserFullName(TEST_USER_FULL_NAME);
session.setUserEmailAddress(user + "@mail.test");
//SET HTTP SESSION ATTRIBUTE
httpSession.setAttribute(USERNAME_ATTRIBUTE, user);
return session;
}
return SessionManager.getInstance().getASLSession(sessionID, user);
}
/**
* Checks if is session expired.
*
* @param httpSession the http session
* @return true if current username into ASL session is WsUtil.TEST_USER, false otherwise
* @throws Exception the exception
*/
public static boolean isSessionExpired(HttpSession httpSession) throws Exception {
logger.trace("workspace session validating...");
//READING USERNAME FROM ASL SESSION
String userUsername = getAslSession(httpSession).getUsername();
boolean isTestUser = userUsername.compareTo(WsUtil.TEST_USER)==0;
//TODO UNCOMMENT THIS FOR RELEASE
logger.trace("Is "+WsUtil.TEST_USER+" test user? "+isTestUser);
if(isTestUser){
logger.error("workspace session is expired! username is: "+WsUtil.TEST_USER);
return true; //is TEST_USER, session is expired
}
logger.trace("workspace session is valid! current username is: "+userUsername);
return false;
}
/**
* Gets the workspace.
*
* @param httpSession the http session
* @return the workspace
* @throws InternalErrorException the internal error exception
* @throws HomeNotFoundException the home not found exception
* @throws WorkspaceFolderNotFoundException the workspace folder not found exception
*/
public static Workspace getWorkspace(final HttpSession httpSession) throws InternalErrorException, HomeNotFoundException, WorkspaceFolderNotFoundException{
logger.trace("Get Workspace");
final ASLSession session = getAslSession(httpSession);
logger.trace("ASLSession scope: "+session.getScope() + " username: "+session.getUsername());
ScopeProvider.instance.set(session.getScope());
logger.trace("Scope provider instancied");
return HomeLibrary.getUserWorkspace(session.getUsername());
}
/**
* Gets the notification manager.
*
* @param session the session
* @return the notification manager
*/
public static NotificationsManager getNotificationManager(ASLSession session)
{
NotificationsManager notifMng = (NotificationsManager) session.getAttribute(NOTIFICATION_MANAGER);
if (notifMng == null) {
try{
logger.trace("Create new NotificationsManager for user: "+session.getUsername());
logger.trace("New ApplicationNotificationsManager with portlet class name: "+NOTIFICATION_PORTLET_CLASS_ID);
notifMng = new ApplicationNotificationsManager(session, NOTIFICATION_PORTLET_CLASS_ID);
session.setAttribute(NOTIFICATION_MANAGER, notifMng);
}catch (Exception e) {
logger.error("An error occurred instancing ApplicationNotificationsManager for user: "+session.getUsername(),e);
}
}
return notifMng;
}
/**
* Gets the notification producer.
*
* @param session the session
* @return the notification producer
*/
public static NotificationsWorkspaceUploaderProducer getNotificationProducer(ASLSession session)
{
NotificationsWorkspaceUploaderProducer notifProducer = (NotificationsWorkspaceUploaderProducer) session.getAttribute(NOTIFICATION_PRODUCER);
if (notifProducer == null) {
logger.trace("Create new Notification Producer for user: "+session.getUsername());
notifProducer = new NotificationsWorkspaceUploaderProducer(session);
session.setAttribute(NOTIFICATION_PRODUCER, notifProducer);
}
return notifProducer;
}
/**
* Put workspace uploader in session.
*
* @param httpSession the http session
* @param uploader the uploader
* @throws Exception the exception
*/
public static void putWorkspaceUploaderInSession(final HttpSession httpSession, WorkspaceUploaderItem uploader) throws Exception
{
logger.trace("Get Workspace");
final ASLSession session = getAslSession(httpSession);
if(uploader.getIdentifier()==null || uploader.getIdentifier().isEmpty())
throw new Exception("Invalid uploader");
logger.debug("Adding uploader: "+uploader.getIdentifier() +" in session");
session.setAttribute(uploader.getIdentifier(), uploader);
}
/**
* Gets the workspace uploader in session.
*
* @param httpSession the http session
* @param uploaderIdentifier the uploader identifier
* @return the workspace uploader in session
* @throws Exception the exception
*/
public static WorkspaceUploaderItem getWorkspaceUploaderInSession(final HttpSession httpSession, String uploaderIdentifier) throws Exception
{
final ASLSession session = getAslSession(httpSession);
if(uploaderIdentifier==null || uploaderIdentifier.isEmpty())
throw new Exception("Invalid uploader");
return (WorkspaceUploaderItem) session.getAttribute(uploaderIdentifier);
}
/**
* Erase workspace uploader in session.
*
* @param httpSession the http session
* @param uploaderIdentifier the uploader identifier
* @return true, if successful
* @throws Exception the exception
*/
public static boolean eraseWorkspaceUploaderInSession(final HttpSession httpSession, String uploaderIdentifier) throws Exception
{
WorkspaceUploaderItem uploader = getWorkspaceUploaderInSession(httpSession, uploaderIdentifier);
if(uploader!=null){
logger.debug("Erased uploader: "+uploader.getIdentifier() +" in session");
uploader = null;
putWorkspaceUploaderInSession(httpSession, uploader);
return true;
}
logger.debug("Uploader not found, skipping erase from session");
return false;
}
/**
* Gets the user id.
*
* @param httpSession the http session
* @return the user id
*/
public static String getUserId(HttpSession httpSession) {
ASLSession session = getAslSession(httpSession);
return session.getUsername();
}
}

View File

@ -0,0 +1,159 @@
package org.gcube.portlets.widgets.workspaceuploader.shared;
import java.io.Serializable;
import java.util.Comparator;
/**
* The Class ContactModel.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 3, 2015
*/
public class ContactModel implements Serializable {
/**
*
*/
private static final long serialVersionUID = 3715519940338008890L;
private String id;
private String login;
private boolean isGroup;
private String fullName;
/**
* Instantiates a new info contact model.
*/
public ContactModel() {}
/**
* Instantiates a new info contact model.
*
* @param id the id
* @param login the login
* @param isGroup the is group
* @param fullName the full name
*/
public ContactModel(String id, String login, boolean isGroup, String fullName) {
super();
this.id = id;
this.login = login;
this.isGroup = isGroup;
this.fullName = fullName;
}
/**
* Gets the id.
*
* @return the id
*/
public String getId() {
return id;
}
/**
* Gets the login.
*
* @return the login
*/
public String getLogin() {
return login;
}
/**
* Checks if is group.
*
* @return the isGroup
*/
public boolean isGroup() {
return isGroup;
}
/**
* Gets the full name.
*
* @return the fullName
*/
public String getFullName() {
return fullName;
}
/**
* Sets the id.
*
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* Sets the login.
*
* @param login the login to set
*/
public void setLogin(String login) {
this.login = login;
}
/**
* Sets the group.
*
* @param isGroup the isGroup to set
*/
public void setGroup(boolean isGroup) {
this.isGroup = isGroup;
}
/**
* Sets the full name.
*
* @param fullName the fullName to set
*/
public void setFullName(String fullName) {
this.fullName = fullName;
}
public static Comparator<ContactModel> COMPARATORFULLNAME = new Comparator<ContactModel>() {
// This is where the sorting happens.
public int compare(ContactModel o1, ContactModel o2) {
if(o1==null)
return -1;
if(o2==null)
return 1;
return o1.getFullName().compareToIgnoreCase(o2.getFullName());
}
};
public static Comparator<ContactModel> COMPARATORLOGINS = new Comparator<ContactModel>() {
// This is where the sorting happens.
public int compare(ContactModel o1, ContactModel o2) {
if(o1==null)
return -1;
if(o2==null)
return 1;
return o1.getLogin().compareToIgnoreCase(o2.getLogin());
}
};
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("InfoContactModel [id=");
builder.append(id);
builder.append(", login=");
builder.append(login);
builder.append(", isGroup=");
builder.append(isGroup);
builder.append(", fullName=");
builder.append(fullName);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,42 @@
package org.gcube.portlets.widgets.workspaceuploader.shared;
/**
* <p>
* FieldVerifier validates that the name the user enters is valid.
* </p>
* <p>
* This class is in the <code>shared</code> packing because we use it in both
* the client code and on the server. On the client, we verify that the name is
* valid before sending an RPC request so the user doesn't have to wait for a
* network round trip to get feedback. On the server, we verify that the name is
* correct to ensure that the input is correct regardless of where the RPC
* originates.
* </p>
* <p>
* When creating a class that is used on both the client and the server, be sure
* that all code is translatable and does not use native JavaScript. Code that
* is note translatable (such as code that interacts with a database or the file
* system) cannot be compiled into client side JavaScript. Code that uses native
* JavaScript (such as Widgets) cannot be run on the server.
* </p>
*/
public class FieldVerifier {
/**
* Verifies that the specified name is valid for our service.
*
* In this example, we only require that the name is at least four
* characters. In your application, you can use more complex checks to ensure
* that usernames, passwords, email addresses, URLs, and other fields have the
* proper syntax.
*
* @param name the name to validate
* @return true if valid, false if invalid
*/
public static boolean isValidName(String name) {
if (name == null) {
return false;
}
return name.length() > 3;
}
}

View File

@ -0,0 +1,154 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.shared;
import java.io.Serializable;
/**
* The Class HandlerResultMessage.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 3, 2015
*/
public class HandlerResultMessage implements Serializable{
/**
*
*/
private static final long serialVersionUID = -4607236625671465107L;
/**
* The Enum Status.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 3, 2015
*/
public enum Status {
/**
* If an error occurs.
*/
ERROR,
/**
* If no error occurs.
*/
OK,
/**
* If there was some problems.
*/
WARN,
/**
* If the result is unknown.
*/
UNKNOWN;
}
/**
* Error result.
*
* @param message the message
* @return the handler result message
*/
public static HandlerResultMessage errorResult(String message){
return new HandlerResultMessage(Status.ERROR, message);
}
/**
* Ok result.
*
* @param message the message
* @return the handler result message
*/
public static HandlerResultMessage okResult(String message){
return new HandlerResultMessage(Status.OK, message);
}
/**
* Warn result.
*
* @param message the message
* @return the handler result message
*/
public static HandlerResultMessage warnResult(String message){
return new HandlerResultMessage(Status.WARN, message);
}
/**
* Parses the result.
*
* @param result the result
* @return the handler result message
*/
public static HandlerResultMessage parseResult(String result){
//expected 200:Upload complete
String statusToken = null;
String messageToken = null;
int index = result.indexOf(':');
if (index>0){
statusToken = result.substring(0,index);
if (index<result.length()){
messageToken = result.substring(index+1);
}
}
Status status = Status.UNKNOWN;
if (statusToken!=null){
status = Status.valueOf(statusToken);
}
String message = (messageToken!=null)?messageToken:"";
return new HandlerResultMessage(status, message);
}
protected Status status;
protected String message;
/**
* Create a new result message.
* @param status the status.
* @param message the message.
*/
public HandlerResultMessage(Status status, String message) {
this.status = status;
this.message = message;
}
/**
* Gets the status.
*
* @return the status
*/
public Status getStatus() {
return status;
}
/**
* Gets the message.
*
* @return the message
*/
public String getMessage() {
return message;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(status);
builder.append(":");
builder.append(message);
return builder.toString();
}
}

View File

@ -0,0 +1,87 @@
package org.gcube.portlets.widgets.workspaceuploader.shared;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.gcube.portlets.widgets.workspaceuploader.shared.event.UploadEvent;
/**
* The Class UploadProgress.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 1, 2015
*/
public final class UploadProgress implements Serializable{
/**
*
*/
private static final long serialVersionUID = -2797791973584424842L;
private List<UploadEvent> events = new ArrayList<UploadEvent>();
/**
* Instantiates a new upload progress.
*/
public UploadProgress() {
}
/**
* Gets the events.
*
* @return the events
*/
public List<UploadEvent> getEvents() {
return events;
}
/**
* Adds the.
*
* @param event the event
*/
public void add(final UploadEvent event) {
events.add(event);
}
/**
* Gets the last event.
*
* @return the last event
*/
public UploadEvent getLastEvent(){
if(isEmpty())
return null;
return events.get(events.size()-1);
}
/**
* Clear.
*/
public void clear() {
events = new ArrayList<UploadEvent>();
}
/**
* Checks if is empty.
*
* @return true, if is empty
*/
public boolean isEmpty() {
return events.isEmpty();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("UploadProgress [events=");
builder.append(events);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,96 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.shared;
import java.io.Serializable;
/**
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 3, 2015
*/
public class WorkspaceUploadFile implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1513046515926364747L;
private String parentId;
private String fileName;
/**
*
*/
public WorkspaceUploadFile() {
}
/**
* @param parentId
* @param fileName
*/
public WorkspaceUploadFile(String parentId, String fileName) {
super();
this.parentId = parentId;
this.fileName = fileName;
}
/**
* @return the parentId
*/
public String getParentId() {
return parentId;
}
/**
* @return the fileName
*/
public String getFileName() {
return fileName;
}
/**
* @param parentId the parentId to set
*/
public void setParentId(String parentId) {
this.parentId = parentId;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
int hash = 31;
hash = hash * 13 + (parentId == null ? 0 : parentId.hashCode());
hash = hash * 17 + (fileName == null ? 0 : fileName.hashCode());
return hash;
}
/**
* @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("WorkspaceUploadFile [parentId=");
builder.append(parentId);
builder.append(", fileName=");
builder.append(fileName);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,229 @@
/**
*
*/
package org.gcube.portlets.widgets.workspaceuploader.shared;
import java.io.Serializable;
/**
* The Class WorkspaceUploaderItem.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 3, 2015
*/
public class WorkspaceUploaderItem implements Serializable{
/**
*
*/
private static final long serialVersionUID = -7657531873615480050L;
/**
* The Enum UPLOAD_STATUS.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 6, 2015
*/
public static enum UPLOAD_STATUS{
WAIT("WAIT", "wait"),
IN_PROGRESS("IN_PROGRESS", "in progress"),
FAILED("FAILED", "failed"),
ABORTED("ABORTED", "aborted"),
COMPLETED("COMPLETED", "completed");
protected String id;
protected String label;
/**
* Instantiates a new upload status.
*
* @param id the id
* @param label the label
*/
private UPLOAD_STATUS(String id, String label) {
this.id = id;
this.label = label;
}
}
private String identifier;
private WorkspaceUploadFile file;
private UPLOAD_STATUS uploadStatus;
private String statusDescription;
private String clientUploadKey;
private UploadProgress uploadProgress;
// private Long threadId;
/**
* Instantiates a new workspace uploader item.
*/
public WorkspaceUploaderItem() {
}
/**
* Instantiates a new workspace uploader item.
*
* @param identifier the identifier
*/
public WorkspaceUploaderItem(String identifier) {
this.identifier = identifier;
}
/**
* Instantiates a new workspace uploader item.
*
* @param identifier the identifier
* @param file the file
* @param status the status
* @param statusDescription the status description
*/
public WorkspaceUploaderItem(String identifier, WorkspaceUploadFile file, UPLOAD_STATUS status, String statusDescription, UploadProgress uploadProgress) {
super();
this.identifier = identifier;
this.file = file;
this.uploadStatus = status;
this.statusDescription = statusDescription;
this.uploadProgress = uploadProgress;
}
/**
* Gets the identifier.
*
* @return the identifier
*/
public String getIdentifier() {
return identifier;
}
/**
* Gets the status description.
*
* @return the statusDescription
*/
public String getStatusDescription() {
return statusDescription;
}
/**
* Sets the status description.
*
* @param statusDescription the statusDescription to set
*/
public void setStatusDescription(String statusDescription) {
this.statusDescription = statusDescription;
}
/**
* Gets the file.
*
* @return the file
*/
public WorkspaceUploadFile getFile() {
return file;
}
/**
* Gets the upload status.
*
* @return the uploadStatus
*/
public UPLOAD_STATUS getUploadStatus() {
return uploadStatus;
}
/**
* Sets the file.
*
* @param file the file to set
*/
public void setFile(WorkspaceUploadFile file) {
this.file = file;
}
/**
* Sets the upload status.
*
* @param uploadStatus the uploadStatus to set
*/
public void setUploadStatus(UPLOAD_STATUS uploadStatus) {
this.uploadStatus = uploadStatus;
}
/**
* Gets the client upload key.
*
* @return the clientUploadKey
*/
public String getClientUploadKey() {
return clientUploadKey;
}
/**
* Sets the client upload key.
*
* @param clientUploadKey the clientUploadKey to set
*/
public void setClientUploadKey(String clientUploadKey) {
this.clientUploadKey = clientUploadKey;
}
/**
* @return the uploadProgress
*/
public UploadProgress getUploadProgress() {
return uploadProgress;
}
/**
* @param uploadProgress the uploadProgress to set
*/
public void setUploadProgress(UploadProgress uploadProgress) {
this.uploadProgress = uploadProgress;
}
// /**
// * @param id
// */
// public void setThreadId(Long id) {
// this.threadId = id;
// }
//
// /**
// * @return the threadId
// */
// public Long getThreadId() {
// return threadId;
// }
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("WorkspaceUploaderItem [identifier=");
builder.append(identifier);
builder.append(", file=");
builder.append(file);
builder.append(", uploadStatus=");
builder.append(uploadStatus);
builder.append(", statusDescription=");
builder.append(statusDescription);
builder.append(", clientUploadKey=");
builder.append(clientUploadKey);
builder.append(", uploadProgress=");
builder.append(uploadProgress);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,40 @@
package org.gcube.portlets.widgets.workspaceuploader.shared.event;
/**
* The Interface UploadEvent.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Sep 1, 2015
*/
public interface UploadEvent {
/**
* Gets the read percentage.
*
* @return the read percentage
*/
Integer getReadPercentage();
/**
* Sets the read percentage.
*
* @param percentage the new read percentage
*/
void setReadPercentage(Integer percentage);
/**
* Sets the read time. (in millisecond)
*
* the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
*
* @param time the new read time
*/
void setReadTime(long time);
/**
* Gets the read time (in millisecond)
*
* @return the read time
*/
long getReadTime();
}

View File

@ -0,0 +1,71 @@
package org.gcube.portlets.widgets.workspaceuploader.shared.event;
import java.io.Serializable;
/**
* The Class UploadProgressChangeEvent.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 1, 2015
*/
public final class UploadProgressChangeEvent implements UploadEvent, Serializable {
/**
*
*/
private static final long serialVersionUID = -3445585716145899197L;
private Integer readPercentage = -1;
private long readTime = 0;
/**
* Instantiates a new upload progress change event.
*/
public UploadProgressChangeEvent() {
}
/* (non-Javadoc)
* @see org.gcube.portlets.widgets.workspaceuploader.shared.event.UploadEvent#getReadPercentage()
*/
public Integer getReadPercentage() {
return readPercentage;
}
/* (non-Javadoc)
* @see org.gcube.portlets.widgets.workspaceuploader.shared.event.UploadEvent#setReadPercentage(java.lang.Integer)
*/
public void setReadPercentage(Integer percentage) {
this.readPercentage = percentage;
}
/* (non-Javadoc)
* @see org.gcube.portlets.widgets.workspaceuploader.shared.event.UploadEvent#setReadTime(long)
*/
@Override
public void setReadTime(long time) {
this.readTime = time;
}
/* (non-Javadoc)
* @see org.gcube.portlets.widgets.workspaceuploader.shared.event.UploadEvent#getReadTime()
*/
@Override
public long getReadTime() {
return readTime;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("UploadProgressChangeEvent [readPercentage=");
builder.append(readPercentage);
builder.append(", readTime=");
builder.append(readTime);
builder.append("]");
return builder.toString();
}
}

View File

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

View File

@ -0,0 +1,18 @@
<%@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"%>
<portlet:defineObjects />
--%>
<link rel="stylesheet"
href="<%=request.getContextPath()%>/workspaceuploader.css"
type="text/css">
<script type="text/javascript" language="javascript"
src="<%=request.getContextPath()%>/workspaceuploader/workspaceuploader.nocache.js"></script>
<div id="workspace-uploader"></div>

View File

@ -0,0 +1,5 @@
<display>
<category name="gCube Applications">
<portlet id="WorkspaceUploader" />
</category>
</display>

View File

@ -0,0 +1,9 @@
name=WorkspaceUploader
module-group-id=liferay
module-incremental-version=2
tags=
short-description=
change-log=
page-url=http://www.gcube-system.org
author=gCube
licenses=EUPL

View File

@ -0,0 +1,11 @@
<?xml version="1.0"?>
<!DOCTYPE liferay-portlet-app PUBLIC "-//Liferay//DTD Portlet Application 5.2.0//EN" "http://www.liferay.com/dtd/liferay-portlet-app_5_2_0.dtd">
<liferay-portlet-app>
<portlet>
<portlet-name>WorkspaceUploader</portlet-name>
<layout-cacheable>false</layout-cacheable>
<instanceable>false</instanceable>
<ajaxable>false</ajaxable>
</portlet>
</liferay-portlet-app>

View File

@ -0,0 +1,18 @@
<?xml version='1.0' encoding='UTF-8' ?>
<portlet-app>
<portlet>
<description>Workspace Uploader</description>
<portlet-name>WorkspaceUploader</portlet-name>
<display-name>Workspace Uploader Portlet</display-name>
<portlet-class>org.gcube.portlets.widgets.workspaceuploader.portlet.WorkspaceUploaderPortlet</portlet-class>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>VIEW</portlet-mode>
</supports>
<portlet-info>
<title>WorkspaceUploader</title>
<short-title>WorkspaceUploader</short-title>
</portlet-info>
</portlet>
</portlet-app>

View File

@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<!-- Servlets -->
<servlet>
<servlet-name>workspaceUploaderService</servlet-name>
<servlet-class>org.gcube.portlets.widgets.workspaceuploader.server.WorkspaceUploaderServiceImpl</servlet-class>
</servlet>
<!-- Servlets -->
<servlet>
<servlet-name>workspaceUploadServlet</servlet-name>
<servlet-class>org.gcube.portlets.widgets.workspaceuploader.server.WorkspaceUploadServlet</servlet-class>
</servlet>
<!-- Servlets -->
<servlet>
<servlet-name>workspaceUploadServletStream</servlet-name>
<servlet-class>org.gcube.portlets.widgets.workspaceuploader.server.WorkspaceUploadServletStream</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>workspaceUploaderService</servlet-name>
<url-pattern>/workspaceuploader/workspaceUploaderService</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>workspaceUploadServlet</servlet-name>
<url-pattern>/workspaceuploader/workspaceUploadServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>workspaceUploadServletStream</servlet-name>
<url-pattern>/workspaceuploader/workspaceUploadServletStream</url-pattern>
</servlet-mapping>
<!-- Default page to serve -->
<welcome-file-list>
<welcome-file>workspaceuploader.html</welcome-file>
</welcome-file-list>
</web-app>

View File

@ -0,0 +1,34 @@
/** Add css rules here for your application. */
/** Example rules used by the template application (remove for your app) */
h1 {
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
.sendButton {
display: block;
font-size: 16pt;
}
/** 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;
}

View File

@ -0,0 +1,49 @@
<!doctype html>
<!-- The DOCTYPE declaration above will set the -->
<!-- browser's rendering engine into -->
<!-- "Standards Mode". Replacing this declaration -->
<!-- with a "Quirks Mode" doctype may lead to some -->
<!-- differences in layout. -->
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!-- -->
<!-- Consider inlining CSS to reduce the number of requested files -->
<!-- -->
<link type="text/css" rel="stylesheet" href="workspaceuploader.css">
<!-- -->
<!-- Any title is fine -->
<!-- -->
<title>Workspace Uploader</title>
<!-- -->
<!-- This script loads your compiled module. -->
<!-- If you add any GWT meta tags, they must -->
<!-- be added before this line. -->
<!-- -->
<script type="text/javascript" language="javascript" src="workspaceuploader/workspaceuploader.nocache.js"></script>
</head>
<!-- -->
<!-- The body can have arbitrary html, or -->
<!-- you can leave the body empty if you want -->
<!-- to create a completely dynamic UI. -->
<!-- -->
<body>
<!-- OPTIONAL: include this if you want history support -->
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
<!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
<noscript>
<div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
Your web browser must have JavaScript enabled
in order for this application to display correctly.
</div>
</noscript>
<div id="workspace-uploader"></div>
</body>
</html>