diff --git a/.classpath b/.classpath index c4c69e5..4042bcb 100644 --- a/.classpath +++ b/.classpath @@ -1,6 +1,6 @@ - + @@ -31,5 +31,5 @@ - + diff --git a/.settings/com.google.gdt.eclipse.core.prefs b/.settings/com.google.gdt.eclipse.core.prefs index 290a082..dff39ab 100644 --- a/.settings/com.google.gdt.eclipse.core.prefs +++ b/.settings/com.google.gdt.eclipse.core.prefs @@ -2,6 +2,6 @@ <<<<<<<=.mine >>>>>>>=.r71295 eclipse.preferences.version=1 -lastWarOutDir=/Users/massi/Documents/workspace/reports/target/reports-4.8.1-SNAPSHOT +lastWarOutDir=/Users/massi/Documents/workspace/reports/target/reports-4.8.2-SNAPSHOT warSrcDir=src/main/webapp warSrcDirIsOutput=false diff --git a/pom.xml b/pom.xml index 3f7d500..2e2cf59 100644 --- a/pom.xml +++ b/pom.xml @@ -12,7 +12,7 @@ org.gcube.portlets.user reports war - 4.8.1-SNAPSHOT + 4.8.3-SNAPSHOT gCube Reports Manager gCube Reports Portlet. @@ -60,7 +60,8 @@ org.gcube.distribution maven-portal-bom - LATEST + + 1.4.0-SNAPSHOT pom import @@ -110,6 +111,12 @@ custom-portal-handler ${setScope} + + org.gcube.common.portal + portal-manager + [1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT) + ${setScope} + com.sencha.gxt gxt @@ -128,7 +135,13 @@ org.gcube.application.rsg reports-store-gateway-client - [0.0.3-SNAPSHOT, 1.0.0-SNAPSHOT) + [1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT) + + + el-api + javax.el + + org.jboss.weld diff --git a/src/main/java/org/gcube/portlets/user/reportgenerator/client/Presenter/Presenter.java b/src/main/java/org/gcube/portlets/user/reportgenerator/client/Presenter/Presenter.java index 83447d8..f3302f8 100644 --- a/src/main/java/org/gcube/portlets/user/reportgenerator/client/Presenter/Presenter.java +++ b/src/main/java/org/gcube/portlets/user/reportgenerator/client/Presenter/Presenter.java @@ -67,6 +67,8 @@ import org.gcube.portlets.widgets.exporter.client.event.ReportExporterEventHandl import org.gcube.portlets.widgets.exporter.shared.TypeExporter; import org.gcube.portlets.widgets.fileupload.client.events.FileUploadCompleteEvent; import org.gcube.portlets.widgets.fileupload.client.events.FileUploadCompleteEventHandler; +import org.gcube.portlets.widgets.fileupload.client.events.FileUploadSelectedEvent; +import org.gcube.portlets.widgets.fileupload.client.events.FileUploadSelectedEventHandler; import org.gcube.portlets.widgets.fileupload.client.view.UploadProgressDialog; import com.extjs.gxt.ui.client.widget.MessageBox; @@ -112,10 +114,10 @@ public class Presenter { private UserBean currentUser; private String currentScope; - + private ClientImage selectedImage; - - + + /** * Model @@ -159,7 +161,28 @@ public class Presenter { private void handleEvents() { - + /** + * get the uploaded selected file name before submitting it + */ + eventBus.addHandler(FileUploadSelectedEvent.TYPE, new FileUploadSelectedEventHandler() { + @Override + public void onFileSelected(FileUploadSelectedEvent event) { + String fileName = event.getSelectedFileName(); + GWT.log("selected file name: " + fileName); + if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png") + || fileName.endsWith(".gif") || fileName.endsWith(".bmp") || fileName.endsWith(".d4sR")) { + try { + uploadDlg.submitForm(); + } catch (Exception e) { + e.printStackTrace(); + } + } + else { + Window.alert("File type not allowed"); + uploadDlg.hide(); + } + } + }); /** * get the uploaded file result */ @@ -286,1169 +309,1177 @@ public class Presenter { } }); - } - - - /** - * constructor - */ - public Presenter() { - model = new TemplateModel(this); - - titleBar = ReportGenerator.get().getTitleHeader(); - dlg.center(); - dlg.show(); - handleEvents(); - AsyncCallback callback = new AsyncCallback() { - public void onFailure(Throwable caught) {} - - public void onSuccess(final SessionInfo sessionInfo) { - currentUser = sessionInfo.getUsername(); - currentScope = sessionInfo.getScope(); - isVME = sessionInfo.isVME(); - addTextToolBar(true); - if (sessionInfo.isWorkflowDocument()) { - model.getModelService().getWorkflowDocumentFromDocumentLibrary(new AsyncCallback() { - - public void onFailure(Throwable caught) { - dlg.hide(); - } - - public void onSuccess(Model wfReport) { - dlg.hide(); - loadModel(wfReport, true); - header.setMenuForWorkflowDocument(sessionInfo.isEditable()); - titleBar.addWorkflowButtons(true); - pollServiceForLockRenewal(); - } - }); - } - else { //not in workflow mode check if a report was open - model.getModelService().readTemplateFromSession(new AsyncCallback() { - public void onFailure(Throwable caught) { - dlg.hide(); - } - public void onSuccess(Model result) { - if (isVME) { - header.setMenuForVME(); - header.enableExports(); - } - dlg.hide(); - if (result != null) { //there was one report open in session - loadModel(result, true); - header.enableExports(); - } else{ - commonCommands.newTemplate.execute(); - } - } - }); - } - } - }; - - model.getModelService().getSessionInfo(getHost(), callback); - commonCommands = new CommonCommands(this); - //importDlg = new FimesFileUploadWindow(eventBus); - } - - public void setClientSequenceSelected(ClientSequence toSet) { - this.clientSeqSelected = toSet; - } - - public void showOpenOptions() { - wp.showOpenOptions(isVME); - } - - public void showLoading() { - wp.showLoading(); - } - - /** - * load the template to edit in the MODEL and in the VIEW - * @param templateToOpen the name of the template to open without extension nor path - * @param templateObjectID the id in the folder of the template to open - * @param isTemplate true if you are opening a template false if you are opening a report - */ - public void openTemplate(String templateToOpen, String templateObjectID, final boolean isTemplate) { - showLoading(); - //will asyncrously return a Serializable Model instance read from disk - model.getModelService().readModel(templateToOpen, templateObjectID, isTemplate, false, new AsyncCallback() { - @Override - public void onSuccess(Model toLoad) { - if (toLoad != null) - loadModel(toLoad, true); - else - Window.alert("Could not Load template, error on server: "); - } - @Override - public void onFailure(Throwable caught) { - Window.alert("Could not Load template, please try again later: " + caught.getMessage()); - - } - }); - } - - /** - * called when a citation is added - * @param citekey . - * @param text . - */ - public void addCitation(String citekey, String text) { - if (! hasBibliography()) { - MessageBox.alert("Warning", "Bibliography will be added as last section of this report", null); - model.insertBiblioSection(); } - model.addCitation(citekey, text); - titleBar.getSectionSwitchPanel().setPageDisplayer(model.getCurrentPage(), model.getTotalPages()); - } - public boolean removeCitation(String citekey) { - boolean toReturn = model.removeCitation(citekey); - if (toReturn) { //if has been removed from the model - if (model.getCurrentPage() == model.getTotalPages()) { //if the view is displaying the bibliography, need to refresh it - seekSection(model.getTotalPages()); - } - } - return toReturn; - } - /** - * look if a section with a specific metadata (that indicate sit is a biblio section) - * exists in the current report model: - * check whether the last section has Metadata "isBiblio" = "true" or false - * @return true if bibliography is present yet false otherwise - */ - public boolean hasBibliography() { - for (Metadata metadata : model.getSection(model.getTotalPages()).getAllMetadata()) - if (metadata.getAttribute().equals(TemplateModel.BIBLIO_SECTION)) return true; - return false; - } - /** - * look if a comment with a specific metadata (that indicate sit is a comment) - * exists in the current report model: - * @return true if comment is present yet false otherwise - */ - public boolean hasComments(Widget toCheck) { - TemplateSection currSection = model.getSection(model.getCurrentPage()); - return currSection.hasComments(toCheck); - } - /** - * look if a comment with a specific metadata (that indicate sit is a comment) - * exists in the current report model: - * @return true if comment is present yet false otherwise - */ - public AddCommentEvent getComponentComments(Widget toCheck) { - TemplateSection currSection = model.getSection(model.getCurrentPage()); - return currSection.getComponentComments(toCheck); - } - /** - * - */ - private void pollServiceForLockRenewal() { - final int fourteenMinutes = 840000; - final Timer t = new Timer() { - public void run() { - model.getModelService().renewLock(new AsyncCallback() { - public void onFailure(Throwable caught) { - } - public void onSuccess(Void result) { - schedule(fourteenMinutes); - } - }); - } - }; - t.schedule(fourteenMinutes); - } - /** - * put the commands in the hashmap - */ - private HashMap getCommands() { /** - * commands to pass to the toolbar + * constructor */ - HashMap toReturn = new HashMap(); + public Presenter() { + model = new TemplateModel(this); - toReturn.put("structureView", commonCommands.structureView); - toReturn.put("save", commonCommands.saveTemplate); - toReturn.put("exportRSG", commonCommands.exportToRSG); - toReturn.put("newdoc", commonCommands.newTemplate); - toReturn.put("open_report", commonCommands.openReport); - toReturn.put("open_template", commonCommands.openTemplate); - toReturn.put("importing", commonCommands.importTemplateCommand); - toReturn.put("insertImage", commonCommands.insertImage); - toReturn.put("pickColor", commonCommands.pickColor); + titleBar = ReportGenerator.get().getTitleHeader(); + dlg.center(); + dlg.show(); + handleEvents(); + AsyncCallback callback = new AsyncCallback() { + public void onFailure(Throwable caught) {} - return toReturn; + public void onSuccess(final SessionInfo sessionInfo) { + currentUser = sessionInfo.getUsername(); + currentScope = sessionInfo.getScope(); + isVME = sessionInfo.isVME(); + addTextToolBar(true); + if (sessionInfo.isWorkflowDocument()) { + model.getModelService().getWorkflowDocumentFromDocumentLibrary(new AsyncCallback() { - } + public void onFailure(Throwable caught) { + dlg.hide(); + } - /** - * to remove the current displayed section - */ - public void discardCurrentSection() { - if (model.getTotalPages() == 1) - Window.alert("Cannot discard section, need ad least 2"); - else { - boolean result = Window.confirm("Are you sure you want to discard section number " + model.getCurrentPage() + "?"); - if (result) { - TemplateSection removed = model.discardSection(model.getCurrentPage()); - if (removed == null) - GWT.log("REMOVED NOTHING", null); - else - GWT.log("REMOVED " + removed.getAllComponents().size(), null); - loadFirstSection(); - } + public void onSuccess(Model wfReport) { + dlg.hide(); + loadModel(wfReport, true); + header.setMenuForWorkflowDocument(sessionInfo.isEditable()); + titleBar.addWorkflowButtons(true); + pollServiceForLockRenewal(); + } + }); + } + else { //not in workflow mode check if a report was open + model.getModelService().readTemplateFromSession(new AsyncCallback() { + public void onFailure(Throwable caught) { + dlg.hide(); + } + public void onSuccess(Model result) { + if (isVME) { + header.setMenuForVME(); + header.enableExports(); + } + dlg.hide(); + if (result != null) { //there was one report open in session + loadModel(result, true); + header.enableExports(); + } else{ + commonCommands.newTemplate.execute(); + } + } + }); + } + } + }; + + model.getModelService().getSessionInfo(getHost(), callback); + commonCommands = new CommonCommands(this); + //importDlg = new FimesFileUploadWindow(eventBus); + } + + public void setClientSequenceSelected(ClientSequence toSet) { + this.clientSeqSelected = toSet; } - } - /** - * - * @param titleBar , - */ - public void setTitleBar(TitleBar titleBar) { - this.titleBar = titleBar; - } - /** - * - * @return . - */ - public String getHost() { - return GWT.getHostPageBaseURL() + "../../"; - } - - /** - * remove the user-added components from the workspace, and from the model - * - */ - public void cleanAll() { - // reset the model - model = new TemplateModel(this); - - //reset the UI - - //give the new model instance - header.setModel(model); - wp.setModel(model); - - cleanWorkspace(); - titleBar.getSectionSwitchPanel().hideNextButton(); - titleBar.getSectionSwitchPanel().hidePrevButton(); - titleBar.setTemplateName(model.getTemplateName()); - titleBar.getSectionSwitchPanel().setPageDisplayer(model.getCurrentPage(), model.getTotalPages()); - titleBar.getSectionSwitchPanel().setVisible(false); - resizeWorkingArea(model.getPageWidth(), model.getPageHeight()); - - toolBoxPanel.clear(); - toolBoxPanel.collapse(); - - } - /** - * remove the user-added components from the workspace (in the current page) but not from the model - * - */ - public void cleanWorkspace() { - wp.getMainLayout().clear(); - ReportGenerator.get().getScrollerPanel().setScrollPosition(0); - } - - - /** - * Save the current report - * @param folderid the id where to save the report - * - */ - public void saveReport(String folderid, String name) { - dlg.center(); - dlg.show(); - Model toSave = model.getSerializableModel(); - reportService.saveReport(toSave, folderid, name, new AsyncCallback() { - public void onFailure(Throwable caught) { - dlg.hide(); - MessageBox.alert("Warning","Report Not Saved: " + caught.getMessage(), null); - } - public void onSuccess(Void result) { - dlg.hide(); - MessageBox.info("Saving Operation","Report Saved Successfully", null); - refreshWorkspace(); - } - }); - - } - /** - * Save the current report in a given folder - * - */ - public void saveReport() { - dlg.center(); - dlg.show(); - Model toSave = model.getSerializableModel(); - reportService.saveReport(toSave, new AsyncCallback() { - public void onFailure(Throwable caught) { - dlg.hide(); - MessageBox.alert("Warning","Report Not Saved: " + caught.getMessage(), null); - } - public void onSuccess(Void result) { - dlg.hide(); - MessageBox.info("Saving Operation","Report Saved Successfully", null); - refreshWorkspace(); - } - }); - } - - /** - * Save the current report in a given folder - * - */ - public void updateWorkflowDocument(boolean update) { - dlg.center(); - dlg.show(); - Model toSave = model.getSerializableModel(); - reportService.updateWorkflowDocument(toSave, update, new AsyncCallback() { - - public void onFailure(Throwable caught) { - dlg.hide(); - Window.alert("failed to update workflow document"); - } - public void onSuccess(Void result) { - dlg.hide(); - loadWorkflowLibraryApp(); - } - }); - } - - /** - * - *@param templateName . - */ - public void changeTemplateName(String templateName) { - //initialize the template - titleBar.setTemplateName(templateName); - } - - /** - * Redirect to VRE Deployer Portlet - */ - private void loadWorkflowLibraryApp(){ - getUrl(); - location += "/../my-workflow-documents"; - Window.open(location, "_self", ""); - } - /** - * Get URL from browser - */ - public native void getUrl()/*-{ - this.@org.gcube.portlets.user.reportgenerator.client.Presenter.Presenter::location = $wnd.location.href; - }-*/; - - /** - * Import a Section in the View and in the Model - * @param toLoad the SerializableModel instance where toget the section - * @param sectionNoToimport section to import 0 -> n-1 - * @param beforeSection say where to import this section (before) - * @param asLastSection say to import this section as last section in the curren template / report - */ - public void importSection(Model toLoad, int sectionNoToimport, int beforeSection, boolean asLastSection) { - model.importSectionInModel(toLoad, sectionNoToimport, beforeSection, asLastSection); - if (asLastSection) - seekLastPage(); - else - seekSection(beforeSection); - Window.alert("Importing Complete"); - } - - /** - * in case someone imported a new section - */ - public void seekLastPage() { - while (! (model.getCurrentPage() == model.getTotalPages()) ) - nextPageButtonClicked(); - } - - /** - * in case someone imported a new section - * @param sect2Seek . - */ - public void seekSection(int sect2Seek) { - loadFirstSection(); - while (! ( model.getCurrentPage() == sect2Seek) ) - nextPageButtonClicked(); - } - /** - * - */ - public void addTextToolBar(boolean enableCommands) { - RichTextToolbar rtbar = new RichTextToolbar(new RichTextArea(), getCommands(), isVME); - rtbar.enableCommands(enableCommands); - - currentSelectedToolbar = rtbar; - SimplePanel deco = new SimplePanel(); - rtbar.setEnabled(false); - deco.add(rtbar); - deco.setSize("100%", "25"); - rtbar.setWidth("100%"); - ReportGenerator.get().getToolbarPanel().clear(); - ReportGenerator.get().getToolbarPanel().add(deco); - } - /** - * enable the format text toolbar for the given Rich Textarea passed as argument - * @param d4sArea the enabled text area - */ - public void enableTextToolBar(RichTextArea d4sArea) { - - RichTextToolbar rtbar = new RichTextToolbar(d4sArea, getCommands(), isVME); - if (menuForWorkflowDocument) //disable open and save buttons from the toolbar - rtbar.enableCommands(false); - currentSelectedToolbar = rtbar; - rtbar.setEnabled(true); - ReportGenerator.get().getToolbarPanel().clear(); - SimplePanel deco = new SimplePanel(); - deco.add(rtbar); - deco.setSize("100%", "25"); - rtbar.setWidth("100%"); - ReportGenerator.get().getToolbarPanel().add(deco); - } - - /** - * enable the format text toolbar for the given Rich Textarea passed as argument - * @param d4sArea the enabled text area - */ - public void enableBiblioEntry(RichTextArea d4sArea) { - ReportGenerator.get().getHeader().enableBiblioEntry(d4sArea); - } - - /** - * generate the docx to be passed to the fimesExporter - * @param model - */ - public void generateFiMES(final TemplateModel model) { - } - /** - * - * @param model . - * @param type . - */ - public void generateManifestation(final TemplateModel model, final ExportManifestationType type) { - GWT.runAsync(ReportExporterPopup.class, new RunAsyncCallback() { - - @SuppressWarnings("incomplete-switch") - @Override - public void onSuccess() { - ReportExporterPopup popup = new ReportExporterPopup(eventBus); - Model reportModel = model.getSerializableModel(); - switch (type) { - case DOCX: - popup.export(reportModel, TypeExporter.DOCX); - break; - case HTML: - popup.export(reportModel, TypeExporter.HTML); - break; - case PDF: - popup.export(reportModel, TypeExporter.PDF); - break; - case XML: - popup.export(reportModel, TypeExporter.XML); - break; - } - } - - @Override - public void onFailure(Throwable reason) { - } - }); - - } - - - - public void openAddCitationDialog() { - AddBiblioEntryDialog dlg = new AddBiblioEntryDialog(eventBus); - dlg.show(); - } - - public void openManageCitationsDialog() { - DeleteCitationsDialog dlg = new DeleteCitationsDialog(eventBus, model.getSection(model.getTotalPages())); - dlg.show(); - } - - /** - * - * @return . - */ - public Headerbar getHeader() { - return header; - } - - - /** - * - * @return . - */ - public TemplateModel getModel() { - return model; - } - - /** - * - * @return . - */ - public ToolboxPanel getToolBoxPanel() { - return toolBoxPanel; - } - - /** - * - * @return . - */ - public WorkspacePanel getWp() { - return wp; - } - - /** - * called when nextPage Button is Clicked - */ - public void nextPageButtonClicked() { - cleanWorkspace(); - //refresh the current page in the model - model.setCurrentPage(model.getCurrentPage() + 1); - - //refresh the current page in the UI - titleBar.getSectionSwitchPanel().setPageDisplayer(model.getCurrentPage(), model.getTotalPages()); - - //read the previous user added elements to the template page from the model and place them back in the UI - placeTemplatePageElements(model.getCurrentPage()); - - if (model.getCurrentPage() == model.getTotalPages()) - titleBar.getSectionSwitchPanel().hideNextButton(); - else - titleBar.getSectionSwitchPanel().showNextButton(); - - if (model.getCurrentPage() == 1) - titleBar.getSectionSwitchPanel().hidePrevButton(); - else - titleBar.getSectionSwitchPanel().showPrevButton(); - } - - /** - * - * @param toLoad - */ - private void loadModel(Model toLoad, boolean savingEnabled) { - //reset the UI - cleanAllNotSession(); - - //load the serializable model in my Model - model.loadModel(toLoad, this); - - wp.setModel(model); - - titleBar.setTemplateName(model.getTemplateName()); - titleBar.getSectionSwitchPanel().setPageDisplayer(model.getCurrentPage(), model.getTotalPages()); - titleBar.getSectionSwitchPanel().setVisible(true); - resizeWorkingArea(model.getPageWidth(), model.getPageHeight()); - - addTextToolBar(savingEnabled); - int currPage = model.getCurrentPage(); - //load the UI components of the current page - GWT.log("READ CURR PAGE"+currPage, null); - placeTemplatePageElements(currPage); - - //if there is more than one page place in the UI the next page button - if (currPage < model.getTotalPages()) { - titleBar.getSectionSwitchPanel().showNextButton(); + public void showOpenOptions() { + wp.showOpenOptions(isVME); } - if (currPage > 1) - titleBar.getSectionSwitchPanel().showPrevButton(); - if (isShowingStructure) - showStructure(); - - } - - /** - * just clean the page - */ - public void cleanAllNotSession() { - // reset the model - model = new TemplateModel(this); - - //reset the UI - - //give the new model instance - header.setModel(model); - wp.setModel(model); - - cleanWorkspace(); - titleBar.getSectionSwitchPanel().hideNextButton(); - titleBar.getSectionSwitchPanel().hidePrevButton(); - titleBar.setTemplateName(model.getTemplateName()); - titleBar.getSectionSwitchPanel().setPageDisplayer(model.getCurrentPage(), model.getTotalPages()); - titleBar.getSectionSwitchPanel().setVisible(false); - resizeWorkingArea(model.getPageWidth(), model.getPageHeight()); - } - - private void loadFirstSection() { - //reset the UI - cleanWorkspace(); - titleBar.getSectionSwitchPanel().hideNextButton(); - titleBar.getSectionSwitchPanel().hidePrevButton(); - model.setCurrentPage(1); - - - titleBar.setTemplateName(model.getTemplateName()); - titleBar.getSectionSwitchPanel().setPageDisplayer(model.getCurrentPage(), model.getTotalPages()); - titleBar.getSectionSwitchPanel().setVisible(true); - addTextToolBar(true); - int currPage = model.getCurrentPage(); - //load the UI components of the current page - GWT.log("READ CURR PAGE"+currPage, null); - placeTemplatePageElements(currPage); - - //if there is more than one page place in the UI the next page button - if (currPage < model.getTotalPages()) { - titleBar.getSectionSwitchPanel().showNextButton(); + public void showLoading() { + wp.showLoading(); } - if (currPage > 1) - titleBar.getSectionSwitchPanel().showPrevButton(); - } + /** + * load the template to edit in the MODEL and in the VIEW + * @param templateToOpen the name of the template to open without extension nor path + * @param templateObjectID the id in the folder of the template to open + * @param isTemplate true if you are opening a template false if you are opening a report + */ + public void openTemplate(String templateToOpen, String templateObjectID, final boolean isTemplate) { + showLoading(); + //will asyncrously return a Serializable Model instance read from disk + model.getModelService().readModel(templateToOpen, templateObjectID, isTemplate, false, new AsyncCallback() { + @Override + public void onSuccess(Model toLoad) { + if (toLoad != null) + loadModel(toLoad, true); + else + Window.alert("Could not Load template, error on server: "); + } + @Override + public void onFailure(Throwable caught) { + Window.alert("Could not Load template, please try again later: " + caught.getMessage()); - /** - * It places back the user added widgets (TemplateComponents) in the page - * - * @param section . the section number of the wanted TemplateComponent(s) - */ + } + }); + } - public void placeTemplatePageElements(int section) { - if (! (model.getSectionComponent(section) == null)) { - List pageElems = model.getSectionComponent(section); + /** + * called when a citation is added + * @param citekey . + * @param text . + */ + public void addCitation(String citekey, String text) { + if (! hasBibliography()) { + MessageBox.alert("Warning", "Bibliography will be added as last section of this report", null); + model.insertBiblioSection(); + } + model.addCitation(citekey, text); + titleBar.getSectionSwitchPanel().setPageDisplayer(model.getCurrentPage(), model.getTotalPages()); + } - for (TemplateComponent component : pageElems) { - int uiX = component.getX(); - int uiY= component.getY(); - switch (component.getType()) { - case HEADING_1: - case HEADING_2: - case HEADING_3: - case HEADING_4: - case HEADING_5: - case TITLE: - if (component.isLocked()) { - HTML text = (HTML) component.getContent(); - wp.addComponentToLayout(text, component.isDoubleColLayout()); - } - else { - HeadingTextArea textArea = (HeadingTextArea) component.getContent(); - textArea.getMyInstance().setTop(uiY); - textArea.getMyInstance().setLeft(uiX); - wp.addComponentToLayout(textArea, component.isDoubleColLayout()); - } + public boolean removeCitation(String citekey) { + boolean toReturn = model.removeCitation(citekey); + if (toReturn) { //if has been removed from the model + if (model.getCurrentPage() == model.getTotalPages()) { //if the view is displaying the bibliography, need to refresh it + seekSection(model.getTotalPages()); + } + } + return toReturn; + } - break; - case BODY_NOT_FORMATTED: - if (component.isLocked()) { - HTML text = (HTML) component.getContent(); - text.addStyleName("readOnlyText"); - wp.addComponentToLayout(text, component.isDoubleColLayout()); - } - else { - BasicTextArea textArea = (BasicTextArea) component.getContent(); - wp.addComponentToLayout(textArea, component.isDoubleColLayout()); - } + /** + * look if a section with a specific metadata (that indicate sit is a biblio section) + * exists in the current report model: + * check whether the last section has Metadata "isBiblio" = "true" or false + * @return true if bibliography is present yet false otherwise + */ + public boolean hasBibliography() { + for (Metadata metadata : model.getSection(model.getTotalPages()).getAllMetadata()) + if (metadata.getAttribute().equals(TemplateModel.BIBLIO_SECTION)) return true; + return false; + } + /** + * look if a comment with a specific metadata (that indicate sit is a comment) + * exists in the current report model: + * @return true if comment is present yet false otherwise + */ + public boolean hasComments(Widget toCheck) { + TemplateSection currSection = model.getSection(model.getCurrentPage()); + return currSection.hasComments(toCheck); + } + /** + * look if a comment with a specific metadata (that indicate sit is a comment) + * exists in the current report model: + * @return true if comment is present yet false otherwise + */ + public AddCommentEvent getComponentComments(Widget toCheck) { + TemplateSection currSection = model.getSection(model.getCurrentPage()); + return currSection.getComponentComments(toCheck); + } + /** + * + */ + private void pollServiceForLockRenewal() { + final int fourteenMinutes = 840000; + final Timer t = new Timer() { + public void run() { + model.getModelService().renewLock(new AsyncCallback() { + public void onFailure(Throwable caught) { + } + public void onSuccess(Void result) { + schedule(fourteenMinutes); + } + }); + } + }; + t.schedule(fourteenMinutes); + } + /** + * put the commands in the hashmap + */ + private HashMap getCommands() { + /** + * commands to pass to the toolbar + */ + HashMap toReturn = new HashMap(); - break; - case BODY: - if (component.isLocked()) { - HTML text = (HTML) component.getContent(); - wp.addComponentToLayout(text, component.isDoubleColLayout()); - } - else { - D4sRichTextarea textArea = (D4sRichTextarea) component.getContent(); - textArea.getMyInstance().setTop(uiY); - textArea.getMyInstance().setLeft(uiX); - wp.addComponentToLayout(textArea, component.isDoubleColLayout()); - } + toReturn.put("structureView", commonCommands.structureView); + toReturn.put("save", commonCommands.saveTemplate); + toReturn.put("exportRSG", commonCommands.exportToRSG); + toReturn.put("newdoc", commonCommands.newTemplate); + toReturn.put("open_report", commonCommands.openReport); + toReturn.put("open_template", commonCommands.openTemplate); + toReturn.put("importing", commonCommands.importTemplateCommand); + toReturn.put("insertImage", commonCommands.insertImage); + toReturn.put("pickColor", commonCommands.pickColor); - break; - case DYNA_IMAGE: - ClientImage imageDropping = (ClientImage) component.getContent(); - wp.addComponentToLayout(imageDropping, component.isDoubleColLayout()); - break; - case FAKE_TEXTAREA: - break; - case TOC: - ReportTextArea dp = (ReportTextArea) component.getContent(); - wp.addComponentToLayout(dp, component.isDoubleColLayout()); - setCurrCursorPos(uiY); - break; - case BIBLIO: - ReportTextArea dp2 = (ReportTextArea) component.getContent(); - wp.addComponentToLayout(dp2, component.isDoubleColLayout()); - setCurrCursorPos(uiY); - break; - case PAGEBREAK: - ReportTextArea dp3 = (ReportTextArea) component.getContent(); - wp.addComponentToLayout(dp3, component.isDoubleColLayout()); - setCurrCursorPos(uiY); - break; - case TIME_SERIES: - break; - case FLEX_TABLE: - GenericTable gt = (GenericTable) component.getContent(); - GWT.log("Reading TABLE rows: " + gt.getRowsNo() + " cols: " + gt.getCols()); - wp.addComponentToLayout(gt, component.isDoubleColLayout()); - break; - case ATTRIBUTE_MULTI: - AttributeMultiSelection at = (AttributeMultiSelection) component.getContent(); - wp.addComponentToLayout(at, component.isDoubleColLayout()); - setCurrCursorPos(uiY); - break; - case ATTRIBUTE_UNIQUE: - AttributeSingleSelection atu = (AttributeSingleSelection) component.getContent(); - wp.addComponentToLayout(atu, component.isDoubleColLayout()); - setCurrCursorPos(uiY); - break; - case COMMENT: - HTML text = (HTML) component.getContent(); - wp.addComponentToLayout(text, component.isDoubleColLayout()); - break; - case INSTRUCTION: - HTML instr = (HTML) component.getContent(); - wp.addComponentToLayout(instr, component.isDoubleColLayout()); - break; - case REPEAT_SEQUENCE_DELIMITER: - GroupingDelimiterArea gpa = (GroupingDelimiterArea) component.getContent(); - wp.addComponentToLayout(gpa, component.isDoubleColLayout()); - break; - case REPEAT_SEQUENCE: - ClientRepeatableSequence rps = (ClientRepeatableSequence) component.getContent(); - wp.addComponentToLayout(rps, component.isDoubleColLayout()); - break; - case REPORT_REFERENCE: - ClientReportReference cmSeq = (ClientReportReference) component.getContent(); - wp.addComponentToLayout(cmSeq, component.isDoubleColLayout()); - break; - case BODY_TABLE_IMAGE: - TextTableImage tti = (TextTableImage) component.getContent(); - wp.addComponentToLayout(tti, component.isDoubleColLayout()); - break; + return toReturn; + + } + + /** + * to remove the current displayed section + */ + public void discardCurrentSection() { + if (model.getTotalPages() == 1) + Window.alert("Cannot discard section, need ad least 2"); + else { + boolean result = Window.confirm("Are you sure you want to discard section number " + model.getCurrentPage() + "?"); + if (result) { + TemplateSection removed = model.discardSection(model.getCurrentPage()); + if (removed == null) + GWT.log("REMOVED NOTHING", null); + else + GWT.log("REMOVED " + removed.getAllComponents().size(), null); + loadFirstSection(); } } } - } - - /** - * - * @param y . - */ - public void setCurrCursorPos(int y) { - this.currFocus = y; - } - public Coords getInsertionPoint() { - int y = getSelectedIndex(); - return new Coords(25, y); - } - public int getSelectedIndex() { - return currFocus; - } - /** - * called when prevPage Button is Clicked - */ - - public void prevPageButtonClicked() { - cleanWorkspace(); - //refresh the current page in the model - model.setCurrentPage(model.getCurrentPage() - 1); - - //refresh the current page in the UI - titleBar.getSectionSwitchPanel().setPageDisplayer(model.getCurrentPage(), model.getTotalPages()); - - //read the previous user added elements to the template page from the model and place them back in the UI - placeTemplatePageElements(model.getCurrentPage()); - - if (model.getCurrentPage() == model.getTotalPages()) - titleBar.getSectionSwitchPanel().hideNextButton(); - else - titleBar.getSectionSwitchPanel().showNextButton(); - - if (model.getCurrentPage() == 1) - titleBar.getSectionSwitchPanel().hidePrevButton(); - else - titleBar.getSectionSwitchPanel().showPrevButton(); - } - - /** - * Resize the template componet just the model - * - * @param toResize . - * @param newWidth . - * @param newHeight . - */ - public void resizeTemplateComponentInModel(Widget toResize, int newWidth, int newHeight) { - model.resizeModelComponent(toResize, newWidth, newHeight); - } - - /** - * @param width . - * @param height . - */ - public void resizeWorkingArea(int width, int height) { - //save the new state ---> TO MODEL - model.setPageWidth(width); - model.setPageHeight(height); - - //apply the change ---> TO VIEW - wp.resizeWorkspace(width, height); - } - /** - * - * @param header . - */ - public void setHeader(Headerbar header) { - this.header = header; - } - /** - * - * @param toolBoxPanel It's the tool box panel - */ - public void setToolBoxPanel(ToolboxPanel toolBoxPanel) { - this.toolBoxPanel = toolBoxPanel; - } - /** - * - * @param wp . - */ - public void setWp(WorkspacePanel wp) { - this.wp = wp; - } - /** - * - * @return the scope in which the application is running on - */ - public String getCurrentScope() { - return currentScope; - } - - /** - * - * @return the user username who is using the application - */ - public UserBean getCurrentUser() { - return currentUser; - } - - /** - * - * @return . - */ - public TitleBar getTitleBar() { - return titleBar; - } - /** - * refresh the root in the workspace - */ - public void refreshWorkspace() { - toolBoxPanel.refreshRoot(); - } - /** - * show the upload file popup - */ - public void showUploadFilePopup(ClientImage selectedImage) { - uploadDlg = new UploadProgressDialog("Upload Image", eventBus); - uploadDlg.center(); - uploadDlg.show(); - this.selectedImage = selectedImage; - } - /** - * - * @return the current selected rich text area - */ - public RichTextToolbar getCurrentSelected() { - return currentSelectedToolbar; - } - - public void setMenuForWorkflowDocument(boolean enable) { - menuForWorkflowDocument = enable; - } - - public boolean getMenuForWorkflowDocument() { - return menuForWorkflowDocument; - } - - public void setAreaForBiblio(RichTextArea d4sArea) { - areaForBiblio = d4sArea; - } - - /** - * show/hide the structure view - */ - - public void toggleReportStructure() { - if (!isShowingStructure) { - showStructure(); - isShowingStructure = true; + /** + * + * @param titleBar , + */ + public void setTitleBar(TitleBar titleBar) { + this.titleBar = titleBar; } - else { + /** + * + * @return . + */ + public String getHost() { + return GWT.getHostPageBaseURL() + "../../"; + } + + + /** + * remove the user-added components from the workspace, and from the model + * + */ + public void cleanAll() { + // reset the model + model = new TemplateModel(this); + + //reset the UI + + //give the new model instance + header.setModel(model); + wp.setModel(model); + + cleanWorkspace(); + titleBar.getSectionSwitchPanel().hideNextButton(); + titleBar.getSectionSwitchPanel().hidePrevButton(); + titleBar.setTemplateName(model.getTemplateName()); + titleBar.getSectionSwitchPanel().setPageDisplayer(model.getCurrentPage(), model.getTotalPages()); + titleBar.getSectionSwitchPanel().setVisible(false); + resizeWorkingArea(model.getPageWidth(), model.getPageHeight()); + + toolBoxPanel.clear(); toolBoxPanel.collapse(); - isShowingStructure = false; + } - } - - private void showStructure() { - toolBoxPanel.showStructure(new ReportStructurePanel(eventBus, model.getSerializableModel(), ToolboxPanel.TOOLBOX_WIDTH+"px", ToolboxPanel.TOOLBOX_HEIGHT+"px")); - - } - - public HorizontalPanel getExportsPanel() { - return exportsPanel; - } - - - public void setExportsPanel(HorizontalPanel exportsPanel) { - this.exportsPanel = exportsPanel; - } - - /** - * when export is done this method is called - * @param filePath - * @param itemName - * @param type - */ - public void showExportSaveOptions(final String filePath, final String itemName, final TypeExporter type) { - clearExportPanel(); - /* - * I need to save a temp file, in case the user uses the Save & Open. - * Smart popup blockers will allow a popup if it is directly associated to a user’s action. - * If it’s delayed in anyway, there’s a good chance it’s going to get blocked. The exported File needs to be there when clicking open. + /** + * remove the user-added components from the workspace (in the current page) but not from the model + * */ - reportService.save(filePath, null, "system.tmp", type, true, new AsyncCallback() { - @Override - public void onSuccess(String createdItemId) { - //here i pass the temp createdItemId - showExportPanel(filePath, itemName, type, createdItemId); - } + public void cleanWorkspace() { + wp.getMainLayout().clear(); + ReportGenerator.get().getScrollerPanel().setScrollPosition(0); + } - @Override - public void onFailure(Throwable caught) { - Window.alert("Error while trying exporting this report: " + caught.getMessage()); - } - }); - } - - public void showExportPanel(final String filePath, final String itemName, final TypeExporter type, String tempFileId) { - final ExportOptions exo = new ExportOptions(this, toolBoxPanel, filePath, itemName, type, reportService, tempFileId); - exportsPanel.add(exo); - //needed for applying the css3 transition effect - final Timer t = new Timer() { - @Override - public void run() { - exo.getMainPanel().addStyleName("exportPanel-show"); - } - }; - t.schedule(10); - } - - public void clearExportPanel() { - exportsPanel.clear(); - } - - public void newDoc() { - changeTemplateName(TemplateModel.DEFAULT_NAME); - cleanAll(); - showOpenOptions(); - } - - /** - * - */ - public void showVMEImportDialog() { - SelectVMEReportDialog dlg = new SelectVMEReportDialog(getEventBus(), VMETypeIdentifier.Vme, Action.SELECT); - dlg.show(); - } - - /** - * - */ - public void showVMEReportRefImportDialog(VMETypeIdentifier refType) { - SelectVMEReportDialog dlg = new SelectVMEReportDialog(getEventBus(), refType, Action.SELECT); - dlg.show(); - } - /** - * - */ - public void showVMERefAssociateDialog(VMETypeIdentifier refType) { - SelectVMEReportDialog dlg = new SelectVMEReportDialog(getEventBus(), refType, Action.ASSOCIATE); - dlg.show(); - } - /** - * - */ - public void showVMEDeleteDialog(VMETypeIdentifier refType) { - SelectVMEReportDialog dlg = new SelectVMEReportDialog(getEventBus(), refType, Action.DELETE); - dlg.show(); - } - - public void importVMETemplate(final VMETypeIdentifier type) { - showLoading(); - reportService.importVMETemplate(type, new AsyncCallback() { - @Override - public void onFailure(Throwable caught) { - Window.alert("Could not Load Template Model, error on server.: " + caught.getMessage()); - } - - @Override - public void onSuccess(Model toLoad) { - if (toLoad != null) { - loadModel(toLoad, type == VMETypeIdentifier.Vme); - currentVmeType = type; - } - else - Window.alert("Could not Load Template Model, error on server."); - } - }); - - } - /** - * Export To the Reports Store Gateway - * - */ - public void exportReportToRSG() { - if (Window.confirm("Are you sure you want to commit the " + model.getTemplateName() + " into the VME Database?")) { + /** + * Save the current report + * @param folderid the id where to save the report + * + */ + public void saveReport(String folderid, String name) { dlg.center(); dlg.show(); Model toSave = model.getSerializableModel(); - reportService.exportReportToRSG(currentVmeType, toSave, new AsyncCallback() { + reportService.saveReport(toSave, folderid, name, new AsyncCallback() { public void onFailure(Throwable caught) { dlg.hide(); - MessageBox.alert("Warning","Report Not Exported: " + caught.getMessage(), null); + MessageBox.alert("Warning","Report Not Saved: " + caught.getMessage(), null); } - public void onSuccess(VmeExportResponse response) { + public void onSuccess(Void result) { dlg.hide(); - //write ok - if (response.isGloballySucceded()) { - MessageBox.info("Exporting to RSG Operation","Report Exported Successfully", null); + MessageBox.info("Saving Operation","Report Saved Successfully", null); + refreshWorkspace(); + } + }); + + } + /** + * Save the current report in a given folder + * + */ + public void saveReport() { + dlg.center(); + dlg.show(); + Model toSave = model.getSerializableModel(); + reportService.saveReport(toSave, new AsyncCallback() { + public void onFailure(Throwable caught) { + dlg.hide(); + MessageBox.alert("Warning","Report Not Saved: " + caught.getMessage(), null); + } + public void onSuccess(Void result) { + dlg.hide(); + MessageBox.info("Saving Operation","Report Saved Successfully", null); + refreshWorkspace(); + } + }); + } + + /** + * Save the current report in a given folder + * + */ + public void updateWorkflowDocument(boolean update) { + dlg.center(); + dlg.show(); + Model toSave = model.getSerializableModel(); + reportService.updateWorkflowDocument(toSave, update, new AsyncCallback() { + + public void onFailure(Throwable caught) { + dlg.hide(); + Window.alert("failed to update workflow document"); + } + public void onSuccess(Void result) { + dlg.hide(); + loadWorkflowLibraryApp(); + } + }); + } + + /** + * + *@param templateName . + */ + public void changeTemplateName(String templateName) { + //initialize the template + titleBar.setTemplateName(templateName); + } + + /** + * Redirect to VRE Deployer Portlet + */ + private void loadWorkflowLibraryApp(){ + getUrl(); + location += "/../my-workflow-documents"; + Window.open(location, "_self", ""); + } + /** + * Get URL from browser + */ + public native void getUrl()/*-{ + this.@org.gcube.portlets.user.reportgenerator.client.Presenter.Presenter::location = $wnd.location.href; + }-*/; + + /** + * Import a Section in the View and in the Model + * @param toLoad the SerializableModel instance where toget the section + * @param sectionNoToimport section to import 0 -> n-1 + * @param beforeSection say where to import this section (before) + * @param asLastSection say to import this section as last section in the curren template / report + */ + public void importSection(Model toLoad, int sectionNoToimport, int beforeSection, boolean asLastSection) { + model.importSectionInModel(toLoad, sectionNoToimport, beforeSection, asLastSection); + if (asLastSection) + seekLastPage(); + else + seekSection(beforeSection); + Window.alert("Importing Complete"); + } + + /** + * in case someone imported a new section + */ + public void seekLastPage() { + while (! (model.getCurrentPage() == model.getTotalPages()) ) + nextPageButtonClicked(); + } + + /** + * in case someone imported a new section + * @param sect2Seek . + */ + public void seekSection(int sect2Seek) { + loadFirstSection(); + while (! ( model.getCurrentPage() == sect2Seek) ) + nextPageButtonClicked(); + } + /** + * + */ + public void addTextToolBar(boolean enableCommands) { + RichTextToolbar rtbar = new RichTextToolbar(new RichTextArea(), getCommands(), isVME); + rtbar.enableCommands(enableCommands); + + currentSelectedToolbar = rtbar; + SimplePanel deco = new SimplePanel(); + rtbar.setEnabled(false); + deco.add(rtbar); + deco.setSize("100%", "25"); + rtbar.setWidth("100%"); + ReportGenerator.get().getToolbarPanel().clear(); + ReportGenerator.get().getToolbarPanel().add(deco); + } + /** + * enable the format text toolbar for the given Rich Textarea passed as argument + * @param d4sArea the enabled text area + */ + public void enableTextToolBar(RichTextArea d4sArea) { + + RichTextToolbar rtbar = new RichTextToolbar(d4sArea, getCommands(), isVME); + if (menuForWorkflowDocument) //disable open and save buttons from the toolbar + rtbar.enableCommands(false); + currentSelectedToolbar = rtbar; + rtbar.setEnabled(true); + ReportGenerator.get().getToolbarPanel().clear(); + SimplePanel deco = new SimplePanel(); + deco.add(rtbar); + deco.setSize("100%", "25"); + rtbar.setWidth("100%"); + ReportGenerator.get().getToolbarPanel().add(deco); + } + + /** + * enable the format text toolbar for the given Rich Textarea passed as argument + * @param d4sArea the enabled text area + */ + public void enableBiblioEntry(RichTextArea d4sArea) { + ReportGenerator.get().getHeader().enableBiblioEntry(d4sArea); + } + + /** + * generate the docx to be passed to the fimesExporter + * @param model + */ + public void generateFiMES(final TemplateModel model) { + } + /** + * + * @param model . + * @param type . + */ + public void generateManifestation(final TemplateModel model, final ExportManifestationType type) { + GWT.runAsync(ReportExporterPopup.class, new RunAsyncCallback() { + + @SuppressWarnings("incomplete-switch") + @Override + public void onSuccess() { + ReportExporterPopup popup = new ReportExporterPopup(eventBus); + Model reportModel = model.getSerializableModel(); + switch (type) { + case DOCX: + popup.export(reportModel, TypeExporter.DOCX); + break; + case HTML: + popup.export(reportModel, TypeExporter.HTML); + break; + case PDF: + popup.export(reportModel, TypeExporter.PDF); + break; + case XML: + popup.export(reportModel, TypeExporter.XML); + break; + } + } + + @Override + public void onFailure(Throwable reason) { + } + }); + + } + + + + public void openAddCitationDialog() { + AddBiblioEntryDialog dlg = new AddBiblioEntryDialog(eventBus); + dlg.show(); + } + + public void openManageCitationsDialog() { + DeleteCitationsDialog dlg = new DeleteCitationsDialog(eventBus, model.getSection(model.getTotalPages())); + dlg.show(); + } + + /** + * + * @return . + */ + public Headerbar getHeader() { + return header; + } + + + /** + * + * @return . + */ + public TemplateModel getModel() { + return model; + } + + /** + * + * @return . + */ + public ToolboxPanel getToolBoxPanel() { + return toolBoxPanel; + } + + /** + * + * @return . + */ + public WorkspacePanel getWp() { + return wp; + } + + /** + * called when nextPage Button is Clicked + */ + public void nextPageButtonClicked() { + cleanWorkspace(); + //refresh the current page in the model + model.setCurrentPage(model.getCurrentPage() + 1); + + //refresh the current page in the UI + titleBar.getSectionSwitchPanel().setPageDisplayer(model.getCurrentPage(), model.getTotalPages()); + + //read the previous user added elements to the template page from the model and place them back in the UI + placeTemplatePageElements(model.getCurrentPage()); + + if (model.getCurrentPage() == model.getTotalPages()) + titleBar.getSectionSwitchPanel().hideNextButton(); + else + titleBar.getSectionSwitchPanel().showNextButton(); + + if (model.getCurrentPage() == 1) + titleBar.getSectionSwitchPanel().hidePrevButton(); + else + titleBar.getSectionSwitchPanel().showPrevButton(); + } + + /** + * + * @param toLoad + */ + private void loadModel(Model toLoad, boolean savingEnabled) { + //reset the UI + cleanAllNotSession(); + + //load the serializable model in my Model + model.loadModel(toLoad, this); + + wp.setModel(model); + + titleBar.setTemplateName(model.getTemplateName()); + titleBar.getSectionSwitchPanel().setPageDisplayer(model.getCurrentPage(), model.getTotalPages()); + titleBar.getSectionSwitchPanel().setVisible(true); + resizeWorkingArea(model.getPageWidth(), model.getPageHeight()); + + addTextToolBar(savingEnabled); + int currPage = model.getCurrentPage(); + //load the UI components of the current page + GWT.log("READ CURR PAGE"+currPage, null); + placeTemplatePageElements(currPage); + + //if there is more than one page place in the UI the next page button + if (currPage < model.getTotalPages()) { + titleBar.getSectionSwitchPanel().showNextButton(); + } + if (currPage > 1) + titleBar.getSectionSwitchPanel().showPrevButton(); + + if (isShowingStructure) + showStructure(); + + } + + /** + * just clean the page + */ + public void cleanAllNotSession() { + // reset the model + model = new TemplateModel(this); + + //reset the UI + + //give the new model instance + header.setModel(model); + wp.setModel(model); + + cleanWorkspace(); + titleBar.getSectionSwitchPanel().hideNextButton(); + titleBar.getSectionSwitchPanel().hidePrevButton(); + titleBar.setTemplateName(model.getTemplateName()); + titleBar.getSectionSwitchPanel().setPageDisplayer(model.getCurrentPage(), model.getTotalPages()); + titleBar.getSectionSwitchPanel().setVisible(false); + resizeWorkingArea(model.getPageWidth(), model.getPageHeight()); + } + + private void loadFirstSection() { + //reset the UI + cleanWorkspace(); + titleBar.getSectionSwitchPanel().hideNextButton(); + titleBar.getSectionSwitchPanel().hidePrevButton(); + model.setCurrentPage(1); + + + titleBar.setTemplateName(model.getTemplateName()); + titleBar.getSectionSwitchPanel().setPageDisplayer(model.getCurrentPage(), model.getTotalPages()); + titleBar.getSectionSwitchPanel().setVisible(true); + addTextToolBar(true); + int currPage = model.getCurrentPage(); + //load the UI components of the current page + GWT.log("READ CURR PAGE"+currPage, null); + placeTemplatePageElements(currPage); + + //if there is more than one page place in the UI the next page button + if (currPage < model.getTotalPages()) { + titleBar.getSectionSwitchPanel().showNextButton(); + } + if (currPage > 1) + titleBar.getSectionSwitchPanel().showPrevButton(); + + } + + /** + * It places back the user added widgets (TemplateComponents) in the page + * + * @param section . the section number of the wanted TemplateComponent(s) + */ + + public void placeTemplatePageElements(int section) { + if (! (model.getSectionComponent(section) == null)) { + List pageElems = model.getSectionComponent(section); + + for (TemplateComponent component : pageElems) { + int uiX = component.getX(); + int uiY= component.getY(); + switch (component.getType()) { + case HEADING_1: + case HEADING_2: + case HEADING_3: + case HEADING_4: + case HEADING_5: + case TITLE: + if (component.isLocked()) { + HTML text = (HTML) component.getContent(); + wp.addComponentToLayout(text, component.isDoubleColLayout()); + } + else { + HeadingTextArea textArea = (HeadingTextArea) component.getContent(); + textArea.getMyInstance().setTop(uiY); + textArea.getMyInstance().setLeft(uiX); + wp.addComponentToLayout(textArea, component.isDoubleColLayout()); + } + + break; + case BODY_NOT_FORMATTED: + if (component.isLocked()) { + HTML text = (HTML) component.getContent(); + text.addStyleName("readOnlyText"); + wp.addComponentToLayout(text, component.isDoubleColLayout()); + } + else { + BasicTextArea textArea = (BasicTextArea) component.getContent(); + wp.addComponentToLayout(textArea, component.isDoubleColLayout()); + } + + break; + case BODY: + if (component.isLocked()) { + HTML text = (HTML) component.getContent(); + wp.addComponentToLayout(text, component.isDoubleColLayout()); + } + else { + D4sRichTextarea textArea = (D4sRichTextarea) component.getContent(); + textArea.getMyInstance().setTop(uiY); + textArea.getMyInstance().setLeft(uiX); + wp.addComponentToLayout(textArea, component.isDoubleColLayout()); + } + + break; + case DYNA_IMAGE: + ClientImage imageDropping = (ClientImage) component.getContent(); + wp.addComponentToLayout(imageDropping, component.isDoubleColLayout()); + break; + case FAKE_TEXTAREA: + break; + case TOC: + ReportTextArea dp = (ReportTextArea) component.getContent(); + wp.addComponentToLayout(dp, component.isDoubleColLayout()); + setCurrCursorPos(uiY); + break; + case BIBLIO: + ReportTextArea dp2 = (ReportTextArea) component.getContent(); + wp.addComponentToLayout(dp2, component.isDoubleColLayout()); + setCurrCursorPos(uiY); + break; + case PAGEBREAK: + ReportTextArea dp3 = (ReportTextArea) component.getContent(); + wp.addComponentToLayout(dp3, component.isDoubleColLayout()); + setCurrCursorPos(uiY); + break; + case TIME_SERIES: + break; + case FLEX_TABLE: + GenericTable gt = (GenericTable) component.getContent(); + GWT.log("Reading TABLE rows: " + gt.getRowsNo() + " cols: " + gt.getCols()); + wp.addComponentToLayout(gt, component.isDoubleColLayout()); + break; + case ATTRIBUTE_MULTI: + AttributeMultiSelection at = (AttributeMultiSelection) component.getContent(); + wp.addComponentToLayout(at, component.isDoubleColLayout()); + setCurrCursorPos(uiY); + break; + case ATTRIBUTE_UNIQUE: + AttributeSingleSelection atu = (AttributeSingleSelection) component.getContent(); + wp.addComponentToLayout(atu, component.isDoubleColLayout()); + setCurrCursorPos(uiY); + break; + case COMMENT: + HTML text = (HTML) component.getContent(); + wp.addComponentToLayout(text, component.isDoubleColLayout()); + break; + case INSTRUCTION: + HTML instr = (HTML) component.getContent(); + wp.addComponentToLayout(instr, component.isDoubleColLayout()); + break; + case REPEAT_SEQUENCE_DELIMITER: + GroupingDelimiterArea gpa = (GroupingDelimiterArea) component.getContent(); + wp.addComponentToLayout(gpa, component.isDoubleColLayout()); + break; + case REPEAT_SEQUENCE: + ClientRepeatableSequence rps = (ClientRepeatableSequence) component.getContent(); + wp.addComponentToLayout(rps, component.isDoubleColLayout()); + break; + case REPORT_REFERENCE: + ClientReportReference cmSeq = (ClientReportReference) component.getContent(); + wp.addComponentToLayout(cmSeq, component.isDoubleColLayout()); + break; + case BODY_TABLE_IMAGE: + TextTableImage tti = (TextTableImage) component.getContent(); + wp.addComponentToLayout(tti, component.isDoubleColLayout()); + break; + } + } + } + } + + /** + * + * @param y . + */ + public void setCurrCursorPos(int y) { + this.currFocus = y; + } + public Coords getInsertionPoint() { + int y = getSelectedIndex(); + return new Coords(25, y); + } + public int getSelectedIndex() { + return currFocus; + } + /** + * called when prevPage Button is Clicked + */ + + public void prevPageButtonClicked() { + cleanWorkspace(); + //refresh the current page in the model + model.setCurrentPage(model.getCurrentPage() - 1); + + //refresh the current page in the UI + titleBar.getSectionSwitchPanel().setPageDisplayer(model.getCurrentPage(), model.getTotalPages()); + + //read the previous user added elements to the template page from the model and place them back in the UI + placeTemplatePageElements(model.getCurrentPage()); + + if (model.getCurrentPage() == model.getTotalPages()) + titleBar.getSectionSwitchPanel().hideNextButton(); + else + titleBar.getSectionSwitchPanel().showNextButton(); + + if (model.getCurrentPage() == 1) + titleBar.getSectionSwitchPanel().hidePrevButton(); + else + titleBar.getSectionSwitchPanel().showPrevButton(); + } + + /** + * Resize the template componet just the model + * + * @param toResize . + * @param newWidth . + * @param newHeight . + */ + public void resizeTemplateComponentInModel(Widget toResize, int newWidth, int newHeight) { + model.resizeModelComponent(toResize, newWidth, newHeight); + } + + /** + * @param width . + * @param height . + */ + public void resizeWorkingArea(int width, int height) { + //save the new state ---> TO MODEL + model.setPageWidth(width); + model.setPageHeight(height); + + //apply the change ---> TO VIEW + wp.resizeWorkspace(width, height); + } + /** + * + * @param header . + */ + public void setHeader(Headerbar header) { + this.header = header; + } + /** + * + * @param toolBoxPanel It's the tool box panel + */ + public void setToolBoxPanel(ToolboxPanel toolBoxPanel) { + this.toolBoxPanel = toolBoxPanel; + } + /** + * + * @param wp . + */ + public void setWp(WorkspacePanel wp) { + this.wp = wp; + } + /** + * + * @return the scope in which the application is running on + */ + public String getCurrentScope() { + return currentScope; + } + + /** + * + * @return the user username who is using the application + */ + public UserBean getCurrentUser() { + return currentUser; + } + + /** + * + * @return . + */ + public TitleBar getTitleBar() { + return titleBar; + } + /** + * refresh the root in the workspace + */ + public void refreshWorkspace() { + toolBoxPanel.refreshRoot(); + } + /** + * show the upload file popup + */ + public void showUploadImagePopup(ClientImage selectedImage) { + uploadDlg = new UploadProgressDialog("Upload Image", eventBus, true); + uploadDlg.center(); + uploadDlg.show(); + this.selectedImage = selectedImage; + } + /** + * show the upload file popup + */ + public void showUploadFilePopup() { + uploadDlg = new UploadProgressDialog("Upload Report", eventBus); + uploadDlg.center(); + uploadDlg.show(); + } + /** + * + * @return the current selected rich text area + */ + public RichTextToolbar getCurrentSelected() { + return currentSelectedToolbar; + } + + public void setMenuForWorkflowDocument(boolean enable) { + menuForWorkflowDocument = enable; + } + + public boolean getMenuForWorkflowDocument() { + return menuForWorkflowDocument; + } + + public void setAreaForBiblio(RichTextArea d4sArea) { + areaForBiblio = d4sArea; + } + + /** + * show/hide the structure view + */ + + public void toggleReportStructure() { + if (!isShowingStructure) { + showStructure(); + isShowingStructure = true; + } + else { + toolBoxPanel.collapse(); + isShowingStructure = false; + } + } + + private void showStructure() { + toolBoxPanel.showStructure(new ReportStructurePanel(eventBus, model.getSerializableModel(), ToolboxPanel.TOOLBOX_WIDTH+"px", ToolboxPanel.TOOLBOX_HEIGHT+"px")); + + } + + public HorizontalPanel getExportsPanel() { + return exportsPanel; + } + + + public void setExportsPanel(HorizontalPanel exportsPanel) { + this.exportsPanel = exportsPanel; + } + + /** + * when export is done this method is called + * @param filePath + * @param itemName + * @param type + */ + public void showExportSaveOptions(final String filePath, final String itemName, final TypeExporter type) { + clearExportPanel(); + /* + * I need to save a temp file, in case the user uses the Save & Open. + * Smart popup blockers will allow a popup if it is directly associated to a user’s action. + * If it’s delayed in anyway, there’s a good chance it’s going to get blocked. The exported File needs to be there when clicking open. + */ + reportService.save(filePath, null, "system.tmp", type, true, new AsyncCallback() { + @Override + public void onSuccess(String createdItemId) { + //here i pass the temp createdItemId + showExportPanel(filePath, itemName, type, createdItemId); + } + + @Override + public void onFailure(Throwable caught) { + Window.alert("Error while trying exporting this report: " + caught.getMessage()); + } + }); + + } + + public void showExportPanel(final String filePath, final String itemName, final TypeExporter type, String tempFileId) { + final ExportOptions exo = new ExportOptions(this, toolBoxPanel, filePath, itemName, type, reportService, tempFileId); + exportsPanel.add(exo); + //needed for applying the css3 transition effect + final Timer t = new Timer() { + @Override + public void run() { + exo.getMainPanel().addStyleName("exportPanel-show"); + } + }; + t.schedule(10); + } + + public void clearExportPanel() { + exportsPanel.clear(); + } + + public void newDoc() { + changeTemplateName(TemplateModel.DEFAULT_NAME); + cleanAll(); + showOpenOptions(); + } + + /** + * + */ + public void showVMEImportDialog() { + SelectVMEReportDialog dlg = new SelectVMEReportDialog(getEventBus(), VMETypeIdentifier.Vme, Action.SELECT); + dlg.show(); + } + + /** + * + */ + public void showVMEReportRefImportDialog(VMETypeIdentifier refType) { + SelectVMEReportDialog dlg = new SelectVMEReportDialog(getEventBus(), refType, Action.SELECT); + dlg.show(); + } + /** + * + */ + public void showVMERefAssociateDialog(VMETypeIdentifier refType) { + SelectVMEReportDialog dlg = new SelectVMEReportDialog(getEventBus(), refType, Action.ASSOCIATE); + dlg.show(); + } + /** + * + */ + public void showVMEDeleteDialog(VMETypeIdentifier refType) { + SelectVMEReportDialog dlg = new SelectVMEReportDialog(getEventBus(), refType, Action.DELETE); + dlg.show(); + } + + public void importVMETemplate(final VMETypeIdentifier type) { + showLoading(); + reportService.importVMETemplate(type, new AsyncCallback() { + @Override + public void onFailure(Throwable caught) { + Window.alert("Could not Load Template Model, error on server.: " + caught.getMessage()); + } + + @Override + public void onSuccess(Model toLoad) { + if (toLoad != null) { + loadModel(toLoad, type == VMETypeIdentifier.Vme); + currentVmeType = type; + } + else + Window.alert("Could not Load Template Model, error on server."); + } + }); + + } + /** + * Export To the Reports Store Gateway + * + */ + public void exportReportToRSG() { + if (Window.confirm("Are you sure you want to commit the " + model.getTemplateName() + " into the VME Database?")) { + dlg.center(); + dlg.show(); + Model toSave = model.getSerializableModel(); + reportService.exportReportToRSG(currentVmeType, toSave, new AsyncCallback() { + public void onFailure(Throwable caught) { + dlg.hide(); + MessageBox.alert("Warning","Report Not Exported: " + caught.getMessage(), null); + } + public void onSuccess(VmeExportResponse response) { + dlg.hide(); + //write ok + if (response.isGloballySucceded()) { + MessageBox.info("Exporting to RSG Operation","Report Exported Successfully", null); + newDoc(); + } + //runtime exception + else if (response.getResponseMessageList().size() == 1 && response.getResponseMessageList().get(0).getResponseEntryCode().equals("RUNTIME_EXCEPTION")) { + MessageBox.alert("Exporting to RSG Operation Failed","Report Exporting has failed for the following reason:
" + response.getResponseMessageList().get(0).getResponseMessage(), null); + } + //user report compile exception + else { + String failReasons = ""; + for (VmeResponseEntry entry : response.getResponseMessageList()) { + failReasons += entry.getResponseMessage() + "
"; + } + MessageBox.alert("Exporting to RSG Operation Failed","Report Exporting has failed for the following reasons:
" + failReasons, null); + } + } + }); + } + } + + private void deleteVMEReport(String reportId, String name, final VMETypeIdentifier type) { + if (Window.confirm("Are you sure you want to delete " + name + " from the VME Database? (This action is Undoable)")) { + showLoading(); + reportService.deleteReportFromRSG(type, reportId, new AsyncCallback() { + @Override + public void onFailure(Throwable caught) { + dlg.hide(); + Window.alert("Could not Delete, error on server.: " + caught.getMessage()); + } + + @Override + public void onSuccess(VmeExportResponse response) { + dlg.hide(); + //delete ok + if (response.getResponseMessageList().size() == 1 && response.getResponseMessageList().get(0).getResponseEntryCode().equalsIgnoreCase("SUCCEEDED")) + MessageBox.info("Delete VME Report Operation","Report Deleted Successfully", null); + //runtime exception + else if (response.getResponseMessageList().size() == 1 && response.getResponseMessageList().get(0).getResponseEntryCode().equals("RUNTIME_EXCEPTION")) { + MessageBox.alert("Delete VME Report Operation Failed","Report Delete has failed for the following reason:
" + response.getResponseMessageList().get(0).getResponseMessage(), null); + } + //user report compile exception + else { + String failReasons = ""; + for (VmeResponseEntry entry : response.getResponseMessageList()) { + failReasons += entry.getResponseMessage() + "
"; + } + MessageBox.alert("Deleting Operation Failed","Report Deletion has failed for the following reasons:
" + failReasons, null); + } newDoc(); } - //runtime exception - else if (response.getResponseMessageList().size() == 1 && response.getResponseMessageList().get(0).getResponseEntryCode().equals("RUNTIME_EXCEPTION")) { - MessageBox.alert("Exporting to RSG Operation Failed","Report Exporting has failed for the following reason:
" + response.getResponseMessageList().get(0).getResponseMessage(), null); - } - //user report compile exception - else { - String failReasons = ""; - for (VmeResponseEntry entry : response.getResponseMessageList()) { - failReasons += entry.getResponseMessage() + "
"; - } - MessageBox.alert("Exporting to RSG Operation Failed","Report Exporting has failed for the following reasons:
" + failReasons, null); - } - } - }); + }); + } } - } - private void deleteVMEReport(String reportId, String name, final VMETypeIdentifier type) { - if (Window.confirm("Are you sure you want to delete " + name + " from the VME Database? (This action is Undoable)")) { + private void importVMEReport(String reportId, String name, final VMETypeIdentifier type) { showLoading(); - reportService.deleteReportFromRSG(type, reportId, new AsyncCallback() { + reportService.importVMEReport(reportId, name, type, new AsyncCallback() { @Override public void onFailure(Throwable caught) { - dlg.hide(); - Window.alert("Could not Delete, error on server.: " + caught.getMessage()); + Window.alert("Could not Load Report Model, error on server.: " + caught.getMessage()); } @Override - public void onSuccess(VmeExportResponse response) { - dlg.hide(); - //delete ok - if (response.getResponseMessageList().size() == 1 && response.getResponseMessageList().get(0).getResponseEntryCode().equalsIgnoreCase("SUCCEEDED")) - MessageBox.info("Delete VME Report Operation","Report Deleted Successfully", null); - //runtime exception - else if (response.getResponseMessageList().size() == 1 && response.getResponseMessageList().get(0).getResponseEntryCode().equals("RUNTIME_EXCEPTION")) { - MessageBox.alert("Delete VME Report Operation Failed","Report Delete has failed for the following reason:
" + response.getResponseMessageList().get(0).getResponseMessage(), null); + public void onSuccess(Model toLoad) { + if (toLoad != null) { + loadModel(toLoad, type == VMETypeIdentifier.Vme); + currentVmeType = type; } - //user report compile exception - else { - String failReasons = ""; - for (VmeResponseEntry entry : response.getResponseMessageList()) { - failReasons += entry.getResponseMessage() + "
"; - } - MessageBox.alert("Deleting Operation Failed","Report Deletion has failed for the following reasons:
" + failReasons, null); - } - newDoc(); + else + Window.alert("Could not Load Report Model, error on server."); } }); } - } - private void importVMEReport(String reportId, String name, final VMETypeIdentifier type) { - showLoading(); - reportService.importVMEReport(reportId, name, type, new AsyncCallback() { - @Override - public void onFailure(Throwable caught) { - Window.alert("Could not Load Report Model, error on server.: " + caught.getMessage()); - } + private void associateVMEReportRef(VMETypeIdentifier type, String reportId) throws Exception { + GWT.log("Type="+type); + GWT.log("Id"+reportId); + reportService.getVMEReportRef2Associate(reportId, type, new AsyncCallback() { - @Override - public void onSuccess(Model toLoad) { - if (toLoad != null) { - loadModel(toLoad, type == VMETypeIdentifier.Vme); - currentVmeType = type; + @Override + public void onFailure(Throwable caught) { + Window.alert("Could not Load Report Model, error on server.: " + caught.getMessage()); } - else - Window.alert("Could not Load Report Model, error on server."); - } - }); - } - private void associateVMEReportRef(VMETypeIdentifier type, String reportId) throws Exception { - GWT.log("Type="+type); - GWT.log("Id"+reportId); - reportService.getVMEReportRef2Associate(reportId, type, new AsyncCallback() { - - @Override - public void onFailure(Throwable caught) { - Window.alert("Could not Load Report Model, error on server.: " + caught.getMessage()); - } - - @Override - public void onSuccess(Model reportRef) { - if (reportRef != null && reportRef.getSections().size() > 0) { - //the Repeatable Seq must be in the 1st Section, second component. (because ReportsModeler put it there) - BasicSection firstSection = reportRef.getSections().get(0); - if (firstSection.getComponents() != null && firstSection.getComponents().size()==2) { - ReportReferences toPass = (ReportReferences) firstSection.getComponents().get(1).getPossibleContent(); - GWT.log("Singola?" + toPass.isSingleRelation()); - String refKey = toPass.getTuples().get(0).getKey(); - Tuple ref = toPass.getTuples().get(0); - clientSeqSelected.add(refKey, ref, toPass.isSingleRelation()); - } - else { - Window.alert("Sorry, we could not locate the ReportRef correctly in the model instance"); + @Override + public void onSuccess(Model reportRef) { + if (reportRef != null && reportRef.getSections().size() > 0) { + //the Repeatable Seq must be in the 1st Section, second component. (because ReportsModeler put it there) + BasicSection firstSection = reportRef.getSections().get(0); + if (firstSection.getComponents() != null && firstSection.getComponents().size()==2) { + ReportReferences toPass = (ReportReferences) firstSection.getComponents().get(1).getPossibleContent(); + GWT.log("Singola?" + toPass.isSingleRelation()); + String refKey = toPass.getTuples().get(0).getKey(); + Tuple ref = toPass.getTuples().get(0); + clientSeqSelected.add(refKey, ref, toPass.isSingleRelation()); + } + else { + Window.alert("Sorry, we could not locate the ReportRef correctly in the model instance"); + } } + else + Window.alert("Could not Load Report Model, error on server."); } - else - Window.alert("Could not Load Report Model, error on server."); - } - }); - } + }); + } - /** - * this method translate the VME ReportRef String in an ENUM - * @param theType - * @return - * @throws Exception - */ - public VMETypeIdentifier getTypeIdFromString(String theType) throws Exception { - if (theType.equals("GeneralMeasure")) - return VMETypeIdentifier.GeneralMeasure; - else if (theType.equals("InformationSource")) - return VMETypeIdentifier.InformationSource; - else if (theType.equals("FisheryAreasHistory")) - return VMETypeIdentifier.FisheryAreasHistory; - else if (theType.equals("VMEsHistory")) - return VMETypeIdentifier.VMEsHistory; - else if (theType.equals("Rfmo")) - return VMETypeIdentifier.Rfmo; - throw new Exception("Could not find any valid Report Ref, got " + theType + " should be any of " + VMETypeIdentifier.values().toString()); + /** + * this method translate the VME ReportRef String in an ENUM + * @param theType + * @return + * @throws Exception + */ + public VMETypeIdentifier getTypeIdFromString(String theType) throws Exception { + if (theType.equals("GeneralMeasure")) + return VMETypeIdentifier.GeneralMeasure; + else if (theType.equals("InformationSource")) + return VMETypeIdentifier.InformationSource; + else if (theType.equals("FisheryAreasHistory")) + return VMETypeIdentifier.FisheryAreasHistory; + else if (theType.equals("VMEsHistory")) + return VMETypeIdentifier.VMEsHistory; + else if (theType.equals("Rfmo")) + return VMETypeIdentifier.Rfmo; + throw new Exception("Could not find any valid Report Ref, got " + theType + " should be any of " + VMETypeIdentifier.values().toString()); + } } -} diff --git a/src/main/java/org/gcube/portlets/user/reportgenerator/client/targets/ClientImage.java b/src/main/java/org/gcube/portlets/user/reportgenerator/client/targets/ClientImage.java index a64a4ea..038d905 100644 --- a/src/main/java/org/gcube/portlets/user/reportgenerator/client/targets/ClientImage.java +++ b/src/main/java/org/gcube/portlets/user/reportgenerator/client/targets/ClientImage.java @@ -60,9 +60,6 @@ public class ClientImage extends Composite { private String idInBasket; - private String currentUser; - private String currentScope; - public static final int DEFAULT_HEIGHT = 100; public static final int DEFAULT_WIDTH = 700; @@ -111,6 +108,7 @@ public class ClientImage extends Composite { else { GWT.log("Found ImageUrl="+imageURL); showImage(new Image(imageURL), width, height); + enableUpload(false); } //set style for buttons @@ -161,6 +159,7 @@ public class ClientImage extends Composite { @Override public void onClick(ClickEvent event) { resetImage(); + enableUpload(true); } }); @@ -189,7 +188,7 @@ public class ClientImage extends Composite { } private void showUploadPopup() { - presenter.showUploadFilePopup(this); + presenter.showUploadImagePopup(this); } private VerticalPanel getAttributesPanel(BasicComponent co) { @@ -287,6 +286,8 @@ public class ClientImage extends Composite { GWT.log("URL:" + url, null); idInBasket = id; showImage(new Image(url), width, height); + enableUpload(false); + } public void fetchImage(String identifier, final boolean isInteralImage, boolean fullDetails) { @@ -399,4 +400,9 @@ public class ClientImage extends Composite { owner.removeFromParent(this); removeFromParent(); } + + private void enableUpload(boolean enabled) { + addImageB.setVisible(enabled); + uploadImageB.setVisible(enabled); + } } diff --git a/src/main/java/org/gcube/portlets/user/reportgenerator/client/uibinder/OpenOptions.java b/src/main/java/org/gcube/portlets/user/reportgenerator/client/uibinder/OpenOptions.java index 92bf4de..e9705a0 100644 --- a/src/main/java/org/gcube/portlets/user/reportgenerator/client/uibinder/OpenOptions.java +++ b/src/main/java/org/gcube/portlets/user/reportgenerator/client/uibinder/OpenOptions.java @@ -10,6 +10,7 @@ import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Command; +import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLPanel; @@ -52,10 +53,10 @@ public class OpenOptions extends Composite { doAction(OpenMode.OPEN_TEMPLATE); } - @UiHandler("uploadReport") - void unUploadClick(ClickEvent e) { - doAction(OpenMode.UPLOAD); - } +// @UiHandler("uploadReport") +// void unUploadClick(ClickEvent e) { +// doAction(OpenMode.UPLOAD); +// } private void doAction(OpenMode mode) { CommonCommands cmd = new CommonCommands(p); @@ -67,7 +68,7 @@ public class OpenOptions extends Composite { cmd.openTemplate.execute(); break; case UPLOAD: - p.showUploadFilePopup(null); //TODO: fix this + //nothing to do, reminded to workspace break; default: break; diff --git a/src/main/java/org/gcube/portlets/user/reportgenerator/client/uibinder/OpenOptions.ui.xml b/src/main/java/org/gcube/portlets/user/reportgenerator/client/uibinder/OpenOptions.ui.xml index 5b3c536..a45fab5 100644 --- a/src/main/java/org/gcube/portlets/user/reportgenerator/client/uibinder/OpenOptions.ui.xml +++ b/src/main/java/org/gcube/portlets/user/reportgenerator/client/uibinder/OpenOptions.ui.xml @@ -11,9 +11,12 @@ Open/Edit Report - Upload from Desktop + + Upload from + Desktop + - + \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/reportgenerator/server/servlet/NotificationsThread.java b/src/main/java/org/gcube/portlets/user/reportgenerator/server/servlet/NotificationsThread.java index 9c18a6f..6ca0590 100644 --- a/src/main/java/org/gcube/portlets/user/reportgenerator/server/servlet/NotificationsThread.java +++ b/src/main/java/org/gcube/portlets/user/reportgenerator/server/servlet/NotificationsThread.java @@ -38,8 +38,8 @@ public class NotificationsThread implements Runnable { public void run() { for (String userId : userIdsToBeNotified) { try { - boolean notifResult = nm.notifyUpdatedItem(userId, subjectItem, sharedFolder); - _log.trace("Update Notification sent to " + userId + " result="+notifResult); + // boolean notifResult = nm.notifyUpdatedItem(userId, subjectItem, sharedFolder); + //_log.trace("Update Notification sent to " + userId + " result="+notifResult); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/org/gcube/portlets/user/reportgenerator/server/servlet/ReportServiceImpl.java b/src/main/java/org/gcube/portlets/user/reportgenerator/server/servlet/ReportServiceImpl.java index 08b35b0..9567f0e 100644 --- a/src/main/java/org/gcube/portlets/user/reportgenerator/server/servlet/ReportServiceImpl.java +++ b/src/main/java/org/gcube/portlets/user/reportgenerator/server/servlet/ReportServiceImpl.java @@ -13,6 +13,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.OutputStream; +import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; @@ -43,13 +44,14 @@ import org.gcube.application.rsg.client.RsgClient; import org.gcube.application.rsg.service.RsgService; import org.gcube.application.rsg.service.dto.ReportEntry; import org.gcube.application.rsg.service.dto.ReportType; -import org.gcube.application.rsg.service.dto.response.Response; -import org.gcube.application.rsg.service.dto.response.ResponseEntry; +import org.gcube.application.rsg.service.dto.response.ServiceResponse; +import org.gcube.application.rsg.service.dto.response.ServiceResponseMessage; import org.gcube.application.rsg.support.builder.exceptions.ReportBuilderException; import org.gcube.application.rsg.support.builder.impl.ReportManagerReportBuilder; import org.gcube.application.rsg.support.model.components.impl.CompiledReport; import org.gcube.applicationsupportlayer.social.ApplicationNotificationsManager; import org.gcube.applicationsupportlayer.social.NotificationsManager; +import org.gcube.common.encryption.StringEncrypter; import org.gcube.common.homelibrary.home.HomeLibrary; import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; @@ -69,6 +71,9 @@ import org.gcube.common.homelibrary.home.workspace.folder.items.ReportTemplate; import org.gcube.common.homelibrary.home.workspace.folder.items.gcube.ImageDocument; import org.gcube.common.homelibrary.home.workspace.folder.items.ts.TimeSeries; import org.gcube.common.resources.gcore.ServiceEndpoint; +import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint; +import org.gcube.common.resources.gcore.ServiceEndpoint.Property; +import org.gcube.common.resources.gcore.utils.Group; import org.gcube.common.scope.api.ScopeProvider; import org.gcube.portal.custom.communitymanager.OrganizationsUtil; import org.gcube.portal.custom.scopemanager.scopehelper.ScopeHelper; @@ -90,6 +95,7 @@ import org.gcube.portlets.user.reportgenerator.server.servlet.loggers.CreateRepo import org.gcube.portlets.user.reportgenerator.server.servlet.loggers.OpenReportLogEntry; import org.gcube.portlets.user.reportgenerator.server.servlet.loggers.OpenWorkflowLogEntry; import org.gcube.portlets.user.reportgenerator.server.servlet.loggers.SaveWorkflowLogEntry; +import org.gcube.portlets.user.reportgenerator.shared.RSGAccessPoint; import org.gcube.portlets.user.reportgenerator.shared.ReportImage; import org.gcube.portlets.user.reportgenerator.shared.SessionInfo; import org.gcube.portlets.user.reportgenerator.shared.UserBean; @@ -128,8 +134,8 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe */ private boolean withinPortal = true; - //private static final String TEST_SCOPE = "/gcube/devsec/devVRE"; - public static final String TEST_SCOPE = "/gcube/devNext/NextNext"; + public static final String TEST_SCOPE = "/gcube/devsec/devVRE"; + //public static final String TEST_SCOPE = "/gcube/devNext/NextNext"; protected static final String IMAGE_SERVICE_URL = "reports/DownloadService"; /** @@ -148,7 +154,7 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe * */ public static final String RSG_WS_ADDRESS = "RSG_WS_ADDRESS"; - + private static final String REPORT_IMAGES_FOLDER = "Report Images"; @@ -412,8 +418,8 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe return new Model(); } - - + + /** * used when an image is uploaded */ @@ -424,10 +430,20 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe try { _log.trace("trying read: "+absolutePathOnServer); WorkspaceFolder imagesFolder = getImagesFolder(); - // Read from an input stream - InputStream imageData = new BufferedInputStream(new FileInputStream(absolutePathOnServer)); - ExternalImage image = imagesFolder.createExternalImageItem(fileName, "automatically uploaded by Reports Manager", getMimeType(imageData, fileName), imageData); + // Read from an input stream + InputStream imageData = new BufferedInputStream(new FileInputStream(absolutePathOnServer)); + String itemName = fileName; + int i = 1; + while (imagesFolder.exists(itemName)) { + String[] splitted = fileName.split("\\."); + itemName = splitted[0]+"_"+i+"."+splitted[splitted.length-1]; + i++; + } + ExternalImage image = imagesFolder.createExternalImageItem(itemName, "automatically uploaded by Reports Manager", getMimeType(imageData, fileName), imageData); _log.trace("Created external image with name " + image.getName()); + //delete the temp file + File toDelete = new File(absolutePathOnServer); + toDelete.delete(); return new ReportImage(image.getId(), buildImageServiceUrl(image.getId()), image.getWidth(), image.getHeight()); } catch (Exception e) { _log.error("Error in server get image by id", e); @@ -435,6 +451,9 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe } return null; } + /** + * @return the images folder of the workspace, create it if not exist. + */ private WorkspaceFolder getImagesFolder() { Workspace ws = null; WorkspaceFolder reportFolder = null; @@ -669,14 +688,15 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe } - private String getRSGWSAddress() { - String addr = (String) getASLSession().getAttribute(RSG_WS_ADDRESS); - _log.trace("getRSGWSAddress: " + addr); - return addr; + private RSGAccessPoint getRSGWSAddress() { + RSGAccessPoint rsgAp = (RSGAccessPoint) getASLSession().getAttribute(RSG_WS_ADDRESS); + _log.trace("getRSGWSAddress: " + rsgAp.getRestUrl()); + return rsgAp; } - private void setRSGWSAddress(String addr) { - getASLSession().setAttribute(RSG_WS_ADDRESS, addr); - _log.trace("setting RSG WS address to " + addr); + + private void setRSGWSAddress(RSGAccessPoint rsgAp) { + getASLSession().setAttribute(RSG_WS_ADDRESS, rsgAp); + _log.trace("setting RSG WS address to " + rsgAp.getRestUrl()); } /** * @@ -946,7 +966,7 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe } catch (Exception e) { _log.warn("ModelReader fails to read this report, continue..."); } - + if (!result) { _log.debug("Could not save report, serializing failed"); @@ -1606,6 +1626,22 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe _log.info("HTTP Session renewed" + new Date(session.getLastAccessedTime())); } + private RsgClient getRsgSecureClient() { + RSGAccessPoint rsgWsAddr = getRSGWSAddress(); + + RsgClient rsgClient = new RsgClient(rsgWsAddr.getRestUrl()); + try { + rsgClient.securedWithEncryptedToken( + rsgWsAddr.getTokenUrl(), + rsgWsAddr.getiMarineKeyRingLocation(), + rsgWsAddr.getPassword(), + rsgWsAddr.getVmeKeyRingLocation()); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + return rsgClient; + } + @Override public ArrayList listVMEReports() { try { @@ -1616,7 +1652,8 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe ReportType type = new ReportType(); type.setTypeIdentifier("Vme"); - RsgService rsgClient = new RsgClient(getRSGWSAddress()); + RsgClient rsgClient = getRsgSecureClient(); + _log.debug("listVMEReports() securedWithEncryptedToken completed"); for (ReportEntry re : rsgClient.listReports(type)) { String rfmo = re.getOwner(); @@ -1638,7 +1675,8 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe ArrayList toReturn = new ArrayList(); ReportType type = new ReportType(); type.setTypeIdentifier(refType.toString()); - RsgService rsgClient = new RsgClient(getRSGWSAddress()); + RsgClient rsgClient = getRsgSecureClient(); + for (ReportEntry re :rsgClient.listReports(new ReportType(refType.getId()))) { String rfmo = re.getOwner(); @@ -1651,7 +1689,8 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe @Override public Model importVMEReport(String id, String name, VMETypeIdentifier refType) { - RsgService rsgClient = new RsgClient(getRSGWSAddress()); + RsgClient rsgClient = getRsgSecureClient(); + CompiledReport cr = null; if (refType == VMETypeIdentifier.Vme) { @@ -1680,7 +1719,9 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe @Override public Model getVMEReportRef2Associate(String id, VMETypeIdentifier refType) { - RsgService rsgClient = new RsgClient(getRSGWSAddress()); + RsgClient rsgClient = getRsgSecureClient(); + + _log.info("Importing Ref type= " + refType.getId() + " id=" + id); CompiledReport cr = rsgClient.getReferenceReportById(new ReportType(refType.getId()), id); Model model = null; @@ -1696,7 +1737,7 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe @Override public Model importVMETemplate(VMETypeIdentifier refType) { - RsgService rsgClient = new RsgClient(getRSGWSAddress()); + RsgClient rsgClient = getRsgSecureClient(); CompiledReport cr = null; if (refType == VMETypeIdentifier.Vme) { @@ -1724,7 +1765,7 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe public VmeExportResponse exportReportToRSG(VMETypeIdentifier refType, Model model) { System.out.println(new ModelReader(model).toString()); - RsgService rsgClient = new RsgClient(getRSGWSAddress()); + RsgClient rsgClient = getRsgSecureClient(); //Use the RSG client to get a template for the report whose type is the last token (i.e. the corresponding class' 'simple name') //appearing in the VME model class name as stored in the 'type' metadata @@ -1746,7 +1787,7 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe } try { //Actual RSG client interface exposes different methods (publish / publishDelta etc.) that need to be updated - Response res = null; + ServiceResponse res = null; if (refType == VMETypeIdentifier.Vme) { _log.info("Exporting VME Report"); res = rsgClient.update(toSend); @@ -1764,10 +1805,10 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe @Override public VmeExportResponse deleteReportFromRSG(VMETypeIdentifier refType, String idToDelete) { - RsgService rsgClient = new RsgClient(getRSGWSAddress()); + RsgClient rsgClient = getRsgSecureClient(); try { - Response res = null; + ServiceResponse res = null; if (refType == VMETypeIdentifier.Vme) { _log.info("Deleting VME Report id = " + idToDelete); res = rsgClient.deleteById(new ReportType(refType.getId()), idToDelete); @@ -1786,8 +1827,9 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe /** * this method look for a ReportsStoreGateway WS available in the infrastructure * @return true if an instance of the ReportsStoreGateway is available in the infrastructure + * @throws Exception */ - private boolean isReportsStoreGatewayAvailable() { + private boolean isReportsStoreGatewayAvailable(){ String scope = getASLSession().getScope(); _log.info("Looking for a running ReportsStoreGateway WS in " + scope); String previousScope = ScopeProvider.instance.get(); @@ -1807,17 +1849,33 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe else if (list.size() == 1) { ServiceEndpoint se = list.get(0); String host = se.profile().runtime().hostedOn(); - String accessPoint = se.profile().accessPoints().iterator().next().address(); - setRSGWSAddress(host+accessPoint); + AccessPoint ap = se.profile().accessPoints().iterator().next(); + String address = ap.address(); + String password = ""; + String iMarineSkrURL = ""; + String vmeSkrURL = ""; + try { + password = StringEncrypter.getEncrypter().decrypt(ap.password()); + for (Property property : ap.properties()) { + if (property.name().compareTo(RSGAccessPoint.IMARINE_SECURE_KEYRING_NAME) == 0) + iMarineSkrURL = StringEncrypter.getEncrypter().decrypt(property.value()); + if (property.name().compareTo(RSGAccessPoint.VME_SECURE_KEYRING_NAME) == 0) + vmeSkrURL = StringEncrypter.getEncrypter().decrypt(property.value()); + } + } catch (Exception e) { + e.printStackTrace(); + } + RSGAccessPoint rsgAp = new RSGAccessPoint(host+address, iMarineSkrURL, vmeSkrURL, password); + setRSGWSAddress(rsgAp); return true; } else return false; } - private VmeExportResponse getClientResponse(Response rsgResponse) { + private VmeExportResponse getClientResponse(ServiceResponse rsgResponse) { VmeExportResponse toReturn = new VmeExportResponse(); - for (ResponseEntry entry : rsgResponse.getResponseMessageList()) { + for (ServiceResponseMessage entry : rsgResponse.getResponseMessageList()) { String entryCode = entry.getResponseCode() == null ? "no-code" : entry.getResponseCode().toString(); String entryMessage = entry.getResponseMessage() == null ? "no response message" : entry.getResponseMessage(); toReturn.getResponseMessageList().add(new VmeResponseEntry(entryCode, entryMessage)); diff --git a/src/main/java/org/gcube/portlets/user/reportgenerator/shared/RSGAccessPoint.java b/src/main/java/org/gcube/portlets/user/reportgenerator/shared/RSGAccessPoint.java new file mode 100644 index 0000000..05aafbd --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/reportgenerator/shared/RSGAccessPoint.java @@ -0,0 +1,49 @@ +package org.gcube.portlets.user.reportgenerator.shared; + +public class RSGAccessPoint { + + public static final String VME_SECURE_KEYRING_NAME = "vme.pkr"; + public static final String IMARINE_SECURE_KEYRING_NAME = "imarine.skr"; + private static final String REST_ENDPOINT = "/rest"; + private static final String TOKEN_ENDPOINT = "/security/token/encrypted/request"; + + private String url; + private String iMarineKeyRing; + private String vmeKeyRing; + private String password; + + public RSGAccessPoint(String url, String iMarineKeyRing, String vmeKeyRing, String password) { + super(); + this.url = url; + this.iMarineKeyRing = iMarineKeyRing; + this.vmeKeyRing = vmeKeyRing; + this.password = password; + } + + public String getRestUrl() { + return url+REST_ENDPOINT; + } + public String getTokenUrl() { + return url+TOKEN_ENDPOINT; + } + public String getiMarineKeyRingLocation() { + return iMarineKeyRing; + } + public String getVmeKeyRingLocation() { + return vmeKeyRing; + } + public String getPassword() { + return password; + } + + @Override + public String toString() { + return "RSGAccessPoint [getRestUrl()=" + getRestUrl() + + ", getTokenUrl()=" + getTokenUrl() + + ", getiMarineKeyRingLocation()=" + + getiMarineKeyRingLocation() + ", getVmeKeyRingLocation()=" + + getVmeKeyRingLocation() + ", getPassword()=" + getPassword() + + "]"; + } + +}