This repository has been archived on 2021-11-25. You can view files and clone it, but cannot push or open issues or pull requests.
vmereports-manager-portlet/src/main/java/org/gcube/portlets/user/reportgenerator/server/servlet/ReportServiceImpl.java

1752 lines
55 KiB
Java

package org.gcube.portlets.user.reportgenerator.server.servlet;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
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;
import javax.servlet.http.HttpSession;
import net.sf.csv4j.CSVFileProcessor;
import net.sf.csv4j.CSVLineProcessor;
import net.sf.csv4j.ParseException;
import net.sf.csv4j.ProcessingException;
import org.apache.commons.io.IOUtils;
import org.gcube.application.framework.accesslogger.library.impl.AccessLogger;
import org.gcube.application.framework.core.session.ASLSession;
import org.gcube.application.framework.core.session.SessionManager;
import org.gcube.applicationsupportlayer.social.ApplicationNotificationsManager;
import org.gcube.applicationsupportlayer.social.NotificationsManager;
import org.gcube.common.core.scope.GCUBEScope.MalformedScopeExpressionException;
import org.gcube.common.core.utils.logging.GCUBEClientLog;
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.client.ComponentType;
import org.gcube.portlets.d4sreporting.common.server.ServiceUtil;
import org.gcube.portlets.d4sreporting.common.shared.SerializableComponent;
import org.gcube.portlets.d4sreporting.common.shared.SerializableModel;
import org.gcube.portlets.d4sreporting.common.shared.SerializableSection;
import org.gcube.portlets.d4sreporting.common.shared.SerializableTable;
import org.gcube.portlets.d4sreporting.common.shared.SerializableTimeSeries;
import org.gcube.portlets.d4sreporting.common.shared.TableCell;
import org.gcube.portlets.docxgenerator.DocxGenerator;
import org.gcube.portlets.user.homelibrary.home.HomeLibrary;
import org.gcube.portlets.user.homelibrary.home.exceptions.HomeNotFoundException;
import org.gcube.portlets.user.homelibrary.home.exceptions.InternalErrorException;
import org.gcube.portlets.user.homelibrary.home.workspace.Workspace;
import org.gcube.portlets.user.homelibrary.home.workspace.WorkspaceFolder;
import org.gcube.portlets.user.homelibrary.home.workspace.WorkspaceItem;
import org.gcube.portlets.user.homelibrary.home.workspace.WorkspaceItemType;
import org.gcube.portlets.user.homelibrary.home.workspace.exceptions.InsufficientPrivilegesException;
import org.gcube.portlets.user.homelibrary.home.workspace.exceptions.ItemAlreadyExistException;
import org.gcube.portlets.user.homelibrary.home.workspace.exceptions.ItemNotFoundException;
import org.gcube.portlets.user.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException;
import org.gcube.portlets.user.homelibrary.home.workspace.folder.FolderItem;
import org.gcube.portlets.user.homelibrary.home.workspace.folder.FolderItemType;
import org.gcube.portlets.user.homelibrary.home.workspace.folder.items.ExternalImage;
import org.gcube.portlets.user.homelibrary.home.workspace.folder.items.Report;
import org.gcube.portlets.user.homelibrary.home.workspace.folder.items.ReportTemplate;
import org.gcube.portlets.user.homelibrary.home.workspace.folder.items.gcube.ImageDocument;
import org.gcube.portlets.user.homelibrary.home.workspace.folder.items.ts.TimeSeries;
import org.gcube.portlets.user.reportgenerator.client.ReportConstants;
import org.gcube.portlets.user.reportgenerator.client.ReportService;
import org.gcube.portlets.user.reportgenerator.client.model.ExportManifestationType;
import org.gcube.portlets.user.reportgenerator.server.servlet.loggers.CreateReportLogEntry;
import org.gcube.portlets.user.reportgenerator.server.servlet.loggers.GenerateReportLogEntry;
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.SessionInfo;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.liferay.portal.service.LockLocalServiceUtil;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
/**
*
* class implementing services
* @author Massimiliano Assante, ISTI-CNR - massimiliano.assante@isti.cnr.it
* @version Feb 2012 (3.3)
*/
@SuppressWarnings("serial")
public class ReportServiceImpl extends RemoteServiceServlet implements ReportService {
public static GCUBEClientLog logger = new GCUBEClientLog(ReportServiceImpl.class);
/**
* EXPORT DIR
*/
private static final String EXPORTS_DIR = "EXPORTS";
/**
*
*/
public static final String USERNAME_ATTRIBUTE = "user";
/**
*
*/
public static final String GIF = "image/gif";
/**
*
*/
public static final String PNG = "image/png";
/**
*
*/
public static final String JPEG = "image/jpeg";
/**
*
*/
public static final String JPG = "image/jpg";
/**
*
*/
public static final String TIFF = "image/tiff";
/**
*
*/
public static final String BMP = "image/bmp";
/**
*
*/
public static final String CURRENT_REPORT_ID_ATTRIBUTE = "CURRENT_REPORT_ID_ATTRIBUTE";
/**
*
*/
public static final String CURRENT_REPORT_INSTANCE = "myReport";
/**
*
*/
public static final String PREVIOUS_REPORT_INSTANCE = "myPreviousReport";
private String currentHost = "";
/**
* the WF DB Store
*/
private Store store;
//set to true if wanna test workflow menu mode
boolean testWorkflow = false;
/**
* Called then servlet is intialized
*/
public void init() {
logger.info("Initializing Servlet ReportServiceImpl...");
store = new MyDerbyStore();
}
/**
* the current ASLSession
* @return .
*/
private ASLSession getASLSession() {
String sessionID = this.getThreadLocalRequest().getSession().getId();
String user = (String) this.getThreadLocalRequest().getSession().getAttribute(ScopeHelper.USERNAME_ATTRIBUTE);
logger.error("Report PORTLET SessionID= " + sessionID);
if (user == null) {
user = "massimiliano.assante";
this.getThreadLocalRequest().getSession().setAttribute(ScopeHelper.USERNAME_ATTRIBUTE, user);
SessionManager.getInstance().getASLSession(sessionID, user).setScope("/gcube/devsec");
}
return SessionManager.getInstance().getASLSession(sessionID, user);
}
/**
* Retrieve the user saved template names
*
* @return a String[] containing the template names
*/
public String[] getUserTemplateNames() {
ServiceUtil myUtil = new ServiceUtil(getASLSession());
Vector<String> tmp = new Vector<String>();
String userDir = myUtil.getTemplateFolder(getVreName(), getUsername());
logger.debug("userDir: " + userDir);
File f = new File(userDir);
//checking if dir exists
if (! f.exists()) {
try {
f.mkdirs();
return new String[0];
} catch (SecurityException ex) {
return new String[0];
}
}
else {
File []f2 = f.listFiles();
for(int i = 0; i < f2.length; i++){
if(f2[i].isDirectory()) {
tmp.add(f2[i].getName());
}
}
return tmp.toArray(new String[0]);
}
}
/**
* @return a SerializableModel instance of the imported fimes xml
*/
public SerializableModel readImportedModel(String tempPath) {
SerializableModel toConvert = null;
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(tempPath);
in = new ObjectInputStream(fis);
toConvert = (SerializableModel) in.readObject();
in.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
logger.debug("Converting Imported Fimes to Serializable object, num sectionss: " + toConvert.getSections().size());
return (toConvert);
}
/**
* @return a SerializableModel instance of the templatename passed as parameter
* @param templateName : the template to read from disk
* @param templateObjectID the id in the basket
* @param isTemplate says if you're opening a template or a report
* @param isImporting says if your importing or youre loading a template in the UI
*
*/
public SerializableModel readModel(String templateName, String templateObjectID, boolean isTemplate, boolean isImporting) {
ServiceUtil myUtil = new ServiceUtil(getASLSession());
logger.debug("Reading " + templateName);
if (! ReportConstants.isDeployed) {
SerializableModel toConvert = null;
FileInputStream fis = null;
ObjectInputStream in = null;
try {
String path = myUtil.getTemplateFolder(getVreName(), getUsername());
fis = new FileInputStream(path + "CURRENT_OPEN/CURRENT_OPEN.d4st");
in = new ObjectInputStream(fis);
toConvert = (SerializableModel) in.readObject();
in.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
logger.debug("Converting fileToRead to Serializable object");
return toConvert;
} else {
Workspace root = null;
try {
root = getWorkspaceArea();
} catch (WorkspaceFolderNotFoundException e) {
e.printStackTrace();
} catch (InternalErrorException e) {
e.printStackTrace();
} catch (HomeNotFoundException e) {
e.printStackTrace();
}
WorkspaceItem item = null;
try {
item = root.getItem(templateObjectID);
if (! isImporting)
storeReportItemIDInSession(templateObjectID);
} catch (ItemNotFoundException e) {
e.printStackTrace();
}
logger.debug("getItem: " + templateObjectID);
String zipToExtract = "";
if (item.getType() == WorkspaceItemType.FOLDER_ITEM) {
logger.debug("\nItem is a BASKET_ITEM");
FolderItem bi = (FolderItem) item;
boolean fromBasket = false;
if (isTemplate) {
if (bi.getFolderItemType() == FolderItemType.REPORT_TEMPLATE) {
ReportTemplate zippedTemplate = (ReportTemplate) bi;
String zipFilename = "";
if (! isTemplate) {//then is a report
zipFilename = templateName + "-report.zip"; //gCube report
logger.debug("********************** Reading report -----------------");
}
else
zipFilename = templateName + ".zip"; //gCube template
String zipPath = myUtil.getTemplatePath(templateName, getVreName(), getUsername());
fromBasket = getTemplateFromBasket(zippedTemplate, zipPath, zipFilename);
zipToExtract = zipPath + zipFilename;
}
}
if (bi.getFolderItemType() == FolderItemType.REPORT) {
logger.debug("Item is a REPORT");
Report zippedTemplate = (Report) bi;
String zipFilename = "";
if (! isTemplate) {//then is a report
zipFilename = templateName + "-report.zip"; //d4science template
logger.debug("********************** Reading report -----------------");
}
else
zipFilename = templateName + ".zip"; //d4science template
File toDelete = new File(zipFilename);
toDelete.delete();
String zipPath = myUtil.getTemplatePath(templateName, getVreName(), getUsername());
fromBasket = getReportFromBasket(zippedTemplate, zipPath, zipFilename);
zipToExtract = zipPath + zipFilename;
}
if (bi.getFolderItemType() == FolderItemType.REPORT || bi.getFolderItemType() == FolderItemType.REPORT_TEMPLATE) {
if (fromBasket) {
File toExtract = new File(zipToExtract);
File outputDir = new File( myUtil.getTemplatePath(templateName, getVreName(), getUsername()) );
ZipUtil.unzipArchive(toExtract, outputDir);
String templatePath = myUtil.getTemplatePath(templateName, getVreName(), getUsername());
String modelFilename = "";
try {
modelFilename = seekModel(templatePath, templateName);
} catch (FileNotFoundException e) { e.printStackTrace(); }
String fileToRead = templatePath + modelFilename + ".d4st" ;
//TODO: check
// String fileToCheck = templatePath + "gCube-label.d4s" ; //lo deve anche cancellare
// File file2Check = new File(fileToCheck);
// Logger.debug("Checking: " + fileToCheck);
// if (! file2Check.exists()) {
// Logger.debug("Not Found: " + fileToCheck);
// return new SerializableModel(950);
// } else {
// file2Check.delete();
// }
logger.debug("Loading fileToRead from Disk");
SerializableModel toReturn = null;
SerializableModel toConvert = null;
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(fileToRead);
in = new ObjectInputStream(fis);
toConvert = (SerializableModel) in.readObject();
in.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
logger.debug("Converting fileToRead to Serializable object");
toReturn = (toConvert);
// changes the template name model
toReturn.setTemplateName(templateName);
File toDelete1 = new File( myUtil.getTemplatePath(templateName, getVreName(), getUsername()));
boolean deleted1 = toDelete1.delete();
File toDelete2 = new File(zipToExtract);
boolean deleted2 = toDelete2.delete();
logger.debug("dirToDelete: " + toDelete1 + " result: " + deleted1 + " \n\n\n");
logger.debug("dirToDelete: " + toDelete2 + " result: " + deleted2 + " \n\n\n");
//**** IMPORTANT ****
if (! isImporting) {
storeTemplateInSession(toReturn);
logger.debug("storeTemplateInSession DONE");
}
AccessLogger log = AccessLogger.getAccessLogger();
OpenReportLogEntry logEntry = new OpenReportLogEntry(toReturn.getTemplateName(), templateObjectID);
log.logEntry(getASLSession().getUsername(), getASLSession().getScopeName(), logEntry);
return toReturn;
}
}
logger.error("FAILED TO READ RETURING EMPTY Serializable Template");
return new SerializableModel();
}
logger.error("FAILED TO READ FROM BASKET RETURING EMPTY Serializable Template");
return new SerializableModel();
}
}
/**
* handles the case that the user has changed the template name in the basket
* @param templatePath
* @param templateName
* @return
* @throws FileNotFoundException
*/
private String seekModel(String templatePath, String templateName) throws FileNotFoundException {
logger.debug("seekModel: tPath=" + templatePath);
String fileToSeek = templatePath + templateName + ".d4st";
File toSeek = new File(fileToSeek);
if (toSeek.exists()) {
logger.debug("seekModel: modelName is the SAME returning");
return templateName;
}
else {
logger.debug("seekModel: modelName DIFFERENT upgrading");
File dirToLookIn = new File(templatePath);
File[] innerFiles = dirToLookIn.listFiles();
for (int i = 0; i < innerFiles.length; i++)
if (innerFiles[i].getName().endsWith(".d4st")) {
String toReturn = innerFiles[i].getName();
toReturn = toReturn.substring(0, toReturn.length()-5);
logger.debug("seekModel: returning.. =" + toReturn);
return toReturn;
}
}
throw new FileNotFoundException();
}
/**
* get the template instance from the Basket
* @param repTmp
* @return
*/
private boolean getTemplateFromBasket(ReportTemplate repTmp, String pathToFile, String filename) {
try {
File dir = new File(pathToFile);
logger.debug("DIR: " + pathToFile);
if (! dir.exists() )
dir.mkdirs();
File f = new File(pathToFile+filename);
InputStream inputStream = null;
try {
inputStream = repTmp.getData();
} catch (InternalErrorException e) {
e.printStackTrace();
return false;
}
OutputStream out = new FileOutputStream(f);
byte buf[] = new byte[1024];
int len;
while((len = inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
logger.info("Successfully got ReportTemplate from Basket: " + pathToFile);
return true;
}
catch (IOException e){
e.printStackTrace();
return false;
}
}
/**
* 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 boolean getReportFromBasket(Report repTmp, String pathToFile, String filename) {
try {
File dir = new File(pathToFile);
logger.debug("DIR: " + pathToFile);
if (! dir.exists() )
dir.mkdirs();
File f = new File(pathToFile+filename);
InputStream inputStream = null;
try {
inputStream = repTmp.getData();
} catch (InternalErrorException e) {
e.printStackTrace();
return false;
}
OutputStream out = new FileOutputStream(f);
byte buf[] = new byte[1024];
int len;
while((len = inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
logger.info("Successfully got ReportTemplate from Basket: " + pathToFile);
return true;
}
catch (IOException e){
e.printStackTrace();
return false;
}
}
/**
*
*/
public String generateTempDocx(SerializableModel model) {
logger.info("Generating docx file");
DocxGenerator docxGenerator = new DocxGenerator(model);
logger.debug("DocxGenerator instanciated:");
boolean result = docxGenerator.exportInDocx(model);
logger.trace("RESULT:" + result);
if (! result)
return "ERROR";
File docx = null;
try {
docx = docxGenerator.writeOutputTempFile(model.getTemplateName());
} catch (Exception e) {
e.printStackTrace();
return "ERROR";
}
logger.info("Generated docx file: " + docx.getAbsolutePath());
return docx.getAbsolutePath();
}
/**
* @param model the model
* @param type the type
* @return true if the generatePDF is successful
*/
public boolean generateManifestation(SerializableModel model, ExportManifestationType type) {
//in case there are dynamic images need to get the from the HL
importDynamicImagesFromHL(model);
//in case there are dynamic TS need to get the CSV from HL and add it to the component
for (SerializableSection section : model.getSections()) {
for (SerializableComponent tc : section.getComponents()) {
if (tc.getType() == ComponentType.TIME_SERIES) {
SerializableTimeSeries sts = (SerializableTimeSeries) tc.getPossibleContent();
File toPass = getTimeSeriesFromWorkspace(sts);
if (toPass == null)
tc.setPossibleContent(null);
else {
sts.setCsvFile(toPass.getAbsolutePath());
tc.setPossibleContent(sts);
}
}
}
}
boolean result = false;
ServiceUtil myUtil = new ServiceUtil(getASLSession());
logger.info("Generating docx file");
logger.debug("Model Converted");
DocxGenerator docxGenerator = new DocxGenerator(model);
logger.info("DocxGenerator instanciated:");
result = docxGenerator.exportInDocx(model);
logger.trace("RESULT:" + result);
//remove the extension
String exportName = model.getTemplateName();
if (exportName.endsWith(".d4sT") || exportName.endsWith(".d4sR") )
exportName = model.getTemplateName().substring(0, model.getTemplateName().length() - 5);
if (result) {
switch (type) {
case DOCX:
try {
File docx = docxGenerator.writeOutputTempFile(exportName);
logger.debug("Generated docx file: " + docx.getAbsolutePath());
File toMoveTo = new File(myUtil.getTemplateFolder(getVreName(), getUsername()) + EXPORTS_DIR + File.separator + exportName + ".docx");
String folder = (myUtil.getTemplateFolder(getVreName(), getUsername()) + EXPORTS_DIR + File.separator);
myUtil.copyFile(docx, toMoveTo, folder);
logger.trace("1 File Copied to " + toMoveTo.getAbsolutePath());
String name = exportName+".docx";
String desc = name;
String mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
saveInWorkSpace(name, desc, mimeType, toMoveTo, type);
} catch (Exception e) {
e.printStackTrace();
}
break;
case HTML:
try {
File html = docxGenerator.createHTML();
logger.info("Generated HTML file: " + html.getAbsolutePath());
File toMoveTo = new File(myUtil.getTemplateFolder(getVreName(), getUsername()) + EXPORTS_DIR + File.separator + exportName + ".html");
String folder = (myUtil.getTemplateFolder(getVreName(), getUsername()) + EXPORTS_DIR + File.separator);
myUtil.copyFile(html, toMoveTo, folder);
logger.trace("1 File Copied to " + toMoveTo.getAbsolutePath());
String name = exportName+".html";
String desc = name;
String mimeType = "text/html";
saveInWorkSpace(name, desc, mimeType, toMoveTo, type);
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
break;
}
}
return result;
}
/**
* save the manifestation in default folder, overwrites if the file name exists already
*
* @param name the name in the Workspace
* @param desc the desc
* @param mimeType its mimetype
* @param payLoad a File instance
*/
private boolean saveInWorkSpace(String name, String desc, String mimeType, File payLoad, ExportManifestationType type ) {
try {
String defaultBasketID = getDefaultBasket();
// Read the pdf input stream
InputStream inputStream = new BufferedInputStream(new FileInputStream(payLoad));
Workspace wp = getWorkspaceArea();
WorkspaceFolder toSaveIn = wp.getRoot();
if (toSaveIn.exists(name)) {
logger.warn("Item exists already, deleting and creating new one");
toSaveIn.removeChild(toSaveIn.find(name));
}
if (type == ExportManifestationType.PDF) {
wp.createExternalPDFFile(name, name, mimeType, inputStream, defaultBasketID);
} else
wp.createExternalFile(name, name, mimeType, inputStream, defaultBasketID);
AccessLogger log = AccessLogger.getAccessLogger();
GenerateReportLogEntry logEntry = new GenerateReportLogEntry(name, mimeType, type.toString());
log.logEntry(getASLSession().getUsername(), getASLSession().getScopeName(), logEntry);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* @return the shared session
*/
public String getUsername() {
if (! ReportConstants.isDeployed) {
return "massimiliano.assante";
} else {
HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
HttpSession session = httpServletRequest.getSession();
String user = (String) session.getAttribute(ScopeHelper.USERNAME_ATTRIBUTE);
if(session.getAttribute(ScopeHelper.USERNAME_ATTRIBUTE)== null)
{
user = "massimiliano.assante";
logger.warn("D4ScienceSession user NULL set to: " + user);
}
logger.warn("ASLSession user: " + user);
ASLSession d4session = SessionManager.getInstance().getASLSession(session.getId(), user);
d4session.setAttribute(ScopeHelper.USERNAME_ATTRIBUTE, user);
return user;
}
}
/**
*
* @return the current scope
*/
public String getVreName() {
if (! ReportConstants.isDeployed) {
return "d4science.research-infrastructures.eu/FARM/FCPPS";
} else {
HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
HttpSession session = httpServletRequest.getSession();
ASLSession d4session = SessionManager.getInstance().getASLSession(session.getId(), getUsername());
String scope = d4session.getScopeName();
if(scope == null) {
scope = "gcube/devsec";
logger.warn("ASL Session scope NULL set to: " + scope);
}
//need to remove the initial / of the scope
if (scope.charAt(0) == '/')
scope = scope.substring(1, scope.length());
logger.info("SCOPE: " + scope);
return scope;
}
}
/**
*
* @return an instance of the user WorkspaceArea
* @throws HomeNotFoundException
* @throws InternalErrorException
* @throws WorkspaceFolderNotFoundException
* @throws WorkspaceNotFoundException
* @throws InternalErrorException
* @throws HomeNotFoundException
*/
protected Workspace getWorkspaceArea() throws WorkspaceFolderNotFoundException, InternalErrorException, HomeNotFoundException {
return HomeLibrary.getUserWorkspace(getASLSession());
}
/**
* reads from the file system and returns the user workspace as TreeNode object
*
* @return the Default basket if if there is no basket in session, else the basket in session id
*/
public String getDefaultBasket() {
logger.info("getDefaultBasket()");
try {
Workspace workspaceArea = getWorkspaceArea();
WorkspaceFolder basket = workspaceArea.getRoot();
return basket.getId();
} catch (MalformedScopeExpressionException e) { e.printStackTrace();
} catch (InternalErrorException e) {e.printStackTrace();
} catch (HomeNotFoundException e) { e.printStackTrace();
} catch (WorkspaceFolderNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Coud not open default basket";
}
/**
*
* @return the model previously stored in the session
*/
public SerializableModel readTemplateFromSession() {
ASLSession d4Session = getASLSession();
String templateid = (String) d4Session.getAttribute("idreport");
Object workflowid = getASLSession().getAttribute(WfDocsLibrary.LAST_WORKFLOW_ID);
logger.debug(" (templateid != null && workflowid != null) = " + (templateid != null) + " - " + (workflowid != null));
if (workflowid != null) {
getASLSession().setAttribute(WfDocsLibrary.LAST_WORKFLOW_ID, null);
return null;
}
String templateName = "";
logger.debug("TEMPLATE ID==NULL " + (templateid == null));
if (templateid != null) {
if (! templateid.equals("")) {
logger.debug("READING SESSION VARIABLE FOR REPORT ID... " + templateid);
//reset the value
d4Session.setAttribute("idreport", "");
Workspace root = null;
WorkspaceItem item = null;
try {
root = getWorkspaceArea();
item = root.getItem(templateid);
logger.info("READ REPORT FROM WP... " + item.getName());
templateName = item.getName();
} catch (WorkspaceFolderNotFoundException e) {e.printStackTrace();
} catch (InternalErrorException e) { e.printStackTrace();
} catch (HomeNotFoundException e) { e.printStackTrace();
} catch (ItemNotFoundException e) { e.printStackTrace();}
SerializableModel toReturn = readModel(templateName, templateid, false, false);
return toReturn;
}
if (d4Session.getAttribute(CURRENT_REPORT_INSTANCE) != null)
return (SerializableModel) d4Session.getAttribute(CURRENT_REPORT_INSTANCE) ;
return null;
}
else {
if (d4Session.getAttribute(CURRENT_REPORT_INSTANCE) != null) {
logger.debug("getAttribute(\"CURRENT_REPORT_INSTANCE\")...");
SerializableModel model = (SerializableModel) d4Session.getAttribute(CURRENT_REPORT_INSTANCE) ;
logger.debug(model.getTemplateName());
return model;
}
}
ServiceUtil myUtil = new ServiceUtil(getASLSession());
String dirToClean = myUtil.getTemplateFolder(getVreName(), getUsername());
logger.info("RETURNING NULL, going to clean user template area: " + dirToClean);
if (ReportConstants.isDeployed)
delTemplateDir(new File(dirToClean));
return null;
}
/**
* recurdively delete the templates folder of the dir dir
* @param dir the dir to delete
*/
public void delTemplateDir(File dir) {
try {
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory())
delTemplateDir(files[i]);
files[i].delete();
}
} catch (Exception e) {
System.out.println("WARNING: Could not cleaning temp dir: reason unknown");
}
}
/**
* @param model to store in the session
*/
public void storeTemplateInSession(SerializableModel model) {
ASLSession d4Session = getASLSession();
d4Session.setAttribute(CURRENT_REPORT_INSTANCE, model);
// Vector<SerialazableSection> sections = model.getSections();
// for (SerialazableSection section : sections) {
// for (SerializableComponent component : section.getComponents()) {
// if (component.getType() == ComponentType.DYNA_IMAGE) {
// Logger.debug("\n\n****FOUND DYNA IMAGE ID In Basket: " + component.getIdInBasket());
// }
// }
// }
}
private void importDynamicImagesFromHL(SerializableModel model) {
ServiceUtil myUtil = new ServiceUtil(getASLSession());
logger.debug("model == NULL " + (model == null));
Vector<SerializableSection> sections = model.getSections();
for (SerializableSection section : sections) {
logger.debug("\n\n****section.getComponents() == NULL " + (section.getComponents() == null));
for (SerializableComponent component : section.getComponents()) {
if (component.getType() == ComponentType.DYNA_IMAGE) {
logger.debug("Found DP: " + component.getPossibleContent());
logger.debug("ID In Basket null?: " + (component.getIdInBasket() == null));
if (component.getIdInBasket() != null) {
String imageID = component.getIdInBasket();
String imageNameFile = getRandom(12);
String imageTargetDIR = myUtil.getTemplatePath(model.getTemplateName(), getVreName(), getUsername()) + "images" + File.separator;
imageNameFile = copyImageFromBasket(imageID, imageTargetDIR, imageNameFile);
component.setPossibleContent(getImageURL(imageNameFile, model.getTemplateName()));
logger.trace("NEW setPossibleContent: " + component.getPossibleContent());
}
}
}
}
}
/**
*
* @param imageName
* @param templateName
* @return
*/
private String getImageURL(String imageName, String templateName) {
String toReturn = currentHost + "usersArea/" + getVreName() + "/templates/" + getUsername() + "/CURRENT_OPEN/images/" + imageName;
logger.info("getImageURL" + toReturn);
return toReturn;
}
/**
*
* @param imageIDinBasket .
* @param pathToFile the directory where to save the file
* @param filename the filename to give to the newly created file
* @return the file imagename with its extension
*/
private String copyImageFromBasket(String imageIDinBasket, String pathToFile, String filename) {
Workspace root = null;
try {
root = getWorkspaceArea();
} catch (WorkspaceFolderNotFoundException e) {e.printStackTrace();
} catch (InternalErrorException e) { e.printStackTrace();
} catch (HomeNotFoundException e) { e.printStackTrace();
}
WorkspaceItem item = null;
try {
item = root.getItem(imageIDinBasket);
} catch (ItemNotFoundException e) {
e.printStackTrace();
}
logger.debug("pathToFile: " + pathToFile);
File f = null;
String toReturn ="";
if (item.getType() == WorkspaceItemType.FOLDER_ITEM) {
logger.debug("\nItem is a BASKET_ITEM");
FolderItem bi = (FolderItem) item;
try {
File dir = new File(pathToFile);
logger.debug("DIR: " + pathToFile);
if (! dir.exists() )
dir.mkdirs();
InputStream data = null;
if (bi.getFolderItemType()==FolderItemType.EXTERNAL_IMAGE){
logger.debug("EXTERNAL_IMAGE -|- " + item.getType());
ExternalImage image = (ExternalImage)item;
data = image.getData();
}
if (bi.getFolderItemType()==FolderItemType.IMAGE_DOCUMENT){
ImageDocument image = (ImageDocument)item;
if (image.getMimeType().equals("image/tiff"))
data = image.getThumbnail();
else
data = image.getData();
}
toReturn = filename + "." + getImageExtension(bi);
f = new File(pathToFile+toReturn);
OutputStream out = new FileOutputStream(f);
byte buf[] = new byte[1024];
int len;
while((len = data.read(buf))>0)
out.write(buf,0,len);
out.close();
data.close();
}
catch (IOException e){
e.printStackTrace();
} catch (InternalErrorException e) {
e.printStackTrace();
}
}
logger.info("RETURNING: " + f.getAbsolutePath());
return toReturn;
}
/**
* return a string for the file extension given a mimetype
*
* @param bi the basketItem
* @return a string for the file extension given a mimetype
*/
public static String getImageExtension(FolderItem bi) {
String mimetype = "";
if (bi.getFolderItemType()==FolderItemType.EXTERNAL_IMAGE){
ExternalImage image = (ExternalImage) bi;
mimetype = image.getMimeType();
}
if (bi.getFolderItemType()==FolderItemType.IMAGE_DOCUMENT){
ImageDocument image = (ImageDocument) bi;
mimetype = image.getMimeType();
}
if (mimetype.equals(GIF))
return "gif";
else if (mimetype.equals(PNG))
return "png";
else if (mimetype.equals(JPG))
return "jpg";
else if (mimetype.equals(JPEG))
return "jpg";
else if (mimetype.equals(TIFF))
return "png";
else if (mimetype.equals(BMP))
return "bmp";
else
return "jpg";
}
/**
* generate a random uid
* @param length
* @return
*/
private String getRandom(int length) {
UUID uuid = UUID.randomUUID();
String myRandom = uuid.toString();
return myRandom.substring(length);
}
/**
* Copies a image from fromTemplate/images/imageNameFile to toTemplate/images/imageNameFile
* @param fromTemplate the origin template
* @param toTemplate the target template
* @param imageNameFile .
* @return true if the copy went fine
*/
public boolean copyImage(String fromTemplate, String toTemplate, String imageNameFile) {
ServiceUtil myUtil = new ServiceUtil(getASLSession());
String imageFrom = myUtil.getTemplatePath(fromTemplate, getVreName(), getUsername()) + "images" + File.separator + imageNameFile;
String imageTarget = myUtil.getTemplatePath(toTemplate, getVreName(), getUsername()) + "images" + File.separator + imageNameFile;
String imageNewFolder = myUtil.getTemplatePath(toTemplate, getVreName(), getUsername()) + "images" + File.separator;
logger.debug("Copying:\n" + imageFrom + "\nto: " + imageTarget);
File from = new File(imageFrom);
File to = new File(imageTarget);
try {
myUtil.copyFile(from, to, imageNewFolder);
} catch (Exception e) {
logger.error("Error While Copying: " + e.getMessage());
return false;
}
logger.debug("Copying Success\n");
return true;
}
/**
* @param reportItemid the report itemd id in basket to store in the session
*/
public void storeReportItemIDInSession(String reportItemid) {
ASLSession d4Session = getASLSession();
d4Session.setAttribute(CURRENT_REPORT_ID_ATTRIBUTE, reportItemid);
logger.debug("WROTE REPORT ID IN SESSION: " + reportItemid);
}
/**
* @return the report item id in basket, or "" if doesn't exist
*/
public String getReportItemIDFromSession() {
ASLSession d4Session = getASLSession();
if (d4Session.getAttribute(CURRENT_REPORT_ID_ATTRIBUTE) == null)
return "";
else
return d4Session.getAttribute(CURRENT_REPORT_ID_ATTRIBUTE).toString();
}
/**
* used to save the report in the same basket *
*/
public void saveReport() {
Workspace root = null;
try {
root = getWorkspaceArea();
} catch (WorkspaceFolderNotFoundException e) {e.printStackTrace();
} catch (InternalErrorException e) { e.printStackTrace();
} catch (HomeNotFoundException e) { e.printStackTrace();
}
WorkspaceItem item = null;
String folderid = "";
String itemName = "";
try {
if (getReportItemIDFromSession().equals("")) {
folderid = getDefaultBasket();
}
else {
logger.debug("getReportItemIDFromSession RETURNS -> " + getReportItemIDFromSession() + "");
item = root.getItem(getReportItemIDFromSession());
folderid = item.getParent().getId();
itemName = item.getName();
}
} catch (ItemNotFoundException e) {
logger.error("ITEM NOT FOUND -> " + getReportItemIDFromSession());
} catch (InternalErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.debug("folderid -> " + folderid);
saveReport(folderid, itemName);
}
/**
* @param basketidToSaveIn .
*
*/
public void saveReport(String folderid, String newname) {
SerializableModel model = readTemplateFromSession();
//raplacing " " with _
logger.info("Serializing Model basketidToSaveIn: " + folderid );
logger.info("Trying to convert dynamic images ... ");
importDynamicImagesFromHL(model);
ServiceUtil myUtil = new ServiceUtil(getASLSession());
boolean result = myUtil.writeModel(model, "CURRENT_OPEN", getVreName(), getUsername());
if (!result) {
logger.debug("Could not save report, serializing failed");
}
else {
String templatePath = myUtil.getTemplateFolder(getVreName(), getUsername()) + "CURRENT_OPEN";
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.debug("Trying to zip folder: " + templatePath);
String folderToZip = templatePath;
String outZip = templatePath+"-report.zip";
try {
ZipUtil.zipDir(outZip, folderToZip);
} catch (IOException e) {
logger.error("Could not zip template, serializing failed");
e.printStackTrace();
}
logger.info("Folder zipped, result: "+ outZip);
InputStream isZip = null;
WorkspaceFolder toSaveIn = null;
try {
isZip = new BufferedInputStream(new FileInputStream(outZip));
toSaveIn = getBasketInstance(folderid);
String templateName = newname;
if (templateName.endsWith("d4sR") ) {
if (toSaveIn.exists(templateName)) {
logger.warn("Item exists already, deleting and creating new one");
toSaveIn.removeChild(toSaveIn.find(templateName));
}
}
if (toSaveIn.exists(templateName + ".d4sR")) {
logger.warn("Item exists already, deleting and creating new one");
toSaveIn.removeChild(toSaveIn.find(templateName + ".d4sR"));
}
//remove the template extension
String templateToInsert = templateName.replace(".d4sT", "");
if (! templateToInsert.endsWith(".d4sR"))
templateToInsert+=".d4sR";
/**
* Create a Report into this basket.
* @param name the report name.
* @param description the report description.
* @param created the report creation time.
* @param lastEdit the last edit time.
* @param author the report author.
* @param lastEditBy the last report editor.
* @param templateName the source template name.
* @param numberOfSections the number of sections.
* @param status the report status.
* @param reportData the report data.
* @return the report.
* @throws InsufficientPrivilegesException if the user don't have sufficient privileges to perform this operation.
* @throws InternalErrorException if an internal error occurs.
* @throws ItemAlreadyExistException if an item with the specified name already exists.
*/
Calendar dateCreated = Calendar.getInstance();
dateCreated.setTime(model.getDateCreated());
Calendar lastEdit = Calendar.getInstance();
lastEdit.setTime(model.getLastEdit());
Report rep = toSaveIn.createReportItem(templateToInsert, templateToInsert, dateCreated, lastEdit,
model.getAuthor(), model.getLastEditBy(), templateToInsert, model.getSections().size(), "no-status", isZip);
//Report rep = toSaveIn.createReportItem(templateToInsert, templateToInsert, isZip);
storeReportItemIDInSession(rep.getId());
AccessLogger log = AccessLogger.getAccessLogger();
CreateReportLogEntry logEntry = new CreateReportLogEntry(model.getTemplateName(), rep.getId());
log.logEntry(getASLSession().getUsername(), getASLSession().getScopeName(), logEntry);
} catch (InsufficientPrivilegesException e) {
e.printStackTrace();
} catch (InternalErrorException e) {
e.printStackTrace();
} catch (ItemAlreadyExistException e) {
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ItemNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private boolean removeIfExist(String name2Check, WorkspaceFolder basket) throws InternalErrorException, InsufficientPrivilegesException {
List<WorkspaceItem> items = basket.getChildren();
for (WorkspaceItem item : items)
if (item.getName().equals(name2Check)) {
item.remove();
logger.info("ITEM REMOVED: "+ name2Check);
return true;
}
return false;
}
/**
* Return an instance of
* @param basketId
* @return
* @throws ItemNotFoundException
*/
private WorkspaceFolder getBasketInstance(String basketId) throws ItemNotFoundException {
Workspace root = null;
try {
root = getWorkspaceArea();
} catch (WorkspaceFolderNotFoundException e) {e.printStackTrace();
} catch (InternalErrorException e) { e.printStackTrace();
} catch (HomeNotFoundException e) { e.printStackTrace();
}
WorkspaceItem item = null;
try {
item = root.getItem(basketId);
} catch (ItemNotFoundException e) {
logger.info("BASKET : " + basketId + " NOT FOUND RETURNING DEFAULT ONE");
return(WorkspaceFolder)root.getItem(getDefaultBasket());
}
logger.debug("Item Type: "+item.getType());
if (item.getType() != WorkspaceItemType.FOLDER) {
logger.error("The item id does not belong to a basket id:" + basketId);
return null;
}
return (WorkspaceFolder) item;
}
/**
* return a sample of the given TS to the client
* @param sTS .
* @return .
*/
public SerializableTable getSampleTimeSeries(SerializableTimeSeries sTS) {
File csvTS = getTimeSeriesFromWorkspace(sTS);
SerializableTable toReturn = null;
try {
toReturn = parseCSV(csvTS, sTS);
} catch (ParseException e) { e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
} catch (ProcessingException e) { e.printStackTrace();
}
return toReturn;
}
/**
* retrieve the given TS csv representation and writes it into /tmp returning the File
* @param sTS serializable TS
* @return a File csv
*/
private File getTimeSeriesFromWorkspace(SerializableTimeSeries sTS) {
try {
String timeSeriesBasketID = sTS.getTsMetadata().getId();
Workspace root = null;
try {
root = getWorkspaceArea();
} catch (WorkspaceFolderNotFoundException e) {e.printStackTrace();
} catch (InternalErrorException e) { e.printStackTrace();
} catch (HomeNotFoundException e) { e.printStackTrace();
}
WorkspaceItem item = null;
try {
item = root.getItem(timeSeriesBasketID);
} catch (ItemNotFoundException e) {
e.printStackTrace();
}
logger.debug("Got Item TS From HL, Item Type: "+item.getType());
if (item.getType() != WorkspaceItemType.FOLDER_ITEM) {
logger.debug("The item id does not belong to a timeseries, id:" + timeSeriesBasketID);
return null;
}
FolderItem bItem = (FolderItem) item;
if (bItem.getFolderItemType() != FolderItemType.TIME_SERIES) {
logger.debug("The basket item does not belong to a timeseries, id:" + timeSeriesBasketID);
return null;
}
TimeSeries ts = (TimeSeries) bItem;
return getTSFromBasket(ts);
}
catch (NullPointerException e) {
logger.error("No TS was dragged in the Area returning NULL");
return null;
}
}
/**
*
* @param toParse the csv to parse
* @throws ProcessingException .
* @throws IOException .
* @throws ParseException .
*/
private SerializableTable parseCSV(File toParse, final SerializableTimeSeries sTS) throws ParseException , IOException, ProcessingException {
final SerializableTable toReturn;
final boolean isFiltered;
final int fromLine;
final int toLine;
//if there is no filter
if ( sTS.getFilter() == null) {
toReturn = new SerializableTable(sTS.getTsMetadata().getHeaderLabels().size());
isFiltered = false;
fromLine = 1;
toLine = 10;
}
else {
int headers = sTS.getFilter().getColsNumberToShow().size();
toReturn = new SerializableTable(headers);
isFiltered = true;
fromLine = sTS.getFilter().getFrom();
toLine = fromLine + 10;
}
final CSVFileProcessor fp = new CSVFileProcessor();
fp.processFile(toParse.getAbsolutePath() , new CSVLineProcessor() {
boolean keepGoing = true;
public void processHeaderLine( final int linenumber, final List<String> fieldNames ) {
ArrayList<TableCell> toInsert = new ArrayList<TableCell>();
for (String field : fieldNames) {
toInsert.add(new TableCell(field));
}
if (! isFiltered)
toReturn.addRow((ArrayList<TableCell>) toInsert);
else {
ArrayList<String> filteredHeaders = new ArrayList<String>();
for (Integer colNo : sTS.getFilter().getColsNumberToShow()) {
String toAdd = sTS.getTsMetadata().getHeaderLabels().get(colNo);
filteredHeaders.add(toAdd);
toInsert = new ArrayList<TableCell>();
for (String field : filteredHeaders) {
toInsert.add(new TableCell(field));
}
}
toReturn.addRow(toInsert);
}
}
public void processDataLine( final int linenumber, final List<String> fieldValues ) {
if (linenumber > toLine)
keepGoing = false;
if (linenumber >= fromLine && linenumber <= toLine) {
ArrayList<TableCell> toInsert = new ArrayList<TableCell>();
for (String field : fieldValues) {
toInsert.add(new TableCell(field));
}
if (! isFiltered)
toReturn.addRow(toInsert);
else {
ArrayList<String> filteredFields = new ArrayList<String>();
for (Integer colNo : sTS.getFilter().getColsNumberToShow()) {
String toAdd = fieldValues.get(colNo);
filteredFields.add(toAdd);
toInsert = new ArrayList<TableCell>();
for (String field : filteredFields) {
toInsert.add(new TableCell(field));
}
}
toReturn.addRow(toInsert);
}
}
}
public boolean continueProcessing() {
return keepGoing;
}
} );
return toReturn;
}
/**
* get the TS from the Basket
* @param ts
* @return a csv file
*/
private File getTSFromBasket(TimeSeries ts) {
try {
File temp = File.createTempFile(ts.getName(), ".csv");
InputStream inputStream = null;
try {
inputStream = ts.getData();
} catch (InternalErrorException e) {
e.printStackTrace();
return null;
}
OutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[1024];
int len;
while((len = inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
logger.debug("Successfully got TimeSeries from Basket: \n" + temp.getAbsolutePath());
return temp;
}
catch (IOException e){
e.printStackTrace();
return null;
} catch (InternalErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* each portlet instance runs in a scope
* each portlet instance is used by a unique username from within the portal
* @param currentHost .
* @return a SessionInfo bean containing the username the scope andis opening a workflow document or not
*/
public SessionInfo getSessionInfo(String currentHost) {
this.currentHost = 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(getUsername(), getVreName(), true, true);
}
if (getASLSession().getAttribute(WfDocsLibrary.WORKFLOW_ID_ATTRIBUTE) == null) {
logger.debug("WfDocsLibrary.WORKFLOW_ID_ATTRIBUTE is NULL: ");
return new SessionInfo(getUsername(), getVreName(), false, false);
}
else {
logger.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(getUsername(), getVreName(), true, canEdit);
}
}
public SerializableModel getWorkflowDocumentFromDocumentLibrary() {
ServiceUtil myUtil = new ServiceUtil(getASLSession());
if (testWorkflow) {
FileInputStream fis = null;
ObjectInputStream in = null;
SerializableModel toConvert = null;
try {
fis = new FileInputStream("/Users/massi/portal/CURRENT_OPEN.d4st");
in = new ObjectInputStream(fis);
toConvert = (SerializableModel) in.readObject();
in.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
toConvert.setTemplateName("TEST");
logger.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();
logger.info("getWorkflowDocumentFromDocumentLibrary() CALLED ***** ID = " + workflowid + " name:\n " + documentName);
//TODO: check this
//reset the values in session
logger.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);
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;
SerializableModel toConvert = null;
try {
String path = myUtil.getTemplateFolder(getVreName(), getUsername());
fis = new FileInputStream(path + "CURRENT_OPEN/CURRENT_OPEN.d4st");
in = new ObjectInputStream(fis);
toConvert = (SerializableModel) in.readObject();
in.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
toConvert.setTemplateName(documentName);
logger.debug("Converting fileToRead to Serializable object, model name: \n" + toConvert.getTemplateName());
SerializableModel 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);
logger.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();
logger.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(boolean update) {
ASLSession session = getASLSession();
ServiceUtil myUtil = new ServiceUtil(session);
String workflowid = session.getAttribute(WfDocsLibrary.LAST_WORKFLOW_ID).toString();
SerializableModel model = null;
String documentWorkflowOwnerId = store.getWorkflowById(workflowid).getAuthor();
String documentWorkflowName = store.getWorkflowById(workflowid).getName();
if (update) {
logger.debug("SAVING in WorkflowDocument Library ");
model = (SerializableModel) session.getAttribute(CURRENT_REPORT_INSTANCE);
logger.debug("Trying to convert dynamic images ... ");
importDynamicImagesFromHL(model);
boolean result = myUtil.writeModel(model, "CURRENT_OPEN", getVreName(), getUsername());
if (!result) {
logger.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();
}
logger.debug("Trying to zip folder: " + templatePath);
String folderToZip = templatePath;
String outZip = templatePath+"-report.zip";
try {
ZipUtil.zipDir(outZip, folderToZip);
logger.debug("Folder zipped, result: "+ outZip);
InputStream isZip = new BufferedInputStream(new FileInputStream(outZip));
DocLibraryUtil.updateFileIntoDocLibrary(getASLSession(), workflowid, getBytesFromInputStream(isZip));
logger.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) {
logger.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);
}
/**
*/
byte[] getBytesFromInputStream(InputStream is) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
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);
logger.info("Log action saved, trying ot unlock document ...");
LockLocalServiceUtil.unlock(DLFileEntry.class.getName(), fileEntry.getFileEntryId());
logger.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);
logger.info("Renewing Lock ...");
long fifteenMin = 900000;
Date currTimePlus15 = new Date(new Date().getTime() + fifteenMin);
LockLocalServiceUtil.getLock(DLFileEntry.class.getName(), fileEntry.getFileEntryId()).setExpirationDate(currTimePlus15);
logger.info("Lock Renewed, expiring: " + currTimePlus15);
} catch (Exception e) {
e.printStackTrace();
}
}
}