true if the new password is correct, exception otherwise
*/
- public boolean isValid(final SbiUser tmpUser, String oldPwd, String newPwd, String newPwd2) throws Exception {
+ public boolean isValid(final SbiUser tmpUser, String oldPwd, boolean isEncrypted, String newPwd, String newPwd2) throws Exception {
IConfigDAO configDao = DAOFactory.getSbiConfigDAO();
List configChecks = configDao.loadConfigParametersByProperties(PROP_NODE);
logger.debug("checks found on db: " + configChecks.size());
if (isValid(newPwd, newPwd2)) {
- if(oldPwd != null && StringUtilities.isEmpty(oldPwd)) {
+ if (oldPwd != null && StringUtilities.isEmpty(oldPwd)) {
logger.debug("The old password is empty.");
throw new EMFUserError(EMFErrorSeverity.ERROR, 14011);
}
-
- if (tmpUser == null || tmpUser != null
- && !Password.encriptPassword(oldPwd).equals(tmpUser.getPassword())) {
+
+ String oldPwdEnc = !isEncrypted ? Password.encriptPassword(oldPwd, tmpUser.getPassword().startsWith(Password.PREFIX_SHA_PWD_ENCRIPTING)) : oldPwd;
+ if (tmpUser == null || tmpUser != null && !oldPwdEnc.equals(tmpUser.getPassword())) {
logger.debug("The old pwd is uncorrect.");
throw new EMFUserError(EMFErrorSeverity.ERROR, 14010);
}
-
+
for (Object lstConfigCheck : configChecks) {
Config check = (Config) lstConfigCheck;
-
+
if (check.getLabel().equals(SpagoBIConstants.CHANGEPWDMOD_CHANGE)) {
if (oldPwd != null && oldPwd.equalsIgnoreCase(newPwd)) {
logger.debug("The password's doesn't be equal the lastest.");
@@ -191,7 +193,11 @@ public boolean isValid(final SbiUser tmpUser, String oldPwd, String newPwd, Stri
}
}
}
-
+
return true;
}
+
+ public boolean isValid(final SbiUser tmpUser, String oldPwd, String newPwd, String newPwd2) throws Exception {
+ return isValid(tmpUser, oldPwd, false, newPwd, newPwd2);
+ }
}
diff --git a/knowage-core/src/main/java/it/eng/spagobi/engines/drivers/svgviewer/SvgViewerDriver.java b/knowage-core/src/main/java/it/eng/spagobi/engines/drivers/svgviewer/SvgViewerDriver.java
index 2d8d0d274a3..38d3b3ddeed 100644
--- a/knowage-core/src/main/java/it/eng/spagobi/engines/drivers/svgviewer/SvgViewerDriver.java
+++ b/knowage-core/src/main/java/it/eng/spagobi/engines/drivers/svgviewer/SvgViewerDriver.java
@@ -17,19 +17,26 @@
*/
package it.eng.spagobi.engines.drivers.svgviewer;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.json.JSONException;
+
+import it.eng.spago.base.SourceBean;
+import it.eng.spago.base.SourceBeanException;
import it.eng.spagobi.engines.drivers.DefaultOutputParameter;
import it.eng.spagobi.engines.drivers.DefaultOutputParameter.TYPE;
import it.eng.spagobi.engines.drivers.generic.GenericDriver;
-import java.util.ArrayList;
-import java.util.List;
-
/**
* @author Marco Cortella (marco.cortella@eng.it)
*
*/
public class SvgViewerDriver extends GenericDriver {
+ static private Logger logger = Logger.getLogger(SvgViewerDriver.class);
+
@Override
public ListloadObjMetadataByID.
- *
- * @param key The choosed metadata id key
+ *
+ * @param key The choosed metadata id key
* @param response The response Source Bean
* @throws EMFUserError If an exception occurs
- */
- private void getObjMetadata(SourceBean request, SourceBean response) throws EMFUserError {
- try {
- ObjMetadata meta = DAOFactory.getObjMetadataDAO().loadObjMetaDataByID(new Integer((String)request.getAttribute("ID")));
+ */
+ private void getObjMetadata(SourceBean request, SourceBean response) throws EMFUserError {
+ try {
+ ObjMetadata meta = DAOFactory.getObjMetadataDAO().loadObjMetaDataByID(new Integer((String) request.getAttribute("ID")));
this.modalita = SpagoBIConstants.DETAIL_MOD;
- if (request.getAttribute("SUBMESSAGEDET") != null &&
- ((String)request.getAttribute("SUBMESSAGEDET")).equalsIgnoreCase(MOD_SAVEBACK))
- {
+ if (request.getAttribute("SUBMESSAGEDET") != null && ((String) request.getAttribute("SUBMESSAGEDET")).equalsIgnoreCase(MOD_SAVEBACK)) {
response.setAttribute("loopback", "true");
return;
}
@@ -129,41 +128,40 @@ private void getObjMetadata(SourceBean request, SourceBean response) throws EMFU
response.setAttribute("modality", modalita);
response.setAttribute("metaObj", meta);
} catch (Exception ex) {
- logger.error("Cannot fill response container" + ex.getLocalizedMessage());
+ logger.error("Cannot fill response container" + ex.getLocalizedMessage());
HashMap params = new HashMap();
params.put(AdmintoolsConstants.PAGE, ListObjMetadataModule.MODULE_PAGE);
throw new EMFUserError(EMFErrorSeverity.ERROR, 13003, new Vector(), params);
}
-
+
}
- /**
- * Inserts/Modifies the detail of a object metadta according to the user request.
- * When a metadata is modified, the modifyObjMetadata method is called; when a new
- * metadata is added, the insertObjMetadatamethod is called. These two cases are
- * differentiated by the mod String input value .
- *
- * @param request The request information contained in a SourceBean Object
- * @param mod A request string used to differentiate insert/modify operations
- * @param response The response SourceBean
- * @throws EMFUserError If an exception occurs
+
+ /**
+ * Inserts/Modifies the detail of a object metadta according to the user request. When a metadata is modified, the modifyObjMetadata method is
+ * called; when a new metadata is added, the insertObjMetadatamethod is called. These two cases are differentiated by the mod
+ * String input value .
+ *
+ * @param request The request information contained in a SourceBean Object
+ * @param mod A request string used to differentiate insert/modify operations
+ * @param response The response SourceBean
+ * @throws EMFUserError If an exception occurs
* @throws SourceBeanException If a SourceBean exception occurs
*/
- private void modifyObjMetadata(SourceBean serviceRequest, String mod, SourceBean serviceResponse)
- throws EMFUserError, SourceBeanException {
-
+ private void modifyObjMetadata(SourceBean serviceRequest, String mod, SourceBean serviceResponse) throws EMFUserError, SourceBeanException {
+
try {
RequestContainer reqCont = getRequestContainer();
SessionContainer sessCont = reqCont.getSessionContainer();
SessionContainer permSess = sessCont.getPermanentContainer();
- IEngUserProfile profile = (IEngUserProfile)permSess.getAttribute(IEngUserProfile.ENG_USER_PROFILE);
-
- IObjMetadataDAO dao=DAOFactory.getObjMetadataDAO();
+ IEngUserProfile profile = (IEngUserProfile) permSess.getAttribute(IEngUserProfile.ENG_USER_PROFILE);
+
+ IObjMetadataDAO dao = DAOFactory.getObjMetadataDAO();
dao.setUserProfile(profile);
-
+
ObjMetadata metaNew = recoverObjMetadataDetails(serviceRequest);
-
+
EMFErrorHandler errorHandler = getErrorHandler();
-
+
// if there are some validation errors into the errorHandler does not write into DB
Collection errors = errorHandler.getErrors();
if (errors != null && errors.size() > 0) {
@@ -177,113 +175,103 @@ private void modifyObjMetadata(SourceBean serviceRequest, String mod, SourceBean
}
}
}
-
- if (mod.equalsIgnoreCase(SpagoBIConstants.DETAIL_INS)) {
- //if a ds with the same label not exists on db ok else error
- if (dao.loadObjMetadataByLabel(metaNew.getLabel()) != null){
+
+ if (mod.equalsIgnoreCase(SpagoBIConstants.DETAIL_INS)) {
+ // if a ds with the same label not exists on db ok else error
+ List metadataWithSameLabel = dao.loadAllObjMetadataByLabelAndCase(metaNew.getLabel(), false);
+ if (metadataWithSameLabel != null && metadataWithSameLabel.size() > 0) {
HashMap params = new HashMap();
params.put(AdmintoolsConstants.PAGE, ListObjMetadataModule.MODULE_PAGE);
- EMFUserError error = new EMFUserError(EMFErrorSeverity.ERROR, 13004, new Vector(), params );
+ EMFUserError error = new EMFUserError(EMFErrorSeverity.ERROR, 13004, new Vector(), params);
getErrorHandler().addError(error);
return;
- }
+ }
dao.insertObjMetadata(metaNew);
-
+
ObjMetadata tmpMeta = dao.loadObjMetadataByLabel(metaNew.getLabel());
metaNew.setObjMetaId(tmpMeta.getObjMetaId());
- mod = SpagoBIConstants.DETAIL_MOD;
- } else {
- //update metadata
- dao.modifyObjMetadata(metaNew);
- }
+ mod = SpagoBIConstants.DETAIL_MOD;
+ } else {
+ // update metadata
+ dao.modifyObjMetadata(metaNew);
+ }
IDomainDAO domaindao = DAOFactory.getDomainDAO();
List dataTypes = domaindao.loadListDomainsByType("OBJMETA_DATA_TYPE");
serviceResponse.setAttribute(OBJMETA_DATA_TYPE, dataTypes);
-
- if (serviceRequest.getAttribute("SUBMESSAGEDET") != null &&
- ((String)serviceRequest.getAttribute("SUBMESSAGEDET")).equalsIgnoreCase(MOD_SAVE)) {
+
+ if (serviceRequest.getAttribute("SUBMESSAGEDET") != null && ((String) serviceRequest.getAttribute("SUBMESSAGEDET")).equalsIgnoreCase(MOD_SAVE)) {
serviceResponse.setAttribute("modality", mod);
- serviceResponse.setAttribute("metaObj", metaNew);
+ serviceResponse.setAttribute("metaObj", metaNew);
+ return;
+ } else if (serviceRequest.getAttribute("SUBMESSAGEDET") != null
+ && ((String) serviceRequest.getAttribute("SUBMESSAGEDET")).equalsIgnoreCase(MOD_SAVEBACK)) {
+ serviceResponse.setAttribute("loopback", "true");
return;
}
- else if (serviceRequest.getAttribute("SUBMESSAGEDET") != null &&
- ((String)serviceRequest.getAttribute("SUBMESSAGEDET")).equalsIgnoreCase(MOD_SAVEBACK)){
- serviceResponse.setAttribute("loopback", "true");
- return;
- }
- } catch (EMFUserError e){
+ } catch (EMFUserError e) {
logger.error("Cannot fill response container" + e.getLocalizedMessage());
HashMap params = new HashMap();
params.put(AdmintoolsConstants.PAGE, ListObjMetadataModule.MODULE_PAGE);
throw new EMFUserError(EMFErrorSeverity.ERROR, 13005, new Vector(), params);
-
+
}
-
- catch (Exception ex) {
- logger.error("Cannot fill response container" , ex);
+
+ catch (Exception ex) {
+ logger.error("Cannot fill response container", ex);
throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
- }
+ }
}
/**
* Deletes an obj metadata choosed by user from the metadata list.
- *
- * @param request The request SourceBean
- * @param mod A request string used to differentiate delete operation
- * @param response The response SourceBean
- * @throws EMFUserError If an Exception occurs
+ *
+ * @param request The request SourceBean
+ * @param mod A request string used to differentiate delete operation
+ * @param response The response SourceBean
+ * @throws EMFUserError If an Exception occurs
* @throws SourceBeanException If a SourceBean Exception occurs
*/
- private void deleteObjMetadata(SourceBean request, String mod, SourceBean response)
- throws EMFUserError, SourceBeanException {
-
+ private void deleteObjMetadata(SourceBean request, String mod, SourceBean response) throws EMFUserError, SourceBeanException {
+
try {
String id = (String) request.getAttribute("ID");
// if the metadata is associated with any BIObjects or BISuobjets, creates an error
- /*boolean bObjects = DAOFactory.getObjMetadataDAO().hasBIObjAssociated(id);
- boolean bSubobjects = DAOFactory.getObjMetadataDAO().hasSubObjAssociated(id);
- if (bObjects || bSubobjects){
- HashMap params = new HashMap();
- params.put(AdmintoolsConstants.PAGE, ListObjMetadataModule.MODULE_PAGE);
- EMFUserError error = new EMFUserError(EMFErrorSeverity.ERROR, 13007, new Vector(), params );
- getErrorHandler().addError(error);
- return;
- }*/
-
- //delete the metadata
+ /*
+ * boolean bObjects = DAOFactory.getObjMetadataDAO().hasBIObjAssociated(id); boolean bSubobjects =
+ * DAOFactory.getObjMetadataDAO().hasSubObjAssociated(id); if (bObjects || bSubobjects){ HashMap params = new HashMap();
+ * params.put(AdmintoolsConstants.PAGE, ListObjMetadataModule.MODULE_PAGE); EMFUserError error = new EMFUserError(EMFErrorSeverity.ERROR, 13007, new
+ * Vector(), params ); getErrorHandler().addError(error); return; }
+ */
+
+ // delete the metadata
ObjMetadata meta = DAOFactory.getObjMetadataDAO().loadObjMetaDataByID(new Integer(id));
DAOFactory.getObjMetadataDAO().eraseObjMetadata(meta);
- }
- catch (EMFUserError e){
- logger.error("Cannot fill response container" + e.getLocalizedMessage());
- HashMap params = new HashMap();
- params.put(AdmintoolsConstants.PAGE, ListObjMetadataModule.MODULE_PAGE);
- throw new EMFUserError(EMFErrorSeverity.ERROR, 13006, new Vector(), params);
-
- }
- catch (Exception ex) {
- ex.printStackTrace();
- logger.error("Cannot fill response container" ,ex);
+ } catch (EMFUserError e) {
+ logger.error("Cannot fill response container" + e.getLocalizedMessage());
+ HashMap params = new HashMap();
+ params.put(AdmintoolsConstants.PAGE, ListObjMetadataModule.MODULE_PAGE);
+ throw new EMFUserError(EMFErrorSeverity.ERROR, 13006, new Vector(), params);
+
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ logger.error("Cannot fill response container", ex);
throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
- }
- response.setAttribute("loopback", "true");
+ }
+ response.setAttribute("loopback", "true");
}
-
-
/**
- * Instantiates a new objmetadata object when a new metadata insertion is required, in order
- * to prepare the page for the insertion.
- *
+ * Instantiates a new objmetadata object when a new metadata insertion is required, in order to prepare the page for the insertion.
+ *
* @param response The response SourceBean
* @throws EMFUserError If an Exception occurred
*/
private void newObjMetadata(SourceBean response) throws EMFUserError {
-
+
try {
-
+
ObjMetadata meta = null;
this.modalita = SpagoBIConstants.DETAIL_INS;
response.setAttribute("modality", modalita);
@@ -295,38 +283,36 @@ private void newObjMetadata(SourceBean response) throws EMFUserError {
meta.setName("");
meta.setCreationDate(null);
response.setAttribute("metaObj", meta);
-
+
IDomainDAO domaindao = DAOFactory.getDomainDAO();
List dataTypes = domaindao.loadListDomainsByType("OBJMETA_DATA_TYPE");
response.setAttribute(OBJMETA_DATA_TYPE, dataTypes);
-
+
} catch (Exception ex) {
- logger.error("Cannot prepare page for the insertion" , ex);
+ logger.error("Cannot prepare page for the insertion", ex);
throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
}
-
+
}
+ private ObjMetadata recoverObjMetadataDetails(SourceBean serviceRequest) throws EMFUserError, SourceBeanException, IOException {
+ ObjMetadata meta = new ObjMetadata();
- private ObjMetadata recoverObjMetadataDetails (SourceBean serviceRequest) throws EMFUserError, SourceBeanException, IOException {
- ObjMetadata meta = new ObjMetadata();
-
- String idStr = (String)serviceRequest.getAttribute("ID");
+ String idStr = (String) serviceRequest.getAttribute("ID");
Integer id = new Integer(idStr);
- String description = (String)serviceRequest.getAttribute("DESCR");
- String label = (String)serviceRequest.getAttribute("LABEL");
- String name = (String)serviceRequest.getAttribute("NAME");
- String dataType = (String)serviceRequest.getAttribute("DATA_TYPE");
- //String creationDate = (String)serviceRequest.getAttribute("USER");
-
+ String description = (String) serviceRequest.getAttribute("DESCR");
+ String label = (String) serviceRequest.getAttribute("LABEL");
+ String name = (String) serviceRequest.getAttribute("NAME");
+ String dataType = (String) serviceRequest.getAttribute("DATA_TYPE");
+ // String creationDate = (String)serviceRequest.getAttribute("USER");
+
meta.setObjMetaId(id.intValue());
meta.setDescription(description);
meta.setLabel(label);
meta.setDataType(Integer.valueOf(dataType));
meta.setName(name);
- //meta.setCreationDate(creationDate);
-
-
+ // meta.setCreationDate(creationDate);
+
return meta;
}
diff --git a/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/dispatcher/DistributionListDocumentDispatchChannel.java b/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/dispatcher/DistributionListDocumentDispatchChannel.java
index aef808834e6..a4a9cf45d90 100644
--- a/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/dispatcher/DistributionListDocumentDispatchChannel.java
+++ b/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/dispatcher/DistributionListDocumentDispatchChannel.java
@@ -1,7 +1,7 @@
/*
* Knowage, Open Source Business Intelligence suite
* Copyright (C) 2016 Engineering Ingegneria Informatica S.p.A.
- *
+ *
* Knowage is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
@@ -11,7 +11,7 @@
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see .
*/
@@ -21,59 +21,34 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.security.Security;
-import java.sql.Timestamp;
import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
-import java.util.Map;
-import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
-import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
-import javax.mail.PasswordAuthentication;
-import javax.mail.Session;
-import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
-import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
-import it.eng.spago.error.EMFUserError;
+import org.apache.log4j.Logger;
+import org.quartz.JobExecutionContext;
+
+import it.eng.knowage.mail.MailSessionBuilder;
+import it.eng.knowage.mail.MailSessionBuilder.SessionFacade;
import it.eng.spago.security.IEngUserProfile;
import it.eng.spagobi.analiticalmodel.document.bo.BIObject;
-import it.eng.spagobi.analiticalmodel.document.bo.ObjTemplate;
-import it.eng.spagobi.analiticalmodel.document.dao.IBIObjectDAO;
-import it.eng.spagobi.analiticalmodel.functionalitytree.bo.LowFunctionality;
-import it.eng.spagobi.behaviouralmodel.analyticaldriver.bo.BIObjectParameter;
-import it.eng.spagobi.commons.SingletonConfig;
-import it.eng.spagobi.commons.bo.Domain;
import it.eng.spagobi.commons.dao.DAOFactory;
-import it.eng.spagobi.commons.dao.IDomainDAO;
import it.eng.spagobi.commons.utilities.GeneralUtilities;
import it.eng.spagobi.commons.utilities.ObjectsAccessVerifier;
-import it.eng.spagobi.commons.utilities.StringUtilities;
import it.eng.spagobi.commons.utilities.messages.IMessageBuilder;
import it.eng.spagobi.commons.utilities.messages.MessageBuilderFactory;
-import it.eng.spagobi.engines.config.bo.Engine;
-import it.eng.spagobi.engines.config.dao.IEngineDAO;
-import it.eng.spagobi.tools.dataset.common.datastore.IDataStore;
-import it.eng.spagobi.tools.dataset.common.datastore.IField;
-import it.eng.spagobi.tools.dataset.common.datastore.IRecord;
import it.eng.spagobi.tools.distributionlist.bo.DistributionList;
import it.eng.spagobi.tools.distributionlist.bo.Email;
-import it.eng.spagobi.tools.massiveExport.services.StartMassiveScheduleAction;
import it.eng.spagobi.tools.scheduler.to.DispatchContext;
-import org.apache.commons.validator.GenericValidator;
-import org.apache.log4j.Logger;
-import org.quartz.JobExecutionContext;
-
/**
* @author Andrea Gioia (andrea.gioia@eng.it)
*
@@ -81,79 +56,50 @@
public class DistributionListDocumentDispatchChannel implements IDocumentDispatchChannel {
private DispatchContext dispatchContext;
-
+
// logger component
- private static Logger logger = Logger.getLogger(DistributionListDocumentDispatchChannel.class);
- final String DEFAULT_SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
- final String CUSTOM_SSL_FACTORY = "it.eng.spagobi.commons.services.DummySSLSocketFactory";
-
+ private static Logger logger = Logger.getLogger(DistributionListDocumentDispatchChannel.class);
+
public DistributionListDocumentDispatchChannel(DispatchContext dispatchContext) {
this.dispatchContext = dispatchContext;
}
-
+
+ @Override
public void setDispatchContext(DispatchContext dispatchContext) {
this.dispatchContext = dispatchContext;
}
+ @Override
public void close() {
-
+
}
-
+
+ @Override
public boolean canDispatch(BIObject document) {
return true;
}
-
+
+ @Override
public boolean dispatch(BIObject document, byte[] executionOutput) {
-
+
String contentType;
String fileExtension;
String nameSuffix;
JobExecutionContext jobExecutionContext;
-
+
logger.debug("IN");
-
+
try{
-
+
contentType = dispatchContext.getContentType();
fileExtension = dispatchContext.getFileExtension();
nameSuffix = dispatchContext.getNameSuffix();
jobExecutionContext = dispatchContext.getJobExecutionContext();
-
- //Custom Trusted Store Certificate Options
- String trustedStorePath = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.trustedStore.file");
- String trustedStorePassword = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.trustedStore.password");
-
- String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
- String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
- String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
- logger.debug(smtphost+" "+smtpport+" use SSL: "+smtpssl);
-
-
- if( (smtphost==null) || smtphost.trim().equals(""))
- throw new Exception("Smtp host not configured");
- String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
- if( (from==null) || from.trim().equals(""))
- from = "spagobi.scheduler@eng.it";
-
- int smptPort=25;
-
- if( (smtpport==null) || smtpport.trim().equals("")){
- throw new Exception("Smtp host not configured");
- }else{
- smptPort=Integer.parseInt(smtpport);
- }
-
- String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
- String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
-
- /*
- if( (user==null) || user.trim().equals(""))
- throw new Exception("Smtp user not configured");
-
- if( (pass==null) || pass.trim().equals(""))
- throw new Exception("Smtp password not configured");
- */
-
+
+ SessionFacade facade = MailSessionBuilder.newInstance()
+ .usingSchedulerProfile()
+ .build();
+
String mailTos = "";
List dlIds = dispatchContext.getDlIds();
Iterator it = dlIds.iterator();
@@ -169,8 +115,8 @@ public boolean dispatch(BIObject document, byte[] executionOutput) {
Email e = (Email) j.next();
String email = e.getEmail();
String userTemp = e.getUserId();
- IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp);
- if(ObjectsAccessVerifier.canSee(document, userProfile)) {
+ IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp);
+ if(ObjectsAccessVerifier.canSee(document, userProfile)) {
if (j.hasNext()) {mailTos = mailTos+email+",";}
else {mailTos = mailTos+email;}
}
@@ -179,55 +125,15 @@ public boolean dispatch(BIObject document, byte[] executionOutput) {
}
- if( (mailTos==null) || mailTos.trim().equals("")) {
+ if( (mailTos==null) || mailTos.trim().equals("")) {
throw new Exception("No recipient address found");
}
String[] recipients = mailTos.split(",");
- //Set the host smtp address
- Properties props = new Properties();
- props.put("mail.smtp.host", smtphost);
- props.put("mail.smtp.port", Integer.toString(smptPort));
-
- Session session = null;
-
- if(StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) {
- props.put("mail.smtp.auth", "false");
- session = Session.getInstance(props);
- logger.debug("Connecting to mail server without authentication");
- } else {
- props.put("mail.smtp.auth", "true");
- Authenticator auth = new SMTPAuthenticator(user, pass);
- //SSL Connection
- if (smtpssl.equals("true")){
- Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
- //props.put("mail.smtp.debug", "true");
- props.put("mail.smtps.auth", "true");
- props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort));
- if ((!StringUtilities.isEmpty(trustedStorePath)) ) {
- /* Dynamic configuration of trustedstore for CA
- * Using Custom SSLSocketFactory to inject certificates directly from specified files
- */
- //System.setProperty("java.security.debug","certpath");
- //System.setProperty("javax.net.debug","ssl ");
- props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);
-
- } else {
- //System.setProperty("java.security.debug","certpath");
- //System.setProperty("javax.net.debug","ssl ");
- props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
- }
- props.put("mail.smtp.socketFactory.fallback", "false");
- }
- session = Session.getInstance(props, auth);
- logger.debug("Connecting to mail server with authentication");
- }
-
+
// create a message
- Message msg = new MimeMessage(session);
- // set the from and to address
- InternetAddress addressFrom = new InternetAddress(from);
- msg.setFrom(addressFrom);
+ Message msg = facade.createNewMimeMessage();
+
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
@@ -252,19 +158,10 @@ public boolean dispatch(BIObject document, byte[] executionOutput) {
mp.addBodyPart(mbp2);
// add the Multipart to the message
msg.setContent(mp);
+
// send message
- if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))){
- //USE SSL Transport comunication with SMTPS
- Transport transport = session.getTransport("smtps");
- transport.connect(smtphost,smptPort,user,pass);
- transport.sendMessage(msg, msg.getAllRecipients());
- transport.close();
- }
- else {
- //Use normal SMTP
- Transport.send(msg);
- }
-
+ facade.sendMessage(msg);
+
if(jobExecutionContext.getNextFireTime()== null){
String triggername = jobExecutionContext.getTrigger().getName();
dlIds = dispatchContext.getDlIds();
@@ -281,48 +178,33 @@ public boolean dispatch(BIObject document, byte[] executionOutput) {
}finally{
logger.debug("OUT");
}
-
- return true;
- }
-
-
-
- private class SMTPAuthenticator extends javax.mail.Authenticator
- {
- private String username = "";
- private String password = "";
-
- public PasswordAuthentication getPasswordAuthentication()
- {
- return new PasswordAuthentication(username, password);
- }
- public SMTPAuthenticator(String user, String pass) {
- this.username = user;
- this.password = pass;
- }
+ return true;
}
-
private class SchedulerDataSource implements DataSource {
byte[] content = null;
String name = null;
String contentType = null;
+ @Override
public String getContentType() {
return contentType;
}
+ @Override
public InputStream getInputStream() throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(content);
return bais;
}
+ @Override
public String getName() {
return name;
}
+ @Override
public OutputStream getOutputStream() throws IOException {
return null;
}
diff --git a/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/dispatcher/MailDocumentDispatchChannel.java b/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/dispatcher/MailDocumentDispatchChannel.java
index 6a230e97cae..fd6a25a2928 100644
--- a/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/dispatcher/MailDocumentDispatchChannel.java
+++ b/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/dispatcher/MailDocumentDispatchChannel.java
@@ -1,7 +1,7 @@
/*
* Knowage, Open Source Business Intelligence suite
* Copyright (C) 2016 Engineering Ingegneria Informatica S.p.A.
- *
+ *
* Knowage is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
@@ -11,62 +11,57 @@
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see .
*/
package it.eng.spagobi.tools.scheduler.dispatcher;
-import it.eng.spago.security.IEngUserProfile;
-import it.eng.spagobi.analiticalmodel.document.bo.BIObject;
-import it.eng.spagobi.behaviouralmodel.analyticaldriver.bo.BIObjectParameter;
-import it.eng.spagobi.commons.SingletonConfig;
-import it.eng.spagobi.commons.dao.DAOFactory;
-import it.eng.spagobi.commons.utilities.StringUtilities;
-import it.eng.spagobi.tools.dataset.bo.IDataSet;
-import it.eng.spagobi.tools.dataset.common.behaviour.UserProfileUtils;
-import it.eng.spagobi.tools.dataset.common.datastore.IDataStore;
-import it.eng.spagobi.tools.dataset.common.datastore.IField;
-import it.eng.spagobi.tools.dataset.common.datastore.IRecord;
-import it.eng.spagobi.tools.scheduler.to.DispatchContext;
-import it.eng.spagobi.utilities.exceptions.SpagoBIRuntimeException;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.security.Security;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.activation.DataHandler;
import javax.activation.DataSource;
-import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
-import javax.mail.Session;
-import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
-import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import org.apache.commons.validator.GenericValidator;
import org.apache.log4j.Logger;
+import it.eng.knowage.mail.MailSessionBuilder;
+import it.eng.knowage.mail.MailSessionBuilder.SessionFacade;
+import it.eng.spago.security.IEngUserProfile;
+import it.eng.spagobi.analiticalmodel.document.bo.BIObject;
+import it.eng.spagobi.behaviouralmodel.analyticaldriver.bo.BIObjectParameter;
+import it.eng.spagobi.commons.dao.DAOFactory;
+import it.eng.spagobi.commons.utilities.StringUtilities;
+import it.eng.spagobi.tools.dataset.bo.IDataSet;
+import it.eng.spagobi.tools.dataset.common.behaviour.UserProfileUtils;
+import it.eng.spagobi.tools.dataset.common.datastore.IDataStore;
+import it.eng.spagobi.tools.dataset.common.datastore.IField;
+import it.eng.spagobi.tools.dataset.common.datastore.IRecord;
+import it.eng.spagobi.tools.scheduler.to.DispatchContext;
+import it.eng.spagobi.utilities.exceptions.SpagoBIRuntimeException;
+
/**
* @author Andrea Gioia (andrea.gioia@eng.it)
- *
+ *
*/
public class MailDocumentDispatchChannel implements IDocumentDispatchChannel {
@@ -74,8 +69,6 @@ public class MailDocumentDispatchChannel implements IDocumentDispatchChannel {
// logger component
private static Logger logger = Logger.getLogger(MailDocumentDispatchChannel.class);
- final String DEFAULT_SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
- final String CUSTOM_SSL_FACTORY = "it.eng.spagobi.commons.services.DummySSLSocketFactory";
public MailDocumentDispatchChannel(DispatchContext dispatchContext) {
this.dispatchContext = dispatchContext;
@@ -95,18 +88,22 @@ public MailDocumentDispatchChannel(DispatchContext dispatchContext) {
}
}
+ @Override
public void setDispatchContext(DispatchContext dispatchContext) {
this.dispatchContext = dispatchContext;
}
+ @Override
public void close() {
}
+ @Override
public boolean canDispatch(BIObject document) {
return canDispatch(dispatchContext, document, dispatchContext.getEmailDispatchDataStore());
}
+ @Override
public boolean dispatch(BIObject document, byte[] executionOutput) {
Map parametersMap;
String contentType;
@@ -132,39 +129,9 @@ public boolean dispatch(BIObject document, byte[] executionOutput) {
: document.getName();
reportNameInSubject = dispatchContext.isReportNameInSubject();
- String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
- String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
- String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
- logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);
-
- // Custom Trusted Store Certificate Options
- String trustedStorePath = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.trustedStore.file");
- String trustedStorePassword = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.trustedStore.password");
-
- int smptPort = 25;
-
- if ((smtphost == null) || smtphost.trim().equals(""))
- throw new Exception("Smtp host not configured");
- if ((smtpport == null) || smtpport.trim().equals("")) {
- throw new Exception("Smtp host not configured");
- } else {
- smptPort = Integer.parseInt(smtpport);
- }
-
- String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
- if ((from == null) || from.trim().equals(""))
- from = "spagobi.scheduler@eng.it";
- String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
- if ((user == null) || user.trim().equals("")) {
- logger.debug("Smtp user not configured");
- user = null;
- }
- // throw new Exception("Smtp user not configured");
- String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
- if ((pass == null) || pass.trim().equals("")) {
- logger.debug("Smtp password not configured");
- }
- // throw new Exception("Smtp password not configured");
+ SessionFacade facade = MailSessionBuilder.newInstance()
+ .usingSchedulerProfile()
+ .build();
String mailSubj = dispatchContext.getMailSubj();
mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false);
@@ -177,58 +144,8 @@ public boolean dispatch(BIObject document, byte[] executionOutput) {
return false;
}
- // Set the host smtp address
- Properties props = new Properties();
- props.put("mail.smtp.host", smtphost);
- props.put("mail.smtp.port", Integer.toString(smptPort));
-
- // open session
- Session session = null;
-
- // create autheticator object
- Authenticator auth = null;
- if (user != null) {
- auth = new SMTPAuthenticator(user, pass);
- props.put("mail.smtp.auth", "true");
- // SSL Connection
- if (smtpssl.equals("true")) {
- Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
- // props.put("mail.smtp.debug", "true");
- props.put("mail.smtps.auth", "true");
- props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort));
- if ((!StringUtilities.isEmpty(trustedStorePath))) {
- /*
- * Dynamic configuration of trustedstore for CA Using Custom SSLSocketFactory to inject certificates directly from specified files
- */
- // System.setProperty("java.security.debug","certpath");
- // System.setProperty("javax.net.debug","ssl ");
- props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);
-
- } else {
- // System.setProperty("java.security.debug","certpath");
- // System.setProperty("javax.net.debug","ssl ");
- props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
- }
- props.put("mail.smtp.socketFactory.fallback", "false");
- }
-
- // session = Session.getDefaultInstance(props, auth);
- session = Session.getInstance(props, auth);
- // session.setDebug(true);
- // session.setDebugOut(null);
- logger.info("Session.getInstance(props, auth)");
-
- } else {
- // session = Session.getDefaultInstance(props);
- session = Session.getInstance(props);
- logger.info("Session.getInstance(props)");
- }
-
// create a message
- Message msg = new MimeMessage(session);
- // set the from and to address
- InternetAddress addressFrom = new InternetAddress(from);
- msg.setFrom(addressFrom);
+ Message msg = facade.createNewMimeMessage();
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
@@ -269,16 +186,7 @@ public boolean dispatch(BIObject document, byte[] executionOutput) {
// add the Multipart to the message
msg.setContent(mp);
// send message
- if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
- // USE SSL Transport comunication with SMTPS
- Transport transport = session.getTransport("smtps");
- transport.connect(smtphost, smptPort, user, pass);
- transport.sendMessage(msg, msg.getAllRecipients());
- transport.close();
- } else {
- // Use normal SMTP
- Transport.send(msg);
- }
+ facade.sendMessage(msg);
logger.info("Mail sent for document with label " + document.getLabel());
} catch (Exception e) {
@@ -529,40 +437,29 @@ private static List findRecipientsFromDataSet(DispatchContext info, BIOb
return recipients;
}
- private class SMTPAuthenticator extends javax.mail.Authenticator {
- private String username = "";
- private String password = "";
-
- @Override
- public PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(username, password);
- }
-
- public SMTPAuthenticator(String user, String pass) {
- this.username = user;
- this.password = pass;
- }
- }
-
private class SchedulerDataSource implements DataSource {
byte[] content = null;
String name = null;
String contentType = null;
+ @Override
public String getContentType() {
return contentType;
}
+ @Override
public InputStream getInputStream() throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(content);
return bais;
}
+ @Override
public String getName() {
return name;
}
+ @Override
public OutputStream getOutputStream() throws IOException {
return null;
}
diff --git a/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/dispatcher/UniqueMailDocumentDispatchChannel.java b/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/dispatcher/UniqueMailDocumentDispatchChannel.java
index df5f135d799..7cc69ef4c90 100644
--- a/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/dispatcher/UniqueMailDocumentDispatchChannel.java
+++ b/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/dispatcher/UniqueMailDocumentDispatchChannel.java
@@ -1,7 +1,7 @@
/*
* Knowage, Open Source Business Intelligence suite
* Copyright (C) 2016 Engineering Ingegneria Informatica S.p.A.
- *
+ *
* Knowage is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
@@ -11,26 +11,12 @@
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see .
*/
package it.eng.spagobi.tools.scheduler.dispatcher;
-import it.eng.spago.security.IEngUserProfile;
-import it.eng.spagobi.analiticalmodel.document.bo.BIObject;
-import it.eng.spagobi.behaviouralmodel.analyticaldriver.bo.BIObjectParameter;
-import it.eng.spagobi.commons.SingletonConfig;
-import it.eng.spagobi.commons.dao.DAOFactory;
-import it.eng.spagobi.commons.utilities.StringUtilities;
-import it.eng.spagobi.tools.dataset.bo.IDataSet;
-import it.eng.spagobi.tools.dataset.common.behaviour.UserProfileUtils;
-import it.eng.spagobi.tools.dataset.common.datastore.IDataStore;
-import it.eng.spagobi.tools.dataset.common.datastore.IField;
-import it.eng.spagobi.tools.dataset.common.datastore.IRecord;
-import it.eng.spagobi.tools.scheduler.to.DispatchContext;
-import it.eng.spagobi.utilities.exceptions.SpagoBIRuntimeException;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -39,34 +25,43 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.security.Security;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.activation.DataHandler;
import javax.activation.DataSource;
-import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
-import javax.mail.Session;
-import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
-import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import org.apache.commons.validator.GenericValidator;
import org.apache.log4j.Logger;
+import it.eng.knowage.mail.MailSessionBuilder;
+import it.eng.knowage.mail.MailSessionBuilder.SessionFacade;
+import it.eng.spago.security.IEngUserProfile;
+import it.eng.spagobi.analiticalmodel.document.bo.BIObject;
+import it.eng.spagobi.behaviouralmodel.analyticaldriver.bo.BIObjectParameter;
+import it.eng.spagobi.commons.dao.DAOFactory;
+import it.eng.spagobi.commons.utilities.StringUtilities;
+import it.eng.spagobi.tools.dataset.bo.IDataSet;
+import it.eng.spagobi.tools.dataset.common.behaviour.UserProfileUtils;
+import it.eng.spagobi.tools.dataset.common.datastore.IDataStore;
+import it.eng.spagobi.tools.dataset.common.datastore.IField;
+import it.eng.spagobi.tools.dataset.common.datastore.IRecord;
+import it.eng.spagobi.tools.scheduler.to.DispatchContext;
+import it.eng.spagobi.utilities.exceptions.SpagoBIRuntimeException;
+
/**
* @author Giulio Gavardi
*
@@ -76,7 +71,7 @@ public class UniqueMailDocumentDispatchChannel implements IDocumentDispatchChann
private DispatchContext dispatchContext;
// logger component
- private static Logger logger = Logger.getLogger(UniqueMailDocumentDispatchChannel.class);
+ private static Logger logger = Logger.getLogger(UniqueMailDocumentDispatchChannel.class);
// COnfigurations stored in mailOptions Map
@@ -95,8 +90,8 @@ public class UniqueMailDocumentDispatchChannel implements IDocumentDispatchChann
public static final String DOCUMENT_STATE_CODE = "DOCUMENT_STATE_CODE";
public static final String PARAMETERS_MAP = "PARAMETERS_MAP";
public static final String REPORT_NAME_IN_SUBJECT = "REPORT_NAME_IN_SUBJECT";
- public static final String DOCUMENT_LABELS = "DOCUMENT_LABELS";
- public static final String IS_ZIP_DOCUMENT = "IS_ZIP_DOCUMENT";
+ public static final String DOCUMENT_LABELS = "DOCUMENT_LABELS";
+ public static final String IS_ZIP_DOCUMENT = "IS_ZIP_DOCUMENT";
@@ -122,31 +117,35 @@ public UniqueMailDocumentDispatchChannel(DispatchContext dispatchContext) {
}
}
+ @Override
public void setDispatchContext(DispatchContext dispatchContext) {
this.dispatchContext = dispatchContext;
}
+ @Override
public void close() {
}
+ @Override
public boolean canDispatch(BIObject document) {
return canDispatch(dispatchContext, document, dispatchContext.getEmailDispatchDataStore() );
}
-
+
/**
* dispatch in this case does not send mail, but store files in temporar folder
*/
-
+
+ @Override
public boolean dispatch(BIObject document, byte[] executionOutput) {
- String fileExtension;
+ String fileExtension;
String nameSuffix;
String containedFileName;
logger.debug("IN");
try{
- fileExtension = dispatchContext.getFileExtension();
+ fileExtension = dispatchContext.getFileExtension();
nameSuffix = dispatchContext.getNameSuffix();
containedFileName = dispatchContext.getContainedFileName() != null && !dispatchContext.getContainedFileName().equals("")?
dispatchContext.getContainedFileName() : document.getName();
@@ -158,7 +157,7 @@ public boolean dispatch(BIObject document, byte[] executionOutput) {
File folder = new File(tempFolderPath);
if(!folder.exists()){
- logger.debug("Temporary Folder not retrieved: "+folder.getAbsolutePath());
+ logger.debug("Temporary Folder not retrieved: "+folder.getAbsolutePath());
throw new Exception("Temporary Folder not retrieved: "+folder.getAbsolutePath());
}
@@ -170,7 +169,7 @@ public boolean dispatch(BIObject document, byte[] executionOutput) {
logger.debug("File to store in temporary folder: "+fileToCreate);
String pathToCreate = folder.getAbsolutePath()+File.separator+fileToCreate;
- FileOutputStream fileOuputStream = new FileOutputStream(pathToCreate);
+ FileOutputStream fileOuputStream = new FileOutputStream(pathToCreate);
fileOuputStream.write(executionOutput);
fileOuputStream.close();
@@ -188,7 +187,7 @@ public boolean dispatch(BIObject document, byte[] executionOutput) {
/** AFter all files are stored in temporary tabe takes them and sens as zip or as separate attachments
- *
+ *
* @param mailOptions
* @return
*/
@@ -197,9 +196,6 @@ public boolean sendFiles(Map mailOptions, String allDocumentLabe
logger.debug("IN");
try{
- final String DEFAULT_SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
- final String CUSTOM_SSL_FACTORY = "it.eng.spagobi.commons.services.DummySSLSocketFactory";
-
String tempFolderPath = (String)mailOptions.get(TEMP_FOLDER_PATH);
File tempFolder = new File(tempFolderPath);
@@ -209,52 +205,9 @@ public boolean sendFiles(Map mailOptions, String allDocumentLabe
return false;
}
- String smtphost = null;
- String pass = null;
- String smtpssl = null;
- String trustedStorePath = null;
- String user = null;
- String from = null;
- int smtpPort = 25;
-
- try{
-
- smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
- String smtpportS = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
- smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
- logger.debug(smtphost+" "+smtpportS+" use SSL: "+smtpssl);
- //Custom Trusted Store Certificate Options
- trustedStorePath = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.trustedStore.file");
-
-
- if( (smtphost==null) || smtphost.trim().equals(""))
- throw new Exception("Smtp host not configured");
- if( (smtpportS==null) || smtpportS.trim().equals("")){
- throw new Exception("Smtp host not configured");
- }else{
- smtpPort=Integer.parseInt(smtpportS);
- }
-
- from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
- if( (from==null) || from.trim().equals(""))
- from = "spagobi.scheduler@eng.it";
- user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
- if( (user==null) || user.trim().equals("")){
- logger.debug("Smtp user not configured");
- user=null;
- }
- // throw new Exception("Smtp user not configured");
- pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
- if( (pass==null) || pass.trim().equals("")){
- logger.debug("Smtp password not configured");
- }
- // throw new Exception("Smtp password not configured");
- }
- catch(Exception e){
- logger.error("Some E-mail configuration not set in table sbi_config: check you have all settings.", e);
- throw new Exception("Some E-mail configuration not set in table sbi_config: check you have all settings.");
- }
-
+ SessionFacade facade = MailSessionBuilder.newInstance()
+ .usingSchedulerProfile()
+ .build();
String mailSubj = mailOptions.get(MAIL_SUBJECT) != null ? (String)mailOptions.get(MAIL_SUBJECT) : null;
Map parametersMap = mailOptions.get(PARAMETERS_MAP) != null ? (Map)mailOptions.get(PARAMETERS_MAP) : null;
@@ -263,60 +216,9 @@ public boolean sendFiles(Map mailOptions, String allDocumentLabe
String mailTxt = mailOptions.get(MAIL_TXT) != null ? (String)mailOptions.get(MAIL_TXT) : null;
String[] recipients = mailOptions.get(RECIPIENTS) != null ? (String[])mailOptions.get(RECIPIENTS) : null;
-
- //Set the host smtp address
- Properties props = new Properties();
- props.put("mail.smtp.host", smtphost);
- props.put("mail.smtp.p ort", Integer.toString(smtpPort));
-
- // open session
- Session session=null;
-
- // create autheticator object
- Authenticator auth = null;
- if (user!=null) {
- auth = new SMTPAuthenticator(user, pass);
- props.put("mail.smtp.auth", "true");
- //SSL Connection
- if (smtpssl.equals("true")){
- Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
- //props.put("mail.smtp.debug", "true");
- props.put("mail.smtps.auth", "true");
- props.put("mail.smtps.socketFactory.port", Integer.toString(smtpPort));
- if ((!StringUtilities.isEmpty(trustedStorePath)) ) {
- /* Dynamic configuration of trustedstore for CA
- * Using Custom SSLSocketFactory to inject certificates directly from specified files
- */
- //System.setProperty("java.security.debug","certpath");
- //System.setProperty("javax.net.debug","ssl ");
- props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);
-
- } else {
- //System.setProperty("java.security.debug","certpath");
- //System.setProperty("javax.net.debug","ssl ");
- props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
- }
- props.put("mail.smtp.socketFactory.fallback", "false");
- }
-
- //session = Session.getDefaultInstance(props, auth);
- session = Session.getInstance(props, auth);
- //session.setDebug(true);
- //session.setDebugOut(null);
- logger.info("Session.getInstance(props, auth)");
-
- }else{
- //session = Session.getDefaultInstance(props);
- session = Session.getInstance(props);
- logger.info("Session.getInstance(props)");
- }
-
-
// create a message
- Message msg = new MimeMessage(session);
- // set the from and to address
- InternetAddress addressFrom = new InternetAddress(from);
- msg.setFrom(addressFrom);
+ Message msg = facade.createNewMimeMessage();
+
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
@@ -352,12 +254,12 @@ public boolean sendFiles(Map mailOptions, String allDocumentLabe
mp.addBodyPart(mbp1);
- if(isZipDocument){
+ if(isZipDocument){
logger.debug("Make zip");
// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
mbp2 = zipAttachment(zipFileName, mailOptions, tempFolder);
- mp.addBodyPart(mbp2);
+ mp.addBodyPart(mbp2);
}
else{
logger.debug("Attach single files");
@@ -372,7 +274,7 @@ public boolean sendFiles(Map mailOptions, String allDocumentLabe
logger.debug("Attach file "+entries[i]);
File f = new File(tempFolder+File.separator+entries[i]);
- byte[] content = getBytesFromFile(f);
+ byte[] content = getBytesFromFile(f);
bodyPart = new MimeBodyPart();
@@ -396,27 +298,16 @@ public boolean sendFiles(Map mailOptions, String allDocumentLabe
// add the Multipart to the message
msg.setContent(mp);
logger.debug("Preparing to send mail");
+
// send message
- if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))){
- logger.debug("Smtps mode active user "+user);
- //USE SSL Transport comunication with SMTPS
- Transport transport = session.getTransport("smtps");
- transport.connect(smtphost,smtpPort,user,pass);
- transport.sendMessage(msg, msg.getAllRecipients());
- transport.close();
- }
- else {
- logger.debug("Smtp mode");
- //Use normal SMTP
- Transport.send(msg);
- }
-
- logger.info("Mail sent for documents with labels ["+allDocumentLabels+"]");
-
+ facade.sendMessage(msg);
+
+ logger.info("Mail sent for documents with labels ["+allDocumentLabels+"]");
+
// logger.debug("delete tempFolder path "+tempFolder.getPath());
// boolean deleted = tempFolder.delete();
// logger.debug("Temp folder deleted "+deleted);
-
+
} catch (Exception e) {
logger.error("Error while sending schedule result mail",e);
return false;
@@ -431,7 +322,7 @@ public boolean sendFiles(Map mailOptions, String allDocumentLabe
public static MimeBodyPart zipAttachment( String zipFileName, Map mailOptions, File tempFolder)
- {
+ {
logger.debug("IN");
MimeBodyPart messageBodyPart = null;
try
@@ -466,7 +357,7 @@ public static MimeBodyPart zipAttachment( String zipFileName, Map mailOptions, F
out.putNextEntry(entry); // Store entry
while ((bytesRead = in.read(buffer)) != -1)
out.write(buffer, 0, bytesRead);
- in.close();
+ in.close();
}
out.close();
@@ -490,7 +381,7 @@ public static MimeBodyPart zipAttachment( String zipFileName, Map mailOptions, F
}
private byte[] zipDocument(String fileZipName, byte[] content) {
- logger.debug("IN");
+ logger.debug("IN");
ByteArrayOutputStream bos=null;
ZipOutputStream zos=null;
@@ -515,21 +406,21 @@ private byte[] zipDocument(String fileZipName, byte[] content) {
return null;
}finally{
if (bos != null) {
- try {
+ try {
bos.close();
} catch (IOException e) {
logger.error("Error closing output stream", e);
}
}
if (zos != null) {
- try {
+ try {
zos.close();
} catch (IOException e) {
logger.error("Error closing output stream", e);
}
}
if (in != null) {
- try {
+ try {
in.close();
} catch (IOException e) {
logger.error("Error closing output stream", e);
@@ -674,15 +565,15 @@ private static List findRecipientsFromDataSet(DispatchContext info, BIOb
String recipient = null;
IRecord record = (IRecord)it.next();
// the parameter value is used to filter on the first dataset field
- IField valueField = (IField) record.getFieldAt(0);
+ IField valueField = record.getFieldAt(0);
Object valueObj = valueField.getValue();
String value = null;
- if (valueObj != null)
+ if (valueObj != null)
value = valueObj.toString();
if (codeValue.equals(value)) {
logger.debug("Found value [" + codeValue + "] on the first field of a record of the dataset.");
// recipient address is on the second dataset field
- IField recipientField = (IField) record.getFieldAt(1);
+ IField recipientField = record.getFieldAt(1);
Object recipientFieldObj = recipientField.getValue();
if (recipientFieldObj != null) {
recipient = recipientFieldObj.toString();
@@ -706,42 +597,29 @@ private static List findRecipientsFromDataSet(DispatchContext info, BIOb
return recipients;
}
- private class SMTPAuthenticator extends javax.mail.Authenticator
- {
- private String username = "";
- private String password = "";
-
- public PasswordAuthentication getPasswordAuthentication()
- {
- return new PasswordAuthentication(username, password);
- }
-
- public SMTPAuthenticator(String user, String pass) {
- this.username = user;
- this.password = pass;
- }
- }
-
-
private class SchedulerDataSource implements DataSource {
byte[] content = null;
String name = null;
String contentType = null;
+ @Override
public String getContentType() {
return contentType;
}
+ @Override
public InputStream getInputStream() throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(content);
return bais;
}
+ @Override
public String getName() {
return name;
}
+ @Override
public OutputStream getOutputStream() throws IOException {
return null;
}
@@ -757,7 +635,7 @@ public SchedulerDataSource(byte[] content, String contentType, String name) {
// Returns the contents of the file in a byte array.
- public static byte[] getBytesFromFile(File file) throws IOException {
+ public static byte[] getBytesFromFile(File file) throws IOException {
// Get the size of the file
long length = file.length();
diff --git a/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/init/ResourceExportFolderSchedulerInitializer.java b/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/init/ResourceExportFolderSchedulerInitializer.java
new file mode 100644
index 00000000000..570bff64362
--- /dev/null
+++ b/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/init/ResourceExportFolderSchedulerInitializer.java
@@ -0,0 +1,119 @@
+package it.eng.spagobi.tools.scheduler.init;
+
+import org.apache.log4j.Logger;
+
+import it.eng.spago.base.SourceBean;
+import it.eng.spago.init.InitializerIFace;
+import it.eng.spagobi.commons.bo.Config;
+import it.eng.spagobi.commons.dao.DAOFactory;
+import it.eng.spagobi.tools.scheduler.bo.Job;
+import it.eng.spagobi.tools.scheduler.bo.Trigger;
+import it.eng.spagobi.tools.scheduler.dao.ISchedulerDAO;
+import it.eng.spagobi.tools.scheduler.jobs.ResourceExportFolderCleaningJob;
+import it.eng.spagobi.tools.scheduler.utils.PredefinedCronExpression;
+
+public class ResourceExportFolderSchedulerInitializer implements InitializerIFace {
+ public static final String DEFAULT_JOB_NAME = "CleanResourceExportFolderJob";
+ public static final String DEFAULT_TRIGGER_NAME = "schedule_resource_export_cleaning";
+
+ public static final String RESOURCE_EXPORT_FOLDER_SCHEDULING_FULL_CLEAN = "SPAGOBI.RESOURCE.EXPORT.FOLDER.SCHEDULING_FULL_CLEAN";
+
+ private String valueCheck = PredefinedCronExpression.DAILY.getLabel();
+
+ private final SourceBean _config = null;
+ private transient Logger logger = Logger.getLogger(ResourceExportFolderSchedulerInitializer.class);
+
+ @Override
+ public void init(SourceBean config) {
+ logger.debug("IN");
+ try {
+ initCleanForDefaultTenant();
+ } catch (Exception e) {
+ } finally {
+ logger.debug("OUT");
+ }
+
+ }
+
+ public void initCleanForDefaultTenant() {
+
+ ISchedulerDAO schedulerDAO = null;
+ try {
+ logger.debug("IN");
+ schedulerDAO = DAOFactory.getSchedulerDAO();
+ /* Tenant is mandatory. Set DEFAULT_TENANT but job is for all the tenants */
+ schedulerDAO.setTenant("DEFAULT_TENANT");
+ Job jobDetail = schedulerDAO.loadJob(DEFAULT_JOB_NAME, DEFAULT_JOB_NAME);
+ if (jobDetail == null) {
+ // CREATE JOB DETAIL
+ jobDetail = new Job();
+ jobDetail.setName(DEFAULT_JOB_NAME);
+ jobDetail.setGroupName(DEFAULT_JOB_NAME);
+ jobDetail.setDescription(DEFAULT_JOB_NAME);
+ jobDetail.setDurable(true);
+ jobDetail.setVolatile(false);
+ jobDetail.setRequestsRecovery(true);
+ jobDetail.setJobClass(ResourceExportFolderCleaningJob.class);
+
+ schedulerDAO.insertJob(jobDetail);
+ logger.debug("Added job with name " + DEFAULT_JOB_NAME);
+ }
+
+ Config configValue = DAOFactory.getSbiConfigDAO().loadConfigParametersByLabel(RESOURCE_EXPORT_FOLDER_SCHEDULING_FULL_CLEAN);
+
+ if (configValue != null && configValue.isActive()) {
+ valueCheck = configValue.getValueCheck();
+ }
+
+ String cronExpression = getCronExpression(valueCheck);
+ schedulerDAO.deleteTrigger(DEFAULT_TRIGGER_NAME, DEFAULT_JOB_NAME);
+ if (cronExpression != null) {
+ String nameTrig = DEFAULT_TRIGGER_NAME;
+
+ Trigger simpleTrigger = new Trigger();
+ simpleTrigger.setName(nameTrig);
+ simpleTrigger.setGroupName(DEFAULT_JOB_NAME);
+ simpleTrigger.setJob(jobDetail);
+ simpleTrigger.getChronExpression().setExpression(cronExpression);
+ simpleTrigger.setRunImmediately(false);
+
+ schedulerDAO.insertTrigger(simpleTrigger);
+ logger.debug("Added trigger with name " + DEFAULT_TRIGGER_NAME);
+ } else {
+ logger.debug("The value " + valueCheck
+ + " is not a valid value for schedule RESOURCE EXPORT FOLDER cleaning trigger. Please provide a valid one and restart the Server. PERIODIC RESOURCE EXPORT FOLDER CLEANING DISABLED.");
+ }
+ logger.debug("OUT");
+ } catch (Exception e) {
+ logger.error("Error while initializing scheduler ", e);
+ } finally {
+ if (schedulerDAO != null) {
+ schedulerDAO.setTenant(null);
+ }
+ }
+ }
+
+ private String getCronExpression(String valueCheck) {
+ if (valueCheck == null) {
+ logger.debug("This value is [" + valueCheck + "]");
+ return null;
+ }
+
+ for (PredefinedCronExpression value : PredefinedCronExpression.values()) {
+ if (valueCheck.equalsIgnoreCase(value.getLabel())) {
+ logger.debug("Found a predefined cron expression with label equals to [" + valueCheck + "]");
+ logger.debug("The cron expression is equals to [" + value.getExpression() + "]");
+ return value.getExpression();
+ }
+ }
+ logger.debug("No predefined cron expression found with label equals to [" + valueCheck + "]. Returning null.");
+ return null;
+ }
+
+ @Override
+ public SourceBean getConfig() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/jobs/ResourceExportFolderCleaningJob.java b/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/jobs/ResourceExportFolderCleaningJob.java
new file mode 100644
index 00000000000..91ec235f045
--- /dev/null
+++ b/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/jobs/ResourceExportFolderCleaningJob.java
@@ -0,0 +1,67 @@
+/*
+ * Knowage, Open Source Business Intelligence suite
+ * Copyright (C) 2016 Engineering Ingegneria Informatica S.p.A.
+ *
+ * Knowage is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Knowage is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+package it.eng.spagobi.tools.scheduler.jobs;
+
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.quartz.Job;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
+
+import it.eng.spagobi.commons.dao.DAOFactory;
+import it.eng.spagobi.commons.metadata.SbiTenant;
+import it.eng.spagobi.tenant.Tenant;
+import it.eng.spagobi.tenant.TenantManager;
+import it.eng.spagobi.tools.dataset.resource.export.ResourceExportFolderCleaningManager;
+
+public class ResourceExportFolderCleaningJob extends AbstractSpagoBIJob implements Job {
+
+ static private Logger logger = Logger.getLogger(ResourceExportFolderCleaningJob.class);
+
+ @Override
+ public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
+ logger.debug("IN");
+ try {
+ executeInternal();
+ } finally {
+ logger.debug("OUT");
+ }
+ }
+
+ private void executeInternal() {
+
+ logger.debug("IN");
+ try {
+ ResourceExportFolderCleaningManager resourceExportFolderCleaningManager = new ResourceExportFolderCleaningManager();
+ List allTenants = DAOFactory.getTenantsDAO().loadAllTenants();
+ for (SbiTenant sbiTenant : allTenants) {
+
+ TenantManager.setTenant(new Tenant(sbiTenant.getName()));
+ resourceExportFolderCleaningManager.executeCleaning();
+ this.unsetTenant();
+ }
+
+ logger.debug("Resource export folder cleaning ended succesfully!");
+ } catch (Exception e) {
+ logger.error("Error while executiong job ", e);
+ } finally {
+ logger.debug("OUT");
+ }
+ }
+}
diff --git a/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/utils/SchedulerUtilitiesV2.java b/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/utils/SchedulerUtilitiesV2.java
index 4273e54e7a0..190d372f1c3 100644
--- a/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/utils/SchedulerUtilitiesV2.java
+++ b/knowage-core/src/main/java/it/eng/spagobi/tools/scheduler/utils/SchedulerUtilitiesV2.java
@@ -245,7 +245,11 @@ public static JobTrigger getJobTriggerFromJsonRequest(JSONObject jsonObject, JSO
}
jobTrigger.setZonedStartTime(jsonObject.optString(JobTrigger.ZONED_START_TIME));
- jobTrigger.setZonedEndTime(jsonObject.optString(JobTrigger.ZONED_END_TIME));
+ try {
+ jobTrigger.setZonedEndTime(jsonObject.getString(JobTrigger.ZONED_END_TIME));
+ } catch (JSONException e) {
+ // End time can be optional
+ }
jobTrigger.setChrono(((JSONObject) jsonObject.opt(JobTrigger.CHRONO)).toString().replaceAll("\"", "'"));
JSONArray ja = (JSONArray) jsonObject.opt(JobTrigger.DOCUMENTS);
diff --git a/knowage-core/src/main/java/it/eng/spagobi/wapp/services/ReadHtmlFile.java b/knowage-core/src/main/java/it/eng/spagobi/wapp/services/ReadHtmlFile.java
index c6f138b4297..de0e70d3ffe 100644
--- a/knowage-core/src/main/java/it/eng/spagobi/wapp/services/ReadHtmlFile.java
+++ b/knowage-core/src/main/java/it/eng/spagobi/wapp/services/ReadHtmlFile.java
@@ -17,6 +17,16 @@
*/
package it.eng.spagobi.wapp.services;
+import java.io.FileInputStream;
+
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.log4j.Logger;
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+
+import it.eng.knowage.menu.api.MenuManagementAPI;
import it.eng.spago.base.SourceBean;
import it.eng.spago.dispatching.action.AbstractHttpAction;
import it.eng.spago.error.EMFErrorSeverity;
@@ -28,15 +38,6 @@
import it.eng.spagobi.commons.utilities.UserUtilities;
import it.eng.spagobi.wapp.bo.Menu;
-import java.io.FileInputStream;
-
-import javax.servlet.ServletOutputStream;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.log4j.Logger;
-import org.hibernate.HibernateException;
-import org.hibernate.Session;
-
public class ReadHtmlFile extends AbstractHttpAction {
static private Logger logger = Logger.getLogger(ReadHtmlFile.class);
@@ -70,6 +71,12 @@ public void service(SourceBean serviceRequest, SourceBean serviceResponse) throw
logger.debug("menuId=" + menuId);
if (menuId != null) {
Menu menu = DAOFactory.getMenuDAO().loadMenuByID(Integer.valueOf(menuId));
+ boolean accessible = new MenuManagementAPI(UserUtilities.getUserProfile()).isAccessibleMenu(menu);
+ if (!accessible) {
+ logger.error("No role found for menu with id = " + menu.getMenuId() + ". Not allowed menu.");
+ throw new Exception("No role found for menu with id = " + menu.getMenuId() + ". Not allowed menu.");
+ }
+
String fileName = menu.getStaticPage();
if (fileName == null) {
diff --git a/knowage-core/src/test/java/it/eng/spagobi/tools/dataset/resource/export/test/ResourceExportFolderCleaningTest1.java b/knowage-core/src/test/java/it/eng/spagobi/tools/dataset/resource/export/test/ResourceExportFolderCleaningTest1.java
new file mode 100644
index 00000000000..64421c8e5a0
--- /dev/null
+++ b/knowage-core/src/test/java/it/eng/spagobi/tools/dataset/resource/export/test/ResourceExportFolderCleaningTest1.java
@@ -0,0 +1,34 @@
+package it.eng.spagobi.tools.dataset.resource.export.test;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.File;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import it.eng.spagobi.tools.dataset.resource.export.ResourceExportFolderCleaningManager;
+import it.eng.spagobi.tools.dataset.resource.export.utils.ResourceExportFolderCleaningManagerUtils;
+
+public class ResourceExportFolderCleaningTest1 extends ResourceExportFolderCleaningTestMain {
+
+ private static final String FOLDER_PATH = "C:\\temp\\TestMain1\\";
+ private ResourceExportFolderCleaningManager resourceExportFolderCleaningManager = new ResourceExportFolderCleaningManager();
+
+ @Before
+ public void prepare() throws Exception {
+ ResourceExportFolderCleaningManagerUtils cleaningManagerUtils = new ResourceExportFolderCleaningManagerUtils();
+ cleaningManagerUtils.createFilesUntilFolderSize(FOLDER_PATH, MAX_FOLDER_SIZE);
+
+ resourceExportFolderCleaningManager.executeCleaning(FOLDER_PATH, MAX_FOLDER_SIZE, CLEANING_PERCENTAGE);
+
+ }
+
+ @Test
+ public void test() throws Exception {
+ Long actualFolderSize = resourceExportFolderCleaningManager.folderSize(new File(FOLDER_PATH));
+
+ assertEquals("Expected FolderSize", true, actualFolderSize < MAX_FOLDER_SIZE * (1 - CLEANING_PERCENTAGE));
+ }
+
+}
diff --git a/knowage-core/src/test/java/it/eng/spagobi/tools/dataset/resource/export/test/ResourceExportFolderCleaningTest2.java b/knowage-core/src/test/java/it/eng/spagobi/tools/dataset/resource/export/test/ResourceExportFolderCleaningTest2.java
new file mode 100644
index 00000000000..bd72359204a
--- /dev/null
+++ b/knowage-core/src/test/java/it/eng/spagobi/tools/dataset/resource/export/test/ResourceExportFolderCleaningTest2.java
@@ -0,0 +1,34 @@
+package it.eng.spagobi.tools.dataset.resource.export.test;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.File;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import it.eng.spagobi.tools.dataset.resource.export.ResourceExportFolderCleaningManager;
+import it.eng.spagobi.tools.dataset.resource.export.utils.ResourceExportFolderCleaningManagerUtils;
+
+public class ResourceExportFolderCleaningTest2 extends ResourceExportFolderCleaningTestMain {
+
+ private static final String FOLDER_PATH = "C:\\temp\\TestMain2\\";
+ private ResourceExportFolderCleaningManager resourceExportFolderCleaningManager = new ResourceExportFolderCleaningManager();
+
+ @Before
+ public void prepare() throws Exception {
+ ResourceExportFolderCleaningManagerUtils cleaningManagerUtils = new ResourceExportFolderCleaningManagerUtils();
+ cleaningManagerUtils.createFilesUntilFolderSize(FOLDER_PATH, MAX_FOLDER_SIZE - 2 * ResourceExportFolderCleaningManagerUtils.DEFAULT_FILE_SIZE);
+
+ resourceExportFolderCleaningManager.executeCleaning(FOLDER_PATH, MAX_FOLDER_SIZE, CLEANING_PERCENTAGE);
+
+ }
+
+ @Test
+ public void test() throws Exception {
+ Long actualFolderSize = resourceExportFolderCleaningManager.folderSize(new File(FOLDER_PATH));
+
+ assertEquals("Expected FolderSize", true, actualFolderSize < MAX_FOLDER_SIZE * (1 - CLEANING_PERCENTAGE));
+ }
+
+}
diff --git a/knowage-core/src/test/java/it/eng/spagobi/tools/dataset/resource/export/test/ResourceExportFolderCleaningTestMain.java b/knowage-core/src/test/java/it/eng/spagobi/tools/dataset/resource/export/test/ResourceExportFolderCleaningTestMain.java
new file mode 100644
index 00000000000..7ccf74bf173
--- /dev/null
+++ b/knowage-core/src/test/java/it/eng/spagobi/tools/dataset/resource/export/test/ResourceExportFolderCleaningTestMain.java
@@ -0,0 +1,6 @@
+package it.eng.spagobi.tools.dataset.resource.export.test;
+
+public class ResourceExportFolderCleaningTestMain {
+ protected static final Long MAX_FOLDER_SIZE = 104857600L;
+ protected static final Double CLEANING_PERCENTAGE = 30.0;
+}
diff --git a/knowage-core/src/test/java/it/eng/spagobi/tools/dataset/resource/export/utils/ResourceExportFolderCleaningManagerUtils.java b/knowage-core/src/test/java/it/eng/spagobi/tools/dataset/resource/export/utils/ResourceExportFolderCleaningManagerUtils.java
new file mode 100644
index 00000000000..8649529e934
--- /dev/null
+++ b/knowage-core/src/test/java/it/eng/spagobi/tools/dataset/resource/export/utils/ResourceExportFolderCleaningManagerUtils.java
@@ -0,0 +1,69 @@
+package it.eng.spagobi.tools.dataset.resource.export.utils;
+
+import java.io.File;
+import java.io.RandomAccessFile;
+import java.util.HashMap;
+import java.util.Map;
+
+public class ResourceExportFolderCleaningManagerUtils {
+
+ public static final long DEFAULT_FILE_SIZE = 10485760L;
+
+ public boolean createSingleFile(String path, Long length) {
+ boolean wellCreated = false;
+ RandomAccessFile rafile;
+ try {
+ rafile = new RandomAccessFile(path, "rw");
+ rafile.setLength(length);
+ wellCreated = true;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return wellCreated;
+ }
+
+ public void createFilesUntilFolderSize(String folderPath, Long folderSize, Long fileSize) {
+ if (!new File(folderPath).exists()) {
+ new File(folderPath).mkdirs();
+ } else {
+ for (File file : new File(folderPath).listFiles()) {
+ file.delete();
+ }
+ new File(folderPath).delete();
+ new File(folderPath).mkdirs();
+ }
+
+ Map filesMap = new HashMap();
+
+ Long currentFolderSize = 0L;
+ int i = 0;
+ do {
+
+ filesMap.put(folderPath + "file_" + i++, fileSize);
+
+ currentFolderSize += fileSize;
+
+ } while (currentFolderSize <= folderSize);
+
+ for (String filePath : filesMap.keySet()) {
+ createSingleFile(filePath, filesMap.get(filePath));
+ }
+
+ }
+
+ public void createFilesUntilFolderSize(String folderPath, Long folderSize) {
+ createFilesUntilFolderSize(folderPath, folderSize, DEFAULT_FILE_SIZE);
+ }
+
+ public long folderSize(File folder) {
+ long length = 0;
+ for (File file : folder.listFiles()) {
+ if (file.isFile()) {
+ length += file.length();
+ } else {
+ length += folderSize(file);
+ }
+ }
+ return length;
+ }
+}
diff --git a/knowage/pom.xml b/knowage/pom.xml
index c5cb954bea2..db857b0ab70 100644
--- a/knowage/pom.xml
+++ b/knowage/pom.xml
@@ -240,6 +240,10 @@
xalan
xalan
+
+ com.google.guava
+ guava
+