Merge pull request 'task_22890' (!1) from task_22890 into master

Reviewed-on: #1
This commit is contained in:
Francesco Mangiacrapa 2022-11-14 15:52:28 +01:00
commit 03412ae0a4
25 changed files with 1121 additions and 518 deletions

View File

@ -28,11 +28,5 @@
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/> <classpathentry kind="output" path="target/classes"/>
</classpath> </classpath>

View File

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

View File

@ -5,4 +5,5 @@
<installed facet="jst.web" version="2.3"/> <installed facet="jst.web" version="2.3"/>
<installed facet="com.gwtplugins.gwt.facet" version="1.0"/> <installed facet="com.gwtplugins.gwt.facet" version="1.0"/>
<installed facet="wst.jsdt.web" version="1.0"/> <installed facet="wst.jsdt.web" version="1.0"/>
<installed facet="jst.jaxrs" version="2.0"/>
</faceted-project> </faceted-project>

View File

@ -4,17 +4,30 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v2.0.0-SNAPSHOT] - 2022-11-14
#### Enhancements
- [#23188] Overloaded the method getProfilesInTheScope(forName)
- [#22890] Including the set/get currentValue for the "Update" facility
- [#23188] Advanced the MultipleDilaogUpload with a more complex object
- [#23544] Integrated with the fieldId added to gCube Metadata Profile
- [#24111] Added dependency required for building with JDK_11
- Moved to GWT 2.9
- Moved to maven-portal-bom 3.6.4
## [v1.0.1-SNAPSHOT] - 2020-10-08 ## [v1.0.1-SNAPSHOT] - 2020-10-08
#### Bug fixes #### Bug fixes
[#20446] Catalogue Publishing Widget: field value unexpectedly added in case of optional field - [#20446] Catalogue Publishing Widget: field value unexpectedly added in case of optional field
## [v1.0.0] - 2020-10-08 ## [v1.0.0] - 2020-10-08
#### First release #### First release
[#19884] Create widget to build a data-entry form by using metadata-profile-discovery - [#19884] Create widget to build a data-entry form by using metadata-profile-discovery
[#19878] Create a data entry facility to get (meta)data object defined by "gCube Metada Profile" - [#19878] Create a data entry facility to get (meta)data object defined by "gCube Metada Profile"

20
pom.xml
View File

@ -14,7 +14,7 @@
<groupId>org.gcube.portlets.widgets</groupId> <groupId>org.gcube.portlets.widgets</groupId>
<artifactId>metadata-profile-form-builder-widget</artifactId> <artifactId>metadata-profile-form-builder-widget</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<version>1.0.1-SNAPSHOT</version> <version>2.0.0-SNAPSHOT</version>
<name>Metadata Profile Form Builder</name> <name>Metadata Profile Form Builder</name>
<description> <description>
The Metadata Profile Form Builder is a widget able to build dynamically a web form by reading "gCube Metadata Profile/s" The Metadata Profile Form Builder is a widget able to build dynamically a web form by reading "gCube Metadata Profile/s"
@ -28,10 +28,10 @@
<properties> <properties>
<!-- Convenience property to set the GWT version --> <!-- Convenience property to set the GWT version -->
<gwtVersion>2.7.0</gwtVersion> <gwtVersion>2.9.0</gwtVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
</properties> </properties>
@ -53,7 +53,7 @@
<dependency> <dependency>
<groupId>org.gcube.distribution</groupId> <groupId>org.gcube.distribution</groupId>
<artifactId>maven-portal-bom</artifactId> <artifactId>maven-portal-bom</artifactId>
<version>3.6.0</version> <version>3.7.0-SNAPSHOT</version>
<type>pom</type> <type>pom</type>
<scope>import</scope> <scope>import</scope>
</dependency> </dependency>
@ -98,6 +98,18 @@
</dependency> </dependency>
<!-- END FWS --> <!-- END FWS -->
<!-- REQUIRED FOR JDK_11 -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
<scope>provided</scope>
</dependency>
<!-- END REQUIRED FOR JDK_11 -->
<!-- JSON PARSER --> <!-- JSON PARSER -->
<dependency> <dependency>
<groupId>org.json</groupId> <groupId>org.json</groupId>

View File

@ -10,6 +10,7 @@ public class ConstantsMPFormBuilder {
//public static final String CURR_USER_ID = "currUserId"; //public static final String CURR_USER_ID = "currUserId";
public static final String IS_OVERWRITE = "isOverwrite"; public static final String IS_OVERWRITE = "isOverwrite";
public static final String UPLOAD_TYPE = "uploadType"; public static final String UPLOAD_TYPE = "uploadType";
public static enum THE_UPLOAD_TYPE {File, Archive}; public static enum THE_UPLOAD_TYPE {File, Archive};
public static final String ID_FOLDER = "idFolder"; public static final String ID_FOLDER = "idFolder";
public static final String UPLOAD_FORM_ELEMENT = "uploadFormElement"; public static final String UPLOAD_FORM_ELEMENT = "uploadFormElement";
@ -17,6 +18,9 @@ public class ConstantsMPFormBuilder {
public static final String CLIENT_UPLOAD_KEYS = "client_upload_keys"; public static final String CLIENT_UPLOAD_KEYS = "client_upload_keys";
public static final String CANCEL_UPLOAD = "cancel_upload"; public static final String CANCEL_UPLOAD = "cancel_upload";
public static final String JSON_CLIENT_KEYS = "ClientKeys"; public static final String JSON_CLIENT_KEYS = "ClientKeys";
public static final String UPL_FILENAME = "filename";
public static final String UPL_CLIENT_KEY = "client_key";
public static final String UPL_FIELD_NAME_FILEPATH = "fieldname_filepath";
public static final int LIMIT_UPLOADS = 50; public static final int LIMIT_UPLOADS = 50;

View File

@ -8,7 +8,6 @@ import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploadingState
import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
// TODO: Auto-generated Javadoc
/** /**
* The client side stub for the RPC service. * The client side stub for the RPC service.
* *
@ -54,4 +53,15 @@ public interface MetadataProfileFormBuilderService extends RemoteService {
* @throws Exception the exception * @throws Exception the exception
*/ */
Integer purgeFilesUploaded() throws Exception; Integer purgeFilesUploaded() throws Exception;
/**
* Gets the profiles in the scope.
*
* @param scope the scope
* @param genericResourceSecondaryType the generic resource secondary type
* @param resourceName the resource name
* @return the profiles in the scope
* @throws Exception the exception
*/
List<MetaDataProfileBean> getProfilesInTheScopeForName(String scope,String genericResourceSecondaryType, String resourceName) throws Exception;
} }

View File

@ -42,4 +42,7 @@ public interface MetadataProfileFormBuilderServiceAsync {
void getUploadStatus(String clientUploadKey, AsyncCallback<FileUploadingState> asyncCallback); void getUploadStatus(String clientUploadKey, AsyncCallback<FileUploadingState> asyncCallback);
void purgeFilesUploaded(AsyncCallback<Integer> callback); void purgeFilesUploaded(AsyncCallback<Integer> callback);
void getProfilesInTheScopeForName(String scope, String genericResourceSecondaryType, String resourceName,
AsyncCallback<List<MetaDataProfileBean>> callback);
} }

View File

@ -3,6 +3,7 @@ package org.gcube.portlets.widgets.mpformbuilder.client.form;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.gcube.portlets.widgets.mpformbuilder.client.form.generic.CreateMetadataForm.OPERATION;
import org.gcube.portlets.widgets.mpformbuilder.client.ui.metadata.MetaDataFieldSkeleton; import org.gcube.portlets.widgets.mpformbuilder.client.ui.metadata.MetaDataFieldSkeleton;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetadataFieldWrapper; import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetadataFieldWrapper;
@ -34,8 +35,6 @@ public class MetaDataField extends Composite {
@UiField VerticalPanel panelMetaDataFieldsSkeleton; @UiField VerticalPanel panelMetaDataFieldsSkeleton;
@UiField Label repeatabilityLabel; @UiField Label repeatabilityLabel;
//@UiField ControlGroup cgMetaDataFieldSkeletonFields;
@UiField Button addFieldButton; @UiField Button addFieldButton;
@ -47,6 +46,8 @@ public class MetaDataField extends Composite {
private HandlerManager eventBus; private HandlerManager eventBus;
private OPERATION operation;
/** /**
* The Interface MetaDataFieldUiBinder. * The Interface MetaDataFieldUiBinder.
* *
@ -65,10 +66,11 @@ public class MetaDataField extends Composite {
* @param eventBus the event bus * @param eventBus the event bus
* @throws Exception the exception * @throws Exception the exception
*/ */
public MetaDataField(final MetadataFieldWrapper field, HandlerManager eventBus) throws Exception { public MetaDataField(final MetadataFieldWrapper field, HandlerManager eventBus, OPERATION operation) throws Exception {
initWidget(uiBinder.createAndBindUi(this)); initWidget(uiBinder.createAndBindUi(this));
this.fieldWrapper = field; this.fieldWrapper = field;
this.eventBus = eventBus; this.eventBus = eventBus;
this.operation = operation;
addNewOccurrenceOfField(); addNewOccurrenceOfField();
checkAllowedAddField(); checkAllowedAddField();
checkAllowedRemoveField(); checkAllowedRemoveField();
@ -143,7 +145,7 @@ public class MetaDataField extends Composite {
*/ */
private void addNewOccurrenceOfField() { private void addNewOccurrenceOfField() {
try { try {
MetaDataFieldSkeleton fieldWidget = new MetaDataFieldSkeleton(fieldWrapper, eventBus); MetaDataFieldSkeleton fieldWidget = new MetaDataFieldSkeleton(fieldWrapper, eventBus, operation);
listOfMetadataFields.add(fieldWidget); listOfMetadataFields.add(fieldWidget);
panelMetaDataFieldsSkeleton.add(fieldWidget); panelMetaDataFieldsSkeleton.add(fieldWidget);
} catch (Exception e) { } catch (Exception e) {

View File

@ -4,20 +4,20 @@
xmlns:m="urn:import:org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.tags"> xmlns:m="urn:import:org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.tags">
<ui:style> <ui:style>
.form-main-style { .form-main-style {
margin-left: 10px; margin-left: 10px !important;
} }
.fieldset-border-style { .fieldset-border-style {
border: 1px groove #444; border: 1px groove #444 !important;
-webkit-box-shadow: 0px 0px 0px 0px #000; -webkit-box-shadow: 0px 0px 0px 0px #000;
box-shadow: 0px 0px 0px 0px #000; box-shadow: 0px 0px 0px 0px #000 !important;
padding: 10px; padding: 10px !important;
} }
.legend-style { .legend-style {
width: auto; width: auto !important;
padding: 10px; padding: 10px !important;
margin-bottom: 0px; margin-bottom: 0px !important;
} }
@external .form-horizontal .input-large; @external .form-horizontal .input-large;

View File

@ -2,6 +2,7 @@ package org.gcube.portlets.widgets.mpformbuilder.client.form.generic;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -61,7 +62,7 @@ import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget; import com.google.gwt.user.client.ui.Widget;
// TODO: Auto-generated Javadoc
/** /**
* Create metadata form for ckan product. * Create metadata form for ckan product.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
@ -238,6 +239,10 @@ public class CreateMetadataForm extends Composite implements HasGenericFormListe
/** The form data bean. */ /** The form data bean. */
private GenericDatasetBean formDataBean; private GenericDatasetBean formDataBean;
private OPERATION operationPerfom;
public enum OPERATION {NEW, UPDATE}
/** /**
* Invoked in the most general case. * Invoked in the most general case.
* *
@ -271,8 +276,9 @@ public class CreateMetadataForm extends Composite implements HasGenericFormListe
* *
* @param profiles the profiles * @param profiles the profiles
*/ */
public CreateMetadataForm(List<MetaDataProfileBean> profiles, HandlerManager eventBus) { public CreateMetadataForm(List<MetaDataProfileBean> profiles, HandlerManager eventBus, OPERATION operation) {
this(eventBus); this(eventBus);
this.operationPerfom = operation;
showLoadingProfiles(true); showLoadingProfiles(true);
createDatasetFormBody(profiles); createDatasetFormBody(profiles);
showLoadingProfiles(false); showLoadingProfiles(false);
@ -302,7 +308,8 @@ public class CreateMetadataForm extends Composite implements HasGenericFormListe
showChooseProfileForm(false); showChooseProfileForm(false);
showCustomFieldsEntries(false); showCustomFieldsEntries(false);
} }
/** /**
* Show loading profiles. * Show loading profiles.
* *
@ -464,7 +471,7 @@ public class CreateMetadataForm extends Composite implements HasGenericFormListe
MetaDataField fieldWidget; MetaDataField fieldWidget;
try { try {
fieldWidget = new MetaDataField(field, uiBus); fieldWidget = new MetaDataField(field, uiBus, operationPerfom);
metadataFieldsPanel.add(fieldWidget); metadataFieldsPanel.add(fieldWidget);
listOfMetadataFields.add(fieldWidget); listOfMetadataFields.add(fieldWidget);
} catch (Exception e) { } catch (Exception e) {
@ -493,7 +500,7 @@ public class CreateMetadataForm extends Composite implements HasGenericFormListe
MetaDataField fieldWidget; MetaDataField fieldWidget;
try { try {
fieldWidget = new MetaDataField(metadataFieldWrapper, uiBus); fieldWidget = new MetaDataField(metadataFieldWrapper, uiBus,operationPerfom);
cp.addField(fieldWidget); cp.addField(fieldWidget);
listOfMetadataFields.add(fieldWidget); listOfMetadataFields.add(fieldWidget);
} catch (Exception e) { } catch (Exception e) {
@ -519,7 +526,7 @@ public class CreateMetadataForm extends Composite implements HasGenericFormListe
MetaDataField fieldWidget; MetaDataField fieldWidget;
try { try {
fieldWidget = new MetaDataField(field, uiBus); fieldWidget = new MetaDataField(field, uiBus, operationPerfom);
extrasCategory.addField(fieldWidget); extrasCategory.addField(fieldWidget);
listOfMetadataFields.add(fieldWidget); listOfMetadataFields.add(fieldWidget);
} catch (Exception e) { } catch (Exception e) {
@ -567,7 +574,7 @@ public class CreateMetadataForm extends Composite implements HasGenericFormListe
//Set<String> tags = new HashSet<String>(tagsPanel.getTags()); //Set<String> tags = new HashSet<String>(tagsPanel.getTags());
List<OrganizationBean> groups = new ArrayList<OrganizationBean>(); List<OrganizationBean> groups = new ArrayList<OrganizationBean>();
List<OrganizationBean> groupsToForceCreation = new ArrayList<OrganizationBean>(); List<OrganizationBean> groupsToForceCreation = new ArrayList<OrganizationBean>();
Map<String, List<String>> customFieldsMap = new HashMap<String, List<String>>(); LinkedHashMap<String, List<String>> customFieldsMap = new LinkedHashMap<String, List<String>>();
List<FileUploaded> listFilesUploaded = new ArrayList<FileUploaded>(); List<FileUploaded> listFilesUploaded = new ArrayList<FileUploaded>();
// prepare custom fields // prepare custom fields

View File

@ -5,6 +5,7 @@ import java.util.List;
import org.gcube.portlets.widgets.mpformbuilder.client.events.CloseCreationFormEvent; import org.gcube.portlets.widgets.mpformbuilder.client.events.CloseCreationFormEvent;
import org.gcube.portlets.widgets.mpformbuilder.client.events.CloseCreationFormEventHandler; import org.gcube.portlets.widgets.mpformbuilder.client.events.CloseCreationFormEventHandler;
import org.gcube.portlets.widgets.mpformbuilder.client.form.generic.CreateMetadataForm.OPERATION;
import org.gcube.portlets.widgets.mpformbuilder.client.openlayerwidget.GeoJsonAreaSelectionDialog; import org.gcube.portlets.widgets.mpformbuilder.client.openlayerwidget.GeoJsonAreaSelectionDialog;
import org.gcube.portlets.widgets.mpformbuilder.client.ui.timeandranges.DataTimeBox; import org.gcube.portlets.widgets.mpformbuilder.client.ui.timeandranges.DataTimeBox;
import org.gcube.portlets.widgets.mpformbuilder.client.ui.upload.DialogUpload; import org.gcube.portlets.widgets.mpformbuilder.client.ui.upload.DialogUpload;
@ -118,10 +119,11 @@ public class MetaDataFieldSkeleton extends Composite {
// time range separator // time range separator
public static final String RANGE_SEPARATOR = ","; public static final String RANGE_SEPARATOR = ",";
private static final String TOOLTIP_MULTISELECTION = "Hold down the Control (CTRL) or Command (CMD) button to select multiple options"; private static final String TOOLTIP_MULTISELECTION = "Hold down the Control (CTRL) or Command (CMD) button to select multiple options";
private static final String UPLOAD_MISSING_FILE = "You must upload a file"; private static final String UPLOAD_MISSING_FILE = "You must upload a file";
public MetaDataFieldSkeleton(final MetadataFieldWrapper field, HandlerManager eventBus) throws Exception { public MetaDataFieldSkeleton(final MetadataFieldWrapper field, HandlerManager eventBus, OPERATION operation)
throws Exception {
initWidget(uiBinder.createAndBindUi(this)); initWidget(uiBinder.createAndBindUi(this));
// prepare information // prepare information
@ -133,6 +135,9 @@ public class MetaDataFieldSkeleton extends Composite {
// bind // bind
bind(); bind();
if (operation == null)
operation = OPERATION.NEW;
switch (field.getType()) { switch (field.getType()) {
case Boolean: case Boolean:
@ -141,6 +146,16 @@ public class MetaDataFieldSkeleton extends Composite {
holder = new CheckBox(); holder = new CheckBox();
if (field.getDefaultValue() != null) if (field.getDefaultValue() != null)
((CheckBox) holder).setValue(Boolean.valueOf(field.getDefaultValue())); ((CheckBox) holder).setValue(Boolean.valueOf(field.getDefaultValue()));
if (operation.equals(OPERATION.UPDATE)) {
try {
if (field.getCurrentValue() != null)
((CheckBox) holder).setValue(Boolean.valueOf(field.getDefaultValue()));
} catch (Exception e) {
// TODO: handle exception
}
}
break; break;
case GeoJSON: case GeoJSON:
@ -154,6 +169,15 @@ public class MetaDataFieldSkeleton extends Composite {
if (field.getDefaultValue() != null) if (field.getDefaultValue() != null)
textArea.setText(field.getDefaultValue()); textArea.setText(field.getDefaultValue());
if (operation.equals(OPERATION.UPDATE)) {
try {
if (field.getCurrentValue() != null)
textArea.setText((String) field.getCurrentValue());
} catch (Exception e) {
// TODO: handle exception
}
}
containerGeoJSON.add(textArea); containerGeoJSON.add(textArea);
HorizontalPanel hp = new HorizontalPanel(); HorizontalPanel hp = new HorizontalPanel();
@ -216,6 +240,16 @@ public class MetaDataFieldSkeleton extends Composite {
if (field.getDefaultValue() != null) if (field.getDefaultValue() != null)
((TextArea) holder).setText(field.getDefaultValue()); ((TextArea) holder).setText(field.getDefaultValue());
if (operation.equals(OPERATION.UPDATE)) {
try {
if (field.getCurrentValue() != null)
((TextArea) holder).setText((String) field.getCurrentValue());
} catch (Exception e) {
// TODO: handle exception
}
}
break; break;
case Time: case Time:
@ -230,6 +264,22 @@ public class MetaDataFieldSkeleton extends Composite {
ref.setStartDate(dateAndTime[0], dateAndTime.length > 1 ? dateAndTime[1] : null); ref.setStartDate(dateAndTime[0], dateAndTime.length > 1 ? dateAndTime[1] : null);
} }
} }
if (operation.equals(OPERATION.UPDATE)) {
// set time, if present
try {
if (field.getCurrentValue() != null) {
String currentValue = (String) field.getCurrentValue();
String[] dateAndTime = currentValue.split(" ");
if (dateAndTime.length > 0) {
ref.setStartDate(dateAndTime[0], dateAndTime.length > 1 ? dateAndTime[1] : null);
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
break; break;
case Time_Interval: case Time_Interval:
@ -237,6 +287,15 @@ public class MetaDataFieldSkeleton extends Composite {
DataTimeBox rangeBox; DataTimeBox rangeBox;
holder = rangeBox = new DataTimeBox(true); holder = rangeBox = new DataTimeBox(true);
setRangeTimeInTimeBox(field.getDefaultValue(), rangeBox); setRangeTimeInTimeBox(field.getDefaultValue(), rangeBox);
if (operation.equals(OPERATION.UPDATE)) {
// set time, if present
try {
setRangeTimeInTimeBox((String) field.getCurrentValue(), rangeBox);
} catch (Exception e) {
// TODO: handle exception
}
}
rangesList.add(rangeBox); rangesList.add(rangeBox);
break; break;
@ -251,6 +310,15 @@ public class MetaDataFieldSkeleton extends Composite {
SimplePanel panelFirstRange = new SimplePanel(); SimplePanel panelFirstRange = new SimplePanel();
DataTimeBox rangeBoxFirst = new DataTimeBox(true); DataTimeBox rangeBoxFirst = new DataTimeBox(true);
setRangeTimeInTimeBox(field.getDefaultValue(), rangeBoxFirst); setRangeTimeInTimeBox(field.getDefaultValue(), rangeBoxFirst);
if (operation.equals(OPERATION.UPDATE)) {
try {
setRangeTimeInTimeBox((String) field.getCurrentValue(), rangeBoxFirst);
} catch (Exception e) {
// TODO: handle exception
}
}
panelFirstRange.add(rangeBoxFirst); panelFirstRange.add(rangeBoxFirst);
rangesList.add(rangeBoxFirst); rangesList.add(rangeBoxFirst);
@ -303,11 +371,20 @@ public class MetaDataFieldSkeleton extends Composite {
if (field.getDefaultValue() != null) if (field.getDefaultValue() != null)
((TextBox) holder).setText(field.getDefaultValue()); ((TextBox) holder).setText(field.getDefaultValue());
if (operation.equals(OPERATION.UPDATE)) {
try {
if (field.getCurrentValue() != null)
((TextBox) holder).setText((String) field.getCurrentValue());
} catch (Exception e) {
// TODO: handle exception
}
}
break; break;
case File: case File:
holder = new MultipleDilaogUpload(); holder = new MultipleDilaogUpload(field.getFieldName());
break; break;
@ -322,6 +399,15 @@ public class MetaDataFieldSkeleton extends Composite {
if (field.getDefaultValue() != null) if (field.getDefaultValue() != null)
((TextBox) holder).setText(field.getDefaultValue()); ((TextBox) holder).setText(field.getDefaultValue());
if (operation.equals(OPERATION.UPDATE)) {
try {
if (field.getCurrentValue() != null)
((TextBox) holder).setText((String) field.getCurrentValue());
} catch (Exception e) {
// TODO: handle exception
}
}
} else { } else {
// listbox // listbox
@ -331,11 +417,13 @@ public class MetaDataFieldSkeleton extends Composite {
if (field.isMultiSelection()) if (field.isMultiSelection())
tempListBox.setTitle(TOOLTIP_MULTISELECTION); tempListBox.setTitle(TOOLTIP_MULTISELECTION);
// if it is not mandatory and not multi-selection, add a disabled option (placeholder) // if it is not mandatory and not multi-selection, add a disabled option
if(!field.getMandatory() && !field.isMultiSelection()){ // (placeholder)
if (!field.getMandatory() && !field.isMultiSelection()) {
tempListBox.addItem("Select " + field.getFieldName()); tempListBox.addItem("Select " + field.getFieldName());
tempListBox.setValue(0, ""); tempListBox.setValue(0, "");
tempListBox.getElement().getElementsByTagName("option").getItem(0).setAttribute("disabled", "disabled"); tempListBox.getElement().getElementsByTagName("option").getItem(0).setAttribute("disabled",
"disabled");
tempListBox.setSelectedValue("Select " + field.getFieldName()); tempListBox.setSelectedValue("Select " + field.getFieldName());
} }
@ -350,6 +438,15 @@ public class MetaDataFieldSkeleton extends Composite {
if (field.getDefaultValue() != null) if (field.getDefaultValue() != null)
tempListBox.setSelectedValue(field.getDefaultValue()); tempListBox.setSelectedValue(field.getDefaultValue());
if (operation.equals(OPERATION.UPDATE)) {
try {
if (field.getCurrentValue() != null)
tempListBox.setSelectedValue((String) field.getCurrentValue());
} catch (Exception e) {
// TODO: handle exception
}
}
} }
break; break;
@ -358,24 +455,22 @@ public class MetaDataFieldSkeleton extends Composite {
return; return;
} }
try { try {
ChangeHandler handler = new ChangeHandler() { ChangeHandler handler = new ChangeHandler() {
@Override @Override
public void onChange(ChangeEvent event) { public void onChange(ChangeEvent event) {
GWT.log("Fired is field value"); GWT.log("Fired is field value");
removeError(); removeError();
isFieldValueValid(); isFieldValueValid();
} }
}; };
holder.addDomHandler(handler, ChangeEvent.getType()); holder.addDomHandler(handler, ChangeEvent.getType());
}catch (Exception e) { } catch (Exception e) {
// TODO: handle exception // TODO: handle exception
} }
// add custom css properties // add custom css properties
controls.addStyleName("form-controls-custom"); controls.addStyleName("form-controls-custom");
@ -421,8 +516,7 @@ public class MetaDataFieldSkeleton extends Composite {
}); });
} }
/** /**
* Gets the holder. * Gets the holder.
* *
@ -631,22 +725,24 @@ public class MetaDataFieldSkeleton extends Composite {
} }
return null; return null;
case File: case File:
GWT.log("Checking is valid File"); GWT.log("Checking is valid File");
if (field.getMandatory()) { if (field.getMandatory()) {
if (holder.getClass().equals(DialogUpload.class) || holder.getClass().equals(MultipleDilaogUpload.class)) { if (holder.getClass().equals(DialogUpload.class)
|| holder.getClass().equals(MultipleDilaogUpload.class)) {
DialogUpload dUpload = (DialogUpload) holder; DialogUpload dUpload = (DialogUpload) holder;
if(dUpload.getFileUploadingState()!=null && dUpload.getFileUploadingState().getFile()!=null) { if (dUpload.getFileUploadingState() != null && dUpload.getFileUploadingState().getFile() != null) {
return dUpload.getFileUploadingState().getFile().getTempSystemPath()!=null?null:UPLOAD_MISSING_FILE; return dUpload.getFileUploadingState().getFile().getTempSystemPath() != null ? null
: UPLOAD_MISSING_FILE;
} }
} }
return UPLOAD_MISSING_FILE; return UPLOAD_MISSING_FILE;
} }
return null; return null;
default: default:
return null; return null;
@ -772,14 +868,14 @@ public class MetaDataFieldSkeleton extends Composite {
} }
// if it was not mandatory but there was no choice, returning empty string // if it was not mandatory but there was no choice, returning empty string
if(!field.getMandatory()) { if (!field.getMandatory()) {
//Task #20446 - bug fix. Ignoring the placeholder // Task #20446 - bug fix. Ignoring the placeholder
if(toReturn.size()==1) { if (toReturn.size() == 1) {
String placeholder = "Select " + field.getFieldName(); String placeholder = "Select " + field.getFieldName();
if(toReturn.get(0).equals(placeholder)){ if (toReturn.get(0).equals(placeholder)) {
GWT.log("Skipping placeholder: "+placeholder); GWT.log("Skipping placeholder: " + placeholder);
toReturn.clear(); toReturn.clear();
//toReturn.add(""); // toReturn.add("");
} }
} }
} }
@ -787,16 +883,16 @@ public class MetaDataFieldSkeleton extends Composite {
break; break;
case File: case File:
if (holder.getClass().equals(MultipleDilaogUpload.class) || holder.getClass().equals(DialogUpload.class)) { if (holder.getClass().equals(MultipleDilaogUpload.class) || holder.getClass().equals(DialogUpload.class)) {
DialogUpload dUpload = (DialogUpload) holder; DialogUpload dUpload = (DialogUpload) holder;
if(dUpload.getFileUploadingState()!=null) { if (dUpload.getFileUploadingState() != null) {
String filePath = dUpload.getFileUploadingState().getFile().getTempSystemPath(); String filePath = dUpload.getFileUploadingState().getFile().getTempSystemPath();
toReturn.add(filePath); toReturn.add(filePath);
}else } else
toReturn.add(null); toReturn.add(null);
} }
break; break;
default: default:
@ -825,8 +921,16 @@ public class MetaDataFieldSkeleton extends Composite {
*/ */
public String getFieldNameQualified() { public String getFieldNameQualified() {
if (field.getFieldNameFromCategory() != null) //see https://support.d4science.org/issues/23544
if (field.getFieldId() != null) {
return field.getFieldId();
}
//Using the getFieldNameFromCategory if the category is present in the model as cateogory:fieldName
if (field.getFieldNameFromCategory() != null && field.getFieldNameFromCategory().compareTo(field.getFieldName())!=0) {
return field.getFieldNameFromCategory(); return field.getFieldNameFromCategory();
}
return field.getFieldName(); return field.getFieldName();
} }

View File

@ -1,6 +1,5 @@
package org.gcube.portlets.widgets.mpformbuilder.client.ui.upload; package org.gcube.portlets.widgets.mpformbuilder.client.ui.upload;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -25,58 +24,56 @@ import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.VerticalPanel;
// TODO: Auto-generated Javadoc // TODO: Auto-generated Javadoc
/** /**
* The Class DialogUploadStream. * The Class DialogUploadStream.
* *
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Sep 24, 2015
* Sep 24, 2015
*/ */
public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotificationListener{ public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotificationListener {
/** The file upload. */ /** The file upload. */
//protected final FormPanel formPanel = new FormPanel(); // protected final FormPanel formPanel = new FormPanel();
protected FileUpload fileUpload; protected FileUpload fileUpload;
/** The json client keys. */ /** The json client keys. */
protected Hidden jsonClientKeys; protected Hidden jsonClientKeys;
/** The fake uploaders. */ /** The fake uploaders. */
protected List<FileUploadingState> fakeUploaders = new ArrayList<FileUploadingState>(); protected List<FileUploadingState> fakeUploaders = new ArrayList<FileUploadingState>();
/** The controller. */ /** The controller. */
protected WorkspaceUploaderListenerController controller = new WorkspaceUploaderListenerController(); protected WorkspaceUploaderListenerController controller = new WorkspaceUploaderListenerController();
/** The timer. */ /** The timer. */
protected TimerUpload timer; protected TimerUpload timer;
protected String fieldName;
/** /**
* The Enum UPLOAD_TYPE. * The Enum UPLOAD_TYPE.
* *
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Sep 11, 2015
* Sep 11, 2015
*/ */
private HTML UPLOADING = new HTML("Uploading..."); private HTML UPLOADING = new HTML("Uploading...");
/** The vertical main panel. */ /** The vertical main panel. */
protected VerticalPanel verticalMainPanel; protected VerticalPanel verticalMainPanel;
// private MonitorPanel monitorPanel; // private MonitorPanel monitorPanel;
//protected String clientUploadKey; // protected String clientUploadKey;
/** The purged uploading file name. */ /** The purged uploading file name. */
private String purgedUploadingFileName; private String purgedUploadingFileName;
/** The upv. */ /** The upv. */
private UploaderProgressView upv; private UploaderProgressView upv;
/** /**
* Instantiates a new dialog upload stream. * Instantiates a new dialog upload stream.
*/ */
public DialogUpload(){ public DialogUpload() {
//setWidth("400px");
fileUpload = new FileUpload(); fileUpload = new FileUpload();
//fileUpload.getElement().setAttribute("multiple", "multiple"); // fileUpload.getElement().setAttribute("multiple", "multiple");
setAction(ConstantsMPFormBuilder.METADATA_FORM_BUILDER_UPLOADING_SERVLET); setAction(ConstantsMPFormBuilder.METADATA_FORM_BUILDER_UPLOADING_SERVLET);
setEncoding(FormPanel.ENCODING_MULTIPART); setEncoding(FormPanel.ENCODING_MULTIPART);
setMethod(FormPanel.METHOD_POST); setMethod(FormPanel.METHOD_POST);
@ -89,8 +86,12 @@ public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotific
fileUpload.setName(ConstantsMPFormBuilder.UPLOAD_FORM_ELEMENT); fileUpload.setName(ConstantsMPFormBuilder.UPLOAD_FORM_ELEMENT);
// Add hidden parameters // Add hidden parameters
verticalMainPanel.add(new Hidden(ConstantsMPFormBuilder.CURR_GROUP_ID, GCubeClientContext.getCurrentContextId())); verticalMainPanel
verticalMainPanel.add(new Hidden(ConstantsMPFormBuilder.UPLOAD_TYPE, ConstantsMPFormBuilder.THE_UPLOAD_TYPE.File.name())); .add(new Hidden(ConstantsMPFormBuilder.CURR_GROUP_ID, GCubeClientContext.getCurrentContextId()));
verticalMainPanel.add(
new Hidden(ConstantsMPFormBuilder.UPLOAD_TYPE, ConstantsMPFormBuilder.THE_UPLOAD_TYPE.File.name()));
verticalMainPanel.add(new Hidden(ConstantsMPFormBuilder.UPL_FIELD_NAME_FILEPATH, fieldName));
initJsonClientKeys(); initJsonClientKeys();
verticalMainPanel.add(jsonClientKeys); verticalMainPanel.add(jsonClientKeys);
@ -105,6 +106,24 @@ public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotific
verticalMainPanel.add(hp); verticalMainPanel.add(hp);
} }
/**
* Sets the field name.
*
* @param fieldName the new field name
*/
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
/**
* Gets the field name.
*
* @return the field name
*/
public String getFieldName() {
return fieldName;
}
/** /**
* Gets the panel. * Gets the panel.
* *
@ -117,14 +136,14 @@ public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotific
/** /**
* Inits the json client keys. * Inits the json client keys.
*/ */
protected void initJsonClientKeys(){ protected void initJsonClientKeys() {
jsonClientKeys = new Hidden(ConstantsMPFormBuilder.CLIENT_UPLOAD_KEYS,""); jsonClientKeys = new Hidden(ConstantsMPFormBuilder.CLIENT_UPLOAD_KEYS, "");
} }
/** /**
* Bind events. * Bind events.
*/ */
public void bindEvents(){ public void bindEvents() {
this.addHandlers(); this.addHandlers();
// this.addListeners(); // this.addListeners();
} }
@ -143,10 +162,11 @@ public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotific
// isStatusCompleted = true; // isStatusCompleted = true;
String result = event.getResults(); String result = event.getResults();
if (result == null) { if (result == null) {
removeLoading(); removeLoading();
Window.alert("An error occurred during file upload"); Window.alert("An error occurred during file upload");
//new DialogResult(null, "Error during upload", "An error occurred during file upload.").center(); // new DialogResult(null, "Error during upload", "An error occurred during file
// upload.").center();
return; return;
} }
String strippedResult = new HTML(result).getText(); String strippedResult = new HTML(result).getText();
@ -155,25 +175,25 @@ public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotific
switch (resultMessage.getStatus()) { switch (resultMessage.getStatus()) {
case ERROR: case ERROR:
removeLoading(); removeLoading();
//timer.cancel(); // timer.cancel();
GWT.log("Error during upload "+resultMessage.getMessage()); GWT.log("Error during upload " + resultMessage.getMessage());
break; break;
case UNKNOWN: case UNKNOWN:
removeLoading(); removeLoading();
//timer.cancel(); // timer.cancel();
GWT.log("Error during upload "+resultMessage.getMessage()); GWT.log("Error during upload " + resultMessage.getMessage());
break; break;
case WARN: { case WARN: {
GWT.log("Upload completed with warnings "+resultMessage.getMessage()); GWT.log("Upload completed with warnings " + resultMessage.getMessage());
removeLoading(); removeLoading();
//timer.cancel(); // timer.cancel();
break; break;
} }
case SESSION_EXPIRED:{ case SESSION_EXPIRED: {
GWT.log("Upload aborted due to session expired: "+ resultMessage.getMessage()); GWT.log("Upload aborted due to session expired: " + resultMessage.getMessage());
Window.alert("Session expired, please reload the page"); Window.alert("Session expired, please reload the page");
removeLoading(); removeLoading();
//timer.cancel(); // timer.cancel();
break; break;
} }
case OK: { case OK: {
@ -193,7 +213,7 @@ public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotific
} }
}); });
//TODO NEVER USED, WE ARE USING MULTIPLE DIALOG UPLOAD // TODO NEVER USED, WE ARE USING MULTIPLE DIALOG UPLOAD
addSubmitHandler(new SubmitHandler() { addSubmitHandler(new SubmitHandler() {
@Override @Override
@ -209,41 +229,45 @@ public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotific
public void onChange(ChangeEvent event) { public void onChange(ChangeEvent event) {
GWT.log("btnSubmit click"); GWT.log("btnSubmit click");
if (fileUpload.getFilename()==null || !(fileUpload.getFilename().length()>2)) { if (fileUpload.getFilename() == null || !(fileUpload.getFilename().length() > 2)) {
GWT.log("No file specified "); GWT.log("No file specified ");
return; return;
} }
GWT.log("fileUpload.getFilename() "+fileUpload.getFilename()); GWT.log("fileUpload.getFilename() " + fileUpload.getFilename());
/* /*
* TODO: recall: Some browser would write in fileUploadField.getValue() C:\fakepath\$fileName * TODO: recall: Some browser would write in fileUploadField.getValue()
* C:\fakepath\$fileName
*/ */
String normalizedFileName = fileUpload.getFilename(); String normalizedFileName = fileUpload.getFilename();
if (normalizedFileName.contains("\\")) { if (normalizedFileName.contains("\\")) {
normalizedFileName = normalizedFileName.substring(normalizedFileName.lastIndexOf("\\")+1); //remove C:\fakepath\ if exists normalizedFileName = normalizedFileName.substring(normalizedFileName.lastIndexOf("\\") + 1); // remove
// C:\fakepath\
// if
// exists
} }
purgedUploadingFileName = normalizedFileName; purgedUploadingFileName = normalizedFileName;
submitForm(); submitForm();
} }
}); });
} }
/** /**
* On submit action. * On submit action.
*/ */
protected void onSubmitAction() { protected void onSubmitAction() {
GWT.log("SubmitEvent"); GWT.log("SubmitEvent");
try { try {
if(upv!=null) if (upv != null)
verticalMainPanel.remove(upv.getPanel()); verticalMainPanel.remove(upv.getPanel());
}catch (Exception e) { } catch (Exception e) {
// TODO: handle exception // TODO: handle exception
} }
addLoading(); addLoading();
enableButtons(false); enableButtons(false);
//Only the first, just to manage single uploading // Only the first, just to manage single uploading
FileUploadingState workspaceUploaderItem = fakeUploaders.get(0); FileUploadingState workspaceUploaderItem = fakeUploaders.get(0);
upv = new UploaderProgressView(workspaceUploaderItem, workspaceUploaderItem.getFile().getFileName(), null); upv = new UploaderProgressView(workspaceUploaderItem, workspaceUploaderItem.getFile().getFileName(), null);
verticalMainPanel.add(upv.getPanel()); verticalMainPanel.add(upv.getPanel());
removeLoading(); removeLoading();
@ -252,33 +276,32 @@ public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotific
fakeUploaders.clear(); fakeUploaders.clear();
} }
/** /**
* Gets the file uploading state. * Gets the file uploading state.
* *
* @return the file uploading state * @return the file uploading state
*/ */
public FileUploadingState getFileUploadingState() { public FileUploadingState getFileUploadingState() {
if(timer!=null) if (timer != null)
return timer.getLastWorkspaceUploader(); return timer.getLastWorkspaceUploader();
return null; return null;
} }
/** /**
* Adds the loading. * Adds the loading.
*/ */
protected void addLoading(){ protected void addLoading() {
verticalMainPanel.add(UPLOADING); verticalMainPanel.add(UPLOADING);
} }
/** /**
* Removes the loading. * Removes the loading.
*/ */
protected void removeLoading(){ protected void removeLoading() {
try{ try {
verticalMainPanel.remove(UPLOADING); verticalMainPanel.remove(UPLOADING);
}catch(Exception e){ } catch (Exception e) {
} }
} }
@ -288,7 +311,7 @@ public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotific
* *
* @param bool the bool * @param bool the bool
*/ */
protected void enableButtons(boolean bool){ protected void enableButtons(boolean bool) {
// btnUpload.setEnabled(bool); // btnUpload.setEnabled(bool);
// btnCancel.setEnabled(bool); // btnCancel.setEnabled(bool);
// upload.setEnabled(bool); // upload.setEnabled(bool);
@ -297,37 +320,33 @@ public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotific
/** /**
* Submit form. * Submit form.
*/ */
public void submitForm(){ public void submitForm() {
submit(); submit();
} }
/** /**
* Removes the item and submit form. * Removes the item and submit form.
* *
* @param itemId the item id * @param itemId the item id
*/ */
protected void removeItemAndSubmitForm(String itemId){ protected void removeItemAndSubmitForm(String itemId) {
/* /*
AppControllerExplorer.rpcWorkspaceService.removeItem(itemId, new AsyncCallback<Boolean>() { * AppControllerExplorer.rpcWorkspaceService.removeItem(itemId, new
* AsyncCallback<Boolean>() {
@Override *
public void onFailure(Throwable caught) { * @Override public void onFailure(Throwable caught) { Info.display("Error",
Info.display("Error", caught.getMessage()); * caught.getMessage());
*
*
} * }
*
@Override * @Override public void onSuccess(Boolean result) { if(result){
public void onSuccess(Boolean result) { * hiddenOverwrite.setValue("true"); submitForm(); }
if(result){ *
hiddenOverwrite.setValue("true"); * }
submitForm(); *
} * });
*/
}
});*/
} }
/** /**
@ -335,8 +354,8 @@ public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotific
* *
* @param itemId the item id * @param itemId the item id
*/ */
protected void updateItemSubmitForm(String itemId){ protected void updateItemSubmitForm(String itemId) {
//hiddenOverwrite.setValue("true"); // hiddenOverwrite.setValue("true");
submitForm(); submitForm();
} }
@ -345,8 +364,14 @@ public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotific
* *
* @param handler the handler * @param handler the handler
*/ */
/* (non-Javadoc) /*
* @see org.gcube.portlets.widgets.workspaceuploader.client.WorkspaceUploadNotification.HasWorskpaceUploadNotificationListener#addWorkspaceUploadNotificationListener(org.gcube.portlets.widgets.workspaceuploader.client.WorkspaceUploadNotification.WorskpaceUploadNotificationListener) * (non-Javadoc)
*
* @see org.gcube.portlets.widgets.workspaceuploader.client.
* WorkspaceUploadNotification.HasWorskpaceUploadNotificationListener#
* addWorkspaceUploadNotificationListener(org.gcube.portlets.widgets.
* workspaceuploader.client.WorkspaceUploadNotification.
* WorskpaceUploadNotificationListener)
*/ */
@Override @Override
public void addWorkspaceUploadNotificationListener(WorskpaceUploadNotificationListener handler) { public void addWorkspaceUploadNotificationListener(WorskpaceUploadNotificationListener handler) {
@ -358,22 +383,26 @@ public class DialogUpload extends FormPanel implements HasWorskpaceUploadNotific
* *
* @param handler the handler * @param handler the handler
*/ */
/* (non-Javadoc) /*
* @see org.gcube.portlets.widgets.workspaceuploader.client.WorkspaceUploadNotification.HasWorskpaceUploadNotificationListener#removeWorkspaceUploadNotificationListener(org.gcube.portlets.widgets.workspaceuploader.client.WorkspaceUploadNotification.WorskpaceUploadNotificationListener) * (non-Javadoc)
*
* @see org.gcube.portlets.widgets.workspaceuploader.client.
* WorkspaceUploadNotification.HasWorskpaceUploadNotificationListener#
* removeWorkspaceUploadNotificationListener(org.gcube.portlets.widgets.
* workspaceuploader.client.WorkspaceUploadNotification.
* WorskpaceUploadNotificationListener)
*/ */
@Override @Override
public void removeWorkspaceUploadNotificationListener(WorskpaceUploadNotificationListener handler) { public void removeWorkspaceUploadNotificationListener(WorskpaceUploadNotificationListener handler) {
controller.removeWorkspaceUploadListener(handler); controller.removeWorkspaceUploadListener(handler);
} }
/** /**
* Enable upload. * Enable upload.
* *
* @param bool the bool * @param bool the bool
*/ */
public void enableUpload(boolean bool){ public void enableUpload(boolean bool) {
fileUpload.setEnabled(bool); fileUpload.setEnabled(bool);
} }
} }

View File

@ -16,9 +16,9 @@ public class FileUpload extends Composite {
@UiField HTMLPanel fileUploadPanel; @UiField HTMLPanel fileUploadPanel;
public FileUpload() { public FileUpload(String fielName) {
initWidget(uiBinder.createAndBindUi(this)); initWidget(uiBinder.createAndBindUi(this));
fileUploadPanel.add(new MultipleDilaogUpload()); fileUploadPanel.add(new MultipleDilaogUpload(fielName));
} }
} }

View File

@ -7,6 +7,7 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import org.gcube.portlets.widgets.mpformbuilder.client.ConstantsMPFormBuilder; import org.gcube.portlets.widgets.mpformbuilder.client.ConstantsMPFormBuilder;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FilePath;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploaded; import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploaded;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploadingState; import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploadingState;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploadingState.UPLOAD_STATUS; import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploadingState.UPLOAD_STATUS;
@ -31,27 +32,27 @@ public class MultipleDilaogUpload extends DialogUpload {
/** The Constant FILE_DELEMITER. */ /** The Constant FILE_DELEMITER. */
public static final String FILE_DELEMITER = ";"; public static final String FILE_DELEMITER = ";";
/** The file upload ID. */ /** The file upload ID. */
private String fileUploadID; private String fileUploadID;
/** The instance. */ /** The instance. */
//private MultipleDNDUpload dnd; // private MultipleDNDUpload dnd;
public MultipleDilaogUpload instance = this; public MultipleDilaogUpload instance = this;
/** The json keys. */ /** The json keys. */
private String jsonKeys; private String jsonKeys;
/** The id folder. */ /** The id folder. */
private String idFolder; private String idFolder;
/** /**
* Instantiates a new multiple dilaog upload. * Instantiates a new multiple dilaog upload.
*/ */
public MultipleDilaogUpload() { public MultipleDilaogUpload(String fieldName) {
fileUploadID = GenerateUUID.get(10, 16); // is tagID this.fileUploadID = GenerateUUID.get(10, 16); // is tagID
fileUpload.getElement().setId(fileUploadID); this.fileUpload.getElement().setId(fileUploadID);
super.setFieldName(fieldName);
this.addHandlers(); this.addHandlers();
} }
@ -63,7 +64,7 @@ public class MultipleDilaogUpload extends DialogUpload {
*/ */
public void generateFakeUploaders(String filesSelected) { public void generateFakeUploaders(String filesSelected) {
if(filesSelected==null || filesSelected.isEmpty()) if (filesSelected == null || filesSelected.isEmpty())
return; return;
String[] files = filesSelected.split(FILE_DELEMITER); String[] files = filesSelected.split(FILE_DELEMITER);
@ -72,11 +73,12 @@ public class MultipleDilaogUpload extends DialogUpload {
for (int i = 0; i < files.length; i++) { for (int i = 0; i < files.length; i++) {
String normalizedFileName = files[i]; String normalizedFileName = files[i];
if (normalizedFileName.contains("\\")) { if (normalizedFileName.contains("\\")) {
files[i] = normalizedFileName.substring(normalizedFileName.lastIndexOf("\\") + 1); // remove C:\fakepath if exists files[i] = normalizedFileName.substring(normalizedFileName.lastIndexOf("\\") + 1); // remove C:\fakepath
// if exists
} }
} }
GWT.log("generating fake uploaders on: "+Arrays.asList(files.toString())); GWT.log("generating fake uploaders on: " + Arrays.asList(files.toString()));
fakeUploaders = new ArrayList<FileUploadingState>(files.length); fakeUploaders = new ArrayList<FileUploadingState>(files.length);
for (int i = 0; i < files.length; i++) { for (int i = 0; i < files.length; i++) {
FileUploadingState fakeItem = new FileUploadingState(); FileUploadingState fakeItem = new FileUploadingState();
@ -85,10 +87,12 @@ public class MultipleDilaogUpload extends DialogUpload {
FileUploaded fakeFile = new FileUploaded(); FileUploaded fakeFile = new FileUploaded();
fakeFile.setFileName(files[i]); fakeFile.setFileName(files[i]);
fakeItem.setFile(fakeFile); fakeItem.setFile(fakeFile);
fakeFile.setFilePaths(new FilePath(getFieldName())); // The Form Field Label is unique for single-multiple
// upload
fakeUploaders.add(fakeItem); fakeUploaders.add(fakeItem);
} }
GWT.log("fakeUploaders generated: "+fakeUploaders.toString()); GWT.log("fakeUploaders generated: " + fakeUploaders.toString());
} }
/** /**
@ -103,7 +107,7 @@ public class MultipleDilaogUpload extends DialogUpload {
@Override @Override
public void onSubmitComplete(SubmitCompleteEvent event) { public void onSubmitComplete(SubmitCompleteEvent event) {
GWT.log("onSubmitComplete in multipleupload"); GWT.log("onSubmitComplete in multipleupload");
// isStatusCompleted = true; // isStatusCompleted = true;
String result = event.getResults(); String result = event.getResults();
@ -115,31 +119,30 @@ public class MultipleDilaogUpload extends DialogUpload {
return; return;
} }
String strippedResult = new HTML(result).getText(); String strippedResult = new HTML(result).getText();
final HandlerResultMessage resultMessage = HandlerResultMessage final HandlerResultMessage resultMessage = HandlerResultMessage.parseResult(strippedResult);
.parseResult(strippedResult);
switch (resultMessage.getStatus()) { switch (resultMessage.getStatus()) {
case ERROR: case ERROR:
removeLoading(); removeLoading();
//timer.cancel(); // timer.cancel();
GWT.log("Error during upload " + resultMessage.getMessage()); GWT.log("Error during upload " + resultMessage.getMessage());
break; break;
case UNKNOWN: case UNKNOWN:
removeLoading(); removeLoading();
//timer.cancel(); // timer.cancel();
GWT.log("Error during upload " + resultMessage.getMessage()); GWT.log("Error during upload " + resultMessage.getMessage());
break; break;
case WARN: { case WARN: {
GWT.log("Upload completed with warnings "+ resultMessage.getMessage()); GWT.log("Upload completed with warnings " + resultMessage.getMessage());
removeLoading(); removeLoading();
//timer.cancel(); // timer.cancel();
break; break;
} }
case SESSION_EXPIRED:{ case SESSION_EXPIRED: {
GWT.log("Upload aborted due to session expired: "+ resultMessage.getMessage()); GWT.log("Upload aborted due to session expired: " + resultMessage.getMessage());
Window.alert("Session expired, please reload the page"); Window.alert("Session expired, please reload the page");
removeLoading(); removeLoading();
//timer.cancel(); // timer.cancel();
break; break;
} }
case OK: { case OK: {
@ -165,20 +168,20 @@ public class MultipleDilaogUpload extends DialogUpload {
@Override @Override
public void onChange(ChangeEvent event) { public void onChange(ChangeEvent event) {
GWT.log("file upload change handler, browse return..."); GWT.log("file upload change handler, browse returns...");
if (fileUpload.getFilename() == null || fileUpload.getFilename().isEmpty()) { if (fileUpload.getFilename() == null || fileUpload.getFilename().isEmpty()) {
GWT.log("No file specified "); GWT.log("No file specified ");
//MultipleDilaogUpload.this.hide(); // MultipleDilaogUpload.this.hide();
return; return;
} }
String[] files = null; String[] files = null;
GWT.log("Current Uploader has id: "+fileUploadID); GWT.log("Current Uploader has id: " + fileUploadID);
String filesSelected = getFilesSelected(fileUploadID, FILE_DELEMITER); String filesSelected = getFilesSelected(fileUploadID, FILE_DELEMITER);
GWT.log("getFilesSelected: " + filesSelected); GWT.log("getFilesSelected: " + filesSelected);
files = filesSelected.split(FILE_DELEMITER); files = filesSelected.split(FILE_DELEMITER);
if(isLimitExceeded(files.length)) if (isLimitExceeded(files.length))
return; return;
// GENERATE NEW UPLOADERS // GENERATE NEW UPLOADERS
@ -199,24 +202,19 @@ public class MultipleDilaogUpload extends DialogUpload {
} }
}); });
} }
/** /**
* Checks if is limit exceeded. * Checks if is limit exceeded.
* *
* @param numbOfFiles the numb of files * @param numbOfFiles the numb of files
* @return true, if is limit exceeded * @return true, if is limit exceeded
*/ */
public boolean isLimitExceeded(int numbOfFiles){ public boolean isLimitExceeded(int numbOfFiles) {
if (numbOfFiles > ConstantsMPFormBuilder.LIMIT_UPLOADS) { if (numbOfFiles > ConstantsMPFormBuilder.LIMIT_UPLOADS) {
Window.alert("Multiple upload limit is " Window.alert("Multiple upload limit is " + ConstantsMPFormBuilder.LIMIT_UPLOADS + " files");
+ ConstantsMPFormBuilder.LIMIT_UPLOADS // MultipleDilaogUpload.this.hide();
+ " files");
//MultipleDilaogUpload.this.hide();
return true; return true;
} }
@ -226,21 +224,22 @@ public class MultipleDilaogUpload extends DialogUpload {
/** /**
* Adds the new submit to monitor. * Adds the new submit to monitor.
*/ */
public void addNewSubmitToMonitor(){ public void addNewSubmitToMonitor() {
GWT.log("addNewSubmitToMonitor..."); GWT.log("addNewSubmitToMonitor...");
/*int queueIndex = UploaderMonitor.getInstance().newQueue(); /*
for (final WorkspaceUploaderItem workspaceUploaderItem : fakeUploaders) { * int queueIndex = UploaderMonitor.getInstance().newQueue(); for (final
UploaderMonitor.getInstance().addNewUploaderToMonitorPanel(workspaceUploaderItem, workspaceUploaderItem.getFile().getFileName()); * WorkspaceUploaderItem workspaceUploaderItem : fakeUploaders) {
setVisible(false); * UploaderMonitor.getInstance().addNewUploaderToMonitorPanel(
removeLoading(); * workspaceUploaderItem, workspaceUploaderItem.getFile().getFileName());
UploaderMonitor.getInstance().addNewUploaderToQueue(queueIndex, workspaceUploaderItem); * setVisible(false); removeLoading();
// UploaderMonitor.getInstance().pollWorkspaceUploader(workspaceUploaderItem); * UploaderMonitor.getInstance().addNewUploaderToQueue(queueIndex,
} * workspaceUploaderItem); //
* UploaderMonitor.getInstance().pollWorkspaceUploader(workspaceUploaderItem); }
UploaderMonitor.getInstance().doStartPollingQueue(queueIndex);*/ *
* UploaderMonitor.getInstance().doStartPollingQueue(queueIndex);
*/
} }
/** /**
* Creates the json key for files. * Creates the json key for files.
* *
@ -257,12 +256,17 @@ public class MultipleDilaogUpload extends DialogUpload {
for (int i = 0; i < fakeUploaders.size(); i++) { for (int i = 0; i < fakeUploaders.size(); i++) {
FileUploadingState file = fakeUploaders.get(i); FileUploadingState file = fakeUploaders.get(i);
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put(file.getClientUploadKey(), new JSONString(file.getFile().getFileName())); // JSONObject innerObj = new JSONObject();
obj.put(ConstantsMPFormBuilder.UPL_CLIENT_KEY, new JSONString(file.getClientUploadKey()));
obj.put(ConstantsMPFormBuilder.UPL_FILENAME, new JSONString(file.getFile().getFileName()));
obj.put(ConstantsMPFormBuilder.UPL_FIELD_NAME_FILEPATH, new JSONString(file.getFile().getFilePath().getFormFieldLabel()));
// obj.put(file.getClientUploadKey(), new
// JSONString(file.getFile().getFileName()));
jsonArray.set(i, obj); jsonArray.set(i, obj);
} }
jsonKeys = productObj.toString(); jsonKeys = productObj.toString();
GWT.log("updated jsonKeys: "+jsonKeys); GWT.log("updated jsonKeys: " + jsonKeys);
} catch (Exception e) { } catch (Exception e) {
GWT.log("error " + e.getMessage()); GWT.log("error " + e.getMessage());
jsonKeys = null; jsonKeys = null;
@ -305,14 +309,11 @@ public class MultipleDilaogUpload extends DialogUpload {
}-*/; }-*/;
/** /**
* Gets the files selected. * Gets the files selected.
* *
* @param tagId * @param tagId the tag id
* the tag id * @param fileDelimiter the file delimiter
* @param fileDelimiter
* the file delimiter
* @return the files selected * @return the files selected
*/ */
public static native String getFilesSelected(final String tagId, final String fileDelimiter) /*-{ public static native String getFilesSelected(final String tagId, final String fileDelimiter) /*-{

View File

@ -0,0 +1,48 @@
package org.gcube.portlets.widgets.mpformbuilder.server;
import org.gcube.portlets.widgets.mpformbuilder.client.ConstantsMPFormBuilder;
import com.fasterxml.jackson.annotation.JsonProperty;
public class JSONFileUploaded {
@JsonProperty(value = ConstantsMPFormBuilder.UPL_CLIENT_KEY)
protected String clienKey;
@JsonProperty(value = ConstantsMPFormBuilder.UPL_FILENAME)
protected String fileName;
// THIS IS THE FIELD LABEL USED IN THE WEB-FORM
// AND DECLARED IN THE FIELDNAME OF THE GCUBE METADATA PROFILE
@JsonProperty(value = ConstantsMPFormBuilder.UPL_FIELD_NAME_FILEPATH)
protected String fieldNameFilePath;
public JSONFileUploaded() {
super();
}
public String getClienKey() {
return clienKey;
}
public String getFileName() {
return fileName;
}
public String getFieldNameFilePath() {
return fieldNameFilePath;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("JSONFileUploaded [clienKey=");
builder.append(clienKey);
builder.append(", fileName=");
builder.append(fileName);
builder.append(", fieldNameFilePath=");
builder.append(fieldNameFilePath);
builder.append("]");
return builder.toString();
}
}

View File

@ -6,6 +6,8 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Random;
import java.util.UUID;
import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBException;
@ -19,6 +21,7 @@ import org.gcube.common.metadataprofilediscovery.jaxb.MetadataValidator;
import org.gcube.common.metadataprofilediscovery.jaxb.MetadataVocabulary; import org.gcube.common.metadataprofilediscovery.jaxb.MetadataVocabulary;
import org.gcube.common.metadataprofilediscovery.jaxb.NamespaceCategory; import org.gcube.common.metadataprofilediscovery.jaxb.NamespaceCategory;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portlets.widgets.mpformbuilder.server.util.WsUtil;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.CategoryWrapper; import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.CategoryWrapper;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.DataTypeWrapper; import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.DataTypeWrapper;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.FieldAsGroup; import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.FieldAsGroup;
@ -75,6 +78,90 @@ public class MetadataDiscovery {
} }
/**
* Gets the metadata profiles list.
*
* @param scope the scope
* @param gRSecondaryType the g R secondary type
* @param resourceName the resource name
* @return the metadata profiles list
* @throws Exception the exception
*/
public static List<MetaDataProfileBean> getMetadataProfilesList(String scope, String gRSecondaryType, String resourceName)
throws Exception {
List<MetaDataProfileBean> beans = new ArrayList<MetaDataProfileBean>();
LOG.debug("Discovering into scope " + scope);
String currentContext = ScopeProvider.instance.get();
try {
ScopeProvider.instance.set(scope);
// TODO two reset methods could be added to force the reader to read again these
// information (after a while)
MetadataProfileReader reader = new MetadataProfileReader(gRSecondaryType, resourceName);
List<MetadataProfile> profiles = reader.getListOfMetadataProfiles();
prettyPrintProfiles(profiles);
LOG.info("Profiles are " + profiles.size());
List<NamespaceCategory> categories = reader.getListOfNamespaceCategories();
if (categories == null)
categories = new ArrayList<NamespaceCategory>();
LOG.debug("All Categories are " + categories);
for (MetadataProfile profile : profiles) {
LOG.debug("Wrapping profile with name " + profile.getName() + " and type " + profile.getMetadataType());
MetadataFormat metadata = reader.getMetadataFormatForMetadataProfile(profile);
MetaDataProfileBean bean = toMetaDataProfileBean(metadata, categories, profile.getName());
beans.add(bean);
if(!WsUtil.isWithinPortal()) {
LOG.info("DEV MODE ENABLED - Out of portal!");
randomizeCurrentValues(bean.getMetadataFields());
}
}
prettyPrintList(beans);
LOG.info("Returning " + beans.size() + " profile/s");
} catch (Exception e) {
LOG.error("Error while retrieving metadata beans ", e);
throw new Exception("Failed to parse Types: " + e.getMessage());
} finally {
ScopeProvider.instance.set(currentContext);
}
return beans;
}
private static void randomizeCurrentValues(List<MetadataFieldWrapper> listFields) {
LOG.info("DEV MODE ENABLED - Generationg random current value");
for (MetadataFieldWrapper metadataFieldWrapper : listFields) {
DataTypeWrapper dtw = metadataFieldWrapper.getType();
switch (dtw) {
case Boolean:
metadataFieldWrapper.setCurrentValue(Boolean.FALSE.toString());
break;
case Number:
metadataFieldWrapper.setCurrentValue(new Random().nextInt()+"");
break;
case String:
case Text:
metadataFieldWrapper.setCurrentValue("Text "+UUID.randomUUID());
break;
default:
break;
}
}
}
/** /**
* Gets the metadata profiles list. * Gets the metadata profiles list.
* *
@ -211,6 +298,7 @@ public class MetadataDiscovery {
wrapperObj.setType(DataTypeWrapper.String); wrapperObj.setType(DataTypeWrapper.String);
} }
wrapperObj.setDefaultValue(metadataField.getDefaultValue()); wrapperObj.setDefaultValue(metadataField.getDefaultValue());
wrapperObj.setFieldId(metadataField.getFieldId());
wrapperObj.setFieldName(metadataField.getFieldName()); wrapperObj.setFieldName(metadataField.getFieldName());
wrapperObj.setMandatory(metadataField.getMandatory()); wrapperObj.setMandatory(metadataField.getMandatory());
wrapperObj.setNote(metadataField.getNote()); wrapperObj.setNote(metadataField.getNote());

View File

@ -66,6 +66,40 @@ public class MetadataProfileFormBuilderServiceImpl extends RemoteServiceServlet
return toReturn; return toReturn;
} }
/**
* Gets the profiles in the scope.
*
* @param scope the scope
* @param genericResourceSecondaryType the generic resource secondary type
* @param resourceName the resource name
* @return the profiles in the scope
* @throws Exception the exception
*/
@Override
public List<MetaDataProfileBean> getProfilesInTheScopeForName(String scope,String genericResourceSecondaryType, String resourceName) throws Exception {
LOG.info("Called getProfilesInTheScope with parameter scope: " +scope+ ", genericResourceSecondaryType: "+genericResourceSecondaryType, "resourceName: "+resourceName);
if(genericResourceSecondaryType==null || genericResourceSecondaryType.isEmpty())
throw new Exception("The input parameter 'genericResourceSecondaryType' is not valid");
if(resourceName==null || resourceName.isEmpty())
throw new Exception("The input parameter 'resourceName' is not valid");
List<MetaDataProfileBean> toReturn = new ArrayList<MetaDataProfileBean>();
try {
String evaluatedScope = scope == null || scope.isEmpty()?ScopeProvider.instance.get():scope;
LOG.debug("Evaluated scope is " + scope);
toReturn = MetadataDiscovery.getMetadataProfilesList(evaluatedScope, genericResourceSecondaryType, resourceName);
} catch (Exception e) {
LOG.error("Failed to retrieve profiles for scope " +scope, e);
throw e;
}
return toReturn;
}
/** /**
* Gets the profile for metadata. * Gets the profile for metadata.
* *
@ -132,7 +166,7 @@ public class MetadataProfileFormBuilderServiceImpl extends RemoteServiceServlet
/** /**
* Purge files uploaded in the current session * Purge files uploaded in the current session.
* *
* @return number of files deleted. Null otherwise. * @return number of files deleted. Null otherwise.
* @throws Exception the exception * @throws Exception the exception

View File

@ -10,6 +10,7 @@ import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.servlet.Servlet; import javax.servlet.Servlet;
@ -33,6 +34,7 @@ import org.gcube.common.portal.PortalContext;
import org.gcube.portlets.widgets.mpformbuilder.client.ConstantsMPFormBuilder; import org.gcube.portlets.widgets.mpformbuilder.client.ConstantsMPFormBuilder;
import org.gcube.portlets.widgets.mpformbuilder.server.util.WsUtil; import org.gcube.portlets.widgets.mpformbuilder.server.util.WsUtil;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.AbstractUploadProgressListener; import org.gcube.portlets.widgets.mpformbuilder.shared.upload.AbstractUploadProgressListener;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FilePath;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploaded; import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploaded;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploadingState; import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploadingState;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploadingState.UPLOAD_STATUS; import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploadingState.UPLOAD_STATUS;
@ -49,14 +51,16 @@ import org.json.JSONTokener;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
/** /**
* The Class MetadataProfileBuilderUploadServlet. * The Class MetadataProfileBuilderUploadServlet.
* *
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it at ISTI-CNR * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it at ISTI-CNR
* *
* Oct 5, 2020 * Oct 5, 2020
*/ */
public class MetadataProfileFormBuilderUploadServlet extends HttpServlet implements Servlet{ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet implements Servlet {
/** The Constant UNKNOWN_UNKNOWN. */ /** The Constant UNKNOWN_UNKNOWN. */
public static final String UNKNOWN_UNKNOWN = "unknown/unknown"; public static final String UNKNOWN_UNKNOWN = "unknown/unknown";
@ -69,11 +73,12 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
/** The Constant VRE_ID_ATTR_NAME. */ /** The Constant VRE_ID_ATTR_NAME. */
public static final String VRE_ID_ATTR_NAME = "gcube-vreid"; public static final String VRE_ID_ATTR_NAME = "gcube-vreid";
/** The Constant CURR_GROUP_ID. */ /** The Constant CURR_GROUP_ID. */
public static final String CURR_GROUP_ID = ConstantsMPFormBuilder.CURR_GROUP_ID; public static final String CURR_GROUP_ID = ConstantsMPFormBuilder.CURR_GROUP_ID;
//public static final String CURR_USER_ID = ConstantsWorkspaceUploader.CURR_USER_ID; // public static final String CURR_USER_ID =
// ConstantsWorkspaceUploader.CURR_USER_ID;
/** The Constant UPLOAD_FORM_ELEMENT. */ /** The Constant UPLOAD_FORM_ELEMENT. */
public static final String UPLOAD_FORM_ELEMENT = ConstantsMPFormBuilder.UPLOAD_FORM_ELEMENT; public static final String UPLOAD_FORM_ELEMENT = ConstantsMPFormBuilder.UPLOAD_FORM_ELEMENT;
@ -90,12 +95,18 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
/** The Constant UPLOAD_TYPE. */ /** The Constant UPLOAD_TYPE. */
public static final String UPLOAD_TYPE = ConstantsMPFormBuilder.UPLOAD_TYPE; public static final String UPLOAD_TYPE = ConstantsMPFormBuilder.UPLOAD_TYPE;
public static final String FIELD_NAME_FILEPATH = ConstantsMPFormBuilder.UPL_FIELD_NAME_FILEPATH;
public static final String FILENAME = ConstantsMPFormBuilder.UPL_FILENAME;
public static final String JSON_CLIENT_KEY = ConstantsMPFormBuilder.UPL_CLIENT_KEY;
/** The logger. */ /** The logger. */
public static Logger logger = LoggerFactory.getLogger(MetadataProfileFormBuilderUploadServlet.class); public static Logger logger = LoggerFactory.getLogger(MetadataProfileFormBuilderUploadServlet.class);
/** The app engine. */ /** The app engine. */
private static boolean appEngine = false; private static boolean appEngine = false;
public static final String JAVA_IO_TMPDIR = System.getProperty("java.io.tmpdir"); public static final String JAVA_IO_TMPDIR = System.getProperty("java.io.tmpdir");
/** /**
@ -119,7 +130,7 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
appEngine = isAppEngine(); appEngine = isAppEngine();
} }
logger.debug("init: appEngine is "+appEngine); logger.debug("init: appEngine is " + appEngine);
} }
/** /**
@ -127,32 +138,32 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
*/ */
@Override @Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.debug("GET method in "+MetadataProfileFormBuilderUploadServlet.class.getName()+" is running"); logger.debug("GET method in " + MetadataProfileFormBuilderUploadServlet.class.getName() + " is running");
String clientUploadKey = request.getParameter(CLIENT_UPLOAD_KEYS); String clientUploadKey = request.getParameter(CLIENT_UPLOAD_KEYS);
if (clientUploadKey == null){ if (clientUploadKey == null) {
sendError(response, "Internal error: UPLOAD KEY NOT FOUND"); sendError(response, "Internal error: UPLOAD KEY NOT FOUND");
return; return;
} }
logger.debug("GET method CLIENT_UPLOAD_KEY "+clientUploadKey); logger.debug("GET method CLIENT_UPLOAD_KEY " + clientUploadKey);
boolean cancelUpload = Boolean.parseBoolean(request.getParameter(CANCEL_UPLOAD)); boolean cancelUpload = Boolean.parseBoolean(request.getParameter(CANCEL_UPLOAD));
logger.debug("GET method CANCEL_UPLOAD "+cancelUpload); logger.debug("GET method CANCEL_UPLOAD " + cancelUpload);
if (cancelUpload) { if (cancelUpload) {
boolean cancelled = cancelUpload(request.getSession(), clientUploadKey); boolean cancelled = cancelUpload(request.getSession(), clientUploadKey);
if(cancelled){ if (cancelled) {
sendMessage(response, "Upload aborted "+clientUploadKey); sendMessage(response, "Upload aborted " + clientUploadKey);
// try { // try {
//// removeCurrentListener(request.getSession(), clientUploadKey); //// removeCurrentListener(request.getSession(), clientUploadKey);
// WsUtil.eraseWorkspaceUploaderInSession(request.getSession(), clientUploadKey); // WsUtil.eraseWorkspaceUploaderInSession(request.getSession(), clientUploadKey);
// }catch (Exception e) { // }catch (Exception e) {
// logger.warn("An error occurred during removing cancelled upload from session "); // logger.warn("An error occurred during removing cancelled upload from session ");
// } // }
} } else
else sendWarnMessage(response,
sendWarnMessage(response, "Upload aborted for id: "+clientUploadKey +" has skipped, already aborted or completed?"); "Upload aborted for id: " + clientUploadKey + " has skipped, already aborted or completed?");
}else } else
logger.debug(CANCEL_UPLOAD + " param not found"); logger.debug(CANCEL_UPLOAD + " param not found");
return; return;
} }
/** /**
@ -160,8 +171,9 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
*/ */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("POST on UploadServlet"); logger.info("POST on UploadServlet");
boolean requestIsNull = request==null; boolean requestIsNull = request == null;
logger.trace("[1] HttpServletRequest is: null? "+requestIsNull+", URI: "+request.getRequestURI() +", ServerName: "+request.getServerName()); logger.trace("[1] HttpServletRequest is: null? " + requestIsNull + ", URI: " + request.getRequestURI()
+ ", ServerName: " + request.getServerName());
if (!ServletFileUpload.isMultipartContent(request)) { if (!ServletFileUpload.isMultipartContent(request)) {
logger.error("ERROR: multipart request not found"); logger.error("ERROR: multipart request not found");
@ -172,41 +184,46 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
try { try {
logger.info("UPLOAD-SERVLET starting"); logger.info("UPLOAD-SERVLET starting");
HttpSession session = request.getSession(); HttpSession session = request.getSession();
logger.info("UPLOAD-SERVLET session: "+session); logger.info("UPLOAD-SERVLET session: " + session);
logger.debug("UPLOAD-SERVLET (" + session.getId() + ") new upload request received."); logger.debug("UPLOAD-SERVLET (" + session.getId() + ") new upload request received.");
if(WsUtil.isSessionExpired(request)){ if (WsUtil.isSessionExpired(request)) {
logger.error("SESSION_EXPIRED: session is expired"); logger.error("SESSION_EXPIRED: session is expired");
sendSessionExpired(response, "SESSION_EXPIRED: session is expired"); sendSessionExpired(response, "SESSION_EXPIRED: session is expired");
return; return;
} }
String uploadType = null; String uploadType = null;
// String clientUploadKey = null; String fieldName = null;
// String clientUploadKey = null;
FileItemStream uploadItem = null; FileItemStream uploadItem = null;
ArrayList<String> listClientUploadKeys = null; ArrayList<String> listClientUploadKeys = null;
GCubeUser user = PortalContext.getConfiguration().getCurrentUser(request); GCubeUser user = PortalContext.getConfiguration().getCurrentUser(request);
FileItemFactory factory = new DiskFileItemFactory(); FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(factory); ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
/** /**
* An iterator to instances of <code>FileItemStream</code> * An iterator to instances of <code>FileItemStream</code> parsed from the
* parsed from the request, in the order that they were * request, in the order that they were transmitted.
*transmitted.
*/ */
FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request); FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request);
int uploadItemsCnt = 0; int uploadItemsCnt = 0;
String scopeGroupId = ""; String scopeGroupId = "";
//GET FILE STREAM // GET FILE STREAM
while (fileItemIterator.hasNext()) { while (fileItemIterator.hasNext()) {
FileItemStream item = fileItemIterator.next(); FileItemStream item = fileItemIterator.next();
if (item.isFormField() && UPLOAD_TYPE.equals(item.getFieldName())){ if (item.isFormField() && UPLOAD_TYPE.equals(item.getFieldName())) {
uploadType = Streams.asString(item.openStream()); uploadType = Streams.asString(item.openStream());
logger.debug("UPLOAD_TYPE OK " +uploadType); logger.debug(UPLOAD_TYPE + " OK " + uploadType);
}
if (item.isFormField() && FIELD_NAME_FILEPATH.equals(item.getFieldName())) {
fieldName = Streams.asString(item.openStream());
logger.debug(FIELD_NAME_FILEPATH + " OK " + fieldName);
} }
// if (item.isFormField() && IS_OVERWRITE.equals(item.getFieldName())){ // if (item.isFormField() && IS_OVERWRITE.equals(item.getFieldName())){
@ -218,24 +235,32 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
// } // }
// } // }
if(item.isFormField() && CLIENT_UPLOAD_KEYS.equals(item.getFieldName())){ if (item.isFormField() && CLIENT_UPLOAD_KEYS.equals(item.getFieldName())) {
String jsonClientUploadKey = Streams.asString(item.openStream()); String jsonClientUploadKey = Streams.asString(item.openStream());
logger.debug("CLIENT_UPLOAD_KEY OK "+jsonClientUploadKey); logger.debug(CLIENT_UPLOAD_KEYS + " OK " + jsonClientUploadKey);
LinkedHashMap<String, String> mapKeys = parseJSONClientUploadKeys(jsonClientUploadKey); LinkedHashMap<String, JSONFileUploaded> mapKeys = parseJSONClientUploadKeys(jsonClientUploadKey);
listClientUploadKeys = new ArrayList<String>(mapKeys.keySet()); listClientUploadKeys = new ArrayList<String>(mapKeys.keySet());
removeListenersIfDone(session, listClientUploadKeys); removeListenersIfDone(session, listClientUploadKeys);
for (String clientUploadKey : listClientUploadKeys) { for (String clientUploadKey : listClientUploadKeys) {
String fileName = mapKeys.get(clientUploadKey); JSONFileUploaded fileUploaded = mapKeys.get(clientUploadKey);
FileUploadingState workspaceUploader = createNewWorkspaceUploader(clientUploadKey,fileName, user.getUsername()); logger.debug("Read file: " + fileUploaded);
logger.debug("created "+workspaceUploader); String fileName = fileUploaded.getFileName() != null ? fileUploaded.getFileName()
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.WAIT, "Uploading "+fileName+" at 0%", request.getSession()); : "No filename " + new Random().nextInt();
fieldName = fileUploaded.getFieldNameFilePath() != null ? fileUploaded.getFieldNameFilePath()
: fieldName;
FileUploadingState workspaceUploader = createNewWorkspaceUploader(clientUploadKey, fileName,
user.getUsername(), fieldName);
logger.debug("created " + workspaceUploader);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.WAIT,
"Uploading " + fileName + " at 0%", request.getSession());
} }
} }
if (item.isFormField() && CURR_GROUP_ID.equals(item.getFieldName())){ if (item.isFormField() && CURR_GROUP_ID.equals(item.getFieldName())) {
scopeGroupId = Streams.asString(item.openStream()); scopeGroupId = Streams.asString(item.openStream());
logger.debug("currentGroupId passed as parameter = " + scopeGroupId); logger.debug("currentGroupId passed as parameter = " + scopeGroupId);
logger.debug("currentGroupId into PortalContext scope= " + PortalContext.getConfiguration().getCurrentScope(scopeGroupId)); logger.debug("currentGroupId into PortalContext scope= "
+ PortalContext.getConfiguration().getCurrentScope(scopeGroupId));
} }
// if (item.isFormField() && CURR_USER_ID.equals(item.getFieldName())){ // if (item.isFormField() && CURR_USER_ID.equals(item.getFieldName())){
@ -244,12 +269,13 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
// logger.debug("currUserinto PortalContext = " + PortalContext.getConfiguration().getCurrentUser(request)); // logger.debug("currUserinto PortalContext = " + PortalContext.getConfiguration().getCurrentUser(request));
// } // }
//MUST BE THE LAST PARAMETER TRASMITTED // MUST BE THE LAST PARAMETER TRASMITTED
if (UPLOAD_FORM_ELEMENT.equals(item.getFieldName())){ if (UPLOAD_FORM_ELEMENT.equals(item.getFieldName())) {
uploadItem = item; uploadItem = item;
logger.debug("UPLOAD_FORM_ELEMENT OK "+uploadItem.getName() + " scopeGroupId="+scopeGroupId); logger.debug("UPLOAD_FORM_ELEMENT OK " + uploadItem.getName() + " scopeGroupId=" + scopeGroupId);
// break; // break;
uploadData(user, scopeGroupId, request, response, uploadItem, uploadType, listClientUploadKeys.get(uploadItemsCnt)); uploadData(user, scopeGroupId, request, response, uploadItem, uploadType,
listClientUploadKeys.get(uploadItemsCnt));
uploadItemsCnt++; uploadItemsCnt++;
} }
} }
@ -265,26 +291,25 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
} }
} }
/** /**
* Removes the listener if done. * Removes the listener if done.
* *
* @param session the session * @param session the session
* @param keys the keys * @param keys the keys
*/ */
private void removeListenersIfDone(HttpSession session, List<String> keys){ private void removeListenersIfDone(HttpSession session, List<String> keys) {
for (String key : keys) { for (String key : keys) {
AbstractUploadProgressListener listener = getCurrentListener(session, key); AbstractUploadProgressListener listener = getCurrentListener(session, key);
if (listener != null) { if (listener != null) {
logger.debug("Listener found"); logger.debug("Listener found");
if (listener.isCanceled() || listener.getPercentage() >= 100){ if (listener.isCanceled() || listener.getPercentage() >= 100) {
logger.debug("Listener isCanceled or 100%, removing"); logger.debug("Listener isCanceled or 100%, removing");
removeCurrentListener(session, key); removeCurrentListener(session, key);
} }
}else } else
logger.debug("Session id: "+session.getId() +" - "+key+" - Listener not found"); logger.debug("Session id: " + session.getId() + " - " + key + " - Listener not found");
} }
} }
@ -297,156 +322,170 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
* @throws FileUploadException the file upload exception * @throws FileUploadException the file upload exception
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
private static LinkedHashMap<String, String> parseJSONClientUploadKeys(final String jsonClientUploadKeys) throws FileUploadException{ private static LinkedHashMap<String, JSONFileUploaded> parseJSONClientUploadKeys(final String jsonClientUploadKeys)
throws FileUploadException {
JSONTokener tokener = new JSONTokener(jsonClientUploadKeys); JSONTokener tokener = new JSONTokener(jsonClientUploadKeys);
JSONObject root; JSONObject root;
LinkedHashMap<String, String> keyFiles = null; LinkedHashMap<String, JSONFileUploaded> keyFiles = null;
try { try {
root = new JSONObject(tokener); root = new JSONObject(tokener);
JSONArray jsonArray = root.getJSONArray(JSON_CLIENT_KEYS); JSONArray jsonArray = root.getJSONArray(JSON_CLIENT_KEYS);
keyFiles = new LinkedHashMap<String, String>(jsonArray.length()); keyFiles = new LinkedHashMap<String, JSONFileUploaded>(jsonArray.length());
logger.debug("jsonArray :"+jsonArray.toString()); logger.debug("jsonArray :" + jsonArray.toString());
for (int i=0; i<jsonArray.length(); i++) { for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i); String objectString = jsonArray.getString(i);
logger.debug("object :"+object); ObjectMapper om = new ObjectMapper();
String key = (String) object.keys().next(); JSONFileUploaded jfu = om.readValue(objectString, JSONFileUploaded.class);
String value = object.getString(key); keyFiles.put(jfu.clienKey, jfu);
logger.debug("key :"+key+", value: "+value); /*
keyFiles.put(key, value); * 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);
*/
} }
} catch (JSONException e) { } catch (JSONException | IOException e) {
logger.error("An error occurred during parsing file names: "+keyFiles, e); logger.error("An error occurred during parsing file names: " + keyFiles, e);
throw new FileUploadException("An error occurred during parsing file names"); throw new FileUploadException("An error occurred during parsing file names");
} }
logger.debug("keyFiles: "+keyFiles); logger.debug("keyFiles: " + keyFiles);
return keyFiles; return keyFiles;
} }
/** /**
* Upload data. * Upload data.
* *
* @param user the user * @param user the user
* @param scopeGroupId the scope group id * @param scopeGroupId the scope group id
* @param request the request * @param request the request
* @param response the response * @param response the response
* @param uploadItem the upload item * @param uploadItem the upload item
* @param uploadType the upload type * @param uploadType the upload type
* @param clientUploadKey the client upload key * @param clientUploadKey the client upload key
* @throws ServletException the servlet exception * @throws ServletException the servlet exception
* @throws IOException Signals that an I/O exception has occurred. * @throws IOException Signals that an I/O exception has occurred.
*/ */
private void uploadData(GCubeUser user, String scopeGroupId, HttpServletRequest request, final HttpServletResponse response, final FileItemStream uploadItem, String uploadType,String clientUploadKey) throws ServletException, IOException{ private void uploadData(GCubeUser user, String scopeGroupId, HttpServletRequest request,
final HttpServletResponse response, final FileItemStream uploadItem, String uploadType,
String clientUploadKey) throws ServletException, IOException {
String fileName = uploadItem.getName(); String fileName = uploadItem.getName();
logger.info("Upload servlet parameters: [fileName: "+fileName+ ", uploadType: "+uploadType+", clientUploadKey: "+clientUploadKey+"]"); logger.info("Upload servlet parameters: [fileName: " + fileName + ", uploadType: " + uploadType
+ ", clientUploadKey: " + clientUploadKey + "]");
if (uploadType == null || uploadType.isEmpty()) { if (uploadType == null || uploadType.isEmpty()) {
logger.error("Error processing request in upload servlet for: "+fileName+". No upload type found"); logger.error("Error processing request in upload servlet for: " + fileName + ". No upload type found");
sendError(response, "Internal error: No upload type found"); sendError(response, "Internal error: No upload type found");
return; return;
} }
if(clientUploadKey==null || clientUploadKey.isEmpty()){ if (clientUploadKey == null || clientUploadKey.isEmpty()) {
logger.error("Error processing request in upload servlet for: "+fileName+". No client upload key found"); logger.error(
"Error processing request in upload servlet for: " + fileName + ". No client upload key found");
sendError(response, "Internal error: No client upload key found"); sendError(response, "Internal error: No client upload key found");
return; return;
} }
//CLIENT UPLOAD IS THE KEY // CLIENT UPLOAD IS THE KEY
// WorkspaceUploaderItem workspaceUploader = createNewWorkspaceUploader(clientUploadKey,destinationId,fileName); // WorkspaceUploaderItem workspaceUploader = createNewWorkspaceUploader(clientUploadKey,destinationId,fileName);
// saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.WAIT, "Uploading "+fileName+" at 0%", request.getSession()); // saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.WAIT, "Uploading "+fileName+" at 0%", request.getSession());
//RETRIVE WORKSPACE UPLOADER FROM SESSION // RETRIVE WORKSPACE UPLOADER FROM SESSION
FileUploadingState workspaceUploader = null; FileUploadingState workspaceUploader = null;
try { try {
workspaceUploader = WsUtil.getWorkspaceUploaderInSession(request, clientUploadKey); workspaceUploader = WsUtil.getWorkspaceUploaderInSession(request, clientUploadKey);
} catch (Exception e) { } catch (Exception e) {
logger.error("Error during workspace uploader retrieving", e); logger.error("Error during workspace uploader retrieving", e);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "An error occurred during upload: "+fileName+". Error processing request in upload servlet", request.getSession()); saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED,
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error processing request in upload servlet"); "An error occurred during upload: " + fileName + ". Error processing request in upload servlet",
request.getSession());
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Error processing request in upload servlet");
return; return;
} }
try { try {
//Removing path from fileName // Removing path from fileName
String itemName = fileName; String itemName = fileName;
//Getting extension // Getting extension
String extension = FilenameUtils.getExtension(itemName); String extension = FilenameUtils.getExtension(itemName);
logger.debug("extension: "+extension); logger.debug("extension: " + extension);
//Getting base name // Getting base name
String baseName = FilenameUtils.getBaseName(itemName); //Using base name in order to avoid Task #12470 String baseName = FilenameUtils.getBaseName(itemName); // Using base name in order to avoid Task #12470
//Task #17152 // Task #17152
extension = extension.isEmpty()?"":"."+extension; extension = extension.isEmpty() ? "" : "." + extension;
itemName = baseName+extension; itemName = baseName + extension;
logger.debug("purged item name is: "+itemName); logger.debug("purged item name is: " + itemName);
//SIZE // SIZE
Long size = getContentLength(request); Long size = getContentLength(request);
logger.debug("size: " + size + " bytes"); logger.debug("size: " + size + " bytes");
//Instancing the progress listener // Instancing the progress listener
final AbstractUploadProgressListener uploadProgressListener = createNewListener(request.getSession(), clientUploadKey); final AbstractUploadProgressListener uploadProgressListener = createNewListener(request.getSession(),
clientUploadKey);
final UploadProgressInputStream inputStream = new UploadProgressInputStream(uploadItem.openStream(), size); final UploadProgressInputStream inputStream = new UploadProgressInputStream(uploadItem.openStream(), size);
inputStream.addListener(uploadProgressListener); inputStream.addListener(uploadProgressListener);
workspaceUploader.setUploadProgress(uploadProgressListener.getUploadProgress()); workspaceUploader.setUploadProgress(uploadProgressListener.getUploadProgress());
saveWorkspaceUploaderInSession(workspaceUploader, request.getSession()); saveWorkspaceUploaderInSession(workspaceUploader, request.getSession());
String contentType = uploadItem.getContentType(); String contentType = uploadItem.getContentType();
logger.debug("Stream content type: "+contentType); logger.debug("Stream content type: " + contentType);
//UPLOAD FILE. IT IS DEFAULT CASE // UPLOAD FILE. IT IS DEFAULT CASE
logger.debug("Uploading file in the TEMP system folder..."); logger.debug("Uploading file in the TEMP system folder...");
workspaceUploader = createStreamToTempFile(request, workspaceUploader, inputStream, user.getUsername(), clientUploadKey, fileName, extension); workspaceUploader = createStreamToTempFile(request, workspaceUploader, inputStream, user.getUsername(),
clientUploadKey, fileName, extension);
saveWorkspaceUploaderInSession(workspaceUploader, request.getSession()); saveWorkspaceUploaderInSession(workspaceUploader, request.getSession());
if(workspaceUploader==null) if (workspaceUploader == null)
throw new Exception("Error when creating uploader, it is null!"); throw new Exception("Error when creating uploader, it is null!");
/* /*
* Incident #10095. Commented OK as response * Incident #10095. Commented OK as response in order to avoid downloading of
* in order to avoid downloading of .dms file by Safari * .dms file by Safari from MAC
* from MAC
*/ */
//sendMessage(response, workspaceUploader.getIdentifier()); // sendMessage(response, workspaceUploader.getIdentifier());
} catch (IOException e){ } catch (IOException e) {
logger.error("Error creating elements, is it cancel?", e); logger.error("Error creating elements, is it cancel?", e);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "Uploading error", request.getSession()); saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "Uploading error",
request.getSession());
sendError(response, "Internal error: An item with that name already exists"); sendError(response, "Internal error: An item with that name already exists");
return; return;
// sendError(response, "Internal error: An item with that name already exists"); // sendError(response, "Internal error: An item with that name already exists");
// return; // return;
}catch (Exception e) { } catch (Exception e) {
logger.error("Error creating elements", e); logger.error("Error creating elements", e);
saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "Uploading error. "+e.getMessage(), request.getSession()); saveWorkspaceUploaderStatus(workspaceUploader, UPLOAD_STATUS.FAILED, "Uploading error. " + e.getMessage(),
request.getSession());
// sendError(response, "Internal error: An error occurred on uploading the file, try again later"); // sendError(response, "Internal error: An error occurred on uploading the file, try again later");
// return; // return;
}finally{ } finally {
//TODO // TODO
removeCurrentListener(request.getSession(), clientUploadKey); removeCurrentListener(request.getSession(), clientUploadKey);
} }
} }
/** /**
* Save workspace uploader status. * Save workspace uploader status.
* *
* @param workspaceUploader the workspace uploader * @param workspaceUploader the workspace uploader
* @param status the status * @param status the status
* @param description the description * @param description the description
* @param session the session * @param session the session
* @return the workspace uploader item * @return the workspace uploader item
*/ */
private synchronized FileUploadingState saveWorkspaceUploaderStatus(FileUploadingState workspaceUploader, UPLOAD_STATUS status, String description, HttpSession session){ private synchronized FileUploadingState saveWorkspaceUploaderStatus(FileUploadingState workspaceUploader,
UPLOAD_STATUS status, String description, HttpSession session) {
workspaceUploader.setUploadStatus(status); workspaceUploader.setUploadStatus(status);
workspaceUploader.setStatusDescription(description); workspaceUploader.setStatusDescription(description);
try { try {
@ -457,20 +496,22 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
return workspaceUploader; return workspaceUploader;
} }
/** /**
* Creates the new workspace uploader. * Creates the new workspace uploader.
* *
* @param clientUploadKey the client upload key * @param clientUploadKey the client upload key
* @param fileName the file name * @param fileName the file name
* @param user the user
* @param formFieldName the form field name
* @return the workspace uploader item * @return the workspace uploader item
*/ */
private FileUploadingState createNewWorkspaceUploader(String clientUploadKey, String fileName, String user){ private FileUploadingState createNewWorkspaceUploader(String clientUploadKey, String fileName, String user,
//CLIENT UPLOAD IS THE KEY String formFieldName) {
// CLIENT UPLOAD IS THE KEY
FileUploadingState workspaceUploader = new FileUploadingState(clientUploadKey); FileUploadingState workspaceUploader = new FileUploadingState(clientUploadKey);
workspaceUploader.setClientUploadKey(clientUploadKey); workspaceUploader.setClientUploadKey(clientUploadKey);
//Create File // Create File
FileUploaded wsUploadFile = new FileUploaded(fileName, null, user); FileUploaded wsUploadFile = new FileUploaded(fileName, null, user, new FilePath(formFieldName));
workspaceUploader.setFile(wsUploadFile); workspaceUploader.setFile(wsUploadFile);
return workspaceUploader; return workspaceUploader;
} }
@ -479,39 +520,43 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
* Save workspace uploader in session. * Save workspace uploader in session.
* *
* @param workspaceUploader the workspace uploader * @param workspaceUploader the workspace uploader
* @param httpSession the http session * @param httpSession the http session
* @return the workspace uploader item * @return the workspace uploader item
* @throws Exception the exception * @throws Exception the exception
*/ */
public static void saveWorkspaceUploaderInSession(FileUploadingState workspaceUploader, HttpSession httpSession) throws Exception { public static void saveWorkspaceUploaderInSession(FileUploadingState workspaceUploader, HttpSession httpSession)
throws Exception {
if(workspaceUploader!=null){ if (workspaceUploader != null) {
try { try {
WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader); WsUtil.putWorkspaceUploaderInSession(httpSession, workspaceUploader);
} catch (Exception e) { } catch (Exception e) {
logger.error("Error during WorkspaceUploaderItem save in session workspace uploader: "+workspaceUploader,e); logger.error(
"Error during WorkspaceUploaderItem save in session workspace uploader: " + workspaceUploader,
e);
throw new Exception("An error occurred in the upload. Try again"); throw new Exception("An error occurred in the upload. Try again");
} }
}else } else
throw new Exception("An error occurred in the upload. Workspace Uploader not found. Abort and try again"); throw new Exception("An error occurred in the upload. Workspace Uploader not found. Abort and try again");
} }
/** /**
* Creates the stream to temp file. * Creates the stream to temp file.
* @param request
* *
* @param request the request
* @param workspaceUploader the workspace uploader * @param workspaceUploader the workspace uploader
* @param in the in * @param in the in
* @param username the username * @param username the username
* @param clientUploadKey the client upload key * @param clientUploadKey the client upload key
* @param fileName the file name * @param fileName the file name
* @param fileExtension the file extension * @param fileExtension the file extension
* @return the workspace uploader item * @return the workspace uploader item
* @throws IOException Signals that an I/O exception has occurred. * @throws IOException Signals that an I/O exception has occurred.
*/ */
public FileUploadingState createStreamToTempFile(HttpServletRequest request, FileUploadingState workspaceUploader, InputStream in, String username, String clientUploadKey, String fileName, String fileExtension) throws IOException{ public FileUploadingState createStreamToTempFile(HttpServletRequest request, FileUploadingState workspaceUploader,
InputStream in, String username, String clientUploadKey, String fileName, String fileExtension)
throws IOException {
if (fileExtension == null) if (fileExtension == null)
fileExtension = ""; fileExtension = "";
if (username == null) if (username == null)
@ -523,8 +568,8 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
String uniqueFileName = String.format("%s_%s", clientUploadKey, fileName); String uniqueFileName = String.format("%s_%s", clientUploadKey, fileName);
File tempFile = File.createTempFile(uniqueFileName, fileExtension); File tempFile = File.createTempFile(uniqueFileName, fileExtension);
tempFile.deleteOnExit(); tempFile.deleteOnExit();
//File tempFile = File.createTempFile(uniqueFileName, fileExtension); // File tempFile = File.createTempFile(uniqueFileName, fileExtension);
//File tempFile = tempFilePath.toFile(); // File tempFile = tempFilePath.toFile();
FileOutputStream out = new FileOutputStream(tempFile); FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out); IOUtils.copy(in, out);
workspaceUploader.getFile().setTempSystemPath(tempFile.getAbsolutePath()); workspaceUploader.getFile().setTempSystemPath(tempFile.getAbsolutePath());
@ -532,110 +577,112 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
workspaceUploader.setUploadStatus(UPLOAD_STATUS.COMPLETED); workspaceUploader.setUploadStatus(UPLOAD_STATUS.COMPLETED);
saveWorkspaceUploaderInSession(workspaceUploader, request.getSession()); saveWorkspaceUploaderInSession(workspaceUploader, request.getSession());
saveFileUplodedInSession(workspaceUploader.getFile(), request.getSession()); saveFileUplodedInSession(workspaceUploader.getFile(), request.getSession());
logger.info("File uploaded at: "+tempFile.getAbsolutePath()); logger.info("File uploaded at: " + tempFile.getAbsolutePath());
}catch (Exception e) { } catch (Exception e) {
workspaceUploader.setStatusDescription("Error on uploading: "+fileName+". "+e.getMessage()); workspaceUploader.setStatusDescription("Error on uploading: " + fileName + ". " + e.getMessage());
workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED); workspaceUploader.setUploadStatus(UPLOAD_STATUS.FAILED);
}finally { } finally {
try { try {
WsUtil.setErasableWorkspaceUploaderInSession(request, workspaceUploader.getIdentifier()); WsUtil.setErasableWorkspaceUploaderInSession(request, workspaceUploader.getIdentifier());
} catch (Exception e2) { } catch (Exception e2) {
logger.error("Error during setErasableWorkspaceUploaderInSession session update: ",e2); logger.error("Error during setErasableWorkspaceUploaderInSession session update: ", e2);
} }
} }
return workspaceUploader; return workspaceUploader;
} }
/** /**
* Save file uploded in session. * Save file uploded in session.
* *
* @param fileUploaded the file uploaded * @param fileUploaded the file uploaded
* @param httpSession the http session * @param httpSession the http session
*/ */
private void saveFileUplodedInSession(FileUploaded fileUploaded, HttpSession httpSession) { private void saveFileUplodedInSession(FileUploaded fileUploaded, HttpSession httpSession) {
if(fileUploaded!=null){ if (fileUploaded != null) {
List<FileUploaded> listFiles = (List<FileUploaded>) httpSession.getAttribute(ConstantsMPFormBuilder.FILE_UPLOADED_SESSION_ATTR); List<FileUploaded> listFiles = (List<FileUploaded>) httpSession
.getAttribute(ConstantsMPFormBuilder.FILE_UPLOADED_SESSION_ATTR);
if(listFiles==null)
if (listFiles == null)
listFiles = new ArrayList<FileUploaded>(); listFiles = new ArrayList<FileUploaded>();
listFiles.add(fileUploaded); listFiles.add(fileUploaded);
httpSession.setAttribute(ConstantsMPFormBuilder.FILE_UPLOADED_SESSION_ATTR, listFiles); httpSession.setAttribute(ConstantsMPFormBuilder.FILE_UPLOADED_SESSION_ATTR, listFiles);
logger.info("Added: "+fileUploaded +" in session"); logger.info("Added: " + fileUploaded + " in session");
} }
} }
//TEST TIME // TEST TIME
/** /**
* Prints the start time. * Prints the start time.
* *
* @return the long * @return the long
*/ */
public static Long printStartTime(){ public static Long printStartTime() {
Long startTime = System.currentTimeMillis(); Long startTime = System.currentTimeMillis();
logger.debug("Start time: "+startTime); logger.debug("Start time: " + startTime);
return startTime; return startTime;
} }
//TEST TIME
// TEST TIME
/** /**
* Prints the elapsed time. * Prints the elapsed time.
* *
* @param startTime the start time * @param startTime the start time
*/ */
public static void printElapsedTime(long startTime){ public static void printElapsedTime(long startTime) {
Long endTime = System.currentTimeMillis() - startTime; Long endTime = System.currentTimeMillis() - startTime;
String time = String.format("%d msc %d sec", endTime, TimeUnit.MILLISECONDS.toSeconds(endTime)); String time = String.format("%d msc %d sec", endTime, TimeUnit.MILLISECONDS.toSeconds(endTime));
logger.debug("Elapsed Time: "+time); logger.debug("Elapsed Time: " + time);
} }
/** /**
* Send error. * Send error.
* *
* @param response the response * @param response the response
* @param message the message * @param message the message
* @throws IOException Signals that an I/O exception has occurred. * @throws IOException Signals that an I/O exception has occurred.
*/ */
protected void sendError(HttpServletResponse response, String message) throws IOException{ protected void sendError(HttpServletResponse response, String message) throws IOException {
try { try {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
HandlerResultMessage resultMessage = HandlerResultMessage.errorResult(message); HandlerResultMessage resultMessage = HandlerResultMessage.errorResult(message);
response.getWriter().write(resultMessage.toString()); response.getWriter().write(resultMessage.toString());
//5.6 Closure of Response Object: // 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 // When a response is closed, the container must immediately flush all remaining
// content in the response buffer to the client
// response.flushBuffer(); // response.flushBuffer();
} catch (IOException e){ } catch (IOException e) {
logger.warn("IOException class name: "+e.getClass().getSimpleName()); logger.warn("IOException class name: " + e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException")) if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage()); logger.warn("Skipping ClientAbortException: " + e.getMessage());
else else
throw e; //Sending Exceptions throw e; // Sending Exceptions
} }
} }
/** /**
* Send session expired. * Send session expired.
* *
* @param response the response * @param response the response
* @param message the message * @param message the message
* @throws IOException Signals that an I/O exception has occurred. * @throws IOException Signals that an I/O exception has occurred.
*/ */
protected void sendSessionExpired(HttpServletResponse response, String message) throws IOException{ protected void sendSessionExpired(HttpServletResponse response, String message) throws IOException {
try { try {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
HandlerResultMessage resultMessage = HandlerResultMessage.sessionExpiredResult(message); HandlerResultMessage resultMessage = HandlerResultMessage.sessionExpiredResult(message);
response.getWriter().write(resultMessage.toString()); response.getWriter().write(resultMessage.toString());
//5.6 Closure of Response Object: // 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 // When a response is closed, the container must immediately flush all remaining
// content in the response buffer to the client
// response.flushBuffer(); // response.flushBuffer();
} catch (IOException e){ } catch (IOException e) {
logger.warn("IOException class name: "+e.getClass().getSimpleName()); logger.warn("IOException class name: " + e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException")) if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage()); logger.warn("Skipping ClientAbortException: " + e.getMessage());
else else
throw e; //Sending Exceptions throw e; // Sending Exceptions
} }
} }
@ -643,24 +690,25 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
* Send message. * Send message.
* *
* @param response the response * @param response the response
* @param message the message * @param message the message
* @throws IOException Signals that an I/O exception has occurred. * @throws IOException Signals that an I/O exception has occurred.
*/ */
protected void sendMessage(HttpServletResponse response, String message) throws IOException{ protected void sendMessage(HttpServletResponse response, String message) throws IOException {
try { try {
response.setStatus(HttpServletResponse.SC_ACCEPTED); response.setStatus(HttpServletResponse.SC_ACCEPTED);
message = message.replaceAll(":", ""); message = message.replaceAll(":", "");
HandlerResultMessage resultMessage = HandlerResultMessage.okResult(message); HandlerResultMessage resultMessage = HandlerResultMessage.okResult(message);
response.getWriter().write(resultMessage.toString()); response.getWriter().write(resultMessage.toString());
//5.6 Closure of Response Object: // 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 // When a response is closed, the container must immediately flush all remaining
// content in the response buffer to the client
// response.flushBuffer(); // response.flushBuffer();
} catch (IOException e){ } catch (IOException e) {
logger.warn("IOException class name: "+e.getClass().getSimpleName()); logger.warn("IOException class name: " + e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException")) if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage()); logger.warn("Skipping ClientAbortException: " + e.getMessage());
else else
throw e; //Sending Exceptions throw e; // Sending Exceptions
} }
} }
@ -668,41 +716,42 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
* Send warn message. * Send warn message.
* *
* @param response the response * @param response the response
* @param message the message * @param message the message
* @throws IOException Signals that an I/O exception has occurred. * @throws IOException Signals that an I/O exception has occurred.
*/ */
protected void sendWarnMessage(HttpServletResponse response, String message) throws IOException{ protected void sendWarnMessage(HttpServletResponse response, String message) throws IOException {
try { try {
response.setStatus(HttpServletResponse.SC_ACCEPTED); response.setStatus(HttpServletResponse.SC_ACCEPTED);
HandlerResultMessage resultMessage = HandlerResultMessage.warnResult(message); HandlerResultMessage resultMessage = HandlerResultMessage.warnResult(message);
response.getWriter().write(resultMessage.toString()); response.getWriter().write(resultMessage.toString());
//5.6 Closure of Response Object: // 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 // When a response is closed, the container must immediately flush all remaining
// content in the response buffer to the client
// response.flushBuffer(); // response.flushBuffer();
} catch (IOException e){ } catch (IOException e) {
logger.warn("IOException class name: "+e.getClass().getSimpleName()); logger.warn("IOException class name: " + e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException")) if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage()); logger.warn("Skipping ClientAbortException: " + e.getMessage());
else else
throw e; //Sending Exceptions throw e; // Sending Exceptions
} }
} }
/** /**
* Mark the current upload process to be canceled. * Mark the current upload process to be canceled.
* *
* @param session the session * @param session the session
* @param clientUploadKey the client upload key * @param clientUploadKey the client upload key
* @return true, if successful * @return true, if successful
*/ */
public boolean cancelUpload(HttpSession session, String clientUploadKey) { public boolean cancelUpload(HttpSession session, String clientUploadKey) {
logger.debug("UPLOAD-SERVLET (" + session.getId()+ ") cancelling Upload: "+clientUploadKey); logger.debug("UPLOAD-SERVLET (" + session.getId() + ") cancelling Upload: " + clientUploadKey);
AbstractUploadProgressListener listener = getCurrentListener(session, clientUploadKey); AbstractUploadProgressListener listener = getCurrentListener(session, clientUploadKey);
if (listener != null && !listener.isCanceled()) { if (listener != null && !listener.isCanceled()) {
logger.info("CancelUpload listener is "+listener.toString()); logger.info("CancelUpload listener is " + listener.toString());
listener.setException(new UploadCanceledException()); listener.setException(new UploadCanceledException());
return true; return true;
}else{ } else {
logger.info("Skipping cancel upload: listener is null or is cancel"); logger.info("Skipping cancel upload: listener is null or is cancel");
return false; return false;
} }
@ -711,7 +760,7 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
/** /**
* Get the listener active in this session. * Get the listener active in this session.
* *
* @param session the session * @param session the session
* @param clientUploadKey the client upload key * @param clientUploadKey the client upload key
* @return the listener active * @return the listener active
*/ */
@ -724,8 +773,8 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
} }
/** /**
* Just a method to detect whether the web container is running with * Just a method to detect whether the web container is running with appengine
* appengine restrictions. * restrictions.
* *
* @return true if the case of the application is running in appengine * @return true if the case of the application is running in appengine
*/ */
@ -736,7 +785,7 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
/** /**
* Create a new listener for this session. * Create a new listener for this session.
* *
* @param session the session * @param session the session
* @param clientUploadKey the client upload key * @param clientUploadKey the client upload key
* @return the appropriate listener * @return the appropriate listener
*/ */
@ -748,7 +797,6 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
} }
} }
/** /**
* Gets the content length. * Gets the content length.
* *
@ -758,8 +806,7 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
private long getContentLength(HttpServletRequest request) { private long getContentLength(HttpServletRequest request) {
long size = -1; long size = -1;
try { try {
size = Long.parseLong(request size = Long.parseLong(request.getHeader(FileUploadBase.CONTENT_LENGTH));
.getHeader(FileUploadBase.CONTENT_LENGTH));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
} }
return size; return size;
@ -768,17 +815,17 @@ public class MetadataProfileFormBuilderUploadServlet extends HttpServlet impleme
/** /**
* Remove the listener active in this session. * Remove the listener active in this session.
* *
* @param session the session * @param session the session
* @param clientUploadKey the client upload key * @param clientUploadKey the client upload key
*/ */
protected void removeCurrentListener(HttpSession session, String clientUploadKey) { protected void removeCurrentListener(HttpSession session, String clientUploadKey) {
logger.debug("RemoveCurrentListener: "+clientUploadKey); logger.debug("RemoveCurrentListener: " + clientUploadKey);
AbstractUploadProgressListener listener = getCurrentListener(session, clientUploadKey); AbstractUploadProgressListener listener = getCurrentListener(session, clientUploadKey);
if (listener != null) { if (listener != null) {
logger.debug("Removing listener: "+listener.getClientUploadKey()); logger.debug("Removing listener: " + listener.getClientUploadKey());
listener.remove(); listener.remove();
}else } else
logger.warn("Listener "+clientUploadKey+ "is null"); logger.warn("Listener " + clientUploadKey + "is null");
} }
} }

View File

@ -1,8 +1,8 @@
package org.gcube.portlets.widgets.mpformbuilder.shared; package org.gcube.portlets.widgets.mpformbuilder.shared;
import java.io.Serializable; import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetaDataProfileBean; import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetaDataProfileBean;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploaded; import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploaded;
@ -25,7 +25,7 @@ public class GenericDatasetBean implements Serializable {
private List<MetaDataProfileBean> metadataProfileList; private List<MetaDataProfileBean> metadataProfileList;
/** The form data entry fields. */ /** The form data entry fields. */
private Map<String, List<String>> formDataEntryFields; private LinkedHashMap<String, List<String>> formDataEntryFields;
/** The files uploaded. */ /** The files uploaded. */
private List<FileUploaded> filesUploaded; private List<FileUploaded> filesUploaded;
@ -44,7 +44,7 @@ public class GenericDatasetBean implements Serializable {
* @param formDataEntryFields the form data entry fields * @param formDataEntryFields the form data entry fields
* @param filesUploaded the files uploaded * @param filesUploaded the files uploaded
*/ */
public GenericDatasetBean(List<MetaDataProfileBean> metadataProfileList, Map<String, List<String>> formDataEntryFields, public GenericDatasetBean(List<MetaDataProfileBean> metadataProfileList, LinkedHashMap<String, List<String>> formDataEntryFields,
List<FileUploaded> filesUploaded) { List<FileUploaded> filesUploaded) {
super(); super();
this.metadataProfileList = metadataProfileList; this.metadataProfileList = metadataProfileList;
@ -78,7 +78,7 @@ public class GenericDatasetBean implements Serializable {
* *
* @return the form data entry fields * @return the form data entry fields
*/ */
public Map<String, List<String>> getFormDataEntryFields() { public LinkedHashMap<String, List<String>> getFormDataEntryFields() {
return formDataEntryFields; return formDataEntryFields;
} }
@ -88,7 +88,7 @@ public class GenericDatasetBean implements Serializable {
* *
* @param formDataEntryFields the form data entry fields * @param formDataEntryFields the form data entry fields
*/ */
public void setFormDataEntryFields(Map<String, List<String>> formDataEntryFields) { public void setFormDataEntryFields(LinkedHashMap<String, List<String>> formDataEntryFields) {
this.formDataEntryFields = formDataEntryFields; this.formDataEntryFields = formDataEntryFields;
} }

View File

@ -3,22 +3,40 @@ package org.gcube.portlets.widgets.mpformbuilder.shared.metadata;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; import java.util.List;
/** /**
* A MetaDataProfileBean with its children (MetaDataType, MetaDataFields, Categories) * The Class MetaDataProfileBean.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) *
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Mar 3, 2022
*/ */
public class MetaDataProfileBean implements Serializable{ public class MetaDataProfileBean implements Serializable{
private static final long serialVersionUID = -7377022025375553568L; /**
*
*/
private static final long serialVersionUID = -8307518917648131477L;
private String type; private String type;
private String title; private String title;
private List<CategoryWrapper> categories; private List<CategoryWrapper> categories;
private List<MetadataFieldWrapper> metadataFields; private List<MetadataFieldWrapper> metadataFields;
/**
* Instantiates a new meta data profile bean.
*/
public MetaDataProfileBean(){ public MetaDataProfileBean(){
super(); super();
} }
/**
* Instantiates a new meta data profile bean.
*
* @param type the type
* @param title the title
* @param metadataFields the metadata fields
* @param categories the categories
*/
public MetaDataProfileBean(String type, public MetaDataProfileBean(String type,
String title, String title,
List<MetadataFieldWrapper> metadataFields, List<MetadataFieldWrapper> metadataFields,
@ -31,43 +49,82 @@ public class MetaDataProfileBean implements Serializable{
} }
/** /**
* Gets the type.
*
* @return the type * @return the type
*/ */
public String getType() { public String getType() {
return type; return type;
} }
/** /**
* Sets the type.
*
* @param type the type to set * @param type the type to set
*/ */
public void setType(String type) { public void setType(String type) {
this.type = type; this.type = type;
} }
/** /**
* Gets the metadata fields.
*
* @return the metadataFields * @return the metadataFields
*/ */
public List<MetadataFieldWrapper> getMetadataFields() { public List<MetadataFieldWrapper> getMetadataFields() {
return metadataFields; return metadataFields;
} }
/** /**
* Sets the metadata fields.
*
* @param metadataFields the metadataFields to set * @param metadataFields the metadataFields to set
*/ */
public void setMetadataFields(List<MetadataFieldWrapper> metadataFields) { public void setMetadataFields(List<MetadataFieldWrapper> metadataFields) {
this.metadataFields = metadataFields; this.metadataFields = metadataFields;
} }
/**
* Gets the categories.
*
* @return the categories
*/
public List<CategoryWrapper> getCategories() { public List<CategoryWrapper> getCategories() {
return categories; return categories;
} }
/**
* Sets the categories.
*
* @param categories the new categories
*/
public void setCategories(List<CategoryWrapper> categories) { public void setCategories(List<CategoryWrapper> categories) {
this.categories = categories; this.categories = categories;
} }
/**
* Gets the title.
*
* @return the title
*/
public String getTitle() { public String getTitle() {
return title; return title;
} }
/**
* Sets the title.
*
* @param title the new title
*/
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }
/**
* To string.
*
* @return the string
*/
@Override @Override
public String toString() { public String toString() {
final int maxLen = 10; final int maxLen = 10;

View File

@ -1,18 +1,19 @@
package org.gcube.portlets.widgets.mpformbuilder.shared.metadata; package org.gcube.portlets.widgets.mpformbuilder.shared.metadata;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; import java.util.List;
/** /**
* The Class MetadataFieldWrapper. * The Class MetadataFieldWrapper.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) *
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
* *
* @author francesco-mangiacrapa at ISTI-CNR (costantino.perciante@isti.cnr.it) * Mar 3, 2022
*/ */
public class MetadataFieldWrapper implements Serializable{ public class MetadataFieldWrapper implements UpdatableField, Serializable {
private static final long serialVersionUID = -8476731365884466698L; private static final long serialVersionUID = -8476731365884466698L;
private String fieldId;
private String fieldName; private String fieldName;
private String fieldNameFromCategory; private String fieldNameFromCategory;
private Boolean mandatory = false; private Boolean mandatory = false;
@ -25,9 +26,11 @@ public class MetadataFieldWrapper implements Serializable{
private CategoryWrapper ownerCategory; private CategoryWrapper ownerCategory;
private FieldAsGroup asGroup; private FieldAsGroup asGroup;
private FieldAsTag asTag; private FieldAsTag asTag;
private Integer maxOccurs = 1; private Integer maxOccurs = 1;
private String currentValue;
/** /**
* Instantiates a new metadata field. * Instantiates a new metadata field.
*/ */
@ -36,22 +39,23 @@ public class MetadataFieldWrapper implements Serializable{
} }
/** /**
* Instantiates a new metadata field. * Instantiates a new metadata field wrapper.
* *
* @param fieldName the field name * @param fieldId the field id (optional) if present is used instead of
* @param mandatory the mandatory * fieldName as result
* @param type the type * @param fieldName the field name
* @param mandatory the mandatory
* @param type the type
* @param defaultValue the default value * @param defaultValue the default value
* @param note the note * @param note the note
* @param vocabulary the vocabulary * @param vocabulary the vocabulary
* @param validator the validator * @param validator the validator
* @param category the category * @param category the category
*/ */
public MetadataFieldWrapper( public MetadataFieldWrapper(String fieldId, String fieldName, Boolean mandatory, DataTypeWrapper type,
String fieldName, Boolean mandatory, DataTypeWrapper type, String defaultValue, String note, List<String> vocabulary, String validator, CategoryWrapper category) {
String defaultValue, String note, List<String> vocabulary,
String validator, CategoryWrapper category) {
super(); super();
this.fieldId = fieldId;
this.fieldName = fieldName; this.fieldName = fieldName;
this.mandatory = mandatory; this.mandatory = mandatory;
this.type = type; this.type = type;
@ -61,8 +65,6 @@ public class MetadataFieldWrapper implements Serializable{
this.validator = validator; this.validator = validator;
this.ownerCategory = category; this.ownerCategory = category;
} }
/** /**
* Gets the max occurs. * Gets the max occurs.
@ -82,10 +84,28 @@ public class MetadataFieldWrapper implements Serializable{
this.maxOccurs = maxOccurs; this.maxOccurs = maxOccurs;
} }
/**
* Gets the field id.
*
* @return the field id
*/
public String getFieldId() {
return fieldId;
}
/**
* Sets the field id.
*
* @param fieldId the new field id
*/
public void setFieldId(String fieldId) {
this.fieldId = fieldId;
}
/** /**
* Gets the field name. * Gets the field name.
* *
* @return the fieldName * @return the serviceFieldName
*/ */
public String getFieldName() { public String getFieldName() {
@ -145,7 +165,7 @@ public class MetadataFieldWrapper implements Serializable{
/** /**
* Sets the field name. * Sets the field name.
* *
* @param fieldName the fieldName to set * @param fieldName the new field name
*/ */
public void setFieldName(String fieldName) { public void setFieldName(String fieldName) {
@ -310,30 +330,62 @@ public class MetadataFieldWrapper implements Serializable{
this.asTag = asTag; this.asTag = asTag;
} }
/* (non-Javadoc) /**
* @see java.lang.Object#toString() * Sets the current value.
*
* @param value the new current value
*/ */
@Override public void setCurrentValue(String value) {
public String toString() { this.currentValue = value;
return "MetadataFieldWrapper ["
+ (fieldName != null ? "fieldName=" + fieldName + ", " : "")
+ (fieldNameFromCategory != null ? "fieldNameFromCategory="
+ fieldNameFromCategory + ", " : "")
+ (mandatory != null ? "mandatory=" + mandatory + ", " : "")
+ (maxOccurs != null ? "maxOccurs=" + maxOccurs + ", " : "")
+ (type != null ? "type=" + type + ", " : "")
+ (defaultValue != null ? "defaultValue=" + defaultValue + ", "
: "")
+ (note != null ? "note=" + note + ", " : "")
+ (vocabulary != null ? "vocabulary=" + vocabulary + ", " : "")
+ "multiSelection="
+ multiSelection
+ ", "
+ (validator != null ? "validator=" + validator + ", " : "")
+ (ownerCategory != null ? "ownerCategory=" + ownerCategory.getId()
+ ", " : "")
+ (asGroup != null ? "asGroup=" + asGroup + ", " : "")
+ (asTag != null ? "asTag=" + asTag : "") + "]";
} }
/**
* Gets the current value.
*
* @return the current value
*/
public String getCurrentValue() {
return currentValue;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("MetadataFieldWrapper [fieldId=");
builder.append(fieldId);
builder.append(", fieldName=");
builder.append(fieldName);
builder.append(", fieldNameFromCategory=");
builder.append(fieldNameFromCategory);
builder.append(", mandatory=");
builder.append(mandatory);
builder.append(", type=");
builder.append(type);
builder.append(", defaultValue=");
builder.append(defaultValue);
builder.append(", note=");
builder.append(note);
builder.append(", vocabulary=");
builder.append(vocabulary);
builder.append(", multiSelection=");
builder.append(multiSelection);
builder.append(", validator=");
builder.append(validator);
builder.append(", ownerCategory=");
builder.append(ownerCategory);
builder.append(", asGroup=");
builder.append(asGroup);
builder.append(", asTag=");
builder.append(asTag);
builder.append(", maxOccurs=");
builder.append(maxOccurs);
builder.append(", currentValue=");
builder.append(currentValue);
builder.append("]");
return builder.toString();
}
} }

View File

@ -0,0 +1,8 @@
package org.gcube.portlets.widgets.mpformbuilder.shared.metadata;
public interface UpdatableField {
void setCurrentValue(String value);
String getCurrentValue();
}

View File

@ -0,0 +1,67 @@
package org.gcube.portlets.widgets.mpformbuilder.shared.upload;
import java.io.Serializable;
/**
* The Class FilePath.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Mar 21, 2022
*/
public class FilePath implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5321133561716734223L;
String formFieldLabel; // is the gcubeProfileFieldName in the UCD of Geoportal
/**
* Instantiates a new file paths.
*/
public FilePath() {
}
/**
* Instantiates a new file path.
*
* @param formFieldLabel the form field label
*/
public FilePath(String formFieldLabel) {
this.formFieldLabel = formFieldLabel;
}
/**
* Gets the form field label.
*
* @return the form field label
*/
public String getFormFieldLabel() {
return formFieldLabel;
}
/**
* Sets the form field label.
*
* @param formFieldLabel the new form field label
*/
public void setFormFieldLabel(String formFieldLabel) {
this.formFieldLabel = formFieldLabel;
}
/**
* To string.
*
* @return the string
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("FilePath [formFieldLabel=");
builder.append(formFieldLabel);
builder.append("]");
return builder.toString();
}
}

View File

@ -7,49 +7,50 @@ import java.io.Serializable;
import com.google.gwt.user.client.rpc.IsSerializable; import com.google.gwt.user.client.rpc.IsSerializable;
/** /**
* The Class FileUploaded. * The Class FileUploaded.
* *
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* *
* Oct 8, 2020 * Oct 8, 2020
*/ */
public class FileUploaded implements Serializable, IsSerializable{ public class FileUploaded implements Serializable, IsSerializable {
/** /**
* *
*/ */
private static final long serialVersionUID = -7869956386977214114L; private static final long serialVersionUID = -6666006742990360875L;
/** The file name. */ /** The file name. */
private String fileName; private String fileName;
/** The item id. */ /** The item id. */
private String tempSystemPath; private String tempSystemPath;
private String createdByUser; private String createdByUser;
private FilePath filePath;
/** /**
* Instantiates a new workspace upload file. * Instantiates a new workspace upload file.
*/ */
public FileUploaded() { public FileUploaded() {
} }
/** /**
* Instantiates a new workspace upload file. * Instantiates a new file uploaded.
* *
* @param fileName the file name * @param fileName the file name
* @param tempSystemPath the temp system path * @param tempSystemPath the temp system path
* @param createdByUser the created by user * @param createdByUser the created by user
* @param filePath the file path
*/ */
public FileUploaded(String fileName, String tempSystemPath, String createdByUser) { public FileUploaded(String fileName, String tempSystemPath, String createdByUser, FilePath filePath) {
super(); super();
this.fileName = fileName; this.fileName = fileName;
this.tempSystemPath = tempSystemPath; this.tempSystemPath = tempSystemPath;
this.createdByUser = createdByUser; this.createdByUser = createdByUser;
this.filePath = filePath;
} }
/** /**
@ -61,8 +62,6 @@ public class FileUploaded implements Serializable, IsSerializable{
return fileName; return fileName;
} }
/** /**
* Sets the file name. * Sets the file name.
* *
@ -72,8 +71,6 @@ public class FileUploaded implements Serializable, IsSerializable{
this.fileName = fileName; this.fileName = fileName;
} }
/** /**
* Gets the temp system path. * Gets the temp system path.
* *
@ -83,8 +80,6 @@ public class FileUploaded implements Serializable, IsSerializable{
return tempSystemPath; return tempSystemPath;
} }
/** /**
* Sets the temp system path. * Sets the temp system path.
* *
@ -94,8 +89,6 @@ public class FileUploaded implements Serializable, IsSerializable{
this.tempSystemPath = tempSystemPath; this.tempSystemPath = tempSystemPath;
} }
/** /**
* Gets the created by user. * Gets the created by user.
* *
@ -105,8 +98,6 @@ public class FileUploaded implements Serializable, IsSerializable{
return createdByUser; return createdByUser;
} }
/** /**
* Sets the created by user. * Sets the created by user.
* *
@ -116,7 +107,29 @@ public class FileUploaded implements Serializable, IsSerializable{
this.createdByUser = createdByUser; this.createdByUser = createdByUser;
} }
/**
* Gets the file paths.
*
* @return the file paths
*/
public FilePath getFilePath() {
return filePath;
}
/**
* Sets the file paths.
*
* @param filePaths the new file paths
*/
public void setFilePaths(FilePath filePaths) {
this.filePath = filePaths;
}
/**
* To string.
*
* @return the string
*/
@Override @Override
public String toString() { public String toString() {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
@ -126,8 +139,10 @@ public class FileUploaded implements Serializable, IsSerializable{
builder.append(tempSystemPath); builder.append(tempSystemPath);
builder.append(", createdByUser="); builder.append(", createdByUser=");
builder.append(createdByUser); builder.append(createdByUser);
builder.append(", filePath=");
builder.append(filePath);
builder.append("]"); builder.append("]");
return builder.toString(); return builder.toString();
} }
} }