diff --git a/.classpath b/.classpath index 3cd7149..032cbf5 100644 --- a/.classpath +++ b/.classpath @@ -1,6 +1,6 @@ - + @@ -31,5 +31,5 @@ - + diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component index 7bc596b..8d0dd4c 100644 --- a/.settings/org.eclipse.wst.common.component +++ b/.settings/org.eclipse.wst.common.component @@ -4,7 +4,10 @@ - + + uses + + uses diff --git a/pom.xml b/pom.xml index fac856f..5ff88fa 100644 --- a/pom.xml +++ b/pom.xml @@ -12,7 +12,7 @@ org.gcube.portlets.user reports war - 5.1.0-SNAPSHOT + 6.0.0-SNAPSHOT gCube Reports Manager gCube Reports Portlet. @@ -38,23 +38,6 @@ UTF-8 UTF-8 - - - offline - - compile - offline - - - - org.gcube.applicationsupportlayer - aslcore-offline - [1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT) - ${setScope} - - - - @@ -71,13 +54,13 @@ com.google.gwt gwt-user ${gwtVersion} - ${setScope} + provided com.google.gwt gwt-servlet ${gwtVersion} - ${setScope} + provided com.google.gwt @@ -92,7 +75,7 @@ org.gcube.portlets.widgets session-checker - [0.4.0-SNAPSHOT, 1.0.0-SNAPSHOT) + [1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT) org.gcube.core @@ -107,22 +90,22 @@ org.gcube.applicationsupportlayer aslsocial - ${setScope} + provided org.gcube.portlets.user gcube-widgets - ${setScope} + provided org.gcube.portal custom-portal-handler - ${setScope} + provided org.gcube.common.portal portal-manager - ${setScope} + provided com.sencha.gxt @@ -153,6 +136,10 @@ javax.el-api javax.el + + xercesImpl + xerces + @@ -176,11 +163,6 @@ workspace-explorer [1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT) - - org.gcube.portlets.admin - document-workflow-library - [1.2.0-SNAPSHOT, 2.0.0-SNAPSHOT) - org.gcube.portlets.widgets report-exporter-widget @@ -221,7 +203,6 @@ org.gcube.common home-library-jcr - provided @@ -232,27 +213,27 @@ org.gcube.applicationsupportlayer accesslogger - ${setScope} + provided org.apache.derby derby - ${setScope} + provided commons-fileupload commons-fileupload - ${setScope} + provided com.liferay.portal portal-service - ${setScope} + provided javax.portlet portlet-api - ${setScope} + provided log4j diff --git a/src/main/java/org/gcube/portlets/user/reportgenerator/client/Headerbar.java b/src/main/java/org/gcube/portlets/user/reportgenerator/client/Headerbar.java index 5e50732..aa67b1e 100644 --- a/src/main/java/org/gcube/portlets/user/reportgenerator/client/Headerbar.java +++ b/src/main/java/org/gcube/portlets/user/reportgenerator/client/Headerbar.java @@ -213,26 +213,6 @@ public class Headerbar extends Composite{ MenuBar workflowMenu = new MenuBar(true); workflowMenu.setAnimationEnabled(true); - MenuItem menu = new MenuItem("Workflow Document Options", true, workflowMenu); - menu.setWidth("400px"); - Command updateWfDocument = new Command() { - public void execute() { - presenter.updateWorkflowDocument(true); - } - }; - Command backCommand = new Command() { - public void execute() { - presenter.updateWorkflowDocument(false); - } - }; - - if (canUpdate) - workflowMenu.addItem("Update this document", updateWfDocument); - //workflowMenu.addItem("Show previous changes", showChanges); - workflowMenu.addSeparator(); - workflowMenu.addItem("Back to My Workflow Documents", backCommand); - - menuBar.addItem(menu); separator1 = menuBar.addSeparator(); viewMenu = getViewMenu(); menuBar.addItem(viewMenu); 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 319bf48..0a93a34 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 @@ -313,1183 +313,1130 @@ 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(); - currentReportsStoreGatewayURL = sessionInfo.getRsgEndpoint(); - 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, currentReportsStoreGatewayURL); - } - - 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 - */ - HashMap toReturn = new HashMap(); - - 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); - - 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 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(); - } - 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() { - MessageBox.confirm("Commit to VME-DB", "Are you sure you want to commit the " + model.getTemplateName() + " into the VME Database?", new Listener() { - @Override - public void handleEvent(MessageBoxEvent be) { - if(Dialog.YES.equalsIgnoreCase(be.getButtonClicked().getItemId())) { - dlg.center(); - 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 + } + + + /** + * 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(); + currentReportsStoreGatewayURL = sessionInfo.getRsgEndpoint(); + addTextToolBar(true); + //not in workflow mode check if a report was open + model.getModelService().readTemplateFromSession(new AsyncCallback() { 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); + public void onSuccess(Model result) { + if (isVME) { + header.setMenuForVME(); + header.enableExports(); } - //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); + dlg.hide(); + if (result != null) { //there was one report open in session + loadModel(result, true); + header.enableExports(); + } else{ + commonCommands.newTemplate.execute(); } - newDoc(); } }); } + + }; + + 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, currentReportsStoreGatewayURL); + } + + 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()); + } - 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()); - } - - @Override - public void onSuccess(Model toLoad) { - if (toLoad != null) { - loadModel(toLoad, type == VMETypeIdentifier.Vme); - currentVmeType = type; - } - 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"); - } - } - else - Window.alert("Could not Load Report Model, error on server."); - } - }); + 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); + } + + /** + * put the commands in the hashmap + */ + private HashMap getCommands() { /** - * this method translate the VME ReportRef String in an ENUM - * @param theType - * @return - * @throws Exception + * commands to pass to the toolbar */ - 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()); + HashMap toReturn = new HashMap(); + + 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); + + 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 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(); + } + }); + } + + + /** + * + *@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() { + MessageBox.confirm("Commit to VME-DB", "Are you sure you want to commit the " + model.getTemplateName() + " into the VME Database?", new Listener() { + @Override + public void handleEvent(MessageBoxEvent be) { + if(Dialog.YES.equalsIgnoreCase(be.getButtonClicked().getItemId())) { + dlg.center(); + 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(); + } + }); + } + } + + 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()); + } + + @Override + public void onSuccess(Model toLoad) { + if (toLoad != null) { + loadModel(toLoad, type == VMETypeIdentifier.Vme); + currentVmeType = type; + } + 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"); + } + } + 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()); + } +} diff --git a/src/main/java/org/gcube/portlets/user/reportgenerator/client/ReportService.java b/src/main/java/org/gcube/portlets/user/reportgenerator/client/ReportService.java index b5b3b45..63185b4 100644 --- a/src/main/java/org/gcube/portlets/user/reportgenerator/client/ReportService.java +++ b/src/main/java/org/gcube/portlets/user/reportgenerator/client/ReportService.java @@ -98,12 +98,6 @@ public interface ReportService extends RemoteService{ VmeExportResponse deleteReportFromRSG(VMETypeIdentifier refType, String idToDelete); - - Model getWorkflowDocumentFromDocumentLibrary(); - - void updateWorkflowDocument(Model toSave, boolean update); - - void renewLock(); /** * * @param tempPath diff --git a/src/main/java/org/gcube/portlets/user/reportgenerator/client/ReportServiceAsync.java b/src/main/java/org/gcube/portlets/user/reportgenerator/client/ReportServiceAsync.java index 84c2e45..d43ec24 100644 --- a/src/main/java/org/gcube/portlets/user/reportgenerator/client/ReportServiceAsync.java +++ b/src/main/java/org/gcube/portlets/user/reportgenerator/client/ReportServiceAsync.java @@ -65,12 +65,6 @@ public interface ReportServiceAsync { */ void getSessionInfo(String currentHost, AsyncCallback callback); - void getWorkflowDocumentFromDocumentLibrary(AsyncCallback callback); - - void updateWorkflowDocument(Model toSave, boolean update, AsyncCallback callback); - - void renewLock(AsyncCallback callback); - void readImportedModel(String tempPath, AsyncCallback callback); void save(String filePath, String workspaceFolderId, String ItemName, TypeExporter type, boolean overwrite, AsyncCallback callback); diff --git a/src/main/java/org/gcube/portlets/user/reportgenerator/client/TitleBar.java b/src/main/java/org/gcube/portlets/user/reportgenerator/client/TitleBar.java index 8e68eaa..e4b4502 100644 --- a/src/main/java/org/gcube/portlets/user/reportgenerator/client/TitleBar.java +++ b/src/main/java/org/gcube/portlets/user/reportgenerator/client/TitleBar.java @@ -101,31 +101,6 @@ import com.google.gwt.user.client.ui.HorizontalPanel; mainLayout.setStyleName("titleBar"); - } - /** - * add the buttons well visible on the top - * @param isEdit - */ - public void addWorkflowButtons(final boolean isEdit) { - Button update = new Button("Update (SAVE)"); - update.addClickHandler(new ClickHandler() { - @Override - public void onClick(ClickEvent event) { - presenter.updateWorkflowDocument(isEdit); - } - }); - Button back = new Button("Do not Update"); - back.addClickHandler(new ClickHandler() { - @Override - public void onClick(ClickEvent event) { - presenter.updateWorkflowDocument(isEdit); - } - }); - update.addStyleName("addEntryButton"); - back.addStyleName("deleteEntryButton"); - captionPanel.add(update); - captionPanel.add(back); - } /** diff --git a/src/main/java/org/gcube/portlets/user/reportgenerator/server/servlet/DocLibraryUtil.java b/src/main/java/org/gcube/portlets/user/reportgenerator/server/servlet/DocLibraryUtil.java deleted file mode 100644 index 9e3dfe4..0000000 --- a/src/main/java/org/gcube/portlets/user/reportgenerator/server/servlet/DocLibraryUtil.java +++ /dev/null @@ -1,312 +0,0 @@ -package org.gcube.portlets.user.reportgenerator.server.servlet; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.gcube.application.framework.core.session.ASLSession; -import org.gcube.portal.custom.communitymanager.OrganizationsUtil; -import org.gcube.portlets.admin.wfdocslibrary.shared.PermissionType; -import org.gcube.portlets.admin.wfdocslibrary.shared.Step; -import org.gcube.portlets.admin.wfdocslibrary.shared.WfRole; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.liferay.portal.kernel.exception.PortalException; -import com.liferay.portal.kernel.exception.SystemException; -import com.liferay.portal.model.Organization; -import com.liferay.portal.model.ResourceConstants; -import com.liferay.portal.model.Role; -import com.liferay.portal.model.User; -import com.liferay.portal.service.OrganizationLocalServiceUtil; -import com.liferay.portal.service.PermissionLocalServiceUtil; -import com.liferay.portal.service.ResourceLocalServiceUtil; -import com.liferay.portal.service.ServiceContext; -import com.liferay.portal.service.UserLocalServiceUtil; -import com.liferay.portlet.documentlibrary.NoSuchFolderException; -import com.liferay.portlet.documentlibrary.model.DLFileEntry; -import com.liferay.portlet.documentlibrary.model.DLFolder; -import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil; -import com.liferay.portlet.documentlibrary.service.DLFolderLocalServiceUtil; - -public class DocLibraryUtil { - - public static final String WORKFLOWS_FOLDER = "Workflow Documents"; - /** - * - */ - private static final Logger log = LoggerFactory.getLogger(DocLibraryUtil.class); - - - /** - * write the Report File (payload) into Liferay DocLibrary in the workflowdocs folder - * @param roles - * @param start each Step contains a Map> that is needed in the writeFileIntoDocLibrary - * @param fileName - * @param buffer the payload as byte array - */ - public static boolean writeFileIntoDocLibrary(ASLSession session, List roles, Step start, String fileName, byte[] buffer) { - long docfolderid = -1; - try { - docfolderid = getWfFolder(session); - long userId = getUserId(session); - //write the file into doclib - DLFileEntry fileEntry = DLFileEntryLocalServiceUtil.addFileEntry( - userId, - getGroupID(session), - docfolderid, - fileName, - fileName, - "workflow document", - "", - "", - buffer, - new ServiceContext()); - log.debug("Wrote file into DocumentLibrary"); - - - - //get the file entry resource id - long resourceId = ResourceLocalServiceUtil.getResource(fileEntry.getCompanyId(), - DLFileEntry.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, String.valueOf(fileEntry.getFileEntryId())).getResourceId(); - - //set the permission on the file for each role - for (Role role : roles) { - String[] actionIds = getPermissionsFromWfStep(role, start); - PermissionLocalServiceUtil.setRolePermissions(role.getRoleId(), actionIds, resourceId); - log.debug("set the permissions for Role: " + role.getName()); - } - } catch (Exception e) { - e.printStackTrace(); - return false; - } - log.debug(" WROTE INTO DOCsLib and ADDING permissions for name: " + fileName); - return true; - } - - public static DLFileEntry updateFileIntoDocLibrary(ASLSession session, String workflowid, byte[] buffer) { - long docfolderid = -1; - DLFileEntry fileEntry = null; - try { - fileEntry = getFileEntry(session, workflowid); - docfolderid = getWfFolder(session); - long userId = getUserId(session); - - String fileName = fileEntry.getTitle(); - log.debug("Update file into DocumentLibrary with Name: " + fileName); - - DLFileEntryLocalServiceUtil.updateFileEntry( - userId, - getGroupID(session), - docfolderid, - fileEntry.getName(), - fileEntry.getName(), - fileName, - fileEntry.getDescription(), - "", - true, - "", - buffer, - new ServiceContext()); - - log.debug("Update file into DocumentLibrary"); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - return fileEntry; - } - - public static boolean deleteFileFromDocLibrary(ASLSession session, String workflowid) { - DLFileEntry fileEntry = null; - try { - fileEntry = getFileEntry(session, workflowid); - DLFileEntryLocalServiceUtil.deleteDLFileEntry(fileEntry); - log.debug("Deleted"); - } catch (Exception e) { - e.printStackTrace(); - return false; - } - return true; - } - /** - * - * @param session - * @param workflowid - * @return - * @throws Exception - * @throws SystemException - * @throws PortalException - */ - public static InputStream getFileEntryAsStream(ASLSession session, String workflowid) throws Exception { - String titleWithExtension = workflowid+".zip"; - - DLFileEntry fileEntry = DLFileEntryLocalServiceUtil.getFileEntryByTitle(getGroupID(session), getWfFolder(session), - titleWithExtension); - - return DLFileEntryLocalServiceUtil.getFileAsStream(fileEntry.getCompanyId(), - getUserId(session), getGroupID(session), getWfFolder(session), fileEntry.getName()); - - } - - public static DLFileEntry getFileEntry(ASLSession session, String workflowid) throws PortalException, SystemException, Exception { - String titleWithExtension = workflowid+".zip"; - - return DLFileEntryLocalServiceUtil.getFileEntryByTitle(getGroupID(session), getWfFolder(session), - titleWithExtension); - - } - - /** - * - * @param role is the liferay role, for convention is created as ROLENAME_WFID e.g. EDITOR_123 - * @param step containts the permissions attached to each role (just the name, e.g. EDITOR) - * @return the permissions to apply - */ - public static String[] getPermissionsFromWfStep(Role role, Step step) { - ArrayList toConvert = new ArrayList(); - for (WfRole steprole : step.getPermissions().keySet()) { - System.out.println("Steprole: "+ steprole.getRolename()); - String name = role.getName().split("_")[0]; //e.g. EDITOR <- EDITOR_123 - System.out.println("role Name: "+ name); - if (steprole.getRolename().equals(name)) { - toConvert = step.getPermissions().get(steprole); - } - } - String[] toReturn = new String[toConvert.size()]; - int i = 0; - for (PermissionType p : toConvert) { - toReturn[i] = getLRActionIdFromWfPermissionType(p); - i++; - } - return toReturn; - } - /** - * check the existence of the WFFolder or create it if not exists - * @param session - * @return true is everything goes ok - * @throws PortalException - * @throws SystemException - */ - public static long getWfFolder(ASLSession session) throws Exception { - long parentFolderId = 0; - DLFolder folder = null; - if (! wfFolderExists(session)) { - folder = DLFolderLocalServiceUtil.addFolder(getUserId(session), getGroupID(session), parentFolderId, WORKFLOWS_FOLDER, "Folder for Workflow Documents", new ServiceContext()); - log.debug("Folder for WorkflowDocs created: /" + WORKFLOWS_FOLDER); - } else - folder = DLFolderLocalServiceUtil.getFolder( getGroupID(session), parentFolderId, WORKFLOWS_FOLDER); - return folder.getFolderId(); - } - /** - * - * @param session the ASL Session instance - * @return true if the workflow docs exists - */ - public static boolean wfFolderExists(ASLSession session) { - try { - long groupid = getGroupID(session); - long parentfolder = 0; - if (DLFolderLocalServiceUtil.getFolder(groupid, parentfolder, "Workflow Documents") != null) - return true; - else - return false; - } - catch (NoSuchFolderException ex) { - log.debug("Folder does not exists"); - return false; - } - catch (Exception e) { - e.printStackTrace(); - return false; - } - } - /** - * - * @param session - * @return - * @throws PortalException - * @throws SystemException - */ - public static long getGroupID(ASLSession session) throws PortalException, SystemException { - long organizationid = session.getGroupId(); - Organization myOrg = OrganizationLocalServiceUtil.getOrganization(organizationid); - return myOrg.getGroup().getGroupId(); - } - /** - * - * @return the company webid - * @throws PortalException - * @throws SystemException - */ - public static long getCompanyID() throws PortalException, SystemException { - return OrganizationsUtil.getCompany().getCompanyId(); - } - /** - * - * @param session the ASL Session instance - * @return the list of the root folders - * @throws SystemException . - * @throws PortalException . - */ - public static List getFolders(ASLSession session) throws SystemException, PortalException { - long companyid = getCompanyID(); - List folders = null; - folders = DLFolderLocalServiceUtil.getFolders(companyid); - for (DLFolder folder : folders) { - log.debug("Folder name: " + folder.getName() + " ID: " + folder.getFolderId() + " Parent: " + folder.getParentFolderId() + " Groupid: " + folder.getGroupId()); - } - return folders; - } - - /** - * - * @param session the ASL Session instance - * @return the userid in the liferay system - */ - public static long getUserId(ASLSession session) { - List users = null; - long userId = 0; - try { - users = UserLocalServiceUtil.getUsers(0, UserLocalServiceUtil.getUsersCount()); - } catch (SystemException e) { - e.printStackTrace(); - } - for(User user: users){ - if(user.getScreenName().equalsIgnoreCase(session.getUsername())){ - userId = user.getUserId(); - break; - } - } - return userId; - } - - - /** - * needed to convert Workflows permission into Lifearay permissions (ActionIDs) - * @param type - * @return - */ - private static String getLRActionIdFromWfPermissionType(PermissionType type) { - switch (type) { - case EDIT_PERMISSIONS: - return "PERMISSIONS"; - case VIEW: - return "VIEW"; - case UPDATE: - return "UPDATE"; - case DELETE: - return "DELETE"; - case ADD_DISCUSSION: - return "ADD_DISCUSSION"; - case DELETE_DISCUSSION: - return "DELETE_DISCUSSION"; - case UPDATE_DISCUSSION: - return "UPDATE_DISCUSSION"; - default: - return ""; - } - } - - -} 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 deleted file mode 100644 index 6ca0590..0000000 --- a/src/main/java/org/gcube/portlets/user/reportgenerator/server/servlet/NotificationsThread.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.gcube.portlets.user.reportgenerator.server.servlet; - -import java.util.List; - -import org.gcube.application.framework.core.session.ASLSession; -import org.gcube.applicationsupportlayer.social.ApplicationNotificationsManager; -import org.gcube.applicationsupportlayer.social.NotificationsManager; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * @author Massimiliano Assante ISTI-CNR - * - */ -public class NotificationsThread implements Runnable { - private static final Logger _log = LoggerFactory.getLogger(NotificationsThread.class); - - private static final String WORKSPACE_PORTLET_ID = "org.gcube.portlets.user.workspace.server.GWTWorkspaceServiceImpl"; - - - private NotificationsManager nm; - private List userIdsToBeNotified; - private WorkspaceItem subjectItem; - private WorkspaceFolder sharedFolder; - - - public NotificationsThread(ASLSession session, List userIdsToBeNotified, WorkspaceItem item, WorkspaceFolder sharedFolder) { - nm = new ApplicationNotificationsManager(session, WORKSPACE_PORTLET_ID); - this.userIdsToBeNotified = userIdsToBeNotified; - subjectItem = item; - this.sharedFolder = sharedFolder; - } - - @Override - public void run() { - for (String userId : userIdsToBeNotified) { - try { - // 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 0169b69..3057393 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 @@ -18,7 +18,6 @@ import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; -import java.util.UUID; import java.util.Vector; import javax.servlet.http.HttpServletRequest; @@ -50,8 +49,6 @@ 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.homelibary.model.items.type.FolderItemType; import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; @@ -75,11 +72,7 @@ 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.scope.api.ScopeProvider; -import org.gcube.portal.custom.communitymanager.OrganizationsUtil; import org.gcube.portal.custom.scopemanager.scopehelper.ScopeHelper; -import org.gcube.portlets.admin.wfdocslibrary.client.WfDocsLibrary; -import org.gcube.portlets.admin.wfdocslibrary.server.db.MyDerbyStore; -import org.gcube.portlets.admin.wfdocslibrary.server.db.Store; import org.gcube.portlets.d4sreporting.common.server.ServiceUtil; import org.gcube.portlets.d4sreporting.common.shared.BasicComponent; import org.gcube.portlets.d4sreporting.common.shared.BasicSection; @@ -93,8 +86,6 @@ import org.gcube.portlets.user.reportgenerator.client.ReportConstants; import org.gcube.portlets.user.reportgenerator.client.ReportService; import org.gcube.portlets.user.reportgenerator.server.servlet.loggers.CreateReportLogEntry; 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; @@ -109,17 +100,18 @@ import org.gcube.portlets.widgets.exporter.shared.TypeExporter; import org.gcube.resources.discovery.client.api.DiscoveryClient; import org.gcube.resources.discovery.client.queries.api.SimpleQuery; import org.gcube.vomanagement.usermanagement.RoleManager; -import org.gcube.vomanagement.usermanagement.impl.liferay.LiferayRoleManager; -import org.gcube.vomanagement.usermanagement.model.RoleModel; +import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager; +import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager; +import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager; +import org.gcube.vomanagement.usermanagement.model.GCubeRole; +import org.gcube.vomanagement.usermanagement.model.GCubeTeam; +import org.gcube.vomanagement.usermanagement.model.GCubeUser; +import org.gcube.vomanagement.usermanagement.model.GatewayRolesNames; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gwt.user.server.rpc.RemoteServiceServlet; -import com.liferay.portal.model.User; -import com.liferay.portal.model.UserModel; -import com.liferay.portal.service.LockLocalServiceUtil; import com.liferay.portal.service.UserLocalServiceUtil; -import com.liferay.portlet.documentlibrary.model.DLFileEntry; @@ -156,24 +148,11 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe public static final String TEST_USER = "test.user"; public static final String TEST_SCOPE = "/gcube/devsec/devVRE"; - /** - * the WF DB Store - */ - private Store store; + //the client for the VME-DB case private RsgReadClient rsgReadClient; private RsgWriteClient rsgWriteClient; - //set to true if want to test workflow menu mode - boolean testWorkflow = false; - - /** - * Called then servlet is intialized - */ - public void init() { - _log.info("Initializing Servlet ReportServiceImpl... connecting to WF DB"); - store = new MyDerbyStore(); - } /** * the current ASLSession @@ -756,13 +735,6 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe String templateid = (String) d4Session.getAttribute("idreport"); - Object workflowid = getASLSession().getAttribute(WfDocsLibrary.LAST_WORKFLOW_ID); - _log.debug(" (templateid != null && workflowid != null) = " + (templateid != null) + " - " + (workflowid != null)); - if (workflowid != null) { - getASLSession().setAttribute(WfDocsLibrary.LAST_WORKFLOW_ID, null); - return null; - } - String templateName = ""; _log.debug("TEMPLATE ID==NULL " + (templateid == null)); if (templateid != null) { @@ -1061,13 +1033,6 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe storeReportItemIDInSession(rep.getId()); - if (toSaveIn.getType() == WorkspaceItemType.SHARED_FOLDER) { - sendReportUpdateNotification(toSaveIn, rep); - } - - AccessLogger log = AccessLogger.getAccessLogger(); - CreateReportLogEntry logEntry = new CreateReportLogEntry(model.getTemplateName(), rep.getId()); - log.logEntry(getASLSession().getUsername(), getASLSession().getScopeName(), logEntry); } catch (Exception e) { e.printStackTrace(); @@ -1106,19 +1071,7 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe return null; } - /** - * send an update notification to all the user sharing this folder - * @param toSaveIn - * @throws InternalErrorException - */ - private void sendReportUpdateNotification(WorkspaceFolder sharedFolder, WorkspaceItem wsItem) throws InternalErrorException { - if (sharedFolder.getType() == WorkspaceItemType.SHARED_FOLDER) { - WorkspaceSharedFolder wsFolder = (WorkspaceSharedFolder) sharedFolder; - List usersToNotify = wsFolder.getUsers(); - Thread thread = new Thread(new NotificationsThread(getASLSession(), usersToNotify, wsItem, sharedFolder)); - thread.start(); - } - } + /** * return a sample of the given TS to the client * @param sTS . @@ -1315,215 +1268,15 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe * @return a SessionInfo bean containing the username the scope andis opening a workflow document or not */ public SessionInfo getSessionInfo(String currentHost) { - if (testWorkflow) { - getASLSession().setAttribute(WfDocsLibrary.WORKFLOW_ID_ATTRIBUTE, "1"); - getASLSession().setAttribute(WfDocsLibrary.WORKFLOW_GIVEN_NAME, "TEST REPORT"); - getASLSession().setAttribute(WfDocsLibrary.WORKFLOW_READONLY_ATTRIBUTE, true); - return new SessionInfo(getUserBean(), getVreName(), true, true, false, ""); - } - boolean isVME = isReportsStoreGatewayAvailable(); - - if (getASLSession().getAttribute(WfDocsLibrary.WORKFLOW_ID_ATTRIBUTE) == null) { - _log.debug("WfDocsLibrary.WORKFLOW_ID_ATTRIBUTE is NULL: "); - String rsgEndpoint = ""; - if (getRSGWSAddress() != null) - rsgEndpoint = ((RSGAccessPoint) getRSGWSAddress()).getRestUrl(); - return new SessionInfo(getUserBean(), getVreName(), false, false, isVME, rsgEndpoint); - - } - else { - _log.debug("FOUND WORKFLOW_ID_ATTRIBUTE ***** "); - //String workflowid = getASLSession().getAttribute(WfDocsLibrary.WORKFLOW_ID_ATTRIBUTE).toString(); - Boolean canEdit = ! (Boolean) getASLSession().getAttribute(WfDocsLibrary.WORKFLOW_READONLY_ATTRIBUTE); - return new SessionInfo(getUserBean(), getVreName(), true, canEdit, false, ""); - } - } - - public Model getWorkflowDocumentFromDocumentLibrary() { - ServiceUtil myUtil = new ServiceUtil(getASLSession()); - - if (testWorkflow) { - FileInputStream fis = null; - ObjectInputStream in = null; - Model toConvert = null; - try { - fis = new FileInputStream("/Users/massi/portal/CURRENT_OPEN.d4st"); - in = new ObjectInputStream(fis); - toConvert = (Model) in.readObject(); - in.close(); - } catch (IOException ex) { - ex.printStackTrace(); - } catch (ClassNotFoundException ex) { - ex.printStackTrace(); - } - toConvert.setTemplateName("TEST"); - _log.info(" Converting TEST REPORT to Serializable object, model name: \n" + toConvert.getTemplateName()); - return toConvert; - } - else { - String workflowid = getASLSession().getAttribute(WfDocsLibrary.WORKFLOW_ID_ATTRIBUTE).toString(); - Boolean canEdit = ! (Boolean) getASLSession().getAttribute(WfDocsLibrary.WORKFLOW_READONLY_ATTRIBUTE); - String documentName = getASLSession().getAttribute(WfDocsLibrary.WORKFLOW_GIVEN_NAME).toString(); - _log.info("getWorkflowDocumentFromDocumentLibrary() CALLED ***** ID = " + workflowid + " name:\n " + documentName); - - //TODO: check this - //reset the values in session - - _log.info("Reset the values in session ... "); - - getASLSession().setAttribute(WfDocsLibrary.LAST_WORKFLOW_ID, workflowid); - getASLSession().setAttribute(WfDocsLibrary.WORKFLOW_ID_ATTRIBUTE, null); - getASLSession().setAttribute(WfDocsLibrary.WORKFLOW_READONLY_ATTRIBUTE, null); - getASLSession().setAttribute(WfDocsLibrary.WORKFLOW_GIVEN_NAME, null); + String rsgEndpoint = ""; + if (getRSGWSAddress() != null) + rsgEndpoint = ((RSGAccessPoint) getRSGWSAddress()).getRestUrl(); + return new SessionInfo(getUserBean(), getVreName(), false, false, isVME, rsgEndpoint); - try { - InputStream inputStream = DocLibraryUtil.getFileEntryAsStream(getASLSession(), workflowid); - String templatePath = myUtil.getTemplateFolder(getVreName(), getUsername()) + "CURRENT_OPEN/"; - String pathToFile = templatePath; - File toExtract = writeReportToDisk(inputStream, pathToFile, "Workflodoc-report.zip"); - - File outputDir = new File( myUtil.getTemplatePath("", getVreName(), getUsername()) ); - ZipUtil.unzipArchive(toExtract, outputDir); - toExtract.delete(); - - - FileInputStream fis = null; - ObjectInputStream in = null; - Model toConvert = null; - try { - String path = myUtil.getTemplateFolder(getVreName(), getUsername()); - - String reportFileName = seekModel(templatePath, UUID.randomUUID().toString()); //random name just to make sure it look for the name - String pathToReport = path + "CURRENT_OPEN/"+reportFileName+".d4st"; - _log.trace("WF PathToReport = " + pathToReport); - fis = new FileInputStream(pathToReport); - in = new ObjectInputStream(fis); - toConvert = (Model) in.readObject(); - in.close(); - } catch (IOException ex) { - ex.printStackTrace(); - } catch (ClassNotFoundException ex) { - ex.printStackTrace(); - } - toConvert.setTemplateName(documentName); - _log.debug("Converting fileToRead to Serializable object, model name: \n" + toConvert.getTemplateName()); - Model toReturn = (toConvert); - - //saves this model as previous one in session - getASLSession().setAttribute(PREVIOUS_REPORT_INSTANCE, toConvert); - - AccessLogger log = AccessLogger.getAccessLogger(); - OpenWorkflowLogEntry logEntry = new OpenWorkflowLogEntry(toConvert.getTemplateName(), toConvert.getUniqueID(), toConvert.getAuthor()); - log.logEntry(getASLSession().getUsername(), getASLSession().getScopeName(), logEntry); - - return toReturn; - - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - } - - /** - * get the report instance from the Basket - * @param repTmp . - * @param pathToFile the directory where to save the file - * @param filename the filename to give to the newly created file - * @return - */ - private File writeReportToDisk(InputStream isData, String pathToFile, String filename) { - try { - File dir = new File(pathToFile); - _log.debug("DIR: " + pathToFile); - if (! dir.exists() ) - dir.mkdirs(); - - File f = new File(pathToFile+filename); - OutputStream out = new FileOutputStream(f); - - IOUtils.copy(isData, out); - out.close(); - _log.debug("Successfully WROTE ReportTemplate from DL: " + pathToFile); - return f; - } - catch (IOException e){ - e.printStackTrace(); - return null; - } - } - /** - * update the Workflow Document in session - */ - public void updateWorkflowDocument(Model toSave, boolean update) { - ASLSession session = getASLSession(); - ServiceUtil myUtil = new ServiceUtil(session); - - String workflowid = session.getAttribute(WfDocsLibrary.LAST_WORKFLOW_ID).toString(); - Model model = null; - String documentWorkflowOwnerId = store.getWorkflowById(workflowid).getAuthor(); - String documentWorkflowName = store.getWorkflowById(workflowid).getName(); - if (update) { - _log.debug("SAVING in WorkflowDocument Library "); - - model = (Model) toSave; - _log.debug("Trying to convert dynamic images ... "); - convertDynamicImagesFromHL(model); - - boolean result = myUtil.writeModel(model, "CURRENT_OPEN", getVreName(), getUsername()); - - if (!result) { - _log.error("Could not save report, serializing failed"); - } - else { - String templatePath = myUtil.getTemplateFolder(getVreName(), getUsername()) + "CURRENT_OPEN"; - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - _log.debug("Trying to zip folder: " + templatePath); - - String folderToZip = templatePath; - String outZip = templatePath+"-report.zip"; - - try { - ZipUtil.zipDir(outZip, folderToZip); - _log.debug("Folder zipped, result: "+ outZip); - InputStream isZip = new BufferedInputStream(new FileInputStream(outZip)); - - DocLibraryUtil.updateFileIntoDocLibrary(getASLSession(), workflowid, getBytesFromInputStream(isZip)); - _log.info("Updated in DOC LIB OK"); - store.addWorkflowLogAction(workflowid, getASLSession().getUsername(), "Updated"); - - //send the notification - NotificationsManager nm = new ApplicationNotificationsManager(session, "org.gcube.admin.portlet.wfdocviewer.server.WorkflowDocServiceImpl"); - nm.notifyDocumentWorkflowUpdate(documentWorkflowOwnerId, workflowid, documentWorkflowName); - - AccessLogger log = AccessLogger.getAccessLogger(); - SaveWorkflowLogEntry logEntry = new SaveWorkflowLogEntry(model.getTemplateName(), model.getUniqueID(), model.getAuthor()); - log.logEntry(getASLSession().getUsername(), getASLSession().getScopeName(), logEntry); - - } - catch (Exception e) { - _log.error("Could not zip template, serializing failed"); - e.printStackTrace(); - } - } - } else { - store.addWorkflowLogAction(workflowid, getASLSession().getUsername(), "Viewed"); - //send the notification - NotificationsManager nm = new ApplicationNotificationsManager(session, "org.gcube.admin.portlet.wfdocviewer.server.WorkflowDocServiceImpl"); - nm.notifyDocumentWorkflowView(documentWorkflowOwnerId, workflowid, documentWorkflowName); - } - //unlocks - unlock(workflowid); - getASLSession().setAttribute("idreport", null); - } + } /** * * @return the info about the current user @@ -1538,17 +1291,17 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe if (isWithinPortal()) { - UserModel user = UserLocalServiceUtil.getUserByScreenName(OrganizationsUtil.getCompany().getCompanyId(), username); - thumbnailURL = "/image/user_male_portrait?img_id="+user.getPortraitId(); - fullName = user.getFirstName() + " " + user.getLastName(); - email = user.getEmailAddress(); - UserBean toReturn = new UserBean(username, fullName, thumbnailURL, user.getEmailAddress()); - _log.info("Returning USER: " + toReturn); + GCubeUser user = new LiferayUserManager().getUserByUsername(username); + thumbnailURL = user.getUserAvatarURL(); + fullName = user.getFullname(); + email = user.getEmail(); + UserBean toReturn = new UserBean(username, fullName, thumbnailURL, email); + _log.debug("Returning USER: " + toReturn); return toReturn; } else { UserBean toReturn = new UserBean(getASLSession().getUsername(), fullName, thumbnailURL, email); - _log.info("Returning test USER: " + toReturn); + _log.debug("Returning test USER: " + toReturn); return toReturn; } @@ -1564,45 +1317,11 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe try { IOUtils.copy(is, os); } catch (IOException e) { - // TODO Auto-generated catch block e.printStackTrace(); } return os.toByteArray(); } - /** - * - * @param workflowid . - */ - private void unlock(String workflowid) { - DLFileEntry fileEntry; - try { - fileEntry = DocLibraryUtil.getFileEntry(getASLSession(), workflowid); - _log.info("Log action saved, trying ot unlock document ..."); - LockLocalServiceUtil.unlock(DLFileEntry.class.getName(), fileEntry.getFileEntryId()); - _log.info("UNLOCK OK!"); - } - catch (Exception e) { - e.printStackTrace(); - } - } - - public void renewLock() { - HttpSession httpSes = this.getThreadLocalRequest().getSession(); - httpSes.setMaxInactiveInterval(-1); //session won't expire - String workflowid = getASLSession().getAttribute(WfDocsLibrary.LAST_WORKFLOW_ID).toString(); - try { - DLFileEntry fileEntry = DocLibraryUtil.getFileEntry(getASLSession(), workflowid); - _log.info("Renewing Lock ..."); - long fifteenMin = 900000; - Date currTimePlus15 = new Date(new Date().getTime() + fifteenMin); - LockLocalServiceUtil.getLock(DLFileEntry.class.getName(), fileEntry.getFileEntryId()).setExpirationDate(currTimePlus15); - _log.info("Lock Renewed, expiring: " + currTimePlus15); - } catch (Exception e) { - e.printStackTrace(); - } - - } - + @Override public String save(String filePath, String workspaceFolderId, String itemName, TypeExporter type, boolean overwrite) throws SaveReportFileException, SaveReportFileExistException { try { @@ -1655,7 +1374,7 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe RSGAccessPoint rsgWsAddr = getRSGWSAddress(); if (rsgReadClient == null) { rsgReadClient = new RsgReadClient(rsgWsAddr.getRestUrl()); - System.out.println("rsgReadClient = new RsgReadClient(rsgWsAddr.getRestUrl()"+rsgWsAddr.getRestUrl()); + _log.info("rsgReadClient = new RsgReadClient(rsgWsAddr.getRestUrl()"+rsgWsAddr.getRestUrl()); } return rsgReadClient; } @@ -1667,7 +1386,7 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe try { rsgWriteClient.secureWithPlainTokenSecurity(rsgWsAddr.getTokenUrl()); - System.out.println("rsgWriteClient.secureWithPlainTokenSecurity(rsgWsAddr.getTokenUrl())"+rsgWsAddr.getTokenUrl()); + _log.info("rsgWriteClient.secureWithPlainTokenSecurity(rsgWsAddr.getTokenUrl())"+rsgWsAddr.getTokenUrl()); } catch (MalformedURLException e) { e.printStackTrace(); } @@ -1687,12 +1406,13 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe RoleManager rm = new LiferayRoleManager(); ASLSession session = getASLSession(); try { - User theUser = OrganizationsUtil.validateUser(session.getUsername()); - List roles = rm.listRolesByUserAndGroup(""+session.getGroupId(), ""+theUser.getUserId()); - for (RoleModel role : roles) { - _log.info("Role " + role.getRoleName() + " Adding RFMO"); - if (role.getRoleName().endsWith("-Editor")) { - String[] splits = role.getRoleName().split("-"); + GCubeUser theUser = new LiferayUserManager().getUserByUsername(session.getUsername()); + long groupId = new LiferayGroupManager().getGroupIdFromInfrastructureScope(session.getScope()); + List roles = rm.listTeamsByUserAndGroup(theUser.getUserId(), groupId); + for (GCubeTeam team : roles) { + _log.info("VRE Group " + team.getTeamName() + " Adding RFMO"); + if (team.getTeamName().endsWith("-Editor")) { + String[] splits = team.getTeamName().split("-"); toReturn.add(splits[0]); _log.info("Added grant for RFMO="+splits[0]); } @@ -1712,10 +1432,11 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe ASLSession session = getASLSession(); try { - User theUser = OrganizationsUtil.validateUser(session.getUsername()); - List roles = rm.listRolesByUserAndGroup(""+session.getGroupId(), ""+theUser.getUserId()); - for (RoleModel role : roles) - if (role.getRoleName().equalsIgnoreCase("VRE-Manager")) return true; + long groupId = new LiferayGroupManager().getGroupIdFromInfrastructureScope(session.getScope()); + GCubeUser theUser = new LiferayUserManager().getUserByUsername(session.getUsername()); + List roles = rm.listRolesByUserAndGroup(theUser.getUserId(), groupId); + for (GCubeRole role : roles) + if (role.getRoleName().equals(GatewayRolesNames.VRE_MANAGER.getRoleName())) return true; } catch (Exception e) { e.printStackTrace(); @@ -1996,6 +1717,8 @@ public class ReportServiceImpl extends RemoteServiceServlet implements ReportSe } RSGAccessPoint rsgAp = new RSGAccessPoint(host+address, iMarineSkrURL, vmeSkrURL, password); setRSGWSAddress(rsgAp); + + new RsgReadClient(rsgAp.getRestUrl()); return true; } else return false; diff --git a/src/main/webapp/WEB-INF/liferay-display.xml b/src/main/webapp/WEB-INF/liferay-display.xml index ae4c1f4..a61999b 100644 --- a/src/main/webapp/WEB-INF/liferay-display.xml +++ b/src/main/webapp/WEB-INF/liferay-display.xml @@ -1,5 +1,5 @@ - + diff --git a/src/main/webapp/WEB-INF/liferay-portlet.xml b/src/main/webapp/WEB-INF/liferay-portlet.xml index fe41288..c4e0229 100644 --- a/src/main/webapp/WEB-INF/liferay-portlet.xml +++ b/src/main/webapp/WEB-INF/liferay-portlet.xml @@ -1,5 +1,5 @@ - +