From 7deb1c473cbadf65b6a09d2f522475db0bd0c07c Mon Sep 17 00:00:00 2001 From: Olivier Maury <Olivier.Maury@inrae.fr> Date: Mon, 2 Dec 2024 18:46:39 +0100 Subject: [PATCH 1/6] Eclipse : organize imports --- .gitignore | 1 + .../java/fr/agrometinfo/www/client/App.java | 2 +- .../www/client/presenter/SurveyPresenter.java | 12 ++--- .../www/client/util/color/ScaleType.java | 2 + .../www/client/view/SurveyView.java | 6 +-- .../agrometinfo/www/server/StartListener.java | 5 +- .../www/server/dao/SurveyOptionDao.java | 4 +- .../www/server/dao/UserResponsesDao.java | 2 +- .../server/dao/UserResponsesDaoHibernate.java | 2 +- .../www/server/rs/ApplicationConfig.java | 3 +- .../www/server/rs/UserResource.java | 46 ------------------- .../www/server/service/MailService.java | 3 +- .../www/server/service/MailServiceImpl.java | 29 ++++++------ .../www/server/SurveyFormHibernateTest.java | 6 +-- .../dao/PraDailyValueDaoHibernateTest.java | 4 +- .../www/server/rs/GeometryResourceTest.java | 4 +- .../www/server/rs/SurveyFormResourceTest.java | 20 ++++---- 17 files changed, 50 insertions(+), 101 deletions(-) delete mode 100644 www-server/src/main/java/fr/agrometinfo/www/server/rs/UserResource.java diff --git a/.gitignore b/.gitignore index cf83f91b..51fcf403 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,7 @@ nb-configuration.xml *.swp /target/ tokei +.vscode/ war/ /www-client/gwt-unitCache/ /www-client/target/ diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/App.java b/www-client/src/main/java/fr/agrometinfo/www/client/App.java index 542e4c03..029b3cd7 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/App.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/App.java @@ -20,9 +20,9 @@ import elemental2.dom.DomGlobal; import fr.agrometinfo.www.client.i18n.AppConstants; import fr.agrometinfo.www.client.i18n.AppMessages; import fr.agrometinfo.www.client.presenter.LayoutPresenter; +import fr.agrometinfo.www.client.presenter.SurveyPresenter; import fr.agrometinfo.www.client.util.ApplicationUtils; import fr.agrometinfo.www.shared.service.ApplicationServiceFactory; -import fr.agrometinfo.www.client.presenter.SurveyPresenter; /** * Entry point classes define <code>onModuleLoad()</code>. diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/SurveyPresenter.java b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/SurveyPresenter.java index 00b81aa2..bfc75e7a 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/SurveyPresenter.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/SurveyPresenter.java @@ -1,7 +1,11 @@ package fr.agrometinfo.www.client.presenter; import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; +import java.util.Set; import org.dominokit.rest.shared.request.FailedResponseBean; @@ -9,17 +13,11 @@ import com.google.gwt.core.client.GWT; import fr.agrometinfo.www.client.view.BaseView; import fr.agrometinfo.www.client.view.SurveyView; -import fr.agrometinfo.www.shared.dto.SurveyQuestionDTO; import fr.agrometinfo.www.shared.dto.SurveyOptionDTO; +import fr.agrometinfo.www.shared.dto.SurveyQuestionDTO; import fr.agrometinfo.www.shared.dto.SurveyResponseDTO; import fr.agrometinfo.www.shared.service.SurveyFormServiceFactory; -import java.util.HashMap; -import java.util.Map; - -import java.util.LinkedHashSet; -import java.util.Set; - /** * Presenter for survey form. * diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/util/color/ScaleType.java b/www-client/src/main/java/fr/agrometinfo/www/client/util/color/ScaleType.java index 0dcc6d99..1ba8377b 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/util/color/ScaleType.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/util/color/ScaleType.java @@ -1,5 +1,7 @@ package fr.agrometinfo.www.client.util.color; +import fr.agrometinfo.www.client.i18n.AppConstants; + /** * The user can choice the color scale : linear or quantile. * diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/view/SurveyView.java b/www-client/src/main/java/fr/agrometinfo/www/client/view/SurveyView.java index 61f2fe19..0a4e677d 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/view/SurveyView.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/view/SurveyView.java @@ -1,10 +1,10 @@ package fr.agrometinfo.www.client.view; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import java.util.ArrayList; -import java.util.HashMap; import org.dominokit.domino.ui.button.Button; import org.dominokit.domino.ui.forms.CheckBox; @@ -21,8 +21,8 @@ import com.google.gwt.storage.client.Storage; import fr.agrometinfo.www.client.i18n.AppConstants; import fr.agrometinfo.www.client.presenter.SurveyPresenter; -import fr.agrometinfo.www.shared.dto.SurveyQuestionDTO; import fr.agrometinfo.www.shared.dto.SurveyOptionDTO; +import fr.agrometinfo.www.shared.dto.SurveyQuestionDTO; /** * View for survey form. diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/StartListener.java b/www-server/src/main/java/fr/agrometinfo/www/server/StartListener.java index ea68d6b2..832d6f93 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/StartListener.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/StartListener.java @@ -1,5 +1,8 @@ package fr.agrometinfo.www.server; +import java.time.LocalDateTime; +import java.util.List; + import fr.agrometinfo.www.server.exception.AgroMetInfoException; import fr.agrometinfo.www.server.service.MailService; import fr.agrometinfo.www.server.util.AppVersion; @@ -7,8 +10,6 @@ import jakarta.inject.Inject; import jakarta.servlet.ServletContextEvent; import jakarta.servlet.ServletContextListener; import jakarta.servlet.annotation.WebListener; -import java.time.LocalDateTime; -import java.util.List; import lombok.extern.log4j.Log4j2; /** diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/dao/SurveyOptionDao.java b/www-server/src/main/java/fr/agrometinfo/www/server/dao/SurveyOptionDao.java index 214e608a..81b54b4f 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/dao/SurveyOptionDao.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/dao/SurveyOptionDao.java @@ -1,9 +1,9 @@ package fr.agrometinfo.www.server.dao; -import fr.agrometinfo.www.server.model.SurveyOption; - import java.util.List; +import fr.agrometinfo.www.server.model.SurveyOption; + /** * DAO for {@link SurveyOption}. * @author jdecome diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserResponsesDao.java b/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserResponsesDao.java index 3a364db7..89640b9b 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserResponsesDao.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserResponsesDao.java @@ -3,8 +3,8 @@ package fr.agrometinfo.www.server.dao; import java.time.LocalDateTime; import java.util.List; -import fr.agrometinfo.www.server.model.SurveyQuestion; import fr.agrometinfo.www.server.model.SurveyOption; +import fr.agrometinfo.www.server.model.SurveyQuestion; import fr.agrometinfo.www.server.model.UserResponse; /** * DAO for {@link UserResponse}. diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserResponsesDaoHibernate.java b/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserResponsesDaoHibernate.java index 01cd1ff5..104fbdd8 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserResponsesDaoHibernate.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserResponsesDaoHibernate.java @@ -4,8 +4,8 @@ import java.time.LocalDateTime; import java.util.List; import java.util.Map; -import fr.agrometinfo.www.server.model.SurveyQuestion; import fr.agrometinfo.www.server.model.SurveyOption; +import fr.agrometinfo.www.server.model.SurveyQuestion; import fr.agrometinfo.www.server.model.UserResponse; import jakarta.enterprise.context.ApplicationScoped; diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/rs/ApplicationConfig.java b/www-server/src/main/java/fr/agrometinfo/www/server/rs/ApplicationConfig.java index b6ff6d45..d3a446c4 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/rs/ApplicationConfig.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/rs/ApplicationConfig.java @@ -44,8 +44,7 @@ public class ApplicationConfig extends Application { JacksonConfig.class, // JAX-RS resources ApplicationResource.class, GeometryResource.class, IndicatorResource.class, - SurveyFormResource.class, UserResource.class, - // POJO + SurveyFormResource.class, // Dependencies of resources LogFilter.class // - diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/rs/UserResource.java b/www-server/src/main/java/fr/agrometinfo/www/server/rs/UserResource.java deleted file mode 100644 index eb145b03..00000000 --- a/www-server/src/main/java/fr/agrometinfo/www/server/rs/UserResource.java +++ /dev/null @@ -1,46 +0,0 @@ -package fr.agrometinfo.www.server.rs; - -import fr.agrometinfo.www.server.SessionAttribute; -import jakarta.enterprise.context.RequestScoped; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpSession; -import jakarta.ws.rs.GET; -import jakarta.ws.rs.Path; -import jakarta.ws.rs.Produces; -import jakarta.ws.rs.core.Context; -import jakarta.ws.rs.core.MediaType; -import lombok.extern.log4j.Log4j2; - -/** - * Resource to handle user. - * - * @author Olivier Maury - */ -@Log4j2 -@Path("user") -@RequestScoped -public class UserResource { - - /** - * Information for HTTP servlet. - */ - @Context - private HttpServletRequest httpServletRequest; - - /** - * @return if the user is authenticated - */ - @GET - @Produces(MediaType.APPLICATION_JSON) - @Path("authenticated") - public final Boolean isAuthenticated() { - LOGGER.traceEntry(); - final HttpSession session = httpServletRequest.getSession(); - if (session == null) { - return false; - } - final Object attribute = session.getAttribute(SessionAttribute.AUTHENTICATED.name()); - return Boolean.TRUE.equals(attribute); - } - -} diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/service/MailService.java b/www-server/src/main/java/fr/agrometinfo/www/server/service/MailService.java index aad093ce..ce516c5f 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/service/MailService.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/service/MailService.java @@ -1,7 +1,8 @@ package fr.agrometinfo.www.server.service; -import fr.agrometinfo.www.server.exception.AgroMetInfoException; import java.util.List; + +import fr.agrometinfo.www.server.exception.AgroMetInfoException; import lombok.Data; /** diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/service/MailServiceImpl.java b/www-server/src/main/java/fr/agrometinfo/www/server/service/MailServiceImpl.java index 2fd35c33..f656068f 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/service/MailServiceImpl.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/service/MailServiceImpl.java @@ -8,7 +8,6 @@ import java.util.StringJoiner; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; - import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.Layout; @@ -26,6 +25,8 @@ import fr.agrometinfo.www.server.exception.AgroMetInfoException; import fr.agrometinfo.www.server.exception.ErrorCategory; import fr.agrometinfo.www.server.exception.ErrorType; import jakarta.annotation.PostConstruct; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; import jakarta.mail.Address; import jakarta.mail.Authenticator; import jakarta.mail.Message; @@ -37,9 +38,6 @@ import jakarta.mail.Transport; import jakarta.mail.internet.InternetAddress; import jakarta.mail.internet.MimeMessage; import lombok.Getter; -import lombok.extern.log4j.Log4j2; -import jakarta.enterprise.context.ApplicationScoped; -import jakarta.inject.Inject; /** * Service to send e-mails. @@ -47,7 +45,6 @@ import jakarta.inject.Inject; * @author Olivier Maury */ @ApplicationScoped -@Log4j2 public class MailServiceImpl implements MailService { /** @@ -75,14 +72,14 @@ public class MailServiceImpl implements MailService { @Override public void append(final LogEvent event) { - Mail mail = new Mail(); + final Mail mail = new Mail(); mail.setFromAddress("agrometinfo@inrae.fr"); mail.setSubject("AgroMetInfo - error log"); mail.setContent(super.toSerializable(event).toString()); mail.setToAddresses(List.of(configuration.get(ConfigurationKey.LOG_EMAIL))); try { send(mail); - } catch (AgroMetInfoException e) { + } catch (final AgroMetInfoException e) { // do nothing LOGGER.info("Cannot send email: {}", e.getMessage()); } @@ -153,7 +150,7 @@ public class MailServiceImpl implements MailService { */ @PostConstruct public void init() { - Properties props = new Properties(); + final Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", configuration.get(ConfigurationKey.SMTP_HOST)); props.put("mail.smtp.port", configuration.get(ConfigurationKey.SMTP_PORT)); @@ -182,7 +179,7 @@ public class MailServiceImpl implements MailService { final Appender appender = new MailAppender(null, layout, true); appender.start(); config.addAppender(appender); - LoggerConfig loggerConfig = LoggerConfig.newBuilder() // + final LoggerConfig loggerConfig = LoggerConfig.newBuilder() // .withAdditivity(false) // .withConfig(config) // .withLevel(Level.ERROR) // @@ -212,13 +209,13 @@ public class MailServiceImpl implements MailService { try { subject = message.getSubject(); recipients = toString(message.getAllRecipients()); - } catch (MessagingException e) { + } catch (final MessagingException e) { throw new AgroMetInfoException(MailErrorType.DETAILS, e.getMessage()); } try { Transport.send(message); - } catch (MessagingException e) { - if (e instanceof SendFailedException sfe) { + } catch (final MessagingException e) { + if (e instanceof final SendFailedException sfe) { final Address[] invalid = sfe.getInvalidAddresses(); if (invalid != null) { throw new AgroMetInfoException(MailErrorType.SEND_FAILED_INVALID, subject, toString(invalid)); @@ -245,11 +242,11 @@ public class MailServiceImpl implements MailService { mail.setFromAddress(configuration.get(ConfigurationKey.APP_EMAIL)); } message.setFrom(new InternetAddress(mail.getFromAddress())); - List<InternetAddress> to = new ArrayList<>(); + final List<InternetAddress> to = new ArrayList<>(); if (mail.getToAddresses() == null || mail.getToAddresses().isEmpty()) { mail.setToAddresses(List.of(configuration.get(ConfigurationKey.SUPPORT_EMAIL))); } - for (String addr : mail.getToAddresses()) { + for (final String addr : mail.getToAddresses()) { to.add(new InternetAddress(addr)); } message.setRecipients(Message.RecipientType.TO, to.toArray(InternetAddress[]::new)); @@ -262,7 +259,7 @@ public class MailServiceImpl implements MailService { message.setContent(content, "text/plain; charset=UTF-8"); message.setHeader("X-Environment", environment); return message; - } catch (MessagingException e) { + } catch (final MessagingException e) { throw new AgroMetInfoException(MailErrorType.DETAILS, e.getLocalizedMessage()); } } @@ -273,7 +270,7 @@ public class MailServiceImpl implements MailService { */ private String toString(final Address[] addresses) { final StringJoiner sj = new StringJoiner(", "); - for (Address addr : addresses) { + for (final Address addr : addresses) { sj.add(addr.toString()); } return sj.toString(); diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/SurveyFormHibernateTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/SurveyFormHibernateTest.java index 8265ff39..f73e89a4 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/SurveyFormHibernateTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/SurveyFormHibernateTest.java @@ -14,16 +14,16 @@ import java.util.concurrent.ThreadLocalRandom; import org.junit.jupiter.api.Test; -import fr.agrometinfo.www.server.dao.SurveyQuestionDao; -import fr.agrometinfo.www.server.dao.SurveyQuestionDaoHibernate; import fr.agrometinfo.www.server.dao.SurveyOptionDao; import fr.agrometinfo.www.server.dao.SurveyOptionDaoHibernate; +import fr.agrometinfo.www.server.dao.SurveyQuestionDao; +import fr.agrometinfo.www.server.dao.SurveyQuestionDaoHibernate; import fr.agrometinfo.www.server.dao.UserEmailDao; import fr.agrometinfo.www.server.dao.UserEmailDaoHibernate; import fr.agrometinfo.www.server.dao.UserResponsesDao; import fr.agrometinfo.www.server.dao.UserResponsesDaoHibernate; -import fr.agrometinfo.www.server.model.SurveyQuestion; import fr.agrometinfo.www.server.model.SurveyOption; +import fr.agrometinfo.www.server.model.SurveyQuestion; import fr.agrometinfo.www.server.model.UserEmail; import fr.agrometinfo.www.server.model.UserResponse; diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernateTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernateTest.java index 2da3fb0a..e1795227 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernateTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernateTest.java @@ -1,12 +1,12 @@ package fr.agrometinfo.www.server.dao; import static fr.agrometinfo.www.server.dao.DailyValueDaoHibernateTest.YEAR; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; import fr.agrometinfo.www.server.model.Indicator; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Test PraDailyValueDao Hibernate implementation. diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/rs/GeometryResourceTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/rs/GeometryResourceTest.java index 4759b006..37dbc1bf 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/rs/GeometryResourceTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/rs/GeometryResourceTest.java @@ -3,11 +3,9 @@ package fr.agrometinfo.www.server.rs; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Comparator; import org.geojson.FeatureCollection; import org.glassfish.hk2.utilities.binding.AbstractBinder; @@ -28,7 +26,7 @@ import jakarta.ws.rs.core.Application; * * @author Olivier Maury */ -public class GeometryResourceTest extends JerseyTest { +class GeometryResourceTest extends JerseyTest { /** * Path separator. */ diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/rs/SurveyFormResourceTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/rs/SurveyFormResourceTest.java index d9024586..670ad63c 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/rs/SurveyFormResourceTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/rs/SurveyFormResourceTest.java @@ -13,36 +13,34 @@ import java.util.HashMap; import java.util.List; import java.util.concurrent.ThreadLocalRandom; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import fr.agrometinfo.www.server.AgroMetInfoConfiguration; - import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.jupiter.api.Test; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; -import fr.agrometinfo.www.server.dao.SurveyQuestionDao; -import fr.agrometinfo.www.server.dao.SurveyQuestionDaoHibernate; +import fr.agrometinfo.www.server.AgroMetInfoConfiguration; import fr.agrometinfo.www.server.dao.SurveyOptionDao; import fr.agrometinfo.www.server.dao.SurveyOptionDaoHibernate; +import fr.agrometinfo.www.server.dao.SurveyQuestionDao; +import fr.agrometinfo.www.server.dao.SurveyQuestionDaoHibernate; import fr.agrometinfo.www.server.dao.UserEmailDao; import fr.agrometinfo.www.server.dao.UserEmailDaoHibernate; import fr.agrometinfo.www.server.dao.UserResponsesDao; import fr.agrometinfo.www.server.dao.UserResponsesDaoHibernate; import fr.agrometinfo.www.server.exception.AgroMetInfoException; -import fr.agrometinfo.www.server.model.SurveyQuestion; import fr.agrometinfo.www.server.model.SurveyOption; +import fr.agrometinfo.www.server.model.SurveyQuestion; import fr.agrometinfo.www.server.model.UserEmail; import fr.agrometinfo.www.server.model.UserResponse; import fr.agrometinfo.www.server.service.MailService; import fr.agrometinfo.www.server.service.MailService.Mail; -import fr.agrometinfo.www.shared.dto.SurveyResponseDTO; -import fr.agrometinfo.www.shared.dto.SurveyQuestionDTO; import fr.agrometinfo.www.shared.dto.SurveyOptionDTO; - +import fr.agrometinfo.www.shared.dto.SurveyQuestionDTO; +import fr.agrometinfo.www.shared.dto.SurveyResponseDTO; import jakarta.ws.rs.client.Entity; import jakarta.ws.rs.core.Application; import jakarta.ws.rs.core.MediaType; -- GitLab From e250109f37c5edaa2453be278a1336e8b4fed9e8 Mon Sep 17 00:00:00 2001 From: Olivier Maury <Olivier.Maury@inrae.fr> Date: Mon, 2 Dec 2024 18:46:55 +0100 Subject: [PATCH 2/6] Eclipse : organize imports --- .../www/shared/service/ApplicationService.java | 7 +++---- .../www/shared/service/IndicatorService.java | 7 +++---- .../www/shared/service/SurveyFormService.java | 11 +++++------ 3 files changed, 11 insertions(+), 14 deletions(-) diff --git a/www-shared/src/main/java/fr/agrometinfo/www/shared/service/ApplicationService.java b/www-shared/src/main/java/fr/agrometinfo/www/shared/service/ApplicationService.java index 7b21b6c1..8a5d0300 100644 --- a/www-shared/src/main/java/fr/agrometinfo/www/shared/service/ApplicationService.java +++ b/www-shared/src/main/java/fr/agrometinfo/www/shared/service/ApplicationService.java @@ -2,14 +2,13 @@ package fr.agrometinfo.www.shared.service; import java.util.Date; -import jakarta.ws.rs.GET; -import jakarta.ws.rs.POST; -import jakarta.ws.rs.Path; - import org.dominokit.rest.shared.request.service.annotations.RequestBody; import org.dominokit.rest.shared.request.service.annotations.RequestFactory; import fr.agrometinfo.www.shared.dto.MessageDTO; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; /** * Interface for client and server resource. diff --git a/www-shared/src/main/java/fr/agrometinfo/www/shared/service/IndicatorService.java b/www-shared/src/main/java/fr/agrometinfo/www/shared/service/IndicatorService.java index 6d7c3ab8..01525cec 100644 --- a/www-shared/src/main/java/fr/agrometinfo/www/shared/service/IndicatorService.java +++ b/www-shared/src/main/java/fr/agrometinfo/www/shared/service/IndicatorService.java @@ -4,16 +4,15 @@ import java.util.Date; import java.util.List; import java.util.Map; -import jakarta.ws.rs.GET; -import jakarta.ws.rs.Path; -import jakarta.ws.rs.QueryParam; - import org.dominokit.rest.shared.request.service.annotations.RequestFactory; import org.geojson.FeatureCollection; import fr.agrometinfo.www.shared.dto.FeatureLevel; import fr.agrometinfo.www.shared.dto.PeriodDTO; import fr.agrometinfo.www.shared.dto.SummaryDTO; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.QueryParam; /** * Interface for client and server resource. diff --git a/www-shared/src/main/java/fr/agrometinfo/www/shared/service/SurveyFormService.java b/www-shared/src/main/java/fr/agrometinfo/www/shared/service/SurveyFormService.java index beb8e043..70abb6a3 100644 --- a/www-shared/src/main/java/fr/agrometinfo/www/shared/service/SurveyFormService.java +++ b/www-shared/src/main/java/fr/agrometinfo/www/shared/service/SurveyFormService.java @@ -2,15 +2,14 @@ package fr.agrometinfo.www.shared.service; import java.util.List; -import jakarta.ws.rs.GET; -import jakarta.ws.rs.POST; -import jakarta.ws.rs.Path; - -import org.dominokit.rest.shared.request.service.annotations.RequestFactory; import org.dominokit.rest.shared.request.service.annotations.RequestBody; +import org.dominokit.rest.shared.request.service.annotations.RequestFactory; -import fr.agrometinfo.www.shared.dto.SurveyResponseDTO; import fr.agrometinfo.www.shared.dto.SurveyOptionDTO; +import fr.agrometinfo.www.shared.dto.SurveyResponseDTO; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; /** * Interface for survey form client server resource. -- GitLab From fd0277644fa2ab371025826a624685efae0d4e60 Mon Sep 17 00:00:00 2001 From: Olivier Maury <Olivier.Maury@inrae.fr> Date: Tue, 3 Dec 2024 09:38:25 +0100 Subject: [PATCH 3/6] style: :art: Nettoyer le code avec Eclipse --- .../fr/agrometinfo/www/client/presenter/SurveyPresenter.java | 4 ++-- .../agrometinfo/www/server/exception/ErrorCategoryTest.java | 4 ++-- .../fr/agrometinfo/www/server/exception/ErrorTypeTest.java | 2 +- .../fr/agrometinfo/www/server/rs/GeometryResourceTest.java | 3 ++- .../fr/agrometinfo/www/server/rs/IndicatorResourceTest.java | 5 +++-- .../fr/agrometinfo/www/server/rs/SurveyFormResourceTest.java | 5 +++-- .../fr/agrometinfo/www/shared/dto/SurveyQuestionDTO.java | 5 +---- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/SurveyPresenter.java b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/SurveyPresenter.java index bfc75e7a..e04a0224 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/SurveyPresenter.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/SurveyPresenter.java @@ -118,8 +118,8 @@ public final class SurveyPresenter implements Presenter { // call to webservice for inserting data final SurveyResponseDTO data = new SurveyResponseDTO( - new ArrayList<SurveyQuestionDTO>(questionsDto), - new ArrayList<SurveyOptionDTO>(responsesDto), + new ArrayList<>(questionsDto), + new ArrayList<>(responsesDto), otherTextMap); // if user has entered their email address, it is added to object diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorCategoryTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorCategoryTest.java index e9ac7527..15a59cf2 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorCategoryTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorCategoryTest.java @@ -18,7 +18,7 @@ import fr.agrometinfo.www.server.I18n; /** * Ensure all implementations of {@link ErrorCategory} are well defined. - * + * * @author Olivier Maury */ public class ErrorCategoryTest { @@ -33,7 +33,7 @@ public class ErrorCategoryTest { public static List<Class<? extends Enum<?>>> data() { return Arrays.asList(AgroMetInfoErrorCategory.class); } - + /** * @param clazz parametrized argument */ diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorTypeTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorTypeTest.java index 678149fe..44cdb201 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorTypeTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorTypeTest.java @@ -19,7 +19,7 @@ import fr.agrometinfo.www.server.service.MailServiceImpl; /** * Ensure all implementations of {@link ErrorType} are well defined. - * + * * @author Olivier Maury */ public class ErrorTypeTest { diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/rs/GeometryResourceTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/rs/GeometryResourceTest.java index 37dbc1bf..a2b03158 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/rs/GeometryResourceTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/rs/GeometryResourceTest.java @@ -19,6 +19,7 @@ import fr.agrometinfo.www.server.dao.PraDaoHibernate; import fr.agrometinfo.www.server.dao.PraDaoHibernateTest; import fr.agrometinfo.www.server.dao.SimulationDaoHibernateTest; import fr.agrometinfo.www.server.service.CacheService; +import fr.agrometinfo.www.shared.service.GeometryService; import jakarta.ws.rs.core.Application; /** @@ -62,7 +63,7 @@ class GeometryResourceTest extends JerseyTest { */ @Test void getPra() { - final FeatureCollection actual = target(GeometryResource.PATH + SEP + GeometryResource.PATH_PRA)// + final FeatureCollection actual = target(GeometryService.PATH + SEP + GeometryService.PATH_PRA)// .request()// .get(FeatureCollection.class); assertNotNull(actual); diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/rs/IndicatorResourceTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/rs/IndicatorResourceTest.java index ffa0ece7..21e3eace 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/rs/IndicatorResourceTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/rs/IndicatorResourceTest.java @@ -33,6 +33,7 @@ import fr.agrometinfo.www.server.dao.SimulationDaoHibernate; import fr.agrometinfo.www.server.dao.SimulationDaoHibernateTest; import fr.agrometinfo.www.server.service.CacheService; import fr.agrometinfo.www.shared.dto.SummaryDTO; +import fr.agrometinfo.www.shared.service.IndicatorService; import jakarta.ws.rs.core.Application; /** @@ -94,7 +95,7 @@ class IndicatorResourceTest extends JerseyTest { */ @Test void getSummary() { - final SummaryDTO actual = target(IndicatorResource.PATH + SEP + IndicatorResource.PATH_SUMMARY)// + final SummaryDTO actual = target(IndicatorService.PATH + SEP + IndicatorService.PATH_SUMMARY)// .queryParam("indicator", "rainsum") // .queryParam("period", "year") // .queryParam("level", "PRA") // @@ -113,7 +114,7 @@ class IndicatorResourceTest extends JerseyTest { */ @Test void getValues() { - final FeatureCollection actual = target(IndicatorResource.PATH + SEP + IndicatorResource.PATH_VALUES)// + final FeatureCollection actual = target(IndicatorService.PATH + SEP + IndicatorService.PATH_VALUES)// .queryParam("indicator", "rainsum") // .queryParam("period", "year") // .queryParam("compare", "false") // diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/rs/SurveyFormResourceTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/rs/SurveyFormResourceTest.java index 670ad63c..b9ba3356 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/rs/SurveyFormResourceTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/rs/SurveyFormResourceTest.java @@ -41,6 +41,7 @@ import fr.agrometinfo.www.server.service.MailService.Mail; import fr.agrometinfo.www.shared.dto.SurveyOptionDTO; import fr.agrometinfo.www.shared.dto.SurveyQuestionDTO; import fr.agrometinfo.www.shared.dto.SurveyResponseDTO; +import fr.agrometinfo.www.shared.service.SurveyFormService; import jakarta.ws.rs.client.Entity; import jakarta.ws.rs.core.Application; import jakarta.ws.rs.core.MediaType; @@ -110,7 +111,7 @@ public class SurveyFormResourceTest extends JerseyTest { assertFalse(questions.isEmpty(), "Question list is empty"); // Get all responses (options) by webservice - final String jsonAllResponses = target(SurveyFormResource.PATH + SEP + SurveyFormResource.PATH_RESPONSES_LIST).request().get(String.class); + final String jsonAllResponses = target(SurveyFormService.PATH + SEP + SurveyFormService.PATH_RESPONSES_LIST).request().get(String.class); assertNotNull(jsonAllResponses, "Unable to retrieve resource (null object) from responses"); assertFalse(jsonAllResponses.isEmpty(), "The JSON character string of the responses is empty"); @@ -155,7 +156,7 @@ public class SurveyFormResourceTest extends JerseyTest { assertEquals(data.getResponses(), responsesDTO, "List of responses in LoginFormData object does not match with the original list"); assertEquals(data.getOtherTextMap(), otherTextMap, "List of free responses in LoginFormData object does not match with the original list"); - jakarta.ws.rs.core.Response ret = target(SurveyFormResource.PATH + SEP + SurveyFormResource.PATH_INSERT_RESPONSE) + jakarta.ws.rs.core.Response ret = target(SurveyFormService.PATH + SEP + SurveyFormService.PATH_INSERT_RESPONSE) .request(MediaType.APPLICATION_JSON).post(Entity.entity(data, MediaType.APPLICATION_JSON)); assertEquals(ret.getStatus(), jakarta.ws.rs.core.Response.Status.OK.getStatusCode(), "The insert entry point should return status code 200 (OK)"); diff --git a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyQuestionDTO.java b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyQuestionDTO.java index 265f2c50..172020df 100644 --- a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyQuestionDTO.java +++ b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyQuestionDTO.java @@ -54,10 +54,7 @@ public class SurveyQuestionDTO { if (this == obj) { return true; } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { + if (obj == null || getClass() != obj.getClass()) { return false; } SurveyQuestionDTO other = (SurveyQuestionDTO) obj; -- GitLab From fcd175177674576aeaea0fa52af0fb78d172a9c4 Mon Sep 17 00:00:00 2001 From: Olivier Maury <Olivier.Maury@inrae.fr> Date: Tue, 3 Dec 2024 11:40:32 +0100 Subject: [PATCH 4/6] style: :art: Nettoyer le code avec NetBeans --- .../www/server/AgroMetInfoConfiguration.java | 4 +- .../www/server/ErrorHandlerServlet.java | 94 ++++++++++--------- .../java/fr/agrometinfo/www/server/I18n.java | 18 ++-- .../agrometinfo/www/server/StartListener.java | 2 +- .../server/dao/DailyVisitDaoHibernate.java | 2 +- .../www/server/dao/DaoHibernate.java | 26 ++--- .../www/server/dao/EntityManagerHandler.java | 2 +- .../server/dao/PraDailyValueDaoHibernate.java | 4 +- .../www/server/dao/PraDaoHibernate.java | 2 +- .../server/dao/SurveyOptionDaoHibernate.java | 2 +- .../www/server/dao/UserEmailDaoHibernate.java | 11 ++- .../server/dao/UserResponsesDaoHibernate.java | 12 +-- .../www/server/exception/ErrorMessage.java | 5 +- .../fr/agrometinfo/www/server/model/Cell.java | 44 ++++----- .../www/server/model/DailyVisit.java | 14 +-- .../www/server/model/Indicator.java | 64 ++++++------- .../agrometinfo/www/server/model/Period.java | 14 +-- .../www/server/model/SurveyOption.java | 10 +- .../www/server/model/SurveyQuestion.java | 10 +- .../www/server/model/UserEmail.java | 14 +-- .../www/server/model/UserResponse.java | 22 ++--- .../www/server/rs/JacksonConfig.java | 2 +- .../scheduled/BackgroundJobManager.java | 7 +- .../www/server/service/CacheService.java | 18 ++-- .../www/server/service/MailServiceImpl.java | 85 ++++++++--------- .../www/server/util/AppVersion.java | 6 +- .../www/server/util/EmailUtils.java | 13 +-- .../www/server/util/GeometryUtils.java | 8 +- .../www/server/util/LocaleUtils.java | 4 +- .../fr/agrometinfo/www/server/util/ST.java | 8 +- .../fr/agrometinfo/www/server/I18nTest.java | 34 +++---- .../www/server/SurveyFormHibernateTest.java | 70 ++++++-------- .../www/server/dao/CellDaoHibernateTest.java | 4 +- .../dao/DailyValueDaoHibernateTest.java | 2 +- .../dao/DailyVisitDaoHibernateTest.java | 2 +- .../dao/PraDailyValueDaoHibernateTest.java | 2 +- .../server/exception/ErrorCategoryTest.java | 47 +++++----- .../www/server/exception/ErrorTypeTest.java | 6 +- .../www/server/rs/GeometryResourceTest.java | 4 +- .../www/server/rs/IndicatorResourceTest.java | 6 +- .../www/server/rs/SurveyFormResourceTest.java | 72 ++++++-------- .../agrometinfo/www/shared/dto/ChoiceDTO.java | 23 ++--- .../www/shared/dto/ErrorResponseDTO.java | 11 +-- .../www/shared/dto/FeatureProperty.java | 2 +- .../www/shared/dto/IndicatorDTO.java | 8 +- .../www/shared/dto/QuantileType.java | 2 +- .../www/shared/dto/SimpleFeature.java | 8 +- .../www/shared/dto/SummaryDTO.java | 8 +- .../www/shared/dto/SurveyOptionDTO.java | 22 ++--- .../www/shared/dto/SurveyQuestionDTO.java | 56 +++++------ .../www/shared/dto/SurveyResponseDTO.java | 60 ++++++------ .../src/main/java/org/geojson/Feature.java | 8 +- .../java/org/geojson/FeatureCollection.java | 2 +- .../src/main/java/org/geojson/LngLatAlt.java | 9 +- .../main/java/org/geojson/MultiPolygon.java | 8 +- .../src/main/java/org/geojson/Polygon.java | 11 ++- .../www/shared/dto/FeaturePropertyTest.java | 8 +- 57 files changed, 506 insertions(+), 516 deletions(-) diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/AgroMetInfoConfiguration.java b/www-server/src/main/java/fr/agrometinfo/www/server/AgroMetInfoConfiguration.java index 785ea1e7..a5050551 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/AgroMetInfoConfiguration.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/AgroMetInfoConfiguration.java @@ -127,11 +127,11 @@ public class AgroMetInfoConfiguration { Objects.requireNonNull(servletContext, "servletContext must not be null!"); for (final ConfigurationKey key : ConfigurationKey.values()) { final String strKey = PREFIX + key.getKey(); - final String value = servletContext.getInitParameter(strKey); + final var value = servletContext.getInitParameter(strKey); Objects.requireNonNull(value, "Key " + strKey + " must have value in context.xml"); values.put(key, value); } - final File dir = new File(getCacheDirectory()); + final var dir = new File(getCacheDirectory()); if (!dir.exists()) { LOGGER.info("Creating directory {}", dir.getAbsolutePath()); if (!dir.mkdirs()) { diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/ErrorHandlerServlet.java b/www-server/src/main/java/fr/agrometinfo/www/server/ErrorHandlerServlet.java index 90a9e3b8..c56370d0 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/ErrorHandlerServlet.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/ErrorHandlerServlet.java @@ -1,8 +1,5 @@ package fr.agrometinfo.www.server; -import java.io.IOException; -import java.util.Locale; - import fr.agrometinfo.www.server.AgroMetInfoConfiguration.ConfigurationKey; import fr.agrometinfo.www.server.util.LocaleUtils; import jakarta.inject.Inject; @@ -12,6 +9,7 @@ import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; /** * Servlet to display user friendly error messages. @@ -34,52 +32,56 @@ public final class ErrorHandlerServlet extends HttpServlet { @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { - final String appUrl = config.get(ConfigurationKey.APP_URL) + "../"; - final Exception exception = (Exception) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); - - final Locale locale = LocaleUtils.getLocale(request); - final I18n i18n = new I18n("fr.agrometinfo.www.server.i18n", locale); + final var appUrl = config.get(ConfigurationKey.APP_URL) + "../"; + final var exception = (Exception) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); + final var locale = LocaleUtils.getLocale(request); + final var i18n = new I18n("fr.agrometinfo.www.server.i18n", locale); String body; - final String title = i18n.format(response.getStatus(), "http.status.title"); + final var title = i18n.format(response.getStatus(), "http.status.title"); switch (response.getStatus()) { - case HttpServletResponse.SC_BAD_REQUEST: - body = "<p>La demande n'a pas pu être comprise par le serveur à cause d'une syntaxe mal formée.<br />" - + "Vous NE DEVRIEZ PAS répéter la demande sans modifications.</p>"; - break; - case HttpServletResponse.SC_NOT_FOUND: - body = "<p>La page que vous cherchez n'existe pas, mais vous n'êtes pas " - + "pour autant dans une impasse. Voici quelques options disponibles :</p>" // - + "<ul>" - + "<li>Assurez-vous d'utiliser la bonne adresse URL.</li>" + "<li>Consultez <a href=\"" + appUrl - + "\" target=\"_blank\">la documentation</a>.</li>" - + "<li>Obtenez de l'aide en écrivant une demande de support dans l'application ou <a href=\"" - + appUrl + "/contact.html\">contactez-nous</a>.</li>" // - + "</ul>"; - break; - case HttpServletResponse.SC_INTERNAL_SERVER_ERROR: - body = "<p>Le serveur a rencontré une condition inattendue qui l'empêche de satisfaire la demande.</p>" - + "<p><b>Erreur :</b> " + exception + "</p>" + "<p><b>Cause :</b> " + exception.getCause() - + "</p>"; - break; - case HttpServletResponse.SC_SERVICE_UNAVAILABLE: - body = "<p>Le serveur est incapable de traiter actuellement la demande à cause d'une surcharge temporaire " - + "ou de la maintenance du serveur.<br />" - + "Il s'agit d'une condition temporaire qui sera levée après un certain temps.</p>"; - break; - default: - body = "<p><b>Erreur :</b> " + exception + "</p>"; - if (exception != null) { - body += "<p><b>Message d'erreur :</b>" + exception.getMessage() + "</p>"; - } - body += "<p><b>Status code:</b> " + response.getStatus() + "</p>"; - body += "<p><b>Request URI:</b> " + request.getScheme() + "://" + request.getServerName() - + request.getRequestURI() + "</p>"; - body += "<p><b>URL:</b> " + request.getRequestURI() + "</p>"; - body += "<p><b>Context path:</b> " + getServletContext().getContextPath() + "</p>"; - if (exception != null) { - body += "<p><b>Cause:</b> " + exception.getCause() + "</p>"; + case HttpServletResponse.SC_BAD_REQUEST -> + body = """ + <p>La demande n'a pas pu être comprise par le serveur à cause d'une syntaxe mal formée.<br /> + Vous NE DEVRIEZ PAS répéter la demande sans modifications.</p> + """; + case HttpServletResponse.SC_NOT_FOUND -> + body = """ + <p>La page que vous cherchez n'existe pas, mais vous n'êtes pas + pour autant dans une impasse. Voici quelques options disponibles :</p> + <ul> + <li>Assurez-vous d'utiliser la bonne adresse URL.</li><li>Consultez <a href=" + """ + appUrl + """ + "target="_blank">la documentation</a>.</li> + <li>Obtenez de l'aide en écrivant une demande de support dans l'application ou <a href=" + """ + appUrl + """ + /contact.html\">contactez-nous</a>.</li> + </ul> + """; + case HttpServletResponse.SC_INTERNAL_SERVER_ERROR -> + body = """ + <p>Le serveur a rencontré une condition inattendue qui l'empêche de satisfaire la demande.</p> + <p><b>Erreur :</b> """ + exception + "</p><p><b>Cause :</b> " + exception.getCause() // + + "</p>"; + case HttpServletResponse.SC_SERVICE_UNAVAILABLE -> + body = """ + <p>Le serveur est incapable de traiter actuellement la demande à cause d'une surcharge temporaire + ou de la maintenance du serveur.<br /> + Il s'agit d'une condition temporaire qui sera levée après un certain temps.</p> + """; + default -> { + body = "<p><b>Erreur :</b> " + exception + "</p>"; + if (exception != null) { + body += "<p><b>Message d'erreur :</b>" + exception.getMessage() + "</p>"; + } + body += "<p><b>Status code:</b> " + response.getStatus() + "</p>"; + body += "<p><b>Request URI:</b> " + request.getScheme() + "://" + request.getServerName() + + request.getRequestURI() + "</p>"; + body += "<p><b>URL:</b> " + request.getRequestURI() + "</p>"; + body += "<p><b>Context path:</b> " + getServletContext().getContextPath() + "</p>"; + if (exception != null) { + body += "<p><b>Cause:</b> " + exception.getCause() + "</p>"; + } } - break; } request.setAttribute("appUrl", appUrl); request.setAttribute("body", body); diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/I18n.java b/www-server/src/main/java/fr/agrometinfo/www/server/I18n.java index ac7e9903..2b0cd7cb 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/I18n.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/I18n.java @@ -107,14 +107,14 @@ public class I18n { * @return if the comparison string matches the value. */ static boolean matches(final String comparison, final int plural) { - final Optional<Operator> operator = Operator.extract(comparison); + final var operator = Operator.extract(comparison); if (operator.isPresent()) { - final Operator op = operator.get(); - String val = comparison.substring(op.getLength()); + final var op = operator.get(); + var val = comparison.substring(op.getLength()); if (val != null) { val = val.trim(); if (!val.isEmpty()) { - final Integer value = Integer.valueOf(val); + final var value = Integer.valueOf(val); return op.apply(plural, value); } } @@ -151,7 +151,7 @@ public class I18n { public I18n(final ResourceBundle rb) { resources = rb; locale = rb.getLocale(); - final var bundleName = rb.getBaseBundleName(); + final String bundleName = rb.getBaseBundleName(); if (bundleName != null) { fallbackResources = ResourceBundle.getBundle(bundleName, Locale.ROOT); } else { @@ -168,7 +168,7 @@ public class I18n { public I18n(@NonNull final String bundleName, @NonNull final Locale requestedLocale) { locale = requestedLocale; fallbackResources = ResourceBundle.getBundle(bundleName, Locale.ROOT); - final var res = ResourceBundle.getBundle(bundleName, locale); + final ResourceBundle res = ResourceBundle.getBundle(bundleName, locale); if (res.getLocale().equals(locale)) { resources = res; } else { @@ -197,7 +197,7 @@ public class I18n { } // with comparators <, <=, >, >= - final List<String> suffixes = getKeys().stream() + final var suffixes = getKeys().stream() .filter(k -> k.startsWith(key + "[") && k.endsWith("]")) .map(k -> k.substring(key.length() + 1, k.length() - 1)) .collect(Collectors.toList()); @@ -219,8 +219,8 @@ public class I18n { * @return message with arguments or exclamation message */ public String format(final String key, final Object... messageArguments) { - final var format = this.get(key); - final var messageFormat = new MessageFormat(format, locale); + final String format = this.get(key); + final MessageFormat messageFormat = new MessageFormat(format, locale); return messageFormat.format(messageArguments); } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/StartListener.java b/www-server/src/main/java/fr/agrometinfo/www/server/StartListener.java index 832d6f93..59336c88 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/StartListener.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/StartListener.java @@ -38,7 +38,7 @@ public final class StartListener implements ServletContextListener { LOGGER.trace("Environment is dev, e-mail isn't send"); return; } - MailService.Mail mail = new MailService.Mail(); + var mail = new MailService.Mail(); mail.setContent("Bonjour,\nAgroMetInfo-www-" + AppVersion.getVersion() + " démarre.\n" + LocalDateTime.now()); mail.setFromAddress(configuration.get(AgroMetInfoConfiguration.ConfigurationKey.APP_EMAIL)); mail.setSubject("Démarrage"); diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/dao/DailyVisitDaoHibernate.java b/www-server/src/main/java/fr/agrometinfo/www/server/dao/DailyVisitDaoHibernate.java index a24a802b..6e9979f2 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/dao/DailyVisitDaoHibernate.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/dao/DailyVisitDaoHibernate.java @@ -39,7 +39,7 @@ public class DailyVisitDaoHibernate extends DaoHibernate<DailyVisit> implements doInJpaTransaction(em -> { var query = em.createNativeQuery(UPDATE_SQL); query.setParameter("environment", environment); - final int nb = query.executeUpdate(); + final var nb = query.executeUpdate(); if (nb == 0) { query = em.createNativeQuery(INSERT_SQL); query.setParameter("environment", environment); diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/dao/DaoHibernate.java b/www-server/src/main/java/fr/agrometinfo/www/server/dao/DaoHibernate.java index 48899a6c..814045d2 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/dao/DaoHibernate.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/dao/DaoHibernate.java @@ -1,15 +1,5 @@ package fr.agrometinfo.www.server.dao; -import java.math.BigDecimal; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - -import org.hibernate.engine.spi.SessionImplementor; - import jakarta.persistence.NoResultException; import jakarta.persistence.Query; import jakarta.persistence.TypedQuery; @@ -17,7 +7,15 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Order; import jakarta.persistence.criteria.Root; +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; import lombok.extern.log4j.Log4j2; +import org.hibernate.engine.spi.SessionImplementor; /** * Common methods for DAO with Hibernate. @@ -300,9 +298,11 @@ public abstract class DaoHibernate<T> { public BigDecimal getSchemaSize(final String schema) { try (ScopedEntityManager em = getScopedEntityManager()) { if (isPostgreSQLDriver(em)) { - final String sql = "SELECT " - + "SUM(pg_total_relation_size(CONCAT(quote_ident(schemaname), '.', quote_ident(tablename)))) " - + "FROM pg_catalog.pg_tables WHERE schemaname=:schema"; + final String sql = """ + SELECT + SUM(pg_total_relation_size(CONCAT(quote_ident(schemaname), '.', quote_ident(tablename)))) + FROM pg_catalog.pg_tables WHERE schemaname=:schema + """; final Query query = em.createNativeQuery(sql); query.setParameter("schema", schema); return (BigDecimal) query.getSingleResult(); diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/dao/EntityManagerHandler.java b/www-server/src/main/java/fr/agrometinfo/www/server/dao/EntityManagerHandler.java index dfea59cc..a760d69f 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/dao/EntityManagerHandler.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/dao/EntityManagerHandler.java @@ -83,7 +83,7 @@ public final class EntityManagerHandler implements AutoCloseable, InvocationHand * @param fn Transaction of ScopedEntityManager * @return result from committed transaction or null */ - protected Object proxyExecuteTransaction(final Object fn) { + Object proxyExecuteTransaction(final Object fn) { final EntityTransaction t = em.getTransaction(); final Object result = null; try { diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernate.java b/www-server/src/main/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernate.java index 3f6d54e4..8b9c990e 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernate.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernate.java @@ -37,7 +37,7 @@ public class PraDailyValueDaoHibernate extends DaoHibernate<PraDailyValue> imple } private static PraDailyValue toPraDailyValue(final Object[] row) { - final PraDailyValue value = new PraDailyValue(); + final var value = new PraDailyValue(); int i = 0; value.setDate(DateUtils.toLocalDate((Date) row[i++])); value.setComparedValue(((Number) row[i++]).floatValue()); @@ -255,7 +255,7 @@ public class PraDailyValueDaoHibernate extends DaoHibernate<PraDailyValue> imple public final List<Indicator> findIndicators(@NonNull final Integer year) { final var sql = "SELECT DISTINCT indicator FROM v_pra_dailyvalue WHERE EXTRACT(YEAR FROM date) = :year"; final List<Long> ids = super.findAllBySQL(sql, Map.of("year", year)).stream() // - .map(i -> Long.valueOf((int) i)).toList(); + .map(i -> Long.valueOf((long) i)).toList(); final var jpql = "SELECT i FROM Indicator AS i JOIN i.period WHERE i.id IN (:ids)"; return super.findAllByJPQL(jpql, Map.of("ids", ids), Indicator.class); } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/dao/PraDaoHibernate.java b/www-server/src/main/java/fr/agrometinfo/www/server/dao/PraDaoHibernate.java index 52d56deb..71d4c440 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/dao/PraDaoHibernate.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/dao/PraDaoHibernate.java @@ -22,7 +22,7 @@ public class PraDaoHibernate extends DaoHibernate<Pra> implements PraDao { @Override public final Pra findByCode(final String code) { - final var jpql = "SELECT t FROM Pra t WHERE t.code=:code"; + final String jpql = "SELECT t FROM Pra t WHERE t.code=:code"; return super.findOneByJPQL(jpql, Map.of("code", code), Pra.class); } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/dao/SurveyOptionDaoHibernate.java b/www-server/src/main/java/fr/agrometinfo/www/server/dao/SurveyOptionDaoHibernate.java index 6b98c993..8f62bd08 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/dao/SurveyOptionDaoHibernate.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/dao/SurveyOptionDaoHibernate.java @@ -21,7 +21,7 @@ public final class SurveyOptionDaoHibernate extends DaoHibernate<SurveyOption> i } @Override public List<SurveyOption> findAllByQuestion(final long questionRef) { - final String jpql = "SELECT r FROM SurveyOption r WHERE r.question.id = :ref"; + final var jpql = "SELECT r FROM SurveyOption r WHERE r.question.id = :ref"; return super.findAllByJPQL(jpql, Map.of("ref", questionRef), SurveyOption.class); } @Override diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserEmailDaoHibernate.java b/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserEmailDaoHibernate.java index e45b99c2..cf895fc9 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserEmailDaoHibernate.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserEmailDaoHibernate.java @@ -17,16 +17,17 @@ public final class UserEmailDaoHibernate extends DaoHibernate<UserEmail> impleme public UserEmailDaoHibernate() { super(UserEmail.class); } + @Override + public List<UserEmail> getEmailAddressList() { + return super.findAll(); + } + @Override public void insertEmailUserAddress(final String email, final LocalDateTime datetime) { - final UserEmail um = new UserEmail(); + final var um = new UserEmail(); um.setEmail(email); um.setDatetime(datetime); this.save(um); } - @Override - public List<UserEmail> getEmailAddressList() { - return super.findAll(); - } } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserResponsesDaoHibernate.java b/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserResponsesDaoHibernate.java index 104fbdd8..39ac4ab5 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserResponsesDaoHibernate.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/dao/UserResponsesDaoHibernate.java @@ -22,14 +22,18 @@ public final class UserResponsesDaoHibernate extends DaoHibernate<UserResponse> } @Override public List<UserResponse> findAllByQuestion(final long questionRef) { - final String jpql = "SELECT u FROM UserResponse u WHERE u.question.id = :ref"; + final var jpql = "SELECT u FROM UserResponse u WHERE u.question.id = :ref"; return super.findAllByJPQL(jpql, Map.of("ref", questionRef), UserResponse.class); } @Override + public int getNbUserResponses() { + return super.findAll().size(); + } + @Override public void insertResponse( final SurveyQuestion q, final SurveyOption r, final String otherText, final LocalDateTime datetime) { - final UserResponse ur = new UserResponse(); + final var ur = new UserResponse(); ur.setDateTime(datetime); ur.setQuestion(q); ur.setOption(r); @@ -41,8 +45,4 @@ public final class UserResponsesDaoHibernate extends DaoHibernate<UserResponse> public void insertResponse(final SurveyQuestion q, final SurveyOption r, final String otherText) { this.insertResponse(q, r, otherText, LocalDateTime.now()); } - @Override - public int getNbUserResponses() { - return super.findAll().size(); - } } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/exception/ErrorMessage.java b/www-server/src/main/java/fr/agrometinfo/www/server/exception/ErrorMessage.java index 2e08c5c6..8f472784 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/exception/ErrorMessage.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/exception/ErrorMessage.java @@ -1,10 +1,9 @@ package fr.agrometinfo.www.server.exception; +import fr.agrometinfo.www.server.I18n; import java.io.Serializable; import java.util.Collection; import java.util.Locale; - -import fr.agrometinfo.www.server.I18n; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; @@ -98,7 +97,7 @@ public final class ErrorMessage implements Serializable { * @return JSON representation */ public String toJSON() { - final StringBuilder sb = new StringBuilder(); + final var sb = new StringBuilder(); sb.append("{"); sb.append("\"bundleName\": \"").append(bundleName).append("\", "); sb.append("\"errorCode\": \"").append(type.getFullCode()).append("\", "); diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/model/Cell.java b/www-server/src/main/java/fr/agrometinfo/www/server/model/Cell.java index a11c8b1e..acd82085 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/model/Cell.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/model/Cell.java @@ -26,6 +26,12 @@ public class Cell { */ @Column(name = "created", nullable = false) private LocalDateTime created = LocalDateTime.now(); + /** + * Main department in the cell. + */ + @JoinColumn(name = "department") + @ManyToOne + private Department department; /** * ID: SAFRAN cell number. */ @@ -33,55 +39,49 @@ public class Cell { @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private long id; - /** - * Main department in the cell. - */ - @JoinColumn(name = "department") - @ManyToOne - private Department department; /** * Latitude of cell center [°N]. */ private Double lat; - /** - * Longitude of cell center [°E]. - */ - private Double lon; /** * Latitude of point 1 [°N]. */ @Column(columnDefinition = "NUMERIC(16,14)") private Double lat1; /** - * Longitude of point 1 [°E]. + * Latitude of point 2 [°N]. */ @Column(columnDefinition = "NUMERIC(16,14)") - private Double lon1; + private Double lat2; /** - * Latitude of point 2 [°N]. + * Latitude of point 3 [°N]. */ @Column(columnDefinition = "NUMERIC(16,14)") - private Double lat2; + private Double lat3; /** - * Longitude of point 2 [°E]. + * Latitude of point 4 [°N]. */ @Column(columnDefinition = "NUMERIC(16,14)") - private Double lon2; + private Double lat4; /** - * Latitude of point 3 [°N]. + * Longitude of cell center [°E]. + */ + private Double lon; + /** + * Longitude of point 1 [°E]. */ @Column(columnDefinition = "NUMERIC(16,14)") - private Double lat3; + private Double lon1; /** - * Longitude of point 3 [°E]. + * Longitude of point 2 [°E]. */ @Column(columnDefinition = "NUMERIC(16,14)") - private Double lon3; + private Double lon2; /** - * Latitude of point 4 [°N]. + * Longitude of point 3 [°E]. */ @Column(columnDefinition = "NUMERIC(16,14)") - private Double lat4; + private Double lon3; /** * Longitude of point 4 [°E]. */ diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/model/DailyVisit.java b/www-server/src/main/java/fr/agrometinfo/www/server/model/DailyVisit.java index 80b3a47a..7896b30b 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/model/DailyVisit.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/model/DailyVisit.java @@ -19,13 +19,6 @@ import lombok.Data; @Entity @Table(name = "dailyvisit") public class DailyVisit { - /** - * PK. - */ - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private long id; /** * Date. */ @@ -36,6 +29,13 @@ public class DailyVisit { */ @Column(name = "environment") private String environment; + /** + * PK. + */ + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private long id; /** * Number of visits per day. */ diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/model/Indicator.java b/www-server/src/main/java/fr/agrometinfo/www/server/model/Indicator.java index badaa288..66e39244 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/model/Indicator.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/model/Indicator.java @@ -28,29 +28,11 @@ import lombok.Data; @Entity @Table(name = "indicator") public class Indicator { - /** - * PK. - */ - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private long id; /** * UID. */ @Column(name = "code") private String code; - /** - * Unit symbol. - */ - @Column(name = "unit") - private String unit; - /** - * Period. - */ - @JoinColumn(name = "period") - @ManyToOne - private Period period; /** * Name of color sequence used to display indicator values on the map. */ @@ -61,16 +43,45 @@ public class Indicator { */ @Column(name = "description") private Integer description; + /** + * Translated descriptions. + */ + @ElementCollection(fetch = FetchType.EAGER) + @JoinTable(name = "v_i18n", joinColumns = @JoinColumn(name = "i18nkey", referencedColumnName = "description")) + @MapKeyColumn(name = "languagetag") + @Column(name = "translation") + private Map<String, String> descriptions; + /** + * PK. + */ + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private long id; /** * Defined to use in @JoinTable. */ @Column(name = "name") private Integer name; + /** + * Translated descriptions. + */ + @ElementCollection(fetch = FetchType.EAGER) + @JoinTable(name = "v_i18n", joinColumns = @JoinColumn(name = "i18nkey", referencedColumnName = "name")) + @MapKeyColumn(name = "languagetag") + @Column(name = "translation") + private Map<String, String> names; /** * Number of classes, for linear. */ @Column(name = "nbofclasses") private Integer nbOfClasses; + /** + * Period. + */ + @JoinColumn(name = "period") + @ManyToOne + private Period period; /** * Quantile type, for quantile. */ @@ -78,19 +89,8 @@ public class Indicator { @Enumerated(EnumType.STRING) private QuantileType quantileType; /** - * Translated descriptions. - */ - @ElementCollection(fetch = FetchType.EAGER) - @JoinTable(name = "v_i18n", joinColumns = @JoinColumn(name = "i18nkey", referencedColumnName = "name")) - @MapKeyColumn(name = "languagetag") - @Column(name = "translation") - private Map<String, String> names; - /** - * Translated descriptions. + * Unit symbol. */ - @ElementCollection(fetch = FetchType.EAGER) - @JoinTable(name = "v_i18n", joinColumns = @JoinColumn(name = "i18nkey", referencedColumnName = "description")) - @MapKeyColumn(name = "languagetag") - @Column(name = "translation") - private Map<String, String> descriptions; + @Column(name = "unit") + private String unit; } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/model/Period.java b/www-server/src/main/java/fr/agrometinfo/www/server/model/Period.java index 02921226..b00dd36c 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/model/Period.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/model/Period.java @@ -24,13 +24,6 @@ import lombok.Data; @Entity @Table(name = "period") public class Period { - /** - * PK. - */ - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private long id; /** * UID. */ @@ -41,6 +34,13 @@ public class Period { */ @Column(name = "firstday") private String firstDay; + /** + * PK. + */ + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private long id; /** * Last day of agroclimatic phase. */ diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/model/SurveyOption.java b/www-server/src/main/java/fr/agrometinfo/www/server/model/SurveyOption.java index ddc5fe7a..b29aa8ba 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/model/SurveyOption.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/model/SurveyOption.java @@ -18,6 +18,11 @@ import lombok.Data; @Entity @Table(name = "surveyoption") public class SurveyOption { + /** + * Label of the option. + */ + @Column(name = "description") + private String description; /** * Reference of the option.<br> * Primary key. @@ -32,9 +37,4 @@ public class SurveyOption { @OneToOne @JoinColumn(name = "surveyquestion") private SurveyQuestion question; - /** - * Label of the option. - */ - @Column(name = "description") - private String description; } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/model/SurveyQuestion.java b/www-server/src/main/java/fr/agrometinfo/www/server/model/SurveyQuestion.java index 6596c6d0..08049e71 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/model/SurveyQuestion.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/model/SurveyQuestion.java @@ -16,6 +16,11 @@ import lombok.Data; @Entity @Table(name = "surveyquestion") public class SurveyQuestion { + /** + * Label of the question. + */ + @Column(name = "description") + private String description; /** * Reference of the question.<br> * Primary key. @@ -24,9 +29,4 @@ public class SurveyQuestion { @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private long id; - /** - * Label of the question. - */ - @Column(name = "description") - private String description; } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/model/UserEmail.java b/www-server/src/main/java/fr/agrometinfo/www/server/model/UserEmail.java index 8c54efc9..fe65c032 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/model/UserEmail.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/model/UserEmail.java @@ -18,13 +18,6 @@ import lombok.Data; @Entity @Table(name = "useremail") public class UserEmail { - /** - * Primary key. - */ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; /** * Date time of user response (creation date). */ @@ -35,4 +28,11 @@ public class UserEmail { */ @Column(name = "email") private String email; + /** + * Primary key. + */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/model/UserResponse.java b/www-server/src/main/java/fr/agrometinfo/www/server/model/UserResponse.java index b6e61475..9119fc45 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/model/UserResponse.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/model/UserResponse.java @@ -20,24 +20,18 @@ import lombok.Data; @Entity @Table(name = "userresponse") public class UserResponse { - /** - * Primary key. - */ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; /** * Date time of user responses (creation date). */ @Column(name = "datetime") private LocalDateTime dateTime; /** - * Related question. + * Primary key. */ - @OneToOne - @JoinColumn(name = "surveyquestion") - private SurveyQuestion question; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; /** * Related option.<br> * Can be null if it's a other response. @@ -51,4 +45,10 @@ public class UserResponse { */ @Column(name = "othertext") private String otherText; + /** + * Related question. + */ + @OneToOne + @JoinColumn(name = "surveyquestion") + private SurveyQuestion question; } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/rs/JacksonConfig.java b/www-server/src/main/java/fr/agrometinfo/www/server/rs/JacksonConfig.java index a2682d2f..1122e68d 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/rs/JacksonConfig.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/rs/JacksonConfig.java @@ -28,7 +28,7 @@ public class JacksonConfig implements ContextResolver<ObjectMapper> { */ public JacksonConfig() { objectMapper = new ObjectMapper(); - final SimpleModule module = new SimpleModule("MyModule", new Version(1, 0, 0, null, null, null)); + final var module = new SimpleModule("MyModule", new Version(1, 0, 0, null, null, null)); module.addSerializer(LngLatAlt.class, new LngLatAltSerializer()); objectMapper.registerModule(module); // NB, to format date as ISO 8601, use objectMapper.setDateFormat(new diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/scheduled/BackgroundJobManager.java b/www-server/src/main/java/fr/agrometinfo/www/server/scheduled/BackgroundJobManager.java index ad2a4575..6e3f718a 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/scheduled/BackgroundJobManager.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/scheduled/BackgroundJobManager.java @@ -15,6 +15,7 @@ import jakarta.inject.Inject; import jakarta.servlet.ServletContextEvent; import jakarta.servlet.ServletContextListener; import jakarta.servlet.annotation.WebListener; +import java.math.BigDecimal; import lombok.extern.log4j.Log4j2; /** @@ -45,8 +46,8 @@ public class BackgroundJobManager implements ServletContextListener { * @return delays in seconds until the next hour:minute */ static long initialDelay(final int hour, final int minute, final int second) { - LocalDateTime next = LocalDateTime.of(LocalDate.now(), LocalTime.of(hour, minute, second)); - final LocalDateTime now = LocalDateTime.now(); + var next = LocalDateTime.of(LocalDate.now(), LocalTime.of(hour, minute, second)); + final var now = LocalDateTime.now(); if (next.isBefore(now)) { next = next.plusDays(1); } @@ -125,7 +126,7 @@ public class BackgroundJobManager implements ServletContextListener { */ private void updateHourlyMetrics() { final var schemaName = indicatorDao.getSchemaName(); - final var schemaSize = indicatorDao.getCurrentSchemaSize(); + final BigDecimal schemaSize = indicatorDao.getCurrentSchemaSize(); SavaUtils.setGaugeValue("schema_size", schemaSize.doubleValue(), schemaName); } } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/service/CacheService.java b/www-server/src/main/java/fr/agrometinfo/www/server/service/CacheService.java index 568c9d67..316ef21d 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/service/CacheService.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/service/CacheService.java @@ -52,7 +52,7 @@ public class CacheService { /** * Number of milliseconds in a day. */ - private static final long MILLISECONDS_IN_A_DAY = 60 * 60 * 24 * 1000; + private static final long MILLISECONDS_IN_A_DAY = 60 * 60 * 24 * 1_000; /** * Cache directory path. @@ -62,6 +62,11 @@ public class CacheService { @Named("cacheDirectory") private String cacheDirectory; + + /** + * Key related to object to cache. + */ + private String cacheKey; /** * Date of last modification of indicators values in database. */ @@ -71,11 +76,6 @@ public class CacheService { @Named("lastModification") private LocalDateTime lastModification; - /** - * Key related to object to cache. - */ - private String cacheKey; - /** * Cache retention in days. */ @@ -97,7 +97,7 @@ public class CacheService { * @return object from cache or null. */ public Object getCache() { - final File cacheFile = getCacheFile(); + final var cacheFile = getCacheFile(); if (!cacheFile.exists()) { return null; } @@ -116,7 +116,7 @@ public class CacheService { * @return cache control */ private CacheControl getCacheControl() { - final CacheControl cc = new CacheControl(); + final var cc = new CacheControl(); final LocalDateTime dayAfter = lastModification.plusDays(nbOfDays); final Long maxAge = ChronoUnit.SECONDS.between(LocalDateTime.now(), dayAfter); // max age = time inn seconds @@ -185,7 +185,7 @@ public class CacheService { * @param objects objects to create a cache key */ public void setCacheKey(final Object... objects) { - final StringJoiner sj = new StringJoiner("-"); + final var sj = new StringJoiner("-"); for (final Object object : objects) { if (object == null) { sj.add("null"); diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/service/MailServiceImpl.java b/www-server/src/main/java/fr/agrometinfo/www/server/service/MailServiceImpl.java index f656068f..230a40cc 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/service/MailServiceImpl.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/service/MailServiceImpl.java @@ -47,44 +47,6 @@ import lombok.Getter; @ApplicationScoped public class MailServiceImpl implements MailService { - /** - * Log4j2 appender to send error logs by e-mail. - */ - private class MailAppender extends AbstractAppender { - /** - * Logger name. - */ - private static final String NAME = "MailAppender"; - - /** - * Constructor. - * - * @param filter The Filter to associate with the Appender. - * @param layout The layout to use to format the event. - * @param ignoreExceptions If true, exceptions will be logged and suppressed. If - * false errors will be logged and then passed to the - * application. - */ - MailAppender(final Filter filter, final Layout<? extends Serializable> layout, final boolean ignoreExceptions) { - super(NAME, filter, layout, ignoreExceptions, null); - - } - - @Override - public void append(final LogEvent event) { - final Mail mail = new Mail(); - mail.setFromAddress("agrometinfo@inrae.fr"); - mail.setSubject("AgroMetInfo - error log"); - mail.setContent(super.toSerializable(event).toString()); - mail.setToAddresses(List.of(configuration.get(ConfigurationKey.LOG_EMAIL))); - try { - send(mail); - } catch (final AgroMetInfoException e) { - // do nothing - LOGGER.info("Cannot send email: {}", e.getMessage()); - } - } - } /** * Keys from messages.properties used to warn about errors. @@ -134,6 +96,45 @@ public class MailServiceImpl implements MailService { } + /** + * Log4j2 appender to send error logs by e-mail. + */ + private class MailAppender extends AbstractAppender { + + /** + * Logger name. + */ + private static final String NAME = "MailAppender"; + + /** + * Constructor. + * + * @param filter The Filter to associate with the Appender. + * @param layout The layout to use to format the event. + * @param ignoreExceptions If true, exceptions will be logged and suppressed. If + * false errors will be logged and then passed to the + * application. + */ + MailAppender(final Filter filter, final Layout<? extends Serializable> layout, final boolean ignoreExceptions) { + super(NAME, filter, layout, ignoreExceptions, null); + } + + @Override + public void append(final LogEvent event) { + final var mail = new Mail(); + mail.setFromAddress("agrometinfo@inrae.fr"); + mail.setSubject("AgroMetInfo - error log"); + mail.setContent(super.toSerializable(event).toString()); + mail.setToAddresses(List.of(configuration.get(ConfigurationKey.LOG_EMAIL))); + try { + send(mail); + } catch (final AgroMetInfoException e) { + // do nothing + LOGGER.info("Cannot send email: {}", e.getMessage()); + } + } + } + /** * Application configuration. */ @@ -150,7 +151,7 @@ public class MailServiceImpl implements MailService { */ @PostConstruct public void init() { - final Properties props = new Properties(); + final var props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", configuration.get(ConfigurationKey.SMTP_HOST)); props.put("mail.smtp.port", configuration.get(ConfigurationKey.SMTP_PORT)); @@ -163,9 +164,9 @@ public class MailServiceImpl implements MailService { }; session = Session.getInstance(props, authenticator); // Send e-mails for ERROR level messages - final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); + final var ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); - final String pattern = """ + final var pattern = """ date : %d level : %-5p class : %c#%M() @@ -269,7 +270,7 @@ public class MailServiceImpl implements MailService { * @return string representation of addresses */ private String toString(final Address[] addresses) { - final StringJoiner sj = new StringJoiner(", "); + final var sj = new StringJoiner(", "); for (final Address addr : addresses) { sj.add(addr.toString()); } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/util/AppVersion.java b/www-server/src/main/java/fr/agrometinfo/www/server/util/AppVersion.java index f123a6cb..7c22f781 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/util/AppVersion.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/util/AppVersion.java @@ -23,7 +23,7 @@ public final class AppVersion { * @return Date of application build */ public static Date getBuildDate() { - final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + final var sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { return sdf.parse(getString("build.date")); } catch (final ParseException e) { @@ -72,8 +72,8 @@ public final class AppVersion { * @return version and date */ public static String getVersionAndBuildDate() { - final String version = getString("version"); - final String date = getString("build.date").replace("-", "").replace(" ", "").replace(":", ""); + final var version = getString("version"); + final var date = getString("build.date").replace("-", "").replace(" ", "").replace(":", ""); return version + "+" + date; } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/util/EmailUtils.java b/www-server/src/main/java/fr/agrometinfo/www/server/util/EmailUtils.java index 1006b227..71fadf51 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/util/EmailUtils.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/util/EmailUtils.java @@ -7,12 +7,7 @@ import java.util.regex.Pattern; * */ public final class EmailUtils { - /** - * Private default constructor. - */ - private EmailUtils() { - } /** * Check if email address provided is a valid address.<br> * Verification by not null and regex @@ -23,7 +18,13 @@ public final class EmailUtils { if (email == null) { return false; } - final String emailPattern = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"; + final var emailPattern = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"; return Pattern.matches(emailPattern, email); } + /** + * Private default constructor. + */ + private EmailUtils() { + + } } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/util/GeometryUtils.java b/www-server/src/main/java/fr/agrometinfo/www/server/util/GeometryUtils.java index 09957546..2dac8515 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/util/GeometryUtils.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/util/GeometryUtils.java @@ -23,9 +23,9 @@ public interface GeometryUtils { * @return GeoJSON feature */ static Feature toFeature(final Cell cell) { - final Feature feature = new Feature(); + final var feature = new Feature(); feature.setId(String.valueOf(cell.getId())); - final MultiPolygon polygon = new MultiPolygon(); + final var polygon = new MultiPolygon(); final List<List<List<LngLatAlt>>> coordinates = List.of(List.of(List.of(// new LngLatAlt(cell.getLon1(), cell.getLat1()), // new LngLatAlt(cell.getLon2(), cell.getLat2()), // @@ -45,9 +45,9 @@ public interface GeometryUtils { * @return GeoJSON feature */ static Feature toFeature(final Pra pra) { - final Feature feature = new Feature(); + final var feature = new Feature(); feature.setId(pra.getCode()); - final MultiPolygon multiPolygon = new MultiPolygon(); + final var multiPolygon = new MultiPolygon(); final List<LngLatAlt> coordinates = new ArrayList<>(); final int nb = pra.getCoordinates().length; if (nb % 2 != 0) { diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/util/LocaleUtils.java b/www-server/src/main/java/fr/agrometinfo/www/server/util/LocaleUtils.java index 871978a9..5252965a 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/util/LocaleUtils.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/util/LocaleUtils.java @@ -32,7 +32,7 @@ public interface LocaleUtils { // 1. URL parameter final String localeParam = request.getParameter("locale"); if (localeParam != null) { - final Locale found = getLocale(localeParam); + final var found = getLocale(localeParam); if (found != null) { return found; } @@ -57,7 +57,7 @@ public interface LocaleUtils { if (tag.startsWith("fr")) { return Locale.FRENCH; } - final Locale found = Locale.forLanguageTag(tag); + final var found = Locale.forLanguageTag(tag); if (found == null || !getLocales().contains(found)) { return Locale.ENGLISH; } diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/util/ST.java b/www-server/src/main/java/fr/agrometinfo/www/server/util/ST.java index a0f46cd3..113aeeb0 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/util/ST.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/util/ST.java @@ -35,15 +35,15 @@ public class ST { SUPPORT_EMAIL; } - /** - * The template with string to be replaced. - */ - private final String template; /** * The strings to replace. */ private final Map<String, String> replacements = new HashMap<>(); + /** + * The template with string to be replaced. + */ + private final String template; /** * Inject an attribute (name/value pair). diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/I18nTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/I18nTest.java index 5b1a6f01..2f94f124 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/I18nTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/I18nTest.java @@ -23,15 +23,15 @@ import fr.agrometinfo.www.server.I18n.Operator; */ class I18nTest { - /** - * Name of test bundle. - */ - private static final String NAME = "fr.agrometinfo.www.server.test"; /** * Key for plural messages to test. */ private static final String KEY = "cartItems"; + /** + * Name of test bundle. + */ + private static final String NAME = "fr.agrometinfo.www.server.test"; /** * {@link MethodSource} annotation marks this method as parameters provider. @@ -45,7 +45,7 @@ class I18nTest { Arguments.of(3, KEY, "Il y a 3 produits dans votre panier, ce qui est peu."), // Arguments.of(42, KEY, "Il y a 42 produits dans votre panier, ce qui est un nombre spécial."), // Arguments.of(101, KEY, "Il y a 101 produits dans votre panier, ce qui est beaucoup."), // - Arguments.of(1314, KEY, "Il y a 1 314 produits dans votre panier, ce qui est beaucoup."), // +Arguments.of(1_314, KEY, "Il y a 1 314 produits dans votre panier, ce qui est beaucoup."), // Arguments.of(1, "cats", "Un chat"), // // Variation is not present, default value. Arguments.of(2, "cats", "2 chats"), // @@ -64,8 +64,8 @@ class I18nTest { @Test void contructorWithResourceBundle() { - final ResourceBundle bundle = ResourceBundle.getBundle(NAME, Locale.FRENCH); - final I18n res = new I18n(bundle); + final var bundle = ResourceBundle.getBundle(NAME, Locale.FRENCH); + final var res = new I18n(bundle); String actual; String expected; actual = res.get("error.title"); @@ -79,38 +79,38 @@ class I18nTest { @Test void format() { - final String actual = res.format("warning.missing", "climat", 1, "WIND"); - final String expected = "climat : ligne 1 : WIND manque."; + final var actual = res.format("warning.missing", "climat", 1, "WIND"); + final var expected = "climat : ligne 1 : WIND manque."; assertEquals(expected, actual); } @ParameterizedTest(name = "formatPluralDefault {index}: {0} {1}") @MethodSource("formatPluralData") void formatPluralDefault(final int nb, final String key, final String expected) { - final String actual = res.format(nb, key, nb); + final var actual = res.format(nb, key, nb); assertEquals(expected, actual); } @Test void formatPluralSpecialDefaultProperties() { final int nb = 42; - final I18n korea = new I18n(NAME, Locale.KOREA); - final String actual = korea.format(nb, KEY, nb); - final String expected = "There are 42 items in your cart, a special number!"; + final var korea = new I18n(NAME, Locale.KOREA); + final var actual = korea.format(nb, KEY, nb); + final var expected = "There are 42 items in your cart, a special number!"; assertEquals(expected, actual); } @Test void getStringDefault() { - final String actual = res.get("not.translated"); - final String expected = "This message is not translated."; + final var actual = res.get("not.translated"); + final var expected = "This message is not translated."; assertEquals(expected, actual); } @Test void getStringExisting() { - final String actual = res.get("error.title"); - final String expected = "Erreur"; + final var actual = res.get("error.title"); + final var expected = "Erreur"; assertEquals(expected, actual); } diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/SurveyFormHibernateTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/SurveyFormHibernateTest.java index f73e89a4..e663e0a5 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/SurveyFormHibernateTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/SurveyFormHibernateTest.java @@ -33,14 +33,14 @@ import fr.agrometinfo.www.server.model.UserResponse; * */ public class SurveyFormHibernateTest { - /** DAO for user's responses. */ - private final UserResponsesDao userResponsesDao = new UserResponsesDaoHibernate(); /** DAO for questions. */ private final SurveyQuestionDao questionsDao = new SurveyQuestionDaoHibernate(); /** DAO for responses. */ private final SurveyOptionDao responsesDao = new SurveyOptionDaoHibernate(); /** DAO for email address of user. */ private final UserEmailDao userEmailDao = new UserEmailDaoHibernate(); + /** DAO for user's responses. */ + private final UserResponsesDao userResponsesDao = new UserResponsesDaoHibernate(); @Test public void getQuestion() { @@ -48,7 +48,7 @@ public class SurveyFormHibernateTest { assertFalse(list.isEmpty(), "Questions list is empty"); for (final SurveyQuestion q : list) { // search question by reference. - final SurveyQuestion foundedByRef = questionsDao.findByRef(q.getId()); + final var foundedByRef = questionsDao.findByRef(q.getId()); assertNotNull(foundedByRef, "Object for question « " + q.getId() + " » is null"); assertEquals(q, foundedByRef, "Object corresponding to question « " + q.getId() + " » doesn't corresponding"); } @@ -63,25 +63,45 @@ public class SurveyFormHibernateTest { assertTrue(questions.contains(r.getQuestion()), "Questions list doesn't contains question " + r.getQuestion().getId()); // Test from question corresponding to response - final SurveyQuestion q = r.getQuestion(); + final var q = r.getQuestion(); assertNotNull(q, "Question corresponding to response « " + r.getId() + " » is null"); - final SurveyQuestion foundedByRef = questionsDao.findByRef(q.getId()); + final var foundedByRef = questionsDao.findByRef(q.getId()); assertNotNull(foundedByRef, "Object corresponding to question « " + q.getId() + " » doesn't corresponding"); assertEquals(r.getQuestion(), foundedByRef, "Object corresponding to question « " + q.getId() + " » doesn't corresponding"); // Search response by reference - final SurveyOption responseByRef = responsesDao.findByRef(r.getId()); + final var responseByRef = responsesDao.findByRef(r.getId()); assertNotNull(responseByRef, "Object corresponding to response " + r.getId() + " is null"); assertEquals(r, responseByRef, "Object corresponding to response " + r.getId() + " is empty"); } } + /** + * Return randomly responses list + * @param list original list + * @param nbElements to pick + * @return + */ + private List<SurveyOption> pickNRandom(final List<SurveyOption> list, final int nbElements) { + final List<SurveyOption> copy = new ArrayList<>(list); + Collections.shuffle(copy); + if (nbElements > copy.size()) { + return copy.subList(0, copy.size()); + } else { + return copy.subList(0, nbElements); + } + } + private void resetUserResponses() { + this.userResponsesDao.deleteAll(); + this.userEmailDao.deleteAll(); + } + @Test public void setUserResponses() { this.resetUserResponses(); final List<SurveyQuestion> questions = questionsDao.findAll(); - final SurveyQuestion profession = questions.stream().filter((q) -> q.getDescription().contains("profession")).findFirst().get(); + final var profession = questions.stream().filter((q) -> q.getDescription().contains("profession")).findFirst().get(); assertNotNull(profession, "No question object matching to question of question about profession"); List<SurveyOption> responses = responsesDao.findAllByQuestion(profession.getId()); assertNotNull(responses, "No response object matching to question of question about profession"); @@ -89,19 +109,16 @@ public class SurveyFormHibernateTest { for (final SurveyOption r : responses) { assertEquals(r.getQuestion(), profession, "Question of responses doesn't corresponding to original question"); } - // Inserting a single response final List<SurveyOption> listOfResponses = new ArrayList<>(); // list of inserted answers SurveyOption r = responses.get(ThreadLocalRandom.current().nextInt(0, responses.size() - 1)); userResponsesDao.insertResponse(profession, r, null); listOfResponses.add(r); - List<UserResponse> list = userResponsesDao.findAllByQuestion(profession.getId()); assertEquals(1, list.size(), "The user's response list must contain an item only"); assertEquals(profession, list.get(0).getQuestion(), "The question in the user's response does not match the original question"); assertEquals(r, list.get(0).getOption(), "The answer contained in the user's response does not match the inserted answer"); assertNull(list.get(0).getOtherText(), "Free response must be null"); - // Inserting of multiple responses final int nbToInsert = 3; for (final SurveyOption res : pickNRandom(responses, nbToInsert)) { @@ -116,13 +133,10 @@ public class SurveyFormHibernateTest { assertEquals(profession, ur.getOption().getQuestion(), "The original question does not match with the Question object present in the Option object"); assertNull(ur.getOtherText(), "The text must be null if it is an answer from a choice"); } - final int newNbResponses = 1 + nbToInsert; - // Insertion of a free choice answer - String other = "This is a free answer"; + var other = "This is a free answer"; userResponsesDao.insertResponse(profession, null, other); - list = userResponsesDao.findAllByQuestion(profession.getId()); assertEquals(list.size(), (newNbResponses + 1), "The user's response list must contain the " + newNbResponses + "+ the free answer"); for (final UserResponse ur : list) { @@ -135,25 +149,20 @@ public class SurveyFormHibernateTest { assertNull(ur.getOtherText(), "The text must be null if it is an answer from a choice"); } } - final SurveyQuestion useCase = questions.stream().filter((q) -> q.getId() == 3).findFirst().get(); assertNotNull(useCase, "No object match the use cases question"); responses = responsesDao.findAllByQuestion(useCase.getId()); assertNotNull(responses, "No answer matches the use case question object"); assertFalse(responses.isEmpty(), "The answer list for the use case question object is empty"); - r = responses.get(ThreadLocalRandom.current().nextInt(0, responses.size() - 1)); userResponsesDao.insertResponse(useCase, r, null); - list = userResponsesDao.findAllByQuestion(useCase.getId()); assertEquals(1, list.size(), "The user answer list for the use case question must contain an item only"); assertEquals(useCase, list.get(0).getQuestion(), "The question in the user's response does not match the original question"); assertEquals(r, list.get(0).getOption(), "The answer contained in the user's response does not match the inserted answer"); assertNull(list.get(0).getOtherText(), "Free text must be null"); - other = other.concat(" for the question of use cases"); userResponsesDao.insertResponse(useCase, null, other); - list = userResponsesDao.findAllByQuestion(useCase.getId()); assertEquals(2, list.size(), "The user answer list for the use case question must contain two items"); for (final UserResponse ur : list) { @@ -167,37 +176,18 @@ public class SurveyFormHibernateTest { } } } + @Test public void setUserResponsesWithEmail() { this.resetUserResponses(); // just testing insertion of email user, without insertion of responses (already tested) - final String email = "jane.doe@inrae.fr"; + final var email = "jane.doe@inrae.fr"; List<UserEmail> list = this.userEmailDao.getEmailAddressList(); assertNotNull(list, "The email list is not initialized"); assertTrue(list.isEmpty(), "The email list must be empty"); this.userEmailDao.insertEmailUserAddress(email, LocalDateTime.now()); - list = this.userEmailDao.getEmailAddressList(); assertEquals(1, list.size(), "The email list must contain an item"); assertEquals(email, list.get(0).getEmail(), "The saved item does not match the inserted email « " + email + " »"); } - /** - * Return randomly responses list - * @param list original list - * @param nbElements to pick - * @return - */ - private List<SurveyOption> pickNRandom(final List<SurveyOption> list, final int nbElements) { - final List<SurveyOption> copy = new ArrayList<>(list); - Collections.shuffle(copy); - if (nbElements > copy.size()) { - return copy.subList(0, copy.size()); - } else { - return copy.subList(0, nbElements); - } - } - private void resetUserResponses() { - this.userResponsesDao.deleteAll(); - this.userEmailDao.deleteAll(); - } } diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/dao/CellDaoHibernateTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/dao/CellDaoHibernateTest.java index 06467a0b..ac37e1bb 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/dao/CellDaoHibernateTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/dao/CellDaoHibernateTest.java @@ -11,7 +11,7 @@ public class CellDaoHibernateTest { /** * Total number of cells in the table. */ - public static final long COUNT = 8602; + public static final long COUNT = 8_602; /** * DAO to test. */ @@ -22,7 +22,7 @@ public class CellDaoHibernateTest { */ @Test void count() { - final var actual = dao.count(); + final long actual = dao.count(); assertEquals(COUNT, actual); } diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/dao/DailyValueDaoHibernateTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/dao/DailyValueDaoHibernateTest.java index c11b039f..d7c37383 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/dao/DailyValueDaoHibernateTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/dao/DailyValueDaoHibernateTest.java @@ -14,7 +14,7 @@ class DailyValueDaoHibernateTest { /** * The year with data. */ - static final int YEAR = 2023; + static final int YEAR = 2_023; /** * DAO to test. diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/dao/DailyVisitDaoHibernateTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/dao/DailyVisitDaoHibernateTest.java index b21a22ad..1da6967a 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/dao/DailyVisitDaoHibernateTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/dao/DailyVisitDaoHibernateTest.java @@ -18,7 +18,7 @@ class DailyVisitDaoHibernateTest { @Test void increment() { - final String environment = "test"; + final var environment = "test"; var actual = dao.findAll(); assertNotNull(actual, "List of daily visits must not be null!"); diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernateTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernateTest.java index e1795227..20d7f633 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernateTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernateTest.java @@ -66,6 +66,6 @@ class PraDailyValueDaoHibernateTest { final var actual = dao.findYears(); assertNotNull(actual); assertEquals(Integer.valueOf(1), actual.size()); - assertEquals(Integer.valueOf(2023), actual.get(0)); + assertEquals(Integer.valueOf(2_023), actual.get(0)); } } diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorCategoryTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorCategoryTest.java index 15a59cf2..3b23baad 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorCategoryTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorCategoryTest.java @@ -34,28 +34,6 @@ public class ErrorCategoryTest { return Arrays.asList(AgroMetInfoErrorCategory.class); } - /** - * @param clazz parametrized argument - */ - @ParameterizedTest - @MethodSource("data") - void i18n(final Class<? extends Enum<?>> clazz) { - final Map<Locale, Map<Class<?>, List<String>>> missing = new HashMap<>(); - for (final Locale locale : Arrays.asList(Locale.ENGLISH, Locale.FRENCH)) { - final I18n i18n = new I18n(BUNDLE_NAME, locale); - final Enum<?>[] values = clazz.getEnumConstants(); - for (final Enum<?> value : values) { - final ErrorCategory k = (ErrorCategory) value; - final String tr = i18n.get(k.getI18nKey()); - if (tr.startsWith("!") && tr.endsWith("!")) { - missing.computeIfAbsent(locale, l -> new HashMap<>()); - missing.get(locale).computeIfAbsent(clazz, l -> new ArrayList<>()); - missing.get(locale).get(clazz).add(k.getI18nKey()); - } - } - } - assertTrue(missing.isEmpty(), "Missing translations in " + BUNDLE_NAME + ": " + missing.toString()); - } /** * @param clazz parametrized argument @@ -67,7 +45,7 @@ public class ErrorCategoryTest { final Set<String> codes = new HashSet<>(); final Set<String> duplicates = new HashSet<>(); for (final Enum<?> value : values) { - final ErrorCategory k = (ErrorCategory) value; + final var k = (ErrorCategory) value; if (codes.contains(k.getCode())) { duplicates.add(k.getCode()); } else { @@ -76,4 +54,27 @@ public class ErrorCategoryTest { } assertTrue(duplicates.isEmpty(), duplicates.toString()); } + + /** + * @param clazz parametrized argument + */ + @ParameterizedTest + @MethodSource(value = "data") + void i18n(final Class<? extends Enum<?>> clazz) { + final Map<Locale, Map<Class<?>, List<String>>> missing = new HashMap<>(); + for (final Locale locale : Arrays.asList(Locale.ENGLISH, Locale.FRENCH)) { + final var i18n = new I18n(BUNDLE_NAME, locale); + final Enum<?>[] values = clazz.getEnumConstants(); + for (final Enum<?> value : values) { + final var k = (ErrorCategory) value; + final String tr = i18n.get(k.getI18nKey()); + if (tr.startsWith("!") && tr.endsWith("!")) { + missing.computeIfAbsent(locale, l -> new HashMap<>()); + missing.get(locale).computeIfAbsent(clazz, l -> new ArrayList<>()); + missing.get(locale).get(clazz).add(k.getI18nKey()); + } + } + } + assertTrue(missing.isEmpty(), "Missing translations in " + BUNDLE_NAME + ": " + missing.toString()); + } } diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorTypeTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorTypeTest.java index 44cdb201..b6a3b93d 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorTypeTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/exception/ErrorTypeTest.java @@ -44,10 +44,10 @@ public class ErrorTypeTest { void i18n(final Class<? extends Enum<?>> clazz) { final Map<Locale, Map<Class<?>, List<String>>> missing = new HashMap<>(); for (final Locale locale : Arrays.asList(Locale.ENGLISH, Locale.FRENCH)) { - final I18n i18n = new I18n(BUNDLE_NAME, locale); + final var i18n = new I18n(BUNDLE_NAME, locale); final Enum<?>[] values = clazz.getEnumConstants(); for (final Enum<?> value : values) { - final ErrorType k = (ErrorType) value; + final var k = (ErrorType) value; final String tr = i18n.get(k.getI18nKey()); if (tr.startsWith("!") && tr.endsWith("!")) { missing.computeIfAbsent(locale, l -> new HashMap<>()); @@ -69,7 +69,7 @@ public class ErrorTypeTest { final Set<String> codes = new HashSet<>(); final Set<String> duplicates = new HashSet<>(); for (final Enum<?> value : values) { - final ErrorType k = (ErrorType) value; + final var k = (ErrorType) value; if (codes.contains(k.getSubCode())) { duplicates.add(k.getSubCode()); } else { diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/rs/GeometryResourceTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/rs/GeometryResourceTest.java index a2b03158..59b69f6d 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/rs/GeometryResourceTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/rs/GeometryResourceTest.java @@ -45,7 +45,7 @@ class GeometryResourceTest extends JerseyTest { @Override protected final Application configure() { - final CacheService cacheService = new CacheService(); + final var cacheService = new CacheService(); cacheService.setLastModification(SimulationDaoHibernateTest.LAST_MODIFICATION); cacheService.setCacheDirectory(cacheDir.toString()); final PraDao praDao = new PraDaoHibernate(); @@ -63,7 +63,7 @@ class GeometryResourceTest extends JerseyTest { */ @Test void getPra() { - final FeatureCollection actual = target(GeometryService.PATH + SEP + GeometryService.PATH_PRA)// + final var actual = target(GeometryService.PATH + SEP + GeometryService.PATH_PRA)// .request()// .get(FeatureCollection.class); assertNotNull(actual); diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/rs/IndicatorResourceTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/rs/IndicatorResourceTest.java index 21e3eace..23a48334 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/rs/IndicatorResourceTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/rs/IndicatorResourceTest.java @@ -73,7 +73,7 @@ class IndicatorResourceTest extends JerseyTest { final IndicatorDao indicatorDao = new IndicatorDaoHibernate(); final RegionDao regionDao = new RegionDaoHibernate(); final SimulationDao simulationDao = new SimulationDaoHibernate(); - final CacheService cacheService = new CacheService(); + final var cacheService = new CacheService(); cacheService.setLastModification(SimulationDaoHibernateTest.LAST_MODIFICATION); cacheService.setCacheDirectory(cacheDir.toString()); return new ResourceConfig(IndicatorResource.class).register(new AbstractBinder() { @@ -95,7 +95,7 @@ class IndicatorResourceTest extends JerseyTest { */ @Test void getSummary() { - final SummaryDTO actual = target(IndicatorService.PATH + SEP + IndicatorService.PATH_SUMMARY)// + final var actual = target(IndicatorService.PATH + SEP + IndicatorService.PATH_SUMMARY)// .queryParam("indicator", "rainsum") // .queryParam("period", "year") // .queryParam("level", "PRA") // @@ -114,7 +114,7 @@ class IndicatorResourceTest extends JerseyTest { */ @Test void getValues() { - final FeatureCollection actual = target(IndicatorService.PATH + SEP + IndicatorService.PATH_VALUES)// + final var actual = target(IndicatorService.PATH + SEP + IndicatorService.PATH_VALUES)// .queryParam("indicator", "rainsum") // .queryParam("period", "year") // .queryParam("compare", "false") // diff --git a/www-server/src/test/java/fr/agrometinfo/www/server/rs/SurveyFormResourceTest.java b/www-server/src/test/java/fr/agrometinfo/www/server/rs/SurveyFormResourceTest.java index b9ba3356..c20c4e2f 100644 --- a/www-server/src/test/java/fr/agrometinfo/www/server/rs/SurveyFormResourceTest.java +++ b/www-server/src/test/java/fr/agrometinfo/www/server/rs/SurveyFormResourceTest.java @@ -73,22 +73,22 @@ public class SurveyFormResourceTest extends JerseyTest { } /** Path separator. */ private static final String SEP = "/"; + /** Mail service. */ + private final MailService mailService = new MailServiceTest(); /** Parsing JSON to object. */ private final ObjectMapper objectMapper = new ObjectMapper(); /** DAO for Questions. */ private final SurveyQuestionDao questionsDao = new SurveyQuestionDaoHibernate(); /** DAO for Responses. */ private final SurveyOptionDao responsesDao = new SurveyOptionDaoHibernate(); - /** DAO for UserResponses. */ - private final UserResponsesDao userResponsesDao = new UserResponsesDaoHibernate(); /** DAO for UserMail */ private final UserEmailDao userEmailDao = new UserEmailDaoHibernate(); - /** Mail service. */ - private final MailService mailService = new MailServiceTest(); + /** DAO for UserResponses. */ + private final UserResponsesDao userResponsesDao = new UserResponsesDaoHibernate(); @Override protected final Application configure() { - final AgroMetInfoConfiguration config = new AgroMetInfoConfiguration(); + final var config = new AgroMetInfoConfiguration(); config.set(AgroMetInfoConfiguration.ConfigurationKey.LOG_EMAIL, "log@example.com"); return new ResourceConfig(SurveyFormResource.class).register(new AbstractBinder() { @Override @@ -126,16 +126,37 @@ public class SurveyFormResourceTest extends JerseyTest { log.info(e.getMessage()); } } + /** + * + * @param list origin list + * @param nbElements to pick in list + * @return randomized list with nbElements + */ + private List<SurveyOption> pickNRandom(final List<SurveyOption> list, final int nbElements) { + final List<SurveyOption> copy = new ArrayList<>(list); + Collections.shuffle(copy); + if (nbElements > copy.size()) { + return copy.subList(0, copy.size()); + } else { + return copy.subList(0, nbElements); + } + } + /** + * Reset tables. + */ + private void resetUserResponses() { + this.userResponsesDao.deleteAll(); + this.userEmailDao.deleteAll(); + } + /** Test by setting answers for questions. */ @Test public void testWithJsonResponses() { this.resetUserResponses(); final List<SurveyQuestion> questionsList = questionsDao.findAll(); final List<SurveyQuestionDTO> questionsDTO = questionsList.stream().map(SurveyFormResource::toDto).toList(); - final List<SurveyOption> responsesList = new ArrayList<>(); final HashMap<Long, String> otherTextMap = new HashMap<>(); - for (final SurveyQuestion q : questionsList) { final List<SurveyOption> responsesListForQuestion = responsesDao.findAllByQuestion(q.getId()); @@ -149,18 +170,14 @@ public class SurveyFormResourceTest extends JerseyTest { otherTextMap.put(q.getId(), "Free answer for the question « " + q.getDescription() + " »"); } final List<SurveyOptionDTO> responsesDTO = responsesList.stream().map(SurveyFormResource::toDto).toList(); - - final SurveyResponseDTO data = new SurveyResponseDTO(questionsDTO, responsesDTO, otherTextMap); + final var data = new SurveyResponseDTO(questionsDTO, responsesDTO, otherTextMap); data.setEmail("john.doe@inrae.fr"); assertEquals(data.getQuestions(), questionsDTO, "List of questions in LoginFormData object does not match with original list"); assertEquals(data.getResponses(), responsesDTO, "List of responses in LoginFormData object does not match with the original list"); assertEquals(data.getOtherTextMap(), otherTextMap, "List of free responses in LoginFormData object does not match with the original list"); - - jakarta.ws.rs.core.Response ret = target(SurveyFormService.PATH + SEP + SurveyFormService.PATH_INSERT_RESPONSE) + var ret = target(SurveyFormService.PATH + SEP + SurveyFormService.PATH_INSERT_RESPONSE) .request(MediaType.APPLICATION_JSON).post(Entity.entity(data, MediaType.APPLICATION_JSON)); - assertEquals(ret.getStatus(), jakarta.ws.rs.core.Response.Status.OK.getStatusCode(), "The insert entry point should return status code 200 (OK)"); - // Retrieves all answers for all questions List<UserResponse> list = new ArrayList<>(); for (final SurveyQuestion q : questionsDao.findAll()) { @@ -171,7 +188,6 @@ public class SurveyFormResourceTest extends JerseyTest { }); list.addAll(responsesByQuestion); } - // Test on all answers list.forEach((ur) -> { assertNotNull(ur.getDateTime(), "The response timestamp must not be null"); @@ -184,55 +200,27 @@ public class SurveyFormResourceTest extends JerseyTest { assertNotNull(ur.getOtherText(), "The user's free response, for a predefined response, must not be null"); } }); - // Check if all records has the same datetime assertEquals(list.stream().map((u) -> u.getDateTime()).distinct().count(), 1, "Not all answers have the same datetime"); final LocalDateTime datetimeResponse = list.stream().map((u) -> u.getDateTime()).distinct().findFirst().get(); assertNotNull(datetimeResponse, "The datetime read in the responses is null"); - // in this case, email address has inserted final List<UserEmail> emails = this.userEmailDao.getEmailAddressList(); assertNotNull(emails, "The email list is not initialized (= null)"); assertFalse(emails.isEmpty(), "Email list is empty"); - emails.forEach((e) -> { assertTrue((e.getId() > 0), "The object id must be greater than 0"); assertNotNull(e.getDatetime(), "The timestamp of the question must not be null"); assertNotNull(e.getEmail(), "The email address contained in the subject must not be null"); }); - assertEquals(emails.stream().map((e) -> e.getDatetime()).distinct().count(), 1, "Not all email addresses have the same datetime"); final LocalDateTime datetimeEmail = emails.stream().map((e) -> e.getDatetime()).distinct().findFirst().get(); assertNotNull(datetimeEmail, "The datetime read in emails is null"); - assertEquals(datetimeResponse, datetimeEmail, "The two datetimes are not identical"); - // Check mail sended to support, when user filled survey form final Mail mail = ((MailServiceTest) this.mailService).getMail(); assertNotNull(mail, "The mail object must not be null"); assertNotNull(mail.getContent(), "Message body is not defined (= null)"); assertFalse(mail.getContent().isEmpty(), "The message body is empty"); } - /** - * - * @param list origin list - * @param nbElements to pick in list - * @return randomized list with nbElements - */ - private List<SurveyOption> pickNRandom(final List<SurveyOption> list, final int nbElements) { - final List<SurveyOption> copy = new ArrayList<>(list); - Collections.shuffle(copy); - if (nbElements > copy.size()) { - return copy.subList(0, copy.size()); - } else { - return copy.subList(0, nbElements); - } - } - /** - * Reset tables. - */ - private void resetUserResponses() { - this.userResponsesDao.deleteAll(); - this.userEmailDao.deleteAll(); - } } diff --git a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/ChoiceDTO.java b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/ChoiceDTO.java index b93db590..40cf0a0d 100644 --- a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/ChoiceDTO.java +++ b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/ChoiceDTO.java @@ -5,6 +5,8 @@ import java.io.Serializable; import org.dominokit.jackson.annotation.JSONMapper; import com.fasterxml.jackson.annotation.JsonIgnore; +import static java.lang.Boolean.FALSE; +import static java.lang.Boolean.TRUE; /** * Choice from user to get indicators. @@ -21,27 +23,26 @@ public final class ChoiceDTO implements Serializable { /** * The user wants to compare with normal. */ - private Boolean comparison = Boolean.FALSE; + private Boolean comparison = FALSE; - /** - * ID of chosen indicator. - */ - private String indicator; - - /** - * Period code of chosen indicator. - */ - private String period; /** * ID of chosen feature (region in left panel, PRA on map). */ private String featureId; + /** + * ID of chosen indicator. + */ + private String indicator; /** * Level of chosen feature (region in left panel or PRA on map). */ private FeatureLevel level; + /** + * Period code of chosen indicator. + */ + private String period; /** * Chosen year. @@ -52,7 +53,7 @@ public final class ChoiceDTO implements Serializable { * @return true if the user wants to compare with normal. */ public boolean getComparison() { - return Boolean.TRUE.equals(comparison); + return TRUE.equals(comparison); } /** diff --git a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/ErrorResponseDTO.java b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/ErrorResponseDTO.java index 4a7a6a51..bc9a87f7 100644 --- a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/ErrorResponseDTO.java +++ b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/ErrorResponseDTO.java @@ -15,25 +15,24 @@ public class ErrorResponseDTO { * @return instance */ public static ErrorResponseDTO of(final int statusCode, final String reasonPhrase, final String explanation) { - final ErrorResponseDTO dto = new ErrorResponseDTO(); + final var dto = new ErrorResponseDTO(); dto.setExplanation(explanation); dto.setReasonPhrase(reasonPhrase); dto.setStatusCode(statusCode); return dto; } /** - * HTTP status code. + * Explanation. */ - private int statusCode; + private String explanation; /** * Related HTTP status message. */ private String reasonPhrase; - /** - * Explanation. + * HTTP status code. */ - private String explanation; + private int statusCode; /** * @return Explanation diff --git a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/FeatureProperty.java b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/FeatureProperty.java index 9a7ab740..74a239d1 100644 --- a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/FeatureProperty.java +++ b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/FeatureProperty.java @@ -36,7 +36,7 @@ public enum FeatureProperty { * @return enum name as camel case format */ public String toCamelCase() { - String str = name().toLowerCase(); + var str = name().toLowerCase(); while (str.contains("_")) { str = str.replaceFirst("_[a-z]", String.valueOf(Character.toUpperCase(str.charAt(str.indexOf("_") + 1)))); } diff --git a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/IndicatorDTO.java b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/IndicatorDTO.java index 172a9eef..eddbcb6b 100644 --- a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/IndicatorDTO.java +++ b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/IndicatorDTO.java @@ -15,10 +15,6 @@ public class IndicatorDTO implements Serializable { * UID for Serializable. */ private static final long serialVersionUID = 5820780438006585102L; - /** - * Localized description. - */ - private String description; /** * UID. * @@ -29,6 +25,10 @@ public class IndicatorDTO implements Serializable { * Color sequence name as defined in {@link ColorSequences}. */ private String colorSequenceName; + /** + * Localized description. + */ + private String description; /** * Number of classes, for linear. diff --git a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/QuantileType.java b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/QuantileType.java index 720aa1de..2cd708ce 100644 --- a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/QuantileType.java +++ b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/QuantileType.java @@ -64,7 +64,7 @@ public enum QuantileType { */ QuantileType(final int... values) { bounds = values; - int prev = 0; + var prev = 0; for (final int value : values) { labels.add(prev + "-" + value + "%"); prev = value; diff --git a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SimpleFeature.java b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SimpleFeature.java index 054c139e..2bae9f0e 100644 --- a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SimpleFeature.java +++ b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SimpleFeature.java @@ -16,14 +16,14 @@ public class SimpleFeature implements Serializable { * Unique identifier. */ private String id; - /** - * Display name. - */ - private String name; /** * Level. */ private FeatureLevel level; + /** + * Display name. + */ + private String name; /** * @return Unique identifier. diff --git a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SummaryDTO.java b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SummaryDTO.java index 140611ba..5f8f24de 100644 --- a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SummaryDTO.java +++ b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SummaryDTO.java @@ -17,14 +17,14 @@ public class SummaryDTO implements Serializable { * Index in the array for the computed daily value. */ public static final int COMPUTED_INDEX = 0; - /** - * Index in the array for the quantile 5%. - */ - public static final int Q5_INDEX = 1; /** * Index in the array for the quantile 50%. */ public static final int MEDIAN_INDEX = 2; + /** + * Index in the array for the quantile 5%. + */ + public static final int Q5_INDEX = 1; /** * Index in the array for the quantile 95%. */ diff --git a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyOptionDTO.java b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyOptionDTO.java index 029b6dee..1c5aefb6 100644 --- a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyOptionDTO.java +++ b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyOptionDTO.java @@ -9,6 +9,10 @@ import org.dominokit.jackson.annotation.JSONMapper; */ @JSONMapper public class SurveyOptionDTO { + /** + * Label of response. + */ + private String description; /** * Reference of this response. */ @@ -18,9 +22,11 @@ public class SurveyOptionDTO { */ private SurveyQuestionDTO question; /** - * Label of response. + * @return the fullname */ - private String description; + public String getDescription() { + return description; + } /** * @return the responseRef */ @@ -34,10 +40,10 @@ public class SurveyOptionDTO { return question; } /** - * @return the fullname + * @param value the fullname to set */ - public String getDescription() { - return description; + public void setDescription(final String value) { + this.description = value; } /** * @param value the responseRef to set @@ -51,10 +57,4 @@ public class SurveyOptionDTO { public void setQuestion(final SurveyQuestionDTO dto) { this.question = dto; } - /** - * @param value the fullname to set - */ - public void setDescription(final String value) { - this.description = value; - } } diff --git a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyQuestionDTO.java b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyQuestionDTO.java index 172020df..20273b7f 100644 --- a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyQuestionDTO.java +++ b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyQuestionDTO.java @@ -1,6 +1,7 @@ package fr.agrometinfo.www.shared.dto; import java.util.Objects; +import static java.util.Objects.hash; import org.dominokit.jackson.annotation.JSONMapper; @@ -11,19 +12,26 @@ import org.dominokit.jackson.annotation.JSONMapper; */ @JSONMapper public class SurveyQuestionDTO { - /** - * Reference of question. - */ - private long id; /** * Label of question. */ private String description; /** - * @return the questionRef + * Reference of question. */ - public long getId() { - return id; + private long id; + /** */ + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + var other = (SurveyQuestionDTO) obj; + return Objects.equals(description, other.description) + && id == other.id; } /** * @return the fullName @@ -32,10 +40,16 @@ public class SurveyQuestionDTO { return description; } /** - * @param value the questionRef to set + * @return the questionRef */ - public void setId(final long value) { - this.id = value; + public long getId() { + return id; + } + + /** */ + @Override + public int hashCode() { + return hash(description, id); } /** * @param value the fullName to set @@ -43,22 +57,10 @@ public class SurveyQuestionDTO { public void setDescription(final String value) { this.description = value; } - /** */ - @Override - public int hashCode() { - return Objects.hash(description, id); - } - /** */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - SurveyQuestionDTO other = (SurveyQuestionDTO) obj; - return Objects.equals(description, other.description) - && id == other.id; + /** + * @param value the questionRef to set + */ + public void setId(final long value) { + this.id = value; } } diff --git a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyResponseDTO.java b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyResponseDTO.java index 67054b18..b9c1abae 100644 --- a/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyResponseDTO.java +++ b/www-shared/src/main/java/fr/agrometinfo/www/shared/dto/SurveyResponseDTO.java @@ -10,6 +10,15 @@ import java.util.Map; * */ public class SurveyResponseDTO { + /** + * Email user.<br> + * Can be null if user don't provide it (by called {@link SurveyResponseDTO#setEmail(String)} method only). + */ + private String email = null; + /** + * Storage, for each response, the other text, if specified. + */ + private Map<Long, String> otherTextMap = new HashMap<>(); /** * List of login form questions.<br> * This list questions contains available questions, obtained by {@link QuestionsDao} @@ -20,15 +29,6 @@ public class SurveyResponseDTO { * This list responses contains available responses, obtained by {@link ResponsesDao} */ private List<SurveyOptionDTO> responses; - /** - * Storage, for each response, the other text, if specified. - */ - private Map<Long, String> otherTextMap = new HashMap<>(); - /** - * Email user.<br> - * Can be null if user don't provide it (by called {@link SurveyResponseDTO#setEmail(String)} method only). - */ - private String email = null; /** * Default constructor. */ @@ -47,16 +47,10 @@ public class SurveyResponseDTO { this.otherTextMap = otherText; } /** - * @return the questions - */ - public List<SurveyQuestionDTO> getQuestions() { - return questions; - } - /** - * @return the responses + * @return the email */ - public List<SurveyOptionDTO> getResponses() { - return responses; + public String getEmail() { + return email; } /** * @return the otherTextMap @@ -65,16 +59,22 @@ public class SurveyResponseDTO { return otherTextMap; } /** - * @param questionsList the questions to set + * @return the questions */ - public void setQuestions(final List<SurveyQuestionDTO> questionsList) { - this.questions = questionsList; + public List<SurveyQuestionDTO> getQuestions() { + return questions; } /** - * @param responsesList the responses to set + * @return the responses */ - public void setResponses(final List<SurveyOptionDTO> responsesList) { - this.responses = responsesList; + public List<SurveyOptionDTO> getResponses() { + return responses; + } + /** + * @param value the email to set + */ + public void setEmail(final String value) { + this.email = value; } /** * @param map the otherTextMap to set @@ -83,15 +83,15 @@ public class SurveyResponseDTO { this.otherTextMap = map; } /** - * @return the email + * @param questionsList the questions to set */ - public String getEmail() { - return email; + public void setQuestions(final List<SurveyQuestionDTO> questionsList) { + this.questions = questionsList; } /** - * @param value the email to set + * @param responsesList the responses to set */ - public void setEmail(final String value) { - this.email = value; + public void setResponses(final List<SurveyOptionDTO> responsesList) { + this.responses = responsesList; } } diff --git a/www-shared/src/main/java/org/geojson/Feature.java b/www-shared/src/main/java/org/geojson/Feature.java index c0b0e3f5..30dbbef3 100644 --- a/www-shared/src/main/java/org/geojson/Feature.java +++ b/www-shared/src/main/java/org/geojson/Feature.java @@ -17,10 +17,6 @@ public final class Feature extends GeoJsonObject { */ private static final long serialVersionUID = 5820780438006585201L; - /** - * Associated properties. - */ - private Map<String, String> properties = new HashMap<>(); /** * Geometric attribute of the feature. @@ -31,6 +27,10 @@ public final class Feature extends GeoJsonObject { * A unique identifier for the feature, never <code>null</code>. */ private String id; + /** + * Associated properties. + */ + private Map<String, String> properties = new HashMap<>(); /** * Constructor. diff --git a/www-shared/src/main/java/org/geojson/FeatureCollection.java b/www-shared/src/main/java/org/geojson/FeatureCollection.java index 8527be6f..cf8e8641 100644 --- a/www-shared/src/main/java/org/geojson/FeatureCollection.java +++ b/www-shared/src/main/java/org/geojson/FeatureCollection.java @@ -16,7 +16,7 @@ public final class FeatureCollection extends GeoJsonObject { /** * UID for Serializable. */ - private static final long serialVersionUID = 5820780438006585202L; + private static final long serialVersionUID = 5_820_780_438_006_585_202L; /** * The Features within this FeatureCollection. diff --git a/www-shared/src/main/java/org/geojson/LngLatAlt.java b/www-shared/src/main/java/org/geojson/LngLatAlt.java index 1fe9e5b9..381c9462 100644 --- a/www-shared/src/main/java/org/geojson/LngLatAlt.java +++ b/www-shared/src/main/java/org/geojson/LngLatAlt.java @@ -1,6 +1,7 @@ package org.geojson; import java.io.Serializable; +import static java.lang.Double.NaN; import org.dominokit.jackson.annotation.JSONMapper; @@ -19,17 +20,17 @@ public final class LngLatAlt implements Serializable { private static final long serialVersionUID = 5820780438006585204L; /** - * "X" according to the specification, longitude in a geographic CRS. + * "Z" according to the specification, altitude in a geographic CRS. */ - private double longitude; + private double altitude = NaN; /** * "Y" according to the specification, latitude in a geographic CRS. */ private double latitude; /** - * "Z" according to the specification, altitude in a geographic CRS. + * "X" according to the specification, longitude in a geographic CRS. */ - private double altitude = Double.NaN; + private double longitude; /** * Constructor. diff --git a/www-shared/src/main/java/org/geojson/MultiPolygon.java b/www-shared/src/main/java/org/geojson/MultiPolygon.java index f4423845..2f9dca45 100644 --- a/www-shared/src/main/java/org/geojson/MultiPolygon.java +++ b/www-shared/src/main/java/org/geojson/MultiPolygon.java @@ -12,15 +12,15 @@ import org.dominokit.jackson.annotation.JSONMapper; */ @JSONMapper public class MultiPolygon extends GeoJsonObject { - /** - * UID for Serializable. - */ - private static final long serialVersionUID = 5820780438006585205L; /** * GeoJSON object type. */ private static final String TYPE = "MultiPolygon"; + /** + * UID for Serializable. + */ + private static final long serialVersionUID = 5820780438006585205L; /** * Coordinates of the polygon. diff --git a/www-shared/src/main/java/org/geojson/Polygon.java b/www-shared/src/main/java/org/geojson/Polygon.java index e2c73e59..da9414b5 100644 --- a/www-shared/src/main/java/org/geojson/Polygon.java +++ b/www-shared/src/main/java/org/geojson/Polygon.java @@ -2,6 +2,7 @@ package org.geojson; import java.util.ArrayList; import java.util.Arrays; +import static java.util.Arrays.asList; import java.util.List; import org.dominokit.jackson.annotation.JSONMapper; @@ -13,15 +14,15 @@ import org.dominokit.jackson.annotation.JSONMapper; */ @JSONMapper public final class Polygon extends GeoJsonObject { - /** - * UID for Serializable. - */ - private static final long serialVersionUID = 5820780438006585206L; /** * GeoJSON object type. */ private static final String TYPE = "Polygon"; + /** + * UID for Serializable. + */ + private static final long serialVersionUID = 5820780438006585206L; /** * Coordinates of the polygon. @@ -52,7 +53,7 @@ public final class Polygon extends GeoJsonObject { */ public Polygon(final LngLatAlt... polygon) { super(TYPE); - add(Arrays.asList(polygon)); + add(asList(polygon)); } /** diff --git a/www-shared/src/test/java/fr/agrometinfo/www/shared/dto/FeaturePropertyTest.java b/www-shared/src/test/java/fr/agrometinfo/www/shared/dto/FeaturePropertyTest.java index e6130cbd..2a131723 100644 --- a/www-shared/src/test/java/fr/agrometinfo/www/shared/dto/FeaturePropertyTest.java +++ b/www-shared/src/test/java/fr/agrometinfo/www/shared/dto/FeaturePropertyTest.java @@ -1,5 +1,7 @@ package fr.agrometinfo.www.shared.dto; +import static fr.agrometinfo.www.shared.dto.FeatureProperty.INDICATOR_NAME; +import static fr.agrometinfo.www.shared.dto.FeatureProperty.PERIOD_FIRST_DAY; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; @@ -16,11 +18,11 @@ class FeaturePropertyTest { */ @Test void toCamelCase() { - var actual = FeatureProperty.INDICATOR_NAME.toCamelCase(); - var expected = "indicatorName"; + String actual = INDICATOR_NAME.toCamelCase(); + String expected = "indicatorName"; assertEquals(expected, actual); - actual = FeatureProperty.PERIOD_FIRST_DAY.toCamelCase(); + actual = PERIOD_FIRST_DAY.toCamelCase(); expected = "periodFirstDay"; assertEquals(expected, actual); } -- GitLab From e7a7760ea28585206c0f8d046f8c097397c6c3c3 Mon Sep 17 00:00:00 2001 From: Olivier Maury <Olivier.Maury@inrae.fr> Date: Tue, 3 Dec 2024 17:05:58 +0100 Subject: [PATCH 5/6] style: :art: Utiliser Inspect and transform de NetBeans --- .gitignore | 1 + .../java/fr/agrometinfo/www/client/App.java | 4 +- .../www/client/event/FeatureSelectEvent.java | 2 +- .../www/client/event/LoadingEvent.java | 2 +- .../client/presenter/ContactPresenter.java | 2 +- .../www/client/presenter/LayoutPresenter.java | 4 +- .../client/presenter/LeftPanelPresenter.java | 30 ++-- .../www/client/presenter/MapPresenter.java | 23 ++- .../client/presenter/RightPanelPresenter.java | 22 +-- .../www/client/presenter/SurveyPresenter.java | 85 +++++------ .../www/client/ui/AgroclimAppsMenu.java | 9 +- .../www/client/ui/CardDetails.java | 2 +- .../www/client/ui/CollapsedSelect.java | 10 +- .../www/client/ui/DominoListBuilder.java | 8 +- .../www/client/ui/chart/CreditsPlugin.java | 5 +- .../www/client/ui/chart/DailyValuesChart.java | 14 +- .../www/client/ui/chart/LogoPlugin.java | 13 +- .../www/client/ui/map/CanvasAttributions.java | 36 ++--- .../www/client/ui/map/CanvasTitle.java | 42 +++--- .../www/client/ui/map/CanvasWidget.java | 17 +-- .../www/client/ui/map/ControlSuppliers.java | 9 +- .../www/client/ui/map/TileSuppliers.java | 44 +++--- .../www/client/ui/map/ToolTip.java | 10 +- .../www/client/util/ApplicationUtils.java | 12 +- .../www/client/util/DateUtils.java | 2 +- .../util/color/ColorSequenceManager.java | 41 +++--- .../www/client/view/AbstractBaseView.java | 23 +-- .../www/client/view/ContactView.java | 23 ++- .../www/client/view/LayoutView.java | 58 ++++---- .../www/client/view/LeftPanelView.java | 40 +++--- .../agrometinfo/www/client/view/MapView.java | 136 +++++++++--------- .../www/client/view/RightPanelView.java | 35 ++--- .../www/client/view/SurveyView.java | 94 ++++++------ .../util/color/ColorSequenceManagerTest.java | 58 ++++---- .../java/fr/agrometinfo/www/server/I18n.java | 1 - .../server/dao/PraDailyValueDaoHibernate.java | 2 +- .../src/main/java/org/geojson/Polygon.java | 3 +- 37 files changed, 446 insertions(+), 476 deletions(-) diff --git a/.gitignore b/.gitignore index 51fcf403..4b643d75 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ .checkstyle .classpath dependency-reduced-pom.xml +.factorypath .~lock.*# logs/ nbactions.xml diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/App.java b/www-client/src/main/java/fr/agrometinfo/www/client/App.java index 029b3cd7..f949bb80 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/App.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/App.java @@ -1,7 +1,5 @@ package fr.agrometinfo.www.client; -import java.util.Date; - import org.dominokit.domino.api.shared.extension.ContextAggregator; import org.dominokit.rest.DominoRestConfig; import org.dominokit.rest.shared.request.RequestInterceptor; @@ -62,7 +60,7 @@ public class App implements EntryPoint { public static final AppMessages MSGS = GWT.create(AppMessages.class); private static void checkVersion() { - final Date clientDate = ApplicationUtils.getVersionDate(); + final var clientDate = ApplicationUtils.getVersionDate(); if (clientDate != null) { ApplicationServiceFactory.INSTANCE// .getApplicationDate() // diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/event/FeatureSelectEvent.java b/www-client/src/main/java/fr/agrometinfo/www/client/event/FeatureSelectEvent.java index ac12ef8c..b508392e 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/event/FeatureSelectEvent.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/event/FeatureSelectEvent.java @@ -24,7 +24,7 @@ public final class FeatureSelectEvent extends Event<FeatureSelectHandler> { * @return built event */ public static FeatureSelectEvent of(final FeatureLevel level, final String id) { - final FeatureSelectEvent event = new FeatureSelectEvent(); + final var event = new FeatureSelectEvent(); event.setId(id); event.setLevel(level); return event; diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/event/LoadingEvent.java b/www-client/src/main/java/fr/agrometinfo/www/client/event/LoadingEvent.java index cf3f91c5..e9c42725 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/event/LoadingEvent.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/event/LoadingEvent.java @@ -34,7 +34,7 @@ public final class LoadingEvent extends Event<LoadingHandler> { * @return built event */ public static LoadingEvent of(final LoadingEventType eventType) { - final LoadingEvent event = new LoadingEvent(); + final var event = new LoadingEvent(); event.setEventType(eventType); return event; } diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/ContactPresenter.java b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/ContactPresenter.java index 59888194..841bf079 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/ContactPresenter.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/ContactPresenter.java @@ -57,7 +57,7 @@ public final class ContactPresenter implements Presenter { * @param message message */ public void send(final String name, final String emailAddress, final String message) { - final StringJoiner sj = new StringJoiner("\n"); + final var sj = new StringJoiner("\n"); sj.add(message); sj.add(""); sj.add("----"); diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/LayoutPresenter.java b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/LayoutPresenter.java index 8f82944a..2fb7ef4e 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/LayoutPresenter.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/LayoutPresenter.java @@ -80,7 +80,7 @@ public final class LayoutPresenter implements Presenter { * Display contact form. */ public void showContactView() { - final ContactPresenter presenter = new ContactPresenter(); + final var presenter = new ContactPresenter(); presenter.setLayoutView(view); presenter.start(); } @@ -94,7 +94,7 @@ public final class LayoutPresenter implements Presenter { view.init(); view.setDevMode(isDevMode()); - final LeftPanelPresenter leftPanelPresenter = new LeftPanelPresenter(); + final var leftPanelPresenter = new LeftPanelPresenter(); leftPanelPresenter.setLayoutView(view); leftPanelPresenter.setLayoutPresenter(this); leftPanelPresenter.start(); diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/LeftPanelPresenter.java b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/LeftPanelPresenter.java index 99a8c40e..7c814d41 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/LeftPanelPresenter.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/LeftPanelPresenter.java @@ -59,33 +59,35 @@ public final class LeftPanelPresenter implements FeatureSelectHandler, Presenter private static final AppConstants CSTS = GWT.create(AppConstants.class); /** - * Periods from server. + * Year chosen by the user. */ - private List<PeriodDTO> periods; + private Integer chosenYear; /** - * Region id : region name. + * The presenter for the application layout. */ - private final Map<String, String> regions = new HashMap<>(); + private LayoutPresenter layoutPresenter; /** - * Related view. + * The layout handling the panel. */ - private View view; + private LayoutView layoutView; /** - * The layout handling the panel. + * Periods from server. */ - private LayoutView layoutView; + private List<PeriodDTO> periods; /** - * The presenter for the application layout. + * Region id : region name. */ - private LayoutPresenter layoutPresenter; + private final Map<String, String> regions = new HashMap<>(); + /** - * Year chosen by the user. + * Related view. */ - private Integer chosenYear; + private View view; + /** * @param choice the user's choice @@ -93,7 +95,7 @@ public final class LeftPanelPresenter implements FeatureSelectHandler, Presenter public void onChoiceChange(final ChoiceDTO choice) { GWT.log("LeftPanelPresenter.onChoiceChange()"); IndicatorDTO chosenIndicator = null; - String periodName = ""; + var periodName = ""; for (final PeriodDTO period : periods) { if (period.getCode().equals(choice.getPeriod())) { periodName = period.getDescription(); @@ -108,7 +110,7 @@ public final class LeftPanelPresenter implements FeatureSelectHandler, Presenter choice.setFeatureId(null); } chosenYear = choice.getYear(); - final String regionName = regions.getOrDefault(choice.getFeatureId(), CSTS.metropolitanFrance()); + final var regionName = regions.getOrDefault(choice.getFeatureId(), CSTS.metropolitanFrance()); layoutPresenter.onChoiceChange(choice, chosenIndicator, periodName, regionName); } diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/MapPresenter.java b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/MapPresenter.java index 46bb0c24..e2bdaddd 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/MapPresenter.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/MapPresenter.java @@ -6,7 +6,6 @@ import java.util.Map; import org.dominokit.domino.ui.utils.DominoElement; import org.dominokit.rest.JsRestfulRequestFactory; -import org.dominokit.rest.shared.RestfulRequest; import org.geojson.FeatureCollection; import com.google.gwt.core.client.GWT; @@ -66,15 +65,15 @@ public final class MapPresenter implements Presenter { private static final AppConstants CSTS = GWT.create(AppConstants.class); /** - * URL to get indicator values. + * I18N messages. */ - private static final String VALUES_URL = ApplicationUtils.getApplicationUrl() + "/rs/" - + IndicatorService.PATH + "/" + IndicatorService.PATH_VALUES; + private static final AppMessages MSGS = GWT.create(AppMessages.class); /** - * I18N messages. + * URL to get indicator values. */ - private static final AppMessages MSGS = GWT.create(AppMessages.class); + private static final String VALUES_URL = ApplicationUtils.getApplicationUrl() + "/rs/" + + IndicatorService.PATH + "/" + IndicatorService.PATH_VALUES; /** * Container for the map. @@ -82,14 +81,14 @@ public final class MapPresenter implements Presenter { private DominoElement<HTMLDivElement> container; /** - * Related view. + * Date of last modification of indicators values in database. */ - private View view; + private String lastModification = ""; /** - * Date of last modification of indicators values in database. + * Related view. */ - private String lastModification = ""; + private View view; /** * Load indicator values on the map. @@ -111,8 +110,8 @@ public final class MapPresenter implements Presenter { titleLines.add(regionName); titleLines.add(choice.getYear().toString()); titleLines.add(lastModification); - final JsRestfulRequestFactory factory = new JsRestfulRequestFactory(); - final RestfulRequest request = factory.get(VALUES_URL); + final var factory = new JsRestfulRequestFactory(); + final var request = factory.get(VALUES_URL); request.addQueryParam("indicator", choice.getIndicator()); if (choice.getPeriod() != null) { request.addQueryParam("period", choice.getPeriod()); diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/RightPanelPresenter.java b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/RightPanelPresenter.java index b23c312f..f73ada27 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/RightPanelPresenter.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/RightPanelPresenter.java @@ -63,25 +63,20 @@ public final class RightPanelPresenter implements FeatureSelectHandler, MapClick } /** - * Last choice. + * Container for the panel. */ - private ChoiceDTO currentChoice; + private DominoElement<HTMLElement> container; /** - * Related view. + * Last choice. */ - private View view; + private ChoiceDTO currentChoice; /** * The layout handling the panel. */ private LayoutView layoutView; - /** - * Container for the panel. - */ - private DominoElement<HTMLElement> container; - /** * Name of chosen period. */ @@ -97,6 +92,11 @@ public final class RightPanelPresenter implements FeatureSelectHandler, MapClick */ private String selectedPra = null; + /** + * Related view. + */ + private View view; + /** * Load indicator values on the panel. * @@ -119,7 +119,7 @@ public final class RightPanelPresenter implements FeatureSelectHandler, MapClick IndicatorServiceFactory.INSTANCE .getSummary(c.getIndicator(), c.getPeriod(), c.getLevel(), c.getFeatureId(), c.getYear()) // .onSuccess(d -> { - GWT.log("RightPanelPresenter.loadValues() succcess"); + GWT.log("RightPanelPresenter.loadValues() success"); if (FeatureLevel.PRA == c.getLevel() && FeatureLevel.REGION == d.getParentFeature().getLevel()) { regionOfSelectedPra = d.getParentFeature().getId(); } else { @@ -157,7 +157,7 @@ public final class RightPanelPresenter implements FeatureSelectHandler, MapClick // this should not occur as a choice should be made from left panel return; } - final ChoiceDTO choice = new ChoiceDTO(); + final var choice = new ChoiceDTO(); choice.setComparison(currentChoice.getComparison()); choice.setIndicator(currentChoice.getIndicator()); choice.setPeriod(currentChoice.getPeriod()); diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/SurveyPresenter.java b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/SurveyPresenter.java index e04a0224..26751383 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/presenter/SurveyPresenter.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/presenter/SurveyPresenter.java @@ -52,56 +52,29 @@ public final class SurveyPresenter implements Presenter { } /** - * Related view. + * List of questions, extracted from responses list. */ - private final SurveyView view = new SurveyView(); - /** List of responses from webservice. */ - private List<SurveyOptionDTO> responses; - /** List of questions, extracted from responses list. */ private List<SurveyQuestionDTO> questions; + /** - * Set responses and extract questions from responses list. - * @param list list of responses + * List of responses from webservice. */ - private void setResponses(final List<SurveyOptionDTO> list) { - GWT.log("SurveyPresenter.setResponses(" + list.size() + ") enter"); - this.responses = list; - final Map<SurveyQuestionDTO, List<SurveyOptionDTO>> responsesMap = new HashMap<>(); - - // extract questions from responses via webservice - for (final SurveyOptionDTO dto : list) { - if (!responsesMap.containsKey(dto.getQuestion())) { - responsesMap.put(dto.getQuestion(), new ArrayList<SurveyOptionDTO>()); - } - responsesMap.get(dto.getQuestion()).add(dto); - } - this.questions = new ArrayList<>(responsesMap.keySet()); - view.setResponses(responsesMap); - - view.init(); - GWT.log("SurveyPresenter.setResponses() end"); - } - @Override - public void start() { - view.setPresenter(this); + private List<SurveyOptionDTO> responses; - SurveyFormServiceFactory.INSTANCE.getResponses() - .onSuccess(this::setResponses) - .onFailed(view::failureNotification) - .send(); - } - public void insertUserResponses( - final List<Long> responsesRef, - final Map<Long, String> otherTextMap, - final String email) { + /** + * Related view. + */ + private final SurveyView view = new SurveyView(); + public void insertUserResponses(final List<Long> responsesRef, final Map<Long, String> otherTextMap, + final String email) { // processing of predefined responses final Set<SurveyQuestionDTO> questionsDto = new LinkedHashSet<>(); final Set<SurveyOptionDTO> responsesDto = new LinkedHashSet<>(); for (final Long ref : responsesRef) { // getting response by reference - final SurveyOptionDTO rDto = this.responses.stream().filter(r -> r.getId() == ref).findFirst().get(); + final var rDto = this.responses.stream().filter(r -> r.getId() == ref).findFirst().get(); if (rDto != null) { responsesDto.add(rDto); @@ -117,7 +90,7 @@ public final class SurveyPresenter implements Presenter { }); // call to webservice for inserting data - final SurveyResponseDTO data = new SurveyResponseDTO( + final var data = new SurveyResponseDTO( new ArrayList<>(questionsDto), new ArrayList<>(responsesDto), otherTextMap); @@ -128,7 +101,39 @@ public final class SurveyPresenter implements Presenter { } SurveyFormServiceFactory.INSTANCE.insertAllResponses(data) - .onSuccess(view::displaySuccessLogin) + .onSuccess(view::displaySuccessLogin) + .onFailed(view::failureNotification) + .send(); + } + + /** + * Set responses and extract questions from responses list. + * @param list list of responses + */ + private void setResponses(final List<SurveyOptionDTO> list) { + GWT.log("SurveyPresenter.setResponses(" + list.size() + ") enter"); + this.responses = list; + final Map<SurveyQuestionDTO, List<SurveyOptionDTO>> responsesMap = new HashMap<>(); + + // extract questions from responses via webservice + for (final SurveyOptionDTO dto : list) { + if (!responsesMap.containsKey(dto.getQuestion())) { + responsesMap.put(dto.getQuestion(), new ArrayList<>()); + } + responsesMap.get(dto.getQuestion()).add(dto); + } + this.questions = new ArrayList<>(responsesMap.keySet()); + view.setResponses(responsesMap); + + view.init(); + GWT.log("SurveyPresenter.setResponses() end"); + } + @Override + public void start() { + view.setPresenter(this); + + SurveyFormServiceFactory.INSTANCE.getResponses() + .onSuccess(this::setResponses) .onFailed(view::failureNotification) .send(); } diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/ui/AgroclimAppsMenu.java b/www-client/src/main/java/fr/agrometinfo/www/client/ui/AgroclimAppsMenu.java index a651cbd2..5c92faff 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/ui/AgroclimAppsMenu.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/ui/AgroclimAppsMenu.java @@ -2,12 +2,9 @@ package fr.agrometinfo.www.client.ui; import org.dominokit.domino.ui.menu.Menu; import org.jboss.elemento.Elements; -import org.jboss.elemento.HtmlContentBuilder; import com.google.gwt.core.client.GWT; -import elemental2.dom.HTMLAnchorElement; -import elemental2.dom.HTMLLIElement; import fr.agrometinfo.www.client.i18n.AppConstants; /** @@ -39,7 +36,7 @@ public class AgroclimAppsMenu extends Menu<String> { .attr("target", "_blank").textContent(CSTS.otherAgroclimApps()))); // patch to display on mobile super.addOpenHandler(() -> { - final String top = element().style.top; + final var top = element().style.top; if (top != null && top.startsWith("-")) { element().style.top = "0px"; } @@ -54,8 +51,8 @@ public class AgroclimAppsMenu extends Menu<String> { * @param url URL of prod */ private void addMenuItem(final String text, final String logo, final String url) { - final HtmlContentBuilder<HTMLLIElement> link = Elements.li().css("menu-item simple-menu-item"); - final HtmlContentBuilder<HTMLAnchorElement> elem = Elements.a(url).attr("target", "_blank"); + final var link = Elements.li().css("menu-item simple-menu-item"); + final var elem = Elements.a(url).attr("target", "_blank"); link.add(elem); if (logo != null) { elem.add(Elements.img(logo)); diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/ui/CardDetails.java b/www-client/src/main/java/fr/agrometinfo/www/client/ui/CardDetails.java index 158102fd..71e2b3da 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/ui/CardDetails.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/ui/CardDetails.java @@ -53,7 +53,7 @@ public class CardDetails extends BaseDominoElement<HTMLElement, CardDetails> { * Constructor. */ public CardDetails() { - final HTMLElement sum = Elements.createElement("summary", HTMLElement.class); + final var sum = Elements.createElement("summary", HTMLElement.class); sum.append(Elements.span().addAll(title, subTitle, value).element()); sum.append(Icons.MDI_ICONS.information_outline_mdi().element()); root.add(sum); diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/ui/CollapsedSelect.java b/www-client/src/main/java/fr/agrometinfo/www/client/ui/CollapsedSelect.java index e0c13963..d5ba9cbd 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/ui/CollapsedSelect.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/ui/CollapsedSelect.java @@ -16,14 +16,16 @@ import elemental2.dom.MouseEvent; * @author Olivier Maury */ public final class CollapsedSelect { - /** - * The root element. - */ - private final HtmlContentBuilder<HTMLDivElement> root; /** * Span displaying the prompt. */ private final HtmlContentBuilder<HTMLElement> promptSpan = Elements.span(); + + /** + * The root element. + */ + private final HtmlContentBuilder<HTMLDivElement> root; + /** * Span displaying the displayed text of the selected item. */ diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/ui/DominoListBuilder.java b/www-client/src/main/java/fr/agrometinfo/www/client/ui/DominoListBuilder.java index 272625d7..5817062c 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/ui/DominoListBuilder.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/ui/DominoListBuilder.java @@ -11,8 +11,6 @@ import org.dominokit.domino.ui.grid.flex.FlexLayout; import org.dominokit.domino.ui.lists.ListGroup; import org.jboss.elemento.Elements; -import elemental2.dom.HTMLDivElement; - /** * Builder for a Domino {@link ListGroup}, a component that allow selecting a * single option from a panel. @@ -49,7 +47,7 @@ public final class DominoListBuilder<T> extends SelectBuilder<T, ListGroup<T>> { if (selectedItems == null || selectedItems.isEmpty()) { return; } - final T item = selectedItems.get(0).getValue(); + final var item = selectedItems.get(0).getValue(); handler.accept(getTextFunction().apply(item)); }); return this; @@ -61,7 +59,7 @@ public final class DominoListBuilder<T> extends SelectBuilder<T, ListGroup<T>> { if (selectedItems == null || selectedItems.isEmpty()) { return; } - final T item = selectedItems.get(0).getValue(); + final var item = selectedItems.get(0).getValue(); handler.accept(getValueFunction().apply(item)); }); return this; @@ -73,7 +71,7 @@ public final class DominoListBuilder<T> extends SelectBuilder<T, ListGroup<T>> { Objects.requireNonNull(getTextFunction(), "setTextFunction() must be called before!"); return getSelect().setItemRenderer( (listGroup, item) -> { - final FlexItem<HTMLDivElement> flexItem = FlexItem.create() // + final var flexItem = FlexItem.create() // .setFlexGrow(1) // .appendChild(// Elements.span().textContent(getTextFunction().apply(item.getValue()))); diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/ui/chart/CreditsPlugin.java b/www-client/src/main/java/fr/agrometinfo/www/client/ui/chart/CreditsPlugin.java index 6cedeb67..c9940922 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/ui/chart/CreditsPlugin.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/ui/chart/CreditsPlugin.java @@ -1,7 +1,6 @@ package fr.agrometinfo.www.client.ui.chart; import org.pepstock.charba.client.IsChart; -import org.pepstock.charba.client.dom.elements.Context2dItem; import org.pepstock.charba.client.enums.TextAlign; import org.pepstock.charba.client.plugins.AbstractPlugin; @@ -27,8 +26,8 @@ public final class CreditsPlugin extends AbstractPlugin { @Override public void onAfterDraw(final IsChart chart) { - final String text = ApplicationUtils.getAttributions(); - final Context2dItem context = chart.getCanvas().getContext2d(); + final var text = ApplicationUtils.getAttributions(); + final var context = chart.getCanvas().getContext2d(); final int xOffset = FONT_SIZE; final int yOffset = FONT_SIZE; final int x = chart.getCanvas().getWidth() - xOffset; diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/ui/chart/DailyValuesChart.java b/www-client/src/main/java/fr/agrometinfo/www/client/ui/chart/DailyValuesChart.java index c73f2f3f..6e9d2dca 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/ui/chart/DailyValuesChart.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/ui/chart/DailyValuesChart.java @@ -14,8 +14,6 @@ import org.pepstock.charba.client.colors.HtmlColor; import org.pepstock.charba.client.commons.Constants; import org.pepstock.charba.client.configuration.CartesianLinearAxis; import org.pepstock.charba.client.configuration.CartesianTimeSeriesAxis; -import org.pepstock.charba.client.data.DataPoint; -import org.pepstock.charba.client.data.Dataset; import org.pepstock.charba.client.data.LineDataset; import org.pepstock.charba.client.data.LiningDataset; import org.pepstock.charba.client.data.TimeSeriesItem; @@ -71,7 +69,7 @@ public final class DailyValuesChart extends TimeSeriesLineChart { GWT.log("DailyValuesChart() " + values.size()); this.unit = summary.getIndicator().getUnit(); - final String subtitle = MSGS.chartSubtitle(summary.getDate(), unit); + final var subtitle = MSGS.chartSubtitle(summary.getDate(), unit); setTitle(CSTS.dailyValues() + " − " + DateUtils.getYear(summary.getDate()), subtitle); setPlugins(); @@ -140,14 +138,14 @@ public final class DailyValuesChart extends TimeSeriesLineChart { } this.getOptions().getLayout().getPadding().setBottom(2 * CreditsPlugin.FONT_SIZE); - final DateTimeFormat dtf = DateTimeFormat.getFormat(PredefinedFormat.DATE_LONG); + final var dtf = DateTimeFormat.getFormat(PredefinedFormat.DATE_LONG); this.getOptions().getTooltips().getCallbacks().setLabelCallback(new TooltipLabelCallback() { @Override public List<String> onLabel(final IsChart chart, final TooltipItem item) { // checks if arguments are consistent if (IsChart.isConsistent(chart) && item != null) { - final Dataset dataset = chart.getData().retrieveDataset(item); - final String label = MSGS.tooltipLabel(dataset.getLabel(), item.getFormattedValue(), unit); + final var dataset = chart.getData().retrieveDataset(item); + final var label = MSGS.tooltipLabel(dataset.getLabel(), item.getFormattedValue(), unit); return Arrays.asList(label); } // if here, the arguments or the labels are not consistent @@ -159,8 +157,8 @@ public final class DailyValuesChart extends TimeSeriesLineChart { @Override public List<String> onTitle(final IsChart aChart, final List<TooltipItem> items) { final TooltipItem item = items.iterator().next(); - final LineDataset ds = (LineDataset) aChart.getData().getDatasets().get(1); - final DataPoint dp = ds.getDataPoints().get(item.getDataIndex()); + final var ds = (LineDataset) aChart.getData().getDatasets().get(1); + final var dp = ds.getDataPoints().get(item.getDataIndex()); return Arrays.asList(dtf.format(dp.getXAsDate())); } }); diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/ui/chart/LogoPlugin.java b/www-client/src/main/java/fr/agrometinfo/www/client/ui/chart/LogoPlugin.java index 05ce1f1b..0f4a4677 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/ui/chart/LogoPlugin.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/ui/chart/LogoPlugin.java @@ -2,7 +2,6 @@ package fr.agrometinfo.www.client.ui.chart; import org.pepstock.charba.client.IsChart; import org.pepstock.charba.client.dom.elements.CastHelper; -import org.pepstock.charba.client.dom.elements.Context2dItem; import org.pepstock.charba.client.plugins.AbstractPlugin; import com.google.gwt.canvas.client.Canvas; @@ -17,6 +16,11 @@ import fr.agrometinfo.www.client.util.ApplicationUtils; * @author Olivier Maury */ public final class LogoPlugin extends AbstractPlugin { + /** + * Width / height computed from SVG file. + */ + private static final double LOGO_SIZE_RATIO = 2.1087; + /** * Width of logo. */ @@ -29,11 +33,6 @@ public final class LogoPlugin extends AbstractPlugin { */ private static final double LOGO_WIDTH_COEFF = 0.45; - /** - * Width / height computed from SVG file. - */ - private static final double LOGO_SIZE_RATIO = 2.1087; - /** * Constructor. */ @@ -44,7 +43,7 @@ public final class LogoPlugin extends AbstractPlugin { @Override public void onAfterDraw(final IsChart chart) { GWT.log("LogoPlugin.onAfterShow()"); - final Context2dItem ctx = chart.getCanvas().getContext2d(); + final var ctx = chart.getCanvas().getContext2d(); // limit logo width to available space on left side final double logoWidth = Math.min(LOGO_WIDTH, chart.getChartElement().getClientWidth() * LOGO_WIDTH_COEFF); // Charba Canvas only accept a canvas as image diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/CanvasAttributions.java b/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/CanvasAttributions.java index e7f94b21..f79cbc33 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/CanvasAttributions.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/CanvasAttributions.java @@ -7,12 +7,9 @@ import java.util.Set; import org.pepstock.charba.client.utils.Window; -import com.google.gwt.canvas.dom.client.Context2d; import com.google.gwt.canvas.dom.client.Context2d.TextAlign; import com.google.gwt.canvas.dom.client.TextMetrics; import com.google.gwt.core.client.GWT; -import com.google.gwt.dom.client.CanvasElement; -import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Document; import elemental2.dom.DomGlobal; @@ -31,9 +28,9 @@ import ol.layer.Group; */ public final class CanvasAttributions extends CanvasWidget { /** - * Attribution separator. + * Font size for title and scale for normal devices (not adjusted to pixel density). */ - private static final String SEP = " − "; + private static final int BASE_FONT_SIZE_NORMAL = 8; /** * Font size for title and scale for small devices (not adjusted to pixel @@ -41,12 +38,6 @@ public final class CanvasAttributions extends CanvasWidget { */ private static final int BASE_FONT_SIZE_SMALL = 6; - /** - * Font size for title and scale for normal devices (not adjusted to pixel - * density). - */ - private static final int BASE_FONT_SIZE_NORMAL = 8; - /** * Margin around the box. */ @@ -56,6 +47,10 @@ public final class CanvasAttributions extends CanvasWidget { * Padding around the text. */ private static final int PADDING = 5; + /** + * Attribution separator. + */ + private static final String SEP = " − "; private static String getAttributions(final Base layer) { GWT.log("CanvasAttributions.getAttributions()"); @@ -64,10 +59,10 @@ public final class CanvasAttributions extends CanvasWidget { return null; } String attributions; - if (value instanceof String[]) { - attributions = String.join("", (String[]) value); - } else if (value instanceof String) { - attributions = (String) value; + if (value instanceof String[] strings) { + attributions = String.join("", strings); + } else if (value instanceof String string) { + attributions = string; } else { return null; } @@ -123,7 +118,7 @@ public final class CanvasAttributions extends CanvasWidget { @Override protected void draw() { GWT.log("CanvasAttributions.draw()"); - final CanvasElement canvas = getCanvas(); + final var canvas = getCanvas(); if (canvas == null) { DomGlobal.console.error("Canvas must not be null!"); return; @@ -132,7 +127,7 @@ public final class CanvasAttributions extends CanvasWidget { final Set<String> uniqueAttributions = getAttributions(); - final Context2d ctx = canvas.getContext2d(); + final var ctx = canvas.getContext2d(); ctx.setFont(getFont()); final int availableWidth = canvas.getWidth() - 2 * PADDING; @@ -140,7 +135,7 @@ public final class CanvasAttributions extends CanvasWidget { final List<String> lines = new ArrayList<>(); lines.add(""); for (final String attribution : uniqueAttributions) { - final String line = lines.get(lines.size() - 1).concat(attribution); + final var line = lines.get(lines.size() - 1).concat(attribution); final TextMetrics measure = ctx.measureText(line); final double lineWidth = measure.getWidth(); if (lineWidth > availableWidth) { @@ -179,15 +174,14 @@ public final class CanvasAttributions extends CanvasWidget { private Set<String> getAttributions() { final Set<String> uniqueAttributions = new LinkedHashSet<>(); - final DivElement div = Document.get().createDivElement(); + final var div = Document.get().createDivElement(); final Collection<Base> layers = getMap().getLayerGroup().getLayers(); for (final Base l : layers.getArray()) { String attributions = getAttributions(l); if (attributions != null) { div.setInnerHTML(attributions); uniqueAttributions.add(div.getInnerText().trim()); - } else if (l instanceof Group) { - final Group group = (Group) l; + } else if (l instanceof Group group) { for (final Base layer : group.getLayers().getArray()) { if (layer.getVisible()) { attributions = getAttributions(layer); diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/CanvasTitle.java b/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/CanvasTitle.java index 8aec988e..64fbe36b 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/CanvasTitle.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/CanvasTitle.java @@ -8,7 +8,6 @@ import org.pepstock.charba.client.utils.Window; import com.google.gwt.canvas.dom.client.Context2d; import com.google.gwt.canvas.dom.client.Context2d.TextAlign; -import com.google.gwt.canvas.dom.client.TextMetrics; import com.google.gwt.dom.client.ImageElement; import com.google.gwt.i18n.client.NumberFormat; @@ -26,12 +25,10 @@ import ol.Map; * @author Olivier Maury */ public final class CanvasTitle extends CanvasWidget { - /** - * Font size for title and scale for small devices (not adjusted to pixel - * density). + * Size of colored border (not adjusted to pixel density). */ - private static final int BASE_FONT_SIZE_SMALL = 10; + private static final int BASE_BORDER_SIZE = 1; /** * Font size for title and scale for normal devices (not adjusted to pixel @@ -40,9 +37,15 @@ public final class CanvasTitle extends CanvasWidget { private static final int BASE_FONT_SIZE_NORMAL = 12; /** - * Size of colored border (not adjusted to pixel density). + * Font size for title and scale for small devices (not adjusted to pixel + * density). */ - private static final int BASE_BORDER_SIZE = 1; + private static final int BASE_FONT_SIZE_SMALL = 10; + + /** + * Width of logo (not adjusted to pixel density). + */ + private static final int BASE_LOGO_WIDTH = 150; /** * Font color for title and scale. @@ -54,11 +57,6 @@ public final class CanvasTitle extends CanvasWidget { */ private static final double LOGO_SIZE_RATIO = 2.1087; - /** - * Width of logo (not adjusted to pixel density). - */ - private static final int BASE_LOGO_WIDTH = 150; - /** * To format scale bounds. */ @@ -171,7 +169,7 @@ public final class CanvasTitle extends CanvasWidget { final int padding = getPadding(); final int width = getWidth(); - final Context2d ctx = getCanvas().getContext2d(); + final var ctx = getCanvas().getContext2d(); final int totalScaleHeight = 3 * getLineHeight(); final double height = Math.max(// getLineHeight() * nbOfLines + 2d * borderSize, // @@ -188,7 +186,7 @@ public final class CanvasTitle extends CanvasWidget { private void drawLogo() { final int logoWidth = getLogoWidth(); final int logoHeight = getLogoHeight(); - final Context2d ctx = getCanvas().getContext2d(); + final var ctx = getCanvas().getContext2d(); final ImageElement logoImg = ApplicationUtils.getApplicationLogo(); ctx.drawImage(logoImg, // 0d + getBorderSize() + getPadding(), // @@ -211,7 +209,7 @@ public final class CanvasTitle extends CanvasWidget { final int logoHeight = getLogoHeight(); final int padding = getPadding(); - final Context2d ctx = getCanvas().getContext2d(); + final var ctx = getCanvas().getContext2d(); ctx.setFont(getFont()); final double scaleLabelWidth = ctx.measureText("0000.00").getWidth(); final int nbOfIntervals = colorIntervals.size(); @@ -222,7 +220,7 @@ public final class CanvasTitle extends CanvasWidget { final double labelTop = cellBottom + lineHeight; double x = padding; for (final ColorInterval value : colorIntervals) { - final String line = NUMBER_FORMAT.format(value.getMin()); + final var line = NUMBER_FORMAT.format(value.getMin()); ctx.setFillStyle("#" + value.getColor()); ctx.fillRect(x, cellTop, cellWidth, cellHeight); ctx.setFillStyle(FONT_COLOR); @@ -231,8 +229,8 @@ public final class CanvasTitle extends CanvasWidget { x += cellWidth; } if (!colorIntervals.isEmpty()) { - final ColorInterval value = colorIntervals.get(nbOfIntervals - 1); - final String line = NUMBER_FORMAT.format(value.getMax()); + final var value = colorIntervals.get(nbOfIntervals - 1); + final var line = NUMBER_FORMAT.format(value.getMax()); ctx.setFillStyle(FONT_COLOR); ctx.setTextAlign(TextAlign.LEFT); ctx.fillText(line, x, labelTop); @@ -259,9 +257,9 @@ public final class CanvasTitle extends CanvasWidget { */ private int getMaxWidth() { final int logoWidth = getLogoWidth(); - final Context2d ctx = getCanvas().getContext2d(); + final var ctx = getCanvas().getContext2d(); ctx.setFont(getFont()); - final String largestDescription = "Nombre de jours chauds (Tmax > 35°C) (j)"; + final var largestDescription = "Nombre de jours chauds (Tmax > 35°C) (j)"; final int largestDescriptionWidth = (int) ctx.measureText(largestDescription).getWidth(); return logoWidth + 2 * getPadding() * 2 + getBorderSize() * 2 + largestDescriptionWidth; } @@ -293,12 +291,12 @@ public final class CanvasTitle extends CanvasWidget { */ private List<String> splitLine(final String line, final Context2d ctx, final double availableWidth) { final List<String> lines = new ArrayList<>(); - TextMetrics measure = ctx.measureText(line); + var measure = ctx.measureText(line); if (measure.getWidth() <= availableWidth) { lines.add(line); } else { final String[] parts = line.split(" "); - StringJoiner sj = new StringJoiner(" "); + var sj = new StringJoiner(" "); for (final String part: parts) { measure = ctx.measureText(sj.toString() + " " + part); if (measure.getWidth() <= availableWidth) { diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/CanvasWidget.java b/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/CanvasWidget.java index ede6f9bc..ba177541 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/CanvasWidget.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/CanvasWidget.java @@ -13,19 +13,15 @@ import ol.Map; * @author Olivier Maury */ abstract class CanvasWidget { - /** - * The same font-family as in style.css. - */ - protected static final String FONT_FAMILY = "\"Roboto\", Arial, Tahoma, sans-serif"; /** * Delay (milliseconds) before drawing. */ private static final int DRAWING_TIMER_DELAY = 200; /** - * OpenLayers map. + * The same font-family as in style.css. */ - private final Map openLayersMap; + protected static final String FONT_FAMILY = "\"Roboto\", Arial, Tahoma, sans-serif"; /** * HTML canvas element. @@ -37,6 +33,11 @@ abstract class CanvasWidget { */ private Timer drawingTimer; + /** + * OpenLayers map. + */ + private final Map openLayersMap; + /** * Constructor. * @@ -77,11 +78,11 @@ abstract class CanvasWidget { private CanvasElement findCanvas(final Element root) { final NodeList<Element> elems = root.getElementsByTagName("canvas"); for (int i = 0; i < elems.getLength(); i++) { - final Element elem = elems.getItem(i); + final var elem = elems.getItem(i); if ("canvas".equalsIgnoreCase(elem.getTagName())) { return (CanvasElement) elem; } - final CanvasElement found = findCanvas(elem); + final var found = findCanvas(elem); if (found != null) { return found; } diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/ControlSuppliers.java b/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/ControlSuppliers.java index fad117ec..d5802162 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/ControlSuppliers.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/ControlSuppliers.java @@ -59,7 +59,7 @@ public abstract class ControlSuppliers { * @return internationalized control to toggle full screen */ public static Control createFullScreen() { - final FullScreenOptions fullScreenOptions = new FullScreenOptions(); + final var fullScreenOptions = new FullScreenOptions(); fullScreenOptions.setTipLabel(CSTS.mapFullScreen()); return setIcon(new FullScreen(fullScreenOptions), Icons.MDI_ICONS.fullscreen_mdi()); } @@ -79,10 +79,10 @@ public abstract class ControlSuppliers { }-*/; public static Zoom createZoom() { - final ZoomOptions options = new ZoomOptions(); + final var options = new ZoomOptions(); options.setZoomInTipLabel(CSTS.mapZoomIn()); options.setZoomOutTipLabel(CSTS.mapZoomOut()); - final Zoom zoom = new Zoom(options); + final var zoom = new Zoom(options); setIcon(zoom.getElement().getChild(0), Icons.MDI_ICONS.plus_mdi()); setIcon(zoom.getElement().getChild(1), Icons.MDI_ICONS.minus_mdi()); return zoom; @@ -95,7 +95,7 @@ public abstract class ControlSuppliers { */ public static Control createZoomToExtent(final Extent extent) { GWT.log("ControlSuppliers.createZoomToExtent()"); - final ZoomToExtentOptions zoomToExtOptions = new ZoomToExtentOptions(); + final var zoomToExtOptions = new ZoomToExtentOptions(); zoomToExtOptions.setExtent(extent); zoomToExtOptions.setLabel(""); final com.google.gwt.dom.client.Element element = DOM.createElement("i"); @@ -116,4 +116,5 @@ public abstract class ControlSuppliers { btn.setInnerHTML(""); btn.appendChild(element); } + } diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/TileSuppliers.java b/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/TileSuppliers.java index 5e4ee58d..f29957d3 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/TileSuppliers.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/TileSuppliers.java @@ -2,9 +2,7 @@ package fr.agrometinfo.www.client.ui.map; import com.google.gwt.core.client.GWT; import com.google.gwt.i18n.client.LocaleInfo; - import fr.agrometinfo.www.client.i18n.MapConstants; -import ol.Coordinate; import ol.OLFactory; import ol.layer.Base; import ol.layer.LayerOptions; @@ -177,7 +175,7 @@ public abstract class TileSuppliers { * @return overlay with IGN administrative limits */ public static Base createIgnAdministrativeLimits() { - final IgnWmtsLayer wmts = new IgnWmtsLayer(); + final var wmts = new IgnWmtsLayer(); wmts.setLayer("ADMINEXPRESS-COG.LATEST"); wmts.setTitle(CSTS.ignAdministrativeLimits()); wmts.setType(""); @@ -189,7 +187,7 @@ public abstract class TileSuppliers { * @return base layer with IGN aerial map */ public static Base createIgnAerial() { - final IgnWmtsLayer wmts = new IgnWmtsLayer(); + final var wmts = new IgnWmtsLayer(); wmts.setLayer("ORTHOIMAGERY.ORTHOPHOTOS"); wmts.setTitle(CSTS.ignAerial()); wmts.setAttributions(CSTS.ignAerialAttributions()); @@ -198,7 +196,7 @@ public abstract class TileSuppliers { } public static Base createIgnHydrography() { - final IgnWmtsLayer wmts = new IgnWmtsLayer(); + final var wmts = new IgnWmtsLayer(); wmts.setLayer("HYDROGRAPHY.BCAE.LATEST"); wmts.setTitle(CSTS.ignHydrography()); wmts.setAttributions(" - " + CSTS.ignOverlayAttributions()); @@ -211,7 +209,7 @@ public abstract class TileSuppliers { * @return base layer with IGN map */ public static Base createIgnMap() { - final IgnWmtsLayer wmts = new IgnWmtsLayer(); + final var wmts = new IgnWmtsLayer(); wmts.setLayer("GEOGRAPHICALGRIDSYSTEMS.PLANIGNV2"); wmts.setTitle(CSTS.ignInternationalMap()); wmts.setAttributions(CSTS.ignInternationalMapAttributions()); @@ -219,7 +217,7 @@ public abstract class TileSuppliers { } public static Base createIgnShadowsFrance() { - final IgnWmtsLayer wmts = new IgnWmtsLayer(); + final var wmts = new IgnWmtsLayer(); wmts.setLayer("ELEVATION.ELEVATIONGRIDCOVERAGE.SHADOW"); wmts.setTitle(CSTS.ignShadowsFrance()); wmts.setAttributions(" - " + CSTS.ignOverlayAttributions()); @@ -235,7 +233,7 @@ public abstract class TileSuppliers { * @return base layer */ private static Base createIgnWmtsLayer(final IgnWmtsLayer wmts) { - final Projection projection = Projection.get("EPSG:3857"); + final var projection = Projection.get("EPSG:3857"); final WmtsOptions wmtsOptions = OLFactory.createOptions(); wmtsOptions.setUrl("https://data.geopf.fr/wmts"); wmtsOptions.setUrl("https://agroclim.inrae.fr/tiles/wmts/geopf"); @@ -250,11 +248,11 @@ public abstract class TileSuppliers { wmtsOptions.setWrapX(true); wmtsOptions.setTileGrid(createWmtsTileGrid(projection)); - final Wmts wmtsSource = new Wmts(wmtsOptions); + final var wmtsSource = new Wmts(wmtsOptions); final LayerOptions wmtsLayerOptions = OLFactory.createOptions(); wmtsLayerOptions.setSource(wmtsSource); - final Tile wmtsLayer = new Tile(wmtsLayerOptions); + final var wmtsLayer = new Tile(wmtsLayerOptions); wmtsLayer.set(TITLE, wmts.getTitle()); wmtsLayer.set(TYPE, wmts.getType()); wmtsLayer.setVisible(false); @@ -266,7 +264,7 @@ public abstract class TileSuppliers { * @return default empty */ public static Base createNone() { - final Vector layer = new Vector(); + final var layer = new Vector(); layer.set(TITLE, CSTS.mapBaseLayerEmpty()); layer.set(TYPE, "base"); layer.setVisible(false); @@ -278,15 +276,15 @@ public abstract class TileSuppliers { * @return tile for OpenTopoMap */ public static Base createOpenTopoMap() { - final XyzOptions options = new XyzOptions(); + final var options = new XyzOptions(); options.setCrossOrigin("anonymous"); options.setUrl("https://{a-c}.tile.opentopomap.org/{z}/{x}/{y}.png"); options.setUrl("https://agroclim.inrae.fr/tiles/xyz/opentopo/{a-c}/{z}/{x}/{y}.png"); options.setAttributions(CSTS.osmOpenTopoMapAttributions()); - final Xyz source = new Xyz(options); + final var source = new Xyz(options); final LayerOptions xyzLayerOptions = OLFactory.createOptions(); xyzLayerOptions.setSource(source); - final Tile tile = new Tile(xyzLayerOptions); + final var tile = new Tile(xyzLayerOptions); tile.set(TITLE, "OpenTopoMap"); tile.set(TYPE, "base"); tile.setVisible(false); @@ -299,7 +297,7 @@ public abstract class TileSuppliers { */ public static Base createOsm() { // create a OSM-layer - final XyzOptions options = new XyzOptions(); + final var options = new XyzOptions(); options.setCrossOrigin("anonymous"); // https://wiki.openstreetmap.org/wiki/FR:Serveurs/tile.openstreetmap.fr if (LocaleInfo.getCurrentLocale().getLocaleName().equals("fr")) { @@ -310,10 +308,10 @@ public abstract class TileSuppliers { options.setUrl("https://agroclim.inrae.fr/tiles/xyz/osm/{a-c}/{z}/{x}/{y}.png"); options.setAttributions(CSTS.osmAttributions()); } - final Osm osmSource = new Osm(options); - final LayerOptions osmLayerOptions = new LayerOptions(); + final var osmSource = new Osm(options); + final var osmLayerOptions = new LayerOptions(); osmLayerOptions.setSource(osmSource); - final Tile osmLayer = new Tile(osmLayerOptions); + final var osmLayer = new Tile(osmLayerOptions); osmLayer.set(TITLE, "OpenStreetMap"); osmLayer.set(TYPE, "base"); osmLayer.setVisible(false); @@ -325,7 +323,7 @@ public abstract class TileSuppliers { * @return tile for piano map. */ public static Base createPiano() { - final XyzOptions options = new XyzOptions(); + final var options = new XyzOptions(); options.setCrossOrigin("anonymous"); if (LocaleInfo.getCurrentLocale().getLocaleName().equals("fr")) { options.setUrl("https://{a-c}.piano.tiles.quaidorsay.fr/fr/{z}/{x}/{y}.png"); @@ -335,10 +333,10 @@ public abstract class TileSuppliers { options.setUrl("https://agroclim.inrae.fr/tiles/xyz/piano-en/{a-c}/{z}/{x}/{y}.png"); } options.setAttributions(CSTS.osmPianoMapAttributions()); - final Xyz source = new Xyz(options); + final var source = new Xyz(options); final LayerOptions xyzLayerOptions = OLFactory.createOptions(); xyzLayerOptions.setSource(source); - final Tile tile = new Tile(xyzLayerOptions); + final var tile = new Tile(xyzLayerOptions); tile.set(TITLE, "OpenStreetMap Piano"); tile.set(TYPE, "base"); tile.set(ATTRIBUTIONS, options.getAttributions()); @@ -356,7 +354,7 @@ public abstract class TileSuppliers { final int resolutionSize = 14; final double[] resolutions = new double[resolutionSize]; - final String[] matrixIds = new String[resolutionSize]; + final var matrixIds = new String[resolutionSize]; final double width = projection.getExtent().getWidth(); final double matrixWidth = width / 256; @@ -366,7 +364,7 @@ public abstract class TileSuppliers { matrixIds[i] = String.valueOf(i); } - final Coordinate tileGridOrigin = projection.getExtent().getTopLeft(); + final var tileGridOrigin = projection.getExtent().getTopLeft(); wmtsTileGridOptions.setOrigin(tileGridOrigin); wmtsTileGridOptions.setResolutions(resolutions); wmtsTileGridOptions.setMatrixIds(matrixIds); diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/ToolTip.java b/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/ToolTip.java index 7a00393c..bb3c1b8d 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/ToolTip.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/ui/map/ToolTip.java @@ -8,8 +8,6 @@ import ol.Extent; import ol.Map; import ol.Overlay; import ol.OverlayOptions; -import ol.Pixel; -import ol.Size; /** * Tooltip widget @@ -49,7 +47,7 @@ public final class ToolTip { public ToolTip(final Map map) { this.olMap = map; // Create tooltip element in a new popup layer. - final OverlayOptions overlayOptions = new OverlayOptions(); + final var overlayOptions = new OverlayOptions(); overlayOptions.setElement(content); overlayOptions.setAutoPan(true); overlayOptions.setId("toolTipOverlay"); @@ -87,14 +85,14 @@ public final class ToolTip { */ public void setPosition(final Extent extent) { if (enabled) { - final Coordinate position = new Coordinate(// + final var position = new Coordinate(// extent.getLowerLeftX() + extent.getWidth(), // extent.getUpperRightY() - extent.getHeight()// ); - final Pixel posPixel = olMap.getPixelFromCoordinate(position); + final var posPixel = olMap.getPixelFromCoordinate(position); final int posX = posPixel.getX(); final int posY = posPixel.getY(); - final Size mapSize = olMap.getSize(); + final var mapSize = olMap.getSize(); final int width = content.getClientWidth(); final int height = content.getClientHeight(); final String xClassName; diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/util/ApplicationUtils.java b/www-client/src/main/java/fr/agrometinfo/www/client/util/ApplicationUtils.java index 63170447..1225d4a7 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/util/ApplicationUtils.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/util/ApplicationUtils.java @@ -40,9 +40,9 @@ public final class ApplicationUtils { */ public static ImageElement getApplicationLogo() { if (LOGO_IMG.getSrc() == null || LOGO_IMG.getSrc().isEmpty()) { - final XMLHttpRequest xhr = new XMLHttpRequest(); + final var xhr = new XMLHttpRequest(); xhr.onload = e -> { - final String resp = xhr.responseText; + final var resp = xhr.responseText; LOGO_IMG.setSrc("data:image/svg+xml;base64," + base64encode(resp)); }; xhr.open("GET", "app/img/logo_etat-agrometinfo.svg"); @@ -55,8 +55,8 @@ public final class ApplicationUtils { * @return root path of application. */ public static String getApplicationUrl() { - final String url = GWT.getModuleBaseURL(); - final String app = "/" + GWT.getModuleName() + "/"; + final var url = GWT.getModuleBaseURL(); + final var app = "/" + GWT.getModuleName() + "/"; return url.substring(0, url.length() - app.length()); } @@ -81,7 +81,7 @@ public final class ApplicationUtils { * @return project version */ public static String getVersion() { - final String val = DOM.getElementById("application_version").getAttribute("content"); + final var val = DOM.getElementById("application_version").getAttribute("content"); if ("VERSION".equals(val)) { return "1.0-dev"; } @@ -92,7 +92,7 @@ public final class ApplicationUtils { * @return build date */ public static Date getVersionDate() { - final String val = DOM.getElementById("application_date").getAttribute("content"); + final var val = DOM.getElementById("application_date").getAttribute("content"); if ("DATE".equals(val)) { return new Date(); } diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/util/DateUtils.java b/www-client/src/main/java/fr/agrometinfo/www/client/util/DateUtils.java index f49f56bd..cdcef28d 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/util/DateUtils.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/util/DateUtils.java @@ -28,7 +28,7 @@ public interface DateUtils { */ @SuppressWarnings("deprecation") static int getYear(final Date date) { - final int offset = 1900; + final int offset = 1_900; return date.getYear() + offset; } } diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/util/color/ColorSequenceManager.java b/www-client/src/main/java/fr/agrometinfo/www/client/util/color/ColorSequenceManager.java index 8ab047d1..54c05390 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/util/color/ColorSequenceManager.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/util/color/ColorSequenceManager.java @@ -44,43 +44,46 @@ public final class ColorSequenceManager { * Color sequence name as defined in {@link ColorSequences}. */ private String colorSequenceName; - /** - * Minimal value, for linear. - */ - private Double minValue; + /** * Maximal value, for linear. */ private Double maxValue; + /** - * Scale type. + * Minimal value, for linear. */ - private ScaleType scaleType; + private Double minValue; + /** * Number of classes, for linear. */ private Integer nbOfClasses; + + /** + * Quantile type, for quantile. + */ + private QuantileType quantileType; + /** * All result values, for quantile. */ private Collection<Double> results; + /** - * Quantile type, for quantile. + * Scale type. */ - private QuantileType quantileType; + private ScaleType scaleType; /** * @return intervals related to the parameters. */ public List<ColorInterval> getColorIntervals() { - switch (scaleType) { - case LINEAR: - return getColorIntervalsForLinear(); - case QUANTILE: - return getColorIntervalsForQuantile(); - default: - throw new UnsupportedOperationException("ScaleType not handled: " + scaleType); - } + return switch (scaleType) { + case LINEAR -> getColorIntervalsForLinear(); + case QUANTILE -> getColorIntervalsForQuantile(); + default -> throw new UnsupportedOperationException("ScaleType not handled: " + scaleType); + }; } /** @@ -101,7 +104,7 @@ public final class ColorSequenceManager { double start = minValue; for (int i = 0; i < nbOfClasses; i++) { final double end = start + step; - final ColorInterval interval = new ColorInterval(); + final var interval = new ColorInterval(); interval.setMin(start); interval.setMax(end); interval.setColor(colors.get(i)); @@ -127,7 +130,7 @@ public final class ColorSequenceManager { final List<String> colors = getSequence(quantileType.getNbOfClasses()); if (Math.abs(maxNum - minNum) < EPSILON) { - final ColorInterval interval = new ColorInterval(); + final var interval = new ColorInterval(); interval.setMin(minNum); interval.setMax(maxNum); interval.setColor(colors.get(0)); @@ -146,7 +149,7 @@ public final class ColorSequenceManager { upperIndex--; } // - final ColorInterval interval = new ColorInterval(); + final var interval = new ColorInterval(); interval.setMin(resultList.get(lowerIndex)); interval.setMax(resultList.get(upperIndex)); interval.setColor(colors.get(i)); diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/view/AbstractBaseView.java b/www-client/src/main/java/fr/agrometinfo/www/client/view/AbstractBaseView.java index 5521df97..74de0af9 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/view/AbstractBaseView.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/view/AbstractBaseView.java @@ -19,25 +19,23 @@ import fr.agrometinfo.www.client.i18n.AppMessages; * @param <T> class of the related presenter */ public abstract class AbstractBaseView<T> implements BaseView<T> { - /** - * Related presenter. - */ - private T presenter; /** * I18N constants. */ private static final AppConstants CSTS = GWT.create(AppConstants.class); + /** * I18N messages. */ private static final AppMessages MSGS = GWT.create(AppMessages.class); + /** * * @param failure * @return details of failure object */ protected static String getDetails(final FailedResponseBean failure) { - final StringJoiner sj = new StringJoiner("<br/>"); + final var sj = new StringJoiner("<br/>"); sj.add(CSTS.failureBody()); sj.add(failure.getBody()); sj.add(CSTS.failureHeaders()); @@ -47,6 +45,10 @@ public abstract class AbstractBaseView<T> implements BaseView<T> { sj.add(failure.getStatusText()); return sj.toString(); } + /** + * Related presenter. + */ + private T presenter; /** * @return related presenter @@ -54,11 +56,7 @@ public abstract class AbstractBaseView<T> implements BaseView<T> { protected final T getPresenter() { return presenter; } - /** */ - @Override - public final void setPresenter(final T value) { - this.presenter = value; - } + /** * Show notification with message. * @param msg message to display @@ -68,4 +66,9 @@ public abstract class AbstractBaseView<T> implements BaseView<T> { DomGlobal.console.info("Notification!"); return Notification.create(msg).setPosition(Notification.TOP_LEFT).show(); } + + @Override + public final void setPresenter(final T value) { + this.presenter = value; + } } diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/view/ContactView.java b/www-client/src/main/java/fr/agrometinfo/www/client/view/ContactView.java index 81adee1b..cc265d6c 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/view/ContactView.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/view/ContactView.java @@ -10,11 +10,9 @@ import org.dominokit.domino.ui.forms.TextBox; import org.dominokit.domino.ui.icons.Icons; import org.dominokit.domino.ui.modals.ModalDialog; import org.dominokit.domino.ui.utils.TextNode; -import org.jboss.elemento.HtmlContentBuilder; import com.google.gwt.core.client.GWT; -import elemental2.dom.HTMLAnchorElement; import fr.agrometinfo.www.client.i18n.AppConstants; import fr.agrometinfo.www.client.presenter.ContactPresenter; @@ -29,6 +27,14 @@ public final class ContactView extends AbstractBaseView<ContactPresenter> implem * I18N constants. */ private static final AppConstants CSTS = GWT.create(AppConstants.class); + /** + * Input box for user's message. + */ + private TextArea bodyTextBox; + /** + * Input box for user's e-mail address. + */ + private EmailBox emailBox; /** * The modal used to display the contact form. @@ -40,15 +46,6 @@ public final class ContactView extends AbstractBaseView<ContactPresenter> implem */ private TextBox nameTextBox; - /** - * Input box for user's e-mail address. - */ - private EmailBox emailBox; - - /** - * Input box for user's message. - */ - private TextArea bodyTextBox; @Override public void close() { @@ -82,9 +79,9 @@ public final class ContactView extends AbstractBaseView<ContactPresenter> implem .setFixErrorsPosition(true) .addLeftAddOn(Icons.ALL.textarea_mdi()) .setPlaceholder(CSTS.contactMessagePlaceHolder()); - final HtmlContentBuilder<HTMLAnchorElement> seeFaq = a(".").attr("target", "_blank") // + final var seeFaq = a(".").attr("target", "_blank") // .attr("href", "../explications.html").textContent(CSTS.contactSeeFAQ()); - final HtmlContentBuilder<HTMLAnchorElement> privacy = a(".").attr("target", "_blank") // + final var privacy = a(".").attr("target", "_blank") // .attr("href", "../privacy.html").textContent(CSTS.seePrivacyPolicy()); modal = ModalDialog.create(CSTS.contactUs()) .setAutoClose(true) // diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/view/LayoutView.java b/www-client/src/main/java/fr/agrometinfo/www/client/view/LayoutView.java index 2f628f93..dc57bbf5 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/view/LayoutView.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/view/LayoutView.java @@ -57,11 +57,10 @@ implements LayoutPresenter.View, LoadingHandler { */ private static final AppConstants CSTS = GWT.create(AppConstants.class); - /** * The minimum screen width to display panels on startup. */ - public static final int MIN_WIDTH_FOR_PANELS = 1000; + public static final int MIN_WIDTH_FOR_PANELS = 1_000; /** * I18N messages. @@ -87,12 +86,11 @@ implements LayoutPresenter.View, LoadingHandler { addMenuItem(menu, text, icon, runnable); } - /** * @param relativePath documentation path relative to documentation root */ private static void goToDocumentation(final String relativePath) { - final String documentationRootUrl = "../"; + final var documentationRootUrl = "../"; if (relativePath.isEmpty()) { DomGlobal.location.assign(documentationRootUrl); } else { @@ -116,40 +114,40 @@ implements LayoutPresenter.View, LoadingHandler { private Layout layout; /** - * Modal to block interface until all data are loaded. + * Container for links in footer. */ - private final HtmlContentBuilder<HTMLDivElement> loadingOverlay = div().css("modal-backdrop fade in"); + private final HtmlContentBuilder<HTMLDivElement> links = div().css("links"); /** - * Animation in modal. + * Counter for loading events. */ - private final Loader loadingLoader = Loader.create(loadingOverlay, LoaderEffect.ROTATION) // - .setLoadingText(CSTS.applicationLoading()); + private int loadingCounter = 0; /** - * Presenter for {@link MapView}. + * Modal to block interface until all data are loaded. */ - private MapPresenter mapPresenter; + private final HtmlContentBuilder<HTMLDivElement> loadingOverlay = div().css("modal-backdrop fade in"); /** - * Presenter for {@link RightPanelView}. + * Animation in modal. */ - private RightPanelPresenter rightPanelPresenter; + private final Loader loadingLoader = Loader.create(loadingOverlay, LoaderEffect.ROTATION) // + .setLoadingText(CSTS.applicationLoading()); /** - * Counter for loading events. + * Container for logos in footer. */ - private int loadingCounter = 0; + private final HtmlContentBuilder<HTMLDivElement> logos = div().css("logos"); /** - * Container for logos in footer. + * Presenter for {@link MapView}. */ - private final HtmlContentBuilder<HTMLDivElement> logos = div().css("logos"); + private MapPresenter mapPresenter; /** - * Container for links in footer. + * Presenter for {@link RightPanelView}. */ - private final HtmlContentBuilder<HTMLDivElement> links = div().css("links"); + private RightPanelPresenter rightPanelPresenter; /** * @param text link text @@ -205,7 +203,7 @@ implements LayoutPresenter.View, LoadingHandler { GWT.log("LayoutView.initLayout()"); layout = Layout.create("AgroMetInfo").show(); layout.css("app-layout"); - final HTMLDivElement contentElement = div().element(); + final var contentElement = div().element(); contentElement.textContent = CSTS.applicationLoading(); layout.getContentPanel().id(MapView.MAP_CONTAINER_ID); layout.getContentPanel().appendChild(contentElement); @@ -301,7 +299,7 @@ implements LayoutPresenter.View, LoadingHandler { */ private void initRibbon() { GWT.log("LayoutView.initRibbon()"); - final String version = ApplicationUtils.getVersion() // + final var version = ApplicationUtils.getVersion() // .replace("-SNAPSHOT", "…") // .replace("-alpha-", " α") // .replace("-beta-", " β"); @@ -379,16 +377,12 @@ implements LayoutPresenter.View, LoadingHandler { @Override public void onLoading(final LoadingEvent event) { GWT.log("LayoutView.onLoading() " + event); - switch (event.getEventType()) { - case END: - loadingCounter--; - break; - case START: - loadingCounter++; - break; - default: - break; - } + DomGlobal.console.log("loadingCounter=" + loadingCounter); + loadingCounter += switch (event.getEventType()) { + case END -> -1; + case START -> 1; + default -> 0; + }; GWT.log("LayoutView.onLoading() " + event.getEventType() + " => " + loadingCounter); if (loadingCounter > 0) { loadingOverlay.hidden(false); @@ -427,7 +421,7 @@ implements LayoutPresenter.View, LoadingHandler { addMenuItem(devDropMenu, "Démo rapport", Icons.ALL.email_box_mdi(), "https://www.agrometinfo.fr/demo_rapport/"); - final String compileUrl = "javascript:%7B%20window.__gwt_bookmarklet_params%20%3D%20%7Bserver_url%3A'" + final var compileUrl = "javascript:%7B%20window.__gwt_bookmarklet_params%20%3D%20%7Bserver_url%3A'" + "http%3A%2F%2F127.0.0.1%3A9876%2F'%2Cmodule_name%3A'app'%7D%3B%20var%20s%20%3D%20" + "document.createElement('script')%3B%20s.src%20%3D%20'http%3A%2F%2F127.0.0.1%3A9876%2F" + "dev_mode_on.js'%3B%20void(document.getElementsByTagName('head')%5B0%5D." diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/view/LeftPanelView.java b/www-client/src/main/java/fr/agrometinfo/www/client/view/LeftPanelView.java index d171645d..2a77f0bb 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/view/LeftPanelView.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/view/LeftPanelView.java @@ -59,34 +59,34 @@ public final class LeftPanelView extends AbstractBaseView<LeftPanelPresenter> im private static final AppMessages MSGS = GWT.create(AppMessages.class); /** - * Layout handling the panel. + * Choice from the user. */ - private final DominoElement<HTMLElement> panel; + private final ChoiceDTO choice = new ChoiceDTO(); /** - * Summary of available indicators. + * The replacement of indicatorSelect when it is hidden. */ - private final HtmlContentBuilder<HTMLDivElement> summary = div().css("p-b-15"); + private final CollapsedSelect collapsedIndicatorSelect = new CollapsedSelect(CSTS.chooseIndicator(), ""); /** - * Selector for indicator periods. + * Selector for indicators. */ - private final Select<PeriodDTO> periodSelect = Select.create(CSTS.choosePeriod()); + private final ListGroup<IndicatorDTO> indicatorSelect = ListGroup.create(); /** - * Choice from the user. + * Layout handling the panel. */ - private final ChoiceDTO choice = new ChoiceDTO(); + private final DominoElement<HTMLElement> panel; /** - * Available indicator periods with indicators. + * Selector for indicator periods. */ - private List<PeriodDTO> periods; + private final Select<PeriodDTO> periodSelect = Select.create(CSTS.choosePeriod()); /** - * Selector for indicators. + * Available indicator periods with indicators. */ - private final ListGroup<IndicatorDTO> indicatorSelect = ListGroup.create(); + private List<PeriodDTO> periods; /** * Selector for regions. @@ -94,9 +94,9 @@ public final class LeftPanelView extends AbstractBaseView<LeftPanelPresenter> im private final Select<Entry<String, String>> regionSelect = Select.create(CSTS.chooseRegion()); /** - * The replacement of indicatorSelect when it is hidden. + * Summary of available indicators. */ - private final CollapsedSelect collapsedIndicatorSelect = new CollapsedSelect(CSTS.chooseIndicator(), ""); + private final HtmlContentBuilder<HTMLDivElement> summary = div().css("p-b-15"); /** * Selector for year. @@ -177,12 +177,12 @@ public final class LeftPanelView extends AbstractBaseView<LeftPanelPresenter> im // GWT.log("LeftPanelView.initLeftPanel() comparison"); - final SwitchButton comparisonBtn = SwitchButton.create(CSTS.normalComparison(), CSTS.no(), CSTS.yes()) // + final var comparisonBtn = SwitchButton.create(CSTS.normalComparison(), CSTS.no(), CSTS.yes()) // .value(false); comparisonBtn.addChangeHandler(this::onComparisonChange); comparisonBtn.addCss("comparison-btn"); - final HTMLElement info = Elements.createElement("details", HTMLElement.class); - final HTMLElement sum = Elements.createElement("summary", HTMLElement.class); + final var info = Elements.createElement("details", HTMLElement.class); + final var sum = Elements.createElement("summary", HTMLElement.class); sum.innerHTML = "<i class='material-icons'>info_outline</i>"; info.innerHTML = CSTS.normalComparisonTooltip(); info.append(sum); @@ -227,8 +227,8 @@ public final class LeftPanelView extends AbstractBaseView<LeftPanelPresenter> im return; } GWT.log("LeftPanelView.onPeriodChange() Indicators : " + list); - final IndicatorDTO firstIndicator = list.get(0); - final IndicatorDTO defaultIndicator = list.stream() // + final var firstIndicator = list.get(0); + final var defaultIndicator = list.stream() // .filter(i -> DEFAULT_INDICATOR.equals(i.getCode())) // .findFirst().orElse(firstIndicator); new DominoListBuilder<IndicatorDTO>() // @@ -307,7 +307,7 @@ public final class LeftPanelView extends AbstractBaseView<LeftPanelPresenter> im @Override public void setRegions(final Map<String, String> list) { GWT.log("LeftPanelView.setRegions()"); - final String metropolitanFranceCode = "0"; + final var metropolitanFranceCode = "0"; list.put(metropolitanFranceCode, CSTS.metropolitanFrance()); final Entry<String, String> defaultRegion = list.entrySet().stream() // .filter(e -> metropolitanFranceCode.equals(e.getKey())) // diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/view/MapView.java b/www-client/src/main/java/fr/agrometinfo/www/client/view/MapView.java index 99ad5077..d1da5557 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/view/MapView.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/view/MapView.java @@ -40,7 +40,6 @@ import fr.agrometinfo.www.shared.dto.FeatureProperty; import fr.agrometinfo.www.shared.dto.IndicatorDTO; import jsinterop.base.Any; import ol.Collection; -import ol.Coordinate; import ol.Extent; import ol.Feature; import ol.Map; @@ -76,6 +75,10 @@ import ol.style.StyleOptions; * @author Olivier Maury */ public final class MapView extends HtmlContentBuilder<HTMLElement> implements FeatureSelectHandler, MapPresenter.View { + /** + * I18N constants. + */ + private static final AppConstants APP_CSTS = GWT.create(AppConstants.class); /** * z-index for base layers. @@ -122,10 +125,6 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe */ private static final String TITLE = "title"; - /** - * I18N constants. - */ - private static final AppConstants APP_CSTS = GWT.create(AppConstants.class); /** * Add base layers (OSM, IGN, None). @@ -134,7 +133,7 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe */ private static void addBaseLayers(final MapOptions options) { GWT.log("MapView.addBaseLayers()"); - final LayerGroupOptions baseLayerGroupOptions = new LayerGroupOptions(); + final var baseLayerGroupOptions = new LayerGroupOptions(); final Collection<Base> baseLayers = new Collection<>(); baseLayers.push(TileSuppliers.createNone()); baseLayers.push(TileSuppliers.createIgnAerial()); @@ -143,7 +142,7 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe baseLayers.push(TileSuppliers.createPiano()); baseLayers.push(TileSuppliers.createOsm()); baseLayerGroupOptions.setLayers(baseLayers); - final Group baseLayerGroup = new Group(baseLayerGroupOptions); + final var baseLayerGroup = new Group(baseLayerGroupOptions); baseLayerGroup.set(TITLE, CSTS.mapBaseLayer()); baseLayerGroup.setZIndex(BASELAYERS_ZINDEX); options.getLayers().push(baseLayerGroup); @@ -156,13 +155,13 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe */ private static void addOverlays(final MapOptions options) { GWT.log("MapView.addOverlays()"); - final LayerGroupOptions overlayGroupOptions = new LayerGroupOptions(); + final var overlayGroupOptions = new LayerGroupOptions(); final Collection<Base> overlays = new Collection<>(); overlays.push(TileSuppliers.createIgnAdministrativeLimits()); overlays.push(TileSuppliers.createIgnShadowsFrance()); overlays.push(TileSuppliers.createIgnHydrography()); overlayGroupOptions.setLayers(overlays); - final Group overlayGroup = new Group(overlayGroupOptions); + final var overlayGroup = new Group(overlayGroupOptions); overlayGroup.set(TITLE, CSTS.mapOverlays()); overlayGroup.setZIndex(OVERLAYS_ZINDEX); options.getLayers().push(overlayGroup); @@ -170,13 +169,12 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe } private static Style createCellStyle(final Color foreground, final Color background) { - final FillOptions fillOption = new FillOptions(); + final var fillOption = new FillOptions(); fillOption.setColor(background); - final Fill fill = new Fill(fillOption); - - final StrokeOptions strokeOptions = new StrokeOptions(); + final var fill = new Fill(fillOption); + final var strokeOptions = new StrokeOptions(); strokeOptions.setColor(foreground); - final StyleOptions styleOption = new StyleOptions(); + final var styleOption = new StyleOptions(); styleOption.setFill(fill); styleOption.setStroke(new Stroke(strokeOptions)); @@ -191,7 +189,7 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe */ private static MapOptions createMapOptions(final String target, final View view) { GWT.log("MapView.createMapOptions() " + target); - final MapOptions options = new MapOptions(); + final var options = new MapOptions(); options.setTarget(target); options.setView(view); // add some controls @@ -201,10 +199,10 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe } private static Vector createVectorLayer(final ol.source.Vector vectorSource) { - final VectorLayerOptions vectorLayerOptions = new VectorLayerOptions(); + final var vectorLayerOptions = new VectorLayerOptions(); vectorLayerOptions.setSource(vectorSource); setRenderModeImage(vectorLayerOptions); - final Vector vectorLayer = new Vector(vectorLayerOptions); + final var vectorLayer = new Vector(vectorLayerOptions); vectorLayer.setVisible(true); vectorLayer.setOpacity(INDICATOR_LAYER_OPACITY); vectorLayer.setZIndex(INDICATOR_LAYER_ZINDEX); @@ -217,7 +215,7 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe * @return string representation of a feature property */ private static String getProperty(final Feature feature, final FeatureProperty property) { - final String propertyName = property.toCamelCase(); + final var propertyName = property.toCamelCase(); if (feature.getProperties().has(propertyName)) { return feature.getProperties().get(propertyName).toString(); } @@ -239,11 +237,11 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe * @return date representation of a feature property */ private static Date getPropertyAsDate(final Feature feature, final FeatureProperty property) { - final String str = getProperty(feature, property); + final var str = getProperty(feature, property); if (str == null) { return null; } - final DateTimeFormat dtf = DateTimeFormat.getFormat(DateUtils.ISO_8601_DATE_FORMAT); + final var dtf = DateTimeFormat.getFormat(DateUtils.ISO_8601_DATE_FORMAT); return dtf.parse(str); } @@ -253,11 +251,11 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe * @return date representation of a feature property */ private static Date getPropertyAsDate(final org.geojson.Feature feature, final FeatureProperty property) { - final String str = getProperty(feature, property); + final var str = getProperty(feature, property); if (str == null) { return null; } - final DateTimeFormat dtf = DateTimeFormat.getFormat(DateUtils.ISO_8601_DATE_FORMAT); + final var dtf = DateTimeFormat.getFormat(DateUtils.ISO_8601_DATE_FORMAT); return dtf.parse(str); } @@ -267,7 +265,7 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe * @return double representation of a feature property */ private static Double getPropertyAsDouble(final Feature feature, final FeatureProperty property) { - final String str = getProperty(feature, property); + final var str = getProperty(feature, property); if (str == null) { return null; } @@ -301,15 +299,24 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe */ private List<ColorInterval> colorIntervals; + /** + * Name of selected indicator. + */ + private String indicatorName; + + /** + * Unit of selected indicator. + */ + private String indicatorUnit; /** * If indicator values are comparison to normal. */ private boolean isComparisonToNormal; /** - * Name of selected indicator. + * map. */ - private String indicatorName; + private Map map; /** * Start date of selected period. @@ -317,19 +324,19 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe private Date periodStartDate; /** - * Unit of selected indicator. + * PRA code ⮕ PRA name. */ - private String indicatorUnit; + private final java.util.Map<String, String> praNames = new HashMap<>(); /** - * map. + * Related presenter. */ - private Map map; + private MapPresenter presenter; /** - * Related presenter. + * Id of selected feature. */ - private MapPresenter presenter; + private String selectedFeatureId = null; /** * Tooltip displayed over PRA. @@ -346,16 +353,6 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe */ private View view; - /** - * Id of selected feature. - */ - private String selectedFeatureId = null; - - /** - * PRA code ⮕ PRA name. - */ - private final java.util.Map<String, String> praNames = new HashMap<>(); - /** * Constructor. * @@ -369,13 +366,13 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe * Mouse click interaction to select a cell. */ private void addClickInteractions() { - final SelectOptions selectOptions = new SelectOptions(); + final var selectOptions = new SelectOptions(); selectOptions.setCondition(Condition.getClick()); selectOptions.setMulti(false); selectOptions.setStyle((f, r) -> createCellStyleForSelection(f)); // create a select interaction - final Select selectFeature = new Select(selectOptions); + final var selectFeature = new Select(selectOptions); map.addInteraction(selectFeature); selectFeature.on("select", event -> onFeatureClick(selectFeature.getFeatures())); @@ -386,9 +383,9 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe * Mouse move interaction to display values in a popup. */ private void addMouseMoveInteraction() { - final SelectOptions selectOptions = new SelectOptions(); + final var selectOptions = new SelectOptions(); selectOptions.setCondition(Condition.getPointerMove()); - final Select featureSelect = new Select(selectOptions); + final var featureSelect = new Select(selectOptions); map.addInteraction(featureSelect); tooltip = new ToolTip(map); @@ -404,13 +401,12 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe } else { title = indicatorName; } - final Feature feature = featureSelect.getFeatures().item(0); - final Date date = getPropertyAsDate(feature, FeatureProperty.DATE); - final Double value = getPropertyAsDouble(feature, FeatureProperty.VALUE); - final String praName = praNames.getOrDefault(feature.getId(), feature.getId() + "/" + praNames.size()); - final String content = MSGS.popupContent(title, value, indicatorUnit, praName, periodStartDate, date); - - final Extent extent = feature.getGeometry().getExtent(); + final var feature = featureSelect.getFeatures().item(0); + final var date = getPropertyAsDate(feature, FeatureProperty.DATE); + final var value = getPropertyAsDouble(feature, FeatureProperty.VALUE); + final var praName = praNames.getOrDefault(feature.getId(), feature.getId() + "/" + praNames.size()); + final var content = MSGS.popupContent(title, value, indicatorUnit, praName, periodStartDate, date); + final var extent = feature.getGeometry().getExtent(); tooltip.setPosition(extent); tooltip.setContent(content); } else { @@ -428,8 +424,8 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe GWT.log("MapView.colorizeFeatures()"); for (final Feature f : features) { final Double value = getValue(f); - final String color = "#" + ColorSequenceManager.getColorForValue(colorIntervals, value); - final Color foreground = Color.getColorFromString(color); + final var color = "#" + ColorSequenceManager.getColorForValue(colorIntervals, value); + final var foreground = Color.getColorFromString(color); final Style style; if (Objects.equals(selectedFeatureId, f.getId())) { style = createCellStyleForSelection(f)[0]; @@ -451,16 +447,16 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe GWT.log("MapView.createCellStyleForSelection()"); final int strokeWidth = 3; final Double value = getValue(feature); - final String color = "#" + ColorSequenceManager.getColorForValue(colorIntervals, value); - final Color background = Color.getColorFromString(color); - final Color foreground = Color.getColorFromString("#333333"); - final Style style = createCellStyle(foreground, background); + final var color = "#" + ColorSequenceManager.getColorForValue(colorIntervals, value); + final var background = Color.getColorFromString(color); + final var foreground = Color.getColorFromString("#333333"); + final var style = createCellStyle(foreground, background); style.getStroke().setWidth(strokeWidth); return new Style[] {style}; } private VectorOptions createVectorOptions(final Feature[] colorizedFeatures) { - final VectorOptions options = new VectorOptions(); + final var options = new VectorOptions(); options.setFeatures(colorizedFeatures); options.setAttributions(ApplicationUtils.getAttributions()); return options; @@ -477,10 +473,10 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe final int minY = 3_000_000; final int maxX = 5_000_000; final int maxY = 10_000_000; - final Extent extent = new Extent(minX, minY, maxX, maxY); - final ViewOptions viewOptions = new ViewOptions(); - final Coordinate coordinate = OLFactory.createCoordinate(franceCenterLon, franceCenterLat); - final Coordinate centerCoordinateFromLonLat = Projection.fromLonLat(coordinate); + final var extent = new Extent(minX, minY, maxX, maxY); + final var viewOptions = new ViewOptions(); + final var coordinate = OLFactory.createCoordinate(franceCenterLon, franceCenterLat); + final var centerCoordinateFromLonLat = Projection.fromLonLat(coordinate); viewOptions.setCenter(centerCoordinateFromLonLat); viewOptions.setExtent(extent); viewOptions.setMinZoom(minZoom); @@ -501,7 +497,7 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe GWT.log("MapView.init()"); createView(); element.innerHTML = ""; - final MapOptions options = createMapOptions(element.id, view); + final var options = createMapOptions(element.id, view); addBaseLayers(options); addOverlays(options); @@ -544,12 +540,12 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe // create Feature and after geojson layer (Vector layer) final GeoJson geoJsonFormat = OLFactory.createGeoJSON(); - final ProjectionOptions projOpt = new ProjectionOptions(); + final var projOpt = new ProjectionOptions(); projOpt.setCode(EPSG_3857); - final GeoJsonFeatureOptions geoJsonFeatureOptions = new GeoJsonFeatureOptions(); + final var geoJsonFeatureOptions = new GeoJsonFeatureOptions(); geoJsonFeatureOptions.setFeatureProjection(new Projection(projOpt)); final Feature[] allFeatures = geoJsonFormat.readFeatures(dataGeoJson, geoJsonFeatureOptions); - final Feature propertiesFeature = allFeatures[0]; + final var propertiesFeature = allFeatures[0]; if (propertiesFeature.getId() == null) { indicatorName = getProperty(propertiesFeature, FeatureProperty.INDICATOR_NAME); indicatorUnit = getProperty(propertiesFeature, FeatureProperty.INDICATOR_UNIT); @@ -557,7 +553,7 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe .equalsIgnoreCase(getProperty(propertiesFeature, FeatureProperty.COMPARISON_TO_NORMAL)); periodStartDate = getPropertyAsDate(propertiesFeature, FeatureProperty.PERIOD_FIRST_DAY); - final Feature[] filtered = new Feature[allFeatures.length - 1]; + final var filtered = new Feature[allFeatures.length - 1]; for (int i = 1; i < allFeatures.length; i++) { filtered[i - 1] = allFeatures[i]; } @@ -598,7 +594,7 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe } final Feature[] colorizedFeatures = colorizeFeatures(features); final VectorOptions vectorSourceOptions = createVectorOptions(colorizedFeatures); - final ol.source.Vector vectorSource = new ol.source.Vector(vectorSourceOptions); + final var vectorSource = new ol.source.Vector(vectorSourceOptions); vectorLayer = createVectorLayer(vectorSource); vectorLayer.set(TileSuppliers.ATTRIBUTIONS, vectorSourceOptions.getAttributions()); map.addLayer(vectorLayer); @@ -612,7 +608,7 @@ public final class MapView extends HtmlContentBuilder<HTMLElement> implements Fe final Feature[] features = parseGeoJson(geoJson); GWT.log("MapView.setGeoJson() nb of features: " + features.length); if (features.length > 0) { - final ColorSequenceManager colorMgr = new ColorSequenceManager(); + final var colorMgr = new ColorSequenceManager(); colorMgr.setColorSequenceName(indicator.getColorSequenceName()); if (indicator.getQuantileType() != null) { final List<Double> values = Arrays.stream(features).map(MapView::getValue).collect(Collectors.toList()); diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/view/RightPanelView.java b/www-client/src/main/java/fr/agrometinfo/www/client/view/RightPanelView.java index b98016a4..77405825 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/view/RightPanelView.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/view/RightPanelView.java @@ -32,7 +32,6 @@ import fr.agrometinfo.www.client.ui.CardDetails; import fr.agrometinfo.www.client.ui.chart.DailyValuesChart; import fr.agrometinfo.www.client.util.UiUtils; import fr.agrometinfo.www.shared.dto.FeatureLevel; -import fr.agrometinfo.www.shared.dto.IndicatorDTO; import fr.agrometinfo.www.shared.dto.SummaryDTO; /** @@ -142,8 +141,8 @@ public final class RightPanelView implements RightPanelPresenter.View { private String getDescription(final boolean comparison) { GWT.log("RightPanelView.getDescription()"); - final IndicatorDTO indicator = summary.getIndicator(); - String region = summary.getFeatureName(); + final var indicator = summary.getIndicator(); + var region = summary.getFeatureName(); if (region == null) { region = CSTS.metropolitanFrance(); } @@ -210,25 +209,17 @@ public final class RightPanelView implements RightPanelPresenter.View { GWT.log("RightPanelView.setSummary()"); summary = data; - final String featureName = data.getFeatureName(); + final var featureName = data.getFeatureName(); final String title; if (featureName == null || featureName.isEmpty()) { title = CSTS.metropolitanFrance(); } else { - switch (data.getChoice().getLevel()) { - case CELL: - title = MSGS.cell(featureName); - break; - case PRA: - title = MSGS.pra(featureName); - break; - case REGION: - title = MSGS.region(featureName); - break; - default: - throw new UnsupportedOperationException("Level not handled: " + data.getChoice().getLevel()); - - } + title = switch (data.getChoice().getLevel()) { + case CELL -> MSGS.cell(featureName); + case PRA -> MSGS.pra(featureName); + case REGION -> MSGS.region(featureName); + default -> throw new UnsupportedOperationException("Level not handled: " + data.getChoice().getLevel()); + }; } if (backBtnClickListener != null) { @@ -240,7 +231,7 @@ public final class RightPanelView implements RightPanelPresenter.View { } else if (data.getParentFeature() != null) { backBtn.getTextSpan().textContent(data.getParentFeature().getName()); backBtnClickListener = e -> { - final FeatureSelectEvent event = new FeatureSelectEvent(); + final var event = new FeatureSelectEvent(); event.setId(data.getParentFeature().getId()); event.setLevel(data.getParentFeature().getLevel()); App.getEventBus().fireEvent(event); @@ -255,14 +246,14 @@ public final class RightPanelView implements RightPanelPresenter.View { backBtn.addClickListener(backBtnClickListener); } - final NumberFormat nf = NumberFormat.getFormat("0.#"); - final DateTimeFormat df = DateTimeFormat.getFormat(PredefinedFormat.DATE_MEDIUM); + final var nf = NumberFormat.getFormat("0.#"); + final var df = DateTimeFormat.getFormat(PredefinedFormat.DATE_MEDIUM); header.element().innerHTML = ""; header.add(title + ", " + periodName); header.add(Elements.br()); header.add(Elements.small(df.format(data.getDate()))); - final IndicatorDTO indicator = data.getIndicator(); + final var indicator = data.getIndicator(); if (indicator == null) { DomGlobal.console.error("data.getIndicator() must not be null!"); diff --git a/www-client/src/main/java/fr/agrometinfo/www/client/view/SurveyView.java b/www-client/src/main/java/fr/agrometinfo/www/client/view/SurveyView.java index 0a4e677d..e5e68fbc 100644 --- a/www-client/src/main/java/fr/agrometinfo/www/client/view/SurveyView.java +++ b/www-client/src/main/java/fr/agrometinfo/www/client/view/SurveyView.java @@ -31,44 +31,73 @@ import fr.agrometinfo.www.shared.dto.SurveyQuestionDTO; * @author Jérémie Décome */ public final class SurveyView extends AbstractBaseView<SurveyPresenter> implements SurveyPresenter.View { + /** + * CSS class for hiding « Other text » area. + */ + private static final String CSS_HIDE_TEXTAREA = "hide-textarea"; + /** * I18N constants. */ private static final AppConstants CSTS = GWT.create(AppConstants.class); + /** * Is survey was already validated by user ? Key for LocalStorage. */ private static final String IS_VALIDATED_KEY = "isValidated"; + /** * Level for questions. */ private static final int SECTION_TITLE_LEVEL = 5; - /** - * CSS class for hidding « Other text » area. - */ - private static final String CSS_HIDE_TEXTAREA = "hide-textarea"; + /** * List of available responses. */ private Map<SurveyQuestionDTO, List<SurveyOptionDTO>> availableResponses; + /** - * The modal used to display the login form. + * List of all checkbox on modal. */ - private ModalDialog modal; - /** Validate button of modal. */ - private Button validate; - /** List of all checkbox on modal. */ private List<CheckBox> checkBoxList = new ArrayList<>(); + /** * E-mail field. */ private EmailBox email; + /** + * The modal used to display the login form. + */ + private ModalDialog modal; + + /** + * Validate button of modal. + */ + private Button validate; + + /** + * Enable or disable validate button depending of checkbox status. + */ + private void activateValidateButton() { + this.validate.setDisabled(!this.checkBoxList.stream().anyMatch((c) -> c.getValue())); + } + @Override public void close() { modal.close(); } + @Override + public void displaySuccessLogin(final String msg) { + this.notification(CSTS.surveyFormSuccess()); + } + + @Override + public void failureNotification(final FailedResponseBean failedResponse) { + this.notification(CSTS.surveyFormFail()); + } + @Override public void init() { GWT.log("LoginView.init()"); @@ -78,9 +107,7 @@ public final class SurveyView extends AbstractBaseView<SurveyPresenter> implemen GWT.log("Survey was already validated for this user, don't showing again"); return; } - final Map<Long, TextArea> otherTextArea = new HashMap<>(); - this.modal = ModalDialog.create(CSTS.surveyFormTitle()).large().setAutoClose(true); this.modal .appendChild(Elements.p() @@ -97,36 +124,31 @@ public final class SurveyView extends AbstractBaseView<SurveyPresenter> implemen .addLeftAddOn(Icons.ALL.email()) .setWidth("75%"); this.modal.appendChild(this.email); - for (Map.Entry<SurveyQuestionDTO, List<SurveyOptionDTO>> entry : this.availableResponses.entrySet()) { final SurveyQuestionDTO k = entry.getKey(); // For each question ... - // displaying label this.modal.appendChild(Elements.h(SECTION_TITLE_LEVEL, "• " + k.getDescription())); - // displaying availables responses - entry.getValue().forEach((r) -> { - final CheckBox cb = CheckBox.create(r.getDescription()).id(Long.toString(r.getId())) + entry.getValue().forEach(r -> { + final var cb = CheckBox.create(r.getDescription()).id(Long.toString(r.getId())) .css("login-checkbox"); this.modal.appendChild(cb); this.checkBoxList.add(cb); }); - // displaying free response field - final CheckBox otherCb = CheckBox.create(CSTS.surveyFormOtherTextCheckbox()) + final var otherCb = CheckBox.create(CSTS.surveyFormOtherTextCheckbox()) .css("login-checkbox"); - final TextArea otherText = TextArea.create() + final var otherText = TextArea.create() .setDisabled(true) .setRows(2) .css("login-textarea") .css(CSS_HIDE_TEXTAREA); - otherCb.addChangeHandler((v) -> { otherText.setDisabled(!otherCb.getValue()); if (otherCb.getValue()) { // TODO : rechercher hide() / show() otherText.removeCss(CSS_HIDE_TEXTAREA) - .focus(); + .focus(); } else { otherText.css(CSS_HIDE_TEXTAREA); } @@ -139,62 +161,40 @@ public final class SurveyView extends AbstractBaseView<SurveyPresenter> implemen this.checkBoxList.forEach((c) -> { c.addChangeHandler((v) -> this.activateValidateButton()); }); - // Window's button this.validate = Button.create(CSTS.validate()).linkify(); - this.validate.addClickListener((evt) -> { + this.validate.addClickListener(evt -> { final HashMap<Long, String> otherTextMap = new HashMap<>(); - // process the predefined responses (retrieval of response references), // excluding checkbox for free responses final List<Long> selectedResponsesRef = this.checkBoxList.stream() .filter((v) -> v.getValue() && v.getId().matches("[0-9]+")) .map(v -> Long.parseLong(v.getId())).collect(Collectors.toList()); - // process the free responses otherTextArea.forEach((k, v) -> { - // if textarea is activ, there is (potentially) a response and if textarea is not empty - if (!v.isDisabled() && !v.getValue().equals("")) { + // if textarea is active, there is (potentially) a response and if textarea is not empty + if (!v.isDisabled() && !v.getValue().isEmpty()) { otherTextMap.put(k, v.getValue()); } }); - this.getPresenter().insertUserResponses(selectedResponsesRef, otherTextMap, this.email.getValue()); - ls.setItem(IS_VALIDATED_KEY, "true"); this.modal.close(); }); this.validate.setDisabled(true); // Validate button is disable by default this.modal.appendFooterChild(validate); - - final Button ignore = Button.create(CSTS.ignore()).linkify(); + final var ignore = Button.create(CSTS.ignore()).linkify(); ignore.addClickListener((evt) -> { this.modal.close(); }); this.modal.appendFooterChild(ignore); - this.modal.open(); GWT.log("LoginView.init() end"); } - @Override - public void failureNotification(final FailedResponseBean failedResponse) { - this.notification(CSTS.surveyFormFail()); - } - @Override public void setResponses(final Map<SurveyQuestionDTO, List<SurveyOptionDTO>> map) { this.availableResponses = map; } - @Override - public void displaySuccessLogin(final String msg) { - this.notification(CSTS.surveyFormSuccess()); - } - /** - * Enable or disable validate button depending of checkbox status. - */ - private void activateValidateButton() { - this.validate.setDisabled(!this.checkBoxList.stream().anyMatch((c) -> c.getValue())); - } } diff --git a/www-client/src/test/java/fr/agrometinfo/www/client/util/color/ColorSequenceManagerTest.java b/www-client/src/test/java/fr/agrometinfo/www/client/util/color/ColorSequenceManagerTest.java index 46e56571..db68290b 100644 --- a/www-client/src/test/java/fr/agrometinfo/www/client/util/color/ColorSequenceManagerTest.java +++ b/www-client/src/test/java/fr/agrometinfo/www/client/util/color/ColorSequenceManagerTest.java @@ -32,15 +32,15 @@ public class ColorSequenceManagerTest { /** * Values to render. */ - private static final List<Double> RESULTS = IntStream.rangeClosed(1, 5630).asDoubleStream().boxed() + private static final List<Double> RESULTS = IntStream.rangeClosed(1, 5_630).asDoubleStream().boxed() .collect(Collectors.toList()); private static void checkColors(final List<ColorInterval> intervals, final Double value) { - final String expectedColor = ColorSequenceManager.getColorForValue(intervals, value); + final var expectedColor = ColorSequenceManager.getColorForValue(intervals, value); IntStream.range(value.intValue(), value.intValue() + 9)// .forEach(v -> { - final String colorAt = ColorSequenceManager.getColorForValue(intervals, (double) v); + final var colorAt = ColorSequenceManager.getColorForValue(intervals, (double) v); assertEquals(expectedColor, colorAt); }); } @@ -51,7 +51,7 @@ public class ColorSequenceManagerTest { final int minValue = 10; final int nbOfClasses = 10; - final ColorSequenceManager mgr = new ColorSequenceManager(); + final var mgr = new ColorSequenceManager(); mgr.setLinear(minValue, maxValue, nbOfClasses); mgr.setColorSequenceName(NAME); final List<ColorInterval> intervals = mgr.getColorIntervals(); @@ -64,7 +64,7 @@ public class ColorSequenceManagerTest { @Test void getColorIntervalsQuantile() { - final ColorSequenceManager mgr = new ColorSequenceManager(); + final var mgr = new ColorSequenceManager(); for (final QuantileType quantile : QuantileType.values()) { final int nbOfClasses = quantile.getNbOfClasses(); mgr.setQuantile(quantile, RESULTS); @@ -80,7 +80,7 @@ public class ColorSequenceManagerTest { final double maxValue = 100.2; final int nbOfClasses = 10; - final ColorSequenceManager mgr = new ColorSequenceManager(); + final var mgr = new ColorSequenceManager(); mgr.setLinear(minValue, maxValue, nbOfClasses); mgr.setColorSequenceName(NAME); final List<ColorInterval> intervals = mgr.getColorIntervals(); @@ -88,14 +88,14 @@ public class ColorSequenceManagerTest { assertEquals(nbOfClasses, intervals.size()); for (double number = minValue; number < maxValue; number++) { - final String actual = ColorSequenceManager.getColorForValue(intervals, number); + final var actual = ColorSequenceManager.getColorForValue(intervals, number); assertNotNull(actual); } - final ColorInterval firstInterval = intervals.get(0); + final var firstInterval = intervals.get(0); assertEquals(minValue, firstInterval.getMin(), 0.1); - final ColorInterval lastInterval = intervals.get(intervals.size() - 1); + final var lastInterval = intervals.get(intervals.size() - 1); assertEquals(maxValue, lastInterval.getMax(), 0.1); } @@ -105,14 +105,14 @@ public class ColorSequenceManagerTest { final double minValue = 40.48128240581562; final double value = maxValue; final int nbOfClasses = 10; - final ColorSequenceManager mgr = new ColorSequenceManager(); + final var mgr = new ColorSequenceManager(); mgr.setLinear(minValue, maxValue, nbOfClasses); mgr.setColorSequenceName(NAME); final List<ColorInterval> intervals = mgr.getColorIntervals(); assertNotNull(intervals); assertEquals(nbOfClasses, intervals.size()); - final String actual = ColorSequenceManager.getColorForValue(intervals, value); - final String expected = ColorSequences.SEQUENCES.get(NAME).get(nbOfClasses).get(nbOfClasses - 1); + final var actual = ColorSequenceManager.getColorForValue(intervals, value); + final var expected = ColorSequences.SEQUENCES.get(NAME).get(nbOfClasses).get(nbOfClasses - 1); assertEquals(expected, actual); } @@ -122,14 +122,14 @@ public class ColorSequenceManagerTest { final double maxValue = value; final double minValue = value; final int nbOfClasses = 10; - final ColorSequenceManager mgr = new ColorSequenceManager(); + final var mgr = new ColorSequenceManager(); mgr.setLinear(minValue, maxValue, nbOfClasses); mgr.setColorSequenceName(NAME); final List<ColorInterval> intervals = mgr.getColorIntervals(); assertNotNull(intervals); assertEquals(nbOfClasses, intervals.size()); - final String actual = ColorSequenceManager.getColorForValue(intervals, value); - final String expected = ColorSequences.SEQUENCES.get(NAME).get(nbOfClasses).get(0); + final var actual = ColorSequenceManager.getColorForValue(intervals, value); + final var expected = ColorSequences.SEQUENCES.get(NAME).get(nbOfClasses).get(0); assertEquals(expected, actual); } @@ -138,16 +138,16 @@ public class ColorSequenceManagerTest { final double value = 5.625; final double maxValue = value; final double minValue = value; - final QuantileType quantile = QuantileType.CENTILES_05; + final var quantile = QuantileType.CENTILES_05; final List<Double> results = Arrays.asList(minValue, value, value, value, maxValue); - final ColorSequenceManager mgr = new ColorSequenceManager(); + final var mgr = new ColorSequenceManager(); mgr.setQuantile(quantile, results); mgr.setColorSequenceName(NAME); final List<ColorInterval> intervals = mgr.getColorIntervals(); assertNotNull(intervals); assertEquals(1, intervals.size()); - final String actual = ColorSequenceManager.getColorForValue(intervals, value); - final String expected = ColorSequences.SEQUENCES.get(NAME).get(quantile.getNbOfClasses()).get(0); + final var actual = ColorSequenceManager.getColorForValue(intervals, value); + final var expected = ColorSequences.SEQUENCES.get(NAME).get(quantile.getNbOfClasses()).get(0); assertEquals(expected, actual); } @@ -159,7 +159,7 @@ public class ColorSequenceManagerTest { final double maxValue = 3.212037037037038; final double minValue = 1.2354814814814814; final int nbOfClasses = 3; - final ColorSequenceManager mgr = new ColorSequenceManager(); + final var mgr = new ColorSequenceManager(); mgr.setLinear(minValue, maxValue, nbOfClasses); mgr.setColorSequenceName(NAME); final List<ColorInterval> intervals = mgr.getColorIntervals(); @@ -173,19 +173,19 @@ public class ColorSequenceManagerTest { for (double d = 0.; d < 100.; d += 1) { results.add(d); } - final QuantileType quantile = QuantileType.CENTILES_05; + final var quantile = QuantileType.CENTILES_05; final Double minValue = results.get(0); final Double maxValue = results.get(results.size() - 1); final int nbOfClasses = quantile.getNbOfClasses(); - final ColorSequenceManager mgr = new ColorSequenceManager(); + final var mgr = new ColorSequenceManager(); mgr.setQuantile(quantile, results); mgr.setColorSequenceName(NAME); final List<ColorInterval> intervals = mgr.getColorIntervals(); assertEquals(nbOfClasses, intervals.size()); - final String firstColor = intervals.get(0).getColor(); - final String secondColor = intervals.get(1).getColor(); - final String thirdColor = intervals.get(2).getColor(); + final var firstColor = intervals.get(0).getColor(); + final var secondColor = intervals.get(1).getColor(); + final var thirdColor = intervals.get(2).getColor(); // < 5% : first color assertEquals(firstColor, ColorSequenceManager.getColorForValue(intervals, minValue)); // 5% - 95% : second color @@ -204,12 +204,12 @@ public class ColorSequenceManagerTest { final double minValue = 5.625; final double maxValue = 6.645; final List<Double> results = Arrays.asList(minValue, maxValue); - final QuantileType quantile = QuantileType.CENTILES_05; - final ColorSequenceManager mgr = new ColorSequenceManager(); + final var quantile = QuantileType.CENTILES_05; + final var mgr = new ColorSequenceManager(); mgr.setQuantile(quantile, results); mgr.setColorSequenceName(NAME); final List<ColorInterval> intervals = mgr.getColorIntervals(); - final String colorAt = ColorSequenceManager.getColorForValue(intervals, minValue); + final var colorAt = ColorSequenceManager.getColorForValue(intervals, minValue); assertNotNull(colorAt); } @@ -219,7 +219,7 @@ public class ColorSequenceManagerTest { final double minValue = 9.8; final int nbOfClasses = 10; - final ColorSequenceManager mgr = new ColorSequenceManager(); + final var mgr = new ColorSequenceManager(); mgr.setLinear(minValue, maxValue, nbOfClasses); mgr.setColorSequenceName(NAME); final List<ColorInterval> intervals = mgr.getColorIntervals(); diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/I18n.java b/www-server/src/main/java/fr/agrometinfo/www/server/I18n.java index 2b0cd7cb..fac4a955 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/I18n.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/I18n.java @@ -3,7 +3,6 @@ package fr.agrometinfo.www.server; import java.text.MessageFormat; import java.util.Collections; import java.util.HashSet; -import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernate.java b/www-server/src/main/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernate.java index 8b9c990e..2759837e 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernate.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/dao/PraDailyValueDaoHibernate.java @@ -255,7 +255,7 @@ public class PraDailyValueDaoHibernate extends DaoHibernate<PraDailyValue> imple public final List<Indicator> findIndicators(@NonNull final Integer year) { final var sql = "SELECT DISTINCT indicator FROM v_pra_dailyvalue WHERE EXTRACT(YEAR FROM date) = :year"; final List<Long> ids = super.findAllBySQL(sql, Map.of("year", year)).stream() // - .map(i -> Long.valueOf((long) i)).toList(); + .map(i -> Long.valueOf((int) i)).toList(); final var jpql = "SELECT i FROM Indicator AS i JOIN i.period WHERE i.id IN (:ids)"; return super.findAllByJPQL(jpql, Map.of("ids", ids), Indicator.class); } diff --git a/www-shared/src/main/java/org/geojson/Polygon.java b/www-shared/src/main/java/org/geojson/Polygon.java index da9414b5..592f2a68 100644 --- a/www-shared/src/main/java/org/geojson/Polygon.java +++ b/www-shared/src/main/java/org/geojson/Polygon.java @@ -2,7 +2,6 @@ package org.geojson; import java.util.ArrayList; import java.util.Arrays; -import static java.util.Arrays.asList; import java.util.List; import org.dominokit.jackson.annotation.JSONMapper; @@ -53,7 +52,7 @@ public final class Polygon extends GeoJsonObject { */ public Polygon(final LngLatAlt... polygon) { super(TYPE); - add(asList(polygon)); + add(Arrays.asList(polygon)); } /** -- GitLab From 0abbb2702ab193dad58e03dffeea1ed80440e503 Mon Sep 17 00:00:00 2001 From: Olivier Maury <Olivier.Maury@inrae.fr> Date: Tue, 3 Dec 2024 18:12:51 +0100 Subject: [PATCH 6/6] checkstyle : Inner assignments --- .../www/server/ErrorHandlerServlet.java | 70 +++++++++---------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/www-server/src/main/java/fr/agrometinfo/www/server/ErrorHandlerServlet.java b/www-server/src/main/java/fr/agrometinfo/www/server/ErrorHandlerServlet.java index c56370d0..d8ac555b 100644 --- a/www-server/src/main/java/fr/agrometinfo/www/server/ErrorHandlerServlet.java +++ b/www-server/src/main/java/fr/agrometinfo/www/server/ErrorHandlerServlet.java @@ -36,53 +36,53 @@ public final class ErrorHandlerServlet extends HttpServlet { final var exception = (Exception) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); final var locale = LocaleUtils.getLocale(request); final var i18n = new I18n("fr.agrometinfo.www.server.i18n", locale); - String body; final var title = i18n.format(response.getStatus(), "http.status.title"); - switch (response.getStatus()) { + final var body = switch (response.getStatus()) { case HttpServletResponse.SC_BAD_REQUEST -> - body = """ - <p>La demande n'a pas pu être comprise par le serveur à cause d'une syntaxe mal formée.<br /> - Vous NE DEVRIEZ PAS répéter la demande sans modifications.</p> - """; + """ + <p>La demande n'a pas pu être comprise par le serveur à cause d'une syntaxe mal formée.<br /> + Vous NE DEVRIEZ PAS répéter la demande sans modifications.</p> + """; case HttpServletResponse.SC_NOT_FOUND -> - body = """ - <p>La page que vous cherchez n'existe pas, mais vous n'êtes pas - pour autant dans une impasse. Voici quelques options disponibles :</p> - <ul> - <li>Assurez-vous d'utiliser la bonne adresse URL.</li><li>Consultez <a href=" - """ + appUrl + """ - "target="_blank">la documentation</a>.</li> - <li>Obtenez de l'aide en écrivant une demande de support dans l'application ou <a href=" - """ + appUrl + """ - /contact.html\">contactez-nous</a>.</li> - </ul> - """; + """ + <p>La page que vous cherchez n'existe pas, mais vous n'êtes pas + pour autant dans une impasse. Voici quelques options disponibles :</p> + <ul> + <li>Assurez-vous d'utiliser la bonne adresse URL.</li><li>Consultez <a href=" + """ + appUrl + """ + "target="_blank">la documentation</a>.</li> + <li>Obtenez de l'aide en écrivant une demande de support dans l'application ou <a href=" + """ + appUrl + """ + /contact.html\">contactez-nous</a>.</li> + </ul> + """; case HttpServletResponse.SC_INTERNAL_SERVER_ERROR -> - body = """ - <p>Le serveur a rencontré une condition inattendue qui l'empêche de satisfaire la demande.</p> - <p><b>Erreur :</b> """ + exception + "</p><p><b>Cause :</b> " + exception.getCause() // - + "</p>"; + """ + <p>Le serveur a rencontré une condition inattendue qui l'empêche de satisfaire la demande.</p> + <p><b>Erreur :</b> """ + exception + "</p><p><b>Cause :</b> " + exception.getCause() // + + "</p>"; case HttpServletResponse.SC_SERVICE_UNAVAILABLE -> - body = """ - <p>Le serveur est incapable de traiter actuellement la demande à cause d'une surcharge temporaire - ou de la maintenance du serveur.<br /> - Il s'agit d'une condition temporaire qui sera levée après un certain temps.</p> - """; + """ + <p>Le serveur est incapable de traiter actuellement la demande à cause d'une surcharge temporaire + ou de la maintenance du serveur.<br /> + Il s'agit d'une condition temporaire qui sera levée après un certain temps.</p> + """; default -> { - body = "<p><b>Erreur :</b> " + exception + "</p>"; + String str = "<p><b>Erreur :</b> " + exception + "</p>"; if (exception != null) { - body += "<p><b>Message d'erreur :</b>" + exception.getMessage() + "</p>"; + str += "<p><b>Message d'erreur :</b>" + exception.getMessage() + "</p>"; } - body += "<p><b>Status code:</b> " + response.getStatus() + "</p>"; - body += "<p><b>Request URI:</b> " + request.getScheme() + "://" + request.getServerName() + str += "<p><b>Status code:</b> " + response.getStatus() + "</p>"; + str += "<p><b>Request URI:</b> " + request.getScheme() + "://" + request.getServerName() + request.getRequestURI() + "</p>"; - body += "<p><b>URL:</b> " + request.getRequestURI() + "</p>"; - body += "<p><b>Context path:</b> " + getServletContext().getContextPath() + "</p>"; + str += "<p><b>URL:</b> " + request.getRequestURI() + "</p>"; + str += "<p><b>Context path:</b> " + getServletContext().getContextPath() + "</p>"; if (exception != null) { - body += "<p><b>Cause:</b> " + exception.getCause() + "</p>"; + str += "<p><b>Cause:</b> " + exception.getCause() + "</p>"; } + yield str; } - } + }; request.setAttribute("appUrl", appUrl); request.setAttribute("body", body); request.setAttribute("locale", locale.getLanguage()); -- GitLab