diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/entities/JobSchedulerConfiguration.java b/libreplan-business/src/main/java/org/libreplan/business/common/entities/JobSchedulerConfiguration.java
index cd65eadcd..3f08058d7 100644
--- a/libreplan-business/src/main/java/org/libreplan/business/common/entities/JobSchedulerConfiguration.java
+++ b/libreplan-business/src/main/java/org/libreplan/business/common/entities/JobSchedulerConfiguration.java
@@ -28,28 +28,17 @@ import org.libreplan.business.common.Registry;
import org.libreplan.business.common.daos.IJobSchedulerConfigurationDAO;
/**
- * JobSchedulerConfiguration entity, represents parameters for the jobs to be
- * scheduled. This entity is used by the SchedulerManager to
+ * JobSchedulerConfiguration entity, represents parameters for the jobs to be scheduled.
+ * This entity is used by the SchedulerManager to
* schedule jobs and in UI to show the scheduler status.
*
* The jobGroup and jobName together forms a job key
- * and non of the fields must be null. Moreover it should contain a valid
- * cronExpression
+ * and non of the fields must be null. Moreover it should contain a valid cronExpression.
*
* @author Miciele Ghiorghis
*/
public class JobSchedulerConfiguration extends BaseEntity implements IHumanIdentifiable {
- public static JobSchedulerConfiguration create() {
- return create(new JobSchedulerConfiguration());
- }
-
- /**
- * Constructor for Hibernate. Do not use!
- */
- protected JobSchedulerConfiguration() {
- }
-
private String jobGroup;
private String jobName;
@@ -62,6 +51,15 @@ public class JobSchedulerConfiguration extends BaseEntity implements IHumanIdent
private String connectorName;
+ /**
+ * Constructor for Hibernate. Do not use!
+ */
+ protected JobSchedulerConfiguration() {}
+
+ public static JobSchedulerConfiguration create() {
+ return create(new JobSchedulerConfiguration());
+ }
+
@NotNull(message = "job group not specified")
public String getJobGroup() {
return jobGroup;
@@ -124,7 +122,9 @@ public class JobSchedulerConfiguration extends BaseEntity implements IHumanIdent
if ( StringUtils.isBlank(jobGroup) && StringUtils.isBlank(jobName) ) {
return true;
}
+
IJobSchedulerConfigurationDAO jobSchedulerConfigurationDAO = Registry.getJobSchedulerConfigurationDAO();
+
if ( isNewObject() ) {
return !jobSchedulerConfigurationDAO.existsByJobGroupAndJobNameAnotherTransaction(this);
} else {
diff --git a/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailNotificationDAO.java b/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailNotificationDAO.java
index ad63fd92f..a1f2a7872 100644
--- a/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailNotificationDAO.java
+++ b/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailNotificationDAO.java
@@ -30,12 +30,11 @@ import java.util.List;
/**
* Dao for {@link EmailNotification}
*
- * Created by
- * @author Vova Perebykivskiy
- * on 19.10.2015.
+ * @author Created by Vova Perebykivskiy on 19.10.2015.
*/
@Repository
-public class EmailNotificationDAO extends GenericDAOHibernate
+public class EmailNotificationDAO
+ extends GenericDAOHibernate
implements IEmailNotificationDAO {
@Override
@@ -45,13 +44,16 @@ public class EmailNotificationDAO extends GenericDAOHibernate getAllByType(EmailTemplateEnum enumeration) {
- return getSession().createCriteria(EmailNotification.class)
- .add(Restrictions.eq("type", enumeration)).list();
+ return getSession()
+ .createCriteria(EmailNotification.class)
+ .add(Restrictions.eq("type", enumeration))
+ .list();
}
@Override
public boolean deleteAll() {
List notifications = list(EmailNotification.class);
+
for (Object item : notifications){
getSession().delete(item);
}
@@ -61,23 +63,30 @@ public class EmailNotificationDAO extends GenericDAOHibernate notifications = getSession().createCriteria(EmailNotification.class)
- .add(Restrictions.eq("type", enumeration)).list();
+ List notifications = getSession()
+ .createCriteria(EmailNotification.class)
+ .add(Restrictions.eq("type", enumeration))
+ .list();
+
for (Object item : notifications){
getSession().delete(item);
}
- if ( getSession().createCriteria(EmailNotification.class)
- .add(Restrictions.eq("type", enumeration.ordinal())).list().size() == 0 ) return true;
- return false;
+ return getSession()
+ .createCriteria(EmailNotification.class)
+ .add(Restrictions.eq("type", enumeration.ordinal()))
+ .list()
+ .size() == 0;
}
@Override
public boolean deleteById(EmailNotification notification) {
getSession().delete(notification);
- if ( getSession().createCriteria(EmailNotification.class).add(Restrictions.eq("id", notification.getId()))
- .uniqueResult() != null ) return false;
- return true;
+
+ return getSession()
+ .createCriteria(EmailNotification.class)
+ .add(Restrictions.eq("id", notification.getId()))
+ .uniqueResult() == null;
}
}
diff --git a/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailTemplateDAO.java b/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailTemplateDAO.java
index d7ab0a0d6..7c8439cae 100644
--- a/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailTemplateDAO.java
+++ b/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailTemplateDAO.java
@@ -19,60 +19,56 @@
package org.libreplan.business.email.daos;
+import org.hibernate.criterion.Restrictions;
import org.libreplan.business.common.daos.GenericDAOHibernate;
+import org.libreplan.business.common.exceptions.InstanceNotFoundException;
import org.libreplan.business.email.entities.EmailTemplate;
+import org.libreplan.business.email.entities.EmailTemplateEnum;
+import org.libreplan.business.settings.entities.Language;
import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* DAO for {@link EmailTemplate}
*
- * Created by
- * @author Vova Perebykivskiy
- * on 24.09.2015.
+ * @author Created by Vova Perebykivskiy on 24.09.2015.
*/
@Repository
public class EmailTemplateDAO extends GenericDAOHibernate implements IEmailTemplateDAO{
@Override
+ @Transactional(readOnly = true)
public List getAll() {
return list(EmailTemplate.class);
}
@Override
- public String getContentBySelectedLanguage(int languageOrdinal, int emailTemplateTypeOrdinal) {
- for (int i = 0; i < list(EmailTemplate.class).size(); i++)
- if ( list(EmailTemplate.class).get(i).getLanguage().ordinal() == languageOrdinal &&
- list(EmailTemplate.class).get(i).getType().ordinal() == emailTemplateTypeOrdinal )
- return list(EmailTemplate.class).get(i).getContent();
- return "";
+ @Transactional(readOnly = true)
+ public List findByType(EmailTemplateEnum type) {
+ return getSession()
+ .createCriteria(EmailTemplate.class)
+ .add(Restrictions.eq("type", type))
+ .list();
}
@Override
- public String getContentBySelectedTemplate(int emailTemplateTypeOrdinal, int languageOrdinal) {
- for (int i = 0; i < list(EmailTemplate.class).size(); i++)
- if ( list(EmailTemplate.class).get(i).getType().ordinal() == emailTemplateTypeOrdinal &&
- list(EmailTemplate.class).get(i).getLanguage().ordinal() == languageOrdinal )
- return list(EmailTemplate.class).get(i).getContent();
- return "";
+ @Transactional(readOnly = true)
+ public EmailTemplate findByTypeAndLanguage(EmailTemplateEnum type, Language language) {
+ return (EmailTemplate) getSession()
+ .createCriteria(EmailTemplate.class)
+ .add(Restrictions.eq("type", type))
+ .add(Restrictions.eq("language", language))
+ .uniqueResult();
}
@Override
- public String getSubjectBySelectedLanguage(int languageOrdinal, int emailTemplateTypeOrdinal) {
- for (int i = 0; i < list(EmailTemplate.class).size(); i++)
- if ( list(EmailTemplate.class).get(i).getLanguage().ordinal() == languageOrdinal &&
- list(EmailTemplate.class).get(i).getType().ordinal() == emailTemplateTypeOrdinal )
- return list(EmailTemplate.class).get(i).getSubject();
- return "";
- }
-
- @Override
- public String getSubjectBySelectedTemplate(int emailTemplateTypeOrdinal, int languageOrdinal) {
- for (int i = 0; i < list(EmailTemplate.class).size(); i++)
- if ( list(EmailTemplate.class).get(i).getType().ordinal() == emailTemplateTypeOrdinal &&
- list(EmailTemplate.class).get(i).getLanguage().ordinal() == languageOrdinal )
- return list(EmailTemplate.class).get(i).getSubject();
- return "";
+ @Transactional
+ public void delete(EmailTemplate entity) {
+ try {
+ remove(entity.getId());
+ } catch (InstanceNotFoundException ignored) {
+ }
}
}
diff --git a/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailNotificationDAO.java b/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailNotificationDAO.java
index 140d85547..a23a69265 100644
--- a/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailNotificationDAO.java
+++ b/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailNotificationDAO.java
@@ -28,15 +28,17 @@ import java.util.List;
/**
* Contract for {@link EmailNotificationDAO}
*
- * Created by
- * @author Vova Perebykivskiy
- * on 19.10.15.
+ * @author Created by Vova Perebykivskiy on 19.10.2015.
*/
public interface IEmailNotificationDAO extends IGenericDAO {
+
List getAll();
+
List getAllByType(EmailTemplateEnum enumeration);
boolean deleteAll();
+
boolean deleteAllByType(EmailTemplateEnum enumeration);
+
boolean deleteById(EmailNotification notification);
}
diff --git a/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailTemplateDAO.java b/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailTemplateDAO.java
index db40ffae4..e2d7ebf3a 100644
--- a/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailTemplateDAO.java
+++ b/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailTemplateDAO.java
@@ -21,6 +21,8 @@ package org.libreplan.business.email.daos;
import org.libreplan.business.common.daos.IGenericDAO;
import org.libreplan.business.email.entities.EmailTemplate;
+import org.libreplan.business.email.entities.EmailTemplateEnum;
+import org.libreplan.business.settings.entities.Language;
import java.util.List;
@@ -28,17 +30,15 @@ import java.util.List;
* DAO interface for the EmailTemplate entity.
* Contract for {@link EmailTemplateDAO}
*
- * Created by
- * @author Vova Perebykivskiy
- * on 29.09.2015.
+ * @author Created by Vova Perebykivskiy on 29.09.2015.
*/
public interface IEmailTemplateDAO extends IGenericDAO{
List getAll();
- String getContentBySelectedLanguage(int languageOrdinal, int emailTemplateTypeOrdinal);
- String getContentBySelectedTemplate(int emailTemplateTypeOrdinal, int languageOrdinal);
+ List findByType(EmailTemplateEnum emailTemplateEnum);
- String getSubjectBySelectedLanguage(int languageOrdinal, int emailTemplateTypeOrdinal);
- String getSubjectBySelectedTemplate(int emailTemplateTypeOrdinal, int languageOrdinal);
+ EmailTemplate findByTypeAndLanguage(EmailTemplateEnum emailTemplateEnum, Language language);
+
+ void delete(EmailTemplate entity);
}
diff --git a/libreplan-business/src/main/java/org/libreplan/business/email/entities/EmailNotification.java b/libreplan-business/src/main/java/org/libreplan/business/email/entities/EmailNotification.java
index 747de25b1..f17415cca 100644
--- a/libreplan-business/src/main/java/org/libreplan/business/email/entities/EmailNotification.java
+++ b/libreplan-business/src/main/java/org/libreplan/business/email/entities/EmailNotification.java
@@ -31,9 +31,7 @@ import java.util.Date;
* This class is intended to work as a Hibernate component.
* It represents the Email notification to be send to user.
*
- * Created by
- * @author Vova Perebykivskyi
- * on 19.10.2015.
+ * @author Created by Vova Perebykivskyi on 19.10.2015.
*/
public class EmailNotification extends BaseEntity {
diff --git a/libreplan-business/src/main/java/org/libreplan/business/email/entities/EmailTemplate.java b/libreplan-business/src/main/java/org/libreplan/business/email/entities/EmailTemplate.java
index 10b56d801..68905c002 100644
--- a/libreplan-business/src/main/java/org/libreplan/business/email/entities/EmailTemplate.java
+++ b/libreplan-business/src/main/java/org/libreplan/business/email/entities/EmailTemplate.java
@@ -27,9 +27,7 @@ import org.libreplan.business.settings.entities.Language;
* This class is intended to work as a Hibernate component.
* It represents the E-mail template to be modified by admin and send to user.
*
- * Created by
- * @author Vova Perebykivskyi
- * on 29.09.2015.
+ * @author Created by Vova Perebykivskyi on 29.09.2015.
*/
public class EmailTemplate extends BaseEntity {
@@ -56,14 +54,14 @@ public class EmailTemplate extends BaseEntity {
}
public String getContent() {
- return content;
+ return content != null ? content : "";
}
public void setContent(String content) {
this.content = content;
}
public String getSubject() {
- return subject;
+ return subject != null ? subject : "";
}
public void setSubject(String subject) {
this.subject = subject;
diff --git a/libreplan-business/src/main/java/org/libreplan/business/email/entities/EmailTemplateEnum.java b/libreplan-business/src/main/java/org/libreplan/business/email/entities/EmailTemplateEnum.java
index 38c67cef5..9cd69bdb5 100644
--- a/libreplan-business/src/main/java/org/libreplan/business/email/entities/EmailTemplateEnum.java
+++ b/libreplan-business/src/main/java/org/libreplan/business/email/entities/EmailTemplateEnum.java
@@ -24,9 +24,7 @@ import static org.libreplan.business.i18n.I18nHelper._;
/**
* Available E-mail templates.
*
- * Created by
- * @author Vova Perebykivskyi
- * on 28.09.2015.
+ * @author Created by Vova Perebykivskyi on 28.09.2015.
*
* TEMPLATE_N(_("Template N")) - for i18n
* TEMPLATE_A("Template A") - for general use (no internationalizing)
diff --git a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/ManualFunction.java b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/ManualFunction.java
index 0035c2e78..783e52f24 100644
--- a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/ManualFunction.java
+++ b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/ManualFunction.java
@@ -20,8 +20,7 @@ package org.libreplan.business.planner.entities;
/**
- * Manual allocation function, it used to represent when user has done a manual
- * allocation.
+ * Manual allocation function, it used to represent when user has done a manual allocation.
*
* @author Manuel Rego Casasnovas
*/
diff --git a/libreplan-business/src/main/java/org/libreplan/business/qualityforms/daos/QualityFormDAO.java b/libreplan-business/src/main/java/org/libreplan/business/qualityforms/daos/QualityFormDAO.java
index d1e88e556..182bab06d 100644
--- a/libreplan-business/src/main/java/org/libreplan/business/qualityforms/daos/QualityFormDAO.java
+++ b/libreplan-business/src/main/java/org/libreplan/business/qualityforms/daos/QualityFormDAO.java
@@ -45,19 +45,20 @@ import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
- * DAO for {@link QualityForm}
+ * DAO for {@link QualityForm}.
+ *
* @author Susana Montes Pedreira
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
-public class QualityFormDAO extends GenericDAOHibernate
- implements IQualityFormDAO {
+public class QualityFormDAO extends GenericDAOHibernate implements IQualityFormDAO {
@Autowired
private IAdvanceTypeDAO advanceTypeDAO;
@Override
+ @Transactional(readOnly = true)
public List getAll() {
return list(QualityForm.class);
}
@@ -67,8 +68,7 @@ public class QualityFormDAO extends GenericDAOHibernate
public boolean isUnique(QualityForm qualityForm) {
try {
QualityForm result = findUniqueByName(qualityForm);
- return (result == null || result.getId()
- .equals(qualityForm.getId()));
+ return result == null || result.getId().equals(qualityForm.getId());
} catch (Exception e) {
e.printStackTrace();
return false;
@@ -78,32 +78,33 @@ public class QualityFormDAO extends GenericDAOHibernate
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
public QualityForm findByNameAndType(String name, QualityFormType type) {
- return (QualityForm) getSession().createCriteria(QualityForm.class)
- .add(Restrictions.eq("name", name)).add(
- Restrictions.eq("qualityFormType", type))
+ return (QualityForm) getSession()
+ .createCriteria(QualityForm.class)
+ .add(Restrictions.eq("name", name))
+ .add(Restrictions.eq("qualityFormType", type))
.uniqueResult();
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
public List getAllByType(QualityFormType type) {
- Criteria c = getSession().createCriteria(QualityForm.class).add(
- Restrictions.eq("qualityFormType", type));
- return ((List) c.list());
+ return getSession()
+ .createCriteria(QualityForm.class)
+ .add(Restrictions.eq("qualityFormType", type))
+ .list();
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
- public QualityForm findUniqueByName(QualityForm qualityForm)
- throws InstanceNotFoundException {
+ public QualityForm findUniqueByName(QualityForm qualityForm) throws InstanceNotFoundException {
Validate.notNull(qualityForm);
+
return findUniqueByName(qualityForm.getName());
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
- public QualityForm findUniqueByName(String name)
- throws InstanceNotFoundException, NonUniqueResultException {
+ public QualityForm findUniqueByName(String name) throws InstanceNotFoundException, NonUniqueResultException {
Criteria c = getSession().createCriteria(QualityForm.class);
c.add(Restrictions.eq("name", name));
QualityForm qualityForm = (QualityForm) c.uniqueResult();
@@ -119,7 +120,8 @@ public class QualityFormDAO extends GenericDAOHibernate
public boolean existsOtherWorkReportTypeByName(QualityForm qualityForm) {
try {
QualityForm t = findUniqueByName(qualityForm);
- return (t != null && t != qualityForm);
+
+ return t != null && t != qualityForm;
} catch (InstanceNotFoundException e) {
return false;
}
@@ -141,8 +143,9 @@ public class QualityFormDAO extends GenericDAOHibernate
advanceTypeDAO.save(advanceType);
advanceType.setUnitName(name);
} else {
- advanceType = AdvanceType.create(name, new BigDecimal(100),
- false, new BigDecimal(0.01), true, true, true);
+ advanceType = AdvanceType.create(
+ name, new BigDecimal(100), false, BigDecimal.valueOf(0.01), true, true, true);
+
advanceTypeDAO.save(advanceType);
entity.setAdvanceType(advanceType);
@@ -154,14 +157,15 @@ public class QualityFormDAO extends GenericDAOHibernate
@Override
public void checkHasTasks(QualityForm qualityForm) throws ValidationException {
- Query query = getSession().createQuery(
- "FROM TaskQualityForm taskQualityForm JOIN taskQualityForm.qualityForm tq WHERE tq IN (:qualityForms)");
+ String queryString =
+ "FROM TaskQualityForm taskQualityForm JOIN taskQualityForm.qualityForm tq WHERE tq IN (:qualityForms)";
+
+ Query query = getSession().createQuery(queryString);
+
query.setParameterList("qualityForms", Collections.singleton(qualityForm));
if (!query.list().isEmpty()) {
- throw ValidationException
- .invalidValueException(
- "Cannot delete quality form. It is being used at this moment by some task.",
- qualityForm);
+ throw ValidationException.invalidValueException(
+ "Cannot delete quality form. It is being used at this moment by some task.", qualityForm);
}
}
}
diff --git a/libreplan-business/src/main/resources/db.changelog-1.5.xml b/libreplan-business/src/main/resources/db.changelog-1.5.xml
index 4f7e0fc59..8b9065668 100644
--- a/libreplan-business/src/main/resources/db.changelog-1.5.xml
+++ b/libreplan-business/src/main/resources/db.changelog-1.5.xml
@@ -32,11 +32,6 @@
INSERT INTO email_template VALUES(1, 0, 3, 'Task assigned to resource : Autogenerated content text', 'Autogenerated subject text');
- INSERT INTO email_template VALUES(2, 1, 3, 'Resource removed from task : Autogenerated content text', 'Autogenerated subject text');
- INSERT INTO email_template VALUES(3, 2, 3, 'Milestone reached : Autogenerated content text', 'Autogenerated subject text');
- INSERT INTO email_template VALUES(4, 3, 3, 'Task should start : Autogenerated content text', 'Autogenerated subject text');
- INSERT INTO email_template VALUES(5, 4, 3, 'Task should finish : Autogenerated content text', 'Autogenerated subject text');
- INSERT INTO email_template VALUES(6, 5, 3, 'Enter data to timesheet : Autogenerated content text', 'Autogenerated subject text');
diff --git a/libreplan-business/src/main/resources/libreplan-business-spring-config.xml b/libreplan-business/src/main/resources/libreplan-business-spring-config.xml
index ce20884e4..919b6c165 100644
--- a/libreplan-business/src/main/resources/libreplan-business-spring-config.xml
+++ b/libreplan-business/src/main/resources/libreplan-business-spring-config.xml
@@ -1,10 +1,12 @@
-
-
+
+
+ class="org.springframework.orm.hibernate5.HibernateTransactionManager"
+ p:sessionFactory-ref="sessionFactory" />
diff --git a/libreplan-business/src/main/resources/org/libreplan/business/email/entities/Email.hbm.xml b/libreplan-business/src/main/resources/org/libreplan/business/email/entities/Email.hbm.xml
index 1f2eba87d..44a382b9a 100644
--- a/libreplan-business/src/main/resources/org/libreplan/business/email/entities/Email.hbm.xml
+++ b/libreplan-business/src/main/resources/org/libreplan/business/email/entities/Email.hbm.xml
@@ -4,7 +4,7 @@
-
+
diff --git a/libreplan-business/src/main/resources/org/libreplan/business/orders/entities/Orders.hbm.xml b/libreplan-business/src/main/resources/org/libreplan/business/orders/entities/Orders.hbm.xml
index de46023e6..f92a04074 100644
--- a/libreplan-business/src/main/resources/org/libreplan/business/orders/entities/Orders.hbm.xml
+++ b/libreplan-business/src/main/resources/org/libreplan/business/orders/entities/Orders.hbm.xml
@@ -79,9 +79,9 @@
-
+
-
+
diff --git a/libreplan-business/src/test/resources/libreplan-business-spring-config-test.xml b/libreplan-business/src/test/resources/libreplan-business-spring-config-test.xml
index d0f2bdc0c..ae5372a45 100644
--- a/libreplan-business/src/test/resources/libreplan-business-spring-config-test.xml
+++ b/libreplan-business/src/test/resources/libreplan-business-spring-config-test.xml
@@ -97,6 +97,9 @@
TestEntities.hbm.xml
+
+ org/libreplan/business/common/entities/Limits.hbm.xml
+
diff --git a/libreplan-webapp/pom.xml b/libreplan-webapp/pom.xml
index a9c5a748e..3354c0c58 100644
--- a/libreplan-webapp/pom.xml
+++ b/libreplan-webapp/pom.xml
@@ -394,9 +394,8 @@
- javax.mail
- mail
- 1.5.0-b01
+ com.sun.mail
+ javax.mail
diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/ComposeMessage.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/ComposeMessage.java
index eed5d5a9c..b79a4a298 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/ComposeMessage.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/ComposeMessage.java
@@ -34,9 +34,7 @@ import static org.libreplan.web.I18nHelper._;
* Sends E-mail to users with data that storing in notification_queue table
* and that are treat to incoming EmailNotification
*
- * Created by
- * @author Vova Perebykivskiy
- * on 20.01.2016.
+ * @author Created by Vova Perebykivskiy on 20.01.2016.
*/
@Component
@@ -76,7 +74,8 @@ public class ComposeMessage {
UserRole currentUserRole = getCurrentUserRole(notification.getType());
- if ( currentWorker.getUser().isInRole(currentUserRole) ){
+ if ( currentWorker.getUser().isInRole(currentUserRole) ) {
+
if ( currentWorker.getUser().getApplicationLanguage().equals(Language.BROWSER_LANGUAGE) ) {
locale = new Locale(System.getProperty("user.language"));
} else {
@@ -96,16 +95,15 @@ public class ComposeMessage {
final String username = usrnme;
final String password = psswrd;
- // It is very important to use Session.getInstance instead of Session.getDefaultInstance
- Session mailSession = Session.getInstance(properties,
- new javax.mail.Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(username, password);
- }
- });
+ // It is very important to use Session.getInstance() instead of Session.getDefaultInstance()
+ Session mailSession = Session.getInstance(properties, new javax.mail.Authenticator() {
+ protected PasswordAuthentication getPasswordAuthentication() {
+ return new PasswordAuthentication(username, password);
+ }
+ });
// Send message
- try{
+ try {
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(sender));
@@ -122,37 +120,42 @@ public class ComposeMessage {
} catch (MessagingException e) {
throw new RuntimeException(e);
- } catch (NullPointerException e){
- if (receiver == null) try {
- Messagebox.show(_(currentWorker.getUser().getLoginName() + " - this user have not filled E-mail"), _("Error"),
- Messagebox.OK, Messagebox.ERROR);
- } catch (InterruptedException e1) {
- e1.printStackTrace();
- }
+ } catch (NullPointerException e) {
+ if (receiver == null)
+ try {
+ Messagebox.show(
+ _(currentWorker.getUser().getLoginName() + " - this user have not filled E-mail"),
+ _("Error"), Messagebox.OK, Messagebox.ERROR);
+ } catch (InterruptedException e1) {
+ e1.printStackTrace();
+ }
}
}
return false;
}
- private Worker getCurrentWorker(Long resourceID){
+ private Worker getCurrentWorker(Long resourceID) {
List workerList = workerModel.getWorkers();
- for(int i = 0; i < workerList.size(); i++)
- if ( workerList.get(i).getId().equals(resourceID) )
- return workerList.get(i);
+ for (Worker current : workerList)
+ if ( current.getId().equals(resourceID) )
+ return current;
+
return null;
}
- private EmailTemplate findCurrentEmailTemplate(EmailTemplateEnum templateEnum, Locale locale){
+ private EmailTemplate findCurrentEmailTemplate(EmailTemplateEnum templateEnum, Locale locale) {
List emailTemplates;
emailTemplates = emailTemplateModel.getAll();
+
for (EmailTemplate item : emailTemplates)
if ( item.getType().equals(templateEnum) && item.getLanguage().getLocale().equals(locale) )
return item;
+
return null;
}
- private String replaceKeywords(String text, Worker currentWorker, EmailNotification notification){
- if ( notification.getType().equals(EmailTemplateEnum.TEMPLATE_ENTER_DATA_IN_TIMESHEET) ){
+ private String replaceKeywords(String text, Worker currentWorker, EmailNotification notification) {
+ if ( notification.getType().equals(EmailTemplateEnum.TEMPLATE_ENTER_DATA_IN_TIMESHEET) ) {
// It is because there is no other data for
// EmailNotification of TEMPLATE_ENTER_DATA_IN_TIMESHEET notification type
text = text.replaceAll("\\{resource\\}", notification.getResource().getName());
@@ -172,38 +175,41 @@ public class ComposeMessage {
private void setupConnectionProperties(){
List emailConnectorProperties = emailConnectionValidator.getEmailConnectorProperties();
- for (int i = 0; i < emailConnectorProperties.size(); i++){
- switch (i){
- case 1: {
+ for (int i = 0; i < emailConnectorProperties.size(); i++) {
+ switch (i) {
+ case 1:
protocol = emailConnectorProperties.get(1).getValue();
break;
- }
- case 2: {
+
+ case 2:
host = emailConnectorProperties.get(2).getValue();
break;
- }
- case 3: {
+
+ case 3:
port = emailConnectorProperties.get(3).getValue();
break;
- }
- case 4: {
+
+ case 4:
sender = emailConnectorProperties.get(4).getValue();
break;
- }
- case 5: {
+
+ case 5:
usrnme = emailConnectorProperties.get(5).getValue();
break;
- }
- case 6: {
+
+ case 6:
psswrd = emailConnectorProperties.get(6).getValue();
break;
- }
+
+ default:
+ /* Nothing */
+ break;
}
}
properties = new Properties();
- if ( protocol.equals("STARTTLS") ) {
+ if ( "STARTTLS".equals(protocol) ) {
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.socketFactory.port", port);
@@ -211,27 +217,36 @@ public class ComposeMessage {
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", port);
}
- else if ( protocol.equals("SMTP") ) {
+ else if ( "SMTP".equals(protocol) ) {
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
}
}
- private UserRole getCurrentUserRole(EmailTemplateEnum type){
- switch (type){
- case TEMPLATE_TASK_ASSIGNED_TO_RESOURCE: return UserRole.ROLE_EMAIL_TASK_ASSIGNED_TO_RESOURCE;
+ private UserRole getCurrentUserRole(EmailTemplateEnum type) {
+ switch (type) {
+ case TEMPLATE_TASK_ASSIGNED_TO_RESOURCE:
+ return UserRole.ROLE_EMAIL_TASK_ASSIGNED_TO_RESOURCE;
- case TEMPLATE_RESOURCE_REMOVED_FROM_TASK: return UserRole.ROLE_EMAIL_RESOURCE_REMOVED_FROM_TASK;
+ case TEMPLATE_RESOURCE_REMOVED_FROM_TASK:
+ return UserRole.ROLE_EMAIL_RESOURCE_REMOVED_FROM_TASK;
- case TEMPLATE_MILESTONE_REACHED: return UserRole.ROLE_EMAIL_MILESTONE_REACHED;
+ case TEMPLATE_MILESTONE_REACHED:
+ return UserRole.ROLE_EMAIL_MILESTONE_REACHED;
- case TEMPLATE_TODAY_TASK_SHOULD_START: return UserRole.ROLE_EMAIL_TASK_SHOULD_START;
+ case TEMPLATE_TODAY_TASK_SHOULD_START:
+ return UserRole.ROLE_EMAIL_TASK_SHOULD_START;
- case TEMPLATE_TODAY_TASK_SHOULD_FINISH: return UserRole.ROLE_EMAIL_TASK_SHOULD_FINISH;
+ case TEMPLATE_TODAY_TASK_SHOULD_FINISH:
+ return UserRole.ROLE_EMAIL_TASK_SHOULD_FINISH;
- case TEMPLATE_ENTER_DATA_IN_TIMESHEET: return UserRole.ROLE_EMAIL_TIMESHEET_DATA_MISSING;
+ case TEMPLATE_ENTER_DATA_IN_TIMESHEET:
+ return UserRole.ROLE_EMAIL_TIMESHEET_DATA_MISSING;
+
+ default:
+ /* There is no other template */
+ return null;
}
- return null;
}
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/EmailConnectionValidator.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/EmailConnectionValidator.java
index ad44fac3b..fb377a2dc 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/EmailConnectionValidator.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/EmailConnectionValidator.java
@@ -28,7 +28,6 @@ import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
-import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import java.util.List;
@@ -37,9 +36,7 @@ import java.util.Properties;
/**
* Validate Email Connection properties
*
- * Created by
- * @author Vova Perebykivskiy
- * on 20.01.2016.
+ * @author Created by Vova Perebykivskyi on 20.01.2016.
*/
@Component
@@ -49,7 +46,10 @@ public class EmailConnectionValidator {
@Autowired
private IConnectorDAO connectorDAO;
- public boolean validConnection(){
+ /* Needed for EmailTest */
+ public static Exception exceptionType;
+
+ public boolean validConnection() {
List emailConnectorProperties = getEmailConnectorProperties();
String protocol = null;
@@ -58,28 +58,31 @@ public class EmailConnectionValidator {
String usrnme = null;
String psswrd = null;
- for (int i = 0; i < emailConnectorProperties.size(); i++){
- switch (i){
- case 1: {
+ for (int i = 0; i < emailConnectorProperties.size(); i++) {
+ switch ( i ) {
+ case 1:
protocol = emailConnectorProperties.get(1).getValue();
break;
- }
- case 2: {
+
+ case 2:
host = emailConnectorProperties.get(2).getValue();
break;
- }
- case 3: {
+
+ case 3:
port = emailConnectorProperties.get(3).getValue();
break;
- }
- case 5: {
+
+ case 5:
usrnme = emailConnectorProperties.get(5).getValue();
break;
- }
- case 6: {
+
+ case 6:
psswrd = emailConnectorProperties.get(6).getValue();
break;
- }
+
+ default:
+ /* Nothing */
+ break;
}
}
@@ -89,48 +92,53 @@ public class EmailConnectionValidator {
Transport transport = null;
try {
- if (protocol.equals("SMTP")) {
+ if ( protocol.equals("SMTP") ) {
properties.setProperty("mail.smtp.port", port);
properties.setProperty("mail.smtp.host", host);
+ properties.setProperty("mail.smtp.connectiontimeout", Integer.toString(3000));
Session session = Session.getInstance(properties, null);
transport = session.getTransport("smtp");
- if (usrnme.equals("") && psswrd.equals("")) transport.connect();
- } else if (protocol.equals("STARTTLS")) {
+ if ( "".equals(usrnme) && "".equals(psswrd) )
+ transport.connect();
+
+ } else if ( protocol.equals("STARTTLS") ) {
properties.setProperty("mail.smtps.port", port);
properties.setProperty("mail.smtps.host", host);
+ properties.setProperty("mail.smtp.connectiontimeout", Integer.toString(3000));
Session session = Session.getInstance(properties, null);
transport = session.getTransport("smtps");
- if (!usrnme.equals("") && psswrd != null) transport.connect(host, usrnme, psswrd);
- }
- if (transport != null && transport.isConnected()) return true;
- } catch (NoSuchProviderException e) {
- e.printStackTrace();
- }
- catch (MessagingException e) {
+ if ( !"".equals(usrnme) && psswrd != null )
+ transport.connect(host, usrnme, psswrd);
+ }
+ if ( transport != null && transport.isConnected() )
+ return true;
+
+ } catch (MessagingException e) {
e.printStackTrace();
+ // FIXME must be a better way to send exception type to test class
+ exceptionType = e;
}
return false;
}
public List getEmailConnectorProperties() {
-
Connector connector = connectorDAO.findUniqueByName("E-mail");
return connector.getProperties();
}
- public boolean isConnectionActivated(){
+ public boolean isConnectionActivated() {
List emailConnectorProperties = getEmailConnectorProperties();
- for (ConnectorProperty item : emailConnectorProperties){
+ for (ConnectorProperty item : emailConnectorProperties) {
if ( item.getKey().equals("Activated") )
if ( item.getValue().equals("Y") )
return true;
- else break;
+ else break;
}
return false;
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/IEmailNotificationJob.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/IEmailNotificationJob.java
index 33147a603..9adfdf9fd 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/IEmailNotificationJob.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/IEmailNotificationJob.java
@@ -22,15 +22,15 @@ package org.libreplan.importers.notifications;
import org.libreplan.business.email.entities.EmailNotification;
/**
- * Sends E-mail to users with data that storing in notification_queue table
+ * Sends E-mail to users with data that storing in notification_queue table.
*
- * Created by
- * @author Vova Perebykivskiy
- * on 13.10.2015.
+ * @author Created by Vova Perebykivskyi on 13.10.2015.
*/
public interface IEmailNotificationJob {
+
void sendEmail();
+
boolean composeMessageForUser(EmailNotification notification);
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnResourceRemovedFromTaskJob.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnResourceRemovedFromTaskJob.java
index a49fc199b..cdbb4f688 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnResourceRemovedFromTaskJob.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnResourceRemovedFromTaskJob.java
@@ -27,22 +27,20 @@ import org.springframework.scheduling.quartz.QuartzJobBean;
/**
* Sends E-mail to users with data that storing in notification_queue table
- * and that are treat to {@link EmailTemplateEnum.TEMPLATE_RESOURCE_REMOVED_FROM_TASK}
- *
- * Created by
- * @author Vova Perebykivskiy
- * on 20.01.2016.
+ * and that are treat to
+ * {@link org.libreplan.business.email.entities.EmailTemplateEnum#TEMPLATE_RESOURCE_REMOVED_FROM_TASK}
*
+ * @author Created by Vova Perebykivskiy on 20.01.2016.
*/
public class SendEmailOnResourceRemovedFromTaskJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
- ApplicationContext applicationContext = (ApplicationContext) context.getJobDetail().
- getJobDataMap().get("applicationContext");
+ ApplicationContext applicationContext =
+ (ApplicationContext) context.getJobDetail().getJobDataMap().get("applicationContext");
- IEmailNotificationJob resourceRemovedFromTask = (IEmailNotificationJob) applicationContext
- .getBean("SendEmailOnResourceRemovedFromTask");
+ IEmailNotificationJob resourceRemovedFromTask =
+ (IEmailNotificationJob) applicationContext.getBean("SendEmailOnResourceRemovedFromTask");
resourceRemovedFromTask.sendEmail();
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTaskAssignedToResourceJob.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTaskAssignedToResourceJob.java
index 80fd86c30..ad86ed8ba 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTaskAssignedToResourceJob.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTaskAssignedToResourceJob.java
@@ -28,23 +28,21 @@ import org.springframework.scheduling.quartz.QuartzJobBean;
/**
* Sends E-mail to users with data that storing in notification_queue table
- * and that are treat to {@link EmailTemplateEnum.TEMPLATE_TASK_ASSIGNED_TO_RESOURCE}
- *
- * Created by
- * @author Vova Perebykivskiy
- * on 13.10.2015.
+ * and that are treat to
+ * {@link org.libreplan.business.email.entities.EmailTemplateEnum#TEMPLATE_TASK_ASSIGNED_TO_RESOURCE}
*
+ * @author Created by Vova Perebykivskiy on 13.10.2015.
*/
public class SendEmailOnTaskAssignedToResourceJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
- ApplicationContext applicationContext = (ApplicationContext) context.getJobDetail().
- getJobDataMap().get("applicationContext");
+ ApplicationContext applicationContext =
+ (ApplicationContext) context.getJobDetail().getJobDataMap().get("applicationContext");
- IEmailNotificationJob taskAssignedToResource = (IEmailNotificationJob) applicationContext
- .getBean("SendEmailOnTaskAssignedToResource");
+ IEmailNotificationJob taskAssignedToResource =
+ (IEmailNotificationJob) applicationContext.getBean("SendEmailOnTaskAssignedToResource");
taskAssignedToResource.sendEmail();
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTaskShouldFinishJob.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTaskShouldFinishJob.java
index c6451f222..0411defcf 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTaskShouldFinishJob.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTaskShouldFinishJob.java
@@ -27,22 +27,21 @@ import org.springframework.scheduling.quartz.QuartzJobBean;
/**
* Sends E-mail to users with data that storing in notification_queue table
- * and that are treat to {@link EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_FINISH}
- *
- * Created by
- * @author Vova Perebykivskiy
- * on 20.01.2016.
+ * and that are treat to
+ * {@link org.libreplan.business.email.entities.EmailTemplateEnum#TEMPLATE_TODAY_TASK_SHOULD_FINISH}
*
+ * @author Created by Vova Perebykivskiy on 20.01.2016.
*/
public class SendEmailOnTaskShouldFinishJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
- ApplicationContext applicationContext = (ApplicationContext) context.getJobDetail().
- getJobDataMap().get("applicationContext");
- IEmailNotificationJob taskShouldFinish = (IEmailNotificationJob) applicationContext
- .getBean("SendEmailOnTaskShouldFinish");
+ ApplicationContext applicationContext =
+ (ApplicationContext) context.getJobDetail().getJobDataMap().get("applicationContext");
+
+ IEmailNotificationJob taskShouldFinish =
+ (IEmailNotificationJob) applicationContext.getBean("SendEmailOnTaskShouldFinish");
taskShouldFinish.sendEmail();
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTaskShouldStartJob.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTaskShouldStartJob.java
index 9018af182..bf7ba945e 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTaskShouldStartJob.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTaskShouldStartJob.java
@@ -27,22 +27,22 @@ import org.springframework.scheduling.quartz.QuartzJobBean;
/**
* Sends E-mail to users with data that storing in notification_queue table
- * and that are treat to {@link EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_START}
+ * and that are treat to
+ * {@link org.libreplan.business.email.entities.EmailTemplateEnum#TEMPLATE_TODAY_TASK_SHOULD_START}.
*
- * Created by
- * @author Vova Perebykivskiy
- * on 20.01.2016.
*
+ * @author Created by Vova Perebykivskyi on 20.01.2016
*/
public class SendEmailOnTaskShouldStartJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
- ApplicationContext applicationContext = (ApplicationContext) context.getJobDetail().
- getJobDataMap().get("applicationContext");
- IEmailNotificationJob taskShouldStart = (IEmailNotificationJob) applicationContext
- .getBean("SendEmailOnTaskShouldStart");
+ ApplicationContext applicationContext = (ApplicationContext)
+ context.getJobDetail().getJobDataMap().get("applicationContext");
+
+ IEmailNotificationJob taskShouldStart =
+ (IEmailNotificationJob) applicationContext.getBean("SendEmailOnTaskShouldStart");
taskShouldStart.sendEmail();
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTimesheetDataMissingJob.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTimesheetDataMissingJob.java
index 37f422b87..22ef96bb6 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTimesheetDataMissingJob.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/jobs/SendEmailOnTimesheetDataMissingJob.java
@@ -27,22 +27,20 @@ import org.springframework.scheduling.quartz.QuartzJobBean;
/**
* Sends E-mail to users with data that storing in notification_queue table
- * and that are treat to {@link EmailTemplateEnum.TEMPLATE_ENTER_DATA_IN_TIMESHEET}
- *
- * Created by
- * @author Vova Perebykivskiy
- * on 20.01.2016.
+ * and that are treat to
+ * {@link org.libreplan.business.email.entities.EmailTemplateEnum#TEMPLATE_ENTER_DATA_IN_TIMESHEET}
*
+ * @author Created by Vova Perebykivskiy on 20.01.2016.
*/
public class SendEmailOnTimesheetDataMissingJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
- ApplicationContext applicationContext = (ApplicationContext) context.getJobDetail().
- getJobDataMap().get("applicationContext");
+ ApplicationContext applicationContext =
+ (ApplicationContext) context.getJobDetail().getJobDataMap().get("applicationContext");
- IEmailNotificationJob timesheetMissing = (IEmailNotificationJob) applicationContext
- .getBean("SendEmailOnTimesheetDataMissing");
+ IEmailNotificationJob timesheetMissing =
+ (IEmailNotificationJob) applicationContext.getBean("SendEmailOnTimesheetDataMissing");
timesheetMissing.sendEmail();
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnMilestoneReached.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnMilestoneReached.java
index 18cf17c40..d947311f3 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnMilestoneReached.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnMilestoneReached.java
@@ -39,7 +39,6 @@ import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
-
import java.util.Date;
import java.util.List;
@@ -51,9 +50,7 @@ import java.util.List;
* Date will be send on current date equals to deadline date of {@link Milestone}
* But it will be only send to Manager (you can assign him in project properties)
*
- * Created by
- * @author Vova Perebykivskiy
- * on 20.01.2016.
+ * @author Created by Vova Perebykivskyi on 20.01.2016
*/
@Component
@@ -80,18 +77,16 @@ public class SendEmailOnMilestoneReached implements IEmailNotificationJob {
// Gathering data
checkMilestoneDate();
- if ( Configuration.isEmailSendingEnabled() ){
+ if ( Configuration.isEmailSendingEnabled() ) {
- if ( emailConnectionValidator.isConnectionActivated() )
+ if ( emailConnectionValidator.isConnectionActivated() && emailConnectionValidator.validConnection() ) {
- if ( emailConnectionValidator.validConnection() ){
+ List notifications =
+ emailNotificationModel.getAllByType(EmailTemplateEnum.TEMPLATE_MILESTONE_REACHED);
- List notifications = emailNotificationModel
- .getAllByType(EmailTemplateEnum.TEMPLATE_MILESTONE_REACHED);
-
- for (int i = 0; i < notifications.size(); i++)
- if ( composeMessageForUser(notifications.get(i)) )
- deleteSingleNotification(notifications.get(i));
+ for (EmailNotification notification : notifications)
+ if ( composeMessageForUser(notification) )
+ deleteSingleNotification(notification);
}
}
}
@@ -144,9 +139,7 @@ public class SendEmailOnMilestoneReached implements IEmailNotificationJob {
int deadlineMonth = deadline.getMonthOfYear();
int deadlineDay = deadline.getDayOfMonth();
- if (currentYear == deadlineYear &&
- currentMonth == deadlineMonth &&
- currentDay == deadlineDay)
+ if ( currentYear == deadlineYear && currentMonth == deadlineMonth && currentDay == deadlineDay )
sendEmailNotificationToManager(item);
}
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnResourceRemovedFromTask.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnResourceRemovedFromTask.java
index 5a6add39b..b0cb0ef2a 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnResourceRemovedFromTask.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnResourceRemovedFromTask.java
@@ -36,12 +36,10 @@ import java.util.List;
/**
* Sends E-mail to users with data that storing in notification_queue table
- * and that are treat to TEMPLATE_RESOUCE_REMOVED_FROM_TASK
+ * and that are treat to {@link EmailTemplateEnum#TEMPLATE_RESOURCE_REMOVED_FROM_TASK}
* Data will be send if resource has been removed from task (in resource allocation)
*
- * Created by
- * @author Vova Perebykivskiy
- * on 20.01.2016.
+ * @author Created by Vova Perebykivskiy on 20.01.2016.
*/
@Component
@@ -61,14 +59,11 @@ public class SendEmailOnResourceRemovedFromTask implements IEmailNotificationJob
public void sendEmail() {
// At this time all data have gathered, if it exists of course
- if ( Configuration.isEmailSendingEnabled() ){
+ if ( Configuration.isEmailSendingEnabled() ) {
+ if ( emailConnectionValidator.isConnectionActivated() && emailConnectionValidator.validConnection() ) {
- if ( emailConnectionValidator.isConnectionActivated() )
-
- if ( emailConnectionValidator.validConnection() ){
-
- List notifications = emailNotificationModel
- .getAllByType(EmailTemplateEnum.TEMPLATE_RESOURCE_REMOVED_FROM_TASK);
+ List notifications =
+ emailNotificationModel.getAllByType(EmailTemplateEnum.TEMPLATE_RESOURCE_REMOVED_FROM_TASK);
for (int i = 0; i < notifications.size(); i++)
if ( composeMessageForUser(notifications.get(i)) )
diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskAssignedToResource.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskAssignedToResource.java
index 926e55ad3..e175969de 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskAssignedToResource.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskAssignedToResource.java
@@ -38,12 +38,10 @@ import java.util.List;
/**
* Sends E-mail to users with data that storing in notification_queue table
- * and that are treat to {@link EmailTemplateEnum.TEMPLATE_ENTER_DATA_IN_TIMESHEET}
+ * and that are treat to {@link EmailTemplateEnum#TEMPLATE_ENTER_DATA_IN_TIMESHEET}
* Data will be send after user will be assigned to some task.
*
- * Created by
- * @author Vova Perebykivskiy
- * on 13.10.2015.
+ * @author Created by Vova Perebykivskyi on 13.10.2015.
*/
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@@ -61,18 +59,16 @@ public class SendEmailOnTaskAssignedToResource implements IEmailNotificationJob
@Override
@Transactional
public void sendEmail() {
- if ( Configuration.isEmailSendingEnabled() ){
+ if ( Configuration.isEmailSendingEnabled() ) {
- if ( emailConnectionValidator.isConnectionActivated() )
+ if ( emailConnectionValidator.isConnectionActivated() && emailConnectionValidator.validConnection() ) {
- if ( emailConnectionValidator.validConnection() ){
+ List notifications =
+ emailNotificationModel.getAllByType(EmailTemplateEnum.TEMPLATE_TASK_ASSIGNED_TO_RESOURCE);
- List notifications = emailNotificationModel
- .getAllByType(EmailTemplateEnum.TEMPLATE_TASK_ASSIGNED_TO_RESOURCE);
-
- for (int i = 0; i < notifications.size(); i++)
- if ( composeMessageForUser(notifications.get(i)) )
- deleteSingleNotification(notifications.get(i));
+ for (EmailNotification notification : notifications)
+ if ( composeMessageForUser(notification) )
+ deleteSingleNotification(notification);
}
}
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldFinish.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldFinish.java
index cbed116e4..2bbf39f1a 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldFinish.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldFinish.java
@@ -44,12 +44,10 @@ import java.util.List;
/**
* Sends E-mail to users with data that storing in notification_queue table
- * and that are treat to {@link EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_FINISH}
+ * and that are treat to {@link EmailTemplateEnum#TEMPLATE_TODAY_TASK_SHOULD_FINISH}
* Data will be send when current day equals to finish date.
*
- * Created by
- * @author Vova Perebykivskiy
- * on 21.01.2016.
+ * @author Created by Vova Perebykivskiy on 21.01.2016.
*/
@Component
@@ -73,14 +71,11 @@ public class SendEmailOnTaskShouldFinish implements IEmailNotificationJob {
// Gather data for email sending
taskShouldFinish();
- if ( Configuration.isEmailSendingEnabled() ){
+ if ( Configuration.isEmailSendingEnabled() ) {
+ if ( emailConnectionValidator.isConnectionActivated() && emailConnectionValidator.validConnection() ) {
- if ( emailConnectionValidator.isConnectionActivated() )
-
- if ( emailConnectionValidator.validConnection() ){
-
- List notifications = emailNotificationModel
- .getAllByType(EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_FINISH);
+ List notifications =
+ emailNotificationModel.getAllByType(EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_FINISH);
for (int i = 0; i < notifications.size(); i++)
if ( composeMessageForUser(notifications.get(i)) )
@@ -100,6 +95,7 @@ public class SendEmailOnTaskShouldFinish implements IEmailNotificationJob {
@Transactional
public void taskShouldFinish() {
+ // TODO resolve deprecated
// Check if current date equals with item date
Date date = new Date();
int currentYear = date.getYear();
@@ -115,7 +111,7 @@ public class SendEmailOnTaskShouldFinish implements IEmailNotificationJob {
if ( currentYear == endYear &&
currentMonth == endMonth &&
- currentDay == endDay ){
+ currentDay == endDay ) {
// Get all resources for current task and send them email notification
sendEmailNotificationAboutTaskShouldFinish(item);
}
@@ -124,10 +120,10 @@ public class SendEmailOnTaskShouldFinish implements IEmailNotificationJob {
private void sendEmailNotificationAboutTaskShouldFinish(TaskElement item){
- List> list = new ArrayList>();
+ List> list = new ArrayList<>();
list.addAll(item.getAllResourceAllocations());
- List resources = new ArrayList();
+ List resources = new ArrayList<>();
for (ResourceAllocation> allocation : list)
resources.add(allocation.getAssociatedResources().get(0));
diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldStart.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldStart.java
index f4e9e4108..f9cab64fd 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldStart.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldStart.java
@@ -44,12 +44,10 @@ import java.util.List;
/**
* Sends E-mail users with data that storing in notification_queue table
- * and that are treat to {@link EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_START}
+ * and that are treat to {@link EmailTemplateEnum#TEMPLATE_TODAY_TASK_SHOULD_START}
* Data will be send if current data equals to start date.
*
- * Created by
- * @author Vova Perebykivskiy
- * on 20.01.2016.
+ * @author Created by Vova Perebykivskyi on 20.01.2016.
*/
@Component
@@ -73,18 +71,16 @@ public class SendEmailOnTaskShouldStart implements IEmailNotificationJob {
// Gather data
taskShouldStart();
- if ( Configuration.isEmailSendingEnabled() ){
+ if ( Configuration.isEmailSendingEnabled() ) {
- if ( emailConnectionValidator.isConnectionActivated() )
+ if ( emailConnectionValidator.isConnectionActivated() && emailConnectionValidator.validConnection() ) {
- if ( emailConnectionValidator.validConnection() ){
+ List notifications =
+ emailNotificationModel.getAllByType(EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_START);
- List notifications = emailNotificationModel
- .getAllByType(EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_START);
-
- for (int i = 0; i < notifications.size(); i++)
- if ( composeMessageForUser(notifications.get(i)) )
- deleteSingleNotification(notifications.get(i));
+ for (EmailNotification notification : notifications)
+ if ( composeMessageForUser(notification) )
+ deleteSingleNotification(notification);
}
}
}
@@ -102,35 +98,34 @@ public class SendEmailOnTaskShouldStart implements IEmailNotificationJob {
public void taskShouldStart() {
// Check if current date equals with item date
Date date = new Date();
+ // TODO resolve deprecated
int currentYear = date.getYear();
int currentMonth = date.getMonth();
int currentDay = date.getDay();
List tasks = taskElementDAO.getTaskElementsWithParentsWithoutMilestones();
- for (TaskElement item : tasks){
+ for (TaskElement item : tasks) {
Date startDate = item.getStartDate();
int startYear = startDate.getYear();
int startMonth = startDate.getMonth();
int startDay = startDate.getDay();
- if ( currentYear == startYear &&
- currentMonth == startMonth &&
- currentDay == startDay){
+ if ( currentYear == startYear && currentMonth == startMonth && currentDay == startDay ) {
// Get all resources for current task and send them email notification
sendEmailNotificationAboutTaskShouldStart(item);
}
}
}
- private void sendEmailNotificationAboutTaskShouldStart(TaskElement item){
- List> list = new ArrayList>();
+ private void sendEmailNotificationAboutTaskShouldStart(TaskElement item) {
+ List> list = new ArrayList<>();
list.addAll(item.getAllResourceAllocations());
- List resources = new ArrayList();
+ List resources = new ArrayList<>();
for (ResourceAllocation> allocation : list)
resources.add(allocation.getAssociatedResources().get(0));
- for (Resource resourceItem : resources){
+ for (Resource resourceItem : resources) {
emailNotificationModel.setNewObject();
emailNotificationModel.setType(EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_START);
emailNotificationModel.setUpdated(new Date());
diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTimesheetDataMissing.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTimesheetDataMissing.java
index effc4c6a4..ca5093915 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTimesheetDataMissing.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTimesheetDataMissing.java
@@ -60,12 +60,10 @@ import java.util.List;
/**
* Sends E-mail to users with data that storing in notification_queue table
- * and that are treat to {@link EmailTemplateEnum.TEMPLATE_ENTER_DATA_IN_TIMESHEET}
+ * and that are treat to {@link EmailTemplateEnum#TEMPLATE_ENTER_DATA_IN_TIMESHEET}
* Data will be send for bound users with empty timesheet lines.
*
- * Created by
- * @author Vova Perebykivskiy
- * on 20.01.2016.
+ * @author Created by Vova Perebykivskiy on 20.01.2016.
*/
@Component
@@ -95,14 +93,11 @@ public class SendEmailOnTimesheetDataMissing implements IEmailNotificationJob {
public void sendEmail() {
checkTimesheet();
- if ( Configuration.isEmailSendingEnabled() ){
+ if ( Configuration.isEmailSendingEnabled() ) {
+ if ( emailConnectionValidator.isConnectionActivated() && emailConnectionValidator.validConnection() ) {
- if ( emailConnectionValidator.isConnectionActivated() )
-
- if ( emailConnectionValidator.validConnection() ){
-
- List notifications = emailNotificationModel
- .getAllByType(EmailTemplateEnum.TEMPLATE_ENTER_DATA_IN_TIMESHEET);
+ List notifications =
+ emailNotificationModel.getAllByType(EmailTemplateEnum.TEMPLATE_ENTER_DATA_IN_TIMESHEET);
for (int i = 0; i < notifications.size(); i++)
if ( composeMessageForUser(notifications.get(i)) )
@@ -128,8 +123,8 @@ public class SendEmailOnTimesheetDataMissing implements IEmailNotificationJob {
@Transactional
private List getPersonalTimesheets() {
- List personalTimesheetDTO = new ArrayList();
- List usersWithoutTimesheets = new ArrayList();
+ List personalTimesheetDTO = new ArrayList<>();
+ List usersWithoutTimesheets = new ArrayList<>();
List users = userModel.getUsers();
for (User user : users)
@@ -139,11 +134,15 @@ public class SendEmailOnTimesheetDataMissing implements IEmailNotificationJob {
LocalDate activationDate = getActivationDate(user.getWorker());
LocalDate currentDate = new LocalDate();
- personalTimesheetDTO.addAll(getPersonalTimesheets(user.getWorker(), activationDate,
- currentDate.plusMonths(1), getPersonalTimesheetsPeriodicity()));
+ personalTimesheetDTO.addAll(getPersonalTimesheets(
+ user.getWorker(),
+ activationDate,
+ currentDate.plusMonths(1),
+ getPersonalTimesheetsPeriodicity()));
- for(PersonalTimesheetDTO item : personalTimesheetDTO){
+ for(PersonalTimesheetDTO item : personalTimesheetDTO) {
WorkReport workReport = item.getWorkReport();
+
if ( item.getTasksNumber() == 0 && workReport == null )
if ( !usersWithoutTimesheets.contains(user) )
usersWithoutTimesheets.add(user);
@@ -173,10 +172,9 @@ public class SendEmailOnTimesheetDataMissing implements IEmailNotificationJob {
end = periodicity.getEnd(end);
int items = periodicity.getItemsBetween(start, end);
- List result = new ArrayList();
+ List result = new ArrayList<>();
- // In decreasing order to provide a list sorted with the more recent
- // personal timesheets at the beginning
+ // In decreasing order to provide a list sorted with the more recent personal timesheets at the beginning
for (int i = items; i >= 0; i--) {
LocalDate date = periodicity.getDateForItemFromDate(i, start);
@@ -189,28 +187,31 @@ public class SendEmailOnTimesheetDataMissing implements IEmailNotificationJob {
tasksNumber = getNumberOfOrderElementsWithTrackedTime(workReport);
}
- result.add(new PersonalTimesheetDTO(date, workReport,
- getResourceCapcity(resource, date, periodicity), hours,
+ result.add(new PersonalTimesheetDTO(
+ date,
+ workReport,
+ getResourceCapcity(resource, date, periodicity),
+ hours,
tasksNumber));
}
return result;
}
private LocalDate getActivationDate(Worker worker) {
- return worker.getCalendar().getFistCalendarAvailability()
- .getStartDate();
+ return worker.getCalendar().getFistCalendarAvailability().getStartDate();
}
private PersonalTimesheetsPeriodicityEnum getPersonalTimesheetsPeriodicity() {
- return configurationDAO.getConfiguration()
- .getPersonalTimesheetsPeriodicity();
+ return configurationDAO.getConfiguration().getPersonalTimesheetsPeriodicity();
}
private WorkReport getWorkReport(Resource resource, LocalDate date,
PersonalTimesheetsPeriodicityEnum periodicity) {
+
WorkReport workReport = workReportDAO.getPersonalTimesheetWorkReport(
resource, date, periodicity);
forceLoad(workReport);
+
return workReport;
}
private void forceLoad(WorkReport workReport) {
@@ -226,7 +227,7 @@ public class SendEmailOnTimesheetDataMissing implements IEmailNotificationJob {
return 0;
}
- List orderElements = new ArrayList();
+ List orderElements = new ArrayList<>();
for (WorkReportLine line : workReport.getWorkReportLines()) {
if (!line.getEffort().isZero()) {
OrderElement orderElement = line.getOrderElement();
@@ -239,14 +240,13 @@ public class SendEmailOnTimesheetDataMissing implements IEmailNotificationJob {
}
private EffortDuration getResourceCapcity(Resource resource, LocalDate date,
PersonalTimesheetsPeriodicityEnum periodicity) {
+
LocalDate start = periodicity.getStart(date);
LocalDate end = periodicity.getEnd(date);
EffortDuration capacity = EffortDuration.zero();
- for (LocalDate day = start; day.compareTo(end) <= 0; day = day
- .plusDays(1)) {
- capacity = capacity.plus(resource.getCalendar().getCapacityOn(
- IntraDayDate.PartialDay.wholeDay(day)));
+ for (LocalDate day = start; day.compareTo(end) <= 0; day = day.plusDays(1)) {
+ capacity = capacity.plus(resource.getCalendar().getCapacityOn(IntraDayDate.PartialDay.wholeDay(day)));
}
return capacity;
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/common/ConfigurationController.java b/libreplan-webapp/src/main/java/org/libreplan/web/common/ConfigurationController.java
index c29bf5478..db70b20ec 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/web/common/ConfigurationController.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/web/common/ConfigurationController.java
@@ -89,7 +89,6 @@ import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.SelectEvent;
import org.zkoss.zk.ui.util.GenericForwardComposer;
-
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Grid;
@@ -119,7 +118,7 @@ import org.zkoss.zul.impl.InputElement;
* @author Susana Montes Pedreira
* @author Cristina Alavarino Perez
* @author Ignacio Diaz Teijido
- * @author Vova Perebykivskiy
+ * @author Vova Perebykivskyi
*/
public class ConfigurationController extends GenericForwardComposer {
@@ -157,7 +156,7 @@ public class ConfigurationController extends GenericForwardComposer {
private IMaterialsModel materialsModel;
@Autowired
- private IAssignedTaskQualityFormsToOrderElementModel assignedQualityFormsModel;
+ private IAssignedTaskQualityFormsToOrderElementModel assignedTaskQualityFormsToOrderElementModel;
private IMessagesForUser messages;
@@ -194,19 +193,17 @@ public class ConfigurationController extends GenericForwardComposer {
@Override
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
+
+ // TODO resolve deprecated
comp.setVariable("configurationController", this, true);
+
configurationModel.init();
- defaultCalendarBandboxSearch.setListboxEventListener(Events.ON_SELECT,
- new EventListener() {
- @Override
- public void onEvent(Event event) {
- Listitem selectedItem = (Listitem) ((SelectEvent) event)
- .getSelectedItems().iterator().next();
- setDefaultCalendar((BaseCalendar) selectedItem
- .getValue());
- }
- });
+ defaultCalendarBandboxSearch.setListboxEventListener(Events.ON_SELECT, event -> {
+ Listitem selectedItem = (Listitem) ((SelectEvent) event).getSelectedItems().iterator().next();
+ setDefaultCalendar((BaseCalendar) selectedItem.getValue());
+ });
+
initializeProgressTypeList();
messages = new MessagesForUser(messagesContainer);
reloadEntitySequences();
@@ -214,13 +211,12 @@ public class ConfigurationController extends GenericForwardComposer {
}
public void changeRoleStrategy() {
- this.getLdapConfiguration().setLdapGroupStrategy(
- strategy.getSelectedItem().getValue().equals("group"));
+ this.getLdapConfiguration().setLdapGroupStrategy(strategy.getSelectedItem().getValue().equals("group"));
loadRoleStrategyRows();
}
private void loadRoleStrategyRows() {
- if (getLdapConfiguration().getLdapGroupStrategy()) {
+ if ( getLdapConfiguration().getLdapGroupStrategy() ) {
strategy.setSelectedIndex(0);
ldapGroupPath.setDisabled(false);
} else {
@@ -235,15 +231,15 @@ public class ConfigurationController extends GenericForwardComposer {
@Override
public void onEvent(Event event) {
Listitem selectedItem = getSelectedItem((SelectEvent) event);
- if (selectedItem != null) {
- ProgressType progressType = (ProgressType) selectedItem
- .getValue();
+ if ( selectedItem != null ) {
+ ProgressType progressType = (ProgressType) selectedItem.getValue();
configurationModel.setProgressType(progressType);
}
}
private Listitem getSelectedItem(SelectEvent event) {
final Set selectedItems = event.getSelectedItems();
+
return selectedItems.iterator().next();
}
@@ -276,26 +272,34 @@ public class ConfigurationController extends GenericForwardComposer {
public void save() throws InterruptedException {
- if (getSelectedConnector() != null && getSelectedConnector().getName().equals("E-mail") &&
- isEmailFieldsValid() == false) {
+ boolean connectorIsEmailAndFieldsAreInvalid = getSelectedConnector() != null &&
+ getSelectedConnector().getName().equals("E-mail") &&
+ !areEmailFieldsValid();
+
+ if ( connectorIsEmailAndFieldsAreInvalid ) {
+ messages.clearMessages();
messages.showMessage(Level.ERROR, _("Check all fields"));
} else {
ConstraintChecker.isValid(configurationWindow);
- if (checkValidEntitySequenceRows()) {
+ if ( checkValidEntitySequenceRows() ) {
try {
configurationModel.confirm();
configurationModel.init();
messages.showMessage(Level.INFO, _("Changes saved"));
+ boolean gatheredDataNotSentAndItIsNotRestricted = !SecurityUtils.isGatheredStatsAlreadySent &&
+ configurationDAO
+ .getConfigurationWithReadOnlyTransaction()
+ .isAllowToGatherUsageStatsEnabled();
+
// Send data to server
- if ( !SecurityUtils.isGatheredStatsAlreadySent &&
- configurationDAO.getConfigurationWithReadOnlyTransaction().isAllowToGatherUsageStatsEnabled() )
+ if ( gatheredDataNotSentAndItIsNotRestricted )
sendDataToServer();
- if (getSelectedConnector() != null
- && !configurationModel
- .scheduleOrUnscheduleJobs(getSelectedConnector())) {
+ if ( getSelectedConnector() != null &&
+ !configurationModel.scheduleOrUnscheduleJobs(getSelectedConnector()) ) {
+
messages.showMessage(
Level.ERROR,
_("Scheduling or unscheduling of jobs for this connector is not completed"));
@@ -316,11 +320,18 @@ public class ConfigurationController extends GenericForwardComposer {
}
}
- private void sendDataToServer(){
+ private void sendDataToServer() {
GatheredUsageStats gatheredUsageStats = new GatheredUsageStats();
- gatheredUsageStats.setupNotAutowiredClasses(userDAO, orderModel, workReportModel, workerModel, machineModel,
- expenseSheetModel, materialsModel, assignedQualityFormsModel);
+ gatheredUsageStats.setupNotAutowiredClasses(
+ userDAO,
+ orderModel,
+ workReportModel,
+ workerModel,
+ machineModel,
+ expenseSheetModel,
+ materialsModel,
+ assignedTaskQualityFormsToOrderElementModel);
gatheredUsageStats.sendGatheredUsageStatsToServer();
SecurityUtils.isGatheredStatsAlreadySent = true;
@@ -337,13 +348,13 @@ public class ConfigurationController extends GenericForwardComposer {
public void testLDAPConnection() {
LdapContextSource source = new LdapContextSource();
+
source.setUrl(configurationModel.getLdapConfiguration().getLdapHost()
+ ":" + configurationModel.getLdapConfiguration().getLdapPort());
+
source.setBase(configurationModel.getLdapConfiguration().getLdapBase());
- source.setUserDn(configurationModel.getLdapConfiguration()
- .getLdapUserDn());
- source.setPassword(configurationModel.getLdapConfiguration()
- .getLdapPassword());
+ source.setUserDn(configurationModel.getLdapConfiguration().getLdapUserDn());
+ source.setPassword(configurationModel.getLdapConfiguration().getLdapPassword());
source.setDirObjectFactory(DefaultDirObjectFactory.class);
source.setPooled(false);
try {
@@ -354,15 +365,16 @@ public class ConfigurationController extends GenericForwardComposer {
LdapTemplate template = new LdapTemplate(source);
try {
- template.authenticate(DistinguishedName.EMPTY_PATH,
- new EqualsFilter(configurationModel.getLdapConfiguration()
- .getLdapUserId(), "test").toString(), "test");
- messages.showMessage(Level.INFO,
- _("LDAP connection was successful"));
+ // TODO resolve deprecated
+ template.authenticate(
+ DistinguishedName.EMPTY_PATH,
+ new EqualsFilter(configurationModel.getLdapConfiguration().getLdapUserId(), "test").toString(),
+ "test");
+
+ messages.showMessage(Level.INFO, _("LDAP connection was successful"));
} catch (Exception e) {
LOG.info(e);
- messages.showMessage(Level.ERROR,
- _("Cannot connect to LDAP server"));
+ messages.showMessage(Level.ERROR, _("Cannot connect to LDAP server"));
}
}
@@ -370,27 +382,21 @@ public class ConfigurationController extends GenericForwardComposer {
* Tests connection
*/
public void testConnection() {
- if (selectedConnector == null) {
- messages.showMessage(Level.ERROR,
- _("Please select a connector to test it"));
+ if ( selectedConnector == null ) {
+ messages.showMessage(Level.ERROR, _("Please select a connector to test it"));
return;
}
Map properties = selectedConnector.getPropertiesAsMap();
String url = properties.get(PredefinedConnectorProperties.SERVER_URL);
- String username = properties
- .get(PredefinedConnectorProperties.USERNAME);
- String password = properties
- .get(PredefinedConnectorProperties.PASSWORD);
+ String username = properties.get(PredefinedConnectorProperties.USERNAME);
+ String password = properties.get(PredefinedConnectorProperties.PASSWORD);
- if ( selectedConnector.getName().equals(
- PredefinedConnectors.TIM.getName()) ) {
+ if ( selectedConnector.getName().equals(PredefinedConnectors.TIM.getName()) ) {
testTimConnection(url, username, password);
- } else if ( selectedConnector.getName().equals(
- PredefinedConnectors.JIRA.getName()) ) {
+ } else if ( selectedConnector.getName().equals(PredefinedConnectors.JIRA.getName()) ) {
testJiraConnection(url, username, password);
- } else if( selectedConnector.getName().equals(
- PredefinedConnectors.EMAIL.getName()) ){
+ } else if( selectedConnector.getName().equals(PredefinedConnectors.EMAIL.getName()) ) {
String host = properties.get(PredefinedConnectorProperties.HOST);
username = properties.get(PredefinedConnectorProperties.EMAIL_USERNAME);
password = properties.get(PredefinedConnectorProperties.EMAIL_PASSWORD);
@@ -412,7 +418,7 @@ public class ConfigurationController extends GenericForwardComposer {
* the password
*/
private void testTimConnection(String url, String username, String password) {
- if (TimSoapClient.checkAuthorization(url, username, password)) {
+ if ( TimSoapClient.checkAuthorization(url, username, password) ) {
messages.showMessage(Level.INFO, _("Tim connection was successful"));
} else {
messages.showMessage(Level.ERROR, _("Cannot connet to Tim server"));
@@ -434,27 +440,22 @@ public class ConfigurationController extends GenericForwardComposer {
try {
WebClient client = WebClient.create(url);
- client.path(JiraRESTClient.PATH_AUTH_SESSION).accept(
- MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML);
+ client.path(JiraRESTClient.PATH_AUTH_SESSION).accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML);
- org.libreplan.ws.common.impl.Util.addAuthorizationHeader(client,
- username, password);
+ org.libreplan.ws.common.impl.Util.addAuthorizationHeader(client, username, password);
Response response = client.get();
- if (response.getStatus() == Status.OK.getStatusCode()) {
- messages.showMessage(Level.INFO,
- _("JIRA connection was successful"));
+ if ( response.getStatus() == Status.OK.getStatusCode() ) {
+ messages.showMessage(Level.INFO, _("JIRA connection was successful"));
} else {
LOG.error("Status code: " + response.getStatus());
- messages.showMessage(Level.ERROR,
- _("Cannot connect to JIRA server"));
+ messages.showMessage(Level.ERROR, _("Cannot connect to JIRA server"));
}
} catch (Exception e) {
LOG.error(e);
- messages.showMessage(Level.ERROR,
- _("Cannot connect to JIRA server"));
+ messages.showMessage(Level.ERROR, _("Cannot connect to JIRA server"));
}
}
@@ -470,18 +471,19 @@ public class ConfigurationController extends GenericForwardComposer {
* @param password
* the password
*/
- private void testEmailConnection(String host, String port, String username, String password){
- Properties props = System.getProperties();
+ private void testEmailConnection(String host, String port, String username, String password) {
+ Properties props = new Properties();
Transport transport = null;
try {
- if ( protocolsCombobox.getSelectedItem().getLabel().equals("SMTP") ){
+ if ( protocolsCombobox.getSelectedItem().getLabel().equals("SMTP") ) {
props.setProperty("mail.smtp.port", port);
props.setProperty("mail.smtp.host", host);
Session session = Session.getInstance(props, null);
transport = session.getTransport("smtp");
- if ( username.equals("") && password.equals("")) transport.connect();
+ if ( username.equals("") && password.equals(""))
+ transport.connect();
}
else if ( protocolsCombobox.getSelectedItem().getLabel().equals("STARTTLS") ) {
props.setProperty("mail.smtps.port", port);
@@ -489,23 +491,29 @@ public class ConfigurationController extends GenericForwardComposer {
Session session = Session.getInstance(props, null);
transport = session.getTransport("smtps");
- if ( !username.equals("") && password != null ) transport.connect(host, username, password);
+ if ( !username.equals("") && password != null )
+ transport.connect(host, username, password);
}
messages.clearMessages();
- if ( transport.isConnected() ) messages.showMessage(Level.INFO, _("Connection successful!"));
- else if ( transport.isConnected() == false ) messages.showMessage(Level.WARNING, _("Connection unsuccessful"));
+ if ( transport.isConnected() )
+ messages.showMessage(Level.INFO, _("Connection successful!"));
+ else if ( !transport.isConnected() )
+ messages.showMessage(Level.WARNING, _("Connection unsuccessful"));
}
catch (AuthenticationFailedException e){
LOG.error(e);
+ messages.clearMessages();
messages.showMessage(Level.ERROR, _("Invalid credentials"));
}
catch (MessagingException e){
LOG.error(e);
+ messages.clearMessages();
messages.showMessage(Level.ERROR, _("Cannot connect"));
}
catch (Exception e){
LOG.error(e);
+ messages.clearMessages();
messages.showMessage(Level.ERROR, _("Failed to connect"));
}
}
@@ -514,31 +522,30 @@ public class ConfigurationController extends GenericForwardComposer {
Rows rows = entitySequencesGrid.getRows();
for (Row row : (List) rows.getChildren()) {
- EntitySequence seq = (EntitySequence) row.getValue();
- if (seq != null) {
+ EntitySequence seq = (EntitySequence) row.getValue();
+ if ( seq != null ) {
Textbox prefixBox = (Textbox) row.getChildren().get(2);
- if (!seq.isAlreadyInUse()) {
- String errorMessage = this.validPrefix(seq,
- prefixBox.getValue());
- if (errorMessage != null) {
- throw new WrongValueException(prefixBox,
- errorMessage);
- }
- }
-
- Intbox digitsBox = (Intbox) row.getChildren().get(3);
- try {
- if (!seq.isAlreadyInUse()) {
- seq.setNumberOfDigits(digitsBox.getValue());
- }
- } catch (IllegalArgumentException e) {
- throw new WrongValueException(digitsBox, _(
- "number of digits must be between {0} and {1}",
- EntitySequence.MIN_NUMBER_OF_DIGITS,
- EntitySequence.MAX_NUMBER_OF_DIGITS));
+ if ( !seq.isAlreadyInUse() ) {
+ String errorMessage = this.validPrefix(seq, prefixBox.getValue());
+ if ( errorMessage != null ) {
+ throw new WrongValueException(prefixBox, errorMessage);
}
}
+ Intbox digitsBox = (Intbox) row.getChildren().get(3);
+ try {
+ if ( !seq.isAlreadyInUse() ) {
+ seq.setNumberOfDigits(digitsBox.getValue());
+ }
+ } catch (IllegalArgumentException e) {
+ throw new WrongValueException(
+ digitsBox,
+ _("number of digits must be between {0} and {1}",
+ EntitySequence.MIN_NUMBER_OF_DIGITS,
+ EntitySequence.MAX_NUMBER_OF_DIGITS));
+ }
+ }
+
}
return true;
}
@@ -548,15 +555,14 @@ public class ConfigurationController extends GenericForwardComposer {
}
private void reloadEntitySequences() {
- entitySequencesGrid.setModel(new SimpleListModel(
- getAllEntitySequences().toArray()));
+ entitySequencesGrid.setModel(new SimpleListModel(getAllEntitySequences().toArray()));
entitySequencesGrid.invalidate();
}
private void reloadConnectors() {
- selectedConnector = configurationModel
- .getConnectorByName(selectedConnector != null ? selectedConnector
- .getName() : null);
+ selectedConnector =
+ configurationModel.getConnectorByName(selectedConnector != null ? selectedConnector.getName() : null);
+
Util.reloadBindings(connectorCombo);
Util.reloadBindings(connectorPropertriesGrid);
}
@@ -582,38 +588,31 @@ public class ConfigurationController extends GenericForwardComposer {
}
public void setGenerateCodeForCriterion(Boolean generateCodeForCriterion) {
- configurationModel
- .setGenerateCodeForCriterion(generateCodeForCriterion);
+ configurationModel.setGenerateCodeForCriterion(generateCodeForCriterion);
}
public Boolean getGenerateCodeForWorkReportType() {
return configurationModel.getGenerateCodeForWorkReportType();
}
- public void setGenerateCodeForWorkReportType(
- Boolean generateCodeForWorkReportType) {
- configurationModel
- .setGenerateCodeForWorkReportType(generateCodeForWorkReportType);
+ public void setGenerateCodeForWorkReportType(Boolean generateCodeForWorkReportType) {
+ configurationModel.setGenerateCodeForWorkReportType(generateCodeForWorkReportType);
}
public Boolean getGenerateCodeForCalendarExceptionType() {
return configurationModel.getGenerateCodeForCalendarExceptionType();
}
- public void setGenerateCodeForCalendarExceptionType(
- Boolean generateCodeForCalendarExceptionType) {
- configurationModel
- .setGenerateCodeForCalendarExceptionType(generateCodeForCalendarExceptionType);
+ public void setGenerateCodeForCalendarExceptionType(Boolean generateCodeForCalendarExceptionType) {
+ configurationModel.setGenerateCodeForCalendarExceptionType(generateCodeForCalendarExceptionType);
}
public Boolean getGenerateCodeForCostCategory() {
return configurationModel.getGenerateCodeForCostCategory();
}
- public void setGenerateCodeForCostCategory(
- Boolean generateCodeForCostCategory) {
- configurationModel
- .setGenerateCodeForCostCategory(generateCodeForCostCategory);
+ public void setGenerateCodeForCostCategory(Boolean generateCodeForCostCategory) {
+ configurationModel.setGenerateCodeForCostCategory(generateCodeForCostCategory);
}
public Boolean getGenerateCodeForLabel() {
@@ -629,8 +628,7 @@ public class ConfigurationController extends GenericForwardComposer {
}
public void setGenerateCodeForWorkReport(Boolean generateCodeForWorkReport) {
- configurationModel
- .setGenerateCodeForWorkReport(generateCodeForWorkReport);
+ configurationModel.setGenerateCodeForWorkReport(generateCodeForWorkReport);
}
public Boolean getGenerateCodeForResources() {
@@ -638,28 +636,23 @@ public class ConfigurationController extends GenericForwardComposer {
}
public void setGenerateCodeForResources(Boolean generateCodeForResources) {
- configurationModel
- .setGenerateCodeForResources(generateCodeForResources);
+ configurationModel.setGenerateCodeForResources(generateCodeForResources);
}
public Boolean getGenerateCodeForTypesOfWorkHours() {
return configurationModel.getGenerateCodeForTypesOfWorkHours();
}
- public void setGenerateCodeForTypesOfWorkHours(
- Boolean generateCodeForTypesOfWorkHours) {
- configurationModel
- .setGenerateCodeForTypesOfWorkHours(generateCodeForTypesOfWorkHours);
+ public void setGenerateCodeForTypesOfWorkHours(Boolean generateCodeForTypesOfWorkHours) {
+ configurationModel.setGenerateCodeForTypesOfWorkHours(generateCodeForTypesOfWorkHours);
}
public Boolean getGenerateCodeForMaterialCategories() {
return configurationModel.getGenerateCodeForMaterialCategories();
}
- public void setGenerateCodeForMaterialCategories(
- Boolean generateCodeForMaterialCategories) {
- configurationModel
- .setGenerateCodeForMaterialCategories(generateCodeForMaterialCategories);
+ public void setGenerateCodeForMaterialCategories(Boolean generateCodeForMaterialCategories) {
+ configurationModel.setGenerateCodeForMaterialCategories(generateCodeForMaterialCategories);
}
public Boolean getGenerateCodeForExpenseSheets() {
@@ -679,18 +672,15 @@ public class ConfigurationController extends GenericForwardComposer {
}
public void setGenerateCodeForUnitTypes(Boolean generateCodeForUnitTypes) {
- configurationModel
- .setGenerateCodeForUnitTypes(generateCodeForUnitTypes);
+ configurationModel.setGenerateCodeForUnitTypes(generateCodeForUnitTypes);
}
public Boolean getGenerateCodeForBaseCalendars() {
return configurationModel.getGenerateCodeForBaseCalendars();
}
- public void setGenerateCodeForBaseCalendars(
- Boolean generateCodeForBaseCalendars) {
- configurationModel
- .setGenerateCodeForBaseCalendars(generateCodeForBaseCalendars);
+ public void setGenerateCodeForBaseCalendars(Boolean generateCodeForBaseCalendars) {
+ configurationModel.setGenerateCodeForBaseCalendars(generateCodeForBaseCalendars);
}
public Boolean isAutocompleteLogin() {
@@ -711,10 +701,8 @@ public class ConfigurationController extends GenericForwardComposer {
}
- public void setMonteCarloMethodTabVisible(
- Boolean expandResourceLoadViewCharts) {
- configurationModel
- .setMonteCarloMethodTabVisible(expandResourceLoadViewCharts);
+ public void setMonteCarloMethodTabVisible(Boolean expandResourceLoadViewCharts) {
+ configurationModel.setMonteCarloMethodTabVisible(expandResourceLoadViewCharts);
}
public Boolean isMonteCarloMethodTabVisible() {
@@ -726,7 +714,6 @@ public class ConfigurationController extends GenericForwardComposer {
}
private static class ProgressTypeRenderer implements ListitemRenderer {
-
@Override
public void render(Listitem item, Object data) {
ProgressType progressType = (ProgressType) data;
@@ -744,8 +731,7 @@ public class ConfigurationController extends GenericForwardComposer {
final EntityNameEnum entityName = entitySequence.getEntityName();
row.setValue(entityName);
- row.appendChild(new Label(_("{0} sequences",
- entityName.getDescription())));
+ row.appendChild(new Label(_("{0} sequences", entityName.getDescription())));
row.setValue(entitySequence);
appendActiveRadiobox(row, entitySequence);
@@ -754,164 +740,124 @@ public class ConfigurationController extends GenericForwardComposer {
appendLastValueInbox(row, entitySequence);
appendOperations(row, entitySequence);
- if (entitySequence.isAlreadyInUse()) {
+ if ( entitySequence.isAlreadyInUse() ) {
row.setTooltiptext(_("Code sequence is already in use and cannot be updated"));
}
- if ((row.getPreviousSibling() != null)
- && !((EntitySequence) ((Row) row.getPreviousSibling())
- .getValue()).getEntityName().equals(entityName)) {
+ if ( (row.getPreviousSibling() != null) &&
+ !((EntitySequence) ((Row)
+ row.getPreviousSibling()).getValue()).getEntityName().equals(entityName) ) {
+
row.setClass("separator");
}
}
}
- private void appendActiveRadiobox(final Row row,
- final EntitySequence entitySequence) {
+ private void appendActiveRadiobox(final Row row, final EntitySequence entitySequence) {
- final Radio radiobox = Util.bind(new Radio(),
- new Util.Getter() {
+ final Radio radiobox = Util.bind(
+ new Radio(),
+ () -> entitySequence.isActive(),
+ value -> {
+ updateOtherSequences(entitySequence);
+ entitySequence.setActive(value);
+ Util.reloadBindings(entitySequencesGrid);
+ reloadEntitySequences();
+ });
- @Override
- public Boolean get() {
- return entitySequence.isActive();
- }
- }, new Util.Setter() {
+ row.appendChild(radiobox);
+ }
- @Override
- public void set(Boolean value) {
- updateOtherSequences(entitySequence);
- entitySequence.setActive(value);
- Util.reloadBindings(entitySequencesGrid);
- reloadEntitySequences();
- }
- });
-
- row.appendChild(radiobox);
+ private void updateOtherSequences(final EntitySequence activeSequence) {
+ for (EntitySequence sequence : getEntitySequences(activeSequence.getEntityName())) {
+ sequence.setActive(false);
}
+ }
- private void updateOtherSequences(final EntitySequence activeSequence) {
- for (EntitySequence sequence : getEntitySequences(activeSequence
- .getEntityName())) {
- sequence.setActive(false);
- }
- }
+ private void appendPrefixTextbox(Row row, final EntitySequence entitySequence) {
+ final Textbox tempTextbox = new Textbox();
+ tempTextbox.setWidth("200px");
- private void appendPrefixTextbox(Row row,
- final EntitySequence entitySequence) {
- final Textbox tempTextbox = new Textbox();
- tempTextbox.setWidth("200px");
- Textbox textbox = Util.bind(tempTextbox, new Util.Getter() {
-
- @Override
- public String get() {
- return entitySequence.getPrefix();
- }
- }, new Util.Setter() {
-
- @Override
- public void set(String value) {
+ Textbox textbox = Util.bind(
+ tempTextbox,
+ () -> entitySequence.getPrefix(),
+ value -> {
try {
entitySequence.setPrefix(value);
} catch (IllegalArgumentException e) {
- throw new WrongValueException(tempTextbox, e
- .getMessage());
+ throw new WrongValueException(tempTextbox, e.getMessage());
}
- }
- });
- textbox.setConstraint(checkConstraintFormatPrefix());
+ });
- if (entitySequence.isAlreadyInUse()) {
- textbox.setDisabled(true);
- }
+ textbox.setConstraint(checkConstraintFormatPrefix());
- row.appendChild(textbox);
+ if ( entitySequence.isAlreadyInUse() ) {
+ textbox.setDisabled(true);
}
- private void appendNumberOfDigitsInbox(Row row,
- final EntitySequence entitySequence) {
- final Intbox tempIntbox = new Intbox();
- Intbox intbox = Util.bind(tempIntbox, new Util.Getter() {
+ row.appendChild(textbox);
+ }
- @Override
- public Integer get() {
- return entitySequence.getNumberOfDigits();
- }
- }, new Util.Setter() {
+ private void appendNumberOfDigitsInbox(Row row, final EntitySequence entitySequence) {
+ final Intbox tempIntbox = new Intbox();
- @Override
- public void set(Integer value) {
+ Intbox intbox = Util.bind(
+ tempIntbox,
+ () -> entitySequence.getNumberOfDigits(),
+ value -> {
try {
entitySequence.setNumberOfDigits(value);
} catch (IllegalArgumentException e) {
- throw new WrongValueException(tempIntbox, _(
- "number of digits must be between {0} and {1}",
- EntitySequence.MIN_NUMBER_OF_DIGITS,
- EntitySequence.MAX_NUMBER_OF_DIGITS));
+ throw new WrongValueException(
+ tempIntbox,
+ _("number of digits must be between {0} and {1}",
+ EntitySequence.MIN_NUMBER_OF_DIGITS,
+ EntitySequence.MAX_NUMBER_OF_DIGITS));
}
- }
- });
- intbox.setConstraint(checkConstraintNumberOfDigits());
+ });
- if (entitySequence.isAlreadyInUse()) {
- intbox.setDisabled(true);
+ intbox.setConstraint(checkConstraintNumberOfDigits());
+
+ if ( entitySequence.isAlreadyInUse() ) {
+ intbox.setDisabled(true);
+ }
+
+ row.appendChild(intbox);
+ }
+
+ private void appendLastValueInbox(Row row, final EntitySequence entitySequence) {
+ Textbox textbox = Util.bind(
+ new Textbox(),
+ () -> EntitySequence.formatValue(entitySequence.getNumberOfDigits(), entitySequence.getLastValue()));
+
+ row.appendChild(textbox);
+ }
+
+ private void appendOperations(final Row row, final EntitySequence entitySequence) {
+ final Button removeButton = Util.createRemoveButton(event -> {
+ if ( isLastOne(entitySequence) ) {
+ showMessageNotDelete();
+ } else {
+ removeEntitySequence(entitySequence);
}
+ });
- row.appendChild(intbox);
+ if ( entitySequence.isAlreadyInUse() ) {
+ removeButton.setDisabled(true);
}
- private void appendLastValueInbox(Row row,
- final EntitySequence entitySequence) {
- Textbox textbox = Util.bind(new Textbox(),
- new Util.Getter() {
-
- @Override
- public String get() {
- return EntitySequence.formatValue(
- entitySequence.getNumberOfDigits(),
- entitySequence.getLastValue());
- }
- });
-
- row.appendChild(textbox);
- }
-
- private void appendOperations(final Row row,
- final EntitySequence entitySequence) {
- final Button removeButton = Util
- .createRemoveButton(new EventListener() {
-
- @Override
- public void onEvent(Event event) {
- if (isLastOne(entitySequence)) {
- showMessageNotDelete();
- } else {
- removeEntitySequence(entitySequence);
- }
- }
- });
-
- if (entitySequence.isAlreadyInUse()) {
- removeButton.setDisabled(true);
- }
-
- row.appendChild(removeButton);
- }
+ row.appendChild(removeButton);
+ }
public Constraint checkConstraintFormatPrefix() {
- return new Constraint() {
- @Override
- public void validate(Component comp, Object value)
- throws WrongValueException {
-
- Row row = (Row) comp.getParent();
- EntitySequence sequence = (EntitySequence) row.getValue();
- if (!sequence.isAlreadyInUse()) {
- String errorMessage = validPrefix(sequence, (String) value);
- if (errorMessage != null) {
- throw new WrongValueException(comp, errorMessage);
- }
+ return (comp, value) -> {
+ Row row = (Row) comp.getParent();
+ EntitySequence sequence = (EntitySequence) row.getValue();
+ if ( !sequence.isAlreadyInUse() ) {
+ String errorMessage = validPrefix(sequence, (String) value);
+ if ( errorMessage != null ) {
+ throw new WrongValueException(comp, errorMessage);
}
}
};
@@ -919,9 +865,9 @@ public class ConfigurationController extends GenericForwardComposer {
private String validPrefix(EntitySequence sequence, String prefixValue) {
sequence.setPrefix(prefixValue);
- if (!configurationModel.checkFrefixFormat(sequence)) {
+ if ( !configurationModel.checkFrefixFormat(sequence) ) {
String message = _("Invalid format prefix. Format prefix cannot be empty, contain '_' or contain whitespaces.");
- if (sequence.getEntityName().canContainLowBar()) {
+ if ( sequence.getEntityName().canContainLowBar() ) {
message = _("format prefix invalid. It cannot be empty or contain whitespaces.");
}
return message;
@@ -930,30 +876,27 @@ public class ConfigurationController extends GenericForwardComposer {
}
public Constraint checkConstraintNumberOfDigits() {
- return new Constraint() {
+ return (comp, value) -> {
+ Row row = (Row) comp.getParent();
+ EntitySequence sequence = (EntitySequence) row.getValue();
- @Override
- public void validate(Component comp, Object value)
- throws WrongValueException {
- Row row = (Row) comp.getParent();
- EntitySequence sequence = (EntitySequence) row.getValue();
- if (!sequence.isAlreadyInUse()) {
- Integer numberOfDigits = (Integer) value;
- try {
- sequence.setNumberOfDigits(numberOfDigits);
- } catch (IllegalArgumentException e) {
- throw new WrongValueException(comp, _(
- "number of digits must be between {0} and {1}",
- EntitySequence.MIN_NUMBER_OF_DIGITS,
- EntitySequence.MAX_NUMBER_OF_DIGITS));
- }
+ if ( !sequence.isAlreadyInUse() ) {
+ Integer numberOfDigits = (Integer) value;
+ try {
+ sequence.setNumberOfDigits(numberOfDigits);
+ } catch (IllegalArgumentException e) {
+
+ throw new WrongValueException(
+ comp,
+ _("number of digits must be between {0} and {1}",
+ EntitySequence.MIN_NUMBER_OF_DIGITS,
+ EntitySequence.MAX_NUMBER_OF_DIGITS));
}
}
};
}
- public void addEntitySequence(EntityNameEnum entityName, String prefix,
- Integer digits) {
+ public void addEntitySequence(EntityNameEnum entityName, String prefix, Integer digits) {
configurationModel.addEntitySequence(entityName, prefix, digits);
reloadEntitySequences();
}
@@ -963,22 +906,21 @@ public class ConfigurationController extends GenericForwardComposer {
}
private boolean isLastOne(EntitySequence sequence) {
- return (getEntitySequences(sequence.getEntityName()).size() == 1);
+ return getEntitySequences(sequence.getEntityName()).size() == 1;
}
private void showMessageNotDelete() {
try {
- Messagebox
- .show(_("It can not be deleted. At least one sequence is necessary."),
- _("Deleting sequence"), Messagebox.OK,
- Messagebox.INFORMATION);
+ Messagebox.show(
+ _("It can not be deleted. At least one sequence is necessary."),
+ _("Deleting sequence"), Messagebox.OK, Messagebox.INFORMATION);
+
} catch (InterruptedException e) {
messages.showMessage(Level.ERROR, e.getMessage());
}
}
- public static class EntitySequenceComparator implements
- Comparator {
+ public static class EntitySequenceComparator implements Comparator {
@Override
public int compare(EntitySequence seq1, EntitySequence seq2) {
@@ -991,7 +933,7 @@ public class ConfigurationController extends GenericForwardComposer {
}
private List getAllEntitySequences() {
- List allSequences = new ArrayList();
+ List allSequences = new ArrayList<>();
for (final EntityNameEnum entityName : EntityNameEnum.values()) {
allSequences.addAll(this.getEntitySequences(entityName));
}
@@ -999,21 +941,20 @@ public class ConfigurationController extends GenericForwardComposer {
}
public void addNewEntitySequence() {
- if (entityCombo != null && numDigitBox != null) {
- if (entityCombo.getSelectedItem() == null) {
- throw new WrongValueException(entityCombo,
- _("Select entity, please"));
+ if ( entityCombo != null && numDigitBox != null ) {
+ if ( entityCombo.getSelectedItem() == null ) {
+ throw new WrongValueException(entityCombo, _("Select entity, please"));
}
- if (prefixBox.getValue() == null || prefixBox.getValue().isEmpty()) {
- throw new WrongValueException(prefixBox,
- _("cannot be empty"));
+ if ( prefixBox.getValue() == null || prefixBox.getValue().isEmpty() ) {
+ throw new WrongValueException(prefixBox, _("cannot be empty"));
}
try {
- addEntitySequence((EntityNameEnum) entityCombo
- .getSelectedItem().getValue(), prefixBox.getValue(),
- numDigitBox.getValue());
+ addEntitySequence(
+ (EntityNameEnum) entityCombo.getSelectedItem().getValue(),
+ prefixBox.getValue(), numDigitBox.getValue());
+
} catch (IllegalArgumentException e) {
throw new WrongValueException(numDigitBox, e.getMessage());
}
@@ -1024,7 +965,7 @@ public class ConfigurationController extends GenericForwardComposer {
return EntityNameEnum.values();
}
- // Tab ldap properties
+ // Tab LDAP properties
public LDAPConfiguration getLdapConfiguration() {
return configurationModel.getLdapConfiguration();
}
@@ -1034,42 +975,36 @@ public class ConfigurationController extends GenericForwardComposer {
}
public RowRenderer getAllUserRolesRenderer() {
- return new RowRenderer() {
- @Override
- public void render(Row row, Object data) throws Exception {
+ return (row, data) -> {
- final UserRole role = (UserRole) data;
- row.appendChild(new Label(role.getDisplayName()));
+ final UserRole role = (UserRole) data;
+ row.appendChild(new Label(role.getDisplayName()));
+
+ final Textbox tempTextbox = new Textbox();
+
+ Textbox textbox = Util.bind(
+ tempTextbox,
+ () -> {
+ List listRoles =
+ configurationModel.getLdapConfiguration().getMapMatchingRoles().get(role.name());
- final Textbox tempTextbox = new Textbox();
- Textbox textbox = Util.bind(tempTextbox, new Util.Getter() {
- @Override
- public String get() {
- List listRoles = configurationModel.
- getLdapConfiguration().getMapMatchingRoles().get(role.name());
Collections.sort(listRoles);
+
return StringUtils.join(listRoles, ";");
- }
- }, new Util.Setter() {
- @Override
- public void set(String value) {
- // Created a set in order to avoid duplicates
- Set rolesLdap = new HashSet(
- Arrays.asList(StringUtils.split(value,
- ";")));
- configurationModel.getLdapConfiguration()
- .setConfigurationRolesLdap(role.name(),
- rolesLdap);
- }
- });
- textbox.setWidth("300px");
- row.appendChild(textbox);
- }
+ },
+ value -> {
+ // Created a set in order to avoid duplicates
+ Set rolesLdap = new HashSet<>(Arrays.asList(StringUtils.split(value, ";")));
+ configurationModel.getLdapConfiguration().setConfigurationRolesLdap(role.name(), rolesLdap);
+ });
+
+ textbox.setWidth("300px");
+ row.appendChild(textbox);
};
}
public UserRole[] getRoles() {
- return roles.values();
+ return UserRole.values();
}
public void setRoles(UserRole roles) {
@@ -1100,10 +1035,8 @@ public class ConfigurationController extends GenericForwardComposer {
return configurationModel.isAllowToGatherUsageStatsEnabled();
}
- public void setAllowToGatherUsageStatsEnabled(
- boolean allowToGatherUsageStatsEnabled) {
- configurationModel
- .setAllowToGatherUsageStatsEnabled(allowToGatherUsageStatsEnabled);
+ public void setAllowToGatherUsageStatsEnabled(boolean allowToGatherUsageStatsEnabled) {
+ configurationModel.setAllowToGatherUsageStatsEnabled(allowToGatherUsageStatsEnabled);
}
public Set getCurrencies() {
@@ -1111,14 +1044,10 @@ public class ConfigurationController extends GenericForwardComposer {
}
public ListitemRenderer getCurrencyRenderer() {
- return new ListitemRenderer() {
- @Override
- public void render(Listitem item, Object data) throws Exception {
- String currencyCode = (String) data;
- item.setLabel(currencyCode + " - "
- + configurationModel.getCurrencySymbol(currencyCode));
- item.setValue(currencyCode);
- }
+ return (item, data) -> {
+ String currencyCode = (String) data;
+ item.setLabel(currencyCode + " - " + configurationModel.getCurrencySymbol(currencyCode));
+ item.setValue(currencyCode);
};
}
@@ -1134,8 +1063,7 @@ public class ConfigurationController extends GenericForwardComposer {
return configurationModel.getPersonalTimesheetsTypeOfWorkHours();
}
- public void setPersonalTimesheetsTypeOfWorkHours(
- TypeOfWorkHours typeOfWorkHours) {
+ public void setPersonalTimesheetsTypeOfWorkHours(TypeOfWorkHours typeOfWorkHours) {
configurationModel.setPersonalTimesheetsTypeOfWorkHours(typeOfWorkHours);
}
@@ -1160,13 +1088,10 @@ public class ConfigurationController extends GenericForwardComposer {
}
public ListitemRenderer getPersonalTimesheetsPeriodicityRenderer() {
- return new ListitemRenderer() {
- @Override
- public void render(Listitem item, Object data) throws Exception {
- PersonalTimesheetsPeriodicityEnum periodicity = (PersonalTimesheetsPeriodicityEnum) data;
- item.setLabel(_(periodicity.getName()));
- item.setValue(periodicity);
- }
+ return (item, data) -> {
+ PersonalTimesheetsPeriodicityEnum periodicity = (PersonalTimesheetsPeriodicityEnum) data;
+ item.setLabel(_(periodicity.getName()));
+ item.setValue(periodicity);
};
}
@@ -1176,8 +1101,8 @@ public class ConfigurationController extends GenericForwardComposer {
public void setSelectedPersonalTimesheetsPeriodicity(
PersonalTimesheetsPeriodicityEnum personalTimesheetsPeriodicity) {
- configurationModel
- .setPersonalTimesheetsPeriodicity(personalTimesheetsPeriodicity);
+
+ configurationModel.setPersonalTimesheetsPeriodicity(personalTimesheetsPeriodicity);
}
public boolean isPersonalTimesheetsPeriodicityDisabled() {
@@ -1185,7 +1110,7 @@ public class ConfigurationController extends GenericForwardComposer {
}
public String getPersonalTimesheetsPeriodicityTooltip() {
- if (isPersonalTimesheetsPeriodicityDisabled()) {
+ if ( isPersonalTimesheetsPeriodicityDisabled() ) {
return _("Periocity cannot be changed because there is already any personal timesheet stored");
}
return "";
@@ -1221,12 +1146,10 @@ public class ConfigurationController extends GenericForwardComposer {
}
public List getConnectorPropertries() {
- if (selectedConnector == null) {
- return Collections.emptyList();
- }
- return selectedConnector.getProperties();
+ return selectedConnector == null ? Collections.emptyList() : selectedConnector.getProperties();
}
+ /* Should be public! */
public RowRenderer getConnectorPropertriesRenderer() {
return new RowRenderer() {
@Override
@@ -1237,135 +1160,108 @@ public class ConfigurationController extends GenericForwardComposer {
Util.appendLabel(row, _(property.getKey()));
// FIXME this is not perfect solution
- if ( property.getKey().equals("Protocol") ) appendValueCombobox(row, property);
+ if ( property.getKey().equals("Protocol") )
+ appendValueCombobox(row, property);
+
else appendValueTextbox(row, property);
}
- private void appendValueTextbox(Row row,
- final ConnectorProperty property) {
+ private void appendValueTextbox(Row row, final ConnectorProperty property) {
final Textbox textbox = new Textbox();
textbox.setWidth("400px");
textbox.setConstraint(checkPropertyValue(property));
- Util.bind(textbox, new Util.Getter() {
+ Util.bind(
+ textbox,
+ () -> property.getValue(),
+ value -> property.setValue(value));
- @Override
- public String get() {
- return property.getValue();
- }
- }, new Util.Setter() {
+ boolean propertyEqualsPasswordOrEmailPassword =
+ property.getKey().equals(PredefinedConnectorProperties.PASSWORD) ||
+ property.getKey().equals(PredefinedConnectorProperties.EMAIL_PASSWORD);
- @Override
- public void set(String value) {
- property.setValue(value);
- }
- });
-
- if ( property.getKey().equals(
- PredefinedConnectorProperties.PASSWORD) ||
- property.getKey().equals(
- PredefinedConnectorProperties.EMAIL_PASSWORD) ) {
+ if ( propertyEqualsPasswordOrEmailPassword ) {
textbox.setType("password");
}
- // Need for method validateEmailFields()
- if ( property.getKey().equals(
- PredefinedConnectorProperties.EMAIL_USERNAME) ) emailUsernameTextbox = textbox;
+ // Needed for method validateEmailFields()
+ if ( property.getKey().equals(PredefinedConnectorProperties.EMAIL_USERNAME) )
+ emailUsernameTextbox = textbox;
- if ( property.getKey().equals(
- PredefinedConnectorProperties.EMAIL_PASSWORD) ) emailPasswordTextbox = textbox;
+ if ( property.getKey().equals(PredefinedConnectorProperties.EMAIL_PASSWORD) )
+ emailPasswordTextbox = textbox;
- if ( property.getKey().equals(
- PredefinedConnectorProperties.EMAIL_SENDER) ) emailSenderTextbox = textbox;
+ if ( property.getKey().equals(PredefinedConnectorProperties.EMAIL_SENDER) )
+ emailSenderTextbox = textbox;
row.appendChild(textbox);
}
- private void appendValueCombobox(Row row,
- final ConnectorProperty property){
+ private void appendValueCombobox(Row row, final ConnectorProperty property) {
final Combobox combobox = new Combobox();
combobox.setWidth("400px");
- final List protocols = new ArrayList();
+ final List protocols = new ArrayList<>();
protocols.add("SMTP");
protocols.add("STARTTLS");
- for (String item : protocols){
+ for (String item : protocols) {
Comboitem comboitem = new Comboitem();
comboitem.setValue(item);
comboitem.setLabel(item);
comboitem.setParent(combobox);
- if ( (!property.getValue().equals("")) &&
- (item.equals(property.getValue())) ){
+ if ( (!"".equals(property.getValue())) && (item.equals(property.getValue())) ){
combobox.setSelectedItem(comboitem);
}
}
- combobox.addEventListener(Events.ON_SELECT,
- new EventListener() {
- @Override
- public void onEvent(Event event) throws Exception {
- if (combobox.getSelectedItem() != null){
- property.setValue(combobox.getSelectedItem().getValue().toString());
- }
- }
- });
-
- Util.bind(combobox, new Util.Getter() {
- @Override
- public Comboitem get() {
- return combobox.getSelectedItem();
- }
- }, new Util.Setter(){
-
- @Override
- public void set(Comboitem item) {
- if ( (item != null) && (item.getValue() != null) &&
- (item.getValue() instanceof String) ){
- property.setValue(combobox.getSelectedItem().getValue().toString());
- }
+ combobox.addEventListener(Events.ON_SELECT, event -> {
+ if ( combobox.getSelectedItem() != null ) {
+ property.setValue(combobox.getSelectedItem().getValue().toString());
}
});
+ Util.bind(
+ combobox,
+ () -> combobox.getSelectedItem(),
+ item -> {
+ if ( (item != null) && (item.getValue() != null) && (item.getValue() instanceof String) ) {
+ property.setValue(combobox.getSelectedItem().getValue().toString());
+ }
+ });
+
row.appendChild(combobox);
- // Need for testing E-mail connection
+ // Needed for testing E-mail connection
protocolsCombobox = combobox;
}
- public Constraint checkPropertyValue(
- final ConnectorProperty property) {
+ public Constraint checkPropertyValue(final ConnectorProperty property) {
final String key = property.getKey();
- return new Constraint() {
- @Override
- public void validate(Component comp, Object value) {
- if ( key.equals(PredefinedConnectorProperties.ACTIVATED) ) {
- if ( !((String) value).equalsIgnoreCase("Y")
- && !((String) value).equalsIgnoreCase("N") ) {
- throw new WrongValueException(comp, _(
- "Only {0} allowed", "Y/N"));
- }
- } else if ( key
- .equals(PredefinedConnectorProperties.SERVER_URL) ||
- key.equals(PredefinedConnectorProperties.USERNAME) ||
- key.equals(PredefinedConnectorProperties.PASSWORD) ||
- key.equals(PredefinedConnectorProperties.JIRA_HOURS_TYPE) ||
- key.equals(PredefinedConnectorProperties.HOST) ||
- key.equals(PredefinedConnectorProperties.PORT) ||
- key.equals(PredefinedConnectorProperties.EMAIL_SENDER) ||
- key.equals(PredefinedConnectorProperties.PROTOCOL) ) {
- ((InputElement) comp).setConstraint("no empty:"
- + _("cannot be empty"));
- } else if ( key
- .equals(PredefinedConnectorProperties.TIM_NR_DAYS_TIMESHEET) ||
- key.equals(PredefinedConnectorProperties.TIM_NR_DAYS_ROSTER) ||
- key.equals(PredefinedConnectorProperties.PORT) ) {
- if ( !isNumeric((String) value) ) {
- throw new WrongValueException(comp,
- _("Only digits allowed"));
- }
+ return (comp, value) -> {
+ if ( key.equals(PredefinedConnectorProperties.ACTIVATED) ) {
+ if ( !((String) value).equalsIgnoreCase("Y") && !((String) value).equalsIgnoreCase("N") ) {
+ throw new WrongValueException(comp, _("Only {0} allowed", "Y/N"));
+ }
+ } else if ( key.equals(PredefinedConnectorProperties.SERVER_URL) ||
+ key.equals(PredefinedConnectorProperties.USERNAME) ||
+ key.equals(PredefinedConnectorProperties.PASSWORD) ||
+ key.equals(PredefinedConnectorProperties.JIRA_HOURS_TYPE) ||
+ key.equals(PredefinedConnectorProperties.HOST) ||
+ key.equals(PredefinedConnectorProperties.PORT) ||
+ key.equals(PredefinedConnectorProperties.EMAIL_SENDER) ||
+ key.equals(PredefinedConnectorProperties.PROTOCOL) ) {
+
+ ((InputElement) comp).setConstraint("no empty:" + _("cannot be empty"));
+
+ } else if ( key.equals(PredefinedConnectorProperties.TIM_NR_DAYS_TIMESHEET) ||
+ key.equals(PredefinedConnectorProperties.TIM_NR_DAYS_ROSTER) ||
+ key.equals(PredefinedConnectorProperties.PORT) ) {
+
+ if ( !isNumeric((String) value) ) {
+ throw new WrongValueException(comp, _("Only digits allowed"));
}
}
};
@@ -1383,8 +1279,8 @@ public class ConfigurationController extends GenericForwardComposer {
};
}
- private boolean isEmailFieldsValid(){
- if ( protocolsCombobox != null && protocolsCombobox.getSelectedItem() != null ){
+ private boolean areEmailFieldsValid() {
+ if ( protocolsCombobox != null && protocolsCombobox.getSelectedItem() != null ) {
if ( protocolsCombobox.getSelectedItem().getLabel().equals("STARTTLS") &&
emailUsernameTextbox.getValue() != null &&
emailPasswordTextbox.getValue() != null &&
@@ -1393,7 +1289,7 @@ public class ConfigurationController extends GenericForwardComposer {
emailSenderTextbox.getValue().matches("^\\S+@\\S+\\.\\S+$") )
return true;
- if ( protocolsCombobox != null && protocolsCombobox.getSelectedItem() != null ){
+ if ( protocolsCombobox != null && protocolsCombobox.getSelectedItem() != null ) {
if ( protocolsCombobox.getSelectedItem().getLabel().equals("SMTP") )
return true;
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/common/IJobSchedulerModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/common/IJobSchedulerModel.java
index c8043e533..e8b3e661e 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/web/common/IJobSchedulerModel.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/web/common/IJobSchedulerModel.java
@@ -37,15 +37,14 @@ import org.libreplan.importers.SynchronizationInfo;
public interface IJobSchedulerModel {
/**
- * returns all job scheduler configurations
+ * Returns all job scheduler configurations.
*
* @return list of JobSchedulerConfiguration
*/
List getJobSchedulerConfigurations();
/**
- * returns next fire time for the specified job from
- * {@link JobSchedulerConfiguration}
+ * Returns next fire time for the specified job from {@link JobSchedulerConfiguration}.
*
* @param jobSchedulerConfiguration
* the job scheduler configuration
@@ -53,18 +52,17 @@ public interface IJobSchedulerModel {
String getNextFireTime(JobSchedulerConfiguration jobSchedulerConfiguration);
/**
- * Do manual action(replacement of scheduling)
+ * Do manual action(replacement of scheduling).
*
* @param jobSchedulerConfiguration
* the job configuration
* @throws ConnectorException
* if connector is not valid
*/
- void doManual(JobSchedulerConfiguration jobSchedulerConfiguration)
- throws ConnectorException;
+ void doManual(JobSchedulerConfiguration jobSchedulerConfiguration) throws ConnectorException;
/**
- * Returns synchronization infos. Failures or successes info
+ * Returns synchronization infos. Failures or successes info.
*/
List getSynchronizationInfos();
@@ -74,7 +72,7 @@ public interface IJobSchedulerModel {
void initCreate();
/**
- * Prepares for edit {@link JobSchedulerConfiguration}
+ * Prepares for edit {@link JobSchedulerConfiguration}.
*
* @param jobSchedulerConfiguration
* object to be edited
@@ -89,7 +87,7 @@ public interface IJobSchedulerModel {
JobSchedulerConfiguration getJobSchedulerConfiguration();
/**
- * Saves the current {@link JobSchedulerConfiguration}
+ * Saves the current {@link JobSchedulerConfiguration}.
*
* @throws ValidationException
* if validation fails
@@ -97,12 +95,12 @@ public interface IJobSchedulerModel {
void confirmSave() throws ValidationException;
/**
- * Cancels the current {@link JobSchedulerConfiguration}
+ * Cancels the current {@link JobSchedulerConfiguration}.
*/
void cancel();
/**
- * Removes the current {@link JobSchedulerConfiguration}
+ * Removes the current {@link JobSchedulerConfiguration}.
*
* @param jobSchedulerConfiguration
* object to be removed
@@ -110,16 +108,15 @@ public interface IJobSchedulerModel {
void remove(JobSchedulerConfiguration jobSchedulerConfiguration);
/**
- * returns list of connectors
+ * Returns list of connectors
*/
List getConnectors();
/**
- * Schedule or unschedule jobs for the specified connector
+ * Schedule or unschedule jobs for the specified connector.
*
- * schedule all jobs of the specified connector's property
- * {@link PredefinedConnectorProperties#ACTIVATED} is 'Y', otherwise
- * unschedule the jobs
+ * Schedule all jobs of the specified connector's property
+ * {@link PredefinedConnectorProperties#ACTIVATED} is 'Y', otherwise unschedule the jobs.
*
* @param connector
* where to check if property is changed
@@ -128,22 +125,20 @@ public interface IJobSchedulerModel {
boolean scheduleOrUnscheduleJobs(Connector connector);
/**
- * schedule or unschedule job for the specified job in
- * {@link JobSchedulerConfiguration}
+ * Schedule or unschedule job for the specified job in {@link JobSchedulerConfiguration}.
*
* @return true if scheduling is succeeded, false otherwise
*/
boolean scheduleOrUnscheduleJob();
/**
- * Delete job specified in {@link JobSchedulerConfiguration}
+ * Delete job specified in {@link JobSchedulerConfiguration}.
*
* @param jobSchedulerConfiguration
* configuration for the job to be deleted
* @return true if job is successfully deleted from the scheduler, false
* otherwise
*/
- boolean deleteScheduledJob(
- JobSchedulerConfiguration jobSchedulerConfiguration);
+ boolean deleteScheduledJob(JobSchedulerConfiguration jobSchedulerConfiguration);
}
\ No newline at end of file
diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/common/JobSchedulerController.java b/libreplan-webapp/src/main/java/org/libreplan/web/common/JobSchedulerController.java
index d2aec0388..f612bb37f 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/web/common/JobSchedulerController.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/web/common/JobSchedulerController.java
@@ -42,7 +42,6 @@ import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.WrongValueException;
-import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
@@ -52,7 +51,6 @@ import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Popup;
-import org.zkoss.zul.Row;
import org.zkoss.zul.RowRenderer;
import org.zkoss.zul.SimpleListModel;
import org.zkoss.zul.api.Caption;
@@ -64,27 +62,30 @@ import org.zkoss.zul.api.Window;
*
* @author Miciele Ghiorghis
*/
-public class JobSchedulerController extends
- BaseCRUDController {
+public class JobSchedulerController extends BaseCRUDController {
- private static final Log LOG = LogFactory
- .getLog(JobSchedulerController.class);
-
- private Grid listJobSchedulings;
- private Grid cronExpressionGrid;
+ private static final Log LOG = LogFactory.getLog(JobSchedulerController.class);
private Popup cronExpressionInputPopup;
private Label jobGroup;
+
private Label jobName;
private Textbox cronExpressionTextBox;
+
private Textbox cronExpressionSeconds;
+
private Textbox cronExpressionMinutes;
+
private Textbox cronExpressionHours;
+
private Textbox cronExpressionDayOfMonth;
+
private Textbox cronExpressionMonth;
+
private Textbox cronExpressionDayOfWeek;
+
private Textbox cronExpressionYear;
private IJobSchedulerModel jobSchedulerModel;
@@ -92,71 +93,67 @@ public class JobSchedulerController extends
@Override
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
- listJobSchedulings = (Grid) listWindow
- .getFellowIfAny("listJobSchedulings");
+ Grid listJobSchedulings = (Grid) listWindow.getFellowIfAny("listJobSchedulings");
listJobSchedulings.getModel();
initCronExpressionPopup();
}
/**
- * initializes cron expressions for popup
+ * Initializes cron expressions for popup
*/
private void initCronExpressionPopup() {
- cronExpressionTextBox = (Textbox) editWindow
- .getFellow("cronExpressionTextBox");
+ cronExpressionTextBox = (Textbox) editWindow.getFellow("cronExpressionTextBox");
- cronExpressionInputPopup = (Popup) editWindow
- .getFellow("cronExpressionInputPopup");
+ cronExpressionInputPopup = (Popup) editWindow.getFellow("cronExpressionInputPopup");
jobGroup = (Label) cronExpressionInputPopup.getFellow("jobGroup");
+
jobName = (Label) cronExpressionInputPopup.getFellow("jobName");
- cronExpressionGrid = (Grid) cronExpressionInputPopup
- .getFellow("cronExpressionGrid");
+ Grid cronExpressionGrid = (Grid) cronExpressionInputPopup.getFellow("cronExpressionGrid");
- cronExpressionSeconds = (Textbox) cronExpressionGrid
- .getFellow("cronExpressionSeconds");
- cronExpressionMinutes = (Textbox) cronExpressionGrid
- .getFellow("cronExpressionMinutes");
- cronExpressionHours = (Textbox) cronExpressionGrid
- .getFellow("cronExpressionHours");
- cronExpressionDayOfMonth = (Textbox) cronExpressionGrid
- .getFellow("cronExpressionDayOfMonth");
- cronExpressionMonth = (Textbox) cronExpressionGrid
- .getFellow("cronExpressionMonth");
- cronExpressionDayOfWeek = (Textbox) cronExpressionGrid
- .getFellow("cronExpressionDayOfWeek");
- cronExpressionYear = (Textbox) cronExpressionGrid
- .getFellow("cronExpressionYear");
+ cronExpressionSeconds = (Textbox) cronExpressionGrid.getFellow("cronExpressionSeconds");
+
+ cronExpressionMinutes = (Textbox) cronExpressionGrid.getFellow("cronExpressionMinutes");
+
+ cronExpressionHours = (Textbox) cronExpressionGrid.getFellow("cronExpressionHours");
+
+ cronExpressionDayOfMonth = (Textbox) cronExpressionGrid.getFellow("cronExpressionDayOfMonth");
+
+ cronExpressionMonth = (Textbox) cronExpressionGrid.getFellow("cronExpressionMonth");
+
+ cronExpressionDayOfWeek = (Textbox) cronExpressionGrid.getFellow("cronExpressionDayOfWeek");
+
+ cronExpressionYear = (Textbox) cronExpressionGrid.getFellow("cronExpressionYear");
}
/**
- * returns a list of {@link JobSchedulerConfiguration}
+ * Returns a list of {@link JobSchedulerConfiguration}
*/
public List getJobSchedulerConfigurations() {
return jobSchedulerModel.getJobSchedulerConfigurations();
}
/**
- * returns {@link JobSchedulerConfiguration}
+ * Returns {@link JobSchedulerConfiguration}
*/
public JobSchedulerConfiguration getJobSchedulerConfiguration() {
return jobSchedulerModel.getJobSchedulerConfiguration();
}
/**
- * returns all predefined jobs
+ * Returns all predefined jobs
*/
public JobClassNameEnum[] getJobNames() {
return JobClassNameEnum.values();
}
/**
- * return list of connectorNames
+ * Return list of connectorNames
*/
public List getConnectorNames() {
List connectors = jobSchedulerModel.getConnectors();
- List connectorNames = new ArrayList();
+ List connectorNames = new ArrayList<>();
for (Connector connector : connectors) {
connectorNames.add(connector.getName());
}
@@ -164,79 +161,55 @@ public class JobSchedulerController extends
}
/**
- * renders job scheduling and returns {@link RowRenderer}
+ * Renders job scheduling and returns {@link RowRenderer}
*/
public RowRenderer getJobSchedulingRenderer() {
- return new RowRenderer() {
+ return (row, data) -> {
+ final JobSchedulerConfiguration jobSchedulerConfiguration = (JobSchedulerConfiguration) data;
+ row.setValue(data);
- @Override
- public void render(Row row, Object data) {
- final JobSchedulerConfiguration jobSchedulerConfiguration = (JobSchedulerConfiguration) data;
- row.setValue(data);
+ Util.appendLabel(row, jobSchedulerConfiguration.getJobGroup());
+ Util.appendLabel(row, jobSchedulerConfiguration.getJobName());
+ Util.appendLabel(row, jobSchedulerConfiguration.getCronExpression());
+ Util.appendLabel(row, getNextFireTime(jobSchedulerConfiguration));
+ Hbox hbox = new Hbox();
- Util.appendLabel(row, jobSchedulerConfiguration.getJobGroup());
- Util.appendLabel(row, jobSchedulerConfiguration.getJobName());
- Util.appendLabel(row,
- jobSchedulerConfiguration.getCronExpression());
- Util.appendLabel(row,
- getNextFireTime(jobSchedulerConfiguration));
- Hbox hbox = new Hbox();
- hbox.appendChild(createManualButton(new EventListener() {
+ hbox.appendChild(createManualButton(event -> {
+ try {
+ jobSchedulerModel.doManual(jobSchedulerConfiguration);
+ showSynchronizationInfo();
+ } catch (ConnectorException e) {
+ messagesForUser.showMessage(Level.ERROR, e.getMessage());
+ }
+ }));
- @Override
- public void onEvent(Event event) throws Exception {
- try {
- jobSchedulerModel.doManual(jobSchedulerConfiguration);
- showSynchronizationInfo();
- } catch (ConnectorException e) {
- messagesForUser.showMessage(Level.ERROR,
- e.getMessage());
- }
- }
- }));
- hbox.appendChild(Util.createEditButton(new EventListener() {
- @Override
- public void onEvent(Event event) {
- goToEditForm(jobSchedulerConfiguration);
- }
- }));
- hbox.appendChild(Util.createRemoveButton(new EventListener() {
- @Override
- public void onEvent(Event event) {
- confirmDelete(jobSchedulerConfiguration);
- }
- }));
- row.appendChild(hbox);
+ hbox.appendChild(Util.createEditButton(event -> goToEditForm(jobSchedulerConfiguration)));
- }
+ hbox.appendChild(Util.createRemoveButton(event -> confirmDelete(jobSchedulerConfiguration)));
+ row.appendChild(hbox);
};
}
public RowRenderer getSynchronizationInfoRenderer() {
- return new RowRenderer() {
+ return (row, data) -> {
+ final SynchronizationInfo synchronizationInfo = (SynchronizationInfo) data;
+ row.setValue(data);
- @Override
- public void render(Row row, Object data) {
- final SynchronizationInfo synchronizationInfo = (SynchronizationInfo) data;
- row.setValue(data);
+ Groupbox groupbox = new Groupbox();
+ groupbox.setClosable(true);
+ Caption caption = new org.zkoss.zul.Caption();
+ caption.setLabel(synchronizationInfo.getAction());
+ groupbox.appendChild(caption);
+ row.appendChild(groupbox);
- Groupbox groupbox = new Groupbox();
- groupbox.setClosable(true);
- Caption caption = new org.zkoss.zul.Caption();
- caption.setLabel(synchronizationInfo.getAction());
- groupbox.appendChild(caption);
- row.appendChild(groupbox);
+ if (synchronizationInfo.isSuccessful()) {
+ groupbox.appendChild(new Label(_("Completed")));
+ } else {
- if (synchronizationInfo.isSuccessful()) {
- groupbox.appendChild(new Label(_("Completed")));
- } else {
+ Listbox listbox = new Listbox();
- Listbox listbox = new Listbox();
-
- listbox.setModel(new SimpleListModel(synchronizationInfo
- .getFailedReasons()));
- groupbox.appendChild(listbox);
- }
+ listbox.setModel(new SimpleListModel(synchronizationInfo.getFailedReasons()));
+ groupbox.appendChild(listbox);
}
};
}
@@ -248,10 +221,9 @@ public class JobSchedulerController extends
private void showSynchronizationInfo() {
- Map args = new HashMap();
+ Map args = new HashMap<>();
- Window win = (Window) Executions.createComponents(
- "/orders/_synchronizationInfo.zul", null, args);
+ Window win = (Window) Executions.createComponents("/orders/_synchronizationInfo.zul", null, args);
Window syncInfoWin = (Window) win.getFellowIfAny("syncInfoWin");
@@ -263,27 +235,23 @@ public class JobSchedulerController extends
try {
win.doModal();
- } catch (SuspendNotAllowedException e) {
- throw new RuntimeException(e);
- } catch (InterruptedException e) {
+ } catch (SuspendNotAllowedException | InterruptedException e) {
throw new RuntimeException(e);
}
}
/**
- * returns the next fire time for the specified job in
- * {@link JobSchedulerConfiguration}
+ * Returns the next fire time for the specified job in {@link JobSchedulerConfiguration}
*
* @param jobSchedulerConfiguration
* the job scheduler configuration
*/
- private String getNextFireTime(
- JobSchedulerConfiguration jobSchedulerConfiguration) {
+ private String getNextFireTime(JobSchedulerConfiguration jobSchedulerConfiguration) {
return jobSchedulerModel.getNextFireTime(jobSchedulerConfiguration);
}
/**
- * creates and returns a button
+ * Creates and returns a button
*
* @param eventListener
* Event listener for this button
@@ -292,6 +260,7 @@ public class JobSchedulerController extends
Button button = new Button(_("Manual"));
button.setTooltiptext(_("Manual"));
button.addEventListener(Events.ON_CLICK, eventListener);
+
return button;
}
@@ -309,14 +278,13 @@ public class JobSchedulerController extends
* @param jobSchedulerConfiguration
* where to read the values
*/
- private void setupCronExpressionPopup(
- final JobSchedulerConfiguration jobSchedulerConfiguration) {
+ private void setupCronExpressionPopup(final JobSchedulerConfiguration jobSchedulerConfiguration) {
if (jobSchedulerConfiguration != null) {
jobGroup.setValue(jobSchedulerConfiguration.getJobGroup());
jobName.setValue(jobSchedulerConfiguration.getJobName());
- String cronExpression = jobSchedulerConfiguration
- .getCronExpression();
+ String cronExpression = jobSchedulerConfiguration.getCronExpression();
+
if (cronExpression == null || cronExpression.isEmpty()) {
return;
}
@@ -337,8 +305,7 @@ public class JobSchedulerController extends
}
/**
- * sets the cronExpressionTextBox value from the
- * cronExpressionInputPopup
+ * Sets the cronExpressionTextBox value from the cronExpressionInputPopup
*/
public void updateCronExpression() {
String cronExpression = getCronExpressionString();
@@ -347,9 +314,9 @@ public class JobSchedulerController extends
new CronExpression(cronExpression);
} catch (ParseException e) {
LOG.info("Unable to parse cron expression", e);
- throw new WrongValueException(cronExpressionInputPopup,
- _("Unable to parse cron expression") + ":\n"
- + e.getMessage());
+
+ throw new WrongValueException(
+ cronExpressionInputPopup, _("Unable to parse cron expression") + ":\n" + e.getMessage());
}
cronExpressionTextBox.setValue(cronExpression);
cronExpressionInputPopup.close();
@@ -371,15 +338,12 @@ public class JobSchedulerController extends
cronExpression += StringUtils.trimToEmpty(cronExpressionDayOfWeek.getValue());
String year = StringUtils.trimToEmpty(cronExpressionYear.getValue());
- if (!year.isEmpty()) {
- cronExpression += " " + year;
- }
- return cronExpression;
+ return !year.isEmpty() ? cronExpression + " " + year : cronExpression;
}
/**
- * closes the popup
+ * Closes the popup
*/
public void cancelPopup() {
cronExpressionInputPopup.close();
@@ -410,8 +374,7 @@ public class JobSchedulerController extends
protected void save() throws ValidationException {
jobSchedulerModel.confirmSave();
if (jobSchedulerModel.scheduleOrUnscheduleJob()) {
- messagesForUser.showMessage(Level.INFO,
- _("Job is scheduled/unscheduled"));
+ messagesForUser.showMessage(Level.INFO, _("Job is scheduled/unscheduled"));
}
}
@@ -426,12 +389,10 @@ public class JobSchedulerController extends
}
@Override
- protected void delete(JobSchedulerConfiguration entity)
- throws InstanceNotFoundException {
+ protected void delete(JobSchedulerConfiguration entity) throws InstanceNotFoundException {
jobSchedulerModel.remove(entity);
if (jobSchedulerModel.deleteScheduledJob(entity)) {
- messagesForUser.showMessage(Level.INFO,
- _("Job is deleted from scheduler"));
+ messagesForUser.showMessage(Level.INFO, _("Job is deleted from scheduler"));
}
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/common/JobSchedulerModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/common/JobSchedulerModel.java
index 6f622a85a..d69f17a1f 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/web/common/JobSchedulerModel.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/web/common/JobSchedulerModel.java
@@ -52,7 +52,7 @@ import static org.libreplan.web.I18nHelper._;
*
* @author Manuel Rego Casasnovas
* @author Miciele Ghiorghis
- * @author Vova Perebykivskiy
+ * @author Vova Perebykivskyi
*/
@Service
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@@ -79,8 +79,6 @@ public class JobSchedulerModel implements IJobSchedulerModel {
@Autowired
private IJiraOrderElementSynchronizer jiraOrderElementSynchronizer;
- private List synchronizationInfos;
-
@Qualifier("sendEmailOnTaskAssignedToResource")
@Autowired
private IEmailNotificationJob taskAssignedToResource;
@@ -105,6 +103,8 @@ public class JobSchedulerModel implements IJobSchedulerModel {
@Autowired
private IEmailNotificationJob timesheetDataMissing;
+ private List synchronizationInfos = new ArrayList<>();
+
@Override
@Transactional(readOnly = true)
@@ -113,63 +113,77 @@ public class JobSchedulerModel implements IJobSchedulerModel {
}
@Override
- public String getNextFireTime(
- JobSchedulerConfiguration jobSchedulerConfiguration) {
+ public String getNextFireTime(JobSchedulerConfiguration jobSchedulerConfiguration) {
return schedulerManager.getNextFireTime(jobSchedulerConfiguration);
}
@Override
- public void doManual(JobSchedulerConfiguration jobSchedulerConfiguration)
- throws ConnectorException {
+ public void doManual(JobSchedulerConfiguration jobSchedulerConfiguration) throws ConnectorException {
String name = jobSchedulerConfiguration.getJobClassName().getName();
- if (name.equals(JobClassNameEnum.IMPORT_ROSTER_FROM_TIM_JOB.getName())) {
+
+ if ( name.equals(JobClassNameEnum.IMPORT_ROSTER_FROM_TIM_JOB.getName()) ) {
synchronizationInfos = importRosterFromTim.importRosters();
+
return;
}
- if (name.equals(JobClassNameEnum.EXPORT_TIMESHEET_TO_TIM_JOB.getName())) {
+
+ if ( name.equals(JobClassNameEnum.EXPORT_TIMESHEET_TO_TIM_JOB.getName()) ) {
synchronizationInfos = exportTimesheetsToTim.exportTimesheets();
+
return;
}
- if (name.equals(JobClassNameEnum.SYNC_ORDERELEMENTS_WITH_JIRA_ISSUES_JOB
- .getName())) {
- synchronizationInfos = jiraOrderElementSynchronizer
- .syncOrderElementsWithJiraIssues();
+
+ if ( name.equals(JobClassNameEnum.SYNC_ORDERELEMENTS_WITH_JIRA_ISSUES_JOB.getName()) ) {
+ synchronizationInfos = jiraOrderElementSynchronizer.syncOrderElementsWithJiraIssues();
+
return;
}
+
if ( name.equals(JobClassNameEnum.SEND_EMAIL_TASK_ASSIGNED_TO_RESOURCE.getName()) ) {
- synchronizationInfos = new ArrayList();
+ synchronizationInfos = new ArrayList<>();
synchronizationInfos.add(new SynchronizationInfo(_("Task assigned to resource emails")));
taskAssignedToResource.sendEmail();
+
return;
}
+
if ( name.equals(JobClassNameEnum.SEND_EMAIL_RESOURCE_REMOVED_FROM_TASK.getName()) ) {
- synchronizationInfos = new ArrayList();
+ synchronizationInfos = new ArrayList<>();
synchronizationInfos.add(new SynchronizationInfo(_("Resource removed from task")));
resourceRemovedFromTask.sendEmail();
+
return;
}
+
if ( name.equals(JobClassNameEnum.SEND_EMAIL_MILESTONE_REACHED.getName()) ) {
- synchronizationInfos = new ArrayList();
+ synchronizationInfos = new ArrayList<>();
synchronizationInfos.add(new SynchronizationInfo(_("Milestone reached")));
milestoneReached.sendEmail();
+
return;
}
+
if ( name.equals(JobClassNameEnum.SEND_EMAIL_TASK_SHOULD_START.getName()) ) {
- synchronizationInfos = new ArrayList();
+ synchronizationInfos = new ArrayList<>();
synchronizationInfos.add(new SynchronizationInfo(_("Task should start")));
taskShouldStart.sendEmail();
+
return;
}
+
if ( name.equals(JobClassNameEnum.SEND_EMAIL_TASK_SHOULD_FINISH.getName()) ) {
- synchronizationInfos = new ArrayList();
+ synchronizationInfos = new ArrayList<>();
synchronizationInfos.add(new SynchronizationInfo(_("Task should finish")));
taskShouldFinish.sendEmail();
+
return;
}
+
if ( name.equals(JobClassNameEnum.SEND_EMAIL_TIMESHEET_DATA_MISSING.getName()) ) {
- synchronizationInfos = new ArrayList();
+ synchronizationInfos = new ArrayList<>();
synchronizationInfos.add(new SynchronizationInfo(_("Timesheet data missing")));
timesheetDataMissing.sendEmail();
+
return;
}
@@ -211,8 +225,7 @@ public class JobSchedulerModel implements IJobSchedulerModel {
@Transactional
public void remove(JobSchedulerConfiguration jobSchedulerConfiguration) {
try {
- jobSchedulerConfigurationDAO.remove(jobSchedulerConfiguration
- .getId());
+ jobSchedulerConfigurationDAO.remove(jobSchedulerConfiguration.getId());
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
}
@@ -226,8 +239,9 @@ public class JobSchedulerModel implements IJobSchedulerModel {
@Override
public boolean scheduleOrUnscheduleJobs(Connector connector) {
- List jobSchedulerConfigurations = jobSchedulerConfigurationDAO
- .findByConnectorName(connector.getName());
+
+ List jobSchedulerConfigurations =
+ jobSchedulerConfigurationDAO.findByConnectorName(connector.getName());
for (JobSchedulerConfiguration jobSchedulerConfiguration : jobSchedulerConfigurations) {
try {
@@ -250,8 +264,7 @@ public class JobSchedulerModel implements IJobSchedulerModel {
}
@Override
- public boolean deleteScheduledJob(
- JobSchedulerConfiguration jobSchedulerConfiguration) {
+ public boolean deleteScheduledJob(JobSchedulerConfiguration jobSchedulerConfiguration) {
try {
schedulerManager.deleteJob(jobSchedulerConfiguration);
} catch (SchedulerException e) {
diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/email/EmailNotificationModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/email/EmailNotificationModel.java
index 6e29c659b..ad3f6b57c 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/web/email/EmailNotificationModel.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/web/email/EmailNotificationModel.java
@@ -40,9 +40,7 @@ import java.util.List;
/**
* Model for operations related to {@link EmailNotification}.
*
- * Created by
- * @author Vova Perebykivskiy
- * on 21.10.15.
+ * @author Created by Vova Perebykivskiy on 21.10.2015.
*/
@Service
diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/email/EmailTemplateController.java b/libreplan-webapp/src/main/java/org/libreplan/web/email/EmailTemplateController.java
index 28866de20..6197b8a10 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/web/email/EmailTemplateController.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/web/email/EmailTemplateController.java
@@ -38,22 +38,20 @@ import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.util.GenericForwardComposer;
-import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Textbox;
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
-import java.util.Comparator;
import java.util.LinkedList;
import static org.libreplan.web.I18nHelper._;
/**
- * Created by
- * @author Vova Perebykivskiy
- * on 25.09.15.
+ * Controller for page Edit email templates.
+ *
+ * @author Created by Vova Perebykivskiy on 25.09.2015.
*/
public class EmailTemplateController extends GenericForwardComposer{
@@ -73,42 +71,41 @@ public class EmailTemplateController extends GenericForwardComposer{
private Textbox subjectTextbox;
- public static ListitemRenderer languagesRenderer = new ListitemRenderer() {
- @Override
- public void render(Listitem item, Object data) throws Exception {
- Language language = (Language) data;
- String displayName = language.getDisplayName();
- item.setLabel(displayName);
- }
+ public static ListitemRenderer languagesRenderer = (item, data) -> {
+ Language language = (Language) data;
+ String displayName = language.getDisplayName();
+ item.setLabel(displayName);
};
@Override
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
+
+ // TODO resolve deprecated
comp.setVariable("emailTemplateController", this, true);
+
messages = new MessagesForUser(messagesContainer);
- // Set default template and language for user
- // And content and subject for that language & template
+ // Set default template and language for user.
+ // And content and subject for that language & template.
setUser();
- setSelectedLanguage(user.getApplicationLanguage());
+ setSelectedLanguage(Language.ENGLISH_LANGUAGE);
getContentDataBySelectedLanguage();
getSubjectDataBySelectedLanguage();
}
- public boolean save(){
+ public boolean save() {
try {
setSelectedContent();
setSelectedSubject();
emailTemplateModel.confirmSave();
messages.clearMessages();
messages.showMessage(Level.INFO, _("E-mail template saved"));
+
return true;
} catch (ValidationException e) {
messages.showInvalidValues(e);
- } catch (InstanceNotFoundException e) {
- e.printStackTrace();
}
return false;
}
@@ -121,7 +118,7 @@ public class EmailTemplateController extends GenericForwardComposer{
return emailTemplateModel.getLanguage();
}
- public void setSelectedLanguage(Language language){
+ public void setSelectedLanguage(Language language) {
emailTemplateModel.setLanguage(language);
getSubjectDataBySelectedLanguage();
@@ -132,20 +129,18 @@ public class EmailTemplateController extends GenericForwardComposer{
return languagesRenderer;
}
public List getLanguages() {
- List languages = new LinkedList(Arrays.asList(Language.values()));
- Collections.sort(languages, new Comparator() {
- @Override
- public int compare(Language o1, Language o2) {
- if (o1.equals(Language.BROWSER_LANGUAGE)) {
- return -1;
- }
- if (o2.equals(Language.BROWSER_LANGUAGE)) {
- return 1;
- }
- return o1.getDisplayName().compareTo(o2.getDisplayName());
+ List languages = new LinkedList<>(Arrays.asList(Language.values()));
+ Collections.sort(languages, (o1, o2) -> {
+ if ( o1.equals(Language.BROWSER_LANGUAGE) ) {
+ return -1;
}
+ if ( o2.equals(Language.BROWSER_LANGUAGE) ) {
+ return 1;
+ }
+ return o1.getDisplayName().compareTo(o2.getDisplayName());
});
languages.remove(0);
+
return languages;
}
@@ -153,7 +148,7 @@ public class EmailTemplateController extends GenericForwardComposer{
public EmailTemplateEnum getSelectedEmailTemplateEnum() {
return emailTemplateModel.getEmailTemplateEnum();
}
- public void setSelectedEmailTemplateEnum(EmailTemplateEnum emailTemplateEnum){
+ public void setSelectedEmailTemplateEnum(EmailTemplateEnum emailTemplateEnum) {
emailTemplateModel.setEmailTemplateEnum(emailTemplateEnum);
getSubjectDataBySelectedTemplate();
@@ -161,13 +156,10 @@ public class EmailTemplateController extends GenericForwardComposer{
}
public ListitemRenderer getEmailTemplateEnumRenderer() {
- return new ListitemRenderer() {
- @Override
- public void render(Listitem item, Object data) throws Exception {
- EmailTemplateEnum template = (EmailTemplateEnum) data;
- item.setLabel(_(template.getTemplateType()));
- item.setValue(template);
- }
+ return (item, data) -> {
+ EmailTemplateEnum template = (EmailTemplateEnum) data;
+ item.setLabel(_(template.getTemplateType()));
+ item.setValue(template);
};
}
public List getEmailTemplateEnum() {
@@ -175,30 +167,30 @@ public class EmailTemplateController extends GenericForwardComposer{
}
- public void setSelectedContent(){
+ public void setSelectedContent() {
emailTemplateModel.setContent(contentsTextbox.getValue());
}
- public void setSelectedSubject(){
+ public void setSelectedSubject() {
emailTemplateModel.setSubject(subjectTextbox.getValue());
}
- private void getContentDataBySelectedLanguage(){
- contentsTextbox.setValue(emailTemplateModel.getContentBySelectedLanguage(getSelectedLanguage().ordinal(), getSelectedEmailTemplateEnum().ordinal()));
+ private void getContentDataBySelectedLanguage() {
+ contentsTextbox.setValue(emailTemplateModel.getContent(getSelectedLanguage(), getSelectedEmailTemplateEnum()));
}
- private void getContentDataBySelectedTemplate(){
- contentsTextbox.setValue( emailTemplateModel.getContentBySelectedTemplate(getSelectedEmailTemplateEnum().ordinal(), getSelectedLanguage().ordinal()) );
+ private void getContentDataBySelectedTemplate() {
+ contentsTextbox.setValue(emailTemplateModel.getContent(getSelectedLanguage(), getSelectedEmailTemplateEnum()));
}
- private void getSubjectDataBySelectedLanguage(){
- subjectTextbox.setValue(emailTemplateModel.getSubjectBySelectedLanguage(getSelectedLanguage().ordinal(), getSelectedEmailTemplateEnum().ordinal()));
+ private void getSubjectDataBySelectedLanguage() {
+ subjectTextbox.setValue(emailTemplateModel.getSubject(getSelectedLanguage(), getSelectedEmailTemplateEnum()));
}
- private void getSubjectDataBySelectedTemplate(){
- subjectTextbox.setValue( emailTemplateModel.getSubjectBySelectedTemplate(getSelectedEmailTemplateEnum().ordinal(), getSelectedLanguage().ordinal()) );
+ private void getSubjectDataBySelectedTemplate() {
+ subjectTextbox.setValue(emailTemplateModel.getSubject(getSelectedLanguage(), getSelectedEmailTemplateEnum()));
}
@Transactional
- private void setUser(){
+ private void setUser() {
try {
user = userDAO.findByLoginName(SecurityUtils.getSessionUserLoginName());
} catch (InstanceNotFoundException e) {
diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/email/EmailTemplateModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/email/EmailTemplateModel.java
index 10a52166f..b6fe0fa4f 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/web/email/EmailTemplateModel.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/web/email/EmailTemplateModel.java
@@ -36,9 +36,7 @@ import java.util.List;
/**
* Model for operations related to {@link EmailTemplate}.
*
- * Created by
- * @author Vova Perebykivskiy
- * on 25.09.15.
+ * @author Created by Vova Perebykivskiy on 25.09.2015.
*/
@Service
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@@ -52,22 +50,31 @@ public class EmailTemplateModel implements IEmailTemplateModel {
@Override
@Transactional
- public void confirmSave() throws InstanceNotFoundException {
+ public void confirmSave() {
- /* If current EmailTemplate entity (id) is existing in DB than it needs to be updated.
- * Else current EmailTemplate entity (id) is creating and getting new values from form.
- */
+ /*
+ * If current EmailTemplate entity (id) is existing in DB than it needs to be updated.
+ * Else current EmailTemplate entity (id) is creating and getting new values from form.
+ */
List emailTemplates = emailTemplateDAO.getAll();
EmailTemplate emailTemplateFromDatabase = null;
+ boolean condition;
- for (int i = 0; i < emailTemplates.size(); i++) {
- if ( emailTemplate.getLanguage() == emailTemplates.get(i).getLanguage() &&
- emailTemplate.getType() == emailTemplates.get(i).getType() ) {
- emailTemplateFromDatabase = emailTemplateDAO.find(emailTemplates.get(i).getId());
+ for (EmailTemplate emailTemplate1 : emailTemplates) {
+
+ condition = emailTemplate.getLanguage() == emailTemplate1.getLanguage() &&
+ emailTemplate.getType() == emailTemplate1.getType();
+
+ if ( condition ) {
+ try {
+ emailTemplateFromDatabase = emailTemplateDAO.find(emailTemplate1.getId());
+ } catch (InstanceNotFoundException e) {
+ e.printStackTrace();
+ }
}
}
- if ( emailTemplateFromDatabase != null ){
+ if ( emailTemplateFromDatabase != null ) {
EmailTemplate temporaryEntity = emailTemplate;
emailTemplate = emailTemplateFromDatabase;
@@ -89,13 +96,11 @@ public class EmailTemplateModel implements IEmailTemplateModel {
}
@Override
- @Transactional
public List getAll() {
return emailTemplateDAO.getAll();
}
@Override
- @Transactional
public Language getLanguage() {
return this.emailTemplate.getLanguage();
}
@@ -113,46 +118,37 @@ public class EmailTemplateModel implements IEmailTemplateModel {
this.emailTemplate.setType(emailTemplateEnum);
}
- @Override
- public String getContent() {
- return this.emailTemplate.getContent();
- }
@Override
public void setContent(String content) {
this.emailTemplate.setContent(content);
}
- @Override
- public String getSubject() {
- return this.emailTemplate.getSubject();
- }
@Override
public void setSubject(String subject) {
this.emailTemplate.setSubject(subject);
}
@Override
- @Transactional
- public String getContentBySelectedLanguage(int languageOrdinal, int emailTemplateTypeOrdinal) {
- return emailTemplateDAO.getContentBySelectedLanguage(languageOrdinal, emailTemplateTypeOrdinal);
+ public String getContent(Language language, EmailTemplateEnum type) {
+ EmailTemplate template = getEmailTemplateByTypeAndLanguage(type, language);
+
+ return template != null ? template.getContent() : "";
}
@Override
- @Transactional
- public String getContentBySelectedTemplate(int emailTemplateTypeOrdinal, int languageOrdinal) {
- return emailTemplateDAO.getContentBySelectedTemplate(emailTemplateTypeOrdinal, languageOrdinal);
+ public String getSubject(Language language, EmailTemplateEnum type) {
+ EmailTemplate template = getEmailTemplateByTypeAndLanguage(type, language);
+
+ return template != null ? template.getSubject() : "";
+ }
+
+ public EmailTemplate getEmailTemplateByTypeAndLanguage(EmailTemplateEnum type, Language language) {
+ return emailTemplateDAO.findByTypeAndLanguage(type, language);
}
@Override
- @Transactional
- public String getSubjectBySelectedLanguage(int languageOrdinal, int emailTemplateTypeOrdinal) {
- return emailTemplateDAO.getSubjectBySelectedLanguage(languageOrdinal, emailTemplateTypeOrdinal);
- }
-
- @Override
- @Transactional
- public String getSubjectBySelectedTemplate(int emailTemplateTypeOrdinal, int languageOrdinal) {
- return emailTemplateDAO.getSubjectBySelectedTemplate(emailTemplateTypeOrdinal, languageOrdinal);
+ public void delete() {
+ emailTemplateDAO.delete(this.emailTemplate);
}
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/email/IEmailNotificationModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/email/IEmailNotificationModel.java
index 96320d94f..a6725f1ff 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/web/email/IEmailNotificationModel.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/web/email/IEmailNotificationModel.java
@@ -31,25 +31,30 @@ import java.util.List;
/**
* Contract for {@link EmailNotification}
*
- * Created by
- * @author Vova Perebykivskiy
- * on 21.10.15.
+ * @author Created by Vova Perebykivskiy on 21.10.2015.
*/
public interface IEmailNotificationModel {
void confirmSave() throws ValidationException;
List getAll();
+
List getAllByType(EmailTemplateEnum enumeration);
boolean deleteAll();
+
boolean deleteAllByType(EmailTemplateEnum enumeration);
+
boolean deleteById(EmailNotification notification);
void setType(EmailTemplateEnum type);
+
void setUpdated(Date date);
+
void setResource(Resource resource);
+
void setTask(TaskElement task);
+
void setProject(TaskElement project);
EmailNotification getEmailNotification();
diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/email/IEmailTemplateModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/email/IEmailTemplateModel.java
index 0393363d5..cfdf24edf 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/web/email/IEmailTemplateModel.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/web/email/IEmailTemplateModel.java
@@ -19,8 +19,6 @@
package org.libreplan.web.email;
-import org.libreplan.business.common.exceptions.InstanceNotFoundException;
-import org.libreplan.business.common.exceptions.ValidationException;
import org.libreplan.business.email.entities.EmailTemplate;
import org.libreplan.business.settings.entities.Language;
import org.libreplan.business.email.entities.EmailTemplateEnum;
@@ -30,31 +28,31 @@ import java.util.List;
/**
* Contract for {@link EmailTemplate}
*
- * Created by
- * @author Vova Perebykivskiy
- * on 28.09.2015.
+ * @author Created by Vova Perebykivskyi on 28.09.2015.
*/
public interface IEmailTemplateModel {
- void confirmSave() throws ValidationException, InstanceNotFoundException;
+ void confirmSave();
List getAll();
- String getContentBySelectedLanguage(int languageOrdinal, int emailTemplateTypeOrdinal);
- String getContentBySelectedTemplate(int emailTemplateTypeOrdinal, int languageOrdinal);
+ String getContent(Language language, EmailTemplateEnum emailTemplateEnum);
- String getSubjectBySelectedLanguage(int languageOrdinal, int emailTemplateTypeOrdinal);
- String getSubjectBySelectedTemplate(int emailTemplateTypeOrdinal, int languageOrdinal);
-
- String getContent();
+ String getSubject(Language language, EmailTemplateEnum emailTemplateEnum);
+
void setContent(String content);
Language getLanguage();
+
void setLanguage(Language language);
EmailTemplateEnum getEmailTemplateEnum();
+
void setEmailTemplateEnum(EmailTemplateEnum emailTemplateEnum);
- String getSubject();
void setSubject(String subject);
+
+ EmailTemplate getEmailTemplateByTypeAndLanguage(EmailTemplateEnum emailTemplateEnum, Language language);
+
+ void delete();
}
diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/orders/AssignedTaskQualityFormsToOrderElementModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/orders/AssignedTaskQualityFormsToOrderElementModel.java
index 1928205a0..809e5a942 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/web/orders/AssignedTaskQualityFormsToOrderElementModel.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/web/orders/AssignedTaskQualityFormsToOrderElementModel.java
@@ -52,7 +52,7 @@ import org.springframework.transaction.annotation.Transactional;
/**
* @author Susana Montes Pedreira
- * @author Vova Perebykivskiy
+ * @author Vova Perebykivskyi
*/
@Service
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@@ -116,15 +116,11 @@ public class AssignedTaskQualityFormsToOrderElementModel implements IAssignedTas
@Override
public List getNotAssignedQualityForms() {
- List result = new ArrayList();
- if ( orderElement != null ) {
- return getListNotAssignedQualityForms();
- }
- return result;
+ return orderElement != null ? getListNotAssignedQualityForms() : new ArrayList<>();
}
private List getListNotAssignedQualityForms() {
- List result = new ArrayList();
+ List result = new ArrayList<>();
for (QualityForm qualityForm : orderModel.getQualityForms()) {
if ( !isAssigned(qualityForm) ) {
result.add(qualityForm);
@@ -135,7 +131,7 @@ public class AssignedTaskQualityFormsToOrderElementModel implements IAssignedTas
@Override
public List getAssignedQualityForms() {
- List result = new ArrayList();
+ List result = new ArrayList<>();
for (QualityForm qualityForm : qualityFormDAO.getAll()) {
if ( isAssigned(qualityForm) ) {
result.add(qualityForm);
@@ -146,7 +142,7 @@ public class AssignedTaskQualityFormsToOrderElementModel implements IAssignedTas
@Override
public List getTaskQualityForms() {
- List result = new ArrayList();
+ List result = new ArrayList<>();
if ( orderElement != null ) {
result.addAll(orderElement.getTaskQualityForms());
}
@@ -176,10 +172,10 @@ public class AssignedTaskQualityFormsToOrderElementModel implements IAssignedTas
@Override
public boolean isAssigned(QualityForm qualityForm) {
- // orderDAO used for gathered data to be sent to LibrePlan server
- // In general case orderElement will be not null and only that part of code will be triggered
+ // orderDAO used for gathered data to be sent to LibrePlan server.
+ // In general case orderElement will be not null and only that part of code will be triggered.
- if ( orderElement != null ){
+ if ( orderElement != null ) {
for (TaskQualityForm taskQualityForm : orderElement.getTaskQualityForms()) {
if ( qualityForm.equals(taskQualityForm.getQualityForm()) ) {
return true;
@@ -203,37 +199,27 @@ public class AssignedTaskQualityFormsToOrderElementModel implements IAssignedTas
}
public boolean isDisabledPassedItem(TaskQualityForm taskQualityForm, TaskQualityFormItem item) {
- if ( (taskQualityForm == null) || ((item == null)) ) {
- return true;
- }
- if ( !taskQualityForm.isByItems() ) {
- return (!(item.getPassed() || taskQualityForm.isPassedPreviousItem(item)));
- }
- return false;
+ return (taskQualityForm == null) ||
+ (item == null) ||
+ !taskQualityForm.isByItems() && !(item.getPassed() ||
+ taskQualityForm.isPassedPreviousItem(item));
}
public boolean isDisabledDateItem(TaskQualityForm taskQualityForm, TaskQualityFormItem item) {
- if ( (taskQualityForm == null) || ((item == null)) ) {
- return true;
- }
- return (!taskQualityForm.isByItems() && (!item.getPassed()));
+ return (taskQualityForm == null) || (item == null) || !taskQualityForm.isByItems() && !item.getPassed();
}
public boolean isCorrectConsecutiveDate(TaskQualityForm taskQualityForm, TaskQualityFormItem item) {
- if ( (taskQualityForm == null) || ((item == null)) ) {
- return true;
- }
- if ( taskQualityForm.isByItems() ) {
- return true;
- }
- return (taskQualityForm.isCorrectConsecutiveDate(item));
+ return (taskQualityForm == null) ||
+ (item == null) ||
+ taskQualityForm.isByItems() ||
+ taskQualityForm.isCorrectConsecutiveDate(item);
}
public void updatePassedTaskQualityFormItems(TaskQualityForm taskQualityForm) {
if (taskQualityForm != null) {
Integer position = getFirstNotPassedPosition(taskQualityForm);
- List items = taskQualityForm
- .getTaskQualityFormItems();
+ List items = taskQualityForm.getTaskQualityFormItems();
for (int i = position; i < items.size(); i++) {
items.get(i).setPassed(false);
items.get(i).setDate(null);
@@ -243,8 +229,7 @@ public class AssignedTaskQualityFormsToOrderElementModel implements IAssignedTas
private Integer getFirstNotPassedPosition(TaskQualityForm taskQualityForm) {
Integer position = 0;
- for (TaskQualityFormItem item : taskQualityForm
- .getTaskQualityFormItems()) {
+ for (TaskQualityFormItem item : taskQualityForm.getTaskQualityFormItems()) {
if (!item.getPassed()) {
return position;
}
@@ -254,12 +239,10 @@ public class AssignedTaskQualityFormsToOrderElementModel implements IAssignedTas
}
// Operation to confirm and validate
-
@Override
public void validate() {
if (getOrderElement() != null) {
- for (TaskQualityForm taskQualityForm : orderElement
- .getTaskQualityForms()) {
+ for (TaskQualityForm taskQualityForm : orderElement.getTaskQualityForms()) {
validateTaskQualityForm(taskQualityForm);
}
}
@@ -270,19 +253,15 @@ public class AssignedTaskQualityFormsToOrderElementModel implements IAssignedTas
}
private void validateTaskQualityFormItems(TaskQualityForm taskQualityForm) {
- for (TaskQualityFormItem item : taskQualityForm
- .getTaskQualityFormItems()) {
+ for (TaskQualityFormItem item : taskQualityForm.getTaskQualityFormItems()) {
- if ((!taskQualityForm.isByItems())
- && (!taskQualityForm.isCorrectConsecutivePassed(item))) {
- throw new ValidationException(
- invalidValue(
+ if ( (!taskQualityForm.isByItems()) && (!taskQualityForm.isCorrectConsecutivePassed(item)) ) {
+ throw new ValidationException(invalidValue(
_("cannot be checked until the previous item is checked before"),
"passed", item.getName(), taskQualityForm));
}
- if ((!taskQualityForm.isByItems())
- && (!taskQualityForm.isCorrectConsecutiveDate(item))) {
+ if ( (!taskQualityForm.isByItems()) && (!taskQualityForm.isCorrectConsecutiveDate(item)) ) {
throw new ValidationException(invalidValue(
_("must be after the previous date"),
"date", item.getName(), taskQualityForm));
@@ -299,8 +278,7 @@ public class AssignedTaskQualityFormsToOrderElementModel implements IAssignedTas
@Override
@Transactional(readOnly = true)
public void addAdvanceAssignmentIfNeeded(TaskQualityForm taskQualityForm)
- throws DuplicateValueTrueReportGlobalAdvanceException,
- DuplicateAdvanceAssignmentForOrderElementException {
+ throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
AdvanceType advanceType = taskQualityForm.getQualityForm().getAdvanceType();
advanceTypeDAO.reattach(advanceType);
@@ -340,8 +318,7 @@ public class AssignedTaskQualityFormsToOrderElementModel implements IAssignedTas
}
private void showMessageDeleteSpread() throws ValidationException {
- throw new ValidationException(
- _("Quality form cannot be removed as it is spreading progress"));
+ throw new ValidationException(_("Quality form cannot be removed as it is spreading progress"));
}
@Override
diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/orders/IAssignedTaskQualityFormsToOrderElementModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/orders/IAssignedTaskQualityFormsToOrderElementModel.java
index fc443c7c7..b5fae0937 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/web/orders/IAssignedTaskQualityFormsToOrderElementModel.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/web/orders/IAssignedTaskQualityFormsToOrderElementModel.java
@@ -33,33 +33,31 @@ import org.libreplan.business.qualityforms.entities.TaskQualityFormItem;
/**
* @author Susana Montes Pedreira
- * @author Vova Perebykivskiy
+ * @author Vova Perebykivskyi
*/
public interface IAssignedTaskQualityFormsToOrderElementModel {
/**
- * Assigns {@link TaskQualityForm} to {@link OrderElement}
+ * Assigns {@link TaskQualityForm} to {@link OrderElement}.
* @param @ QualityForm}
*/
void assignTaskQualityForm(QualityForm qualityForm);
/**
- * Delete {@link TaskQualityForm}
+ * Delete {@link TaskQualityForm}.
* @param taskQualityForm
*/
void deleteTaskQualityForm(TaskQualityForm taskQualityForm);
/**
- * Gets all {@link TaskQualityForm} assigned to the current
- * {@link OrderElement}
- * @return
+ * Gets all {@link TaskQualityForm} assigned to the current {@link OrderElement}.
+ * @return {@link List}
*/
List getTaskQualityForms();
/**
- * Returns all the unallocated {@link QualityForm} to the current
- * {@link OrderElement}
- * @return
+ * Returns all the unallocated {@link QualityForm} to the current {@link OrderElement}.
+ * @return {@link List}
*/
List getNotAssignedQualityForms();
@@ -69,22 +67,20 @@ public interface IAssignedTaskQualityFormsToOrderElementModel {
List getAssignedQualityForms();
/**
- * Returns {@link OrderElement}
- * @return
+ * @return {@link OrderElement}
*/
OrderElement getOrderElement();
void init(OrderElement orderElement);
/**
- * Check whether {@link QualityForm} has been already assigned to
- * {@link OrderElement} or not
+ * Check whether {@link QualityForm} has been already assigned to {@link OrderElement} or not.
* @param qualityForm
*/
boolean isAssigned(QualityForm qualityForm);
/**
- * Set {@link OrderElement}
+ * Set {@link OrderElement}.
* @param orderElement
*/
void setOrderElement(OrderElement orderElement);
@@ -95,47 +91,36 @@ public interface IAssignedTaskQualityFormsToOrderElementModel {
void setOrderModel(IOrderModel orderModel);
/**
- * Update the date and the property passed of all the
- * {@link TaskQualityFormItem} of the {@ TaskQualityForm}
+ * Update the date and the property passed of all the {@link TaskQualityFormItem} of the {@link TaskQualityForm}.
* @param taskQualityForm
*/
void updatePassedTaskQualityFormItems(TaskQualityForm taskQualityForm);
/**
- * Check whether {@link QualityFormItem} the property passed must be
- * disabled
- * @param taskQualityForm
- * ,item
+ * Check whether {@link QualityFormItem} the property passed must be disabled.
+ * @param taskQualityForm, item
*/
- boolean isDisabledPassedItem(TaskQualityForm taskQualityForm,
- TaskQualityFormItem item);
+ boolean isDisabledPassedItem(TaskQualityForm taskQualityForm, TaskQualityFormItem item);
/**
- * Check whether {@link QualityFormItem} date must be disabled
- * @param taskQualityForm
- * ,item
+ * Check whether {@link QualityFormItem} date must be disabled.
+ * @param taskQualityForm, item
*/
- boolean isDisabledDateItem(TaskQualityForm taskQualityForm,
- TaskQualityFormItem item);
+ boolean isDisabledDateItem(TaskQualityForm taskQualityForm, TaskQualityFormItem item);
/**
- * Check whether {@link QualityFormItem} date is consecutive
- * @param taskQualityForm
- * ,item
+ * Check whether {@link QualityFormItem} date is consecutive.
+ * @param taskQualityForm, item
*/
- boolean isCorrectConsecutiveDate(TaskQualityForm taskQualityForm,
- TaskQualityFormItem item);
+ boolean isCorrectConsecutiveDate(TaskQualityForm taskQualityForm, TaskQualityFormItem item);
/**
- * Check whether all {@link QualityForm} and its {@link QualityFormItem} are
- * valid.
- * @param
+ * Check whether all {@link QualityForm} and its {@link QualityFormItem} are valid.
*/
void validate();
void addAdvanceAssignmentIfNeeded(TaskQualityForm taskQualityForm)
- throws DuplicateValueTrueReportGlobalAdvanceException,
- DuplicateAdvanceAssignmentForOrderElementException;
+ throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException;
void removeAdvanceAssignmentIfNeeded(TaskQualityForm taskQualityForm);
diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/planner/allocation/ResourceAllocationController.java b/libreplan-webapp/src/main/java/org/libreplan/web/planner/allocation/ResourceAllocationController.java
index ffd93e9eb..14e77eb5e 100644
--- a/libreplan-webapp/src/main/java/org/libreplan/web/planner/allocation/ResourceAllocationController.java
+++ b/libreplan-webapp/src/main/java/org/libreplan/web/planner/allocation/ResourceAllocationController.java
@@ -48,7 +48,6 @@ import org.libreplan.web.common.components.AllocationSelector;
import org.libreplan.web.common.components.NewAllocationSelector;
import org.libreplan.web.common.components.NewAllocationSelectorCombo;
import org.libreplan.web.common.components.ResourceAllocationBehaviour;
-import org.libreplan.web.planner.allocation.TaskInformation.ITotalHoursCalculationListener;
import org.libreplan.web.planner.order.PlanningStateCreator.PlanningState;
import org.libreplan.web.planner.taskedition.EditTaskController;
import org.libreplan.web.planner.taskedition.TaskPropertiesController;
@@ -61,7 +60,6 @@ import org.zkoss.ganttz.timetracker.OnColumnsRowRenderer;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
-import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Button;
@@ -88,7 +86,7 @@ import org.zkoss.zul.Window;
* @author Manuel Rego Casasnovas
* @author Diego Pino Garcia
* @author Javier Moran Rua
- * @author Vova Perebykivskiy
+ * @author Vova Perebykivskyi
*/
@org.springframework.stereotype.Component("resourceAllocationController")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@@ -117,10 +115,13 @@ public class ResourceAllocationController extends GenericForwardComposer {
private Decimalbox allResourcesPerDay;
private Label allOriginalEffort;
+
private Label allTotalEffort;
+
private Label allConsolidatedEffort;
private Label allTotalResourcesPerDay;
+
private Label allConsolidatedResourcesPerDay;
private Button applyButton;
@@ -172,12 +173,15 @@ public class ResourceAllocationController extends GenericForwardComposer {
}
/**
- * Shows Resource Allocation window
+ * Shows Resource Allocation window.
+ * @param context
* @param task
- * @param ganttTask
* @param planningState
+ * @param messagesForUser
*/
- public void init(IContextWithPlannerTask context, Task task, PlanningState planningState,
+ public void init(IContextWithPlannerTask context,
+ Task task,
+ PlanningState planningState,
IMessagesForUser messagesForUser) {
try {
if ( formBinder != null ) {
@@ -240,13 +244,7 @@ public class ResourceAllocationController extends GenericForwardComposer {
private void initializeTaskInformationComponent() {
taskInformation.initializeGridTaskRows(resourceAllocationModel.getHoursAggregatedByCriterions());
formBinder.setRecommendedAllocation(taskInformation.getBtnRecommendedAllocation());
- taskInformation.onCalculateTotalHours(new ITotalHoursCalculationListener() {
-
- @Override
- public Integer getTotalHours() {
- return resourceAllocationModel.getOrderHours();
- }
- });
+ taskInformation.onCalculateTotalHours(() -> resourceAllocationModel.getOrderHours());
}
private void initializeAllocationConfigurationComponent() {
@@ -261,18 +259,18 @@ public class ResourceAllocationController extends GenericForwardComposer {
return new Label(data.getCriterionsJoinedByComma());
}
},
- RESOURCE_TYPE{
+ RESOURCE_TYPE{
@Override
public Component cell(HoursRendererColumn column, AggregatedHoursGroup data) {
return new Label(asString(data.getResourceType()));
}
},
+
HOURS {
@Override
public Component cell(HoursRendererColumn column, AggregatedHoursGroup data) {
- Label result = new Label(Integer.toString(data.getHours()));
- return result;
+ return new Label(Integer.toString(data.getHours()));
}
};
@@ -286,6 +284,7 @@ public class ResourceAllocationController extends GenericForwardComposer {
default:
LOG.warn("no i18n for " + resourceType.name());
+
return resourceType.name();
}
}
@@ -294,8 +293,7 @@ public class ResourceAllocationController extends GenericForwardComposer {
}
/**
- * Pick resources selected from {@link NewAllocationSelector} and add them to
- * resource allocation list
+ * Pick resources selected from {@link NewAllocationSelector} and add them to resource allocation list.
*
* @param e
*/
@@ -305,8 +303,12 @@ public class ResourceAllocationController extends GenericForwardComposer {
} finally {
// For email notification feature
int rowsSize = allocationRows.getCurrentRows().size();
- editTaskController.getTaskPropertiesController().listToAdd
+
+ editTaskController
+ .getTaskPropertiesController()
+ .getListToAdd()
.add(allocationRows.getCurrentRows().get(rowsSize - 1).getAssociatedResources().get(0));
+
editTaskController.getTaskPropertiesController().setResourcesAdded(true);
tbResourceAllocation.setSelected(true);
@@ -320,15 +322,13 @@ public class ResourceAllocationController extends GenericForwardComposer {
applyButton.setVisible(false);
workerSearchTab.setSelected(true);
- LocalDate start = LocalDate
- .fromDateFields(resourceAllocationModel.getTaskStart());
- LocalDate end = LocalDate
- .fromDateFields(resourceAllocationModel.getTaskEnd());
+ LocalDate start = LocalDate.fromDateFields(resourceAllocationModel.getTaskStart());
+ LocalDate end = LocalDate.fromDateFields(resourceAllocationModel.getTaskEnd());
newAllocationSelector.open(start, end);
}
/**
- * Shows the extended view of the resources allocations
+ * Shows the extended view of the resources allocations.
*/
public void onCheckExtendedView() {
if (isExtendedView()) {
@@ -345,21 +345,14 @@ public class ResourceAllocationController extends GenericForwardComposer {
}
public int getColspanHours() {
- if (isExtendedView()) {
- return 4;
- }
- return 1;
+ return isExtendedView() ? 4 : 1;
}
public int getColspanResources() {
- if (isExtendedView()) {
- return 3;
- }
- return 1;
+ return isExtendedView() ? 3 : 1;
}
/**
- * Close search worker in worker search tab
- * @param e
+ * Close search worker in worker search tab.
*/
public void onCloseSelectWorkers() {
tbResourceAllocation.setSelected(true);
@@ -380,6 +373,7 @@ public class ResourceAllocationController extends GenericForwardComposer {
return resourceAllocationController.getTaskWorkableDays();
}
},
+
NUMBER_OF_HOURS(CalculatedValue.NUMBER_OF_HOURS) {
@Override
public String getName() {
@@ -392,8 +386,8 @@ public class ResourceAllocationController extends GenericForwardComposer {
return resourceAllocationController.assignedEffortComponent;
}
},
- RESOURCES_PER_DAY(CalculatedValue.RESOURCES_PER_DAY) {
+ RESOURCES_PER_DAY(CalculatedValue.RESOURCES_PER_DAY) {
@Override
public String getName() {
return _("Calculate Resources per Day");
@@ -406,36 +400,34 @@ public class ResourceAllocationController extends GenericForwardComposer {
}
};
+ private final CalculatedValue calculatedValue;
+
+ CalculationTypeRadio(CalculatedValue calculatedValue) {
+ this.calculatedValue = calculatedValue;
+
+ }
+
public static CalculationTypeRadio from(CalculatedValue calculatedValue) {
Validate.notNull(calculatedValue);
- for (CalculationTypeRadio calculationTypeRadio : CalculationTypeRadio
- .values()) {
+ for (CalculationTypeRadio calculationTypeRadio : CalculationTypeRadio.values()) {
if (calculationTypeRadio.getCalculatedValue() == calculatedValue) {
return calculationTypeRadio;
}
}
- throw new RuntimeException("not found "
- + CalculationTypeRadio.class.getSimpleName() + " for "
- + calculatedValue);
+ throw new RuntimeException(
+ "not found " + CalculationTypeRadio.class.getSimpleName() + " for " + calculatedValue);
}
- public abstract Component input(
- ResourceAllocationController resourceAllocationController);
+ public abstract Component input(ResourceAllocationController resourceAllocationController);
public Radio createRadio() {
Radio result = new Radio();
result.setLabel(getName());
result.setValue(toString());
+
return result;
}
- private final CalculatedValue calculatedValue;
-
- private CalculationTypeRadio(CalculatedValue calculatedValue) {
- this.calculatedValue = calculatedValue;
-
- }
-
public abstract String getName();
public CalculatedValue getCalculatedValue() {
@@ -451,32 +443,37 @@ public class ResourceAllocationController extends GenericForwardComposer {
return new Label(data.getName());
}
},
+
ALPHA(_("Alpha")) {
@Override
public Component cellFor(DerivedAllocation data) {
return new Label(String.format("%3.2f", data.getAlpha()));
}
},
+
HOURS(_("Total Hours")) {
@Override
public Component cellFor(DerivedAllocation data) {
- return new Label(data.getHours() + "");
+ return new Label(Integer.toString(data.getHours()));
}
};
+ private final String name;
+
+ private static final ICellForDetailItemRenderer cellRenderer =
+ (column, data) -> column.cellFor(data);
+
+ DerivedAllocationColumn(String name) {
+ this.name = name;
+ }
+
/**
- * Forces to mark the string as needing translation
+ * Forces to mark the string as needing translation.
*/
private static String _(String string) {
return string;
}
- private final String name;
-
- private DerivedAllocationColumn(String name) {
- this.name = name;
- }
-
public String getName() {
return I18nHelper._(name);
}
@@ -489,26 +486,16 @@ public class ResourceAllocationController extends GenericForwardComposer {
public static void appendColumnsTo(Grid grid) {
Columns columns = new Columns();
grid.appendChild(columns);
+
for (DerivedAllocationColumn each : values()) {
columns.appendChild(each.toColumn());
}
}
public static RowRenderer createRenderer() {
- return OnColumnsRowRenderer.create(cellRenderer, Arrays
- .asList(DerivedAllocationColumn.values()));
+ return OnColumnsRowRenderer.create(cellRenderer, Arrays.asList(DerivedAllocationColumn.values()));
}
- private static final ICellForDetailItemRenderer cellRenderer= new ICellForDetailItemRenderer() {
-
- @Override
- public Component cellFor(
- DerivedAllocationColumn column,
- DerivedAllocation data) {
- return column.cellFor(data);
- }
- };
-
abstract Component cellFor(DerivedAllocation data);
}
@@ -516,15 +503,16 @@ public class ResourceAllocationController extends GenericForwardComposer {
return Arrays.asList(CalculationTypeRadio.values());
}
- public List extends Object> getResourceAllocations() {
- return formBinder != null ? plusAggregatingRow(formBinder
- .getCurrentRows()) : Collections
- . emptyList();
+ public List> getResourceAllocations() {
+ return formBinder != null
+ ? plusAggregatingRow(formBinder.getCurrentRows())
+ : Collections. emptyList();
}
private List