From 4aa468c58b1a0859c61bf9f73b6ec64fde781f76 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Tue, 19 Oct 2021 12:02:14 +0300 Subject: [PATCH 001/137] Initial commit --- .gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..85e7c1df --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/.idea/ From d40f3ef7bb10c5ce3d8bcb11d845bc1e256a1371 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 11 Nov 2021 15:46:33 +0200 Subject: [PATCH 002/137] TCDING-62: Setup the application. Remove unused files. Update the db driver. --- forms/pom.xml | 38 +++-------------- .../toolkit/forms/application.properties | 2 +- .../toolkit/forms/wicket/page/BasePage.java | 14 ------- .../forms/wicket/page/Homepage.properties | 2 +- persistence-mongodb/pom.xml | 6 +-- .../persistence/mongo/application.properties | 2 +- persistence/pom.xml | 6 +-- .../persistence/application.properties | 7 +++- .../spring/DatabaseConfiguration.java | 19 --------- .../src/test/resources/test.properties | 4 ++ pom.xml | 13 +++--- reporting/pom.xml | 4 +- .../toolkit/ui/application.properties | 2 +- web/pom.xml | 12 ++---- .../toolkit/web/application.properties | 2 +- .../controller/SaveCustomerController.java | 41 ------------------- web/src/test/resources/test.properties | 6 ++- 17 files changed, 41 insertions(+), 139 deletions(-) delete mode 100644 web/src/main/java/org/devgateway/toolkit/web/rest/controller/SaveCustomerController.java diff --git a/forms/pom.xml b/forms/pom.xml index a98d10a9..b749bb4c 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -19,11 +19,11 @@ jar Wicket Forms - DGToolkit Forms + TCDI Admin Forms - org.devgateway.toolkit - toolkit + org.devgateway.tcdi + admin 0.0.1-SNAPSHOT @@ -43,7 +43,7 @@ - org.devgateway.toolkit + org.devgateway.tcdi persistence 0.0.1-SNAPSHOT @@ -61,35 +61,7 @@ - org.devgateway.toolkit - persistence-mongodb - 0.0.1-SNAPSHOT - - - - org.devgateway.toolkit - ui - 0.0.1-SNAPSHOT - - - - - - - - - - - - - - - - - - - - org.devgateway.toolkit + org.devgateway.tcdi web 0.0.1-SNAPSHOT diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/application.properties b/forms/src/main/java/org/devgateway/toolkit/forms/application.properties index 642e6623..0170f98a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/application.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/application.properties @@ -10,7 +10,7 @@ # Development Gateway - initial API and implementation ############################################################################### spring.profiles.active=reports -server.port = 8090 +server.port = 8080 server.servlet.session.timeout=7d javamelody.enabled=true javamelody.spring-monitoring-enabled=true diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 2da7ea12..95bbf724 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -283,20 +283,6 @@ JavamelodyPage.class, new StringResourceModel("navbar.javamelody", new StringResourceModel("navbar.springendpoints", this, null)) .setIconType(FontAwesomeIconType.anchor)); - final MenuBookmarkablePageLink uiBrowserLink = - new MenuBookmarkablePageLink( - UIRedirectPage.class, null, new StringResourceModel("navbar.ui", this, null)) { - private static final long serialVersionUID = 1L; - - @Override - protected void onComponentTag(final ComponentTag tag) { - super.onComponentTag(tag); - tag.put("target", "_blank"); - } - }; - uiBrowserLink.setIconType(FontAwesomeIconType.rocket).setEnabled(true); - list.add(uiBrowserLink); - list.add(new MenuDivider()); list.add(new MenuBookmarkablePageLink(EditAdminSettingsPage.class, diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties index bb3cec81..48508802 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties @@ -10,4 +10,4 @@ # Development Gateway - initial API and implementation ############################################################################### page.title=Home Page -welcome=Welcome to DG-Toolkit! +welcome=Welcome to TCDI Data Entry diff --git a/persistence-mongodb/pom.xml b/persistence-mongodb/pom.xml index a0e37796..0ccd3e25 100644 --- a/persistence-mongodb/pom.xml +++ b/persistence-mongodb/pom.xml @@ -23,15 +23,15 @@ UTF-8 - org.devgateway.toolkit.persistence.spring.PersistenceApplication + org.devgateway.tcdi.persistence.spring.PersistenceApplication 1.8 2.2.6 1.9 - org.devgateway.toolkit - toolkit + org.devgateway.tcdi + admin 0.0.1-SNAPSHOT diff --git a/persistence-mongodb/src/main/java/org/devgateway/toolkit/persistence/mongo/application.properties b/persistence-mongodb/src/main/java/org/devgateway/toolkit/persistence/mongo/application.properties index 2a925ce5..e25cc0be 100644 --- a/persistence-mongodb/src/main/java/org/devgateway/toolkit/persistence/mongo/application.properties +++ b/persistence-mongodb/src/main/java/org/devgateway/toolkit/persistence/mongo/application.properties @@ -9,4 +9,4 @@ # Contributors: # Development Gateway - initial API and implementation ############################################################################### -server.port = 8090 +server.port = 8080 diff --git a/persistence/pom.xml b/persistence/pom.xml index 2bc0406e..d0f31a64 100644 --- a/persistence/pom.xml +++ b/persistence/pom.xml @@ -13,7 +13,7 @@ jar JPA Persistence - DGToolkit Persistence + TCDI Admin Persistence UTF-8 @@ -27,8 +27,8 @@ - org.devgateway.toolkit - toolkit + org.devgateway.tcdi + admin 0.0.1-SNAPSHOT diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties index f17fcb76..09afb91d 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties @@ -9,14 +9,14 @@ # Contributors: # Development Gateway - initial API and implementation ############################################################################### -server.port = 8090 +server.port = 8080 # liquibase properties spring.liquibase.enabled=true spring.liquibase.change-log=classpath:liquibase-changelog.xml #spring.jpa.show-sql=true -spring.jpa.database-platform=org.devgateway.toolkit.persistence.derby.DerbyDialect +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL95Dialect #performance tunning for hibernate spring.jpa.hibernate.max_fetch_depth=0 @@ -33,6 +33,9 @@ spring.servlet.multipart.enabled = false #enable modified flag for envers, to track field-level modifications spring.jpa.properties.org.hibernate.envers.global_with_modified_flag=true +# tell hibernate to not detect jdbc features as it would cause unhelpful LOG stack trace in logs +spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false + spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.jcache.JCacheRegionFactory spring.jpa.properties.hibernate.javax.cache.missing_cache_strategy=create diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java index fe09b9f5..fe0c4d94 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java @@ -46,9 +46,6 @@ public class DatabaseConfiguration { private static final Logger logger = LoggerFactory.getLogger(DatabaseConfiguration.class); - @Value("${dg-toolkit.derby.port}") - private int derbyPort; - @Value("${dg-toolkit.datasource.jndi-name}") private String datasourceJndiName; @@ -89,26 +86,10 @@ public SimpleNamingContextBuilder jndiBuilder() { */ @Bean @ConfigurationProperties(prefix = "spring.datasource") - @DependsOn(value = {"derbyServer"}) public DataSource dataSource() { return DataSourceBuilder.create().build(); } - /** - * Graciously starts a Derby Database Server when the application starts up - * - * @return - * @throws Exception - */ - @Bean(destroyMethod = "shutdown") - public NetworkServerControl derbyServer() throws Exception { - Properties p = System.getProperties(); - p.put("derby.storage.pageCacheSize", "30000"); - p.put("derby.language.maxMemoryPerTable", "20000"); - NetworkServerControl nsc = new NetworkServerControl(InetAddress.getByName("localhost"), derbyPort); - nsc.start(new PrintWriter(java.lang.System.out, true)); - return nsc; - } @Bean public SpringLiquibaseRunner liquibaseAfterJPA(final SpringLiquibase springLiquibase, diff --git a/persistence/src/test/resources/test.properties b/persistence/src/test/resources/test.properties index 7a3693d7..1acd006f 100644 --- a/persistence/src/test/resources/test.properties +++ b/persistence/src/test/resources/test.properties @@ -13,5 +13,9 @@ logging.level.org.springframework.test=error logging.level.org.springframework.web=error logging.level.org.hibernate=error +spring.jpa.database-platform=org.hibernate.dialect.DerbyTenSevenDialect + spring.datasource.driver-class-name=org.apache.derby.jdbc.EmbeddedDriver spring.datasource.url=jdbc:derby:memory:toolkit;create=true + +derby.stream.error.file=target/derby.log diff --git a/pom.xml b/pom.xml index 4b012118..610a6a79 100644 --- a/pom.xml +++ b/pom.xml @@ -12,13 +12,12 @@ 4.0.0 - org.devgateway.toolkit - toolkit + org.devgateway.tcdi + admin 0.0.1-SNAPSHOT pom - DGToolkit - DG Toolkit archetype - quick and easy way to start new projects through a working template - + TCDI Admin + TCDI Admin UTF-8 @@ -38,10 +37,10 @@ persistence web - ui + forms - persistence-mongodb + checkstyle diff --git a/reporting/pom.xml b/reporting/pom.xml index 749837dd..7eed4d53 100644 --- a/reporting/pom.xml +++ b/reporting/pom.xml @@ -34,8 +34,8 @@ - org.devgateway.toolkit - toolkit + org.devgateway.tcdi + admin 0.0.1-SNAPSHOT diff --git a/ui/src/main/java/org/devgateway/toolkit/ui/application.properties b/ui/src/main/java/org/devgateway/toolkit/ui/application.properties index 88653873..fe544a52 100644 --- a/ui/src/main/java/org/devgateway/toolkit/ui/application.properties +++ b/ui/src/main/java/org/devgateway/toolkit/ui/application.properties @@ -10,4 +10,4 @@ # Development Gateway - initial API and implementation ############################################################################### spring.servlet.multipart.enabled = false -server.port = 8090 \ No newline at end of file +server.port = 8080 \ No newline at end of file diff --git a/web/pom.xml b/web/pom.xml index ecd29f92..1082a174 100644 --- a/web/pom.xml +++ b/web/pom.xml @@ -22,8 +22,8 @@ - org.devgateway.toolkit - toolkit + org.devgateway.tcdi + admin 0.0.1-SNAPSHOT @@ -84,17 +84,11 @@ - org.devgateway.toolkit + org.devgateway.tcdi persistence 0.0.1-SNAPSHOT - - org.devgateway.toolkit - persistence-mongodb - 0.0.1-SNAPSHOT - - org.springframework.boot spring-boot-starter-mail diff --git a/web/src/main/java/org/devgateway/toolkit/web/application.properties b/web/src/main/java/org/devgateway/toolkit/web/application.properties index 5ad54bd1..0cb8232d 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/application.properties +++ b/web/src/main/java/org/devgateway/toolkit/web/application.properties @@ -10,7 +10,7 @@ # Development Gateway - initial API and implementation ############################################################################### spring.servlet.multipart.enabled = false -server.port = 8090 +server.port = 8080 management.endpoints.web.base-path=/manage management.endpoints.web.expose=* management.endpoint.shutdown.enabled=true diff --git a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/SaveCustomerController.java b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/SaveCustomerController.java deleted file mode 100644 index 7105d7a4..00000000 --- a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/SaveCustomerController.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Development Gateway, Inc and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the MIT License (MIT) - * which accompanies this distribution, and is available at - * https://opensource.org/licenses/MIT - * - * Contributors: - * Development Gateway - initial API and implementation - *******************************************************************************/ -package org.devgateway.toolkit.web.rest.controller; - -import java.util.List; - -import org.devgateway.toolkit.persistence.mongo.dao.Customer; -import org.devgateway.toolkit.persistence.mongo.repository.CustomerRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * - * @author mpostelnicu - * - */ -@RestController -public class SaveCustomerController { - - @Autowired - private CustomerRepository customerRepository; - - @RequestMapping("/createCustomer") - public List createCustomer() { - customerRepository.save(new Customer("Alice", "Smith")); - customerRepository.save(new Customer("Bob", "Smith")); - - List findAll = customerRepository.findAll(); - return findAll; - } -} \ No newline at end of file diff --git a/web/src/test/resources/test.properties b/web/src/test/resources/test.properties index f88ef6bd..52724287 100644 --- a/web/src/test/resources/test.properties +++ b/web/src/test/resources/test.properties @@ -15,5 +15,9 @@ logging.level.org.springframework.test=error logging.level.org.springframework.web=error logging.level.org.hibernate=error +spring.jpa.database-platform=org.hibernate.dialect.DerbyTenSevenDialect + spring.datasource.driver-class-name=org.apache.derby.jdbc.EmbeddedDriver -spring.datasource.url=jdbc:derby:memory:toolkit;create=true \ No newline at end of file +spring.datasource.url=jdbc:derby:memory:toolkit;create=true + +derby.stream.error.file=target/derby.log \ No newline at end of file From 2e6856bb8baac2c4610c510481a1101aa6bfb465 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 25 Nov 2021 23:14:08 +0200 Subject: [PATCH 003/137] TCDING-62: Remove unused file. Configure the docker env. --- Dockerfile | 14 +++++ README.md | 4 +- dev_services.bat | 3 + dev_services.sh | 2 + docker-compose.override.yml | 6 ++ docker-compose.yml | 28 +++++++++ forms/pom.xml | 8 +-- .../toolkit/forms/application.properties | 3 +- .../forms/wicket/FormsWebApplication.java | 1 + persistence/pom.xml | 13 ++-- .../persistence/application-dev.properties | 16 +++++ .../persistence/application.properties | 9 ++- .../toolkit/persistence/dao/data/DataSet.java | 63 +++++++++++++++++++ .../spring/DatabaseConfiguration.java | 12 ++-- persistence/src/main/resources/Person.sql | 26 -------- .../src/main/resources/Person_roles.sql | 5 -- .../main/resources/liquibase-changelog.xml | 16 ++++- pom.xml | 3 +- web/pom.xml | 6 +- 19 files changed, 178 insertions(+), 60 deletions(-) create mode 100644 Dockerfile create mode 100644 dev_services.bat create mode 100644 dev_services.sh create mode 100644 docker-compose.override.yml create mode 100644 docker-compose.yml create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DataSet.java delete mode 100644 persistence/src/main/resources/Person.sql delete mode 100644 persistence/src/main/resources/Person_roles.sql diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..f2cf0fc4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,14 @@ +FROM maven:3.8-jdk-11 AS build +RUN mkdir /tcdi-admin +WORKDIR /tcdi-admin +COPY . /tcdi-admin + +RUN mvn -B clean package +RUN mkdir -p /opt/tcdi/admin +RUN mv */target/*-0.0.1-SNAPSHOT.jar /opt/tcdi/admin + +FROM openjdk:11-jre-slim +WORKDIR /opt/tcdi/admin +COPY --from=build /opt/tcdi/admin ./ +EXPOSE 8080 +ENTRYPOINT ["java","-jar","/opt/tcdi/admin/tcdi-admin-forms-0.0.1-SNAPSHOT.jar"] diff --git a/README.md b/README.md index d61ed239..0fedd451 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# dg-toolkit +# tcdi-admin based on dg-toolkit [![Build Status](https://travis-ci.org/devgateway/dg-toolkit.svg?branch=master)](https://travis-ci.org/devgateway/dg-toolkit) @@ -113,7 +113,7 @@ frolvlad/alpine-oraclejdk8 slim 00d8610f052e 2 weeks ago The image can be started with ``` -$docker run -p 8090:8090 -t devgateway/toolkit/forms +$docker run -p 8080:8080 -t devgateway/toolkit/forms ``` That's it, congrats! diff --git a/dev_services.bat b/dev_services.bat new file mode 100644 index 00000000..e20c201f --- /dev/null +++ b/dev_services.bat @@ -0,0 +1,3 @@ +set TAG=staging + +docker-compose up postgres admin \ No newline at end of file diff --git a/dev_services.sh b/dev_services.sh new file mode 100644 index 00000000..cee88436 --- /dev/null +++ b/dev_services.sh @@ -0,0 +1,2 @@ +set TAG=staging +docker-compose up postgres admin \ No newline at end of file diff --git a/docker-compose.override.yml b/docker-compose.override.yml new file mode 100644 index 00000000..d01e0d40 --- /dev/null +++ b/docker-compose.override.yml @@ -0,0 +1,6 @@ +version: '3' + +services: + postgres: + volumes: + - ./data/postgres:/var/lib/postgresql/data diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..bb6bd13a --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,28 @@ +version: '3' + +services: + admin: + build: . + depends_on: + - postgres + volumes: + - admin:/opt/tcdi/admin + ports: + - 8080:8080 + logging: &json_file + driver: json-file + + postgres: + image: mdillon/postgis + restart: unless-stopped + volumes: + - postgres:/var/lib/postgresql/data + environment: + POSTGRES_PASSWORD: postgres + POSTGRES_USER: postgres + POSTGRES_DB: tcdi-admin + logging: *json_file + +volumes: + admin: null + postgres: null diff --git a/forms/pom.xml b/forms/pom.xml index b749bb4c..53848dec 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -15,7 +15,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - forms + tcdi-admin-forms jar Wicket Forms @@ -23,7 +23,7 @@ org.devgateway.tcdi - admin + tcdi-admin 0.0.1-SNAPSHOT @@ -44,7 +44,7 @@ org.devgateway.tcdi - persistence + tcdi-admin-persistence 0.0.1-SNAPSHOT @@ -62,7 +62,7 @@ org.devgateway.tcdi - web + tcdi-admin-web 0.0.1-SNAPSHOT diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/application.properties b/forms/src/main/java/org/devgateway/toolkit/forms/application.properties index 0170f98a..59cd8613 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/application.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/application.properties @@ -10,9 +10,10 @@ # Development Gateway - initial API and implementation ############################################################################### spring.profiles.active=reports +spring.application.name=tcdi-admin server.port = 8080 server.servlet.session.timeout=7d -javamelody.enabled=true +javamelody.enabled=false javamelody.spring-monitoring-enabled=true javamelody.init-parameters.log=true javamelody.advisor-auto-proxy-creator-enabled=false diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java index a313cf56..d79b0450 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java @@ -62,6 +62,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.PropertySources; import org.springframework.scheduling.annotation.EnableScheduling; import org.wicketstuff.annotation.scan.AnnotatedMountScanner; import org.wicketstuff.select2.ApplicationSettings; diff --git a/persistence/pom.xml b/persistence/pom.xml index d0f31a64..fbba99ef 100644 --- a/persistence/pom.xml +++ b/persistence/pom.xml @@ -9,7 +9,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - persistence + tcdi-admin-persistence jar JPA Persistence @@ -28,7 +28,7 @@ org.devgateway.tcdi - admin + tcdi-admin 0.0.1-SNAPSHOT @@ -147,14 +147,15 @@ org.apache.derby - derbyclient + derby ${derby.version} + test - org.apache.derby - derbynet - ${derby.version} + org.postgresql + postgresql + ${pgsql.version} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties new file mode 100644 index 00000000..d9a21465 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties @@ -0,0 +1,16 @@ +############################################################################### +# Copyright (c) 2015 Development Gateway, Inc and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the MIT License (MIT) +# which accompanies this distribution, and is available at +# https://opensource.org/licenses/MIT +# +# Contributors: +# Development Gateway - initial API and implementation +############################################################################### +spring.config.activate.on-profile=dev + +spring.datasource.username=postgres +spring.datasource.password=postgres +spring.datasource.jdbc-url=jdbc:postgresql:tcdi-admin diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties index 09afb91d..e5e3d1d3 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties @@ -38,15 +38,14 @@ spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.jcache.JCacheRegionFactory -spring.jpa.properties.hibernate.javax.cache.missing_cache_strategy=create spring.datasource.max-active=3000 spring.datasource.max-idle=8 spring.datasource.min-idle=8 spring.datasource.initial-size=20 -spring.datasource.driver-class-name=org.apache.derby.jdbc.ClientDriver40 -spring.datasource.username=app -spring.datasource.password=app -spring.datasource.jdbc-url=jdbc:derby://localhost//derby/toolkit;create=true +spring.datasource.driver-class-name=org.postgresql.Driver +spring.datasource.username=postgres +spring.datasource.password=postgres +spring.datasource.jdbc-url=jdbc:postgresql://postgres:5432/tcdi-admin spring.datasource.transaction-isolation=2 dg-toolkit.datasource.jndi-name=toolkitDS dg-toolkit.derby.port=1527 diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DataSet.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DataSet.java new file mode 100644 index 00000000..69d54ec6 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DataSet.java @@ -0,0 +1,63 @@ +package org.devgateway.toolkit.persistence.dao.data; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.devgateway.toolkit.persistence.dao.AbstractAuditableEntity; +import org.devgateway.toolkit.persistence.dao.FileMetadata; +import org.devgateway.toolkit.persistence.dao.Labelable; +import org.devgateway.toolkit.persistence.dao.Person; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import java.io.Serializable; +import java.util.Collection; +import java.util.Set; + +@Entity +public class DataSet extends AbstractAuditableEntity implements Serializable, Labelable { + + private String label; + + private String source; + + @Column(length = 1024) + private String description; + + private Integer year; + + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) + private Set files; + + private boolean approved; + + @ManyToOne(fetch = FetchType.EAGER) + private Person uploadedBy; + + @ManyToOne(fetch = FetchType.EAGER) + private Person approvedBy; + + @JsonIgnore + @Column(insertable = false, updatable = false) + private String dtype; + + @Override + public AbstractAuditableEntity getParent() { + return null; + } + + @Override + public void setLabel(final String label) { + + } + + @Override + public String getLabel() { + return null; + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java index fe0c4d94..b6ba719f 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java @@ -16,7 +16,6 @@ import com.zaxxer.hikari.HikariDataSource; import liquibase.integration.spring.SpringLiquibase; -import org.apache.derby.drda.NetworkServerControl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -27,21 +26,24 @@ import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.PropertySources; import org.springframework.mock.jndi.SimpleNamingContextBuilder; import javax.naming.NamingException; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; -import java.io.PrintWriter; -import java.net.InetAddress; -import java.util.Properties; /** * @author mpostelnicu * */ @Configuration -@PropertySource("classpath:/org/devgateway/toolkit/persistence/application.properties") +@PropertySources({ + @PropertySource("classpath:/org/devgateway/toolkit/persistence/application.properties"), + @PropertySource( + value = "classpath:/org/devgateway/toolkit/persistence/application-${spring.profiles.active}.properties", + ignoreResourceNotFound = true) +}) @Profile("!integration") public class DatabaseConfiguration { private static final Logger logger = LoggerFactory.getLogger(DatabaseConfiguration.class); diff --git a/persistence/src/main/resources/Person.sql b/persistence/src/main/resources/Person.sql deleted file mode 100644 index 6270228c..00000000 --- a/persistence/src/main/resources/Person.sql +++ /dev/null @@ -1,26 +0,0 @@ -INSERT INTO PERSON -( - ID, - CHANGE_PASSWORD_NEXT_SIGN_IN, - EMAIL, - ENABLED, - FIRST_NAME, - LAST_NAME, - PASSWORD, - TITLE, - USERNAME, - GROUP_ID -) -VALUES -( - NEXT VALUE FOR HIBERNATE_SEQUENCE, - false, - NULL, - true, - NULL, - NULL, - '$2a$10$wvn/WOzcIGu.GGFGDhEzS.0KVIhHG3ypCNjH4ui1Xa8h3qgt2mdZ6', - NULL, - 'admin', - NULL -); \ No newline at end of file diff --git a/persistence/src/main/resources/Person_roles.sql b/persistence/src/main/resources/Person_roles.sql deleted file mode 100644 index e41283c9..00000000 --- a/persistence/src/main/resources/Person_roles.sql +++ /dev/null @@ -1,5 +0,0 @@ -INSERT INTO PERSON_ROLES(PERSON_ID, ROLES_ID) - SELECT p.ID, r.ID - FROM PERSON p, ROLE r - WHERE p.USERNAME = 'admin' - AND r.AUTHORITY IN ('ROLE_ADMIN', 'ROLE_USER'); diff --git a/persistence/src/main/resources/liquibase-changelog.xml b/persistence/src/main/resources/liquibase-changelog.xml index a53e6add..b72874b3 100644 --- a/persistence/src/main/resources/liquibase-changelog.xml +++ b/persistence/src/main/resources/liquibase-changelog.xml @@ -47,7 +47,13 @@ - + + + + + + + @@ -57,7 +63,13 @@ - + diff --git a/pom.xml b/pom.xml index 610a6a79..8005b5cd 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.devgateway.tcdi - admin + tcdi-admin 0.0.1-SNAPSHOT pom TCDI Admin @@ -24,6 +24,7 @@ 1.8 3.8.9 2.2.11.RELEASE + 42.2.5 10.14.2.0 4.0.1 devgateway/toolkit diff --git a/web/pom.xml b/web/pom.xml index 1082a174..14e9ecc3 100644 --- a/web/pom.xml +++ b/web/pom.xml @@ -7,7 +7,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - web + tcdi-admin-web jar Web @@ -23,7 +23,7 @@ org.devgateway.tcdi - admin + tcdi-admin 0.0.1-SNAPSHOT @@ -85,7 +85,7 @@ org.devgateway.tcdi - persistence + tcdi-admin-persistence 0.0.1-SNAPSHOT From f78dce8a1d0dbe90094418c141c244243454d36f Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 1 Dec 2021 18:07:45 +0200 Subject: [PATCH 004/137] TCDING-57: Init dataset model --- entrypoint.sh | 30 +++++++++++++++++++ .../dao/data/{DataSet.java => Dataset.java} | 4 +-- persistence/src/main/resources/ehcache.xml | 2 ++ 3 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 entrypoint.sh rename persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/{DataSet.java => Dataset.java} (94%) diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100644 index 00000000..434d6c27 --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,30 @@ +#!/bin/sh + + PROP_FILE="tcdi-admin.properties" + echo "Writing to $PROP_FILE:" + + PROPERTIES="$(cat <<-EOF + server.port + spring.application.name + spring.liquibase.enabled + spring.datasource.jdbc-url + spring.datasource.url + spring.mail.host + EOF + )" + + echo "$PROPERTIES" | while IFS=read PROPERTY; do + VAR_NAME="$(echo "$PROPERTY" | tr '[:lower:].-' '[:upper:]__')" + eval VALUE="\$$VAR_NAME" + if [ -n "$VALUE" ]; then + echo "$PROPERTY=$VALUE" + fi + done | tee -a "$PROP_FILE" + + JAR="tcdi-admin-forms-0.0.1-SNAPSHOT.jar" + JAVA_OPTS="-Dspring.config.location=file://$PROP_FILE" + exec /bin/sh -c "java -jar '$JAR' $JAVA_OPTS $@" nobody + ;; +*) + exec $@ + ;; \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DataSet.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java similarity index 94% rename from persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DataSet.java rename to persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java index 69d54ec6..7630aa1f 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DataSet.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java @@ -19,12 +19,10 @@ import java.util.Set; @Entity -public class DataSet extends AbstractAuditableEntity implements Serializable, Labelable { +public class Dataset extends AbstractAuditableEntity implements Serializable, Labelable { private String label; - private String source; - @Column(length = 1024) private String description; diff --git a/persistence/src/main/resources/ehcache.xml b/persistence/src/main/resources/ehcache.xml index 06139dc6..f2a54102 100644 --- a/persistence/src/main/resources/ehcache.xml +++ b/persistence/src/main/resources/ehcache.xml @@ -18,4 +18,6 @@ + + \ No newline at end of file From 0c9a6f8eedc47d752109be3d0a4e93cb51d63ec3 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 1 Dec 2021 18:09:09 +0200 Subject: [PATCH 005/137] TCDING-57: Setup the menu items and logos. --- .../toolkit/forms/wicket/page/BasePage.html | 2 +- .../toolkit/forms/wicket/page/BasePage.java | 65 ++++++++++++-- .../forms/wicket/page/BasePage.properties | 7 ++ .../forms/wicket/page/Homepage.properties | 2 +- .../forms/wicket/styles/BaseStyles.css | 4 + .../styles/assets/img/icons/tcdi-favicon.svg | 15 ++++ .../assets/img/tcdi-horizontal-logo.svg | 90 +++++++++++++++++++ 7 files changed, 178 insertions(+), 7 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/assets/img/icons/tcdi-favicon.svg create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/assets/img/tcdi-horizontal-logo.svg diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.html index 00d13c0c..43ccfe44 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.html @@ -2,7 +2,7 @@ - DGToolkit + TCDI Admin diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 95bbf724..088208a9 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -29,7 +29,6 @@ import org.apache.wicket.Component; import org.apache.wicket.Page; import org.apache.wicket.authroles.authorization.strategies.role.metadata.MetaDataRoleAuthorizationStrategy; -import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.head.CssHeaderItem; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.JavaScriptHeaderItem; @@ -55,6 +54,7 @@ import org.devgateway.toolkit.forms.security.SecurityUtil; import org.devgateway.toolkit.forms.wicket.page.lists.ListGroupPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListTestFormPage; +import org.devgateway.toolkit.forms.wicket.page.lists.ListTobaccoProductPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListUserPage; import org.devgateway.toolkit.forms.wicket.page.user.EditUserPage; import org.devgateway.toolkit.forms.wicket.page.user.LogoutPage; @@ -199,7 +199,7 @@ protected List newSubMenuButtons(final String buttonMarkupId) { protected MetaDataHeaderItem getFavicon() { PackageResourceReference faviconRef = - new PackageResourceReference(BaseStyles.class, "assets/img/icons/toolkit-favicon.svg"); + new PackageResourceReference(BaseStyles.class, "assets/img/icons/tcdi-favicon.svg"); MetaDataHeaderItem icon = MetaDataHeaderItem.forLinkTag("icon", urlFor(faviconRef, null).toString()); icon.addTagAttribute("type", "image/svg+xml"); @@ -299,6 +299,61 @@ JavamelodyPage.class, new StringResourceModel("navbar.javamelody", return adminMenu; } + protected NavbarDropDownButton newDatasetsMenu() { + NavbarDropDownButton categoriesMenu = new NavbarDropDownButton( + new StringResourceModel("navbar.datasets", this, null)) { + private static final long serialVersionUID = 1L; + + @Override + protected List newSubMenuButtons(final String arg0) { + final List list = new ArrayList<>(); + list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, + new StringResourceModel("navbar.tetsim", this, null)) + .setIconType(FontAwesomeIconType.percent)); + + list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, + new StringResourceModel("navbar.prevalence", this, null)) + .setIconType(FontAwesomeIconType.list_ul)); + + list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, + new StringResourceModel("navbar.policy", this, null)) + .setIconType(FontAwesomeIconType.list_ul)); + + list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, + new StringResourceModel("navbar.ecigarettes", this, null)) + .setIconType(FontAwesomeIconType.list_ul)); + + return list; + } + }; + + categoriesMenu.setIconType(FontAwesomeIconType.table); + MetaDataRoleAuthorizationStrategy.authorize(categoriesMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); + + return categoriesMenu; + } + + protected NavbarDropDownButton newCategoriesMenu() { + NavbarDropDownButton categoriesMenu = new NavbarDropDownButton( + new StringResourceModel("navbar.categories", this, null)) { + private static final long serialVersionUID = 1L; + + @Override + protected List newSubMenuButtons(final String arg0) { + final List list = new ArrayList<>(); + list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, + new StringResourceModel("navbar.tobaccoproducts", this, null)) + .setIconType(FontAwesomeIconType.leaf)); + return list; + } + }; + + categoriesMenu.setIconType(FontAwesomeIconType.list_ul); + MetaDataRoleAuthorizationStrategy.authorize(categoriesMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); + + return categoriesMenu; + } + /** * creates a new {@link Navbar} instance * @@ -315,14 +370,14 @@ protected Navbar newNavbar(final String markupId) { * @see org.devgateway.toolkit.forms.wicket.styles.BaseStyles */ navbar.setPosition(Navbar.Position.TOP); - navbar.setBrandImage(new PackageResourceReference(BaseStyles.class, "assets/img/toolkit-logo-0048.png"), + navbar.setBrandImage(new PackageResourceReference(BaseStyles.class, "assets/img/tcdi-horizontal-logo.svg"), new StringResourceModel("brandImageAltText", this, null)); - navbar.setInverted(true); navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.RIGHT, newHomeMenu(), newAdminMenu(), + newDatasetsMenu(), newCategoriesMenu(), newAccountMenu(), newLogoutMenu())); - navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.LEFT, newLanguageMenu())); +// navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.RIGHT, newLanguageMenu())); return navbar; } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties index a7520833..a0fe0e79 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties @@ -14,6 +14,13 @@ navbar.logout=Logout navbar.users=Users navbar.groups=Groups navbar.admin=Admin +navbar.datasets=Datasets +navbar.tetsim=TETSIM +navbar.prevalence=Prevalence +navbar.policy=Policy +navbar.ecigarettes=E-cigarette +navbar.categories=Categories +navbar.tobaccoproducts=Tobacco Products navbar.testcomponents=Test Components navbar.swagger=Swagger navbar.halbrowser=HAL Browser diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties index 48508802..31158b08 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties @@ -10,4 +10,4 @@ # Development Gateway - initial API and implementation ############################################################################### page.title=Home Page -welcome=Welcome to TCDI Data Entry +welcome=Welcome to TCDI Data Entry Admin diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css index d569e2e7..90a4a311 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css @@ -58,6 +58,10 @@ body { padding: 0px; } +.navbar-brand > img { + height: 100%; +} + .mainContainer { /* * The main page content should have some height. diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/assets/img/icons/tcdi-favicon.svg b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/assets/img/icons/tcdi-favicon.svg new file mode 100644 index 00000000..0b45c2de --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/assets/img/icons/tcdi-favicon.svg @@ -0,0 +1,15 @@ + + + + + + + + + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/assets/img/tcdi-horizontal-logo.svg b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/assets/img/tcdi-horizontal-logo.svg new file mode 100644 index 00000000..f601aadc --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/assets/img/tcdi-horizontal-logo.svg @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 9c7d2e4010a7a1e0d89060f534086b2df8191d4f Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 1 Dec 2021 18:09:56 +0200 Subject: [PATCH 006/137] TCDING-57: Add tobacco products pages and models --- .../filter/TobaccoProductFilterState.java | 39 ++++++++++ .../wicket/page/edit/AbstractEditPage.java | 10 +++ .../page/edit/AbstractEditPage.properties | 2 + .../edit/category/EditTobaccoProductPage.html | 15 ++++ .../edit/category/EditTobaccoProductPage.java | 58 +++++++++++++++ .../EditTobaccoProductPage.properties | 5 ++ .../wicket/page/lists/AbstractListPage.java | 23 +++--- .../page/lists/ListTobaccoProductPage.java | 74 +++++++++++++++++++ .../lists/ListTobaccoProductPage.properties | 3 + .../dao/categories/TobaccoProduct.java | 23 ++++++ .../category/TobaccoProductRepository.java | 11 +++ .../category/TobaccoProductService.java | 10 +++ .../category/TobaccoProductServiceImpl.java | 42 +++++++++++ 13 files changed, 305 insertions(+), 10 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TobaccoProductFilterState.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.properties create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/TobaccoProduct.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/TobaccoProductRepository.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductService.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TobaccoProductFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TobaccoProductFilterState.java new file mode 100644 index 00000000..6c1e5445 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TobaccoProductFilterState.java @@ -0,0 +1,39 @@ +package org.devgateway.toolkit.forms.wicket.components.table.filter; + +import org.apache.commons.lang3.StringUtils; +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct_; +import org.devgateway.toolkit.persistence.repository.SpecificationContext; +import org.springframework.data.jpa.domain.Specification; + +import javax.persistence.criteria.Predicate; +import java.util.ArrayList; +import java.util.List; + +public class TobaccoProductFilterState extends JpaFilterState { + + private static final long serialVersionUID = 6916178929560942055L; + + private String label; + + @Override + public Specification getSpecification() { + return (root, query, cb) -> { + List predicates = new ArrayList<>(); + SpecificationContext sc = new SpecificationContext<>(root, query, cb); + + if (StringUtils.isNotBlank(label)) { + predicates.add(cb.like(root.get(TobaccoProduct_.label), "%" + label + "%")); + } + return cb.and(predicates.toArray(new Predicate[predicates.size()])); + }; + } + + public String getLabel() { + return label; + } + + public void setLabel(final String label) { + this.label = label; + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java index 5556976c..a51b3ca7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java @@ -483,6 +483,8 @@ protected void onComponentTag(final ComponentTag tag) { Fragment fragment = new Fragment("extraButtons", "noButtons", this); editForm.add(fragment); + pageTitle.setDefaultModel(getTitleModel()); + } protected void onDelete(final AjaxRequestTarget target) { @@ -536,4 +538,12 @@ protected void onInitialize() { protected void afterLoad(final IModel model) { } + + protected StringResourceModel getTitleModel() { + if (entityId == null) { + return new StringResourceModel("page.title.add", this, null); + } else { + return new StringResourceModel("page.title.edit", this, null); + } + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.properties index 313d965e..d75a9e2d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.properties @@ -10,6 +10,8 @@ # Development Gateway - initial API and implementation ############################################################################### page.title=Edit Item +page.title.add=Add Item +page.title.edit=Edit Item WorkstreamSectionEditPage.page.title=Workstream Section Edit CountryEditPage.page.title=Countries Edit CoordinationGoalsEditPage.page.title=Coordination Goals Edit diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.html new file mode 100644 index 00000000..929b3043 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.html @@ -0,0 +1,15 @@ + + + + + Edit Tobacco Product + + + +
+
+
+
+
+ + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java new file mode 100644 index 00000000..f246ba84 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (c) 2015 Development Gateway, Inc and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the MIT License (MIT) + * which accompanies this distribution, and is available at + * https://opensource.org/licenses/MIT + * + * Contributors: + * Development Gateway - initial API and implementation + *******************************************************************************/ +package org.devgateway.toolkit.forms.wicket.page.edit.category; + +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.util.string.StringValue; +import org.devgateway.toolkit.forms.WebConstants; +import org.devgateway.toolkit.forms.validators.UniquePropertyValidator; +import org.devgateway.toolkit.forms.wicket.components.form.CheckBoxYesNoToggleBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; +import org.devgateway.toolkit.forms.wicket.page.lists.ListTobaccoProductPage; +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; +import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; +import org.wicketstuff.annotation.mount.MountPath; + +/** + * @author mpostelnicu + */ +@MountPath(value = "/editTobaccoProduct") +public class EditTobaccoProductPage extends AbstractEditPage { + + private static final long serialVersionUID = 8165480663853267637L; + + @SpringBean + protected TobaccoProductService tobaccoProductService; + + public EditTobaccoProductPage(final PageParameters parameters) { + super(parameters); + this.jpaService = tobaccoProductService; + this.listPageClass = ListTobaccoProductPage.class; + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + final TextFieldBootstrapFormComponent name = new TextFieldBootstrapFormComponent<>("label"); + name.required(); + final StringValue id = getPageParameters().get(WebConstants.PARAM_ID); + name.getField().add(new UniquePropertyValidator<>(tobaccoProductService, id.toLong(-1L), + "label", this)); + name.getField().add(WebConstants.StringValidators.MAXIMUM_LENGTH_VALIDATOR_STD_DEFAULT_TEXT); + editForm.add(name); + + editForm.add(new CheckBoxYesNoToggleBootstrapFormComponent("illicit")); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.properties new file mode 100644 index 00000000..05e8b238 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.properties @@ -0,0 +1,5 @@ +page.title.add=Add Tobacco Product +page.title.edit=Edit Tobacco Product +label.label=Product Name +illicit.label=Is it an illicit product? +uniqueLabel=Name should be unique! \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java index 092ac219..20753670 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java @@ -81,7 +81,7 @@ public abstract class AbstractListPage jpaService; - private SortableJpaServiceDataProvider dataProvider; + protected SortableJpaServiceDataProvider dataProvider; private BootstrapBookmarkablePageLink editPageLink; @@ -190,18 +190,21 @@ public ActionPanel(final String id, final IModel model) { add(getPrintButton(pageParameters)); + add(getRevisionsLink(entity)); + } + } - PageParameters revisionsPageParameters = new PageParameters(); - revisionsPageParameters.set(WebConstants.PARAM_ID, entity.getId()); - revisionsPageParameters.set(WebConstants.PARAM_ENTITY_CLASS, entity.getClass().getName()); + protected Component getRevisionsLink(final T entity) { + PageParameters revisionsPageParameters = new PageParameters(); + revisionsPageParameters.set(WebConstants.PARAM_ID, entity.getId()); + revisionsPageParameters.set(WebConstants.PARAM_ENTITY_CLASS, entity.getClass().getName()); - BootstrapBookmarkablePageLink revisionsPageLink = new BootstrapBookmarkablePageLink<>("revisions", - RevisionsPage.class, revisionsPageParameters, Buttons.Type.Info); - revisionsPageLink.setIconType(FontAwesomeIconType.clock_o).setSize(Size.Small) - .setLabel(new StringResourceModel("revisions", AbstractListPage.this, null)); - add(revisionsPageLink); + BootstrapBookmarkablePageLink revisionsPageLink = new BootstrapBookmarkablePageLink<>("revisions", + RevisionsPage.class, revisionsPageParameters, Buttons.Type.Info); + revisionsPageLink.setIconType(FontAwesomeIconType.clock_o).setSize(Size.Small) + .setLabel(new StringResourceModel("revisions", AbstractListPage.this, null)); - } + return revisionsPageLink; } /** diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.java new file mode 100644 index 00000000..50e0a568 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.java @@ -0,0 +1,74 @@ +/******************************************************************************* + * Copyright (c) 2015 Development Gateway, Inc and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the MIT License (MIT) + * which accompanies this distribution, and is available at + * https://opensource.org/licenses/MIT + * + * Contributors: + * Development Gateway - initial API and implementation + *******************************************************************************/ +package org.devgateway.toolkit.forms.wicket.page.lists; + +import org.apache.wicket.Component; +import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.wicket.components.table.TextFilteredBootstrapPropertyColumn; +import org.devgateway.toolkit.forms.wicket.components.table.filter.JpaFilterState; +import org.devgateway.toolkit.forms.wicket.components.table.filter.TestFormFilterState; +import org.devgateway.toolkit.forms.wicket.components.table.filter.TobaccoProductFilterState; +import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; +import org.devgateway.toolkit.forms.wicket.page.edit.EditTestFormPage; +import org.devgateway.toolkit.forms.wicket.page.edit.category.EditTobaccoProductPage; +import org.devgateway.toolkit.persistence.dao.TestForm; +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; +import org.devgateway.toolkit.persistence.service.RoleService; +import org.devgateway.toolkit.persistence.service.TestFormService; +import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; +import org.wicketstuff.annotation.mount.MountPath; + +@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) +@MountPath(value = "/listTobaccoProduct") +public class ListTobaccoProductPage extends AbstractListPage { + private static final long serialVersionUID = -324298525712620234L; + + @SpringBean + private TobaccoProductService tobaccoProductService; + + public ListTobaccoProductPage(final PageParameters pageParameters) { + super(pageParameters); + this.jpaService = tobaccoProductService; + this.editPageClass = EditTobaccoProductPage.class; + + columns.add(new TextFilteredBootstrapPropertyColumn<>(new StringResourceModel("label"), "label", "label")); + columns.add(new PropertyColumn<>(new StringResourceModel("illicit"), "illicit", "illicit")); + } + + + @Override + protected void onInitialize() { + super.onInitialize(); + + dataProvider.setSort("label", SortOrder.ASCENDING); + + excelForm.setVisibilityAllowed(false); + } + + @Override + protected Component getRevisionsLink(final TobaccoProduct entity) { + return new WebMarkupContainer("revisions").setVisibilityAllowed(false); + } + + @Override + public JpaFilterState newFilterState() { + return new TobaccoProductFilterState(); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.properties new file mode 100644 index 00000000..bd5dc168 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.properties @@ -0,0 +1,3 @@ +page.title=Tobacco Products +label=Product Name +illicit=Is it an illicit product? \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/TobaccoProduct.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/TobaccoProduct.java new file mode 100644 index 00000000..2fde075d --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/TobaccoProduct.java @@ -0,0 +1,23 @@ +package org.devgateway.toolkit.persistence.dao.categories; + +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; +import org.hibernate.envers.Audited; + +import javax.persistence.Entity; + +@Entity +@Audited +@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) +public class TobaccoProduct extends Category { + + private Boolean illicit; + + public Boolean isIllicit() { + return illicit; + } + + public void setIllicit(final Boolean illicit) { + this.illicit = illicit; + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/TobaccoProductRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/TobaccoProductRepository.java new file mode 100644 index 00000000..72581fa0 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/TobaccoProductRepository.java @@ -0,0 +1,11 @@ +package org.devgateway.toolkit.persistence.repository.category; + +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; +import org.devgateway.toolkit.persistence.repository.norepository.UniquePropertyRepository; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public interface TobaccoProductRepository extends CategoryRepository, + UniquePropertyRepository { + +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductService.java new file mode 100644 index 00000000..7180b018 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductService.java @@ -0,0 +1,10 @@ +package org.devgateway.toolkit.persistence.service.category; + +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; +import org.devgateway.toolkit.persistence.service.BaseJpaService; +import org.devgateway.toolkit.persistence.service.TextSearchableService; +import org.devgateway.toolkit.persistence.service.UniquePropertyService; + +public interface TobaccoProductService extends BaseJpaService, TextSearchableService, + UniquePropertyService { +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java new file mode 100644 index 00000000..7f841fab --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java @@ -0,0 +1,42 @@ +package org.devgateway.toolkit.persistence.service.category; + +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; +import org.devgateway.toolkit.persistence.repository.category.GroupRepository; +import org.devgateway.toolkit.persistence.repository.category.TobaccoProductRepository; +import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; +import org.devgateway.toolkit.persistence.repository.norepository.TextSearchableRepository; +import org.devgateway.toolkit.persistence.repository.norepository.UniquePropertyRepository; +import org.devgateway.toolkit.persistence.service.BaseJpaServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheConfig; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@CacheConfig(cacheNames = "servicesCache") +@Transactional(readOnly = true) +public class TobaccoProductServiceImpl extends BaseJpaServiceImpl implements TobaccoProductService { + + @Autowired + private TobaccoProductRepository tobaccoProductRepository; + + @Override + public TobaccoProduct newInstance() { + return new TobaccoProduct(); + } + + @Override + protected BaseJpaRepository repository() { + return tobaccoProductRepository; + } + + @Override + public TextSearchableRepository textRepository() { + return tobaccoProductRepository; + } + + @Override + public UniquePropertyRepository uniquePropertyRepository() { + return tobaccoProductRepository; + } +} From 03c8dd4514debc5ca5f5854495923f5adee0d1ee Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 2 Dec 2021 09:11:54 +0200 Subject: [PATCH 007/137] TCDING-57: Update font awesome icons version --- checkstyle-suppressions.xml | 1 + forms/pom.xml | 9 +++- .../components/form/BootstrapAddButton.java | 6 +-- .../form/BootstrapCancelButton.java | 4 +- .../form/BootstrapDeleteButton.java | 4 +- .../form/BootstrapSubmitButton.java | 6 +-- .../CheckBoxPickerBootstrapFormComponent.java | 7 ++- ...ileInputBootstrapFormComponentWrapper.java | 6 +-- .../components/modal/ConfirmationModal.java | 4 +- .../components/util/CustomDownloadLink.java | 4 +- .../toolkit/forms/wicket/page/BasePage.java | 45 ++++++++++--------- .../edit/AbstractEditStatusEntityPage.java | 12 ++--- .../wicket/page/lists/AbstractListPage.java | 10 ++--- 13 files changed, 63 insertions(+), 55 deletions(-) diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml index 86fcf6c4..dc2ebe72 100644 --- a/checkstyle-suppressions.xml +++ b/checkstyle-suppressions.xml @@ -9,4 +9,5 @@ files="PersistenceApplication\.java|MongoPersistenceApplication\.java|UIWebApplication\.java|WebApplication\.java|ReportingApplication\.java" /> + \ No newline at end of file diff --git a/forms/pom.xml b/forms/pom.xml index 53848dec..81f12a28 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -32,13 +32,14 @@ 1.8 8.10.0 8.10.0 - 2.0.11 + 2.0.15 1.13 2.0.19 v20200406 3.1 2.4.8 1.86.0 + 5.15.3 @@ -149,6 +150,12 @@ ${wicket.webjars.version}
+ + org.webjars + font-awesome + ${font.awesome.version} + + org.apache.wicket wicket-devutils diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapAddButton.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapAddButton.java index d0937a10..b380deef 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapAddButton.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapAddButton.java @@ -16,7 +16,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons.Size; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeIconType; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.event.IEvent; @@ -37,9 +37,9 @@ public abstract class BootstrapAddButton extends LaddaAjaxButton { */ public BootstrapAddButton(final String id, final IModel model) { super(id, model, Buttons.Type.Info); - setIconType(FontAwesomeIconType.save); + setIconType(FontAwesome5IconType.save_s); setDefaultFormProcessing(false); - setIconType(FontAwesomeIconType.plus).setSize(Size.Medium).setLabel(model); + setIconType(FontAwesome5IconType.plus_s).setSize(Size.Medium).setLabel(model); setOutputMarkupPlaceholderTag(true); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapCancelButton.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapCancelButton.java index b20acc67..5f1d9f02 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapCancelButton.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapCancelButton.java @@ -15,7 +15,7 @@ package org.devgateway.toolkit.forms.wicket.components.form; import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeIconType; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.IModel; @@ -36,7 +36,7 @@ public abstract class BootstrapCancelButton extends LaddaAjaxButton { public BootstrapCancelButton(final String id, final IModel model) { super(id, model, Buttons.Type.Default); setDefaultFormProcessing(false); - setIconType(FontAwesomeIconType.ban); + setIconType(FontAwesome5IconType.ban_s); } @Override diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapDeleteButton.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapDeleteButton.java index fd9611ef..1f1f8fb9 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapDeleteButton.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapDeleteButton.java @@ -15,7 +15,7 @@ package org.devgateway.toolkit.forms.wicket.components.form; import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeIconType; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxCallListener; @@ -55,7 +55,7 @@ protected void onInitialize() { super.onInitialize(); add(new AttributeAppender("onclick", new Model("window.onbeforeunload = null;"), " ")); setDefaultFormProcessing(false); - setIconType(FontAwesomeIconType.trash_o); + setIconType(FontAwesome5IconType.trash_s); if (ComponentUtil.isViewMode()) { setVisibilityAllowed(false); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapSubmitButton.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapSubmitButton.java index 65a9b22f..cabd7ec6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapSubmitButton.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapSubmitButton.java @@ -15,7 +15,7 @@ package org.devgateway.toolkit.forms.wicket.components.form; import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeIconType; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; import org.apache.wicket.ajax.AjaxRequestTarget; @@ -37,12 +37,12 @@ public abstract class BootstrapSubmitButton extends LaddaAjaxButton { */ public BootstrapSubmitButton(final String id, final IModel model) { super(id, model, Buttons.Type.Primary); - setIconType(FontAwesomeIconType.save); + setIconType(FontAwesome5IconType.save_s); } public BootstrapSubmitButton(final String id, final Form form, final IModel model) { super(id, model, form, Buttons.Type.Primary); - setIconType(FontAwesomeIconType.save); + setIconType(FontAwesome5IconType.save_s); } @Override diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxPickerBootstrapFormComponent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxPickerBootstrapFormComponent.java index 4f609a29..6905f202 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxPickerBootstrapFormComponent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxPickerBootstrapFormComponent.java @@ -11,10 +11,9 @@ *******************************************************************************/ package org.devgateway.toolkit.forms.wicket.components.form; -import de.agilecoders.wicket.core.markup.html.bootstrap.button.ButtonGroup; import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.checkbox.bootstrapcheckbox.BootstrapCheckBoxPicker; import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.checkbox.bootstrapcheckbox.BootstrapCheckBoxPickerConfig; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeIconType; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.model.IModel; @@ -50,8 +49,8 @@ public CheckBoxPickerBootstrapFormComponent(final String id) { protected BootstrapCheckBoxPicker inputField(final String id, final IModel model) { config = new BootstrapCheckBoxPickerConfig().withOnClass("btn-info").withOffClass("btn-warning") - .withOnIcon(FontAwesomeIconType.thumbs_up).withOffIcon(FontAwesomeIconType.thumbs_down) - .withReverse(true).withStyle(ButtonGroup.Size.Small); + .withOnIcon(FontAwesome5IconType.thumbs_up_s).withOffIcon(FontAwesome5IconType.thumbs_down_s) + .withReverse(true).withSize(BootstrapCheckBoxPickerConfig.Size.Small); final BootstrapCheckBoxPicker checkBoxPicker = new BootstrapCheckBoxPicker("field", initFieldModel(), config); checkBoxPicker.add(new AjaxFormComponentUpdatingBehavior("change") { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/FileInputBootstrapFormComponentWrapper.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/FileInputBootstrapFormComponentWrapper.java index b611b9ca..3e3891f2 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/FileInputBootstrapFormComponentWrapper.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/FileInputBootstrapFormComponentWrapper.java @@ -19,7 +19,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.image.IconBehavior; import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.fileinput.BootstrapFileInput; import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.fileinput.FileInputConfig; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeIconType; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import de.agilecoders.wicket.jquery.Key; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; @@ -235,7 +235,7 @@ public void onClick(final AjaxRequestTarget target) { target.add(alreadyUploadedFiles); } }; - delete.add(new IconBehavior(FontAwesomeIconType.trash)); + delete.add(new IconBehavior(FontAwesome5IconType.trash_s)); delete.add(new TooltipBehavior(new StringResourceModel("removeUploadedFileTooltip", FileInputBootstrapFormComponentWrapper.this, null), TOOLTIP_CONFIG)); @@ -345,7 +345,7 @@ public void onClick(final AjaxRequestTarget target) { FileInputBootstrapFormComponentWrapper.this.onUpdate(target); } }; - delete.add(new IconBehavior(FontAwesomeIconType.trash)); + delete.add(new IconBehavior(FontAwesome5IconType.trash_s)); delete.add(new TooltipBehavior(new StringResourceModel("removeUploadedFileTooltip", FileInputBootstrapFormComponentWrapper.this, null), TOOLTIP_CONFIG)); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/modal/ConfirmationModal.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/modal/ConfirmationModal.java index 9b8a9632..5b8b92f7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/modal/ConfirmationModal.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/modal/ConfirmationModal.java @@ -2,7 +2,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.core.markup.html.bootstrap.dialog.Modal; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeIconType; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; @@ -55,7 +55,7 @@ protected void onError(final AjaxRequestTarget target) { } }; submitButton.setType(Buttons.Type.Success); - submitButton.setIconType(FontAwesomeIconType.check); + submitButton.setIconType(FontAwesome5IconType.check_s); return submitButton; } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/util/CustomDownloadLink.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/util/CustomDownloadLink.java index 1caabf6c..6f85c07d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/util/CustomDownloadLink.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/util/CustomDownloadLink.java @@ -14,7 +14,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.components.TooltipBehavior; import de.agilecoders.wicket.core.markup.html.bootstrap.components.TooltipConfig; import de.agilecoders.wicket.core.markup.html.bootstrap.image.IconBehavior; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeIconType; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.model.IModel; import org.apache.wicket.model.StringResourceModel; @@ -36,7 +36,7 @@ public class CustomDownloadLink extends Link { public CustomDownloadLink(final String id, final IModel model) { super(id, model); - add(new IconBehavior(FontAwesomeIconType.download)); + add(new IconBehavior(FontAwesome5IconType.download_s)); add(new TooltipBehavior(new StringResourceModel("downloadUploadedFileTooltip", this, null), TOOLTIP_CONFIG)); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 088208a9..1c24f040 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -24,8 +24,8 @@ import de.agilecoders.wicket.core.markup.html.references.RespondJavaScriptReference; import de.agilecoders.wicket.core.markup.html.themes.bootstrap.BootstrapCssReference; import de.agilecoders.wicket.core.util.CssClassNames; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeCssReference; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeIconType; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5CssReference; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.Component; import org.apache.wicket.Page; import org.apache.wicket.authroles.authorization.strategies.role.metadata.MetaDataRoleAuthorizationStrategy; @@ -193,7 +193,7 @@ protected List newSubMenuButtons(final String buttonMarkupId) { return list; } }; - languageDropDown.setIconType(FontAwesomeIconType.flag); + languageDropDown.setIconType(FontAwesome5IconType.flag_s); return languageDropDown; } @@ -211,7 +211,7 @@ protected NavbarButton newLogoutMenu() { // logout menu final NavbarButton logoutMenu = new NavbarButton(LogoutPage.class, new StringResourceModel("navbar.logout", this, null)); - logoutMenu.setIconType(FontAwesomeIconType.sign_out); + logoutMenu.setIconType(FontAwesome5IconType.sign_out_alt_s); MetaDataRoleAuthorizationStrategy.authorize(logoutMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); return logoutMenu; @@ -229,7 +229,7 @@ protected NavbarButton newAccountMenu() { final NavbarButton accountMenu = new NavbarButton<>(EditUserPage.class, pageParametersForAccountPage, account); - accountMenu.setIconType(FontAwesomeIconType.user); + accountMenu.setIconType(FontAwesome5IconType.user_s); MetaDataRoleAuthorizationStrategy.authorize(accountMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); return accountMenu; } @@ -238,7 +238,7 @@ protected NavbarButton newHomeMenu() { // home NavbarButton homeMenu = new NavbarButton<>(Homepage.class, new StringResourceModel("navbar.home", this, null)); - homeMenu.setIconType(FontAwesomeIconType.home); + homeMenu.setIconType(FontAwesome5IconType.home_s); MetaDataRoleAuthorizationStrategy.authorize(homeMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); return homeMenu; } @@ -254,46 +254,47 @@ protected List newSubMenuButtons(final String arg0) { final List list = new ArrayList<>(); list.add(new MenuBookmarkablePageLink(ListUserPage.class, null, new StringResourceModel("navbar.users", this, null)) - .setIconType(FontAwesomeIconType.users)); + .setIconType(FontAwesome5IconType.users_s)); list.add(new MenuBookmarkablePageLink(ListGroupPage.class, null, - new StringResourceModel("navbar.groups", this, null)).setIconType(FontAwesomeIconType.tags)); + new StringResourceModel("navbar.groups", this, null)) + .setIconType(FontAwesome5IconType.tags_s)); list.add(new MenuBookmarkablePageLink(ListTestFormPage.class, null, new StringResourceModel("navbar.testcomponents", this, null)) - .setIconType(FontAwesomeIconType.android)); + .setIconType(FontAwesome5IconType.android)); list.add(new MenuDivider()); final BootstrapBookmarkablePageLink swagger = new MenuBookmarkablePageLink(SwaggerPage.class, new StringResourceModel("navbar.swagger", BasePage.this, null)) - .setIconType(FontAwesomeIconType.code); + .setIconType(FontAwesome5IconType.code_s); MetaDataRoleAuthorizationStrategy.authorize(swagger, Component.RENDER, SecurityConstants.Roles.ROLE_ADMIN); list.add(swagger); final BootstrapBookmarkablePageLink javamelody = new MenuBookmarkablePageLink( JavamelodyPage.class, new StringResourceModel("navbar.javamelody", - BasePage.this, null)).setIconType(FontAwesomeIconType.eye); + BasePage.this, null)).setIconType(FontAwesome5IconType.eye_s); MetaDataRoleAuthorizationStrategy.authorize(javamelody, Component.RENDER, SecurityConstants.Roles.ROLE_ADMIN); list.add(javamelody); list.add(new MenuBookmarkablePageLink(SpringEndpointsPage.class, null, new StringResourceModel("navbar.springendpoints", this, null)) - .setIconType(FontAwesomeIconType.anchor)); + .setIconType(FontAwesome5IconType.anchor_s)); list.add(new MenuDivider()); list.add(new MenuBookmarkablePageLink(EditAdminSettingsPage.class, new StringResourceModel("navbar.adminSettings", BasePage.this, null)) - .setIconType(FontAwesomeIconType.briefcase)); + .setIconType(FontAwesome5IconType.briefcase_s)); return list; } }; - adminMenu.setIconType(FontAwesomeIconType.cog); + adminMenu.setIconType(FontAwesome5IconType.cog_s); MetaDataRoleAuthorizationStrategy.authorize(adminMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); return adminMenu; @@ -309,25 +310,25 @@ protected List newSubMenuButtons(final String arg0) { final List list = new ArrayList<>(); list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, new StringResourceModel("navbar.tetsim", this, null)) - .setIconType(FontAwesomeIconType.percent)); + .setIconType(FontAwesome5IconType.percentage_s)); list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, new StringResourceModel("navbar.prevalence", this, null)) - .setIconType(FontAwesomeIconType.list_ul)); + .setIconType(FontAwesome5IconType.list_ul_s)); list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, new StringResourceModel("navbar.policy", this, null)) - .setIconType(FontAwesomeIconType.list_ul)); + .setIconType(FontAwesome5IconType.list_ul_s)); list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, new StringResourceModel("navbar.ecigarettes", this, null)) - .setIconType(FontAwesomeIconType.list_ul)); + .setIconType(FontAwesome5IconType.list_ul_s)); return list; } }; - categoriesMenu.setIconType(FontAwesomeIconType.table); + categoriesMenu.setIconType(FontAwesome5IconType.table_s); MetaDataRoleAuthorizationStrategy.authorize(categoriesMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); return categoriesMenu; @@ -343,12 +344,12 @@ protected List newSubMenuButtons(final String arg0) { final List list = new ArrayList<>(); list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, new StringResourceModel("navbar.tobaccoproducts", this, null)) - .setIconType(FontAwesomeIconType.leaf)); + .setIconType(FontAwesome5IconType.leaf_s)); return list; } }; - categoriesMenu.setIconType(FontAwesomeIconType.list_ul); + categoriesMenu.setIconType(FontAwesome5IconType.list_ul_s); MetaDataRoleAuthorizationStrategy.authorize(categoriesMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); return categoriesMenu; @@ -391,7 +392,7 @@ public void renderHead(final IHeaderResponse response) { // Load Styles. response.render(CssHeaderItem.forReference(BootstrapCssReference.instance())); - response.render(CssHeaderItem.forReference(FontAwesomeCssReference.instance())); + response.render(CssHeaderItem.forReference(FontAwesome5CssReference.instance())); response.render(CssHeaderItem.forReference(BaseStyles.INSTANCE)); // Load Scripts. diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index 0855f117..9124bac3 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -14,7 +14,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.core.markup.html.bootstrap.dialog.TextContentModal; import de.agilecoders.wicket.core.markup.html.bootstrap.form.BootstrapCheckbox; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeIconType; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; @@ -514,7 +514,7 @@ protected void onSubmit(final AjaxRequestTarget target) { } }; - button.setIconType(FontAwesomeIconType.send); + button.setIconType(FontAwesome5IconType.envelope_s); return button; } @@ -543,7 +543,7 @@ protected PageParameters getParameterPage() { } }; - button.setIconType(FontAwesomeIconType.tasks); + button.setIconType(FontAwesome5IconType.tasks_s); return button; } @@ -590,7 +590,7 @@ protected PageParameters getParameterPage() { } }; - button.setIconType(FontAwesomeIconType.tasks); + button.setIconType(FontAwesome5IconType.tasks_s); return button; } @@ -609,7 +609,7 @@ protected void onSubmit(final AjaxRequestTarget target) { super.onSubmit(target); } }; - saveEditPageButton.setIconType(FontAwesomeIconType.thumbs_up); + saveEditPageButton.setIconType(FontAwesome5IconType.thumbs_up_s); return saveEditPageButton; } @@ -631,7 +631,7 @@ protected void onSubmit(final AjaxRequestTarget target) { onAfterRevertToDraft(target); } }; - saveEditPageButton.setIconType(FontAwesomeIconType.thumbs_down); + saveEditPageButton.setIconType(FontAwesome5IconType.thumbs_down_s); return saveEditPageButton; } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java index 20753670..3fc7c337 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java @@ -14,7 +14,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapBookmarkablePageLink; import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons.Size; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeIconType; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; @@ -156,7 +156,7 @@ public void populateItem(final Item> cellItem, final String co pageParameters.set(WebConstants.PARAM_ID, null); editPageLink = new BootstrapBookmarkablePageLink("new", editPageClass, pageParameters, Buttons.Type.Success); - editPageLink.setIconType(FontAwesomeIconType.plus_circle).setSize(Size.Large) + editPageLink.setIconType(FontAwesome5IconType.plus_circle_s).setSize(Size.Large) .setLabel(new StringResourceModel("new", AbstractListPage.this, null)); add(editPageLink); @@ -184,7 +184,7 @@ public ActionPanel(final String id, final IModel model) { editItemPageLink = new BootstrapBookmarkablePageLink<>("edit", editPageClass, pageParameters, Buttons.Type.Info); - editItemPageLink.setIconType(FontAwesomeIconType.edit).setSize(Size.Small) + editItemPageLink.setIconType(FontAwesome5IconType.edit_s).setSize(Size.Small) .setLabel(new StringResourceModel("edit", AbstractListPage.this, null)); add(editItemPageLink); @@ -201,7 +201,7 @@ protected Component getRevisionsLink(final T entity) { BootstrapBookmarkablePageLink revisionsPageLink = new BootstrapBookmarkablePageLink<>("revisions", RevisionsPage.class, revisionsPageParameters, Buttons.Type.Info); - revisionsPageLink.setIconType(FontAwesomeIconType.clock_o).setSize(Size.Small) + revisionsPageLink.setIconType(FontAwesome5IconType.clock_s).setSize(Size.Small) .setLabel(new StringResourceModel("revisions", AbstractListPage.this, null)); return revisionsPageLink; @@ -335,7 +335,7 @@ protected void onSubmit(final AjaxRequestTarget target) { download.initiate(target); } }; - excelButton.setIconType(FontAwesomeIconType.file_excel_o); + excelButton.setIconType(FontAwesome5IconType.file_excel_s); add(excelButton); } } From 830a704242978c74d6a6a231d16b7ae80581cefb Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 3 Dec 2021 15:25:35 +0200 Subject: [PATCH 008/137] TCDING-57: Add TETSIM model --- .../toolkit/forms/wicket/page/BasePage.java | 8 +- .../toolkit/persistence/dao/data/Dataset.java | 26 +-- .../persistence/dao/data/TetsimDataset.java | 188 ++++++++++++++++++ .../dao/data/TetsimPriceVariable.java | 39 ++++ .../dao/data/TetsimTobaccoProductValue.java | 48 +++++ .../repository/data/DatasetRepository.java | 10 + .../data/TetsimDatasetRepository.java | 10 + .../service/data/TetsimDatasetService.java | 7 + .../data/TetsimDatasetServiceImpl.java | 30 +++ 9 files changed, 341 insertions(+), 25 deletions(-) create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimPriceVariable.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 1c24f040..8dfc6ab5 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -310,19 +310,19 @@ protected List newSubMenuButtons(final String arg0) { final List list = new ArrayList<>(); list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, new StringResourceModel("navbar.tetsim", this, null)) - .setIconType(FontAwesome5IconType.percentage_s)); + .setIconType(FontAwesome5IconType.percent_s)); list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, new StringResourceModel("navbar.prevalence", this, null)) - .setIconType(FontAwesome5IconType.list_ul_s)); + .setIconType(FontAwesome5IconType.users_s)); list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, new StringResourceModel("navbar.policy", this, null)) - .setIconType(FontAwesome5IconType.list_ul_s)); + .setIconType(FontAwesome5IconType.tasks_s)); list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, new StringResourceModel("navbar.ecigarettes", this, null)) - .setIconType(FontAwesome5IconType.list_ul_s)); + .setIconType(FontAwesome5IconType.smoking_s)); return list; } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java index 7630aa1f..0c9cdff1 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java @@ -1,25 +1,17 @@ package org.devgateway.toolkit.persistence.dao.data; -import com.fasterxml.jackson.annotation.JsonIgnore; import org.devgateway.toolkit.persistence.dao.AbstractAuditableEntity; -import org.devgateway.toolkit.persistence.dao.FileMetadata; import org.devgateway.toolkit.persistence.dao.Labelable; import org.devgateway.toolkit.persistence.dao.Person; -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; -import javax.persistence.CascadeType; import javax.persistence.Column; -import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; +import javax.persistence.MappedSuperclass; import java.io.Serializable; -import java.util.Collection; -import java.util.Set; -@Entity -public class Dataset extends AbstractAuditableEntity implements Serializable, Labelable { +@MappedSuperclass +public abstract class Dataset extends AbstractAuditableEntity implements Serializable, Labelable { private String label; @@ -28,10 +20,6 @@ public class Dataset extends AbstractAuditableEntity implements Serializable, La private Integer year; - @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) - private Set files; - private boolean approved; @ManyToOne(fetch = FetchType.EAGER) @@ -40,10 +28,6 @@ public class Dataset extends AbstractAuditableEntity implements Serializable, La @ManyToOne(fetch = FetchType.EAGER) private Person approvedBy; - @JsonIgnore - @Column(insertable = false, updatable = false) - private String dtype; - @Override public AbstractAuditableEntity getParent() { return null; @@ -51,11 +35,11 @@ public AbstractAuditableEntity getParent() { @Override public void setLabel(final String label) { - + this.label = label; } @Override public String getLabel() { - return null; + return label; } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java new file mode 100644 index 00000000..f3d14c93 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java @@ -0,0 +1,188 @@ +package org.devgateway.toolkit.persistence.dao.data; + +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; +import org.hibernate.envers.Audited; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.OneToOne; +import java.math.BigDecimal; + +@Entity +@Audited +@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) +public class TetsimDataset extends Dataset { + + BigDecimal cigaretteConsumption; + + BigDecimal vatRate; + + BigDecimal cigaretteDeclaredCustomValue; + + BigDecimal adultPopulation; + + BigDecimal smokingPrevalence; + + @OneToOne(fetch = FetchType.LAZY) + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) + TetsimPriceVariable retailPrice; + + @OneToOne(fetch = FetchType.LAZY) + TetsimPriceVariable marketShare; + + @OneToOne(fetch = FetchType.LAZY) + TetsimPriceVariable CIF; + + @OneToOne(fetch = FetchType.LAZY) + TetsimPriceVariable tobaccoLevy; + + @OneToOne(fetch = FetchType.LAZY) + TetsimPriceVariable exciseTax; + + @OneToOne(fetch = FetchType.LAZY) + TetsimPriceVariable customsDuty; + + @OneToOne(fetch = FetchType.LAZY) + TetsimPriceVariable elasticityOfDemandPrice; + + @OneToOne(fetch = FetchType.LAZY) + TetsimPriceVariable elasticityOfDemandCrossPrice; + + @OneToOne(fetch = FetchType.LAZY) + TetsimPriceVariable changeInIllicitNot; + + @OneToOne(fetch = FetchType.LAZY) + TetsimPriceVariable overShifting; + + @OneToOne(fetch = FetchType.LAZY) + TetsimPriceVariable underShifting; + + public BigDecimal getCigaretteConsumption() { + return cigaretteConsumption; + } + + public void setCigaretteConsumption(final BigDecimal cigaretteConsumption) { + this.cigaretteConsumption = cigaretteConsumption; + } + + public BigDecimal getVatRate() { + return vatRate; + } + + public void setVatRate(final BigDecimal vatRate) { + this.vatRate = vatRate; + } + + public BigDecimal getCigaretteDeclaredCustomValue() { + return cigaretteDeclaredCustomValue; + } + + public void setCigaretteDeclaredCustomValue(final BigDecimal cigaretteDeclaredCustomValue) { + this.cigaretteDeclaredCustomValue = cigaretteDeclaredCustomValue; + } + + public BigDecimal getAdultPopulation() { + return adultPopulation; + } + + public void setAdultPopulation(final BigDecimal adultPopulation) { + this.adultPopulation = adultPopulation; + } + + public BigDecimal getSmokingPrevalence() { + return smokingPrevalence; + } + + public void setSmokingPrevalence(final BigDecimal smokingPrevalence) { + this.smokingPrevalence = smokingPrevalence; + } + + public TetsimPriceVariable getRetailPrice() { + return retailPrice; + } + + public void setRetailPrice(final TetsimPriceVariable retailPrice) { + this.retailPrice = retailPrice; + } + + public TetsimPriceVariable getMarketShare() { + return marketShare; + } + + public void setMarketShare(final TetsimPriceVariable marketShare) { + this.marketShare = marketShare; + } + + public TetsimPriceVariable getCIF() { + return CIF; + } + + public void setCIF(final TetsimPriceVariable CIF) { + this.CIF = CIF; + } + + public TetsimPriceVariable getTobaccoLevy() { + return tobaccoLevy; + } + + public void setTobaccoLevy(final TetsimPriceVariable tobaccoLevy) { + this.tobaccoLevy = tobaccoLevy; + } + + public TetsimPriceVariable getExciseTax() { + return exciseTax; + } + + public void setExciseTax(final TetsimPriceVariable exciseTax) { + this.exciseTax = exciseTax; + } + + public TetsimPriceVariable getCustomsDuty() { + return customsDuty; + } + + public void setCustomsDuty(final TetsimPriceVariable customsDuty) { + this.customsDuty = customsDuty; + } + + public TetsimPriceVariable getElasticityOfDemandPrice() { + return elasticityOfDemandPrice; + } + + public void setElasticityOfDemandPrice(final TetsimPriceVariable elasticityOfDemandPrice) { + this.elasticityOfDemandPrice = elasticityOfDemandPrice; + } + + public TetsimPriceVariable getElasticityOfDemandCrossPrice() { + return elasticityOfDemandCrossPrice; + } + + public void setElasticityOfDemandCrossPrice(final TetsimPriceVariable elasticityOfDemandCrossPrice) { + this.elasticityOfDemandCrossPrice = elasticityOfDemandCrossPrice; + } + + public TetsimPriceVariable getChangeInIllicitNot() { + return changeInIllicitNot; + } + + public void setChangeInIllicitNot(final TetsimPriceVariable changeInIllicitNot) { + this.changeInIllicitNot = changeInIllicitNot; + } + + public TetsimPriceVariable getOverShifting() { + return overShifting; + } + + public void setOverShifting(final TetsimPriceVariable overShifting) { + this.overShifting = overShifting; + } + + public TetsimPriceVariable getUnderShifting() { + return underShifting; + } + + public void setUnderShifting(final TetsimPriceVariable underShifting) { + this.underShifting = underShifting; + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimPriceVariable.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimPriceVariable.java new file mode 100644 index 00000000..1db06d52 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimPriceVariable.java @@ -0,0 +1,39 @@ +package org.devgateway.toolkit.persistence.dao.data; + +import org.devgateway.toolkit.persistence.dao.AbstractAuditableEntity; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; +import org.hibernate.envers.Audited; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import java.util.Set; + +@Entity +@Audited +@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) +public class TetsimPriceVariable extends AbstractAuditableEntity { + + @ManyToOne + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) + private TetsimDataset dataset; + + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) + private Set values; + + @Override + public AbstractAuditableEntity getParent() { + return dataset; + } + + public Set getValues() { + return values; + } + + public void setValues(final Set values) { + this.values = values; + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java new file mode 100644 index 00000000..c9c02993 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java @@ -0,0 +1,48 @@ +package org.devgateway.toolkit.persistence.dao.data; + +import org.devgateway.toolkit.persistence.dao.AbstractAuditableEntity; +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; +import org.hibernate.envers.Audited; + +import javax.persistence.Entity; +import javax.persistence.ManyToOne; +import java.math.BigDecimal; + +@Entity +@Audited +@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) +public class TetsimTobaccoProductValue extends AbstractAuditableEntity { + + @ManyToOne + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) + private TetsimPriceVariable priceVariable; + + @ManyToOne + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) + private TobaccoProduct product; + + private BigDecimal value; + + public TobaccoProduct getProduct() { + return product; + } + + public void setProduct(final TobaccoProduct product) { + this.product = product; + } + + public BigDecimal getValue() { + return value; + } + + public void setValue(final BigDecimal value) { + this.value = value; + } + + @Override + public AbstractAuditableEntity getParent() { + return priceVariable; + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java new file mode 100644 index 00000000..477c9118 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java @@ -0,0 +1,10 @@ +package org.devgateway.toolkit.persistence.repository.data; + +import org.devgateway.toolkit.persistence.dao.data.Dataset; +import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; +import org.springframework.data.repository.NoRepositoryBean; + +@NoRepositoryBean +public interface DatasetRepository extends BaseJpaRepository { + +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java new file mode 100644 index 00000000..6a709dec --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java @@ -0,0 +1,10 @@ +package org.devgateway.toolkit.persistence.repository.data; + +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; + +import javax.transaction.Transactional; + +@Transactional +public interface TetsimDatasetRepository extends DatasetRepository { + +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java new file mode 100644 index 00000000..23f1b0f4 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java @@ -0,0 +1,7 @@ +package org.devgateway.toolkit.persistence.service.data; + +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.service.BaseJpaService; + +public interface TetsimDatasetService extends BaseJpaService { +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java new file mode 100644 index 00000000..87bed7e9 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java @@ -0,0 +1,30 @@ +package org.devgateway.toolkit.persistence.service.data; + +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.repository.data.TetsimDatasetRepository; +import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; +import org.devgateway.toolkit.persistence.service.BaseJpaServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheConfig; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@CacheConfig(cacheNames = "servicesCache") +@Transactional(readOnly = true) +public class TetsimDatasetServiceImpl extends BaseJpaServiceImpl implements TetsimDatasetService { + + @Autowired + private TetsimDatasetRepository tetsimDatasetRepository; + + @Override + public TetsimDataset newInstance() { + return new TetsimDataset(); + } + + @Override + protected BaseJpaRepository repository() { + return tetsimDatasetRepository; + } + +} From 2a4d11ef3fcba2a895e8a05b4d0b5e77d015e22c Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 9 Dec 2021 14:33:48 +0200 Subject: [PATCH 009/137] TOBACCO-791: Add TETSIM list page --- .../toolkit/forms/wicket/page/BasePage.java | 3 +- .../edit/category/EditTobaccoProductPage.java | 2 +- .../edit/dataset/EditTetsimDatasetPage.html | 14 +++ .../edit/dataset/EditTetsimDatasetPage.java | 47 ++++++++++ .../dataset/EditTetsimDatasetPage.properties | 3 + .../lists/dataset/ListTetsimDatasetPage.java | 86 +++++++++++++++++++ .../dataset/ListTetsimDatasetPage.properties | 6 ++ .../toolkit/persistence/dao/data/Dataset.java | 44 +++++----- .../persistence/dao/data/DatasetStatus.java | 19 ++++ .../persistence/dao/data/TetsimDataset.java | 26 ++++++ 10 files changed, 228 insertions(+), 22 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DatasetStatus.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 8dfc6ab5..53f53df1 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -54,6 +54,7 @@ import org.devgateway.toolkit.forms.security.SecurityUtil; import org.devgateway.toolkit.forms.wicket.page.lists.ListGroupPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListTestFormPage; +import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListTobaccoProductPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListUserPage; import org.devgateway.toolkit.forms.wicket.page.user.EditUserPage; @@ -308,7 +309,7 @@ protected NavbarDropDownButton newDatasetsMenu() { @Override protected List newSubMenuButtons(final String arg0) { final List list = new ArrayList<>(); - list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, + list.add(new MenuBookmarkablePageLink(ListTetsimDatasetPage.class, null, new StringResourceModel("navbar.tetsim", this, null)) .setIconType(FontAwesome5IconType.percent_s)); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java index f246ba84..6c2d011a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java @@ -25,7 +25,7 @@ import org.wicketstuff.annotation.mount.MountPath; /** - * @author mpostelnicu + * @author vchihai */ @MountPath(value = "/editTobaccoProduct") public class EditTobaccoProductPage extends AbstractEditPage { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html new file mode 100644 index 00000000..cbc90bc5 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html @@ -0,0 +1,14 @@ + + + + + Edit TETSIM Datasets + + + +
+
+
+
+ + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java new file mode 100644 index 00000000..267a38bc --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -0,0 +1,47 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.dataset; + +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.util.string.StringValue; +import org.devgateway.toolkit.forms.WebConstants; +import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; +import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; +import org.devgateway.toolkit.persistence.dao.data.DatasetStatus; +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; +import org.wicketstuff.annotation.mount.MountPath; + +/** + * @author vchihai + */ +@MountPath(value = "/editTetsimDataset") +public class EditTetsimDatasetPage extends AbstractEditPage { + + private static final long serialVersionUID = -8460878260874111506L; + + @SpringBean + protected TetsimDatasetService tetsimDatasetService; + + public EditTetsimDatasetPage(final PageParameters parameters) { + super(parameters); + this.jpaService = tetsimDatasetService; + this.listPageClass = ListTetsimDatasetPage.class; + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + final TextFieldBootstrapFormComponent year = new TextFieldBootstrapFormComponent<>("year"); + year.required(); + year.integer(); + editForm.add(year); + + final StringValue id = getPageParameters().get(WebConstants.PARAM_ID); + + if (id.isEmpty()) { + editForm.getModelObject().setStatus(DatasetStatus.DRAFT); + } + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties new file mode 100644 index 00000000..78cbc216 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties @@ -0,0 +1,3 @@ +page.title.add=Add TETSIM Dataset +page.title.edit=Edit TETSIM Dataset +year.label=Year \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java new file mode 100644 index 00000000..3126cff4 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java @@ -0,0 +1,86 @@ +/******************************************************************************* + * Copyright (c) 2015 Development Gateway, Inc and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the MIT License (MIT) + * which accompanies this distribution, and is available at + * https://opensource.org/licenses/MIT + * + * Contributors: + * Development Gateway - initial API and implementation + *******************************************************************************/ +package org.devgateway.toolkit.forms.wicket.page.lists.dataset; + +import org.apache.wicket.Component; +import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.wicket.components.table.filter.JpaFilterState; +import org.devgateway.toolkit.forms.wicket.page.edit.dataset.EditTetsimDatasetPage; +import org.devgateway.toolkit.forms.wicket.page.lists.AbstractListPage; +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; +import org.wicketstuff.annotation.mount.MountPath; + +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) +@MountPath(value = "/listTetsimDataset") +public class ListTetsimDatasetPage extends AbstractListPage { + private static final long serialVersionUID = -324298525712620234L; + + @SpringBean + private TetsimDatasetService tetsimDatasetService; + + public ListTetsimDatasetPage(final PageParameters pageParameters) { + super(pageParameters); + this.jpaService = tetsimDatasetService; + this.editPageClass = EditTetsimDatasetPage.class; + + columns.clear(); + + columns.add(new PropertyColumn<>(new StringResourceModel("year"), "year", "year")); + columns.add(new PropertyColumn<>(new StringResourceModel("lastModifiedBy"), "lastModifiedBy", + "lastModifiedBy.get")); + columns.add(new PropertyColumn(new StringResourceModel("lastModifiedDate"), + "lastModifiedDate", + "lastModifiedDate.get") { + + @Override + public IModel getDataModel(final IModel rowModel) { + IModel model = super.getDataModel(rowModel); + ZonedDateTime modifiedDate = (ZonedDateTime) model.getObject(); + return Model.of(modifiedDate.format(DateTimeFormatter.ofPattern("dd/MM/yy"))); + } + }); + columns.add(new PropertyColumn<>(new StringResourceModel("status"), "status", "status")); + + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + dataProvider.setSort("year", SortOrder.ASCENDING); + + excelForm.setVisibilityAllowed(false); + } + + @Override + protected Component getRevisionsLink(final TetsimDataset entity) { + return new WebMarkupContainer("revisions").setVisibilityAllowed(false); + } + + @Override + public JpaFilterState newFilterState() { + return new JpaFilterState<>(); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties new file mode 100644 index 00000000..56abb78d --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties @@ -0,0 +1,6 @@ +page.title=South Africa TETSIM +year=Year +lastModifiedBy=Editor +lastModifiedDate=Latest Modification +status=Status +actionsColumn=Action \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java index 0c9cdff1..1f397edf 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java @@ -1,45 +1,49 @@ package org.devgateway.toolkit.persistence.dao.data; import org.devgateway.toolkit.persistence.dao.AbstractAuditableEntity; -import org.devgateway.toolkit.persistence.dao.Labelable; import org.devgateway.toolkit.persistence.dao.Person; +import org.hibernate.envers.Audited; import javax.persistence.Column; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.ManyToOne; import javax.persistence.MappedSuperclass; +import javax.validation.constraints.NotNull; import java.io.Serializable; @MappedSuperclass -public abstract class Dataset extends AbstractAuditableEntity implements Serializable, Labelable { - - private String label; - - @Column(length = 1024) - private String description; +public abstract class Dataset extends AbstractAuditableEntity implements Serializable { + @NotNull + @Audited private Integer year; - private boolean approved; - - @ManyToOne(fetch = FetchType.EAGER) - private Person uploadedBy; - - @ManyToOne(fetch = FetchType.EAGER) - private Person approvedBy; + @NotNull + @Audited + @Enumerated(EnumType.STRING) + private DatasetStatus status; @Override public AbstractAuditableEntity getParent() { return null; } - @Override - public void setLabel(final String label) { - this.label = label; + public Integer getYear() { + return year; } - @Override - public String getLabel() { - return label; + public void setYear(final Integer year) { + this.year = year; } + + public DatasetStatus getStatus() { + return status; + } + + public void setStatus(final DatasetStatus status) { + this.status = status; + } + } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DatasetStatus.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DatasetStatus.java new file mode 100644 index 00000000..ee9e5740 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DatasetStatus.java @@ -0,0 +1,19 @@ +package org.devgateway.toolkit.persistence.dao.data; + +public enum DatasetStatus { + + DRAFT("Draft"), + SAVED("Saved"), + PUBLISHED("Published"), + UNPUBLISHED("Unpublished"); + + private String label; + + DatasetStatus(final String label) { + this.label = label; + } + + public String getLabel() { + return label; + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java index f3d14c93..0f283b37 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java @@ -14,48 +14,74 @@ @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class TetsimDataset extends Dataset { + @Audited BigDecimal cigaretteConsumption; + @Audited BigDecimal vatRate; + @Audited BigDecimal cigaretteDeclaredCustomValue; + @Audited BigDecimal adultPopulation; + @Audited BigDecimal smokingPrevalence; @OneToOne(fetch = FetchType.LAZY) + @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) TetsimPriceVariable retailPrice; @OneToOne(fetch = FetchType.LAZY) + @Audited + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) TetsimPriceVariable marketShare; @OneToOne(fetch = FetchType.LAZY) + @Audited + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) TetsimPriceVariable CIF; @OneToOne(fetch = FetchType.LAZY) + @Audited + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) TetsimPriceVariable tobaccoLevy; @OneToOne(fetch = FetchType.LAZY) + @Audited + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) TetsimPriceVariable exciseTax; @OneToOne(fetch = FetchType.LAZY) + @Audited + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) TetsimPriceVariable customsDuty; @OneToOne(fetch = FetchType.LAZY) + @Audited + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) TetsimPriceVariable elasticityOfDemandPrice; @OneToOne(fetch = FetchType.LAZY) + @Audited + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) TetsimPriceVariable elasticityOfDemandCrossPrice; @OneToOne(fetch = FetchType.LAZY) + @Audited + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) TetsimPriceVariable changeInIllicitNot; @OneToOne(fetch = FetchType.LAZY) + @Audited + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) TetsimPriceVariable overShifting; @OneToOne(fetch = FetchType.LAZY) + @Audited + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) TetsimPriceVariable underShifting; public BigDecimal getCigaretteConsumption() { From bf27518a1a83c7ffaca9895f22676d280d9ab857 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 10 Dec 2021 17:29:32 +0200 Subject: [PATCH 010/137] TOBACCO-792: Add homepages for datasets, categories --- .../forms/wicket/FormsWebApplication.java | 6 +++ .../wicket/components/BigLinkDefinition.java | 40 ++++++++++++++++ .../wicket/components/BigLinksPanel.html | 12 +++++ .../wicket/components/BigLinksPanel.java | 34 ++++++++++++++ .../components/buttons/HomepageButton.html | 15 ++++++ .../components/buttons/HomepageButton.java | 38 +++++++++++++++ .../toolkit/forms/wicket/page/BasePage.java | 16 +++---- .../forms/wicket/page/CategoriesHomepage.html | 12 +++++ .../forms/wicket/page/CategoriesHomepage.java | 33 +++++++++++++ .../wicket/page/CategoriesHomepage.properties | 4 ++ .../forms/wicket/page/DatasetsHomepage.html | 12 +++++ .../forms/wicket/page/DatasetsHomepage.java | 47 +++++++++++++++++++ .../page/EditAdminSettingsPage.properties | 1 + .../toolkit/forms/wicket/page/Homepage.html | 8 ++-- .../toolkit/forms/wicket/page/Homepage.java | 30 ++++++------ .../forms/wicket/page/Homepage.properties | 24 +++++----- .../forms/wicket/styles/BaseStyles.css | 42 +++++++++++++++++ 17 files changed, 334 insertions(+), 40 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinkDefinition.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/HomepageButton.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/HomepageButton.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java index d79b0450..ce2515d9 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java @@ -17,11 +17,14 @@ import de.agilecoders.wicket.core.request.resource.caching.version.Adler32ResourceVersion; import de.agilecoders.wicket.core.settings.BootstrapSettings; import de.agilecoders.wicket.core.settings.IBootstrapSettings; +import de.agilecoders.wicket.core.settings.ThemeProvider; import de.agilecoders.wicket.extensions.javascript.GoogleClosureJavaScriptCompressor; import de.agilecoders.wicket.extensions.javascript.YuiCssCompressor; import de.agilecoders.wicket.extensions.markup.html.bootstrap.editor.SummernoteConfig; import de.agilecoders.wicket.extensions.markup.html.bootstrap.editor.SummernoteStoredImageResourceReference; import de.agilecoders.wicket.less.BootstrapLess; +import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchTheme; +import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchThemeProvider; import de.agilecoders.wicket.webjars.WicketWebjars; import nl.dries.wicket.hibernate.dozer.DozerRequestCycleListener; import nl.dries.wicket.hibernate.dozer.SessionFinderHolder; @@ -153,6 +156,9 @@ private void configureBootstrap() { final IBootstrapSettings settings = new BootstrapSettings(); settings.useCdnResources(false); + final ThemeProvider themeProvider = new BootswatchThemeProvider(BootswatchTheme.Paper); + settings.setThemeProvider(themeProvider); + // use the default bootstrap theme Bootstrap.install(this, settings); BootstrapLess.install(this); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinkDefinition.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinkDefinition.java new file mode 100644 index 00000000..63fea463 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinkDefinition.java @@ -0,0 +1,40 @@ +package org.devgateway.toolkit.forms.wicket.components; + +import de.agilecoders.wicket.core.markup.html.bootstrap.image.IconType; +import org.apache.wicket.Page; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.ResourceModel; + +import java.io.Serializable; + +/** + * @author Octavian Ciubotaru + */ +public class BigLinkDefinition implements Serializable { + + private final String id; + private final Class pageClass; + private final IconType iconType; + + public BigLinkDefinition(String id, Class pageClass, IconType iconType) { + this.id = id; + this.pageClass = pageClass; + this.iconType = iconType; + } + + public IModel getLabelModel() { + return new ResourceModel(id + ".label"); + } + + public IModel getDescModel() { + return new ResourceModel(id + ".desc"); + } + + public Class getPageClass() { + return pageClass; + } + + public IconType getIconType() { + return iconType; + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.html new file mode 100644 index 00000000..a124266a --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.html @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.java new file mode 100644 index 00000000..9ce32297 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.java @@ -0,0 +1,34 @@ +package org.devgateway.toolkit.forms.wicket.components; + +import org.apache.wicket.behavior.AttributeAppender; +import org.apache.wicket.markup.html.list.ListItem; +import org.apache.wicket.markup.html.list.ListView; +import org.apache.wicket.markup.html.panel.GenericPanel; +import org.apache.wicket.model.IModel; +import org.devgateway.toolkit.forms.wicket.components.buttons.HomepageButton; + +import java.util.List; + +/** + * @author Octavian Ciubotaru + */ +public class BigLinksPanel extends GenericPanel> { + + public BigLinksPanel(String id, IModel> model) { + super(id, model); + + int size = model.getObject().size(); + int colSpan = (size == 0 || size > 3) ? 3 : 12 / size; + + add(new ListView("buttons", model) { + + @Override + protected void populateItem(ListItem item) { + BigLinkDefinition def = item.getModelObject(); + item.add(new AttributeAppender("class", "col-md-" + colSpan, " ")); + item.add(new HomepageButton<>("button", + def.getPageClass(), def.getLabelModel(), def.getDescModel(), def.getIconType())); + } + }); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/HomepageButton.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/HomepageButton.html new file mode 100644 index 00000000..3e106122 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/HomepageButton.html @@ -0,0 +1,15 @@ + + + HomePageButton + + + + +

+ + +

+ + + + \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/HomepageButton.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/HomepageButton.java new file mode 100644 index 00000000..33228ef5 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/HomepageButton.java @@ -0,0 +1,38 @@ +package org.devgateway.toolkit.forms.wicket.components.buttons; + +import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapBookmarkablePageLink; +import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; +import de.agilecoders.wicket.core.markup.html.bootstrap.image.IconType; +import org.apache.wicket.Component; +import org.apache.wicket.Page; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.ResourceModel; + +public class HomepageButton extends BootstrapBookmarkablePageLink { + + public

HomepageButton(final String componentId, final Class

pageClass, + final IconType iconType) { + this(componentId, pageClass, null, null, iconType); + } + + public

HomepageButton(String componentId, Class

pageClass, IModel labelModel, + IModel descriptionModel, IconType iconType) { + super(componentId, pageClass, Buttons.Type.Default); + + setLabel(labelModel == null + ? new ResourceModel(componentId + ".label") + : labelModel); + + add(new Label("description", descriptionModel == null + ? new ResourceModel(componentId + ".desc") + : descriptionModel)); + + setIconType(iconType); + setSize(Buttons.Size.Large); + } + + protected Component newLabel(final String markupId) { + return super.newLabel(markupId).setRenderBodyOnly(false); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 53f53df1..1c42da37 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -289,7 +289,7 @@ JavamelodyPage.class, new StringResourceModel("navbar.javamelody", list.add(new MenuBookmarkablePageLink(EditAdminSettingsPage.class, new StringResourceModel("navbar.adminSettings", BasePage.this, null)) - .setIconType(FontAwesome5IconType.briefcase_s)); + .setIconType(FontAwesome5IconType.cogs_s)); return list; } @@ -302,7 +302,7 @@ JavamelodyPage.class, new StringResourceModel("navbar.javamelody", } protected NavbarDropDownButton newDatasetsMenu() { - NavbarDropDownButton categoriesMenu = new NavbarDropDownButton( + NavbarDropDownButton dataSetsMenu = new NavbarDropDownButton( new StringResourceModel("navbar.datasets", this, null)) { private static final long serialVersionUID = 1L; @@ -311,7 +311,7 @@ protected List newSubMenuButtons(final String arg0) { final List list = new ArrayList<>(); list.add(new MenuBookmarkablePageLink(ListTetsimDatasetPage.class, null, new StringResourceModel("navbar.tetsim", this, null)) - .setIconType(FontAwesome5IconType.percent_s)); + .setIconType(FontAwesome5IconType.percentage_s)); list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, new StringResourceModel("navbar.prevalence", this, null)) @@ -329,10 +329,10 @@ protected List newSubMenuButtons(final String arg0) { } }; - categoriesMenu.setIconType(FontAwesome5IconType.table_s); - MetaDataRoleAuthorizationStrategy.authorize(categoriesMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); + dataSetsMenu.setIconType(FontAwesome5IconType.table_s); + MetaDataRoleAuthorizationStrategy.authorize(dataSetsMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); - return categoriesMenu; + return dataSetsMenu; } protected NavbarDropDownButton newCategoriesMenu() { @@ -345,12 +345,12 @@ protected List newSubMenuButtons(final String arg0) { final List list = new ArrayList<>(); list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, new StringResourceModel("navbar.tobaccoproducts", this, null)) - .setIconType(FontAwesome5IconType.leaf_s)); + .setIconType(FontAwesome5IconType.smoking_s)); return list; } }; - categoriesMenu.setIconType(FontAwesome5IconType.list_ul_s); + categoriesMenu.setIconType(FontAwesome5IconType.list_alt_r); MetaDataRoleAuthorizationStrategy.authorize(categoriesMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); return categoriesMenu; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.html new file mode 100644 index 00000000..eaa6cdfb --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.html @@ -0,0 +1,12 @@ + + + + + Categories Homepage + + + +

+ + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.java new file mode 100644 index 00000000..848be210 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.java @@ -0,0 +1,33 @@ +package org.devgateway.toolkit.forms.wicket.page; + +import com.google.common.collect.ImmutableList; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; +import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; +import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; +import org.devgateway.toolkit.forms.wicket.page.lists.ListTobaccoProductPage; +import org.wicketstuff.annotation.mount.MountPath; + +import java.util.List; + +/** + * @author Viorel Chihai + */ +@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) +@MountPath +public class CategoriesHomepage extends BasePage { + + private static final List LINKS = new ImmutableList.Builder() + .add(new BigLinkDefinition("tobaccoProducts", ListTobaccoProductPage.class, + FontAwesome5IconType.smoking_s)) + .build(); + + public CategoriesHomepage(final PageParameters parameters) { + super(parameters); + + add(new BigLinksPanel("links", Model.ofList(LINKS))); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties new file mode 100644 index 00000000..7f6abb64 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties @@ -0,0 +1,4 @@ +page.title=South Africa categories + +tobaccoProducts.label=Tobacco Products +tobaccoProducts.desc=Manage the tobacco products used in the system \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.html new file mode 100644 index 00000000..b0e96a79 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.html @@ -0,0 +1,12 @@ + + + + + Datasets + + + +
+
+ + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.java new file mode 100644 index 00000000..a223c780 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) 2015 Development Gateway, Inc and others. + *

+ * All rights reserved. This program and the accompanying materials + * are made available under the terms of the MIT License (MIT) + * which accompanies this distribution, and is available at + * https://opensource.org/licenses/MIT + *

+ * Contributors: + * Development Gateway - initial API and implementation + */ +/** + * + */ +package org.devgateway.toolkit.forms.wicket.page; + +import com.google.common.collect.ImmutableList; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; +import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; +import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; +import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; +import org.wicketstuff.annotation.mount.MountPath; + +import java.util.List; + +/** + * @author Viorel Chihai + */ +@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) +@MountPath +public class DatasetsHomepage extends BasePage { + + private static final List LINKS = new ImmutableList.Builder() + .add(new BigLinkDefinition("tetsimDataset", ListTetsimDatasetPage.class, + FontAwesome5IconType.percentage_s)) + .build(); + + public DatasetsHomepage(final PageParameters parameters) { + super(parameters); + + add(new BigLinksPanel("links", Model.ofList(LINKS))); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties index e17132db..d38f9f8c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties @@ -1,4 +1,5 @@ page.title=Admin settings +page.title.add=Admin settings systemTitle=System Settings rebootServer.label=Enable server reboot warning autosaveTime.label=Autosave Time (minutes) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.html index 8bce0124..d8ce2dee 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.html @@ -6,11 +6,9 @@ -

-
-

-
-
+ +
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java index 10eebf3e..8f95c00c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java @@ -1,22 +1,15 @@ -/** - * Copyright (c) 2015 Development Gateway, Inc and others. - *

- * All rights reserved. This program and the accompanying materials - * are made available under the terms of the MIT License (MIT) - * which accompanies this distribution, and is available at - * https://opensource.org/licenses/MIT - *

- * Contributors: - * Development Gateway - initial API and implementation - */ -/** - * - */ package org.devgateway.toolkit.forms.wicket.page; +import com.google.common.collect.ImmutableList; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; +import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; + +import java.util.List; /** * @author mpostelnicu @@ -24,10 +17,19 @@ */ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) public class Homepage extends BasePage { + + private static final List LINKS = new ImmutableList.Builder() + .add(new BigLinkDefinition("datasets", DatasetsHomepage.class, FontAwesome5IconType.table_s)) + .add(new BigLinkDefinition("categories", CategoriesHomepage.class, FontAwesome5IconType.list_alt_r)) + .add(new BigLinkDefinition("settings", EditAdminSettingsPage.class, FontAwesome5IconType.cogs_s)) + .build(); + /** * @param parameters */ public Homepage(final PageParameters parameters) { super(parameters); + + add(new BigLinksPanel("links", Model.ofList(LINKS))); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties index 31158b08..784b7bee 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties @@ -1,13 +1,11 @@ -############################################################################### -# Copyright (c) 2015 Development Gateway, Inc and others. -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the MIT License (MIT) -# which accompanies this distribution, and is available at -# https://opensource.org/licenses/MIT -# -# Contributors: -# Development Gateway - initial API and implementation -############################################################################### -page.title=Home Page -welcome=Welcome to TCDI Data Entry Admin +page.title=South Africa data admin module +welcome=South Africa data admin module + +datasets.label=Datasets +datasets.desc=Upload, edit, revert to draft and validate Datasets + +categories.label=Categories +categories.desc=Edit categories in the system like Tobacco Products + +settings.label=Settings +settings.desc=Manage the general settings of the system \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css index 90a4a311..378beced 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css @@ -226,3 +226,45 @@ hr.edit-separator { /* -------------------------------------------------- */ + +.bigLinkContainer .bigLinkItem { + padding: 15px; +} + +button .btn-home-desc { + padding-top: 0; + width: 140px; + font-size: 12px; + text-transform: none; + white-space: normal; +} + +button .btn-home-label { + white-space: normal; + line-height: 20px; +} + +.btn-homepage { + width: 250px; + height: 250px; + margin: 0 auto; + padding: 10px; + display: inline-block; + line-height: 15px; + text-align: center; +} + +div.parentElement{text-align: center;} + +button .btn-home-desc { + padding-top: 0; + width: 140px; + font-size: 12px; + text-transform: none; + white-space: normal; +} + +button .btn-home-label { + white-space: normal; + line-height: 20px; +} \ No newline at end of file From 5f1676d8022b5a31a3e727b61babf954a0b3b5b1 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 15 Dec 2021 12:31:39 +0200 Subject: [PATCH 011/137] TOBACCO-798: Add base line numbers to tetsim dataset homepage --- .../PhoneNumberValidator.properties | 1 + .../PositiveBigDecimalValidator.java | 36 ++++++++ .../PositiveBigDecimalValidator.properties | 2 + .../forms/wicket/FormsWebApplication.java | 5 +- .../wicket/page/DatasetsHomepage.properties | 4 + .../edit/dataset/EditTetsimDatasetPage.html | 21 ++++- .../edit/dataset/EditTetsimDatasetPage.java | 87 +++++++++++++++++-- .../dataset/EditTetsimDatasetPage.properties | 17 +++- .../TetsimBaselineDecimalVariable.java | 22 +++++ .../edit/dataset/TetsimBaselineVariable.html | 16 ++++ .../edit/dataset/TetsimBaselineVariable.java | 47 ++++++++++ .../dataset/TetsimBaselineVariable.properties | 1 + 12 files changed, 247 insertions(+), 12 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/validators/PositiveBigDecimalValidator.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/validators/PositiveBigDecimalValidator.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineDecimalVariable.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.properties diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/validators/PhoneNumberValidator.properties b/forms/src/main/java/org/devgateway/toolkit/forms/validators/PhoneNumberValidator.properties index 2806775d..36f13fb4 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/validators/PhoneNumberValidator.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/validators/PhoneNumberValidator.properties @@ -10,3 +10,4 @@ # Development Gateway - initial API and implementation ############################################################################### pattern=Invalid telephone number. The maximum length is 50 characters. The telephone number should contain only numbers 0-9, whitespace or the characters ()-+. +must be greater than 1 \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/validators/PositiveBigDecimalValidator.java b/forms/src/main/java/org/devgateway/toolkit/forms/validators/PositiveBigDecimalValidator.java new file mode 100644 index 00000000..2a4b676f --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/validators/PositiveBigDecimalValidator.java @@ -0,0 +1,36 @@ +package org.devgateway.toolkit.forms.validators; + +import org.apache.wicket.validation.IValidatable; +import org.apache.wicket.validation.IValidator; +import org.apache.wicket.validation.ValidationError; + +import java.math.BigDecimal; + +public class PositiveBigDecimalValidator implements IValidator { + + private boolean includeZero; + + public PositiveBigDecimalValidator() { + this(false); + } + + public PositiveBigDecimalValidator(boolean includeZero) { + this.includeZero = includeZero; + } + + @Override + public void validate(final IValidatable validatable) { + BigDecimal value = validatable.getValue(); + if (includeZero) { + if (value.compareTo(BigDecimal.ZERO) < 0) { + ValidationError error = new ValidationError(this); + error.addKey("positive"); + validatable.error(error); + } + } else if (value.compareTo(BigDecimal.ZERO) <= 0) { + ValidationError error = new ValidationError(this); + error.addKey("nonNegative"); + validatable.error(error); + } + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/validators/PositiveBigDecimalValidator.properties b/forms/src/main/java/org/devgateway/toolkit/forms/validators/PositiveBigDecimalValidator.properties new file mode 100644 index 00000000..c6600c97 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/validators/PositiveBigDecimalValidator.properties @@ -0,0 +1,2 @@ +positive=The value must be greater than 0 +nonNegative=The value must be greater than or equal to 0 \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java index ce2515d9..52e41489 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java @@ -113,7 +113,6 @@ public static void main(final String[] args) { @Override protected IConverterLocator newConverterLocator() { ConverterLocator locator = (ConverterLocator) super.newConverterLocator(); - locator.set(BigDecimal.class, new NonNumericFilteredBigDecimalConverter(defaultDecimalFormatter)); locator.set(Double.class, new FormattedDoubleConverter(defaultDecimalFormatter)); locator.set(LocalDate.class, new LocalDateFormatter()); locator.set(ZonedDateTime.class, new ZonedDateTimeFormatter()); @@ -156,8 +155,8 @@ private void configureBootstrap() { final IBootstrapSettings settings = new BootstrapSettings(); settings.useCdnResources(false); - final ThemeProvider themeProvider = new BootswatchThemeProvider(BootswatchTheme.Paper); - settings.setThemeProvider(themeProvider); +// final ThemeProvider themeProvider = new BootswatchThemeProvider(BootswatchTheme.Paper); +// settings.setThemeProvider(themeProvider); // use the default bootstrap theme Bootstrap.install(this, settings); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties new file mode 100644 index 00000000..a0721f83 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties @@ -0,0 +1,4 @@ +page.title=South Africa datasets + +tetsimDataset.label=TETSIM +tetsimDataset.desc=Manage the TETSIM dataset \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html index cbc90bc5..fbb292da 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html @@ -7,7 +7,26 @@

-
+
+
+
+
+

Base-line Numbers:

+
+
+ + + + + + + + + + + +
Base-line NumbersUnitValues
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index 267a38bc..111fbe27 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -1,9 +1,12 @@ package org.devgateway.toolkit.forms.wicket.page.edit.dataset; +import org.apache.wicket.Component; +import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.util.string.StringValue; -import org.devgateway.toolkit.forms.WebConstants; +import org.devgateway.toolkit.forms.validators.PositiveBigDecimalValidator; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; @@ -33,15 +36,85 @@ public EditTetsimDatasetPage(final PageParameters parameters) { protected void onInitialize() { super.onInitialize(); + if (editForm.getModelObject().isNew()) { + editForm.getModelObject().setStatus(DatasetStatus.DRAFT); + } + + editForm.add(getYear()); + editForm.add(getBaseLineNumbers()); + } + + private TextFieldBootstrapFormComponent getYear() { final TextFieldBootstrapFormComponent year = new TextFieldBootstrapFormComponent<>("year"); year.required(); year.integer(); - editForm.add(year); + return year; + } - final StringValue id = getPageParameters().get(WebConstants.PARAM_ID); + private Component getBaseLineNumbers() { + RepeatingView baseLineNumbers = new RepeatingView("baseLineNumbers"); + baseLineNumbers.add(getCigaretteConsumptionVariable(baseLineNumbers.newChildId())); + baseLineNumbers.add(getVatRateVariable(baseLineNumbers.newChildId())); + baseLineNumbers.add(getCigaretteDeclaredCustomValueVariable(baseLineNumbers.newChildId())); + baseLineNumbers.add(getAdultPopulationVariable(baseLineNumbers.newChildId())); + baseLineNumbers.add(getSmokingPrevalenceVariable(baseLineNumbers.newChildId())); - if (id.isEmpty()) { - editForm.getModelObject().setStatus(DatasetStatus.DRAFT); - } + return baseLineNumbers; } + + private Component getCigaretteConsumptionVariable(final String id) { + TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, + new StringResourceModel("cigaretteConsumption.label"), + new StringResourceModel("cigaretteConsumption.unit"), + new PropertyModel<>(editForm.getModel(), "cigaretteConsumption")); + + variable.getInputField().getField().add(new PositiveBigDecimalValidator()); + + return variable; + } + + private Component getVatRateVariable(final String id) { + TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, + new StringResourceModel("vatRate.label"), + new StringResourceModel("vatRate.unit"), + new PropertyModel<>(editForm.getModel(), "vatRate")); + + variable.getInputField().getField().add(new PositiveBigDecimalValidator()); + + return variable; + } + + private Component getCigaretteDeclaredCustomValueVariable(final String id) { + TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, + new StringResourceModel("cigaretteDeclaredCustomValue.label"), + new StringResourceModel("cigaretteDeclaredCustomValue.unit"), + new PropertyModel<>(editForm.getModel(), "cigaretteDeclaredCustomValue")); + variable.getInputField().getField().add(new PositiveBigDecimalValidator(true)); + + return variable; + } + + private Component getAdultPopulationVariable(final String id) { + TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, + new StringResourceModel("adultPopulation.label"), + new StringResourceModel("adultPopulation.unit"), + new PropertyModel<>(editForm.getModel(), "adultPopulation")); + + variable.getInputField().getField().add(new PositiveBigDecimalValidator()); + + return variable; + } + + private Component getSmokingPrevalenceVariable(final String id) { + TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, + new StringResourceModel("smokingPrevalence.label"), + new StringResourceModel("smokingPrevalence.unit"), + new PropertyModel<>(editForm.getModel(), "smokingPrevalence")); + + variable.getInputField().getField().add(new PositiveBigDecimalValidator()); + + return variable; + } + + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties index 78cbc216..c5566782 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties @@ -1,3 +1,18 @@ page.title.add=Add TETSIM Dataset page.title.edit=Edit TETSIM Dataset -year.label=Year \ No newline at end of file +year.label=Year + +cigaretteConsumption.label=Total cigarette consumption (including illicit cigarettes) +cigaretteConsumption.unit=Full number of packs + +vatRate.label=VAT rate +vatRate.unit=Percentage + +cigaretteDeclaredCustomValue.label=Declared customs value of imported cigarettes (FOB amount) +cigaretteDeclaredCustomValue.unit={0} per pack + +adultPopulation.label=Adult Population (15+) +adultPopulation.unit=Full number + +smokingPrevalence.label=Smoking prevalence +smokingPrevalence.unit=Percentage \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineDecimalVariable.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineDecimalVariable.java new file mode 100644 index 00000000..c83436e0 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineDecimalVariable.java @@ -0,0 +1,22 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.dataset; + +import org.apache.wicket.model.IModel; +import org.devgateway.toolkit.forms.wicket.components.form.GenericBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; + +public class TetsimBaselineDecimalVariable extends TetsimBaselineVariable { + + public TetsimBaselineDecimalVariable(final String id, final IModel labelModel, + final IModel unitModel, final IModel variableModel) { + super(id, labelModel, unitModel, variableModel); + } + + @Override + protected GenericBootstrapFormComponent createInputField() { + TextFieldBootstrapFormComponent field = new TextFieldBootstrapFormComponent<>("input", variableModel); + field.decimal(); + field.required(); + field.hideLabel(); + return field; + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.html new file mode 100644 index 00000000..6891b558 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.html @@ -0,0 +1,16 @@ + + + + + + + + + + + +
+ + + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.java new file mode 100644 index 00000000..d14b1132 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.java @@ -0,0 +1,47 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.dataset; + +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.devgateway.toolkit.forms.wicket.components.form.GenericBootstrapFormComponent; + +/** + * @author Viorel Chihai + */ +public abstract class TetsimBaselineVariable extends Panel { + + private final IModel labelModel; + + private final IModel unitModel; + + protected final IModel variableModel; + + protected GenericBootstrapFormComponent inputField; + + public TetsimBaselineVariable(final String id, final IModel labelModel, + final IModel unitModel, + final IModel variableModel) { + super(id); + this.labelModel = labelModel; + this.unitModel = unitModel; + this.variableModel = variableModel; + inputField = createInputField(); + } + + @Override + protected void onInitialize() { + super.onInitialize(); + add(new Label("label", labelModel)); + add(new Label("unit", unitModel)); + add(inputField); + } + + protected abstract GenericBootstrapFormComponent createInputField(); + + public GenericBootstrapFormComponent getInputField() { + return inputField; + } + +} + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.properties new file mode 100644 index 00000000..ef09e41b --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.properties @@ -0,0 +1 @@ +input.label=input \ No newline at end of file From 3cb36266bb3691a7d66ef5e3db6cee3fc80d6b7b Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 3 Jan 2022 13:10:54 +0200 Subject: [PATCH 012/137] TOBACCO-799: Add price analysis variables --- .../toolkit/forms/WebConstants.java | 2 + .../edit/dataset/EditTetsimDatasetPage.html | 21 +- .../edit/dataset/EditTetsimDatasetPage.java | 75 +---- .../dataset/EditTetsimDatasetPage.properties | 17 +- .../dataset/TetsimBaselineNumbersPanel.html | 25 ++ .../dataset/TetsimBaselineNumbersPanel.java | 95 ++++++ .../TetsimBaselineNumbersPanel.properties | 14 + .../dataset/TetsimPriceAnalysisPanel.html | 23 ++ .../dataset/TetsimPriceAnalysisPanel.java | 284 ++++++++++++++++++ .../TetsimPriceAnalysisPanel.properties | 27 ++ .../TetsimTobaccoProductsVariable.html | 14 + .../TetsimTobaccoProductsVariable.java | 123 ++++++++ .../TetsimTobaccoProductsVariable.properties | 1 + .../persistence/dao/data/TetsimDataset.java | 53 ++-- .../dao/data/TetsimPriceVariable.java | 20 +- .../dao/data/TetsimTobaccoProductValue.java | 8 + .../persistence/service/BaseJpaService.java | 2 + .../service/BaseJpaServiceImpl.java | 9 + .../category/TobaccoProductServiceImpl.java | 6 + 19 files changed, 695 insertions(+), 124 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.properties diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java index e2cae919..d14e3a1d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java @@ -54,6 +54,8 @@ public static final class StringValidators { StringValidator.maximumLength(DBConstants.MAX_DEFAULT_TEXT_AREA); } + public static final int MAXIMUM_PERCENTAGE = 100; + // add more languages here. It is pointless to make this dynamic because the // wicket i18n is in .properties files so we need // to change the src code anyway. diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html index fbb292da..310e030c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html @@ -10,23 +10,10 @@
-
-

Base-line Numbers:

-
-
- - - - - - - - - - - -
Base-line NumbersUnitValues
-
+ +
+
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index 111fbe27..1f759546 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -1,7 +1,9 @@ package org.devgateway.toolkit.forms.wicket.page.edit.dataset; import org.apache.wicket.Component; +import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -10,11 +12,16 @@ import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; import org.devgateway.toolkit.persistence.dao.data.DatasetStatus; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; +import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.wicketstuff.annotation.mount.MountPath; +import java.util.List; + /** * @author vchihai */ @@ -42,6 +49,7 @@ protected void onInitialize() { editForm.add(getYear()); editForm.add(getBaseLineNumbers()); + editForm.add(getPriceAnalysisNumbers()); } private TextFieldBootstrapFormComponent getYear() { @@ -51,70 +59,11 @@ private TextFieldBootstrapFormComponent getYear() { return year; } - private Component getBaseLineNumbers() { - RepeatingView baseLineNumbers = new RepeatingView("baseLineNumbers"); - baseLineNumbers.add(getCigaretteConsumptionVariable(baseLineNumbers.newChildId())); - baseLineNumbers.add(getVatRateVariable(baseLineNumbers.newChildId())); - baseLineNumbers.add(getCigaretteDeclaredCustomValueVariable(baseLineNumbers.newChildId())); - baseLineNumbers.add(getAdultPopulationVariable(baseLineNumbers.newChildId())); - baseLineNumbers.add(getSmokingPrevalenceVariable(baseLineNumbers.newChildId())); - - return baseLineNumbers; - } - - private Component getCigaretteConsumptionVariable(final String id) { - TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, - new StringResourceModel("cigaretteConsumption.label"), - new StringResourceModel("cigaretteConsumption.unit"), - new PropertyModel<>(editForm.getModel(), "cigaretteConsumption")); - - variable.getInputField().getField().add(new PositiveBigDecimalValidator()); - - return variable; + private TetsimBaselineNumbersPanel getBaseLineNumbers() { + return new TetsimBaselineNumbersPanel("baseLineNumbers", editForm.getModel()); } - private Component getVatRateVariable(final String id) { - TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, - new StringResourceModel("vatRate.label"), - new StringResourceModel("vatRate.unit"), - new PropertyModel<>(editForm.getModel(), "vatRate")); - - variable.getInputField().getField().add(new PositiveBigDecimalValidator()); - - return variable; - } - - private Component getCigaretteDeclaredCustomValueVariable(final String id) { - TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, - new StringResourceModel("cigaretteDeclaredCustomValue.label"), - new StringResourceModel("cigaretteDeclaredCustomValue.unit"), - new PropertyModel<>(editForm.getModel(), "cigaretteDeclaredCustomValue")); - variable.getInputField().getField().add(new PositiveBigDecimalValidator(true)); - - return variable; + private TetsimPriceAnalysisPanel getPriceAnalysisNumbers() { + return new TetsimPriceAnalysisPanel("priceAnalysisNumbers", editForm.getModel()); } - - private Component getAdultPopulationVariable(final String id) { - TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, - new StringResourceModel("adultPopulation.label"), - new StringResourceModel("adultPopulation.unit"), - new PropertyModel<>(editForm.getModel(), "adultPopulation")); - - variable.getInputField().getField().add(new PositiveBigDecimalValidator()); - - return variable; - } - - private Component getSmokingPrevalenceVariable(final String id) { - TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, - new StringResourceModel("smokingPrevalence.label"), - new StringResourceModel("smokingPrevalence.unit"), - new PropertyModel<>(editForm.getModel(), "smokingPrevalence")); - - variable.getInputField().getField().add(new PositiveBigDecimalValidator()); - - return variable; - } - - } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties index c5566782..78cbc216 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties @@ -1,18 +1,3 @@ page.title.add=Add TETSIM Dataset page.title.edit=Edit TETSIM Dataset -year.label=Year - -cigaretteConsumption.label=Total cigarette consumption (including illicit cigarettes) -cigaretteConsumption.unit=Full number of packs - -vatRate.label=VAT rate -vatRate.unit=Percentage - -cigaretteDeclaredCustomValue.label=Declared customs value of imported cigarettes (FOB amount) -cigaretteDeclaredCustomValue.unit={0} per pack - -adultPopulation.label=Adult Population (15+) -adultPopulation.unit=Full number - -smokingPrevalence.label=Smoking prevalence -smokingPrevalence.unit=Percentage \ No newline at end of file +year.label=Year \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.html new file mode 100644 index 00000000..3e3fa1e4 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.html @@ -0,0 +1,25 @@ + + + + +
+

Base-line Numbers:

+
+
+ + + + + + + + + + + + +
Base-line NumbersUnitValues
+
+
+ + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java new file mode 100644 index 00000000..3ff7a3a5 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java @@ -0,0 +1,95 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.dataset; + +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.devgateway.toolkit.forms.validators.PositiveBigDecimalValidator; +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; + +/** + * @author Viorel Chihai + */ +public class TetsimBaselineNumbersPanel extends Panel { + + protected final IModel tetsimDatasetIModel; + + public TetsimBaselineNumbersPanel(final String id, final IModel tetsimDatasetIModel) { + super(id); + this.tetsimDatasetIModel = tetsimDatasetIModel; + } + + @Override + protected void onInitialize() { + super.onInitialize(); + add(getBaseLineNumbers()); + } + + private RepeatingView getBaseLineNumbers() { + RepeatingView baseLineNumbers = new RepeatingView("numbers"); + baseLineNumbers.add(getCigaretteConsumptionVariable(baseLineNumbers.newChildId())); + baseLineNumbers.add(getVatRateVariable(baseLineNumbers.newChildId())); + baseLineNumbers.add(getCigaretteDeclaredCustomValueVariable(baseLineNumbers.newChildId())); + baseLineNumbers.add(getAdultPopulationVariable(baseLineNumbers.newChildId())); + baseLineNumbers.add(getSmokingPrevalenceVariable(baseLineNumbers.newChildId())); + + return baseLineNumbers; + } + + private TetsimBaselineDecimalVariable getCigaretteConsumptionVariable(final String id) { + TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, + new StringResourceModel("cigaretteConsumption.label"), + new StringResourceModel("cigaretteConsumption.unit"), + new PropertyModel<>(tetsimDatasetIModel, "cigaretteConsumption")); + + variable.getInputField().getField().add(new PositiveBigDecimalValidator()); + + return variable; + } + + private TetsimBaselineDecimalVariable getVatRateVariable(final String id) { + TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, + new StringResourceModel("vatRate.label"), + new StringResourceModel("vatRate.unit"), + new PropertyModel<>(tetsimDatasetIModel, "vatRate")); + + variable.getInputField().getField().add(new PositiveBigDecimalValidator()); + + return variable; + } + + private TetsimBaselineDecimalVariable getCigaretteDeclaredCustomValueVariable(final String id) { + TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, + new StringResourceModel("cigaretteDeclaredCustomValue.label"), + new StringResourceModel("cigaretteDeclaredCustomValue.unit"), + new PropertyModel<>(tetsimDatasetIModel, "cigaretteDeclaredCustomValue")); + variable.getInputField().getField().add(new PositiveBigDecimalValidator(true)); + + return variable; + } + + private TetsimBaselineDecimalVariable getAdultPopulationVariable(final String id) { + TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, + new StringResourceModel("adultPopulation.label"), + new StringResourceModel("adultPopulation.unit"), + new PropertyModel<>(tetsimDatasetIModel, "adultPopulation")); + + variable.getInputField().getField().add(new PositiveBigDecimalValidator()); + + return variable; + } + + private TetsimBaselineDecimalVariable getSmokingPrevalenceVariable(final String id) { + TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, + new StringResourceModel("smokingPrevalence.label"), + new StringResourceModel("smokingPrevalence.unit"), + new PropertyModel<>(tetsimDatasetIModel, "smokingPrevalence")); + + variable.getInputField().getField().add(new PositiveBigDecimalValidator()); + + return variable; + } +} + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties new file mode 100644 index 00000000..d718ba3b --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties @@ -0,0 +1,14 @@ +cigaretteConsumption.label=Total cigarette consumption (including illicit cigarettes) +cigaretteConsumption.unit=Full number of packs + +vatRate.label=VAT rate +vatRate.unit=Percentage + +cigaretteDeclaredCustomValue.label=Declared customs value of imported cigarettes (FOB amount) +cigaretteDeclaredCustomValue.unit={0} per pack + +adultPopulation.label=Adult Population (15+) +adultPopulation.unit=Full number + +smokingPrevalence.label=Smoking prevalence +smokingPrevalence.unit=Percentage \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.html new file mode 100644 index 00000000..f0e5a201 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.html @@ -0,0 +1,23 @@ + + + + +
+

Price Analysis:

+
+ +
+ + + + + + + + +
+
+
+
+ + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java new file mode 100644 index 00000000..2f08b1e9 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java @@ -0,0 +1,284 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.dataset; + +import org.apache.wicket.Component; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.validation.validator.RangeValidator; +import org.devgateway.toolkit.forms.validators.PositiveBigDecimalValidator; +import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; + +import java.math.BigDecimal; +import java.util.List; + +import static org.devgateway.toolkit.forms.WebConstants.MAXIMUM_PERCENTAGE; + +/** + * @author Viorel Chihai + */ +public class TetsimPriceAnalysisPanel extends Panel { + + protected final IModel tetsimDatasetIModel; + @SpringBean + protected TobaccoProductService tobaccoProductService; + + public TetsimPriceAnalysisPanel(final String id, final IModel tetsimDatasetIModel) { + super(id); + this.tetsimDatasetIModel = tetsimDatasetIModel; + } + + @Override + protected void onInitialize() { + super.onInitialize(); + add(getPriceAnalysisHeaders()); + add(getPriceAnalysisVariables()); + } + + private Component getPriceAnalysisHeaders() { + RepeatingView analysisHeaders = new RepeatingView("analysisHeaders"); + analysisHeaders.add(new Label(analysisHeaders.newChildId(), Model.of("Price Variable"))); + analysisHeaders.add(new Label(analysisHeaders.newChildId(), Model.of("Unit"))); + + List tobaccoProducts = tobaccoProductService.findAllSorted(); + for (TobaccoProduct tobaccoProduct : tobaccoProducts) { + analysisHeaders.add(new Label(analysisHeaders.newChildId(), + new PropertyModel<>(tobaccoProduct, "label"))); + } + + return analysisHeaders; + } + + private Component getPriceAnalysisVariables() { + RepeatingView variables = new RepeatingView("analysisVariables"); + + variables.add(getRetailPriceVariable(variables.newChildId())); + variables.add(getMarketShareVariable(variables.newChildId())); + variables.add(getCifVariable(variables.newChildId())); + variables.add(getTobaccoLevy(variables.newChildId())); + variables.add(getExciseTax(variables.newChildId())); + variables.add(getCustomsDuty(variables.newChildId())); + variables.add(getElasticityOfDemandPrice(variables.newChildId())); + variables.add(getElasticityOfDemandCrossPrice(variables.newChildId())); + variables.add(getChangeInIllicitNot(variables.newChildId())); + + return variables; + } + + /** + * Get retail price variable panel with tobacco product inputs. + * Mandatory. Numerical fields with decimals. No negative or 0 values accepted. + * + * @param id + * @return TetsimTobaccoProductsVariable + */ + private TetsimTobaccoProductsVariable getRetailPriceVariable(final String id) { + TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + new StringResourceModel("retailPrice.label"), + new StringResourceModel("retailPrice.unit"), + new PropertyModel<>(tetsimDatasetIModel, "retailPrice")) { + + @Override + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { + super.addBehavioursToTobaccoProductVariable(variable); + variable.getField().add(new PositiveBigDecimalValidator()); + } + }; + + return variable; + } + + /** + * Get market share variable panel with tobacco product inputs. + * Mandatory. Numerical fields with decimals. No negative values accepted. + * The total of all inputs should add up to 100. + * + * @param id + * @return TetsimTobaccoProductsVariable + */ + private TetsimTobaccoProductsVariable getMarketShareVariable(final String id) { + TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + new StringResourceModel("marketShare.label"), + new StringResourceModel("marketShare.unit"), + new PropertyModel<>(tetsimDatasetIModel, "marketShare")) { + + @Override + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { + super.addBehavioursToTobaccoProductVariable(variable); + variable.getField().add(new PositiveBigDecimalValidator(true)); + variable.getField().add(RangeValidator.maximum(BigDecimal.valueOf(MAXIMUM_PERCENTAGE))); + } + }; + + //TODO add sum of all percentages validator based on inputs values + + return variable; + } + + /** + * Get CIF variable panel with tobacco product inputs. + * Mandatory. Numerical fields with decimals. No negative values accepted. + * + * @param id + * @return TetsimTobaccoProductsVariable + */ + private TetsimTobaccoProductsVariable getCifVariable(final String id) { + TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + new StringResourceModel("cif.label"), + new StringResourceModel("cif.unit"), + new PropertyModel<>(tetsimDatasetIModel, "cif")) { + + @Override + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { + super.addBehavioursToTobaccoProductVariable(variable); + variable.getField().add(new PositiveBigDecimalValidator(true)); + } + }; + + return variable; + } + + /** + * Get tobacco levy variable panel with tobacco product inputs. + * Mandatory. Numerical fields with decimals. No negative values accepted. + * + * @param id + * @return TetsimTobaccoProductsVariable + */ + private TetsimTobaccoProductsVariable getTobaccoLevy(final String id) { + TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + new StringResourceModel("tobaccoLevy.label"), + new StringResourceModel("tobaccoLevy.unit"), + new PropertyModel<>(tetsimDatasetIModel, "tobaccoLevy")) { + + @Override + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { + super.addBehavioursToTobaccoProductVariable(variable); + variable.getField().add(new PositiveBigDecimalValidator(true)); + variable.getField().add(RangeValidator.maximum(BigDecimal.valueOf(MAXIMUM_PERCENTAGE))); + } + }; + + return variable; + } + + /** + * Get excise tax variable panel with tobacco product inputs. + * Mandatory. Numerical fields with decimals. No negative values accepted. + * + * @param id + * @return TetsimTobaccoProductsVariable + */ + private TetsimTobaccoProductsVariable getExciseTax(final String id) { + TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + new StringResourceModel("exciseTax.label"), + new StringResourceModel("exciseTax.unit"), + new PropertyModel<>(tetsimDatasetIModel, "exciseTax")) { + + @Override + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { + super.addBehavioursToTobaccoProductVariable(variable); + variable.getField().add(new PositiveBigDecimalValidator(true)); + } + }; + + return variable; + } + + /** + * Get customs duty variable panel with tobacco product inputs. + * Not Mandatory. Numerical fields with decimals. No negative values accepted. + * + * @param id + * @return TetsimTobaccoProductsVariable + */ + private TetsimTobaccoProductsVariable getCustomsDuty(final String id) { + TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + new StringResourceModel("customsDuty.label"), + new StringResourceModel("customsDuty.unit"), + new PropertyModel<>(tetsimDatasetIModel, "customsDuty"), false) { + + @Override + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { + super.addBehavioursToTobaccoProductVariable(variable); + variable.getField().add(new PositiveBigDecimalValidator(true)); + } + }; + + return variable; + } + + /** + * Get price elasticity of demand variable panel with tobacco product inputs. + * Mandatory. Numerical fields with decimals between -1 and 1. + * + * @param id + * @return TetsimTobaccoProductsVariable + */ + private TetsimTobaccoProductsVariable getElasticityOfDemandPrice(final String id) { + TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + new StringResourceModel("elasticityOfDemandPrice.label"), + new StringResourceModel("elasticityOfDemandPrice.unit"), + new PropertyModel<>(tetsimDatasetIModel, "elasticityOfDemandPrice")) { + + @Override + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { + super.addBehavioursToTobaccoProductVariable(variable); + variable.getField().add(RangeValidator.range(BigDecimal.valueOf(-1), BigDecimal.ONE)); + } + }; + + return variable; + } + + /** + * Get cross-price elasticity of demand variable panel with tobacco product inputs. + * Mandatory. Numerical fields with decimals between -1 and 1. + * + * @param id + * @return TetsimTobaccoProductsVariable + */ + private TetsimTobaccoProductsVariable getElasticityOfDemandCrossPrice(final String id) { + TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + new StringResourceModel("elasticityOfDemandCrossPrice.label"), + new StringResourceModel("elasticityOfDemandCrossPrice.unit"), + new PropertyModel<>(tetsimDatasetIModel, "elasticityOfDemandPrice")) { + + @Override + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { + super.addBehavioursToTobaccoProductVariable(variable); + variable.getField().add(RangeValidator.range(BigDecimal.valueOf(-1), BigDecimal.ONE)); + } + }; + + return variable; + } + + /** + * Get change in illicit not variable panel with tobacco product inputs. + * Only allowed for product marked as illicit in the system category. + * Numerical field with decimals. + * + * @param id + * @return TetsimTobaccoProductsVariable + */ + private TetsimTobaccoProductsVariable getChangeInIllicitNot(final String id) { + TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + new StringResourceModel("changeInIllicitNot.label"), + new StringResourceModel("changeInIllicitNot.unit"), + new PropertyModel<>(tetsimDatasetIModel, "changeInIllicitNot"), false, true) { + }; + + return variable; + } + +} + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.properties new file mode 100644 index 00000000..41288c78 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.properties @@ -0,0 +1,27 @@ +retailPrice.label=Retail Price +retailPrice.unit={currency} per pack + +marketShare.label=Market Share +marketShare.unit=Percentage + +cif.label=CIF +cif.unit={currency} per pack + +tobaccoLevy.label=Tobacco Levy +tobaccoLevy.unit=Percentage of CIF + +exciseTax.label=Excise tax +exciseTax.unit={currency} per pack + +customsDuty.label=Customs duty on imported cigarettes +customsDuty.unit=Percentage of FOB value + +elasticityOfDemandPrice.label=Price elasticity of demand +elasticityOfDemandPrice.unit=Number (between -1 and 1) + +elasticityOfDemandCrossPrice.label=Cross-price elasticity of demand (from higher price category) +elasticityOfDemandCrossPrice.unit=Number (between -1 and 1) + +changeInIllicitNot.label=Change in illicit NOT (proportion of change in discount price): sensitivity factor +changeInIllicitNot.unit=Proportion + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.html new file mode 100644 index 00000000..989fcf25 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.html @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.java new file mode 100644 index 00000000..690bf94a --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.java @@ -0,0 +1,123 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.dataset; + +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; +import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; +import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; +import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; + +import java.util.List; +import java.util.Set; + +/** + * @author Viorel Chihai + */ +public class TetsimTobaccoProductsVariable extends Panel { + + private final IModel labelModel; + + private final IModel unitModel; + + private final boolean required; + + private final boolean illicitOnly; + + protected final IModel variableModel; + + @SpringBean + protected TobaccoProductService tobaccoProductService; + + protected RepeatingView inputFields; + + public TetsimTobaccoProductsVariable(final String id, final IModel labelModel, + final IModel unitModel, + final IModel variableModel) { + this(id, labelModel, unitModel, variableModel, true); + } + + public TetsimTobaccoProductsVariable(final String id, final IModel labelModel, + final IModel unitModel, + final IModel variableModel, + final boolean required) { + this(id, labelModel, unitModel, variableModel, required, false); + } + + public TetsimTobaccoProductsVariable(final String id, final IModel labelModel, + final IModel unitModel, + final IModel variableModel, + final boolean required, final boolean illicitOnly) { + super(id); + this.labelModel = labelModel; + this.unitModel = unitModel; + this.variableModel = variableModel; + this.required = required; + this.illicitOnly = illicitOnly; + + inputFields = createInputFields(); + } + + @Override + protected void onInitialize() { + super.onInitialize(); + add(new Label("label", labelModel)); + add(new Label("unit", unitModel)); + add(inputFields); + } + + protected RepeatingView createInputFields() { + RepeatingView fields = new RepeatingView("tobaccoProducts"); + List tobaccoProducts = tobaccoProductService.findAllSorted(); + TetsimPriceVariable priceVariable = variableModel.getObject(); + + for (TobaccoProduct tobaccoProduct: tobaccoProducts) { + if (!illicitOnly || tobaccoProduct.isIllicit()) { + TetsimTobaccoProductValue tobaccoProductValue = getTobaccoProductValue(priceVariable, tobaccoProduct); + TextFieldBootstrapFormComponent field = new TextFieldBootstrapFormComponent<>(fields.newChildId(), + new PropertyModel<>(Model.of(tobaccoProductValue), "value")); + field.decimal(); + field.hideLabel(); + field.getField().setRequired(required); + + addBehavioursToTobaccoProductVariable(field); + + fields.add(field); + } else { + fields.add(new WebMarkupContainer(fields.newChildId())); + } + } + + return fields; + } + + public TetsimTobaccoProductValue getTobaccoProductValue(final TetsimPriceVariable priceVariable, + final TobaccoProduct product) { + Set tobaccoProductValues = priceVariable.getValues(); + + TetsimTobaccoProductValue productValue = tobaccoProductValues.stream() + .filter(t -> t.getProduct().getId().equals(product.getId())).findAny() + .orElse(null); + + if (productValue == null) { + productValue = new TetsimTobaccoProductValue(); + productValue.setProduct(product); + productValue.setPriceVariable(priceVariable); + tobaccoProductValues.add(productValue); + } + + return productValue; + } + + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { + } + +} + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.properties new file mode 100644 index 00000000..ef09e41b --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.properties @@ -0,0 +1 @@ +input.label=input \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java index 0f283b37..d35d1f86 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java @@ -4,6 +4,7 @@ import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; +import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToOne; @@ -29,60 +30,60 @@ public class TetsimDataset extends Dataset { @Audited BigDecimal smokingPrevalence; - @OneToOne(fetch = FetchType.LAZY) + @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable retailPrice; + TetsimPriceVariable retailPrice = new TetsimPriceVariable(this); - @OneToOne(fetch = FetchType.LAZY) + @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable marketShare; + TetsimPriceVariable marketShare = new TetsimPriceVariable(this); - @OneToOne(fetch = FetchType.LAZY) + @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable CIF; + TetsimPriceVariable cif = new TetsimPriceVariable(this); - @OneToOne(fetch = FetchType.LAZY) + @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable tobaccoLevy; + TetsimPriceVariable tobaccoLevy = new TetsimPriceVariable(this); - @OneToOne(fetch = FetchType.LAZY) + @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable exciseTax; + TetsimPriceVariable exciseTax = new TetsimPriceVariable(this); - @OneToOne(fetch = FetchType.LAZY) + @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable customsDuty; + TetsimPriceVariable customsDuty = new TetsimPriceVariable(this); - @OneToOne(fetch = FetchType.LAZY) + @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable elasticityOfDemandPrice; + TetsimPriceVariable elasticityOfDemandPrice = new TetsimPriceVariable(this); - @OneToOne(fetch = FetchType.LAZY) + @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable elasticityOfDemandCrossPrice; + TetsimPriceVariable elasticityOfDemandCrossPrice = new TetsimPriceVariable(this); - @OneToOne(fetch = FetchType.LAZY) + @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable changeInIllicitNot; + TetsimPriceVariable changeInIllicitNot = new TetsimPriceVariable(this); - @OneToOne(fetch = FetchType.LAZY) + @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable overShifting; + TetsimPriceVariable overShifting = new TetsimPriceVariable(this); - @OneToOne(fetch = FetchType.LAZY) + @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable underShifting; + TetsimPriceVariable underShifting = new TetsimPriceVariable(this); public BigDecimal getCigaretteConsumption() { return cigaretteConsumption; @@ -140,12 +141,12 @@ public void setMarketShare(final TetsimPriceVariable marketShare) { this.marketShare = marketShare; } - public TetsimPriceVariable getCIF() { - return CIF; + public TetsimPriceVariable getCif() { + return cif; } - public void setCIF(final TetsimPriceVariable CIF) { - this.CIF = CIF; + public void setCif(final TetsimPriceVariable CIF) { + this.cif = CIF; } public TetsimPriceVariable getTobaccoLevy() { diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimPriceVariable.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimPriceVariable.java index 1db06d52..aeb53876 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimPriceVariable.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimPriceVariable.java @@ -9,12 +9,13 @@ import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; +import java.util.HashSet; import java.util.Set; @Entity @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) -public class TetsimPriceVariable extends AbstractAuditableEntity { +public class TetsimPriceVariable extends AbstractAuditableEntity { @ManyToOne @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @@ -22,13 +23,28 @@ public class TetsimPriceVariable extends AbstractAuditableEntity { @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - private Set values; + private Set values = new HashSet<>(); + + public TetsimPriceVariable() { + } + + public TetsimPriceVariable(final TetsimDataset dataset) { + this.dataset = dataset; + } @Override public AbstractAuditableEntity getParent() { return dataset; } + public TetsimDataset getDataset() { + return dataset; + } + + public void setDataset(final TetsimDataset dataset) { + this.dataset = dataset; + } + public Set getValues() { return values; } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java index c9c02993..0e31a9f4 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java @@ -41,6 +41,14 @@ public void setValue(final BigDecimal value) { this.value = value; } + public TetsimPriceVariable getPriceVariable() { + return priceVariable; + } + + public void setPriceVariable(final TetsimPriceVariable priceVariable) { + this.priceVariable = priceVariable; + } + @Override public AbstractAuditableEntity getParent() { return priceVariable; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/BaseJpaService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/BaseJpaService.java index c58f88c1..aa1e7a3f 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/BaseJpaService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/BaseJpaService.java @@ -16,6 +16,8 @@ public interface BaseJpaService { List findAll(Sort sort); + List findAllSorted(); + List findAll(Specification spec); Page findAll(Specification spec, Pageable pageable); diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/BaseJpaServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/BaseJpaServiceImpl.java index 0d98ab1f..a25f1906 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/BaseJpaServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/BaseJpaServiceImpl.java @@ -30,6 +30,11 @@ public List findAll(final Sort sort) { return repository().findAll(sort); } + @Override + public List findAllSorted() { + return repository().findAll(getSort()); + } + @Override public List findAll(final Specification spec) { return repository().findAll(spec); @@ -89,6 +94,10 @@ public void delete(final T entity) { repository().delete(entity); } + public Sort getSort() { + return Sort.by(Sort.Direction.ASC, "id"); + } + protected abstract BaseJpaRepository repository(); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java index 7f841fab..ecc9427a 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java @@ -9,6 +9,7 @@ import org.devgateway.toolkit.persistence.service.BaseJpaServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; +import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -39,4 +40,9 @@ public TextSearchableRepository textRepository() { public UniquePropertyRepository uniquePropertyRepository() { return tobaccoProductRepository; } + + @Override + public Sort getSort() { + return Sort.by(Sort.Direction.ASC, "label"); + } } From 4d183f839af636439bc8cc9ab03076255abe23e3 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 3 Jan 2022 16:32:38 +0200 Subject: [PATCH 013/137] TOBACCO-800: Add industry responses variables --- .../edit/dataset/EditTetsimDatasetPage.html | 1 + .../edit/dataset/EditTetsimDatasetPage.java | 44 +++++++-- .../dataset/EditTetsimDatasetPage.properties | 4 +- .../dataset/TetsimIndustryResponsesPanel.html | 23 +++++ .../dataset/TetsimIndustryResponsesPanel.java | 96 +++++++++++++++++++ .../TetsimIndustryResponsesPanel.properties | 6 ++ .../dataset/TetsimPriceAnalysisPanel.java | 93 +++++++----------- 7 files changed, 200 insertions(+), 67 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.properties diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html index 310e030c..5cebebdc 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html @@ -13,6 +13,7 @@
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index 1f759546..96a66adf 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -1,26 +1,23 @@ package org.devgateway.toolkit.forms.wicket.page.edit.dataset; -import org.apache.wicket.Component; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.repeater.RepeatingView; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.form.FormComponent; +import org.apache.wicket.markup.html.form.validation.AbstractFormValidator; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; -import org.devgateway.toolkit.forms.validators.PositiveBigDecimalValidator; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; import org.devgateway.toolkit.persistence.dao.data.DatasetStatus; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; -import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; +import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.wicketstuff.annotation.mount.MountPath; -import java.util.List; +import java.math.BigDecimal; + +import static org.devgateway.toolkit.forms.WebConstants.MAXIMUM_PERCENTAGE; /** * @author vchihai @@ -50,6 +47,9 @@ protected void onInitialize() { editForm.add(getYear()); editForm.add(getBaseLineNumbers()); editForm.add(getPriceAnalysisNumbers()); + editForm.add(getIndustryResponsesNumbers()); + + editForm.add(new TetsimMarketSharePercentageValidator()); } private TextFieldBootstrapFormComponent getYear() { @@ -66,4 +66,28 @@ private TetsimBaselineNumbersPanel getBaseLineNumbers() { private TetsimPriceAnalysisPanel getPriceAnalysisNumbers() { return new TetsimPriceAnalysisPanel("priceAnalysisNumbers", editForm.getModel()); } + + private TetsimIndustryResponsesPanel getIndustryResponsesNumbers() { + return new TetsimIndustryResponsesPanel("industryResponsesNumbers", editForm.getModel()); + } + + private class TetsimMarketSharePercentageValidator extends AbstractFormValidator { + + @Override + public FormComponent[] getDependentFormComponents() { + return new FormComponent[0]; + } + + @Override + public void validate(final Form form) { + TetsimPriceVariable marketShare = editForm.getModelObject().getMarketShare(); + BigDecimal sum = marketShare.getValues().stream() + .map(TetsimTobaccoProductValue::getValue) + .reduce(BigDecimal.ZERO, BigDecimal::add); + + if (sum.intValue() > MAXIMUM_PERCENTAGE) { + editForm.error(getString("error.form.validation.marketShare.percentage")); + } + } + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties index 78cbc216..b83fab3f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties @@ -1,3 +1,5 @@ page.title.add=Add TETSIM Dataset page.title.edit=Edit TETSIM Dataset -year.label=Year \ No newline at end of file +year.label=Year + +error.form.validation.marketShare.percentage=The total of all the market share values should add up to 100 \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.html new file mode 100644 index 00000000..1903c0a1 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.html @@ -0,0 +1,23 @@ + + + + +
+

Industry responses to the change in taxation:

+
+ +
+ + + + + + + + +
+
+
+
+ + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.java new file mode 100644 index 00000000..35dcc273 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.java @@ -0,0 +1,96 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.dataset; + +import org.apache.wicket.Component; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; + +import java.util.List; + +/** + * @author Viorel Chihai + */ +public class TetsimIndustryResponsesPanel extends Panel { + + protected final IModel tetsimDatasetIModel; + + @SpringBean + protected TobaccoProductService tobaccoProductService; + + public TetsimIndustryResponsesPanel(final String id, final IModel tetsimDatasetIModel) { + super(id); + this.tetsimDatasetIModel = tetsimDatasetIModel; + } + + @Override + protected void onInitialize() { + super.onInitialize(); + add(getIndustryResponsesHeaders()); + add(getIndustryResponsesVariables()); + } + + private Component getIndustryResponsesHeaders() { + RepeatingView analysisHeaders = new RepeatingView("industryResponsesHeaders"); + analysisHeaders.add(new Label(analysisHeaders.newChildId(), + Model.of("Industry responses to the change in taxation"))); + analysisHeaders.add(new Label(analysisHeaders.newChildId(), Model.of("Unit"))); + + List tobaccoProducts = tobaccoProductService.findAllSorted(); + for (TobaccoProduct tobaccoProduct : tobaccoProducts) { + analysisHeaders.add(new Label(analysisHeaders.newChildId(), + new PropertyModel<>(tobaccoProduct, "label"))); + } + + return analysisHeaders; + } + + private Component getIndustryResponsesVariables() { + RepeatingView variables = new RepeatingView("industryResponsesVariables"); + + variables.add(getOverShifting(variables.newChildId())); + variables.add(getUnderShifting(variables.newChildId())); + + return variables; + } + + /** + * Get overshifting variable panel with tobacco product inputs. + * Mandatory. Numerical fields with decimals. + * + * @param id + * @return TetsimTobaccoProductsVariable + */ + private TetsimTobaccoProductsVariable getOverShifting(final String id) { + return new TetsimTobaccoProductsVariable(id, + new StringResourceModel("overShifting.label"), + new StringResourceModel("overShifting.unit"), + new PropertyModel<>(tetsimDatasetIModel, "overShifting"), true) { + }; + } + + /** + * Get undershifting variable panel with tobacco product inputs. + * Mandatory. Numerical fields with decimals. + * + * @param id + * @return TetsimTobaccoProductsVariable + */ + private TetsimTobaccoProductsVariable getUnderShifting(final String id) { + return new TetsimTobaccoProductsVariable(id, + new StringResourceModel("underShifting.label"), + new StringResourceModel("underShifting.unit"), + new PropertyModel<>(tetsimDatasetIModel, "underShifting"), true) { + }; + } + +} + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.properties new file mode 100644 index 00000000..c4f11b14 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.properties @@ -0,0 +1,6 @@ +overShifting.label=Overshifting (% change above excise tax increase) +overShifting.unit=Percentage change above excise tax increase + +underShifting.label=Change in illicit NOT (proportion of change in discount price): sensitivity factor +underShifting.unit=Undershifting (% change below excise tax increase) + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java index 2f08b1e9..cc450ff8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java @@ -27,6 +27,7 @@ public class TetsimPriceAnalysisPanel extends Panel { protected final IModel tetsimDatasetIModel; + @SpringBean protected TobaccoProductService tobaccoProductService; @@ -56,7 +57,7 @@ private Component getPriceAnalysisHeaders() { return analysisHeaders; } - private Component getPriceAnalysisVariables() { + private RepeatingView getPriceAnalysisVariables() { RepeatingView variables = new RepeatingView("analysisVariables"); variables.add(getRetailPriceVariable(variables.newChildId())); @@ -80,19 +81,17 @@ private Component getPriceAnalysisVariables() { * @return TetsimTobaccoProductsVariable */ private TetsimTobaccoProductsVariable getRetailPriceVariable(final String id) { - TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + return new TetsimTobaccoProductsVariable(id, new StringResourceModel("retailPrice.label"), new StringResourceModel("retailPrice.unit"), new PropertyModel<>(tetsimDatasetIModel, "retailPrice")) { @Override - protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { - super.addBehavioursToTobaccoProductVariable(variable); - variable.getField().add(new PositiveBigDecimalValidator()); + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable1) { + super.addBehavioursToTobaccoProductVariable(variable1); + variable1.getField().add(new PositiveBigDecimalValidator()); } }; - - return variable; } /** @@ -104,22 +103,18 @@ protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFor * @return TetsimTobaccoProductsVariable */ private TetsimTobaccoProductsVariable getMarketShareVariable(final String id) { - TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + return new TetsimTobaccoProductsVariable(id, new StringResourceModel("marketShare.label"), new StringResourceModel("marketShare.unit"), new PropertyModel<>(tetsimDatasetIModel, "marketShare")) { @Override - protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { - super.addBehavioursToTobaccoProductVariable(variable); - variable.getField().add(new PositiveBigDecimalValidator(true)); - variable.getField().add(RangeValidator.maximum(BigDecimal.valueOf(MAXIMUM_PERCENTAGE))); + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable1) { + super.addBehavioursToTobaccoProductVariable(variable1); + variable1.getField().add(new PositiveBigDecimalValidator(true)); + variable1.getField().add(RangeValidator.maximum(BigDecimal.valueOf(MAXIMUM_PERCENTAGE))); } }; - - //TODO add sum of all percentages validator based on inputs values - - return variable; } /** @@ -130,19 +125,17 @@ protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFor * @return TetsimTobaccoProductsVariable */ private TetsimTobaccoProductsVariable getCifVariable(final String id) { - TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + return new TetsimTobaccoProductsVariable(id, new StringResourceModel("cif.label"), new StringResourceModel("cif.unit"), new PropertyModel<>(tetsimDatasetIModel, "cif")) { @Override - protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { - super.addBehavioursToTobaccoProductVariable(variable); - variable.getField().add(new PositiveBigDecimalValidator(true)); + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable1) { + super.addBehavioursToTobaccoProductVariable(variable1); + variable1.getField().add(new PositiveBigDecimalValidator(true)); } }; - - return variable; } /** @@ -153,20 +146,18 @@ protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFor * @return TetsimTobaccoProductsVariable */ private TetsimTobaccoProductsVariable getTobaccoLevy(final String id) { - TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + return new TetsimTobaccoProductsVariable(id, new StringResourceModel("tobaccoLevy.label"), new StringResourceModel("tobaccoLevy.unit"), new PropertyModel<>(tetsimDatasetIModel, "tobaccoLevy")) { @Override - protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { - super.addBehavioursToTobaccoProductVariable(variable); - variable.getField().add(new PositiveBigDecimalValidator(true)); - variable.getField().add(RangeValidator.maximum(BigDecimal.valueOf(MAXIMUM_PERCENTAGE))); + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable1) { + super.addBehavioursToTobaccoProductVariable(variable1); + variable1.getField().add(new PositiveBigDecimalValidator(true)); + variable1.getField().add(RangeValidator.maximum(BigDecimal.valueOf(MAXIMUM_PERCENTAGE))); } }; - - return variable; } /** @@ -177,19 +168,17 @@ protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFor * @return TetsimTobaccoProductsVariable */ private TetsimTobaccoProductsVariable getExciseTax(final String id) { - TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + return new TetsimTobaccoProductsVariable(id, new StringResourceModel("exciseTax.label"), new StringResourceModel("exciseTax.unit"), new PropertyModel<>(tetsimDatasetIModel, "exciseTax")) { @Override - protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { - super.addBehavioursToTobaccoProductVariable(variable); - variable.getField().add(new PositiveBigDecimalValidator(true)); + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable1) { + super.addBehavioursToTobaccoProductVariable(variable1); + variable1.getField().add(new PositiveBigDecimalValidator(true)); } }; - - return variable; } /** @@ -200,19 +189,17 @@ protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFor * @return TetsimTobaccoProductsVariable */ private TetsimTobaccoProductsVariable getCustomsDuty(final String id) { - TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + return new TetsimTobaccoProductsVariable(id, new StringResourceModel("customsDuty.label"), new StringResourceModel("customsDuty.unit"), new PropertyModel<>(tetsimDatasetIModel, "customsDuty"), false) { @Override - protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { - super.addBehavioursToTobaccoProductVariable(variable); - variable.getField().add(new PositiveBigDecimalValidator(true)); + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable1) { + super.addBehavioursToTobaccoProductVariable(variable1); + variable1.getField().add(new PositiveBigDecimalValidator(true)); } }; - - return variable; } /** @@ -223,19 +210,17 @@ protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFor * @return TetsimTobaccoProductsVariable */ private TetsimTobaccoProductsVariable getElasticityOfDemandPrice(final String id) { - TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + return new TetsimTobaccoProductsVariable(id, new StringResourceModel("elasticityOfDemandPrice.label"), new StringResourceModel("elasticityOfDemandPrice.unit"), new PropertyModel<>(tetsimDatasetIModel, "elasticityOfDemandPrice")) { @Override - protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { - super.addBehavioursToTobaccoProductVariable(variable); - variable.getField().add(RangeValidator.range(BigDecimal.valueOf(-1), BigDecimal.ONE)); + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable1) { + super.addBehavioursToTobaccoProductVariable(variable1); + variable1.getField().add(RangeValidator.range(BigDecimal.valueOf(-1), BigDecimal.ONE)); } }; - - return variable; } /** @@ -246,19 +231,17 @@ protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFor * @return TetsimTobaccoProductsVariable */ private TetsimTobaccoProductsVariable getElasticityOfDemandCrossPrice(final String id) { - TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + return new TetsimTobaccoProductsVariable(id, new StringResourceModel("elasticityOfDemandCrossPrice.label"), new StringResourceModel("elasticityOfDemandCrossPrice.unit"), new PropertyModel<>(tetsimDatasetIModel, "elasticityOfDemandPrice")) { @Override - protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable) { - super.addBehavioursToTobaccoProductVariable(variable); - variable.getField().add(RangeValidator.range(BigDecimal.valueOf(-1), BigDecimal.ONE)); + protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable1) { + super.addBehavioursToTobaccoProductVariable(variable1); + variable1.getField().add(RangeValidator.range(BigDecimal.valueOf(-1), BigDecimal.ONE)); } }; - - return variable; } /** @@ -270,13 +253,11 @@ protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFor * @return TetsimTobaccoProductsVariable */ private TetsimTobaccoProductsVariable getChangeInIllicitNot(final String id) { - TetsimTobaccoProductsVariable variable = new TetsimTobaccoProductsVariable(id, + return new TetsimTobaccoProductsVariable(id, new StringResourceModel("changeInIllicitNot.label"), new StringResourceModel("changeInIllicitNot.unit"), new PropertyModel<>(tetsimDatasetIModel, "changeInIllicitNot"), false, true) { }; - - return variable; } } From a01af4c31b11ad54bb012806d95fc77f55945242 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Tue, 4 Jan 2022 14:10:34 +0200 Subject: [PATCH 014/137] TOBACCO-793: Add validators on tobacco product form --- .../UniqueTobaccoProductIllicitValidator.java | 64 +++++++++++++++++++ ...eTobaccoProductIllicitValidator.properties | 1 + .../edit/category/EditTobaccoProductPage.java | 10 ++- .../forms/wicket/styles/BaseStyles.css | 4 ++ 4 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.properties diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.java b/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.java new file mode 100644 index 00000000..97c384bb --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.java @@ -0,0 +1,64 @@ +package org.devgateway.toolkit.forms.validators; + +import org.apache.wicket.Component; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.validation.IValidatable; +import org.apache.wicket.validation.IValidator; +import org.apache.wicket.validation.ValidationError; +import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; + +import java.util.Collection; +import java.util.Collections; + +/** + * @author Viorel Chihai + */ +public class UniqueTobaccoProductIllicitValidator implements IValidator { + private static final long serialVersionUID = -695597033541103492L; + + protected final TobaccoProductService tobaccoProductService; + + protected final Collection entityIdsToIgnore; + + protected final String propertyName; + + protected final IModel propertyLabel; + + public UniqueTobaccoProductIllicitValidator(final TobaccoProductService tobaccoProductService, + final long entityIdToIgnore, final String propertyName, + final Component component) { + this(tobaccoProductService, Collections.singleton(entityIdToIgnore), propertyName, component); + } + + public UniqueTobaccoProductIllicitValidator(final TobaccoProductService uniquePropertyService, + final Collection entityIdsToIgnore, final String propertyName, + final Component component) { + this(uniquePropertyService, entityIdsToIgnore, propertyName, + new StringResourceModel(propertyName + ".label", component)); + } + + public UniqueTobaccoProductIllicitValidator(final TobaccoProductService tobaccoProductService, + final Collection entityIdsToIgnore, final String propertyName, + final IModel propertyLabel) { + if (entityIdsToIgnore.isEmpty()) { + entityIdsToIgnore.add(-1L); + } + + this.tobaccoProductService = tobaccoProductService; + this.entityIdsToIgnore = entityIdsToIgnore; + this.propertyName = propertyName; + this.propertyLabel = propertyLabel; + } + + @Override + public void validate(final IValidatable validatable) { + final Boolean value = validatable.getValue(); + if (Boolean.TRUE.equals(value) + && tobaccoProductService.existsByProperty(propertyName, value, entityIdsToIgnore)) { + ValidationError error = new ValidationError(this); + validatable.error(error); + } + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.properties b/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.properties new file mode 100644 index 00000000..e0e3cc89 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.properties @@ -0,0 +1 @@ +UniqueTobaccoProductIllicitValidator=There is already another product marked as illicit. diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java index 6c2d011a..fe6f3f49 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java @@ -16,6 +16,7 @@ import org.apache.wicket.util.string.StringValue; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.validators.UniquePropertyValidator; +import org.devgateway.toolkit.forms.validators.UniqueTobaccoProductIllicitValidator; import org.devgateway.toolkit.forms.wicket.components.form.CheckBoxYesNoToggleBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; @@ -44,15 +45,20 @@ public EditTobaccoProductPage(final PageParameters parameters) { @Override protected void onInitialize() { super.onInitialize(); + final StringValue id = getPageParameters().get(WebConstants.PARAM_ID); final TextFieldBootstrapFormComponent name = new TextFieldBootstrapFormComponent<>("label"); name.required(); - final StringValue id = getPageParameters().get(WebConstants.PARAM_ID); + name.getField().add(new UniquePropertyValidator<>(tobaccoProductService, id.toLong(-1L), "label", this)); name.getField().add(WebConstants.StringValidators.MAXIMUM_LENGTH_VALIDATOR_STD_DEFAULT_TEXT); editForm.add(name); - editForm.add(new CheckBoxYesNoToggleBootstrapFormComponent("illicit")); + final CheckBoxYesNoToggleBootstrapFormComponent illicit = + new CheckBoxYesNoToggleBootstrapFormComponent("illicit"); + illicit.getField().add(new UniqueTobaccoProductIllicitValidator(tobaccoProductService, id.toLong(-1L), + "illicit", this)); + editForm.add(illicit); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css index 378beced..f2391bb9 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css @@ -267,4 +267,8 @@ button .btn-home-desc { button .btn-home-label { white-space: normal; line-height: 20px; +} + +.feedbackPanel, .form-wrapper { + margin: 10px 5px 10px 10px; } \ No newline at end of file From f8cb72922bbf237228d87bb2700620d7015b6e7b Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 7 Jan 2022 14:09:30 +0200 Subject: [PATCH 015/137] TOBACCO-802: Add datasets statuses --- .../filter/TetsimDatasetFilterState.java | 33 ++++ .../toolkit/forms/wicket/page/Footer.html | 2 +- .../wicket/page/edit/AbstractEditPage.html | 1 + .../wicket/page/edit/AbstractEditPage.java | 55 ++++-- .../edit/AbstractEditStatusEntityPage.html | 8 +- .../edit/AbstractEditStatusEntityPage.java | 171 ++++++++++++++---- .../AbstractEditStatusEntityPage.properties | 9 +- .../edit/dataset/EditTetsimDatasetPage.html | 4 +- .../edit/dataset/EditTetsimDatasetPage.java | 36 +++- .../dataset/TetsimBaselineNumbersPanel.html | 29 ++- .../edit/dataset/TetsimBaselineVariable.html | 4 +- .../dataset/TetsimIndustryResponsesPanel.html | 24 ++- .../dataset/TetsimPriceAnalysisPanel.html | 24 ++- .../lists/dataset/ListTetsimDatasetPage.java | 3 +- .../forms/wicket/styles/BaseStyles.css | 23 ++- .../dao/AbstractStatusAuditableEntity.java | 12 +- .../toolkit/persistence/dao/DBConstants.java | 7 +- .../toolkit/persistence/dao/Statusable.java | 6 + .../toolkit/persistence/dao/data/Dataset.java | 22 +-- .../persistence/dao/data/DatasetStatus.java | 19 -- 20 files changed, 333 insertions(+), 159 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DatasetStatus.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java new file mode 100644 index 00000000..185fba9a --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java @@ -0,0 +1,33 @@ +package org.devgateway.toolkit.forms.wicket.components.table.filter; + +import org.devgateway.toolkit.persistence.dao.AbstractStatusAuditableEntity_; +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.repository.SpecificationContext; +import org.springframework.data.jpa.domain.Specification; + +import javax.persistence.criteria.Predicate; +import java.util.ArrayList; +import java.util.List; + +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; + +/** + * Created by Viorel Chihai + */ +public class TetsimDatasetFilterState extends JpaFilterState { + + private static final long serialVersionUID = 6655165533257383853L; + + @Override + public Specification getSpecification() { + return (root, query, cb) -> { + List predicates = new ArrayList<>(); + SpecificationContext sc = new SpecificationContext<>(root, query, cb); + + predicates.add(sc.cb().notLike(sc.root().get(AbstractStatusAuditableEntity_.status), DELETED)); + + return cb.and(predicates.toArray(new Predicate[predicates.size()])); + }; + } + +} \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Footer.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Footer.html index 2b7601b0..70fdd5e2 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Footer.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Footer.html @@ -9,7 +9,7 @@
- DG-Toolkit   + TCDI Admin    -  © Copyright diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html index ce5c4283..1fd18ef8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html @@ -15,6 +15,7 @@
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java index a51b3ca7..625ea570 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java @@ -115,12 +115,14 @@ private T newInstance() { protected TextContentModal deleteModal; + protected TextContentModal cancelModal; + protected TextContentModal deleteFailedModal; protected TextContentModal saveFailedModal; @SpringBean - private EntityManager entityManager; + protected EntityManager entityManager; @SpringBean(required = false) private MarkupCacheService markupCacheService; @@ -152,8 +154,7 @@ public GenericBootstrapValidationVisitor getBootstrapValidationVisitor(final Aja protected TextContentModal createDeleteModal() { final TextContentModal modal = new TextContentModal("deleteModal", - Model.of("DELETE is an irreversible operation. Are you sure?")); - modal.addCloseButton(); + Model.of("Are you sure you want to delete? You will no longer be able to access this data.")); final LaddaAjaxButton deleteButton = new LaddaAjaxButton("button", Buttons.Type.Danger) { @Override @@ -166,12 +167,34 @@ protected void onSubmit(final AjaxRequestTarget target) { } }; deleteButton.setDefaultFormProcessing(false); - deleteButton.setLabel(Model.of("DELETE")); + deleteButton.setLabel(Model.of("Yes")); + modal.addCloseButton(Model.of("No")); modal.addButton(deleteButton); return modal; } + protected TextContentModal createCancelModal() { + final TextContentModal cancelModal = new TextContentModal("cancelModal", + Model.of("Are you sure you want to cancel? Any changes made will be lost.")); + + final LaddaAjaxButton cancelButton = new BootstrapCancelButton("button", Model.of("Yes")) { + private static final long serialVersionUID = -9144254663723097155L; + + @Override + protected void onSubmit(final AjaxRequestTarget target) { + cancelModal.appendCloseDialogJavaScript(target); + setResponsePage(listPageClass); + } + }; + + cancelButton.setType(Buttons.Type.Success); + cancelModal.addButton(cancelButton); + cancelModal.addCloseButton(Model.of("No")); + + return cancelModal; + } + protected TextContentModal createDeleteFailedModal() { final TextContentModal modal = new TextContentModal("deleteFailedModal", new ResourceModel("delete_error_message")); @@ -256,6 +279,9 @@ public EditForm(final String id) { deleteModal = createDeleteModal(); add(deleteModal); + cancelModal = createCancelModal(); + add(cancelModal); + deleteFailedModal = createDeleteFailedModal(); add(deleteFailedModal); @@ -272,14 +298,21 @@ public EditForm(final String id) { } protected BootstrapCancelButton getCancelButton(final String id) { - return new BootstrapCancelButton(id, new StringResourceModel("cancelButton", this, null)) { - private static final long serialVersionUID = -249084359200507749L; + return new CancelEditPageButton(id, new StringResourceModel("cancelButton", this, null)); + } - @Override - protected void onSubmit(final AjaxRequestTarget target) { - setResponsePage(listPageClass); - } - }; + public class CancelEditPageButton extends BootstrapCancelButton { + private static final long serialVersionUID = -1474498211555760931L; + + public CancelEditPageButton(final String id, final IModel model) { + super(id, model); + } + + @Override + protected void onSubmit(final AjaxRequestTarget target) { + cancelModal.show(true); + target.add(cancelModal); + } } /** diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html index efa99fb7..aa4fdff4 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html @@ -9,7 +9,7 @@

-
+
@@ -80,10 +80,14 @@ - + + +
+
+ diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index 9124bac3..709dfa6e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -63,6 +63,10 @@ import org.wicketstuff.datetime.markup.html.basic.DateLabel; import org.wicketstuff.select2.Select2Choice; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DRAFT; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.SAVED; + /** * @author mpostelnicu * Page used to make editing easy, extend to get easy access to one entity for editing @@ -78,10 +82,16 @@ public abstract class AbstractEditStatusEntityPage 0 - && Strings.isEqual(editForm.getModelObject().getStatus(), DBConstants.Status.DRAFT)) { + && Strings.isEqual(editForm.getModelObject().getStatus(), DRAFT)) { saveDraftContinueButton.add(getAutosaveBehavior()); autoSaveLabel.setVisibilityAllowed(true); if (target != null) { @@ -396,11 +468,11 @@ private String getStatusLabelClass() { } switch (editForm.getModelObject().getStatus()) { - case DBConstants.Status.APPROVED: + case PUBLISHED: return "label-success"; - case DBConstants.Status.DRAFT: + case DRAFT: return "label-danger"; - case DBConstants.Status.SUBMITTED: + case SAVED: return "label-warning"; default: return ""; @@ -423,6 +495,7 @@ public void onEvent(final IEvent event) { } }; checkBoxBootstrapFormComponent.setVisibilityAllowed(!isViewMode()); + checkBoxBootstrapFormComponent.setVisibilityAllowed(false); return checkBoxBootstrapFormComponent; } @@ -436,6 +509,7 @@ public void onEvent(final IEvent event) { } }; comment.setShowTooltip(true); + comment.setVisibilityAllowed(false); return comment; } @@ -491,7 +565,7 @@ protected String getOnClickScript() { protected void onSubmit(final AjaxRequestTarget target) { editForm.visitChildren(GenericBootstrapFormComponent.class, new AllowNullForCertainInvalidFieldsVisitor()); - setStatusAppendComment(DBConstants.Status.DRAFT); + setStatusAppendComment(DRAFT); super.onSubmit(target); } }; @@ -509,7 +583,7 @@ protected String getOnClickScript() { @Override protected void onSubmit(final AjaxRequestTarget target) { - setStatusAppendComment(DBConstants.Status.SUBMITTED); + setStatusAppendComment(SAVED); super.onSubmit(target); } }; @@ -528,7 +602,7 @@ protected String getOnClickScript() { @Override protected void onSubmit(final AjaxRequestTarget target) { - setStatusAppendComment(DBConstants.Status.SUBMITTED); + setStatusAppendComment(SAVED); super.onSubmit(target); } @@ -575,7 +649,7 @@ protected String getOnClickScript() { protected void onSubmit(final AjaxRequestTarget target) { editForm.visitChildren(GenericBootstrapFormComponent.class, new AllowNullForCertainInvalidFieldsVisitor()); - setStatusAppendComment(DBConstants.Status.DRAFT); + setStatusAppendComment(DRAFT); super.onSubmit(target); } @@ -595,8 +669,8 @@ protected PageParameters getParameterPage() { } private SaveEditPageButton getSaveApprovePageButton() { - final SaveEditPageButton saveEditPageButton = new SaveEditPageButton("approve", - new StringResourceModel("approve", this, null)) { + final SaveEditPageButton saveEditPageButton = new SaveEditPageButton("saveApprove", + new StringResourceModel("saveApprove", this, null)) { @Override protected String getOnClickScript() { @@ -605,7 +679,7 @@ protected String getOnClickScript() { @Override protected void onSubmit(final AjaxRequestTarget target) { - setStatusAppendComment(DBConstants.Status.APPROVED); + setStatusAppendComment(PUBLISHED); super.onSubmit(target); } }; @@ -613,23 +687,42 @@ protected void onSubmit(final AjaxRequestTarget target) { return saveEditPageButton; } + private SaveEditPageButton getApprovePageButton() { + final SaveEditPageButton saveEditPageButton = new SaveEditPageButton("approve", + new StringResourceModel("approve", this, null)) { + + @Override + protected void onSubmit(final AjaxRequestTarget target) { + approveModal.show(true); + target.add(approveModal); + } + + @Override + protected void onError(final AjaxRequestTarget target) { + super.onError(target); + target.add(feedbackPanel); + } + }; + saveEditPageButton.setIconType(FontAwesome5IconType.thumbs_up_s); + return saveEditPageButton; + } + protected SaveEditPageButton getRevertToDraftPageButton() { final SaveEditPageButton saveEditPageButton = new SaveEditPageButton("revertToDraft", new StringResourceModel("revertToDraft", this, null)) { + @Override - protected String getOnClickScript() { - return WebConstants.DISABLE_FORM_LEAVING_JS; + protected void onSubmit(final AjaxRequestTarget target) { + unpublishModal.show(true); + target.add(unpublishModal); } @Override - protected void onSubmit(final AjaxRequestTarget target) { - setStatusAppendComment(DBConstants.Status.DRAFT); - editForm.getModelObject().setRemoveLock(true); - super.onSubmit(target); - target.add(editForm); - setButtonsPermissions(); - onAfterRevertToDraft(target); + protected void onError(final AjaxRequestTarget target) { + super.onError(target); + target.add(feedbackPanel); } + }; saveEditPageButton.setIconType(FontAwesome5IconType.thumbs_down_s); return saveEditPageButton; @@ -660,7 +753,8 @@ protected void setButtonsPermissions() { addSaveButtonsPermissions(saveDraftContinueButton); addSaveButtonsPermissions(submitAndNext); addSaveButtonsPermissions(saveSubmitButton); - addApproveButtonPermissions(saveApproveButton); + addSaveApproveButtonPermissions(saveApproveButton); + addApproveButtonPermissions(approveButton); addSaveRevertButtonPermissions(revertToDraftPageButton); addDeleteButtonPermissions(deleteButton); @@ -670,6 +764,7 @@ protected void setButtonsPermissions() { submitAndNext.setVisibilityAllowed(false); saveSubmitButton.setVisibilityAllowed(false); saveApproveButton.setVisibilityAllowed(false); + approveButton.setVisibilityAllowed(false); revertToDraftPageButton.setVisibilityAllowed(false); } } @@ -686,19 +781,15 @@ protected void addSaveRevertButtonPermissions(final Component button) { MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, getValidatorRole()); MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, getCommaCombinedRoles()); button.setVisibilityAllowed(button.isVisibilityAllowed() - && !DBConstants.Status.DRAFT.equals(editForm.getModelObject().getStatus())); - - // additionally normal users should not revert anything that was already validated - if (FormSecurityUtil.isCurrentRoleOnlyUser(getUserRole(), getValidatorRole()) - && DBConstants.Status.APPROVED.equals(editForm.getModelObject().getStatus())) { - button.setVisibilityAllowed(false); - } else - - //admins can revert anything - if (FormSecurityUtil.isCurrentUserAdmin() - && DBConstants.Status.APPROVED.equals(editForm.getModelObject().getStatus())) { - button.setVisibilityAllowed(true); - } + && PUBLISHED.equals(editForm.getModelObject().getStatus())); + } + + protected void addSaveApproveButtonPermissions(final Component button) { + addDefaultAllButtonsPermissions(button); + MetaDataRoleAuthorizationStrategy.authorize( + button, Component.RENDER, getValidatorRole()); + button.setVisibilityAllowed(button.isVisibilityAllowed() + && DRAFT.equals(editForm.getModelObject().getStatus())); } protected void addApproveButtonPermissions(final Component button) { @@ -706,14 +797,14 @@ protected void addApproveButtonPermissions(final Component button) { MetaDataRoleAuthorizationStrategy.authorize( button, Component.RENDER, getValidatorRole()); button.setVisibilityAllowed(button.isVisibilityAllowed() - && DBConstants.Status.SUBMITTED.equals(editForm.getModelObject().getStatus())); + && SAVED.equals(editForm.getModelObject().getStatus())); } protected void addSaveButtonsPermissions(final Component button) { addDefaultAllButtonsPermissions(button); MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, getCommaCombinedRoles()); button.setVisibilityAllowed(button.isVisibilityAllowed() - && DBConstants.Status.DRAFT.equals(editForm.getModelObject().getStatus())); + && DRAFT.equals(editForm.getModelObject().getStatus())); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties index 97f5162f..c4471e42 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties @@ -9,10 +9,11 @@ # Contributors: # Development Gateway - initial API and implementation ############################################################################### -approve=Approve -revertToDraft=Reject to draft -saveButton=Save Draft -saveSubmit=Save & Submit +approve=Publish +revertToDraft=Unpublish +saveButton=Save as Draft +saveSubmit=Save +saveApprove=Save and Publish submitAndNext=Save and Next saveContinue=Save Draft & Continue newStatusComment.label=Update Comment diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html index 5cebebdc..64160afe 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html @@ -7,8 +7,8 @@
-
-
+
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index 96a66adf..83b254e5 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -1,29 +1,31 @@ package org.devgateway.toolkit.forms.wicket.page.edit.dataset; +import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.form.validation.AbstractFormValidator; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; -import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; +import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditStatusEntityPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; -import org.devgateway.toolkit.persistence.dao.data.DatasetStatus; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; +import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.wicketstuff.annotation.mount.MountPath; import java.math.BigDecimal; import static org.devgateway.toolkit.forms.WebConstants.MAXIMUM_PERCENTAGE; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; /** * @author vchihai */ @MountPath(value = "/editTetsimDataset") -public class EditTetsimDatasetPage extends AbstractEditPage { +public class EditTetsimDatasetPage extends AbstractEditStatusEntityPage { private static final long serialVersionUID = -8460878260874111506L; @@ -40,10 +42,6 @@ public EditTetsimDatasetPage(final PageParameters parameters) { protected void onInitialize() { super.onInitialize(); - if (editForm.getModelObject().isNew()) { - editForm.getModelObject().setStatus(DatasetStatus.DRAFT); - } - editForm.add(getYear()); editForm.add(getBaseLineNumbers()); editForm.add(getPriceAnalysisNumbers()); @@ -59,6 +57,30 @@ private TextFieldBootstrapFormComponent getYear() { return year; } + @Override + protected void onDelete(final AjaxRequestTarget target) { + try { + // save the object and go back to the list page + TetsimDataset saveable = editForm.getModelObject(); + saveable.setStatus(DELETED); + + beforeSaveEntity(saveable); + // saves the entity and flushes the changes + jpaService.saveAndFlush(saveable); + + // clears session and detaches all entities that are currently attached + entityManager.clear(); + + // we flush the mondrian/wicket/reports cache to ensure it gets rebuilt + flushReportingCaches(); + afterSaveEntity(saveable); + } catch (ObjectOptimisticLockingFailureException e) { + deleteFailedModal.show(target); + target.add(deleteFailedModal); + } + setResponsePage(listPageClass); + } + private TetsimBaselineNumbersPanel getBaseLineNumbers() { return new TetsimBaselineNumbersPanel("baseLineNumbers", editForm.getModel()); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.html index 3e3fa1e4..504031cd 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.html @@ -2,24 +2,23 @@ -
+

Base-line Numbers:

-
- - - - - - - - - - - -
Base-line NumbersUnitValues
-
+ + + + + + + + + + + + +
Base-line NumbersUnitValues
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.html index 6891b558..5fa933eb 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineVariable.html @@ -5,10 +5,10 @@ - + - +
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.html index 1903c0a1..4143c49f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.html @@ -2,22 +2,20 @@ -
+

Industry responses to the change in taxation:

-
- - - - - - - - -
-
-
+ + + + + + + + +
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.html index f0e5a201..d5551f50 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.html @@ -2,22 +2,20 @@ -
+

Price Analysis:

-
- - - - - - - - -
-
-
+ + + + + + + + +
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java index 3126cff4..7986e5fc 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java @@ -23,6 +23,7 @@ import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.wicket.components.table.filter.JpaFilterState; +import org.devgateway.toolkit.forms.wicket.components.table.filter.TetsimDatasetFilterState; import org.devgateway.toolkit.forms.wicket.page.edit.dataset.EditTetsimDatasetPage; import org.devgateway.toolkit.forms.wicket.page.lists.AbstractListPage; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; @@ -81,6 +82,6 @@ protected Component getRevisionsLink(final TetsimDataset entity) { @Override public JpaFilterState newFilterState() { - return new JpaFilterState<>(); + return new TetsimDatasetFilterState(); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css index f2391bb9..349bcee8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css @@ -29,6 +29,11 @@ body { border-radius: 0; } +.navbar-default { + height: 80px; + padding-top: 15px; +} + .mainHeader.with-navbar-fixed-top { /* * The mainHeader doesn't have any height when the navbar is fixed, and other elements are behind it. @@ -39,7 +44,7 @@ body { * @see: Navbar.Position.TOP * @see: bootstrap::navbar.less */ - min-height: 50px; + min-height: 80px; margin-bottom: 32px; } @@ -67,19 +72,26 @@ body { * The main page content should have some height. */ min-height: 20em; + padding-bottom: 40px; } .mainFooter { /* * Add some spacing around the footer. */ - margin-top: 2em; + margin-top: -20px; + padding: 20px 0; + min-height: 80px; position: absolute; bottom: 0; width: 100%; /* Set the fixed height of the footer here */ height: 50px; - background-color: #222; + background-color: #175372; +} + +.mainFooter .text-muted { + color: #acdef7; } /* file upload @@ -270,5 +282,6 @@ button .btn-home-label { } .feedbackPanel, .form-wrapper { - margin: 10px 5px 10px 10px; -} \ No newline at end of file + margin: 10px 5px 10px 0px; +} + diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractStatusAuditableEntity.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractStatusAuditableEntity.java index 534b4100..8f0f1ffb 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractStatusAuditableEntity.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractStatusAuditableEntity.java @@ -17,11 +17,16 @@ import java.util.ArrayList; import java.util.List; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DRAFT; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; + @MappedSuperclass public abstract class AbstractStatusAuditableEntity extends AbstractAuditableEntity implements Statusable { + @NotNull @Audited - private String status = DBConstants.Status.DRAFT; + private String status = DRAFT; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @@ -51,6 +56,11 @@ public abstract class AbstractStatusAuditableEntity extends AbstractAuditableEnt @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private Person checkedOutUser; + @JsonIgnore + public boolean isDeleted() { + return DELETED.equals(getStatus()); + } + @Override public String getStatus() { return status; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java index 47a40fd9..5c564bdd 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java @@ -23,10 +23,11 @@ private DBConstants() { public static final class Status { public static final String DRAFT = "DRAFT"; - public static final String SUBMITTED = "SUBMITTED"; - public static final String APPROVED = "APPROVED"; + public static final String SAVED = "SAVED"; + public static final String PUBLISHED = "PUBLISHED"; + public static final String DELETED = "DELETED"; - public static final String[] ALL = {DRAFT, SUBMITTED, APPROVED}; + public static final String[] ALL = {DRAFT, SAVED, PUBLISHED}; public static final List ALL_LIST = Collections.unmodifiableList(Arrays.asList(ALL)); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Statusable.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Statusable.java index b8cbdd2d..496d2a68 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Statusable.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Statusable.java @@ -2,6 +2,8 @@ import com.fasterxml.jackson.annotation.JsonIgnore; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; + /** * @author mihai *

@@ -12,4 +14,8 @@ public interface Statusable { String getStatus(); + @JsonIgnore + default boolean isPublished() { + return PUBLISHED.equals(getStatus()); + } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java index 1f397edf..5b967868 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java @@ -1,30 +1,20 @@ package org.devgateway.toolkit.persistence.dao.data; import org.devgateway.toolkit.persistence.dao.AbstractAuditableEntity; -import org.devgateway.toolkit.persistence.dao.Person; +import org.devgateway.toolkit.persistence.dao.AbstractStatusAuditableEntity; import org.hibernate.envers.Audited; -import javax.persistence.Column; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.FetchType; -import javax.persistence.ManyToOne; import javax.persistence.MappedSuperclass; import javax.validation.constraints.NotNull; import java.io.Serializable; @MappedSuperclass -public abstract class Dataset extends AbstractAuditableEntity implements Serializable { +public abstract class Dataset extends AbstractStatusAuditableEntity implements Serializable { @NotNull @Audited private Integer year; - @NotNull - @Audited - @Enumerated(EnumType.STRING) - private DatasetStatus status; - @Override public AbstractAuditableEntity getParent() { return null; @@ -38,12 +28,4 @@ public void setYear(final Integer year) { this.year = year; } - public DatasetStatus getStatus() { - return status; - } - - public void setStatus(final DatasetStatus status) { - this.status = status; - } - } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DatasetStatus.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DatasetStatus.java deleted file mode 100644 index ee9e5740..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/DatasetStatus.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.devgateway.toolkit.persistence.dao.data; - -public enum DatasetStatus { - - DRAFT("Draft"), - SAVED("Saved"), - PUBLISHED("Published"), - UNPUBLISHED("Unpublished"); - - private String label; - - DatasetStatus(final String label) { - this.label = label; - } - - public String getLabel() { - return label; - } -} From f977e43327928f2855380a1162e5de77821ee432 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 7 Jan 2022 15:02:53 +0200 Subject: [PATCH 016/137] TOBACCO-802: Add year valaidator --- .../edit/dataset/EditTetsimDatasetPage.html | 2 +- .../edit/dataset/EditTetsimDatasetPage.java | 18 ++++++++++++++++++ .../toolkit/persistence/dao/DBConstants.java | 3 +++ .../data/TetsimDatasetRepository.java | 8 +++++++- .../service/data/TetsimDatasetService.java | 7 ++++++- .../service/data/TetsimDatasetServiceImpl.java | 12 ++++++++++++ 6 files changed, 47 insertions(+), 3 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html index 64160afe..a2fa0ca7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html @@ -8,7 +8,7 @@

-
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index 83b254e5..52ef37fe 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -6,6 +6,10 @@ import org.apache.wicket.markup.html.form.validation.AbstractFormValidator; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.util.string.StringValue; +import org.apache.wicket.validation.validator.RangeValidator; +import org.devgateway.toolkit.forms.WebConstants; +import org.devgateway.toolkit.forms.validators.UniquePropertyValidator; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditStatusEntityPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; @@ -17,8 +21,12 @@ import org.wicketstuff.annotation.mount.MountPath; import java.math.BigDecimal; +import java.util.List; +import java.util.stream.Collectors; import static org.devgateway.toolkit.forms.WebConstants.MAXIMUM_PERCENTAGE; +import static org.devgateway.toolkit.persistence.dao.DBConstants.MAX_YEAR_DATASET; +import static org.devgateway.toolkit.persistence.dao.DBConstants.MIN_YEAR_DATASET; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; /** @@ -54,6 +62,15 @@ private TextFieldBootstrapFormComponent getYear() { final TextFieldBootstrapFormComponent year = new TextFieldBootstrapFormComponent<>("year"); year.required(); year.integer(); + year.getField().add(RangeValidator.range(MIN_YEAR_DATASET, MAX_YEAR_DATASET)); + + final StringValue id = getPageParameters().get(WebConstants.PARAM_ID); + List deletedIds = tetsimDatasetService.findAllDeleted().stream() + .map(TetsimDataset::getId) + .collect(Collectors.toList()); + deletedIds.add(id.toLong(-1L)); + year.getField().add(new UniquePropertyValidator<>(tetsimDatasetService, deletedIds,"year", this)); + return year; } @@ -105,6 +122,7 @@ public void validate(final Form form) { TetsimPriceVariable marketShare = editForm.getModelObject().getMarketShare(); BigDecimal sum = marketShare.getValues().stream() .map(TetsimTobaccoProductValue::getValue) + .filter(v -> v != null) .reduce(BigDecimal.ZERO, BigDecimal::add); if (sum.intValue() > MAXIMUM_PERCENTAGE) { diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java index 5c564bdd..8536f0d8 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java @@ -35,4 +35,7 @@ public static final class Status { public static final int STD_DEFAULT_TEXT_LENGTH = 255; public static final int MAX_DEFAULT_TEXT_LENGTH_ONE_LINE = 3000; public static final int MAX_DEFAULT_TEXT_AREA = 10000; + + public static final int MIN_YEAR_DATASET = 1900; + public static final int MAX_YEAR_DATASET = 2100; } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java index 6a709dec..6a48fd32 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java @@ -1,10 +1,16 @@ package org.devgateway.toolkit.persistence.repository.data; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.repository.norepository.UniquePropertyRepository; +import org.springframework.data.jpa.repository.Query; import javax.transaction.Transactional; +import java.util.List; @Transactional -public interface TetsimDatasetRepository extends DatasetRepository { +public interface TetsimDatasetRepository extends DatasetRepository, + UniquePropertyRepository { + @Query("select td from TetsimDataset td where td.status like 'DELETED'") + List findAllDeleted(); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java index 23f1b0f4..2a3fc9c5 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java @@ -2,6 +2,11 @@ import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.service.BaseJpaService; +import org.devgateway.toolkit.persistence.service.UniquePropertyService; -public interface TetsimDatasetService extends BaseJpaService { +import java.util.List; + +public interface TetsimDatasetService extends BaseJpaService, UniquePropertyService { + + List findAllDeleted(); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java index 87bed7e9..b50087d7 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java @@ -3,12 +3,15 @@ import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.repository.data.TetsimDatasetRepository; import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; +import org.devgateway.toolkit.persistence.repository.norepository.UniquePropertyRepository; import org.devgateway.toolkit.persistence.service.BaseJpaServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.List; + @Service @CacheConfig(cacheNames = "servicesCache") @Transactional(readOnly = true) @@ -27,4 +30,13 @@ protected BaseJpaRepository repository() { return tetsimDatasetRepository; } + @Override + public UniquePropertyRepository uniquePropertyRepository() { + return tetsimDatasetRepository; + } + + @Override + public List findAllDeleted() { + return tetsimDatasetRepository.findAllDeleted(); + } } From e4bcb1ac54db217966c92b4fa76ca9cd38a81b3e Mon Sep 17 00:00:00 2001 From: Styopa Semenukha Date: Wed, 12 Jan 2022 11:14:09 -0500 Subject: [PATCH 017/137] Add entrypoint --- Dockerfile | 4 ++-- forms/entrypoint.sh | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) create mode 100755 forms/entrypoint.sh diff --git a/Dockerfile b/Dockerfile index f2cf0fc4..2a65010c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ RUN mkdir -p /opt/tcdi/admin RUN mv */target/*-0.0.1-SNAPSHOT.jar /opt/tcdi/admin FROM openjdk:11-jre-slim -WORKDIR /opt/tcdi/admin +WORKDIR /opt/devgateway/tcdi/admin COPY --from=build /opt/tcdi/admin ./ EXPOSE 8080 -ENTRYPOINT ["java","-jar","/opt/tcdi/admin/tcdi-admin-forms-0.0.1-SNAPSHOT.jar"] +ENTRYPOINT ["/opt/devgateway/tcdi/admin/entrypoint.sh"] diff --git a/forms/entrypoint.sh b/forms/entrypoint.sh new file mode 100755 index 00000000..d995a3e8 --- /dev/null +++ b/forms/entrypoint.sh @@ -0,0 +1,14 @@ +#!/bin/sh +case "$1" in + admin) + JAVA_ARGS="$(tr '\n' ' ' <<-EOF + -cp .:lib/* + org.devgateway.toolkit.forms.wicket.FormsWebApplication + EOF + )" + exec java $JAVA_ARGS $@ + ;; + *) + exec $@ + ;; +esac From 0d0cdad0a6db4c817504651daf605353e0bbad8b Mon Sep 17 00:00:00 2001 From: Styopa Semenukha Date: Wed, 12 Jan 2022 11:47:24 -0500 Subject: [PATCH 018/137] Use unpacked JAR content in image --- Dockerfile | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/Dockerfile b/Dockerfile index 2a65010c..2f71df24 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,14 +1,9 @@ -FROM maven:3.8-jdk-11 AS build -RUN mkdir /tcdi-admin -WORKDIR /tcdi-admin -COPY . /tcdi-admin - -RUN mvn -B clean package -RUN mkdir -p /opt/tcdi/admin -RUN mv */target/*-0.0.1-SNAPSHOT.jar /opt/tcdi/admin - FROM openjdk:11-jre-slim WORKDIR /opt/devgateway/tcdi/admin -COPY --from=build /opt/tcdi/admin ./ +COPY target/deps/BOOT-INF/lib lib +COPY target/deps/META-INF META-INF +COPY entrypoint.sh ./ +COPY target/deps/BOOT-INF/classes . +USER nobody EXPOSE 8080 ENTRYPOINT ["/opt/devgateway/tcdi/admin/entrypoint.sh"] From a46bc1857f8761d55bb2a49c3b434fcd4db71904 Mon Sep 17 00:00:00 2001 From: Styopa Semenukha Date: Wed, 12 Jan 2022 11:50:19 -0500 Subject: [PATCH 019/137] Add Jenkinsfile --- Jenkinsfile | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Jenkinsfile diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 00000000..35446676 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,52 @@ +#!/usr/bin/env groovy +pipeline { + agent { label 'docker' } + + environment { + MAVEN_IMAGE = 'maven:3.8-jdk-11' + } + + stages { + + stage('Package') { + steps { + script { + def args = "-e JAVA_TOOL_OPTIONS=-Duser.home=$WORKSPACE_TMP" + withDockerContainer(image: env.MAVEN_IMAGE, args: args) { + sh 'mvn -B clean package -DskipTests && mkdir forms/target/deps' + dir('forms/target/deps') { + sh 'jar -xf ../*.jar' + } + } + } + } + } // Package + + stage('Build Image') { + steps { + dir('forms') { + script { + def image = 'registry.developmentgateway.org/tcdi/admin' + def tag = ['main', 'master'].contains(env.BRANCH_NAME) ? + 'latest' : + env.BRANCH_NAME.replaceAll('[^\\p{Alnum}-_]', '_').toLowerCase() + sh "docker build -t $image:$tag ." + } + } + } + } // Build Image + + stage('Publish Image') { + steps { + script { + def image = 'registry.developmentgateway.org/tcdi/admin' + def tag = ['main', 'master'].contains(env.BRANCH_NAME) ? + 'latest' : + env.BRANCH_NAME.replaceAll('[^\\p{Alnum}-_]', '_').toLowerCase() + sh "docker push $image:$tag" + } + } + } // Publish Image + + } // stages +} From aee204173cb904121fb776455424aab4ae8d90e9 Mon Sep 17 00:00:00 2001 From: Styopa Semenukha Date: Wed, 12 Jan 2022 11:53:14 -0500 Subject: [PATCH 020/137] Temporarily skip checkstyle --- Jenkinsfile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 35446676..d40453e9 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -13,7 +13,8 @@ pipeline { script { def args = "-e JAVA_TOOL_OPTIONS=-Duser.home=$WORKSPACE_TMP" withDockerContainer(image: env.MAVEN_IMAGE, args: args) { - sh 'mvn -B clean package -DskipTests && mkdir forms/target/deps' + // TODO + sh 'mvn -B clean package -DskipTests -Dcheckstyle.skip && mkdir forms/target/deps' dir('forms/target/deps') { sh 'jar -xf ../*.jar' } From 5218c430697d4c59913007f5ebae8609be34bb9a Mon Sep 17 00:00:00 2001 From: Styopa Semenukha Date: Wed, 12 Jan 2022 11:57:35 -0500 Subject: [PATCH 021/137] Correct Dockerfile path --- Jenkinsfile | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index d40453e9..b8240a56 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -25,14 +25,12 @@ pipeline { stage('Build Image') { steps { - dir('forms') { - script { - def image = 'registry.developmentgateway.org/tcdi/admin' - def tag = ['main', 'master'].contains(env.BRANCH_NAME) ? - 'latest' : - env.BRANCH_NAME.replaceAll('[^\\p{Alnum}-_]', '_').toLowerCase() - sh "docker build -t $image:$tag ." - } + script { + def image = 'registry.developmentgateway.org/tcdi/admin' + def tag = ['main', 'master'].contains(env.BRANCH_NAME) ? + 'latest' : + env.BRANCH_NAME.replaceAll('[^\\p{Alnum}-_]', '_').toLowerCase() + sh "docker build -t $image:$tag ." } } } // Build Image From 7dd83509cddf5d9678ab19edb34f6e54732b8651 Mon Sep 17 00:00:00 2001 From: Styopa Semenukha Date: Wed, 12 Jan 2022 12:04:50 -0500 Subject: [PATCH 022/137] Move Dockerfile to correct path --- docker-compose.override.yml | 4 ++++ docker-compose.yml | 1 - Dockerfile => forms/Dockerfile | 0 3 files changed, 4 insertions(+), 1 deletion(-) rename Dockerfile => forms/Dockerfile (100%) diff --git a/docker-compose.override.yml b/docker-compose.override.yml index d01e0d40..b4918546 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -1,6 +1,10 @@ version: '3' services: + admin: + build: + context: forms + postgres: volumes: - ./data/postgres:/var/lib/postgresql/data diff --git a/docker-compose.yml b/docker-compose.yml index bb6bd13a..5e3de2cd 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,7 +2,6 @@ version: '3' services: admin: - build: . depends_on: - postgres volumes: diff --git a/Dockerfile b/forms/Dockerfile similarity index 100% rename from Dockerfile rename to forms/Dockerfile From 8f091b38de0df495f47e6b0411c7dff3785e89f2 Mon Sep 17 00:00:00 2001 From: Styopa Semenukha Date: Wed, 12 Jan 2022 12:06:38 -0500 Subject: [PATCH 023/137] Revert "Correct Dockerfile path" This reverts commit 5218c430697d4c59913007f5ebae8609be34bb9a. --- Jenkinsfile | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index b8240a56..d40453e9 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -25,12 +25,14 @@ pipeline { stage('Build Image') { steps { - script { - def image = 'registry.developmentgateway.org/tcdi/admin' - def tag = ['main', 'master'].contains(env.BRANCH_NAME) ? - 'latest' : - env.BRANCH_NAME.replaceAll('[^\\p{Alnum}-_]', '_').toLowerCase() - sh "docker build -t $image:$tag ." + dir('forms') { + script { + def image = 'registry.developmentgateway.org/tcdi/admin' + def tag = ['main', 'master'].contains(env.BRANCH_NAME) ? + 'latest' : + env.BRANCH_NAME.replaceAll('[^\\p{Alnum}-_]', '_').toLowerCase() + sh "docker build -t $image:$tag ." + } } } } // Build Image From dfba520fd1d50283fbccd3ba2bf6e56cc73a2686 Mon Sep 17 00:00:00 2001 From: Styopa Semenukha Date: Thu, 13 Jan 2022 12:59:51 -0500 Subject: [PATCH 024/137] Update compose files --- docker-compose.override.yml | 2 +- docker-compose.yml | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/docker-compose.override.yml b/docker-compose.override.yml index b4918546..fe0c4067 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -1,4 +1,4 @@ -version: '3' +version: '3.4' services: admin: diff --git a/docker-compose.yml b/docker-compose.yml index 5e3de2cd..e64a7897 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,11 +1,10 @@ -version: '3' +version: '3.4' services: admin: + image: ${REPO}tcdi-admin/admin:${TAG-local} depends_on: - postgres - volumes: - - admin:/opt/tcdi/admin ports: - 8080:8080 logging: &json_file @@ -23,5 +22,4 @@ services: logging: *json_file volumes: - admin: null postgres: null From 3894502d41b0d109ee904c1de5bba685c629b7b6 Mon Sep 17 00:00:00 2001 From: Styopa Semenukha Date: Thu, 13 Jan 2022 13:03:13 -0500 Subject: [PATCH 025/137] Build & publish with Compose --- Jenkinsfile | 32 +++++++++++--------------------- 1 file changed, 11 insertions(+), 21 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index d40453e9..477f08dc 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -4,16 +4,18 @@ pipeline { environment { MAVEN_IMAGE = 'maven:3.8-jdk-11' + DOCKER_BUILDKIT = '1' + REPO = 'registry.developmentgateway.org/' } stages { - stage('Package') { + stage('Compile') { steps { script { def args = "-e JAVA_TOOL_OPTIONS=-Duser.home=$WORKSPACE_TMP" withDockerContainer(image: env.MAVEN_IMAGE, args: args) { - // TODO + // TODO: checkstyle sh 'mvn -B clean package -DskipTests -Dcheckstyle.skip && mkdir forms/target/deps' dir('forms/target/deps') { sh 'jar -xf ../*.jar' @@ -21,33 +23,21 @@ pipeline { } } } - } // Package + } // Compile - stage('Build Image') { - steps { - dir('forms') { - script { - def image = 'registry.developmentgateway.org/tcdi/admin' - def tag = ['main', 'master'].contains(env.BRANCH_NAME) ? - 'latest' : - env.BRANCH_NAME.replaceAll('[^\\p{Alnum}-_]', '_').toLowerCase() - sh "docker build -t $image:$tag ." - } - } - } - } // Build Image - - stage('Publish Image') { + stage('Package & Publish') { steps { script { - def image = 'registry.developmentgateway.org/tcdi/admin' def tag = ['main', 'master'].contains(env.BRANCH_NAME) ? 'latest' : env.BRANCH_NAME.replaceAll('[^\\p{Alnum}-_]', '_').toLowerCase() - sh "docker push $image:$tag" + withEnv(["TAG=$tag"]) { + def dc = 'docker-compose' + sh "$dc build admin && $dc push admin" + } } } - } // Publish Image + } // Package & Publish } // stages } From 0e483f77577b6054989534e97643dd78f7dba867 Mon Sep 17 00:00:00 2001 From: Styopa Semenukha Date: Thu, 13 Jan 2022 13:07:36 -0500 Subject: [PATCH 026/137] Deploy with Ansible --- Jenkinsfile | 25 ++++++++++++++++ deploy.yml | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 deploy.yml diff --git a/Jenkinsfile b/Jenkinsfile index 477f08dc..7366e50b 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -5,6 +5,7 @@ pipeline { environment { MAVEN_IMAGE = 'maven:3.8-jdk-11' DOCKER_BUILDKIT = '1' + PROJECT_TITLE = 'TCDI Admin' REPO = 'registry.developmentgateway.org/' } @@ -39,5 +40,29 @@ pipeline { } } // Package & Publish + stage('Deploy') { + when { branch 'develop' } + agent { label 'ansible' } + steps { + script { + def tag = ['main', 'master'].contains(env.BRANCH_NAME) ? + 'latest' : + env.BRANCH_NAME.replaceAll('[^\\p{Alnum}-_]', '_').toLowerCase() + ansiblePlaybook( + credentialsId: 'Deploy', + become: true, + playbook: 'deploy.yml', + skippedTags: 'provision', + extraVars: [ + project_title: env.PROJECT_TITLE, + repo: env.REPO, + tag: tag, + pull: "true" + ] + ) + } // script + } // steps + } + } // stages } diff --git a/deploy.yml b/deploy.yml new file mode 100644 index 00000000..48de8636 --- /dev/null +++ b/deploy.yml @@ -0,0 +1,84 @@ +--- +- name: Deploy + hosts: + - "{{ project_title | regex_replace('[^\\w_]', '_') | lower }}_{{ tag }}" + vars: + product: "{{ project_title | regex_replace('[^\\w_]', '_') | lower }}" + systemd_service: + Unit.Description: "{{ project_title }}" + Unit.After: docker.socket docker.service + Unit.BindsTo: docker.socket docker.service + Install.WantedBy: multi-user.target + Service.Type: exec + Service.ExecStart: /usr/bin/docker-compose --no-ansi up + Service.WorkingDirectory: "/opt/devgateway/{{ product }}" + Service.Environment: "TAG={{ tag }} REPO={{ repo }}" + + tasks: + + - name: Install packages + ansible.builtin.package: + name: + - firewalld + - docker-compose + tags: + - provision + + - name: Open firewall ports + ansible.posix.firewalld: + service: http + state: enabled + permanent: true + immediate: true + zone: public + tags: + - provision + + - name: Configure Systemd unit + community.general.ini_file: + path: /etc/systemd/system/{{ product }}.service + create: true + no_extra_spaces: true + section: "{{ item.key.split('.')[0] }}" + option: "{{ item.key.split('.')[1] }}" + value: "{{ item.value }}" + loop: "{{ systemd_service | dict2items }}" + loop_control: + label: "{{ item.key }}" + notify: + - Reload Systemd + + - name: Install Compose file + ansible.builtin.copy: + src: docker-compose.yml + dest: "{{ systemd_service['Service.WorkingDirectory'] }}/" + notify: + - Restart stack + + - name: Update images + ansible.builtin.command: + chdir: "{{ systemd_service['Service.WorkingDirectory'] }}" + cmd: /usr/bin/docker-compose pull --quiet + environment: + TAG: "{{ tag }}" + REPO: "{{ repo }}" + notify: + - Restart stack + when: pull | default(false) + + - name: Enable Compose service + ansible.builtin.service: + name: "{{ product }}" + enabled: true + state: started + + handlers: + + - name: Reload Systemd + ansible.builtin.systemd: + daemon_reload: true + + - name: Restart stack + ansible.builtin.service: + name: "{{ product }}" + state: restarted From abec218a3c5e82159579484f321de0856bbb3393 Mon Sep 17 00:00:00 2001 From: Styopa Semenukha Date: Thu, 13 Jan 2022 19:07:27 -0500 Subject: [PATCH 027/137] Provide default command --- forms/Dockerfile | 1 + 1 file changed, 1 insertion(+) diff --git a/forms/Dockerfile b/forms/Dockerfile index 2f71df24..7a8adca0 100644 --- a/forms/Dockerfile +++ b/forms/Dockerfile @@ -7,3 +7,4 @@ COPY target/deps/BOOT-INF/classes . USER nobody EXPOSE 8080 ENTRYPOINT ["/opt/devgateway/tcdi/admin/entrypoint.sh"] +CMD ["admin"] From 6cb586a36648735fecec09f1709b5499b3af829d Mon Sep 17 00:00:00 2001 From: Styopa Semenukha Date: Thu, 13 Jan 2022 19:11:26 -0500 Subject: [PATCH 028/137] Expose Java port 8080 at host port 80 --- docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yml b/docker-compose.yml index e64a7897..2e276350 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -6,7 +6,7 @@ services: depends_on: - postgres ports: - - 8080:8080 + - 80:8080 logging: &json_file driver: json-file From ea8962b623c67c1b06731b34274141a74d10085b Mon Sep 17 00:00:00 2001 From: Styopa Semenukha Date: Thu, 13 Jan 2022 19:18:11 -0500 Subject: [PATCH 029/137] Configure networking --- docker-compose.override.yml | 3 +++ docker-compose.yml | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/docker-compose.override.yml b/docker-compose.override.yml index fe0c4067..25439865 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -8,3 +8,6 @@ services: postgres: volumes: - ./data/postgres:/var/lib/postgresql/data + networks: &both + - backend + - frontend diff --git a/docker-compose.yml b/docker-compose.yml index 2e276350..703e8658 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -5,6 +5,9 @@ services: image: ${REPO}tcdi-admin/admin:${TAG-local} depends_on: - postgres + networks: + - backend + - frontend ports: - 80:8080 logging: &json_file @@ -15,6 +18,8 @@ services: restart: unless-stopped volumes: - postgres:/var/lib/postgresql/data + networks: + - backend environment: POSTGRES_PASSWORD: postgres POSTGRES_USER: postgres @@ -23,3 +28,8 @@ services: volumes: postgres: null + +networks: + backend: + frontend: + driver: bridge From b0a754798edb8112f835bf97e05902602b035898 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 14 Jan 2022 18:16:22 +0200 Subject: [PATCH 030/137] TOBACCO-812: Update log configuration --- forms/src/main/resources/logback.xml | 25 ++++++------------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/forms/src/main/resources/logback.xml b/forms/src/main/resources/logback.xml index c6cb063e..1c3e8ef0 100644 --- a/forms/src/main/resources/logback.xml +++ b/forms/src/main/resources/logback.xml @@ -1,30 +1,17 @@ - + + + - - ${LOG_DIR}/logger.log - - %d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n - - - - ${LOG_DIR}/logger.%d{yyyy-MM-dd}.%i.log - - - 64MB - - - 30 - - - + + @@ -36,6 +23,6 @@ - + From 2105c680fb4c0ea4cbbad2808669ab29416f0f20 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Sat, 15 Jan 2022 17:26:20 +0200 Subject: [PATCH 031/137] TOBACCO-812: Remove file appender --- forms/src/main/resources/logback.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forms/src/main/resources/logback.xml b/forms/src/main/resources/logback.xml index 1c3e8ef0..de0096fe 100644 --- a/forms/src/main/resources/logback.xml +++ b/forms/src/main/resources/logback.xml @@ -3,7 +3,7 @@ - + From f1bfac6f7d9f54d0fabf2ff04a8ea1bd92117df4 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 17 Jan 2022 11:56:25 +0200 Subject: [PATCH 032/137] TOBACCO-809: Add currencies --- .../wicket/page/EditAdminSettingsPage.html | 22 ++++++++-- .../wicket/page/EditAdminSettingsPage.java | 17 ++++++++ .../page/EditAdminSettingsPage.properties | 2 + ...nericPersistableJpaTextChoiceProvider.java | 9 ++++ .../persistence/dao/AdminSettings.java | 11 +++++ .../persistence/dao/categories/Currency.java | 11 +++++ .../category/CurrencyRepository.java | 9 ++++ .../service/category/CurrencyService.java | 9 ++++ .../service/category/CurrencyServiceImpl.java | 42 +++++++++++++++++++ .../main/resources/liquibase-changelog.xml | 13 ++++++ 10 files changed, 142 insertions(+), 3 deletions(-) create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Currency.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/CurrencyRepository.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyService.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyServiceImpl.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html index bd60a80b..d9f0152e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html @@ -12,11 +12,27 @@ [[System Settings]]
-
-
+
+
+
+
+
+
+
- +
+
+ + [[Application Settings]] +
+
+
+
+
+
+
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java index 88822a8d..b269c888 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java @@ -8,10 +8,15 @@ import org.apache.wicket.validation.validator.RangeValidator; import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.wicket.components.form.CheckBoxToggleBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; +import org.devgateway.toolkit.forms.wicket.providers.GenericPersistableJpaTextChoiceProvider; import org.devgateway.toolkit.persistence.dao.AdminSettings; +import org.devgateway.toolkit.persistence.dao.categories.Currency; import org.devgateway.toolkit.persistence.service.AdminSettingsService; +import org.devgateway.toolkit.persistence.service.category.CurrencyService; +import org.springframework.data.domain.Sort; import org.wicketstuff.annotation.mount.MountPath; import java.util.List; @@ -26,6 +31,9 @@ public class EditAdminSettingsPage extends AbstractEditPage { private static final long serialVersionUID = 5742724046825803877L; + @SpringBean + private CurrencyService currencyService; + private CheckBoxToggleBootstrapFormComponent rebootServer; private TextFieldBootstrapFormComponent autosaveTime; @@ -57,10 +65,19 @@ protected void onInitialize() { rebootServer = new CheckBoxToggleBootstrapFormComponent("rebootServer"); editForm.add(rebootServer); + editForm.add(new Label("appSettingsTitle", new StringResourceModel("appSettingsTitle", this, null))); + + Select2ChoiceBootstrapFormComponent currency = new Select2ChoiceBootstrapFormComponent<>( + "defaultCurrency", + new GenericPersistableJpaTextChoiceProvider<>(currencyService).setSort(Sort.Direction.ASC, "label")); + currency.required(); + editForm.add(currency); + autosaveTime = new TextFieldBootstrapFormComponent<>("autosaveTime"); autosaveTime.integer().required(); autosaveTime.getField().add(RangeValidator.range(0, 60)); autosaveTime.setShowTooltip(true); editForm.add(autosaveTime); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties index d38f9f8c..8eeab44e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties @@ -1,6 +1,8 @@ page.title=Admin settings page.title.add=Admin settings systemTitle=System Settings +appSettingsTitle=Application Settings rebootServer.label=Enable server reboot warning autosaveTime.label=Autosave Time (minutes) autosaveTime.help=Set to 0 to disable +defaultCurrency.label=Default Currency \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/providers/GenericPersistableJpaTextChoiceProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/providers/GenericPersistableJpaTextChoiceProvider.java index 3f5a0dc4..033eb93e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/providers/GenericPersistableJpaTextChoiceProvider.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/providers/GenericPersistableJpaTextChoiceProvider.java @@ -84,6 +84,15 @@ public void setExcludedIds(final Set excludedIds) { this.excludedIds = excludedIds; } + public GenericPersistableJpaTextChoiceProvider setSort(final Sort sort) { + this.sort = sort; + return this; + } + + public GenericPersistableJpaTextChoiceProvider setSort(final Sort.Direction direction, final String... properties) { + return this.setSort(Sort.by(direction, properties)); + } + @Override public String getIdValue(final T choice) { // if the object is not null but it hasn't an ID return 0 diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java index 48a5c594..05c4997d 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java @@ -1,5 +1,6 @@ package org.devgateway.toolkit.persistence.dao; +import org.devgateway.toolkit.persistence.dao.categories.Currency; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; @@ -27,6 +28,8 @@ public class AdminSettings extends AbstractAuditableEntity { private Integer autosaveTime = AUTOSAVE_TIME_DEFAULT; + private Currency defaultCurrency; + @Override public AbstractAuditableEntity getParent() { return null; @@ -59,4 +62,12 @@ public Integer getAutosaveTime() { public void setAutosaveTime(Integer autosaveTime) { this.autosaveTime = autosaveTime; } + + public Currency getDefaultCurrency() { + return defaultCurrency; + } + + public void setDefaultCurrency(final Currency defaultCurrency) { + this.defaultCurrency = defaultCurrency; + } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Currency.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Currency.java new file mode 100644 index 00000000..ed0fddf6 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Currency.java @@ -0,0 +1,11 @@ +package org.devgateway.toolkit.persistence.dao.categories; + +import org.hibernate.envers.Audited; + +import javax.persistence.Entity; + +@Entity +@Audited +public class Currency extends Category { + +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/CurrencyRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/CurrencyRepository.java new file mode 100644 index 00000000..659ffb35 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/CurrencyRepository.java @@ -0,0 +1,9 @@ +package org.devgateway.toolkit.persistence.repository.category; + +import org.devgateway.toolkit.persistence.dao.categories.Currency; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public interface CurrencyRepository extends CategoryRepository { + +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyService.java new file mode 100644 index 00000000..44b25338 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyService.java @@ -0,0 +1,9 @@ +package org.devgateway.toolkit.persistence.service.category; + +import org.devgateway.toolkit.persistence.dao.categories.Currency; +import org.devgateway.toolkit.persistence.service.BaseJpaService; +import org.devgateway.toolkit.persistence.service.TextSearchableService; + +public interface CurrencyService extends BaseJpaService, TextSearchableService { + +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyServiceImpl.java new file mode 100644 index 00000000..cf9aa93b --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyServiceImpl.java @@ -0,0 +1,42 @@ +package org.devgateway.toolkit.persistence.service.category; + +import org.devgateway.toolkit.persistence.dao.categories.Currency; +import org.devgateway.toolkit.persistence.repository.category.CurrencyRepository; +import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; +import org.devgateway.toolkit.persistence.repository.norepository.TextSearchableRepository; +import org.devgateway.toolkit.persistence.service.BaseJpaServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheConfig; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@CacheConfig(cacheNames = "servicesCache") +@Transactional(readOnly = true) +public class CurrencyServiceImpl extends BaseJpaServiceImpl implements CurrencyService { + + @Autowired + private CurrencyRepository currencyRepository; + + @Override + public Currency newInstance() { + return new Currency(); + } + + @Override + protected BaseJpaRepository repository() { + return currencyRepository; + } + + @Override + public TextSearchableRepository textRepository() { + return currencyRepository; + } + + @Override + public Sort getSort() { + return Sort.by(Sort.Direction.ASC, "label"); + } + +} diff --git a/persistence/src/main/resources/liquibase-changelog.xml b/persistence/src/main/resources/liquibase-changelog.xml index b72874b3..524b48bb 100644 --- a/persistence/src/main/resources/liquibase-changelog.xml +++ b/persistence/src/main/resources/liquibase-changelog.xml @@ -137,4 +137,17 @@ + + + + + + + + + + + + + \ No newline at end of file From c01a695d6a802a11765abee75c6b196ea009aa31 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 17 Jan 2022 11:56:51 +0200 Subject: [PATCH 033/137] TOBACCO-809: Set unit currency to variables --- .../edit/dataset/TetsimPriceAnalysisPanel.java | 14 +++++++++++--- .../dataset/TetsimPriceAnalysisPanel.properties | 6 +++--- .../dataset/TetsimTobaccoProductsVariable.java | 4 +++- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java index cc450ff8..43074d46 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java @@ -14,6 +14,7 @@ import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.service.AdminSettingsService; import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; import java.math.BigDecimal; @@ -31,6 +32,9 @@ public class TetsimPriceAnalysisPanel extends Panel { @SpringBean protected TobaccoProductService tobaccoProductService; + @SpringBean + protected AdminSettingsService adminSettingsService; + public TetsimPriceAnalysisPanel(final String id, final IModel tetsimDatasetIModel) { super(id); this.tetsimDatasetIModel = tetsimDatasetIModel; @@ -83,7 +87,7 @@ private RepeatingView getPriceAnalysisVariables() { private TetsimTobaccoProductsVariable getRetailPriceVariable(final String id) { return new TetsimTobaccoProductsVariable(id, new StringResourceModel("retailPrice.label"), - new StringResourceModel("retailPrice.unit"), + new StringResourceModel("retailPrice.unit").setParameters(getDefaultCurrency()), new PropertyModel<>(tetsimDatasetIModel, "retailPrice")) { @Override @@ -127,7 +131,7 @@ protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFor private TetsimTobaccoProductsVariable getCifVariable(final String id) { return new TetsimTobaccoProductsVariable(id, new StringResourceModel("cif.label"), - new StringResourceModel("cif.unit"), + new StringResourceModel("cif.unit").setParameters(getDefaultCurrency()), new PropertyModel<>(tetsimDatasetIModel, "cif")) { @Override @@ -170,7 +174,7 @@ protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFor private TetsimTobaccoProductsVariable getExciseTax(final String id) { return new TetsimTobaccoProductsVariable(id, new StringResourceModel("exciseTax.label"), - new StringResourceModel("exciseTax.unit"), + new StringResourceModel("exciseTax.unit").setParameters(getDefaultCurrency()), new PropertyModel<>(tetsimDatasetIModel, "exciseTax")) { @Override @@ -260,6 +264,10 @@ private TetsimTobaccoProductsVariable getChangeInIllicitNot(final String id) { }; } + private String getDefaultCurrency() { + return adminSettingsService.get().getDefaultCurrency().getLabel(); + } + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.properties index 41288c78..6ce36c81 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.properties @@ -1,17 +1,17 @@ retailPrice.label=Retail Price -retailPrice.unit={currency} per pack +retailPrice.unit={0} per pack marketShare.label=Market Share marketShare.unit=Percentage cif.label=CIF -cif.unit={currency} per pack +cif.unit={0} per pack tobaccoLevy.label=Tobacco Levy tobaccoLevy.unit=Percentage of CIF exciseTax.label=Excise tax -exciseTax.unit={currency} per pack +exciseTax.unit={0} per pack customsDuty.label=Customs duty on imported cigarettes customsDuty.unit=Percentage of FOB value diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.java index 690bf94a..1137ae04 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.java @@ -14,6 +14,7 @@ import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; +import java.util.HashSet; import java.util.List; import java.util.Set; @@ -99,7 +100,8 @@ protected RepeatingView createInputFields() { public TetsimTobaccoProductValue getTobaccoProductValue(final TetsimPriceVariable priceVariable, final TobaccoProduct product) { - Set tobaccoProductValues = priceVariable.getValues(); + Set tobaccoProductValues = priceVariable == null ? new HashSet<>() + : priceVariable.getValues(); TetsimTobaccoProductValue productValue = tobaccoProductValues.stream() .filter(t -> t.getProduct().getId().equals(product.getId())).findAny() From 9ed908c2f7d2529e77cdf18320889d52c4db5d46 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 17 Jan 2022 17:59:38 +0200 Subject: [PATCH 034/137] TOBACCO-810: Error message for no Tobacco Products --- .../wicket/page/edit/AbstractEditPage.java | 21 +++---- .../edit/AbstractEditStatusEntityPage.java | 8 +-- .../edit/dataset/EditTetsimDatasetPage.html | 12 ++++ .../edit/dataset/EditTetsimDatasetPage.java | 57 ++++++++++++++++++- .../edit/dataset/NoTobaccoProductsPanel.html | 15 +++++ .../edit/dataset/NoTobaccoProductsPanel.java | 22 +++++++ .../dataset/NoTobaccoProductsPanel.properties | 2 + .../dataset/TetsimBaselineNumbersPanel.html | 4 -- .../dataset/TetsimBaselineNumbersPanel.java | 11 +++- .../dataset/TetsimIndustryResponsesPanel.html | 3 - .../dataset/TetsimPriceAnalysisPanel.html | 20 +++---- 11 files changed, 135 insertions(+), 40 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.properties diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java index 625ea570..723322d1 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java @@ -298,21 +298,14 @@ public EditForm(final String id) { } protected BootstrapCancelButton getCancelButton(final String id) { - return new CancelEditPageButton(id, new StringResourceModel("cancelButton", this, null)); - } - - public class CancelEditPageButton extends BootstrapCancelButton { - private static final long serialVersionUID = -1474498211555760931L; + return new BootstrapCancelButton(id, new StringResourceModel("cancelButton", this, null)) { + private static final long serialVersionUID = -249084359200507749L; - public CancelEditPageButton(final String id, final IModel model) { - super(id, model); - } - - @Override - protected void onSubmit(final AjaxRequestTarget target) { - cancelModal.show(true); - target.add(cancelModal); - } + @Override + protected void onSubmit(final AjaxRequestTarget target) { + setResponsePage(listPageClass); + } + }; } /** diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index 709dfa6e..63588baf 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -76,15 +76,15 @@ public abstract class AbstractEditStatusEntityPage
+
+
+

Base-line Numbers:

+
+ +
+

Price Analysis:

+
+ +
+

Industry responses to the change in taxation:

+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index 52ef37fe..48e2a84e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -1,21 +1,26 @@ package org.devgateway.toolkit.forms.wicket.page.edit.dataset; +import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.form.validation.AbstractFormValidator; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.util.string.StringValue; import org.apache.wicket.validation.validator.RangeValidator; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.validators.UniquePropertyValidator; +import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditStatusEntityPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; +import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.wicketstuff.annotation.mount.MountPath; @@ -40,6 +45,9 @@ public class EditTetsimDatasetPage extends AbstractEditStatusEntityPage model) { + super(id, model); + } + + @Override + protected void onSubmit(final AjaxRequestTarget target) { + cancelModal.show(true); + target.add(cancelModal); + } + } + private TetsimBaselineNumbersPanel getBaseLineNumbers() { return new TetsimBaselineNumbersPanel("baseLineNumbers", editForm.getModel()); } - private TetsimPriceAnalysisPanel getPriceAnalysisNumbers() { + private Component getPriceAnalysisNumbers() { + if (tobaccoProductsNotDefined()) { + return new NoTobaccoProductsPanel("priceAnalysisNumbers"); + } + return new TetsimPriceAnalysisPanel("priceAnalysisNumbers", editForm.getModel()); } - private TetsimIndustryResponsesPanel getIndustryResponsesNumbers() { + private Component getIndustryResponsesNumbers() { + if (tobaccoProductsNotDefined()) { + return new NoTobaccoProductsPanel("industryResponsesNumbers"); + } + return new TetsimIndustryResponsesPanel("industryResponsesNumbers", editForm.getModel()); } @@ -130,4 +164,23 @@ public void validate(final Form form) { } } } + + private boolean tobaccoProductsNotDefined() { + return tobaccoProductService.count() == 0; + } + + @Override + protected void enableDisableAutosaveFields(final AjaxRequestTarget target) { + super.enableDisableAutosaveFields(target); + + if (tobaccoProductsNotDefined()) { + saveDraftContinueButton.setEnabled(false); + saveButton.setEnabled(false); + submitAndNext.setEnabled(false); + saveSubmitButton.setEnabled(false); + saveApproveButton.setEnabled(false); + approveButton.setEnabled(false); + revertToDraftPageButton.setEnabled(false); + } + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.html new file mode 100644 index 00000000..84387025 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.html @@ -0,0 +1,15 @@ + + + + + Edit TETSIM Datasets + + + +
+ + +
+
+ + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.java new file mode 100644 index 00000000..b4469533 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.java @@ -0,0 +1,22 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.dataset; + +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.link.BookmarkablePageLink; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.StringResourceModel; +import org.devgateway.toolkit.forms.wicket.page.lists.ListTobaccoProductPage; + +public class NoTobaccoProductsPanel extends Panel { + + public NoTobaccoProductsPanel(final String id) { + super(id); + } + + @Override + protected void onInitialize() { + super.onInitialize(); + add(new Label("message", getString("message"))); + add(new BookmarkablePageLink<>("link", ListTobaccoProductPage.class, null) + .setBody(new StringResourceModel("linkText"))); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.properties new file mode 100644 index 00000000..0f242097 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.properties @@ -0,0 +1,2 @@ +message=Please configure the +linkText=Tobacco Products \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.html index 504031cd..16481935 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.html @@ -2,10 +2,6 @@ -
-

Base-line Numbers:

-
- diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java index 3ff7a3a5..84b97954 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java @@ -5,14 +5,19 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.validators.PositiveBigDecimalValidator; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.service.AdminSettingsService; /** * @author Viorel Chihai */ public class TetsimBaselineNumbersPanel extends Panel { + @SpringBean + AdminSettingsService adminSettingsService; + protected final IModel tetsimDatasetIModel; public TetsimBaselineNumbersPanel(final String id, final IModel tetsimDatasetIModel) { @@ -62,7 +67,7 @@ private TetsimBaselineDecimalVariable getVatRateVariable(final String id) { private TetsimBaselineDecimalVariable getCigaretteDeclaredCustomValueVariable(final String id) { TetsimBaselineDecimalVariable variable = new TetsimBaselineDecimalVariable(id, new StringResourceModel("cigaretteDeclaredCustomValue.label"), - new StringResourceModel("cigaretteDeclaredCustomValue.unit"), + new StringResourceModel("cigaretteDeclaredCustomValue.unit").setParameters(getDefaultCurrency()), new PropertyModel<>(tetsimDatasetIModel, "cigaretteDeclaredCustomValue")); variable.getInputField().getField().add(new PositiveBigDecimalValidator(true)); @@ -90,6 +95,10 @@ private TetsimBaselineDecimalVariable getSmokingPrevalenceVariable(final String return variable; } + + private String getDefaultCurrency() { + return adminSettingsService.get().getDefaultCurrency().getLabel(); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.html index 4143c49f..aeef6abe 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.html @@ -2,9 +2,6 @@ -
-

Industry responses to the change in taxation:

-
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.html index d5551f50..db3ade0e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.html @@ -2,19 +2,15 @@ -
-

Price Analysis:

-
-
- - - - - - - + + + + + + +
-
+
From d9502e0a865cac331750851a25eaa053cec7578f Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 17 Jan 2022 18:07:57 +0200 Subject: [PATCH 035/137] TOBACCO-812: Update menu links --- .../toolkit/forms/wicket/page/BasePage.java | 54 +++++++++---------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 1c42da37..378b2647 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -261,30 +261,30 @@ protected List newSubMenuButtons(final String arg0) { new StringResourceModel("navbar.groups", this, null)) .setIconType(FontAwesome5IconType.tags_s)); - list.add(new MenuBookmarkablePageLink(ListTestFormPage.class, null, - new StringResourceModel("navbar.testcomponents", this, null)) - .setIconType(FontAwesome5IconType.android)); - - list.add(new MenuDivider()); - - final BootstrapBookmarkablePageLink swagger = new MenuBookmarkablePageLink(SwaggerPage.class, - new StringResourceModel("navbar.swagger", BasePage.this, null)) - .setIconType(FontAwesome5IconType.code_s); - MetaDataRoleAuthorizationStrategy.authorize(swagger, Component.RENDER, - SecurityConstants.Roles.ROLE_ADMIN); - list.add(swagger); - - final BootstrapBookmarkablePageLink javamelody = new MenuBookmarkablePageLink( - JavamelodyPage.class, new StringResourceModel("navbar.javamelody", - BasePage.this, null)).setIconType(FontAwesome5IconType.eye_s); - MetaDataRoleAuthorizationStrategy.authorize(javamelody, Component.RENDER, - SecurityConstants.Roles.ROLE_ADMIN); - list.add(javamelody); - - list.add(new MenuBookmarkablePageLink(SpringEndpointsPage.class, null, - new StringResourceModel("navbar.springendpoints", this, null)) - .setIconType(FontAwesome5IconType.anchor_s)); - +// list.add(new MenuBookmarkablePageLink(ListTestFormPage.class, null, +// new StringResourceModel("navbar.testcomponents", this, null)) +// .setIconType(FontAwesome5IconType.android)); + +// list.add(new MenuDivider()); +// +// final BootstrapBookmarkablePageLink swagger = new MenuBookmarkablePageLink(SwaggerPage.class, +// new StringResourceModel("navbar.swagger", BasePage.this, null)) +// .setIconType(FontAwesome5IconType.code_s); +// MetaDataRoleAuthorizationStrategy.authorize(swagger, Component.RENDER, +// SecurityConstants.Roles.ROLE_ADMIN); +// list.add(swagger); +// +// final BootstrapBookmarkablePageLink javamelody = new MenuBookmarkablePageLink( +// JavamelodyPage.class, new StringResourceModel("navbar.javamelody", +// BasePage.this, null)).setIconType(FontAwesome5IconType.eye_s); +// MetaDataRoleAuthorizationStrategy.authorize(javamelody, Component.RENDER, +// SecurityConstants.Roles.ROLE_ADMIN); +// list.add(javamelody); +// +// list.add(new MenuBookmarkablePageLink(SpringEndpointsPage.class, null, +// new StringResourceModel("navbar.springendpoints", this, null)) +// .setIconType(FontAwesome5IconType.anchor_s)); +// list.add(new MenuDivider()); list.add(new MenuBookmarkablePageLink(EditAdminSettingsPage.class, @@ -313,15 +313,15 @@ protected List newSubMenuButtons(final String arg0) { new StringResourceModel("navbar.tetsim", this, null)) .setIconType(FontAwesome5IconType.percentage_s)); - list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, + list.add(new MenuBookmarkablePageLink(DatasetsHomepage.class, null, new StringResourceModel("navbar.prevalence", this, null)) .setIconType(FontAwesome5IconType.users_s)); - list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, + list.add(new MenuBookmarkablePageLink(DatasetsHomepage.class, null, new StringResourceModel("navbar.policy", this, null)) .setIconType(FontAwesome5IconType.tasks_s)); - list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, + list.add(new MenuBookmarkablePageLink(DatasetsHomepage.class, null, new StringResourceModel("navbar.ecigarettes", this, null)) .setIconType(FontAwesome5IconType.smoking_s)); From b59e91b00061a44ebae8a72b4a3dddf62d1c7981 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 19 Jan 2022 11:08:44 +0200 Subject: [PATCH 036/137] TOBACCO-814: Remove datasets subitems --- .../toolkit/forms/wicket/page/BasePage.java | 31 +++---------------- 1 file changed, 4 insertions(+), 27 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 378b2647..e70c0e4d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -301,33 +301,10 @@ protected List newSubMenuButtons(final String arg0) { return adminMenu; } - protected NavbarDropDownButton newDatasetsMenu() { - NavbarDropDownButton dataSetsMenu = new NavbarDropDownButton( - new StringResourceModel("navbar.datasets", this, null)) { - private static final long serialVersionUID = 1L; - - @Override - protected List newSubMenuButtons(final String arg0) { - final List list = new ArrayList<>(); - list.add(new MenuBookmarkablePageLink(ListTetsimDatasetPage.class, null, - new StringResourceModel("navbar.tetsim", this, null)) - .setIconType(FontAwesome5IconType.percentage_s)); - - list.add(new MenuBookmarkablePageLink(DatasetsHomepage.class, null, - new StringResourceModel("navbar.prevalence", this, null)) - .setIconType(FontAwesome5IconType.users_s)); - - list.add(new MenuBookmarkablePageLink(DatasetsHomepage.class, null, - new StringResourceModel("navbar.policy", this, null)) - .setIconType(FontAwesome5IconType.tasks_s)); - - list.add(new MenuBookmarkablePageLink(DatasetsHomepage.class, null, - new StringResourceModel("navbar.ecigarettes", this, null)) - .setIconType(FontAwesome5IconType.smoking_s)); - - return list; - } - }; + protected NavbarButton newDatasetsMenu() { + NavbarButton dataSetsMenu = new NavbarButton(DatasetsHomepage.class, + new StringResourceModel("navbar.datasets", this, null)) + .setIconType(FontAwesome5IconType.table_s); dataSetsMenu.setIconType(FontAwesome5IconType.table_s); MetaDataRoleAuthorizationStrategy.authorize(dataSetsMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); From dd68e7b5d15235241657dc7c89afd951a470bcf4 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 19 Jan 2022 12:48:14 +0200 Subject: [PATCH 037/137] TOBACCO-791: Update date format for tetsim list page --- .../forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java index 7986e5fc..be0f50a8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java @@ -59,7 +59,7 @@ public ListTetsimDatasetPage(final PageParameters pageParameters) { public IModel getDataModel(final IModel rowModel) { IModel model = super.getDataModel(rowModel); ZonedDateTime modifiedDate = (ZonedDateTime) model.getObject(); - return Model.of(modifiedDate.format(DateTimeFormatter.ofPattern("dd/MM/yy"))); + return Model.of(modifiedDate.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"))); } }); columns.add(new PropertyColumn<>(new StringResourceModel("status"), "status", "status")); From 045e7d8731715b6f127d549b6ec6b2450632948c Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 20 Jan 2022 23:57:54 +0200 Subject: [PATCH 038/137] TOBACCO-798: Update the mechanism of setting the year to the dataset --- .../toolkit/forms/WebConstants.java | 1 + .../Select2ChoiceBootstrapFormComponent.java | 6 +- .../edit/AbstractEditStatusEntityPage.java | 2 - .../edit/dataset/EditTetsimDatasetPage.java | 43 ++++--- .../wicket/page/lists/AbstractListPage.html | 17 +++ .../wicket/page/lists/AbstractListPage.java | 7 +- .../lists/dataset/ListTetsimDatasetPage.html | 25 ++++ .../lists/dataset/ListTetsimDatasetPage.java | 115 ++++++++++++++++++ .../dataset/ListTetsimDatasetPage.properties | 7 +- .../forms/wicket/styles/BaseStyles.css | 3 + .../toolkit/persistence/dao/DBConstants.java | 2 - .../data/TetsimDatasetRepository.java | 5 + .../service/data/TetsimDatasetService.java | 2 + .../data/TetsimDatasetServiceImpl.java | 5 + .../toolkit/web/util/SettingsUtils.java | 14 +++ 15 files changed, 227 insertions(+), 27 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.html diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java index d14e3a1d..adfe3604 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java @@ -36,6 +36,7 @@ private WebConstants() { = "if(typeof disableFormLeavingConfirmation === 'function') disableFormLeavingConfirmation();"; public static final String PARAM_PRINT = "print"; + public static final String PARAM_YEAR = "year"; public static final String PARAM_ID = "id"; public static final String V_POSITION = "vPosition"; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/Select2ChoiceBootstrapFormComponent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/Select2ChoiceBootstrapFormComponent.java index 4a0a04f6..9730939f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/Select2ChoiceBootstrapFormComponent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/Select2ChoiceBootstrapFormComponent.java @@ -78,7 +78,7 @@ public String getUpdateEvent() { */ @Override protected void onInitialize() { - field.getSettings().setPlaceholder("Click to select"); + field.getSettings().setPlaceholder(getPlaceholder()); field.getSettings().setAllowClear(true); field.getSettings().setCloseOnSelect(true); field.getSettings().setDropdownAutoWidth(true); @@ -86,6 +86,10 @@ protected void onInitialize() { super.onInitialize(); } + protected String getPlaceholder() { + return "Click to select"; + } + @Override public void enableRevisionsView(final Class auditorClass, final EntityManager entityManager, diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index 63588baf..1ba05b15 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -52,12 +52,10 @@ import org.devgateway.toolkit.forms.wicket.components.form.OptionallyRequiredTextAreaFieldComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextAreaFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.util.ComponentUtil; -import org.devgateway.toolkit.forms.wicket.components.util.FormSecurityUtil; import org.devgateway.toolkit.forms.wicket.events.EditingDisabledEvent; import org.devgateway.toolkit.forms.wicket.page.BasePage; import org.devgateway.toolkit.forms.wicket.styles.BlockUiJavaScript; import org.devgateway.toolkit.persistence.dao.AbstractStatusAuditableEntity; -import org.devgateway.toolkit.persistence.dao.DBConstants; import org.devgateway.toolkit.persistence.dao.StatusChangedComment; import org.springframework.util.ObjectUtils; import org.wicketstuff.datetime.markup.html.basic.DateLabel; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index 48e2a84e..f62160d3 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -9,29 +9,24 @@ import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.util.string.StringValue; -import org.apache.wicket.validation.validator.RangeValidator; -import org.devgateway.toolkit.forms.WebConstants; -import org.devgateway.toolkit.forms.validators.UniquePropertyValidator; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; -import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditStatusEntityPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; +import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; +import org.devgateway.toolkit.web.util.SettingsUtils; import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.wicketstuff.annotation.mount.MountPath; import java.math.BigDecimal; -import java.util.List; -import java.util.stream.Collectors; import static org.devgateway.toolkit.forms.WebConstants.MAXIMUM_PERCENTAGE; -import static org.devgateway.toolkit.persistence.dao.DBConstants.MAX_YEAR_DATASET; -import static org.devgateway.toolkit.persistence.dao.DBConstants.MIN_YEAR_DATASET; +import static org.devgateway.toolkit.forms.WebConstants.PARAM_YEAR; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; /** @@ -42,9 +37,14 @@ public class EditTetsimDatasetPage extends AbstractEditStatusEntityPage year; + @SpringBean protected TetsimDatasetService tetsimDatasetService; + @SpringBean + protected SettingsUtils settingsUtils; + @SpringBean protected TobaccoProductService tobaccoProductService; @@ -64,20 +64,18 @@ protected void onInitialize() { editForm.add(getIndustryResponsesNumbers()); editForm.add(new TetsimMarketSharePercentageValidator()); + + if (editForm.getModelObject().isNew() && getYearParam() != null) { + editForm.getModelObject().setYear(getYearParam()); + } } - private TextFieldBootstrapFormComponent getYear() { - final TextFieldBootstrapFormComponent year = new TextFieldBootstrapFormComponent<>("year"); + private Select2ChoiceBootstrapFormComponent getYear() { + year = new Select2ChoiceBootstrapFormComponent<>("year", + new GenericChoiceProvider<>(settingsUtils.getYearsRange())); + editForm.add(year); year.required(); - year.integer(); - year.getField().add(RangeValidator.range(MIN_YEAR_DATASET, MAX_YEAR_DATASET)); - - final StringValue id = getPageParameters().get(WebConstants.PARAM_ID); - List deletedIds = tetsimDatasetService.findAllDeleted().stream() - .map(TetsimDataset::getId) - .collect(Collectors.toList()); - deletedIds.add(id.toLong(-1L)); - year.getField().add(new UniquePropertyValidator<>(tetsimDatasetService, deletedIds,"year", this)); + year.setEnabled(false); return year; } @@ -183,4 +181,9 @@ protected void enableDisableAutosaveFields(final AjaxRequestTarget target) { revertToDraftPageButton.setEnabled(false); } } + + protected Integer getYearParam() { + return getPageParameters().get(PARAM_YEAR).toOptionalInteger(); + } + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.html index 07e2b2dd..d7829743 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.html @@ -2,6 +2,12 @@ +
+
+ +
+
+
@@ -19,11 +25,22 @@
+
+
+ +
+
+ +
+
+ + +
\ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java index 3fc7c337..6f76ffc7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java @@ -27,6 +27,7 @@ import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.IFilteredColumn; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.panel.Fragment; import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.IModel; @@ -83,7 +84,7 @@ public abstract class AbstractListPage dataProvider; - private BootstrapBookmarkablePageLink editPageLink; + protected BootstrapBookmarkablePageLink editPageLink; protected Boolean filterGoReset = false; @@ -107,6 +108,9 @@ public ActionPanel getActionPanel(final String id, final IModel model) { protected void onInitialize() { super.onInitialize(); + Fragment fragment = new Fragment("bottomPageFragment", "noBottomPageFragment", this); + add(fragment); + if (jpaService == null) { throw new NullJpaServiceException(); } @@ -158,6 +162,7 @@ public void populateItem(final Item> cellItem, final String co editPageLink = new BootstrapBookmarkablePageLink("new", editPageClass, pageParameters, Buttons.Type.Success); editPageLink.setIconType(FontAwesome5IconType.plus_circle_s).setSize(Size.Large) .setLabel(new StringResourceModel("new", AbstractListPage.this, null)); + editPageLink.setOutputMarkupId(true); add(editPageLink); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.html new file mode 100644 index 00000000..88f7fdab --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.html @@ -0,0 +1,25 @@ + + + + + + +
+
+
+ +
+
+
+
+
+
+
+ +
+
+
+
+
+ + \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java index be0f50a8..264a7241 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java @@ -12,35 +12,58 @@ package org.devgateway.toolkit.forms.wicket.page.lists.dataset; import org.apache.wicket.Component; +import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.panel.Fragment; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.table.filter.JpaFilterState; import org.devgateway.toolkit.forms.wicket.components.table.filter.TetsimDatasetFilterState; import org.devgateway.toolkit.forms.wicket.page.edit.dataset.EditTetsimDatasetPage; import org.devgateway.toolkit.forms.wicket.page.lists.AbstractListPage; +import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; +import org.devgateway.toolkit.web.util.SettingsUtils; +import org.springframework.util.ObjectUtils; import org.wicketstuff.annotation.mount.MountPath; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; +import java.util.Collections; +import java.util.List; + +import static org.devgateway.toolkit.forms.WebConstants.PARAM_YEAR; @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) @MountPath(value = "/listTetsimDataset") public class ListTetsimDatasetPage extends AbstractListPage { private static final long serialVersionUID = -324298525712620234L; + private Integer selectedYear; + @SpringBean private TetsimDatasetService tetsimDatasetService; + @SpringBean + protected SettingsUtils settingsUtils; + + protected Select2ChoiceBootstrapFormComponent year; + + private Label addButtonError; + + protected Fragment yearSelectorFragment; + public ListTetsimDatasetPage(final PageParameters pageParameters) { super(pageParameters); this.jpaService = tetsimDatasetService; @@ -72,9 +95,101 @@ protected void onInitialize() { dataProvider.setSort("year", SortOrder.ASCENDING); + addNewYearSelector(); + + editPageLink.setEnabled(false); + excelForm.setVisibilityAllowed(false); } + private void addNewYearSelector() { + yearSelectorFragment = new Fragment("bottomPageFragment", "yearSelectorFragment", + ListTetsimDatasetPage.this); + replace(yearSelectorFragment); + + Form form = new Form<>("form"); + yearSelectorFragment.add(form); + + year = new Select2ChoiceBootstrapFormComponent("year", + new GenericChoiceProvider<>(getYearsNewData()), Model.of(selectedYear)) { + @Override + public String getPlaceholder() { + return "Select new year to add"; + } + + @Override + protected void onUpdate(final AjaxRequestTarget target) { + preparePageLinkButton(target); + } + }; + + year.setVisibilityAllowed(true); + year.hideLabel(); + form.add(year); + + Label helperTextYear = new Label("helperTextYear"); + form.add(helperTextYear); + + addButtonError = new Label("addButtonError"); + addButtonError.setOutputMarkupId(true); + addButtonError.setOutputMarkupPlaceholderTag(true); + addButtonError.setVisibilityAllowed(false); + form.add(addButtonError); + } + + protected List getYearsNewData() { + return settingsUtils.getYearsRange(); + } + + protected void preparePageLinkButton(final AjaxRequestTarget target) { + if (year.getModelObject() == null) { + addButtonError.setVisibilityAllowed(false); + editPageLink.setEnabled(false); + target.add(addButtonError, editPageLink); + return; + } + + List errors = getAddButtonErrors(); + + addButtonError.setVisibilityAllowed(!errors.isEmpty()); + addButtonError.setDefaultModel(Model.of(String.join("\n", errors))); + target.add(addButtonError); + + if (!errors.isEmpty()) { + editPageLink.setEnabled(false); + target.add(editPageLink); + return; + } + + if (!ObjectUtils.isEmpty(year.getModelObject())) { + editPageLink.setEnabled(true); + attachYearParameters(editPageLink.getPageParameters(), year.getModelObject()); + } else { + editPageLink.setEnabled(false); + } + + target.add(editPageLink); + } + + protected List getAddButtonErrors() { + long c = countByNonPublished(); + if (c > 0) { + return Collections.singletonList(getString("existingData")); + } else { + return Collections.emptyList(); + } + } + + protected long countByNonPublished() { + return tetsimDatasetService.countByNonPublished(year.getModelObject()); + } + + void attachYearParameters(PageParameters pageParameters, Integer year) { + if (year != null) { + pageParameters.set(PARAM_YEAR, year); + } + } + @Override protected Component getRevisionsLink(final TetsimDataset entity) { return new WebMarkupContainer("revisions").setVisibilityAllowed(false); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties index 56abb78d..214c43e5 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties @@ -3,4 +3,9 @@ year=Year lastModifiedBy=Editor lastModifiedDate=Latest Modification status=Status -actionsColumn=Action \ No newline at end of file +actionsColumn=Action + +year.label=Select Year +new=Add new dataset +helperTextYear=Select the year and then click on Add new dataset +existingData=There is already a dataset for the selected period. \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css index 349bcee8..8f44b972 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css @@ -285,3 +285,6 @@ button .btn-home-label { margin: 10px 5px 10px 0px; } +.error-row { + color: red; +} \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java index 8536f0d8..93b28c05 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java @@ -36,6 +36,4 @@ public static final class Status { public static final int MAX_DEFAULT_TEXT_LENGTH_ONE_LINE = 3000; public static final int MAX_DEFAULT_TEXT_AREA = 10000; - public static final int MIN_YEAR_DATASET = 1900; - public static final int MAX_YEAR_DATASET = 2100; } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java index 6a48fd32..fe09912d 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java @@ -3,6 +3,7 @@ import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.repository.norepository.UniquePropertyRepository; import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import javax.transaction.Transactional; import java.util.List; @@ -13,4 +14,8 @@ public interface TetsimDatasetRepository extends DatasetRepository findAllDeleted(); + + @Query ("select count(e) from #{#entityName} e where (:year is null or e.year=:year) " + + "and e.status not in ('DELETED')") + long countByNonPublished(@Param("year") Integer year); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java index 2a3fc9c5..c9c912ca 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java @@ -9,4 +9,6 @@ public interface TetsimDatasetService extends BaseJpaService, UniquePropertyService { List findAllDeleted(); + + long countByNonPublished(Integer year); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java index b50087d7..ad37141d 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java @@ -39,4 +39,9 @@ public UniquePropertyRepository uniquePropertyRepository() public List findAllDeleted() { return tetsimDatasetRepository.findAllDeleted(); } + + @Override + public long countByNonPublished(final Integer year) { + return tetsimDatasetRepository.countByNonPublished(year); + } } diff --git a/web/src/main/java/org/devgateway/toolkit/web/util/SettingsUtils.java b/web/src/main/java/org/devgateway/toolkit/web/util/SettingsUtils.java index 0e007e89..70baa8db 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/util/SettingsUtils.java +++ b/web/src/main/java/org/devgateway/toolkit/web/util/SettingsUtils.java @@ -10,7 +10,11 @@ import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; +import java.util.Calendar; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; /** * @author idobre @@ -20,6 +24,8 @@ public class SettingsUtils { protected static Logger logger = LoggerFactory.getLogger(SettingsUtils.class); + public static final int START_YEAR = 2000; + @Autowired private AdminSettingsService adminSettingsService; @@ -54,6 +60,14 @@ private void init() { } } + public List getYearsRange() { + return IntStream.rangeClosed(getStartYear(), Calendar.getInstance().get(Calendar.YEAR)). + boxed().sorted(Collections.reverseOrder()).collect(Collectors.toList()); + } + + public int getStartYear() { + return START_YEAR; + } public static final String DEFAULT_LANGUAGE = "en_US"; From e15a43866811fb4b3f3b9ec93c4ea7cddb961b5b Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 21 Jan 2022 00:01:31 +0200 Subject: [PATCH 039/137] TOBACCO-798: Fix max bigdecimal issue --- .../toolkit/forms/wicket/FormsWebApplication.java | 2 ++ .../NonNumericFilteredBigDecimalConverter.java | 13 ++++++++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java index 52e41489..d1b3ce3f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java @@ -45,6 +45,7 @@ import org.apache.wicket.request.resource.caching.version.CachingResourceVersion; import org.apache.wicket.settings.RequestCycleSettings.RenderStrategy; import org.apache.wicket.spring.injection.annot.SpringComponentInjector; +import org.apache.wicket.util.convert.converter.BigDecimalConverter; import org.apache.wicket.util.file.Folder; import org.devgateway.toolkit.forms.serializer.SpringDevToolsSerializer; import org.devgateway.toolkit.forms.service.SessionFinderService; @@ -114,6 +115,7 @@ public static void main(final String[] args) { protected IConverterLocator newConverterLocator() { ConverterLocator locator = (ConverterLocator) super.newConverterLocator(); locator.set(Double.class, new FormattedDoubleConverter(defaultDecimalFormatter)); + locator.set(BigDecimal.class, new NonNumericFilteredBigDecimalConverter(defaultDecimalFormatter)); locator.set(LocalDate.class, new LocalDateFormatter()); locator.set(ZonedDateTime.class, new ZonedDateTimeFormatter()); return locator; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/converters/NonNumericFilteredBigDecimalConverter.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/converters/NonNumericFilteredBigDecimalConverter.java index b20eece7..b6e0c057 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/converters/NonNumericFilteredBigDecimalConverter.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/converters/NonNumericFilteredBigDecimalConverter.java @@ -39,6 +39,8 @@ public class NonNumericFilteredBigDecimalConverter extends BigDecimalConverter { private static final long serialVersionUID = 1L; + private int MAX_SCALE_BIG_DECIMAL = 16; + private final INumberFormatter numberFormatter; public NonNumericFilteredBigDecimalConverter(final INumberFormatter numberFormatter) { @@ -53,10 +55,11 @@ protected NumberFormat newNumberFormat(final Locale locale) { @Override public BigDecimal convertToObject(final String value, final Locale locale) { - String newValue = value; - if (newValue != null) { - newValue = newValue.replaceAll("[^\\d\\.]", ""); - } - return super.convertToObject(newValue, locale); +// String newValue = value; +// if (newValue != null) { +// newValue = newValue.replaceAll("[^\\d\\.]", ""); +// } + + return parse(value, null, BigDecimal.TEN.scaleByPowerOfTen(MAX_SCALE_BIG_DECIMAL), locale); } } From f0e84b2037bc58c3f6cb7243dff0e1c635f7d1cf Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 21 Jan 2022 12:32:57 +0200 Subject: [PATCH 040/137] TOBACCO-792: Rename titles --- .../toolkit/forms/wicket/page/CategoriesHomepage.properties | 2 +- .../toolkit/forms/wicket/page/DatasetsHomepage.properties | 4 ++-- .../devgateway/toolkit/forms/wicket/page/Homepage.properties | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties index 7f6abb64..6ed88622 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties @@ -1,4 +1,4 @@ -page.title=South Africa categories +page.title=South Africa Categories tobaccoProducts.label=Tobacco Products tobaccoProducts.desc=Manage the tobacco products used in the system \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties index a0721f83..8771a822 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties @@ -1,4 +1,4 @@ -page.title=South Africa datasets +page.title=South Africa Datasets tetsimDataset.label=TETSIM -tetsimDataset.desc=Manage the TETSIM dataset \ No newline at end of file +tetsimDataset.desc=Manage the TETSIM Dataset \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties index 784b7bee..1cde229f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties @@ -1,5 +1,5 @@ -page.title=South Africa data admin module -welcome=South Africa data admin module +page.title=South Africa Data Admin Module +welcome=South Africa Data Admin Module datasets.label=Datasets datasets.desc=Upload, edit, revert to draft and validate Datasets From d91b00105c1ec54563da4dc64df59ac1bd9e2386 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 21 Jan 2022 19:13:27 +0200 Subject: [PATCH 041/137] TOBACCO-817: Display autosave when the action happens --- .../java/org/devgateway/toolkit/forms/WebConstants.java | 1 + .../wicket/page/edit/AbstractEditStatusEntityPage.java | 6 ++++-- .../page/edit/AbstractEditStatusEntityPage.properties | 2 +- .../persistence/converter/DefaultDecimalFormatter.java | 2 -- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java index adfe3604..ae58d7be 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java @@ -43,6 +43,7 @@ private WebConstants() { public static final String MAX_HEIGHT = "maxPosition"; public static final String PARAM_REVISION_ID = "revisionId"; public static final String PARAM_ENTITY_CLASS = "class"; + public static final String PARAM_AUTO_SAVE = "autosave"; public static final String LANGUAGE_PARAM = "lang"; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index 1ba05b15..d5a83a7b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -61,6 +61,7 @@ import org.wicketstuff.datetime.markup.html.basic.DateLabel; import org.wicketstuff.select2.Select2Choice; +import static org.devgateway.toolkit.forms.WebConstants.PARAM_AUTO_SAVE; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DRAFT; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.SAVED; @@ -422,7 +423,8 @@ private void addAutosaveBehavior(final AjaxRequestTarget target) { if (!ComponentUtil.isPrintMode() && adminSettingsService.getAutosaveTime() > 0 && Strings.isEqual(editForm.getModelObject().getStatus(), DRAFT)) { saveDraftContinueButton.add(getAutosaveBehavior()); - autoSaveLabel.setVisibilityAllowed(true); + boolean isAutoSaveVisible = getPageParameters().get(PARAM_AUTO_SAVE).toBoolean(false); + autoSaveLabel.setVisibilityAllowed(isAutoSaveVisible); if (target != null) { target.add(autoSaveLabel); } @@ -658,7 +660,7 @@ protected Class getResponsePage() { @Override protected PageParameters getParameterPage() { - return getPageParameters(); + return getPageParameters().set(PARAM_AUTO_SAVE, true); } }; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties index c4471e42..eb4bc9d7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties @@ -21,7 +21,7 @@ newStatusComment.help=Add a comment to describe this update during validation or PLEASE NOTE, text entered here will be viewable by anyone with access to this page. visibleStatusComments.label=View comments and form history autosave_message=Form is saving -autoSaveLabelMessage=Form auto-saved less than {0,number} minutes ago +autoSaveLabelMessage=Form auto-saved less than {0,number} minutes ago. checkedOutToMessage=Checked out to user {0}. removeLock.label=Force form check in removeLock.help=This will check back in a form that has been checked out by another user. Use this only if you know \ diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/converter/DefaultDecimalFormatter.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/converter/DefaultDecimalFormatter.java index 007d022f..c9bac36e 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/converter/DefaultDecimalFormatter.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/converter/DefaultDecimalFormatter.java @@ -19,8 +19,6 @@ public NumberFormat get(final Locale locale) { public DecimalFormat init(final Locale locale) { DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale); - decimalFormat.setMaximumFractionDigits(2); - decimalFormat.setMinimumFractionDigits(2); DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance(locale); decimalFormatSymbols.setDecimalSeparator('.'); From 9adf534f7c36cb89f52c2f9bc07eadbf18158c52 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 24 Jan 2022 17:49:17 +0200 Subject: [PATCH 042/137] TOBACCO-816: Enable modal buttons when autosave fails --- .../forms/wicket/page/edit/AbstractEditPage.html | 10 ++++++---- .../wicket/page/edit/AbstractEditStatusEntityPage.java | 3 +++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html index 1fd18ef8..247b7fa4 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html @@ -15,10 +15,12 @@
-
-
-
-
+
+
+
+
+
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index d5a83a7b..1839a5fd 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -447,8 +447,11 @@ protected void onTimer(final AjaxRequestTarget target) { + "$('#" + verticalPosition.getMarkupId() + "').val($(window).scrollTop()); " + "$('#" + saveDraftContinueButton.getMarkupId() + "').click();"); + target.prependJavaScript(getShowBlockUICode()); + // disable all buttons from js target.prependJavaScript("$('#" + editForm.getMarkupId() + " button').prop('disabled', true);"); + target.prependJavaScript("$('#modals button').prop('disabled', false);"); } }; From 3cdd4480cf4d5993cd6b5f9f2b2ad16dd656f869 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 24 Jan 2022 18:20:36 +0200 Subject: [PATCH 043/137] TOBACCO-813: Update categories menu --- .../toolkit/forms/wicket/page/BasePage.java | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index e70c0e4d..85ebef92 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -312,22 +312,11 @@ protected NavbarButton newDatasetsMenu() { return dataSetsMenu; } - protected NavbarDropDownButton newCategoriesMenu() { - NavbarDropDownButton categoriesMenu = new NavbarDropDownButton( - new StringResourceModel("navbar.categories", this, null)) { - private static final long serialVersionUID = 1L; - - @Override - protected List newSubMenuButtons(final String arg0) { - final List list = new ArrayList<>(); - list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, - new StringResourceModel("navbar.tobaccoproducts", this, null)) - .setIconType(FontAwesome5IconType.smoking_s)); - return list; - } - }; + protected NavbarButton newCategoriesMenu() { + NavbarButton categoriesMenu = new NavbarButton(CategoriesHomepage.class, + new StringResourceModel("navbar.categories", this, null)) + .setIconType(FontAwesome5IconType.list_alt_r); - categoriesMenu.setIconType(FontAwesome5IconType.list_alt_r); MetaDataRoleAuthorizationStrategy.authorize(categoriesMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); return categoriesMenu; From 74395f5afc56b5a0b96821f772350a247f8e2302 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 27 Jan 2022 16:07:59 +0200 Subject: [PATCH 044/137] TOBACCO-818: Don't add autosave behaviour when the form isnew --- .../forms/wicket/page/edit/AbstractEditStatusEntityPage.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index 1839a5fd..8e6c0b33 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -421,7 +421,8 @@ protected void enableDisableAutosaveFields(final AjaxRequestTarget target) { private void addAutosaveBehavior(final AjaxRequestTarget target) { // enable autosave if (!ComponentUtil.isPrintMode() && adminSettingsService.getAutosaveTime() > 0 - && Strings.isEqual(editForm.getModelObject().getStatus(), DRAFT)) { + && Strings.isEqual(editForm.getModelObject().getStatus(), DRAFT) + && !editForm.getModelObject().isNew()) { saveDraftContinueButton.add(getAutosaveBehavior()); boolean isAutoSaveVisible = getPageParameters().get(PARAM_AUTO_SAVE).toBoolean(false); autoSaveLabel.setVisibilityAllowed(isAutoSaveVisible); From ad126d7a288703600b7a66d2f040f075bde9b5f9 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 28 Jan 2022 11:51:44 +0200 Subject: [PATCH 045/137] TOBACCO-802: Hide delete button when dataset is published --- .../forms/wicket/page/edit/AbstractEditStatusEntityPage.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index 8e6c0b33..96af593f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -775,7 +775,8 @@ protected void setButtonsPermissions() { protected void addDeleteButtonPermissions(final Component button) { MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, SecurityConstants.Roles.ROLE_ADMIN); - button.setVisibilityAllowed(entityId != null && !isViewMode()); + button.setVisibilityAllowed(entityId != null && !isViewMode() + && !PUBLISHED.equals(editForm.getModelObject().getStatus())); MetaDataRoleAuthorizationStrategy.authorize( button, Component.RENDER, getCommaCombinedRoles()); } From 6bdd87b76c4198e3a3b5e4086dbca10bf69cef63 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Tue, 1 Feb 2022 15:03:29 +0200 Subject: [PATCH 046/137] TOBACCO-812: Fix checksyle issues --- checkstyle-suppressions.xml | 1 + checkstyle.xml | 16 ++++--- checkstyle/.gitignore | 1 - checkstyle/pom.xml | 26 ------------ .../checks/CachableQueryAnnotationCheck.java | 42 ------------------- .../src/main/resources/packagenames.xml | 10 ----- forms/pom.xml | 6 --- .../toolkit/forms/WarInitializer.java | 3 +- .../NullEditPageClassException.java | 10 ++--- .../NullListPageClassException.java | 10 ++--- .../forms/models/SubComponentWrapModel.java | 10 ++--- .../forms/security/SecurityConstants.java | 10 ++--- .../service/DerbyDatabaseBackupService.java | 19 ++++----- .../forms/service/SessionFinderService.java | 4 +- ...AbstractEarlierThanDateFieldValidator.java | 5 +-- .../AbstractEarlierThanDateValidator.java | 4 -- .../EarlierThanDateFieldValidator.java | 10 ++--- .../validators/EarlierThanDateValidator.java | 6 +-- .../forms/validators/YearValidator.java | 14 +++---- .../forms/wicket/FormsWebApplication.java | 5 --- .../wicket/SSAuthenticatedWebSession.java | 41 +++++++++--------- .../toolkit/forms/wicket/WebInitializer.java | 2 - .../wicket/components/CollapsablePanel.java | 2 +- .../form/BootstrapCancelButton.java | 14 +++---- .../form/BootstrapDeleteButton.java | 12 +++--- .../form/BootstrapSubmitButton.java | 13 +++--- .../form/CheckBoxBootstrapFormComponent.java | 3 +- .../CheckBoxPickerBootstrapFormComponent.java | 3 +- .../ColorPickerBootstrapFormComponent.java | 12 +++--- .../components/form/EditableTablePanel.java | 20 ++++----- .../form/GenericBootstrapFormComponent.java | 12 +----- ...GenericEnablingBootstrapFormComponent.java | 22 +++++----- ...PercentageFieldBootstrapFormComponent.java | 14 +++---- .../Select2ChoiceBootstrapFormComponent.java | 2 - ...actBootstrapPagingNavigationWithError.java | 2 +- .../table/AjaxBootstrapNavigator.java | 2 - .../table/PagingNavigationFactory.java | 1 - ...NonNumericFilteredBigDecimalConverter.java | 2 +- .../wicket/events/EditingDisabledEvent.java | 3 +- .../wicket/events/EditingEnabledEvent.java | 3 +- .../toolkit/forms/wicket/page/BasePage.java | 19 ++++----- .../forms/wicket/page/JavamelodyPage.java | 2 - .../forms/wicket/page/RevisionsPage.java | 1 - .../wicket/page/SpringEndpointsPage.java | 10 ++--- .../dataset/TetsimBaselineNumbersPanel.java | 2 +- .../TetsimBaselineNumbersPanel.properties | 2 +- .../page/lists/ListTobaccoProductPage.java | 7 ---- .../lists/dataset/ListTetsimDatasetPage.java | 16 +++---- ...nericPersistableJpaTextChoiceProvider.java | 3 +- .../converter/INumberFormatter.java | 2 +- .../dao/AbstractStatusAuditableEntity.java | 1 - .../toolkit/persistence/dao/FileContent.java | 1 - .../toolkit/persistence/dao/FileMetadata.java | 1 - .../toolkit/persistence/dao/JsonViews.java | 2 - .../toolkit/persistence/dao/Person.java | 1 - .../toolkit/persistence/dao/Role.java | 1 - .../toolkit/persistence/dao/TestForm.java | 1 - .../persistence/dao/categories/Category.java | 1 - .../persistence/dao/categories/Group.java | 2 - .../persistence/dao/data/TetsimDataset.java | 36 ++++++++-------- .../data/TetsimDatasetRepository.java | 4 +- .../service/AdminSettingsServiceImpl.java | 4 +- .../service/BaseJpaServiceImpl.java | 2 - .../service/FileMetadataServiceImpl.java | 1 - .../service/PersonServiceImpl.java | 1 - .../persistence/service/RoleServiceImpl.java | 1 - .../service/TestFormServiceImpl.java | 1 - .../service/category/GroupServiceImpl.java | 1 - .../category/TobaccoProductServiceImpl.java | 1 - .../spring/CacheConfiguration.java | 6 --- .../spring/DatabaseConfiguration.java | 1 - pom.xml | 35 ++++++---------- .../web/excelcharts/util/XSSFChartUtil.java | 24 +++++------ .../toolkit/web/util/SettingsUtils.java | 15 ++----- 74 files changed, 205 insertions(+), 400 deletions(-) delete mode 100644 checkstyle/.gitignore delete mode 100644 checkstyle/pom.xml delete mode 100644 checkstyle/src/main/java/org/devgateway/toolkit/checks/CachableQueryAnnotationCheck.java delete mode 100644 checkstyle/src/main/resources/packagenames.xml diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml index dc2ebe72..0a8e36a1 100644 --- a/checkstyle-suppressions.xml +++ b/checkstyle-suppressions.xml @@ -7,6 +7,7 @@ + diff --git a/checkstyle.xml b/checkstyle.xml index 7416a841..3d334b4b 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -10,12 +10,13 @@ --> + + + - - @@ -43,10 +44,7 @@ - - - - + @@ -58,6 +56,7 @@ + @@ -97,12 +96,12 @@ - + @@ -112,12 +111,11 @@ - + - diff --git a/checkstyle/.gitignore b/checkstyle/.gitignore deleted file mode 100644 index b83d2226..00000000 --- a/checkstyle/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target/ diff --git a/checkstyle/pom.xml b/checkstyle/pom.xml deleted file mode 100644 index fc9c04af..00000000 --- a/checkstyle/pom.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - 4.0.0 - - checkstyle - org.devgateway.toolkit - 1.0 - - - UTF-8 - 8 - 8 - 3.0.0 - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${maven-checkstyle-plugin.version} - - - - diff --git a/checkstyle/src/main/java/org/devgateway/toolkit/checks/CachableQueryAnnotationCheck.java b/checkstyle/src/main/java/org/devgateway/toolkit/checks/CachableQueryAnnotationCheck.java deleted file mode 100644 index 1671cdfd..00000000 --- a/checkstyle/src/main/java/org/devgateway/toolkit/checks/CachableQueryAnnotationCheck.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.devgateway.toolkit.checks; - -import com.puppycrawl.tools.checkstyle.api.AbstractCheck; -import com.puppycrawl.tools.checkstyle.api.DetailAST; -import com.puppycrawl.tools.checkstyle.api.TokenTypes; -import com.puppycrawl.tools.checkstyle.utils.AnnotationUtility; - -/** - * Checks that the methods of all classes annotated with @CacheableHibernateQueryResult - * are explicitly annotated to cache or not the query result. - * - * Anytime a new method is defined this will catch a potential missing caching definition. - * - * @author Nadejda Mandrescu - */ -public class CachableQueryAnnotationCheck extends AbstractCheck { - private static final String ERROR_MESSAGE = - "@CacheableHibernateQueryResult must annotate its methods explicitly either with " + - "@CacheHibernateQueryResult or @NoCacheHibernateQueryResult"; - - @Override - public int[] getDefaultTokens() { - return new int[]{TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF}; - } - - @Override - public void visitToken(DetailAST ast) { - if (AnnotationUtility.containsAnnotation(ast, "CacheableHibernateQueryResult")) { - DetailAST objBlock = ast.findFirstToken(TokenTypes.OBJBLOCK); - DetailAST methodDef = objBlock.findFirstToken(TokenTypes.METHOD_DEF); - while (methodDef != null) { - if (methodDef.getType() == TokenTypes.METHOD_DEF) { - if (!(AnnotationUtility.containsAnnotation(methodDef, "CacheHibernateQueryResult") - || AnnotationUtility.containsAnnotation(methodDef, "NoCacheHibernateQueryResult"))) { - log(methodDef.getLineNo(), ERROR_MESSAGE); - } - } - methodDef = methodDef.getNextSibling(); - } - } - } -} diff --git a/checkstyle/src/main/resources/packagenames.xml b/checkstyle/src/main/resources/packagenames.xml deleted file mode 100644 index bb173ad8..00000000 --- a/checkstyle/src/main/resources/packagenames.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - diff --git a/forms/pom.xml b/forms/pom.xml index 81f12a28..e919bf10 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -55,12 +55,6 @@ true - - org.springframework.boot - spring-boot-devtools - true - - org.devgateway.tcdi tcdi-admin-web diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/WarInitializer.java b/forms/src/main/java/org/devgateway/toolkit/forms/WarInitializer.java index ab641f75..a00580a0 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/WarInitializer.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/WarInitializer.java @@ -17,9 +17,8 @@ /** * Allows the app to deployed as Servlet 3.0 WAR - * - * @author mpostelnicu * + * @author mpostelnicu */ public class WarInitializer extends SpringBootServletInitializer { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/exceptions/NullEditPageClassException.java b/forms/src/main/java/org/devgateway/toolkit/forms/exceptions/NullEditPageClassException.java index 4252babd..ee95d617 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/exceptions/NullEditPageClassException.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/exceptions/NullEditPageClassException.java @@ -1,16 +1,16 @@ -/******************************************************************************* +/** * Copyright (c) 2015 Development Gateway, Inc and others. - * + *

* All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT - * + *

* Contributors: * Development Gateway - initial API and implementation - *******************************************************************************/ + */ /** - * + * */ package org.devgateway.toolkit.forms.exceptions; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/exceptions/NullListPageClassException.java b/forms/src/main/java/org/devgateway/toolkit/forms/exceptions/NullListPageClassException.java index 496ee949..80281d27 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/exceptions/NullListPageClassException.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/exceptions/NullListPageClassException.java @@ -1,16 +1,16 @@ -/******************************************************************************* +/** * Copyright (c) 2015 Development Gateway, Inc and others. - * + *

* All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT - * + *

* Contributors: * Development Gateway - initial API and implementation - *******************************************************************************/ + */ /** - * + * */ package org.devgateway.toolkit.forms.exceptions; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/models/SubComponentWrapModel.java b/forms/src/main/java/org/devgateway/toolkit/forms/models/SubComponentWrapModel.java index 194fe406..9de6bf91 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/models/SubComponentWrapModel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/models/SubComponentWrapModel.java @@ -1,16 +1,16 @@ -/******************************************************************************* +/** * Copyright (c) 2015 Development Gateway, Inc and others. - * + *

* All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT - * + *

* Contributors: * Development Gateway - initial API and implementation - *******************************************************************************/ + */ /** - * + * */ package org.devgateway.toolkit.forms.models; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/security/SecurityConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/security/SecurityConstants.java index 220de14d..774b518f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/security/SecurityConstants.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/security/SecurityConstants.java @@ -1,16 +1,16 @@ -/******************************************************************************* +/** * Copyright (c) 2015 Development Gateway, Inc and others. - * + *

* All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT - * + *

* Contributors: * Development Gateway - initial API and implementation - *******************************************************************************/ + */ /** - * + * */ package org.devgateway.toolkit.forms.security; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/DerbyDatabaseBackupService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/DerbyDatabaseBackupService.java index 68a0026c..3352a52a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/DerbyDatabaseBackupService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/DerbyDatabaseBackupService.java @@ -32,17 +32,15 @@ /** * @author mpostelnicu Provides built-in backup services. Defaults to the - * database location derby.system.home. Currently works only for Derby. - * Runs 9PM daily (good backup time for both EST and CET) + * database location derby.system.home. Currently works only for Derby. + * Runs 9PM daily (good backup time for both EST and CET) */ @Service public class DerbyDatabaseBackupService { - private static final Logger logger = LoggerFactory.getLogger(DerbyDatabaseBackupService.class); - public static final String DATABASE_PRODUCT_NAME_APACHE_DERBY = "Apache Derby"; public static final String ARCHIVE_SUFFIX = ".zip"; - + private static final Logger logger = LoggerFactory.getLogger(DerbyDatabaseBackupService.class); @Autowired private DataSource datasource; @@ -89,9 +87,8 @@ public void backupDatabase() { * last leaf of backup's location parent directory + {@link #databaseName} * If the backupPath does not have a parent, it uses the host name from * {@link InetAddress#getLocalHost()} - * - * @param backupPath - * the parent directory for the backup + * + * @param backupPath the parent directory for the backup * @return the backup url to be used by the backup procedure * @throws UnknownHostException */ @@ -121,7 +118,7 @@ private String createBackupURL(final String backupPath) { * Use backup.home system variable, if exists, as homedir for backups If * backup.home does not exist try using derby.system.home If that is also * null, use user.dir - * + * * @return the backupURL */ private String createBackupURL() { @@ -138,11 +135,11 @@ private String createBackupURL() { /** * Backup the On-Line Derby database. This temporarily locks the db in * readonly mode - * + *

* Invokes SYSCS_BACKUP_DATABASE and dumps the database to the temporary * directory Use {@link ZipUtil#pack(File, File)} to zip the directory * Deletes the temporary directory - * + * * @see #createBackupURL(String) */ private void backupDerbyDatabase() { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/SessionFinderService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/SessionFinderService.java index 909253e0..760f5c35 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/SessionFinderService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/SessionFinderService.java @@ -22,7 +22,7 @@ /** * Spring Service allowing access to hibernate session. This is needed by * {@link DozerModel} - * + * * @author mpostelnicu * @see DozerModel */ @@ -34,7 +34,7 @@ public class SessionFinderService implements SessionFinder { /* * (non-Javadoc) - * + * * @see * nl.dries.wicket.hibernate.dozer.SessionFinder#getHibernateSession(java * .lang.Class) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/validators/AbstractEarlierThanDateFieldValidator.java b/forms/src/main/java/org/devgateway/toolkit/forms/validators/AbstractEarlierThanDateFieldValidator.java index 031dbfb3..114a5cb0 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/validators/AbstractEarlierThanDateFieldValidator.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/validators/AbstractEarlierThanDateFieldValidator.java @@ -5,12 +5,9 @@ import org.apache.wicket.validation.ValidationError; import org.devgateway.toolkit.forms.wicket.components.form.AbstractDateFieldBootstrapFormComponent; -import java.time.LocalDate; -import java.util.Date; - /** * @author mpostelnicu {@link AbstractDateFieldBootstrapFormComponent} validator for - * dates that have a chronology + * dates that have a chronology */ public abstract class AbstractEarlierThanDateFieldValidator implements IValidator { private static final long serialVersionUID = 5915013097774040799L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/validators/AbstractEarlierThanDateValidator.java b/forms/src/main/java/org/devgateway/toolkit/forms/validators/AbstractEarlierThanDateValidator.java index 68c4f428..b2a3ddf1 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/validators/AbstractEarlierThanDateValidator.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/validators/AbstractEarlierThanDateValidator.java @@ -1,13 +1,9 @@ package org.devgateway.toolkit.forms.validators; -import org.apache.poi.ss.formula.functions.T; import org.apache.wicket.validation.IValidatable; import org.apache.wicket.validation.IValidator; import org.apache.wicket.validation.ValidationError; -import java.time.LocalDate; -import java.util.Date; - /** * Validator to test if the date is earlier than provided high date * diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/validators/EarlierThanDateFieldValidator.java b/forms/src/main/java/org/devgateway/toolkit/forms/validators/EarlierThanDateFieldValidator.java index 03f51ce4..0fa38520 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/validators/EarlierThanDateFieldValidator.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/validators/EarlierThanDateFieldValidator.java @@ -1,16 +1,16 @@ -/******************************************************************************* +/** * Copyright (c) 2015 Development Gateway, Inc and others. - * + *

* All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT - * + *

* Contributors: * Development Gateway - initial API and implementation - *******************************************************************************/ + */ /** - * + * */ package org.devgateway.toolkit.forms.validators; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/validators/EarlierThanDateValidator.java b/forms/src/main/java/org/devgateway/toolkit/forms/validators/EarlierThanDateValidator.java index 68e11b2f..5cb11154 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/validators/EarlierThanDateValidator.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/validators/EarlierThanDateValidator.java @@ -11,15 +11,11 @@ *******************************************************************************/ package org.devgateway.toolkit.forms.validators; -import org.apache.wicket.validation.IValidatable; -import org.apache.wicket.validation.IValidator; -import org.apache.wicket.validation.ValidationError; - import java.util.Date; /** * Validator to test if the date is earlier than provided high date - * + * * @author idobre * @since 5/18/15 */ diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/validators/YearValidator.java b/forms/src/main/java/org/devgateway/toolkit/forms/validators/YearValidator.java index 8c605edd..32f111c7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/validators/YearValidator.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/validators/YearValidator.java @@ -1,25 +1,25 @@ -/******************************************************************************* +/** * Copyright (c) 2015 Development Gateway, Inc and others. - * + *

* All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT - * + *

* Contributors: * Development Gateway - initial API and implementation - *******************************************************************************/ + */ /** - * + * */ package org.devgateway.toolkit.forms.validators; -import java.util.Calendar; - import org.apache.wicket.validation.IValidatable; import org.apache.wicket.validation.IValidator; import org.apache.wicket.validation.ValidationError; +import java.util.Calendar; + /** * @author mpostelnicu Validates an Integer input to be a valid year Returns * errors when this is not true diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java index d1b3ce3f..fa850d6c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java @@ -17,14 +17,11 @@ import de.agilecoders.wicket.core.request.resource.caching.version.Adler32ResourceVersion; import de.agilecoders.wicket.core.settings.BootstrapSettings; import de.agilecoders.wicket.core.settings.IBootstrapSettings; -import de.agilecoders.wicket.core.settings.ThemeProvider; import de.agilecoders.wicket.extensions.javascript.GoogleClosureJavaScriptCompressor; import de.agilecoders.wicket.extensions.javascript.YuiCssCompressor; import de.agilecoders.wicket.extensions.markup.html.bootstrap.editor.SummernoteConfig; import de.agilecoders.wicket.extensions.markup.html.bootstrap.editor.SummernoteStoredImageResourceReference; import de.agilecoders.wicket.less.BootstrapLess; -import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchTheme; -import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchThemeProvider; import de.agilecoders.wicket.webjars.WicketWebjars; import nl.dries.wicket.hibernate.dozer.DozerRequestCycleListener; import nl.dries.wicket.hibernate.dozer.SessionFinderHolder; @@ -45,7 +42,6 @@ import org.apache.wicket.request.resource.caching.version.CachingResourceVersion; import org.apache.wicket.settings.RequestCycleSettings.RenderStrategy; import org.apache.wicket.spring.injection.annot.SpringComponentInjector; -import org.apache.wicket.util.convert.converter.BigDecimalConverter; import org.apache.wicket.util.file.Folder; import org.devgateway.toolkit.forms.serializer.SpringDevToolsSerializer; import org.devgateway.toolkit.forms.service.SessionFinderService; @@ -66,7 +62,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; -import org.springframework.context.annotation.PropertySources; import org.springframework.scheduling.annotation.EnableScheduling; import org.wicketstuff.annotation.scan.AnnotatedMountScanner; import org.wicketstuff.select2.ApplicationSettings; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/SSAuthenticatedWebSession.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/SSAuthenticatedWebSession.java index ba74b461..e77c261e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/SSAuthenticatedWebSession.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/SSAuthenticatedWebSession.java @@ -11,9 +11,6 @@ *******************************************************************************/ package org.devgateway.toolkit.forms.wicket; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.apache.wicket.Session; import org.apache.wicket.authroles.authentication.AuthenticatedWebSession; import org.apache.wicket.authroles.authorization.strategies.role.Roles; @@ -32,11 +29,13 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.RememberMeServices; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import java.util.Collection; /** * AuthenticatedWebSession implementation using Spring Security. - * + *

* Based on: * https://cwiki.apache.org/confluence/display/WICKET/Spring+Security+and+Wicket-auth-roles * @@ -62,9 +61,23 @@ public class SSAuthenticatedWebSession extends AuthenticatedWebSession { // @SpringBean // private SessionRegistry sessionRegistry; + public SSAuthenticatedWebSession(final Request request) { + super(request); + Injector.get().inject(this); + ensureDependenciesNotNull(); + if (authenticationManager == null) { + throw new IllegalStateException("Injection of AuthenticationManager failed."); + } + + } + + public static SSAuthenticatedWebSession getSSAuthenticatedWebSession() { + return (SSAuthenticatedWebSession) Session.get(); + } + /* * (non-Javadoc) - * + * * @see org.apache.wicket.Session#replaceSession() */ @Override @@ -78,20 +91,6 @@ private void ensureDependenciesNotNull() { } } - public SSAuthenticatedWebSession(final Request request) { - super(request); - Injector.get().inject(this); - ensureDependenciesNotNull(); - if (authenticationManager == null) { - throw new IllegalStateException("Injection of AuthenticationManager failed."); - } - - } - - public static SSAuthenticatedWebSession getSSAuthenticatedWebSession() { - return (SSAuthenticatedWebSession) Session.get(); - } - @Override public boolean authenticate(final String username, final String password) { boolean authenticated; @@ -129,10 +128,10 @@ public Roles getRoles() { /** * Gets the Spring roles and dumps them into Wicket's {@link Roles} object, * only if the user is signed in - * + * + * @param roles * @see {@link #isSignedIn()} * @see #addRolesFromAuthentication(Roles, Authentication) - * @param roles */ private void getRolesIfSignedIn(final Roles roles) { if (isSignedIn()) { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/WebInitializer.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/WebInitializer.java index 02fd99fa..f95b5aa6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/WebInitializer.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/WebInitializer.java @@ -20,8 +20,6 @@ import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import javax.servlet.ServletException; -import javax.servlet.SessionTrackingMode; -import java.util.Collections; import static org.devgateway.toolkit.web.WebConstants.FORMS_BASE_PATH; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/CollapsablePanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/CollapsablePanel.java index c7be026e..829800c3 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/CollapsablePanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/CollapsablePanel.java @@ -46,5 +46,5 @@ protected void onInitialize() { onInitializeBody(body); } - protected abstract void onInitializeBody(final WebMarkupContainer body); + protected abstract void onInitializeBody(WebMarkupContainer body); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapCancelButton.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapCancelButton.java index 5f1d9f02..9d41f521 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapCancelButton.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapCancelButton.java @@ -1,16 +1,16 @@ -/******************************************************************************* +/** * Copyright (c) 2015 Development Gateway, Inc and others. - * + *

* All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT - * + *

* Contributors: * Development Gateway - initial API and implementation - *******************************************************************************/ + */ /** - * + * */ package org.devgateway.toolkit.forms.wicket.components.form; @@ -23,7 +23,7 @@ /** * @author mpostelnicu - * + * */ public abstract class BootstrapCancelButton extends LaddaAjaxButton { @@ -44,7 +44,7 @@ public BootstrapCancelButton(final String id, final IModel model) { /* * (non-Javadoc) - * + * * @see de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda. * LaddaAjaxButton#onInitialize() */ diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapDeleteButton.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapDeleteButton.java index 1f1f8fb9..046bd525 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapDeleteButton.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapDeleteButton.java @@ -1,16 +1,16 @@ -/******************************************************************************* +/** * Copyright (c) 2015 Development Gateway, Inc and others. - * + *

* All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT - * + *

* Contributors: * Development Gateway - initial API and implementation - *******************************************************************************/ + */ /** - * + * */ package org.devgateway.toolkit.forms.wicket.components.form; @@ -29,7 +29,7 @@ /** * @author mpostelnicu - * + * */ public abstract class BootstrapDeleteButton extends LaddaAjaxButton { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapSubmitButton.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapSubmitButton.java index cabd7ec6..4f5793cd 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapSubmitButton.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapSubmitButton.java @@ -1,23 +1,22 @@ -/******************************************************************************* +/** * Copyright (c) 2015 Development Gateway, Inc and others. - * + *

* All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT - * + *

* Contributors: * Development Gateway - initial API and implementation - *******************************************************************************/ + */ /** - * + * */ package org.devgateway.toolkit.forms.wicket.components.form; import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; - import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.model.IModel; @@ -25,7 +24,7 @@ /** * @author mpostelnicu - * + * */ public abstract class BootstrapSubmitButton extends LaddaAjaxButton { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxBootstrapFormComponent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxBootstrapFormComponent.java index 7fe82e93..2c425b2f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxBootstrapFormComponent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxBootstrapFormComponent.java @@ -19,7 +19,6 @@ /** * @author mpostelnicu - * */ public class CheckBoxBootstrapFormComponent extends GenericEnablingBootstrapFormComponent { private static final long serialVersionUID = -4032850928243673675L; @@ -27,7 +26,7 @@ public class CheckBoxBootstrapFormComponent extends GenericEnablingBootstrapForm private CheckBox wrappedCheckbox; public CheckBoxBootstrapFormComponent(final String id, final IModel labelModel, - final IModel model) { + final IModel model) { super(id, labelModel, model); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxPickerBootstrapFormComponent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxPickerBootstrapFormComponent.java index 6905f202..2d159ed8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxPickerBootstrapFormComponent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxPickerBootstrapFormComponent.java @@ -20,7 +20,6 @@ /** * @author mpostelnicu - * */ public class CheckBoxPickerBootstrapFormComponent extends GenericEnablingBootstrapFormComponent { @@ -29,7 +28,7 @@ public class CheckBoxPickerBootstrapFormComponent private BootstrapCheckBoxPickerConfig config; public CheckBoxPickerBootstrapFormComponent(final String id, final IModel labelModel, - final IModel model) { + final IModel model) { super(id, labelModel, model); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/ColorPickerBootstrapFormComponent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/ColorPickerBootstrapFormComponent.java index 950291f4..5ecc96e7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/ColorPickerBootstrapFormComponent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/ColorPickerBootstrapFormComponent.java @@ -1,16 +1,16 @@ -/******************************************************************************* +/** * Copyright (c) 2015 Development Gateway, Inc and others. - * + *

* All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT - * + *

* Contributors: * Development Gateway - initial API and implementation - *******************************************************************************/ + */ /** - * + * */ package org.devgateway.toolkit.forms.wicket.components.form; @@ -19,7 +19,7 @@ /** * @author mpostelnicu - * + * */ public class ColorPickerBootstrapFormComponent extends GenericBootstrapFormComponent { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/EditableTablePanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/EditableTablePanel.java index 3f822c34..45561a12 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/EditableTablePanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/EditableTablePanel.java @@ -35,11 +35,11 @@ /** * This panel can be used to edit small data grid tables. - * + *

*

For many columns you need to use {@link org.devgateway.toolkit.forms.wicket.components.ListViewSectionPanel}. * For too many rows you should check * {@link org.devgateway.toolkit.forms.wicket.components.form.EditableGridFormComponent}. - * + *

*

This class also tracks and updates computed columns (computed formula must be defined in the column model). * *

(Optional) You can use bottom toolbar for computed totals. @@ -52,16 +52,13 @@ public class EditableTablePanel property that can be used as unique id among entries */ protected String rowIdProperty; - + protected boolean usePagingWithErrors = true; + protected CustomUpdatableToolbar customUpdatableToolbar; private List computedColumnsProperties = new ArrayList<>(); private Map rowId2RowIndex = new HashMap<>(); private Map> rowId2ComputedColumnsComponentIds = new HashMap<>(); - - protected boolean usePagingWithErrors = true; private LoopItem currentPaginatorLoopItem; - protected CustomUpdatableToolbar customUpdatableToolbar; - public EditableTablePanel(final String id, final IModel parentModel) { super(id, parentModel); } @@ -98,7 +95,7 @@ public void addComputedColumn(final String resourceKey, final String property) { } public void addComputedColumn(final String resourceKey, final String sortProperty, final String property, - final String css) { + final String css) { if (rowIdProperty == null) { throw new RuntimeException("No row id property configured."); } @@ -106,9 +103,10 @@ public void addComputedColumn(final String resourceKey, final String sortPropert IColumn computedColumn = new PropertyColumn( new StringResourceModel(resourceKey), sortProperty, property) { private static final long serialVersionUID = -3578903469355827616L; + @Override public void populateItem(final Item> item, final String componentId, - final IModel rowModel) { + final IModel rowModel) { super.populateItem(item, componentId, rowModel); item.setOutputMarkupId(true); @@ -146,7 +144,7 @@ protected void onUpdate(final AjaxRequestTarget target) { protected boolean hasErrors(final long pageIndex) { // customize with your page validation logic - return false; + return false; } private void onRowEdit(final AjaxRequestTarget target, final IModel rowModel) { @@ -195,7 +193,7 @@ public class EditableTablePagination extends AbstractBootstrapPagingNavigationWi private static final long serialVersionUID = -5015086509864523000L; public EditableTablePagination(final String id, final IPageable pageable, - final IPagingLabelProvider labelProvider) { + final IPagingLabelProvider labelProvider) { super(id, pageable, labelProvider); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/GenericBootstrapFormComponent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/GenericBootstrapFormComponent.java index d925fcb7..f02095a0 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/GenericBootstrapFormComponent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/GenericBootstrapFormComponent.java @@ -16,14 +16,12 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.form.InputBehavior; import de.agilecoders.wicket.core.markup.html.bootstrap.form.InputBehavior.Size; import de.agilecoders.wicket.core.util.Attributes; -import org.apache.wicket.AttributeModifier; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.event.IEvent; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.TransparentWebMarkupContainer; -import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.CheckGroup; import org.apache.wicket.markup.html.form.FormComponent; @@ -42,8 +40,6 @@ import org.hibernate.envers.AuditReaderFactory; import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.query.AuditQuery; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import java.util.ArrayList; @@ -54,20 +50,14 @@ */ public abstract class GenericBootstrapFormComponent> extends FieldPanel { private static final long serialVersionUID = -7051128382707812456L; - + private final IModel labelModel; protected FormGroup border; - protected FIELD field; - private InputBehavior sizeBehavior; - private TooltipConfig.OpenTrigger configWithTrigger = TooltipConfig.OpenTrigger.hover; - // use a flag if we need to display a Tooltip since StringResourceModel it's expensive private Boolean showTooltip = false; - private final IModel labelModel; - public GenericBootstrapFormComponent(final String id) { this(id, null); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/GenericEnablingBootstrapFormComponent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/GenericEnablingBootstrapFormComponent.java index 2edc5cad..23b6f891 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/GenericEnablingBootstrapFormComponent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/GenericEnablingBootstrapFormComponent.java @@ -1,16 +1,16 @@ -/******************************************************************************* +/** * Copyright (c) 2015 Development Gateway, Inc and others. - * + *

* All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT - * + *

* Contributors: * Development Gateway - initial API and implementation - *******************************************************************************/ + */ /** - * + * */ package org.devgateway.toolkit.forms.wicket.components.form; @@ -54,14 +54,14 @@ public GenericEnablingBootstrapFormComponent(final String id, final IModel * @param model */ public GenericEnablingBootstrapFormComponent(final String id, final IModel labelModel, - final IModel model) { + final IModel model) { super(id, labelModel, model); } /** * Returns true if the bound components should have * {@link #setVisibilityAllowed(boolean)} to true otherwise returns false. - * + * * @param selectedValue * the selected value of the current component, that may be taken * into consideration when evaluating the visibility of the bound @@ -73,7 +73,7 @@ public GenericEnablingBootstrapFormComponent(final String id, final IModel addBoundComponent(fina /** * This is the negated version of * {@link GenericEnablingBootstrapFormComponent#addBoundComponent(Component)} - * + * * @param c * @return */ diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/PercentageFieldBootstrapFormComponent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/PercentageFieldBootstrapFormComponent.java index 000654eb..93b1c519 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/PercentageFieldBootstrapFormComponent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/PercentageFieldBootstrapFormComponent.java @@ -1,16 +1,16 @@ -/******************************************************************************* +/** * Copyright (c) 2015 Development Gateway, Inc and others. - * + *

* All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT - * + *

* Contributors: * Development Gateway - initial API and implementation - *******************************************************************************/ + */ /** - * + * */ package org.devgateway.toolkit.forms.wicket.components.form; @@ -38,7 +38,7 @@ public class PercentageFieldBootstrapFormComponent extends TextFieldBootstrapFor private Label label; public PercentageFieldBootstrapFormComponent(final String id, final IModel labelModel, - final IModel model) { + final IModel model) { super(id, labelModel, model); } @@ -60,7 +60,7 @@ protected TextField inputField(final String id, final IModel !s.isEmpty()).collect(Collectors.joining(" ")); } - protected abstract boolean hasErrors(final long pageIndex); + protected abstract boolean hasErrors(long pageIndex); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/AjaxBootstrapNavigator.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/AjaxBootstrapNavigator.java index 736c8d0d..43b0aac2 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/AjaxBootstrapNavigator.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/AjaxBootstrapNavigator.java @@ -12,13 +12,11 @@ package org.devgateway.toolkit.forms.wicket.components.table; import org.apache.wicket.Component; -import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator; import org.apache.wicket.markup.html.link.AbstractLink; import org.apache.wicket.markup.html.navigation.paging.IPageable; import org.apache.wicket.markup.html.navigation.paging.IPagingLabelProvider; import org.apache.wicket.markup.html.navigation.paging.PagingNavigation; -import org.devgateway.toolkit.forms.WebConstants; /** * @author idobre diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/PagingNavigationFactory.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/PagingNavigationFactory.java index a3ca7811..880fb97a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/PagingNavigationFactory.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/PagingNavigationFactory.java @@ -5,7 +5,6 @@ import org.apache.wicket.markup.html.navigation.paging.PagingNavigation; import java.io.Serializable; -import java.lang.reflect.InvocationTargetException; /** * @author Nadejda Mandrescu diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/converters/NonNumericFilteredBigDecimalConverter.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/converters/NonNumericFilteredBigDecimalConverter.java index b6e0c057..8f2c60da 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/converters/NonNumericFilteredBigDecimalConverter.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/converters/NonNumericFilteredBigDecimalConverter.java @@ -39,7 +39,7 @@ public class NonNumericFilteredBigDecimalConverter extends BigDecimalConverter { private static final long serialVersionUID = 1L; - private int MAX_SCALE_BIG_DECIMAL = 16; + private static final int MAX_SCALE_BIG_DECIMAL = 16; private final INumberFormatter numberFormatter; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/events/EditingDisabledEvent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/events/EditingDisabledEvent.java index 09f1f5e8..fedbfa2f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/events/EditingDisabledEvent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/events/EditingDisabledEvent.java @@ -13,9 +13,8 @@ /** * Event that triggers all editing fields/buttons to enabled=false - * - * @author mpostelnicu * + * @author mpostelnicu */ public class EditingDisabledEvent { } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/events/EditingEnabledEvent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/events/EditingEnabledEvent.java index b91f05ae..b6412831 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/events/EditingEnabledEvent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/events/EditingEnabledEvent.java @@ -13,9 +13,8 @@ /** * Event that triggers all editing fields/buttons to enabled=true - * - * @author mpostelnicu * + * @author mpostelnicu */ public class EditingEnabledEvent { } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 85ebef92..c9e0f4d6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -12,7 +12,6 @@ package org.devgateway.toolkit.forms.wicket.page; import de.agilecoders.wicket.core.markup.html.bootstrap.behavior.CssClassNameAppender; -import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapBookmarkablePageLink; import de.agilecoders.wicket.core.markup.html.bootstrap.button.dropdown.MenuBookmarkablePageLink; import de.agilecoders.wicket.core.markup.html.bootstrap.button.dropdown.MenuDivider; import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel; @@ -26,7 +25,6 @@ import de.agilecoders.wicket.core.util.CssClassNames; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5CssReference; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; -import org.apache.wicket.Component; import org.apache.wicket.Page; import org.apache.wicket.authroles.authorization.strategies.role.metadata.MetaDataRoleAuthorizationStrategy; import org.apache.wicket.markup.head.CssHeaderItem; @@ -50,12 +48,9 @@ import org.apache.wicket.resource.JQueryResourceReference; import org.apache.wicket.util.string.StringValue; import org.devgateway.toolkit.forms.WebConstants; -import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.security.SecurityUtil; import org.devgateway.toolkit.forms.wicket.page.lists.ListGroupPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListTestFormPage; -import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; -import org.devgateway.toolkit.forms.wicket.page.lists.ListTobaccoProductPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListUserPage; import org.devgateway.toolkit.forms.wicket.page.user.EditUserPage; import org.devgateway.toolkit.forms.wicket.page.user.LogoutPage; @@ -68,6 +63,8 @@ import java.util.List; import java.util.Locale; +import static org.devgateway.toolkit.forms.security.SecurityConstants.Roles.ROLE_USER; + /** * Base wicket-bootstrap {@link org.apache.wicket.Page} * @@ -213,7 +210,7 @@ protected NavbarButton newLogoutMenu() { final NavbarButton logoutMenu = new NavbarButton(LogoutPage.class, new StringResourceModel("navbar.logout", this, null)); logoutMenu.setIconType(FontAwesome5IconType.sign_out_alt_s); - MetaDataRoleAuthorizationStrategy.authorize(logoutMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); + MetaDataRoleAuthorizationStrategy.authorize(logoutMenu, RENDER, ROLE_USER); return logoutMenu; } @@ -231,7 +228,7 @@ protected NavbarButton newAccountMenu() { final NavbarButton accountMenu = new NavbarButton<>(EditUserPage.class, pageParametersForAccountPage, account); accountMenu.setIconType(FontAwesome5IconType.user_s); - MetaDataRoleAuthorizationStrategy.authorize(accountMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); + MetaDataRoleAuthorizationStrategy.authorize(accountMenu, RENDER, ROLE_USER); return accountMenu; } @@ -240,7 +237,7 @@ protected NavbarButton newHomeMenu() { NavbarButton homeMenu = new NavbarButton<>(Homepage.class, new StringResourceModel("navbar.home", this, null)); homeMenu.setIconType(FontAwesome5IconType.home_s); - MetaDataRoleAuthorizationStrategy.authorize(homeMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); + MetaDataRoleAuthorizationStrategy.authorize(homeMenu, RENDER, ROLE_USER); return homeMenu; } @@ -296,7 +293,7 @@ protected List newSubMenuButtons(final String arg0) { }; adminMenu.setIconType(FontAwesome5IconType.cog_s); - MetaDataRoleAuthorizationStrategy.authorize(adminMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); + MetaDataRoleAuthorizationStrategy.authorize(adminMenu, RENDER, ROLE_USER); return adminMenu; } @@ -307,7 +304,7 @@ protected NavbarButton newDatasetsMenu() { .setIconType(FontAwesome5IconType.table_s); dataSetsMenu.setIconType(FontAwesome5IconType.table_s); - MetaDataRoleAuthorizationStrategy.authorize(dataSetsMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); + MetaDataRoleAuthorizationStrategy.authorize(dataSetsMenu, RENDER, ROLE_USER); return dataSetsMenu; } @@ -317,7 +314,7 @@ protected NavbarButton newCategoriesMenu() { new StringResourceModel("navbar.categories", this, null)) .setIconType(FontAwesome5IconType.list_alt_r); - MetaDataRoleAuthorizationStrategy.authorize(categoriesMenu, Component.RENDER, SecurityConstants.Roles.ROLE_USER); + MetaDataRoleAuthorizationStrategy.authorize(categoriesMenu, RENDER, ROLE_USER); return categoriesMenu; } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/JavamelodyPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/JavamelodyPage.java index a0493d19..c2ca0124 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/JavamelodyPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/JavamelodyPage.java @@ -1,9 +1,7 @@ package org.devgateway.toolkit.forms.wicket.page; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; -import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.pages.RedirectPage; -import org.apache.wicket.request.flow.RedirectToUrlException; import org.devgateway.toolkit.forms.security.SecurityConstants; /** diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/RevisionsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/RevisionsPage.java index 3cdf80a3..93b52985 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/RevisionsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/RevisionsPage.java @@ -30,7 +30,6 @@ import javax.persistence.EntityManager; import java.util.ArrayList; -import java.util.Date; import java.util.List; import static org.devgateway.toolkit.persistence.PersistenceConstants.ZONED_DATE_TIME_PATTER; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/SpringEndpointsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/SpringEndpointsPage.java index 528979dc..c40b7d75 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/SpringEndpointsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/SpringEndpointsPage.java @@ -1,16 +1,16 @@ -/******************************************************************************* +/** * Copyright (c) 2015 Development Gateway, Inc and others. - * + *

* All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT - * + *

* Contributors: * Development Gateway - initial API and implementation - *******************************************************************************/ + */ /** - * + * */ package org.devgateway.toolkit.forms.wicket.page; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java index 84b97954..01e20f69 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java @@ -16,7 +16,7 @@ public class TetsimBaselineNumbersPanel extends Panel { @SpringBean - AdminSettingsService adminSettingsService; + private AdminSettingsService adminSettingsService; protected final IModel tetsimDatasetIModel; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties index d718ba3b..29b2524f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties @@ -4,7 +4,7 @@ cigaretteConsumption.unit=Full number of packs vatRate.label=VAT rate vatRate.unit=Percentage -cigaretteDeclaredCustomValue.label=Declared customs value of imported cigarettes (FOB amount) +cigaretteDeclaredCustomValue.label=Declared customs value of imported cigarettes (FOB amount) cigaretteDeclaredCustomValue.unit={0} per pack adultPopulation.label=Adult Population (15+) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.java index 50e0a568..97393dde 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.java @@ -16,22 +16,15 @@ import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.model.Model; import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.wicket.components.table.TextFilteredBootstrapPropertyColumn; import org.devgateway.toolkit.forms.wicket.components.table.filter.JpaFilterState; -import org.devgateway.toolkit.forms.wicket.components.table.filter.TestFormFilterState; import org.devgateway.toolkit.forms.wicket.components.table.filter.TobaccoProductFilterState; -import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; -import org.devgateway.toolkit.forms.wicket.page.edit.EditTestFormPage; import org.devgateway.toolkit.forms.wicket.page.edit.category.EditTobaccoProductPage; -import org.devgateway.toolkit.persistence.dao.TestForm; import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; -import org.devgateway.toolkit.persistence.service.RoleService; -import org.devgateway.toolkit.persistence.service.TestFormService; import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; import org.wicketstuff.annotation.mount.MountPath; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java index 264a7241..73f4fcf6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java @@ -49,20 +49,14 @@ @MountPath(value = "/listTetsimDataset") public class ListTetsimDatasetPage extends AbstractListPage { private static final long serialVersionUID = -324298525712620234L; - - private Integer selectedYear; - - @SpringBean - private TetsimDatasetService tetsimDatasetService; - @SpringBean protected SettingsUtils settingsUtils; - protected Select2ChoiceBootstrapFormComponent year; - - private Label addButtonError; - protected Fragment yearSelectorFragment; + private Integer selectedYear; + @SpringBean + private TetsimDatasetService tetsimDatasetService; + private Label addButtonError; public ListTetsimDatasetPage(final PageParameters pageParameters) { super(pageParameters); @@ -82,7 +76,7 @@ public ListTetsimDatasetPage(final PageParameters pageParameters) { public IModel getDataModel(final IModel rowModel) { IModel model = super.getDataModel(rowModel); ZonedDateTime modifiedDate = (ZonedDateTime) model.getObject(); - return Model.of(modifiedDate.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"))); + return Model.of(modifiedDate.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"))); } }); columns.add(new PropertyColumn<>(new StringResourceModel("status"), "status", "status")); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/providers/GenericPersistableJpaTextChoiceProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/providers/GenericPersistableJpaTextChoiceProvider.java index 033eb93e..5376d549 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/providers/GenericPersistableJpaTextChoiceProvider.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/providers/GenericPersistableJpaTextChoiceProvider.java @@ -89,7 +89,8 @@ public GenericPersistableJpaTextChoiceProvider setSort(final Sort sort) { return this; } - public GenericPersistableJpaTextChoiceProvider setSort(final Sort.Direction direction, final String... properties) { + public GenericPersistableJpaTextChoiceProvider setSort(final Sort.Direction direction, + final String... properties) { return this.setSort(Sort.by(direction, properties)); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/converter/INumberFormatter.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/converter/INumberFormatter.java index d1c960aa..2ddf68b7 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/converter/INumberFormatter.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/converter/INumberFormatter.java @@ -8,5 +8,5 @@ */ public interface INumberFormatter { - NumberFormat get(final Locale locale); + NumberFormat get(Locale locale); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractStatusAuditableEntity.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractStatusAuditableEntity.java index 8f0f1ffb..4f423a9d 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractStatusAuditableEntity.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractStatusAuditableEntity.java @@ -19,7 +19,6 @@ import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DRAFT; -import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; @MappedSuperclass public abstract class AbstractStatusAuditableEntity extends AbstractAuditableEntity implements Statusable { diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileContent.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileContent.java index c76c2760..dc78144b 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileContent.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileContent.java @@ -16,7 +16,6 @@ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Lob; -import java.io.Serializable; /** * @author idobre diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileMetadata.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileMetadata.java index 890d6a6c..3e9dbd8f 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileMetadata.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileMetadata.java @@ -20,7 +20,6 @@ import javax.persistence.Index; import javax.persistence.OneToOne; import javax.persistence.Table; -import java.io.Serializable; /** * @author idobre diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/JsonViews.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/JsonViews.java index 66c34a98..2161f325 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/JsonViews.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/JsonViews.java @@ -1,7 +1,5 @@ package org.devgateway.toolkit.persistence.dao; -import org.apache.xmlbeans.impl.xb.xsdschema.Public; - /** * These is a set of possible views to be used with com.fasterxml.jackson.annotation.JsonView, * that allows multiple serializations options for the same class based on the view. diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Person.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Person.java index 2326f40f..ba2abe0a 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Person.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Person.java @@ -27,7 +27,6 @@ import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; -import java.io.Serializable; import java.util.Collection; import java.util.List; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Role.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Role.java index c8c7e71f..75640f78 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Role.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Role.java @@ -19,7 +19,6 @@ import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.Table; -import java.io.Serializable; /** * @author mpostelnicu diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/TestForm.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/TestForm.java index c37960c4..3015b9cc 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/TestForm.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/TestForm.java @@ -28,7 +28,6 @@ import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OrderColumn; -import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Category.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Category.java index 9995aaf7..b102119b 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Category.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Category.java @@ -21,7 +21,6 @@ import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.Table; -import java.io.Serializable; /** * @author idobre diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Group.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Group.java index abab2483..aeca60f2 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Group.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Group.java @@ -23,9 +23,7 @@ import java.util.Set; /** - * * @author mpostelnicu - * */ @Entity @Audited diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java index d35d1f86..fcd1ef43 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java @@ -16,74 +16,74 @@ public class TetsimDataset extends Dataset { @Audited - BigDecimal cigaretteConsumption; + private BigDecimal cigaretteConsumption; @Audited - BigDecimal vatRate; + private BigDecimal vatRate; @Audited - BigDecimal cigaretteDeclaredCustomValue; + private BigDecimal cigaretteDeclaredCustomValue; @Audited - BigDecimal adultPopulation; + private BigDecimal adultPopulation; @Audited - BigDecimal smokingPrevalence; + private BigDecimal smokingPrevalence; @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable retailPrice = new TetsimPriceVariable(this); + private TetsimPriceVariable retailPrice = new TetsimPriceVariable(this); @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable marketShare = new TetsimPriceVariable(this); + private TetsimPriceVariable marketShare = new TetsimPriceVariable(this); @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable cif = new TetsimPriceVariable(this); + private TetsimPriceVariable cif = new TetsimPriceVariable(this); @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable tobaccoLevy = new TetsimPriceVariable(this); + private TetsimPriceVariable tobaccoLevy = new TetsimPriceVariable(this); @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable exciseTax = new TetsimPriceVariable(this); + private TetsimPriceVariable exciseTax = new TetsimPriceVariable(this); @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable customsDuty = new TetsimPriceVariable(this); + private TetsimPriceVariable customsDuty = new TetsimPriceVariable(this); @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable elasticityOfDemandPrice = new TetsimPriceVariable(this); + private TetsimPriceVariable elasticityOfDemandPrice = new TetsimPriceVariable(this); @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable elasticityOfDemandCrossPrice = new TetsimPriceVariable(this); + private TetsimPriceVariable elasticityOfDemandCrossPrice = new TetsimPriceVariable(this); @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable changeInIllicitNot = new TetsimPriceVariable(this); + private TetsimPriceVariable changeInIllicitNot = new TetsimPriceVariable(this); @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable overShifting = new TetsimPriceVariable(this); + private TetsimPriceVariable overShifting = new TetsimPriceVariable(this); @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - TetsimPriceVariable underShifting = new TetsimPriceVariable(this); + private TetsimPriceVariable underShifting = new TetsimPriceVariable(this); public BigDecimal getCigaretteConsumption() { return cigaretteConsumption; @@ -145,8 +145,8 @@ public TetsimPriceVariable getCif() { return cif; } - public void setCif(final TetsimPriceVariable CIF) { - this.cif = CIF; + public void setCif(final TetsimPriceVariable cif) { + this.cif = cif; } public TetsimPriceVariable getTobaccoLevy() { diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java index fe09912d..8f6fbc30 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java @@ -15,7 +15,7 @@ public interface TetsimDatasetRepository extends DatasetRepository findAllDeleted(); - @Query ("select count(e) from #{#entityName} e where (:year is null or e.year=:year) " + - "and e.status not in ('DELETED')") + @Query ("select count(e) from #{#entityName} e where (:year is null or e.year=:year) " + + "and e.status not in ('DELETED')") long countByNonPublished(@Param("year") Integer year); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/AdminSettingsServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/AdminSettingsServiceImpl.java index c9b542f1..64738666 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/AdminSettingsServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/AdminSettingsServiceImpl.java @@ -55,12 +55,12 @@ private void preProcessRebootAlert(final S as) { @Override public AdminSettings get() { List entries = repository().findAll(); - return entries.isEmpty() ? null : entries.get(0); + return entries.isEmpty() ? null : entries.get(0); } private AdminSettings getOrDefault() { List entries = repository().findAll(); - return entries.isEmpty() ? new AdminSettings() : entries.get(0); + return entries.isEmpty() ? new AdminSettings() : entries.get(0); } @Override diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/BaseJpaServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/BaseJpaServiceImpl.java index a25f1906..b2fe66d2 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/BaseJpaServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/BaseJpaServiceImpl.java @@ -2,8 +2,6 @@ import org.devgateway.toolkit.persistence.dao.GenericPersistable; import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; -import org.springframework.cache.annotation.CacheConfig; -import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/FileMetadataServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/FileMetadataServiceImpl.java index 1a3782a2..50cb8321 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/FileMetadataServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/FileMetadataServiceImpl.java @@ -4,7 +4,6 @@ import org.devgateway.toolkit.persistence.repository.FileMetadataRepository; import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.CacheConfig; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/PersonServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/PersonServiceImpl.java index 4aafb948..7d7436ef 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/PersonServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/PersonServiceImpl.java @@ -4,7 +4,6 @@ import org.devgateway.toolkit.persistence.repository.PersonRepository; import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.CacheConfig; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/RoleServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/RoleServiceImpl.java index 6ebd4111..0830e818 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/RoleServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/RoleServiceImpl.java @@ -5,7 +5,6 @@ import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; import org.devgateway.toolkit.persistence.repository.norepository.TextSearchableRepository; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.CacheConfig; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/TestFormServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/TestFormServiceImpl.java index 54019f33..c4f0ddd2 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/TestFormServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/TestFormServiceImpl.java @@ -5,7 +5,6 @@ import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; import org.devgateway.toolkit.persistence.repository.norepository.UniquePropertyRepository; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.CacheConfig; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/GroupServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/GroupServiceImpl.java index cea24820..091f9d55 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/GroupServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/GroupServiceImpl.java @@ -6,7 +6,6 @@ import org.devgateway.toolkit.persistence.repository.norepository.TextSearchableRepository; import org.devgateway.toolkit.persistence.service.BaseJpaServiceImpl; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.CacheConfig; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java index ecc9427a..26241424 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java @@ -1,7 +1,6 @@ package org.devgateway.toolkit.persistence.service.category; import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; -import org.devgateway.toolkit.persistence.repository.category.GroupRepository; import org.devgateway.toolkit.persistence.repository.category.TobaccoProductRepository; import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; import org.devgateway.toolkit.persistence.repository.norepository.TextSearchableRepository; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/CacheConfiguration.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/CacheConfiguration.java index 94ff4d9b..d97a3de2 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/CacheConfiguration.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/CacheConfiguration.java @@ -18,18 +18,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer; import org.springframework.cache.annotation.EnableCaching; -import org.springframework.cache.ehcache.EhCacheCacheManager; -import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; import org.springframework.cache.jcache.JCacheCacheManager; -import org.springframework.cache.jcache.JCacheManagerFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.core.io.ClassPathResource; import org.springframework.data.auditing.DateTimeProvider; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; -import javax.cache.CacheManager; import javax.management.MBeanServer; import java.time.ZonedDateTime; import java.util.Optional; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java index b6ba719f..a28fd523 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java @@ -23,7 +23,6 @@ import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; diff --git a/pom.xml b/pom.xml index 8005b5cd..4a5dff4d 100644 --- a/pom.xml +++ b/pom.xml @@ -29,7 +29,7 @@ 4.0.1 devgateway/toolkit 0.4.13 - 3.0.0 + 3.1.2 2.22.1 2.5.3 3.27.0-GA @@ -42,7 +42,6 @@ forms - checkstyle 2015 @@ -112,14 +111,6 @@ javassist ${javassist.version} - - - org.devgateway.toolkit - checkstyle - 1.0 - compile - true - org.reflections reflections @@ -143,15 +134,6 @@ org.apache.maven.plugins maven-checkstyle-plugin ${maven-checkstyle-plugin.version} - - - validate - validate - - check - - - checkstyle.xml checkstyle-suppressions.xml @@ -161,12 +143,21 @@ true warning + + + validate + validate + true + + check + + + - org.devgateway.toolkit + com.puppycrawl.tools checkstyle - 1.0 - compile + 8.42 diff --git a/web/src/main/java/org/devgateway/toolkit/web/excelcharts/util/XSSFChartUtil.java b/web/src/main/java/org/devgateway/toolkit/web/excelcharts/util/XSSFChartUtil.java index 625aa0d6..81b7439e 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/excelcharts/util/XSSFChartUtil.java +++ b/web/src/main/java/org/devgateway/toolkit/web/excelcharts/util/XSSFChartUtil.java @@ -13,9 +13,9 @@ /** * @author idobre * @since 8/8/16 - * - * Package private class with utility methods. It's based on - * org.apache.poi.xssf.usermodel.charts.XSSFChartUtil class + *

+ * Package private class with utility methods. It's based on + * org.apache.poi.xssf.usermodel.charts.XSSFChartUtil class */ public final class XSSFChartUtil { private XSSFChartUtil() { @@ -24,11 +24,9 @@ private XSSFChartUtil() { /** * Builds CTAxDataSource object content from POI ChartDataSource. - * - * @param ctAxDataSource - * OOXML data source to build - * @param dataSource - * POI data source to use + * + * @param ctAxDataSource OOXML data source to build + * @param dataSource POI data source to use */ public static void buildAxDataSource(final CTAxDataSource ctAxDataSource, final ChartDataSource dataSource) { if (dataSource.isNumeric()) { @@ -48,14 +46,12 @@ public static void buildAxDataSource(final CTAxDataSource ctAxDataSource, final /** * Builds CTNumDataSource object content from POI ChartDataSource - * - * @param ctNumDataSource - * OOXML data source to build - * @param dataSource - * POI data source to use + * + * @param ctNumDataSource OOXML data source to build + * @param dataSource POI data source to use */ public static void buildNumDataSource(final CTNumDataSource ctNumDataSource, - final ChartDataSource dataSource) { + final ChartDataSource dataSource) { if (dataSource.isReference()) { buildNumRef(ctNumDataSource.addNewNumRef(), dataSource); } else { diff --git a/web/src/main/java/org/devgateway/toolkit/web/util/SettingsUtils.java b/web/src/main/java/org/devgateway/toolkit/web/util/SettingsUtils.java index 70baa8db..7fd5e17a 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/util/SettingsUtils.java +++ b/web/src/main/java/org/devgateway/toolkit/web/util/SettingsUtils.java @@ -8,7 +8,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -import org.springframework.util.ObjectUtils; import java.util.Calendar; import java.util.Collections; @@ -22,17 +21,16 @@ */ @Service public class SettingsUtils { - protected static Logger logger = LoggerFactory.getLogger(SettingsUtils.class); - public static final int START_YEAR = 2000; - + public static final String DEFAULT_LANGUAGE = "en_US"; + protected static Logger logger = LoggerFactory.getLogger(SettingsUtils.class); @Autowired private AdminSettingsService adminSettingsService; - private AdminSettings setting; - @Value("${googleAnalyticsTrackingId:#{null}}") private String googleAnalyticsTrackingId; + @Autowired + private AdminSettingsRepository adminSettingsRepository; public String getGoogleAnalyticsTrackingId() { return googleAnalyticsTrackingId; @@ -69,11 +67,6 @@ public int getStartYear() { return START_YEAR; } - public static final String DEFAULT_LANGUAGE = "en_US"; - - @Autowired - private AdminSettingsRepository adminSettingsRepository; - public AdminSettings getSettings() { List list = adminSettingsRepository.findAll(); if (list.size() == 0) { From f51f5b8cdb2b7a2303d5404452aab47362a667b3 Mon Sep 17 00:00:00 2001 From: sdimunzio Date: Tue, 1 Feb 2022 11:50:35 -0300 Subject: [PATCH 047/137] adding admin to country stack --- .../org/devgateway/toolkit/persistence/application.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties index e5e3d1d3..205b2cf1 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties @@ -44,8 +44,8 @@ spring.datasource.min-idle=8 spring.datasource.initial-size=20 spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.username=postgres -spring.datasource.password=postgres -spring.datasource.jdbc-url=jdbc:postgresql://postgres:5432/tcdi-admin +spring.datasource.password=admin +spring.datasource.jdbc-url=jdbc:postgresql://localhost:5435/tcdi-admin spring.datasource.transaction-isolation=2 dg-toolkit.datasource.jndi-name=toolkitDS dg-toolkit.derby.port=1527 From 5962b9524d7677f8a0e7e37e781550cd00e6221a Mon Sep 17 00:00:00 2001 From: sdimunzio Date: Wed, 2 Feb 2022 09:51:46 -0300 Subject: [PATCH 048/137] updating nginx config & entrypoint --- entrypoint.sh | 4 +- forms/Dockerfile | 2 +- forms/entrypoint.sh | 49 +++++++++++++++---- .../persistence/application-dev.properties | 2 +- .../persistence/application.properties | 2 +- 5 files changed, 46 insertions(+), 13 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index 434d6c27..cb7485aa 100644 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -1,5 +1,6 @@ #!/bin/sh + PROP_FILE="tcdi-admin.properties" echo "Writing to $PROP_FILE:" @@ -23,7 +24,8 @@ JAR="tcdi-admin-forms-0.0.1-SNAPSHOT.jar" JAVA_OPTS="-Dspring.config.location=file://$PROP_FILE" - exec /bin/sh -c "java -jar '$JAR' $JAVA_OPTS $@" nobody + #exec /bin/sh -c "java -jar '$JAR' $JAVA_OPTS $@" nobody + exec /bin/bash ;; *) exec $@ diff --git a/forms/Dockerfile b/forms/Dockerfile index 7a8adca0..527a99e5 100644 --- a/forms/Dockerfile +++ b/forms/Dockerfile @@ -4,7 +4,7 @@ COPY target/deps/BOOT-INF/lib lib COPY target/deps/META-INF META-INF COPY entrypoint.sh ./ COPY target/deps/BOOT-INF/classes . -USER nobody +#USER nobody EXPOSE 8080 ENTRYPOINT ["/opt/devgateway/tcdi/admin/entrypoint.sh"] CMD ["admin"] diff --git a/forms/entrypoint.sh b/forms/entrypoint.sh index d995a3e8..0ae08515 100755 --- a/forms/entrypoint.sh +++ b/forms/entrypoint.sh @@ -1,14 +1,45 @@ #!/bin/sh -case "$1" in - admin) - JAVA_ARGS="$(tr '\n' ' ' <<-EOF + + PROP_FILE="/etc/$1.properties" + echo "Writing to $PROP_FILE:" + truncate -s 0 $PROP_FILE + + echo "..................... Writing to $PROP_FILE: ............... " + + PROPERTIES="$(cat <<-EOF + server.port + spring.application.name + spring.liquibase.enabled + spring.datasource.url + spring.datasource.jdbc.url + spring.datasource.username + spring.datasource.password + spring.jpa.hibernate.ddl.auto + + + EOF + )" + + echo "$PROPERTIES" | while IFS= read PROPERTY; do + VAR_NAME="$(echo "$PROPERTY" | tr '[:lower:].-' '[:upper:]__')" + eval VALUE="\$$VAR_NAME" + if [ -n "$VALUE" ]; then + echo "$PROPERTY=$VALUE" + fi + done | tee -a "$PROP_FILE" + echo "................. Properties ................." + cat $PROP_FILE + echo "................. End sou ................." + JAVA_ARGS="$(tr '\n' ' ' <<-EOF -cp .:lib/* org.devgateway.toolkit.forms.wicket.FormsWebApplication EOF )" - exec java $JAVA_ARGS $@ - ;; - *) - exec $@ - ;; -esac + + JAVA_OPTS="-Dspring.config.location=file://$PROP_FILE" + exec java $JAVA_ARGS $JAVA_OPTS $@ nobody + ;; +*) + exec $@ + ;; + diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties index d9a21465..54a6a199 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties @@ -12,5 +12,5 @@ spring.config.activate.on-profile=dev spring.datasource.username=postgres -spring.datasource.password=postgres +spring.datasource.password=admin spring.datasource.jdbc-url=jdbc:postgresql:tcdi-admin diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties index 205b2cf1..0a3825be 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties @@ -45,7 +45,7 @@ spring.datasource.initial-size=20 spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.username=postgres spring.datasource.password=admin -spring.datasource.jdbc-url=jdbc:postgresql://localhost:5435/tcdi-admin +spring.datasource.jdbc-url=jdbc:postgresql://postgresql:5432/tcdi-admin spring.datasource.transaction-isolation=2 dg-toolkit.datasource.jndi-name=toolkitDS dg-toolkit.derby.port=1527 From 6af00dc4a8dd3014f8e52be83f0d9c95d45e1a52 Mon Sep 17 00:00:00 2001 From: sdimunzio Date: Wed, 2 Feb 2022 12:04:34 -0300 Subject: [PATCH 049/137] creating admin db --- checkstyle/target/checkstyle-1.0.jar | Bin 0 -> 3484 bytes .../checks/CachableQueryAnnotationCheck.class | Bin 0 -> 1746 bytes checkstyle/target/classes/packagenames.xml | 10 ++++++++++ checkstyle/target/maven-archiver/pom.properties | 5 +++++ .../compile/default-compile/createdFiles.lst | 1 + .../compile/default-compile/inputFiles.lst | 1 + 6 files changed, 17 insertions(+) create mode 100644 checkstyle/target/checkstyle-1.0.jar create mode 100644 checkstyle/target/classes/org/devgateway/toolkit/checks/CachableQueryAnnotationCheck.class create mode 100644 checkstyle/target/classes/packagenames.xml create mode 100644 checkstyle/target/maven-archiver/pom.properties create mode 100644 checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst create mode 100644 checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst diff --git a/checkstyle/target/checkstyle-1.0.jar b/checkstyle/target/checkstyle-1.0.jar new file mode 100644 index 0000000000000000000000000000000000000000..41e9041d4ce589fb66c11518b1791b5118af644b GIT binary patch literal 3484 zcmbVP2{_c-8y=Ls8v8!TzRNoKlU_RQ6O9kt~U1 z&zcYtUEBT571KZ5?$ep)w>-~$?|aU7zWLtsjwy_42R(>16pv_I{PXhTMh84i^ewby zj1C*fnf?f)1t|bwoZ_{v7~pGv;9~tb%tZUJk%7Lsg{+CetVu)tA()J8^DdZ-WMjjd zLb&`}#l9hTY2(IPX_$--EzRI<%V>6~D&Y$y$)Ru-7~Gt2Lo$z*mx1}ZBAm^Wr5--Z zdUdWr%K#d4YB<^l8EUS8ht1|F%nDwXD7BM#ujS#xKE}m8>ptyH0a{<*<}`Ky>%+P` zZ)C7JV$Y8VC*(P21Oa&-LHw6sj?KXYEY=m}LiiUDWP6a~X`~|xzk#Lwrwq6*M)tP= z<|G9O1O}csgd+;!jKm<&NWAO?v@1Hi0P{>995An5Gxu%bX^!Z=zGf*APkj{eKmv#EtA^;8@C2Z9Sv$LgXGB0i4MRw-T8O@%Y|HHT$B- zWa2%`!BlI*`0)2h5B)~Jr}GKE6#W<^qI9C4X1#)IJAl83YqF;Tfm*0RAg$l-o-V@i zG{V6ZX?7OrPSnO=uml9b1&h%o?X9e%D*}(daTJE<(Fd-_5QfwT{P+u%L7{Q$<)?ziz*EU%jzCyVQI^0$Ktj3fTH&`XO8c1by@m)^5 zaS+R$GpLIhnTtu2_cEPVy=Ok$1Pzl9o(Qy!I(?_V!r zQ-D+UW6bAjOZFdU6pK?;d8Z1=l~Lu6k&ES;dB|7!()K2e%;Q_STt&lmSvi*tXSJ|y zPsBJ4IGhCL_yY6_ifSTqbI>i}ZB7E8D!MahRf(+})Q5;&y#u$D#(fpCKPWg@Wo6$V z!h}|^w>#XNx6O<0jqIH3d^WC!iSa;x{Brcjm1SeF`0Ixj+HIfVhUZ|TBGVD`o)y_@ zdj+bU3J8~C1PjH4h*?g>$8(8i+9$r1c2{!DcxfIG<>pOWti%zImBMuJW5>9YW<_sC zpPB5Mi)lyT0twEBQ}o@IA6R*sp9`6MR#uuDmbPV!o@4hb28(v3X zaNdFi<-9wS=IumDfp`J6PDd;5M@)9!G{(L1gOFDzJ@f;b&HVCW116b56WeW?7btGU znzX8UtFyXzwmFEi9kbuv=RHxARy~m@G*x=xHqV2x>s&FJP*=lvAEG`*0RFyPh*OH? zRNoF}rOe6nX^oa*VXnH!Z2KzjaFd=)HzmtX@uqkUr7EsuK2Qojv{y%=r#@^cr6le? zetbUaTgP8VN{Y$>>!zZTLbEaN`MfAfG!w(x*JMi5<-n~Pf0i$K-} zs7PPmUN-_4e?RrIS}cxE`L8xshehG{G7&@2J7!g9AMlAu)8oM92__NYk*YyM)lbB& z;%{Sz`K@kOaw>kAR$Oo1t;KcY6hR}-Au$_Tw>el8==5KL0qK?{3$yI+wRYcs=2(+n z0?`$@u_Rhh+C@!^eX3tZ&jQjr0tgWFPv~%1G)boY;q@3ld2soN6!;Tcl9Gl6liT4u z3kfr+xm$L&9ucd9Q?`Cq26j26eWw`D%WRvi|XfwdWS|*#Gy2xEeaMY8# zJI>v9-2lh;(s8NMM!jtJ{;(@bvBuQ8B~0e6791gFAJk_D7W#M{9gAtw0|L7)873l( z@}W-H9=a9_mh!+b^=s^wp72xrP&eE6ogHXuI!IMY9DB~&$v0v8ygAXwv&Pu1?>u;T zpKkI~O1FX5i%X7omxCKUcjaqvwk)=YTs~kN>E>i%EnkefE@XnETZt<~4cR(Kw(s>z z8)C}Tw1r9)6&XHF0YCDmLKGFswOA+62bb1}98(21zpSEGIg8hd(^rP|pW@m%BCIP_ zf&)s32QJM&EhWw!i$l5-T#)!(^#$}mML|s(_HKO;2jfWk-L}Woii0$9qU}oJM*H7H zFL`zMqEe!R%xa&*5!E_I%Cp*EQgS&**r@ePAZ&4<5=wzXd) z1(U{YUoqgm0sG0lkr_63Dalc-4KQd~`z7$Y=C8J2D#>B34H9AucqJjoZ4LC__F$6Z zS{o!VJJ6TEfXSM$JqgKykx5|NlWh30b*`-)**aU1Zy><+t3M;Bv$dNcqk}28P3Ol- ze(!C_vu&=`&pW@mY5=&YjcTup@p_`0!6Z3e8(`4tDt>i*iK+4K%iZ~XB0SfQb>Qk GKz{>kB*~Eg literal 0 HcmV?d00001 diff --git a/checkstyle/target/classes/org/devgateway/toolkit/checks/CachableQueryAnnotationCheck.class b/checkstyle/target/classes/org/devgateway/toolkit/checks/CachableQueryAnnotationCheck.class new file mode 100644 index 0000000000000000000000000000000000000000..b450e25100d34a937f0ee3fd2c23e33499923992 GIT binary patch literal 1746 zcmbVNOH&(15dH=UR+440RvyIfCHNr;#M%yi#1IErKth!eWkjfQd`OL!u{3DeQSFYv z`V097$tky7lM6|uk{omJ!T%?RJbG4?P4pFl&~sg&Qf{v~Vkf3_dc@oQ2yArK6+k}qSWFYFj-KGdP zdDAB(UsE3Uw|FSc{t!&+wu~4SYAS5G+hVW9wbJNZl5pvrm&Vu=l2592Gi?M}$N9H7tYm=8o`m7N24;R){Gj^J$dif8`l@Bmxr@zBgId757w>VeMr{cw# z5}l> + + + + + + + diff --git a/checkstyle/target/maven-archiver/pom.properties b/checkstyle/target/maven-archiver/pom.properties new file mode 100644 index 00000000..abc2b553 --- /dev/null +++ b/checkstyle/target/maven-archiver/pom.properties @@ -0,0 +1,5 @@ +#Generated by Maven +#Tue Feb 01 09:57:37 ART 2022 +groupId=org.devgateway.toolkit +artifactId=checkstyle +version=1.0 diff --git a/checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst new file mode 100644 index 00000000..985cb47c --- /dev/null +++ b/checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst @@ -0,0 +1 @@ +org/devgateway/toolkit/checks/CachableQueryAnnotationCheck.class diff --git a/checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst new file mode 100644 index 00000000..c4b4099f --- /dev/null +++ b/checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst @@ -0,0 +1 @@ +/home/sdimunzio/projects/tcdi-ng/tcdi-admin/checkstyle/src/main/java/org/devgateway/toolkit/checks/CachableQueryAnnotationCheck.java From 18205893f1ddf104487c062453c6fdc5c62c111e Mon Sep 17 00:00:00 2001 From: sdimunzio Date: Thu, 3 Feb 2022 11:01:37 -0300 Subject: [PATCH 050/137] updating admin reverse proxy --- .../devgateway/toolkit/persistence/application-dev.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties index 54a6a199..0abb1340 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties @@ -10,7 +10,7 @@ # Development Gateway - initial API and implementation ############################################################################### spring.config.activate.on-profile=dev - spring.datasource.username=postgres spring.datasource.password=admin -spring.datasource.jdbc-url=jdbc:postgresql:tcdi-admin +spring.datasource.jdbc-url=jdbc:postgresql://localhost:5432/tcdi_admin +management.health.mail.enabled=false \ No newline at end of file From 17e9f080569eff81357cadb5df2b3ac6b092ac9a Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 3 Feb 2022 16:50:05 +0200 Subject: [PATCH 051/137] TOBACCO-828: Set base path to admin --- .../toolkit/forms/FormsSecurityConfig.java | 26 +++++++++++-------- .../toolkit/forms/wicket/WebInitializer.java | 12 +++++---- .../forms/wicket/page/user/LogoutPage.java | 9 +++---- .../persistence/application-dev.properties | 4 ++- .../persistence/application.properties | 2 ++ .../devgateway/toolkit/web/WebConstants.java | 9 ------- .../rest/controller/HTTPErrorController.java | 12 ++++++--- .../toolkit/web/spring/WebSecurityConfig.java | 16 +++++++----- .../toolkit/web/util/SettingsUtils.java | 16 ++++++++++++ 9 files changed, 64 insertions(+), 42 deletions(-) delete mode 100644 web/src/main/java/org/devgateway/toolkit/web/WebConstants.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java b/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java index 9b97fa58..598e52c7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java @@ -13,6 +13,8 @@ import org.devgateway.toolkit.persistence.spring.CustomJPAUserDetailsService; import org.devgateway.toolkit.web.spring.WebSecurityConfig; +import org.devgateway.toolkit.web.util.SettingsUtils; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; @@ -25,8 +27,6 @@ import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices; import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices; -import static org.devgateway.toolkit.web.WebConstants.FORMS_BASE_PATH; - @Configuration @EnableWebSecurity @Order(1) // this ensures the forms security comes first @@ -37,6 +37,9 @@ public class FormsSecurityConfig extends WebSecurityConfig { */ private static final String UNIQUE_SECRET_REMEMBER_ME_KEY = "secret"; + @Autowired + private SettingsUtils settingsUtils; + /** * We ensure the superclass configuration is being applied Take note the * {@link FormsSecurityConfig} extends {@link WebSecurityConfig} which has @@ -47,18 +50,19 @@ public class FormsSecurityConfig extends WebSecurityConfig { @Override public void configure(final WebSecurity web) throws Exception { super.configure(web); + String formsBasePath = settingsUtils.getFormsBasePath(); web.ignoring().antMatchers("/img/**", "/css*/**", "/js*/**", "/assets*/**", "/favicon.ico", "/resources/**", "/resources/public/**"); web.ignoring().antMatchers( - FORMS_BASE_PATH + "/wicket/resource/**/*.js", - FORMS_BASE_PATH + "/wicket/resource/**/*.css", - FORMS_BASE_PATH + "/wicket/resource/**/*.png", - FORMS_BASE_PATH + "/wicket/resource/**/*.jpg", - FORMS_BASE_PATH + "/wicket/resource/**/*.woff", - FORMS_BASE_PATH + "/wicket/resource/**/*.woff2", - FORMS_BASE_PATH + "/wicket/resource/**/*.ttf", - FORMS_BASE_PATH + "/wicket/resource/**/*.svg", - FORMS_BASE_PATH + "/wicket/resource/**/*.gif"); + formsBasePath + "/wicket/resource/**/*.js", + formsBasePath + "/wicket/resource/**/*.css", + formsBasePath + "/wicket/resource/**/*.png", + formsBasePath + "/wicket/resource/**/*.jpg", + formsBasePath + "/wicket/resource/**/*.woff", + formsBasePath + "/wicket/resource/**/*.woff2", + formsBasePath + "/wicket/resource/**/*.ttf", + formsBasePath + "/wicket/resource/**/*.svg", + formsBasePath + "/wicket/resource/**/*.gif"); } /** diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/WebInitializer.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/WebInitializer.java index f95b5aa6..395699b6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/WebInitializer.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/WebInitializer.java @@ -13,6 +13,8 @@ import org.apache.wicket.protocol.http.WicketFilter; import org.apache.wicket.spring.SpringWebApplicationFactory; +import org.devgateway.toolkit.web.util.SettingsUtils; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.ServletContextInitializer; import org.springframework.context.annotation.Configuration; import org.springframework.security.web.session.HttpSessionEventPublisher; @@ -21,8 +23,6 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; -import static org.devgateway.toolkit.web.WebConstants.FORMS_BASE_PATH; - /** * This class is the replacement of the web.xml. It registers the wicket filter * in the spring aware configuration style. @@ -33,8 +33,10 @@ @Configuration public class WebInitializer implements ServletContextInitializer { + @Autowired + private SettingsUtils settingsUtils; + private static final String PARAM_APP_BEAN = "applicationBean"; - public static final String FORMS_PATH_PATTERN = FORMS_BASE_PATH + "/*"; @Override public void onStartup(final ServletContext sc) throws ServletException { @@ -53,8 +55,8 @@ public void onStartup(final ServletContext sc) throws ServletException { filter.setInitParameter(PARAM_APP_BEAN, "formsWebApplication"); // This line is the only surprise when comparing to the equivalent // web.xml. Without some initialization seems to be missing. - filter.setInitParameter(WicketFilter.FILTER_MAPPING_PARAM, FORMS_PATH_PATTERN); - filter.addMappingForUrlPatterns(null, false, FORMS_PATH_PATTERN); + filter.setInitParameter(WicketFilter.FILTER_MAPPING_PARAM, settingsUtils.getFormsBasePath() + "/*"); + filter.addMappingForUrlPatterns(null, false, settingsUtils.getFormsBasePath() + "/*"); // // Request Listener // sc.addListener(new RequestContextListener()); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LogoutPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LogoutPage.java index 5bd2b52f..633ac913 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LogoutPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LogoutPage.java @@ -17,15 +17,13 @@ import org.apache.wicket.authroles.authentication.AbstractAuthenticatedWebSession; import org.apache.wicket.markup.html.pages.RedirectPage; import org.apache.wicket.request.cycle.RequestCycle; -import org.apache.wicket.spring.injection.annot.SpringBean; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.web.authentication.RememberMeServices; import org.wicketstuff.annotation.mount.MountPath; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import static org.devgateway.toolkit.web.WebConstants.FORMS_BASE_PATH; - /** * @author mpostelnicu * @@ -34,11 +32,12 @@ public class LogoutPage extends RedirectPage { private static final long serialVersionUID = 1L; - @SpringBean(required = false) + @Autowired(required = false) private RememberMeServices rememberMeServices; public LogoutPage() { - super(RequestCycle.get().getRequest().getContextPath() + FORMS_BASE_PATH + "/login"); + super(RequestCycle.get().getRequest().getContextPath() + + RequestCycle.get().getRequest().getFilterPath() + "/login"); AbstractAuthenticatedWebSession.get().invalidate(); if (rememberMeServices != null) { diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties index 0abb1340..cb51f917 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties @@ -13,4 +13,6 @@ spring.config.activate.on-profile=dev spring.datasource.username=postgres spring.datasource.password=admin spring.datasource.jdbc-url=jdbc:postgresql://localhost:5432/tcdi_admin -management.health.mail.enabled=false \ No newline at end of file +management.health.mail.enabled=false + +dg-toolkit.forms.base-path=/admin \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties index 0a3825be..19095afc 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties @@ -54,3 +54,5 @@ spring.cache.jcache.config=classpath:ehcache.xml spring.data.rest.base-path=/rest spring.profiles.active=integration + +dg-toolkit.forms.base-path=/admin diff --git a/web/src/main/java/org/devgateway/toolkit/web/WebConstants.java b/web/src/main/java/org/devgateway/toolkit/web/WebConstants.java deleted file mode 100644 index dce15350..00000000 --- a/web/src/main/java/org/devgateway/toolkit/web/WebConstants.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.devgateway.toolkit.web; - -public final class WebConstants { - private WebConstants() { - } - - // by default no custom base path for forms - public static final String FORMS_BASE_PATH = ""; -} diff --git a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/HTTPErrorController.java b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/HTTPErrorController.java index 76125b68..840c09c4 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/HTTPErrorController.java +++ b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/HTTPErrorController.java @@ -1,5 +1,7 @@ package org.devgateway.toolkit.web.rest.controller; +import org.devgateway.toolkit.web.util.SettingsUtils; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.RequestMapping; @@ -10,13 +12,15 @@ import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import static org.devgateway.toolkit.web.WebConstants.FORMS_BASE_PATH; - /** * @author Nadejda Mandrescu */ @RestController public class HTTPErrorController implements ErrorController { + + @Autowired + private SettingsUtils settingsUtils; + @Override public String getErrorPath() { return null; @@ -29,9 +33,9 @@ public void handleError(final HttpServletRequest request, final HttpServletRespo int statusCode = Integer.parseInt(status.toString()); String contextPath = request.getContextPath(); if (statusCode == HttpStatus.NOT_FOUND.value()) { - response.sendRedirect(contextPath + FORMS_BASE_PATH + "/error/not-found"); + response.sendRedirect(contextPath + settingsUtils.getFormsBasePath() + "/error/not-found"); } else if (statusCode == HttpStatus.FORBIDDEN.value()) { - response.sendRedirect(contextPath + FORMS_BASE_PATH + "/error/access-denied"); + response.sendRedirect(contextPath + settingsUtils.getFormsBasePath() + "/error/access-denied"); } } } diff --git a/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java b/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java index 708e9269..849b7056 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java +++ b/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java @@ -12,6 +12,7 @@ package org.devgateway.toolkit.web.spring; import org.devgateway.toolkit.persistence.spring.CustomJPAUserDetailsService; +import org.devgateway.toolkit.web.util.SettingsUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; @@ -36,8 +37,6 @@ import org.springframework.security.web.firewall.HttpFirewall; import org.springframework.security.web.firewall.StrictHttpFirewall; -import static org.devgateway.toolkit.web.WebConstants.FORMS_BASE_PATH; - /** * @author mpostelnicu This configures the spring security for the Web project. * An @@ -63,6 +62,9 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private PasswordEncoder passwordEncoder; + @Autowired + private SettingsUtils settingsUtils; + @Bean public HttpFirewall allowUrlEncodedSlashHttpFirewall() { final StrictHttpFirewall firewall = new StrictHttpFirewall(); @@ -89,16 +91,16 @@ public void configure(final WebSecurity web) throws Exception { web.httpFirewall(allowUrlEncodedSlashHttpFirewall()) .ignoring().antMatchers(allowedApiEndpoints).and() .ignoring().antMatchers( - FORMS_BASE_PATH + "/login", - FORMS_BASE_PATH + "/forgotPassword/**"); + settingsUtils.getFormsBasePath() + "/login", + settingsUtils.getFormsBasePath() + "/forgotPassword/**"); } @Override protected void configure(final HttpSecurity http) throws Exception { http.authorizeRequests().expressionHandler(webExpressionHandler()) // inject role hierarchy - .antMatchers(FORMS_BASE_PATH + "/monitoring/**").access("hasRole('ROLE_ADMIN')") - .antMatchers(FORMS_BASE_PATH + "/**").authenticated().and() - .formLogin().loginPage(FORMS_BASE_PATH + "/login").permitAll().and() + .antMatchers(settingsUtils.getFormsBasePath() + "/monitoring/**").access("hasRole('ROLE_ADMIN')") + .antMatchers(settingsUtils.getFormsBasePath() + "/**").authenticated().and() + .formLogin().loginPage(settingsUtils.getFormsBasePath() + "/login").permitAll().and() .requestCache().and().logout().permitAll().and() .sessionManagement().and().csrf().disable(); http.addFilter(securityContextPersistenceFilter()); diff --git a/web/src/main/java/org/devgateway/toolkit/web/util/SettingsUtils.java b/web/src/main/java/org/devgateway/toolkit/web/util/SettingsUtils.java index 7fd5e17a..ca9eb907 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/util/SettingsUtils.java +++ b/web/src/main/java/org/devgateway/toolkit/web/util/SettingsUtils.java @@ -21,14 +21,24 @@ */ @Service public class SettingsUtils { + public static final int START_YEAR = 2000; + public static final String DEFAULT_LANGUAGE = "en_US"; + protected static Logger logger = LoggerFactory.getLogger(SettingsUtils.class); + @Autowired private AdminSettingsService adminSettingsService; + private AdminSettings setting; + @Value("${googleAnalyticsTrackingId:#{null}}") private String googleAnalyticsTrackingId; + + @Value("${dg-toolkit.forms.base-path}") + private String formsBasePath; + @Autowired private AdminSettingsRepository adminSettingsRepository; @@ -76,5 +86,11 @@ public AdminSettings getSettings() { } } + public String getFormsBasePath() { + return formsBasePath; + } + public void setFormsBasePath(final String formsBasePath) { + this.formsBasePath = formsBasePath; + } } From d525d745b0f1fd924422498348fad94563d7d129 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Tue, 15 Feb 2022 12:18:04 +0200 Subject: [PATCH 052/137] TOBACCO-791: Fix default sorting --- .../org/devgateway/toolkit/forms/FormsSecurityConfig.java | 7 +++++-- .../wicket/page/lists/dataset/ListTetsimDatasetPage.java | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java b/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java index 598e52c7..c9d97c36 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java @@ -51,8 +51,11 @@ public class FormsSecurityConfig extends WebSecurityConfig { public void configure(final WebSecurity web) throws Exception { super.configure(web); String formsBasePath = settingsUtils.getFormsBasePath(); - web.ignoring().antMatchers("/img/**", "/css*/**", "/js*/**", "/assets*/**", "/favicon.ico", "/resources/**", - "/resources/public/**"); + web.ignoring().antMatchers(formsBasePath + "/img/**", + formsBasePath + "/css*/**", + formsBasePath + "/js*/**", + formsBasePath + "/assets*/**", formsBasePath + "/favicon.ico", formsBasePath + "/resources/**", + formsBasePath + "/resources/public/**"); web.ignoring().antMatchers( formsBasePath + "/wicket/resource/**/*.js", formsBasePath + "/wicket/resource/**/*.css", diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java index 73f4fcf6..b3150e9a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java @@ -87,7 +87,7 @@ public IModel getDataModel(final IModel rowModel) { protected void onInitialize() { super.onInitialize(); - dataProvider.setSort("year", SortOrder.ASCENDING); + dataProvider.setSort("year", SortOrder.DESCENDING); addNewYearSelector(); From ecf3315aeda2747d0e9d44d5297d0108e6102e94 Mon Sep 17 00:00:00 2001 From: sdimunzio Date: Tue, 15 Feb 2022 11:35:52 -0300 Subject: [PATCH 053/137] flexible API refactoring --- .../devgateway/toolkit/forms/wicket/page/BasePage.properties | 2 +- .../page/edit/dataset/TetsimBaselineNumbersPanel.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties index a0fe0e79..fb6c225a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties @@ -16,7 +16,7 @@ navbar.groups=Groups navbar.admin=Admin navbar.datasets=Datasets navbar.tetsim=TETSIM -navbar.prevalence=Prevalence +navbar.seed=Prevalence navbar.policy=Policy navbar.ecigarettes=E-cigarette navbar.categories=Categories diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties index 29b2524f..5696265b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties @@ -10,5 +10,5 @@ cigaretteDeclaredCustomValue.unit={0} per pack adultPopulation.label=Adult Population (15+) adultPopulation.unit=Full number -smokingPrevalence.label=Smoking prevalence +smokingPrevalence.label=Smoking seed smokingPrevalence.unit=Percentage \ No newline at end of file From b85062c1a2035612563341f14342b6b8c537d4ed Mon Sep 17 00:00:00 2001 From: sdimunzio Date: Tue, 15 Feb 2022 15:39:56 -0300 Subject: [PATCH 054/137] flexible API refactoring --- docker-compose.override.yml | 13 ------------- docker-compose.yml | 35 ----------------------------------- 2 files changed, 48 deletions(-) delete mode 100644 docker-compose.override.yml delete mode 100644 docker-compose.yml diff --git a/docker-compose.override.yml b/docker-compose.override.yml deleted file mode 100644 index 25439865..00000000 --- a/docker-compose.override.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: '3.4' - -services: - admin: - build: - context: forms - - postgres: - volumes: - - ./data/postgres:/var/lib/postgresql/data - networks: &both - - backend - - frontend diff --git a/docker-compose.yml b/docker-compose.yml deleted file mode 100644 index 703e8658..00000000 --- a/docker-compose.yml +++ /dev/null @@ -1,35 +0,0 @@ -version: '3.4' - -services: - admin: - image: ${REPO}tcdi-admin/admin:${TAG-local} - depends_on: - - postgres - networks: - - backend - - frontend - ports: - - 80:8080 - logging: &json_file - driver: json-file - - postgres: - image: mdillon/postgis - restart: unless-stopped - volumes: - - postgres:/var/lib/postgresql/data - networks: - - backend - environment: - POSTGRES_PASSWORD: postgres - POSTGRES_USER: postgres - POSTGRES_DB: tcdi-admin - logging: *json_file - -volumes: - postgres: null - -networks: - backend: - frontend: - driver: bridge From f14c2d180d494adf422c800a3cdca997fc29d4ea Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 17 Feb 2022 11:21:16 +0200 Subject: [PATCH 055/137] Revert "flexible API refactoring" This reverts commit ecf3315aeda2747d0e9d44d5297d0108e6102e94. --- .../devgateway/toolkit/forms/wicket/page/BasePage.properties | 2 +- .../page/edit/dataset/TetsimBaselineNumbersPanel.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties index fb6c225a..a0fe0e79 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties @@ -16,7 +16,7 @@ navbar.groups=Groups navbar.admin=Admin navbar.datasets=Datasets navbar.tetsim=TETSIM -navbar.seed=Prevalence +navbar.prevalence=Prevalence navbar.policy=Policy navbar.ecigarettes=E-cigarette navbar.categories=Categories diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties index 5696265b..29b2524f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.properties @@ -10,5 +10,5 @@ cigaretteDeclaredCustomValue.unit={0} per pack adultPopulation.label=Adult Population (15+) adultPopulation.unit=Full number -smokingPrevalence.label=Smoking seed +smokingPrevalence.label=Smoking prevalence smokingPrevalence.unit=Percentage \ No newline at end of file From f04dd2699dbdf9fc540baf118daf439472a1a8f7 Mon Sep 17 00:00:00 2001 From: sdimunzio Date: Thu, 3 Mar 2022 17:06:26 -0300 Subject: [PATCH 056/137] updating dimension names --- entrypoint.sh | 3 +++ forms/entrypoint.sh | 38 +++++++++++++++----------------------- 2 files changed, 18 insertions(+), 23 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index cb7485aa..58ac7b02 100644 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -11,9 +11,12 @@ spring.datasource.jdbc-url spring.datasource.url spring.mail.host + spring.jpa.hibernate.ddl-auto EOF )" + env + echo "$PROPERTIES" | while IFS=read PROPERTY; do VAR_NAME="$(echo "$PROPERTY" | tr '[:lower:].-' '[:upper:]__')" eval VALUE="\$$VAR_NAME" diff --git a/forms/entrypoint.sh b/forms/entrypoint.sh index 0ae08515..ce870333 100755 --- a/forms/entrypoint.sh +++ b/forms/entrypoint.sh @@ -1,32 +1,24 @@ -#!/bin/sh +#!/bin/bash PROP_FILE="/etc/$1.properties" - echo "Writing to $PROP_FILE:" - truncate -s 0 $PROP_FILE + truncate -s 0 $PROP_FILE + echo "..................... Writing to $PROP_FILE: ............... " - echo "..................... Writing to $PROP_FILE: ............... " + while IFS='=' read -r -d '' n v; do + if [[ $n == SPRING* ]]; then + VAR_NAME="$(echo "$n" | tr '[:upper:]_' '[:lower:].')" + echo "$VAR_NAME=$v" >> $PROP_FILE + fi + done < <(env -0) - PROPERTIES="$(cat <<-EOF - server.port - spring.application.name - spring.liquibase.enabled - spring.datasource.url - spring.datasource.jdbc.url - spring.datasource.username - spring.datasource.password - spring.jpa.hibernate.ddl.auto + while IFS='=' read -r -d '' n v; do + if [[ $n == TCDI_* ]]; then + VAR_NAME="$(echo "$n" | tr '[:upper:]_' '[:lower:].' | cut -c 6-)" + echo "$VAR_NAME=$v" >> $PROP_FILE + fi + done < <(env -0) - EOF - )" - - echo "$PROPERTIES" | while IFS= read PROPERTY; do - VAR_NAME="$(echo "$PROPERTY" | tr '[:lower:].-' '[:upper:]__')" - eval VALUE="\$$VAR_NAME" - if [ -n "$VALUE" ]; then - echo "$PROPERTY=$VALUE" - fi - done | tee -a "$PROP_FILE" echo "................. Properties ................." cat $PROP_FILE echo "................. End sou ................." From 4c10e795e1f6fd7adc8c5fb8840b6de072c43874 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 14 Mar 2022 14:10:39 +0200 Subject: [PATCH 057/137] TOBACCO-830: Remove unused files --- checkstyle/target/checkstyle-1.0.jar | Bin 3484 -> 0 bytes .../checks/CachableQueryAnnotationCheck.class | Bin 1746 -> 0 bytes checkstyle/target/classes/packagenames.xml | 10 ---------- checkstyle/target/maven-archiver/pom.properties | 5 ----- .../compile/default-compile/createdFiles.lst | 1 - .../compile/default-compile/inputFiles.lst | 1 - 6 files changed, 17 deletions(-) delete mode 100644 checkstyle/target/checkstyle-1.0.jar delete mode 100644 checkstyle/target/classes/org/devgateway/toolkit/checks/CachableQueryAnnotationCheck.class delete mode 100644 checkstyle/target/classes/packagenames.xml delete mode 100644 checkstyle/target/maven-archiver/pom.properties delete mode 100644 checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst delete mode 100644 checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst diff --git a/checkstyle/target/checkstyle-1.0.jar b/checkstyle/target/checkstyle-1.0.jar deleted file mode 100644 index 41e9041d4ce589fb66c11518b1791b5118af644b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3484 zcmbVP2{_c-8y=Ls8v8!TzRNoKlU_RQ6O9kt~U1 z&zcYtUEBT571KZ5?$ep)w>-~$?|aU7zWLtsjwy_42R(>16pv_I{PXhTMh84i^ewby zj1C*fnf?f)1t|bwoZ_{v7~pGv;9~tb%tZUJk%7Lsg{+CetVu)tA()J8^DdZ-WMjjd zLb&`}#l9hTY2(IPX_$--EzRI<%V>6~D&Y$y$)Ru-7~Gt2Lo$z*mx1}ZBAm^Wr5--Z zdUdWr%K#d4YB<^l8EUS8ht1|F%nDwXD7BM#ujS#xKE}m8>ptyH0a{<*<}`Ky>%+P` zZ)C7JV$Y8VC*(P21Oa&-LHw6sj?KXYEY=m}LiiUDWP6a~X`~|xzk#Lwrwq6*M)tP= z<|G9O1O}csgd+;!jKm<&NWAO?v@1Hi0P{>995An5Gxu%bX^!Z=zGf*APkj{eKmv#EtA^;8@C2Z9Sv$LgXGB0i4MRw-T8O@%Y|HHT$B- zWa2%`!BlI*`0)2h5B)~Jr}GKE6#W<^qI9C4X1#)IJAl83YqF;Tfm*0RAg$l-o-V@i zG{V6ZX?7OrPSnO=uml9b1&h%o?X9e%D*}(daTJE<(Fd-_5QfwT{P+u%L7{Q$<)?ziz*EU%jzCyVQI^0$Ktj3fTH&`XO8c1by@m)^5 zaS+R$GpLIhnTtu2_cEPVy=Ok$1Pzl9o(Qy!I(?_V!r zQ-D+UW6bAjOZFdU6pK?;d8Z1=l~Lu6k&ES;dB|7!()K2e%;Q_STt&lmSvi*tXSJ|y zPsBJ4IGhCL_yY6_ifSTqbI>i}ZB7E8D!MahRf(+})Q5;&y#u$D#(fpCKPWg@Wo6$V z!h}|^w>#XNx6O<0jqIH3d^WC!iSa;x{Brcjm1SeF`0Ixj+HIfVhUZ|TBGVD`o)y_@ zdj+bU3J8~C1PjH4h*?g>$8(8i+9$r1c2{!DcxfIG<>pOWti%zImBMuJW5>9YW<_sC zpPB5Mi)lyT0twEBQ}o@IA6R*sp9`6MR#uuDmbPV!o@4hb28(v3X zaNdFi<-9wS=IumDfp`J6PDd;5M@)9!G{(L1gOFDzJ@f;b&HVCW116b56WeW?7btGU znzX8UtFyXzwmFEi9kbuv=RHxARy~m@G*x=xHqV2x>s&FJP*=lvAEG`*0RFyPh*OH? zRNoF}rOe6nX^oa*VXnH!Z2KzjaFd=)HzmtX@uqkUr7EsuK2Qojv{y%=r#@^cr6le? zetbUaTgP8VN{Y$>>!zZTLbEaN`MfAfG!w(x*JMi5<-n~Pf0i$K-} zs7PPmUN-_4e?RrIS}cxE`L8xshehG{G7&@2J7!g9AMlAu)8oM92__NYk*YyM)lbB& z;%{Sz`K@kOaw>kAR$Oo1t;KcY6hR}-Au$_Tw>el8==5KL0qK?{3$yI+wRYcs=2(+n z0?`$@u_Rhh+C@!^eX3tZ&jQjr0tgWFPv~%1G)boY;q@3ld2soN6!;Tcl9Gl6liT4u z3kfr+xm$L&9ucd9Q?`Cq26j26eWw`D%WRvi|XfwdWS|*#Gy2xEeaMY8# zJI>v9-2lh;(s8NMM!jtJ{;(@bvBuQ8B~0e6791gFAJk_D7W#M{9gAtw0|L7)873l( z@}W-H9=a9_mh!+b^=s^wp72xrP&eE6ogHXuI!IMY9DB~&$v0v8ygAXwv&Pu1?>u;T zpKkI~O1FX5i%X7omxCKUcjaqvwk)=YTs~kN>E>i%EnkefE@XnETZt<~4cR(Kw(s>z z8)C}Tw1r9)6&XHF0YCDmLKGFswOA+62bb1}98(21zpSEGIg8hd(^rP|pW@m%BCIP_ zf&)s32QJM&EhWw!i$l5-T#)!(^#$}mML|s(_HKO;2jfWk-L}Woii0$9qU}oJM*H7H zFL`zMqEe!R%xa&*5!E_I%Cp*EQgS&**r@ePAZ&4<5=wzXd) z1(U{YUoqgm0sG0lkr_63Dalc-4KQd~`z7$Y=C8J2D#>B34H9AucqJjoZ4LC__F$6Z zS{o!VJJ6TEfXSM$JqgKykx5|NlWh30b*`-)**aU1Zy><+t3M;Bv$dNcqk}28P3Ol- ze(!C_vu&=`&pW@mY5=&YjcTup@p_`0!6Z3e8(`4tDt>i*iK+4K%iZ~XB0SfQb>Qk GKz{>kB*~Eg diff --git a/checkstyle/target/classes/org/devgateway/toolkit/checks/CachableQueryAnnotationCheck.class b/checkstyle/target/classes/org/devgateway/toolkit/checks/CachableQueryAnnotationCheck.class deleted file mode 100644 index b450e25100d34a937f0ee3fd2c23e33499923992..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1746 zcmbVNOH&(15dH=UR+440RvyIfCHNr;#M%yi#1IErKth!eWkjfQd`OL!u{3DeQSFYv z`V097$tky7lM6|uk{omJ!T%?RJbG4?P4pFl&~sg&Qf{v~Vkf3_dc@oQ2yArK6+k}qSWFYFj-KGdP zdDAB(UsE3Uw|FSc{t!&+wu~4SYAS5G+hVW9wbJNZl5pvrm&Vu=l2592Gi?M}$N9H7tYm=8o`m7N24;R){Gj^J$dif8`l@Bmxr@zBgId757w>VeMr{cw# z5}l> - - - - - - - diff --git a/checkstyle/target/maven-archiver/pom.properties b/checkstyle/target/maven-archiver/pom.properties deleted file mode 100644 index abc2b553..00000000 --- a/checkstyle/target/maven-archiver/pom.properties +++ /dev/null @@ -1,5 +0,0 @@ -#Generated by Maven -#Tue Feb 01 09:57:37 ART 2022 -groupId=org.devgateway.toolkit -artifactId=checkstyle -version=1.0 diff --git a/checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst deleted file mode 100644 index 985cb47c..00000000 --- a/checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst +++ /dev/null @@ -1 +0,0 @@ -org/devgateway/toolkit/checks/CachableQueryAnnotationCheck.class diff --git a/checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst deleted file mode 100644 index c4b4099f..00000000 --- a/checkstyle/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst +++ /dev/null @@ -1 +0,0 @@ -/home/sdimunzio/projects/tcdi-ng/tcdi-admin/checkstyle/src/main/java/org/devgateway/toolkit/checks/CachableQueryAnnotationCheck.java From ee2a811192ec7687b194a0a2cd5422d62c451632 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 14 Mar 2022 14:17:31 +0200 Subject: [PATCH 058/137] TOBACCO-840: Calculate variables in TETSIM Outputs --- .../forms/service/TetsimOutputService.java | 9 + .../tetsim/TetsimOutputBaseCalculator.java | 548 ++++++++++++++++++ .../util/tetsim/TetsimOutputCalculator.java | 9 + .../TetsimOutputOvershiftCalculator.java | 27 + .../TetsimOutputUndershiftCalculator.java | 33 ++ .../toolkit/forms/util/tetsim/TetsimUtil.java | 19 + .../persistence/dao/data/TetsimDataset.java | 20 +- .../toolkit/persistence/dto/TetsimOutput.java | 132 +++++ .../persistence/dto/TetsimOutputs.java | 33 ++ 9 files changed, 820 insertions(+), 10 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/TetsimOutputService.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculator.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculator.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculator.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimUtil.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutputs.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/TetsimOutputService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/TetsimOutputService.java new file mode 100644 index 00000000..e494ad5b --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/TetsimOutputService.java @@ -0,0 +1,9 @@ +package org.devgateway.toolkit.forms.service; + +import org.springframework.stereotype.Service; + +@Service +public class TetsimOutputService { + + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java new file mode 100644 index 00000000..10e36dab --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java @@ -0,0 +1,548 @@ +package org.devgateway.toolkit.forms.util.tetsim; + +import com.google.common.collect.ImmutableMap; +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dto.TetsimOutput; + +import java.math.BigDecimal; +import java.math.MathContext; +import java.util.Map; + +import static java.math.BigDecimal.ONE; +import static java.math.BigDecimal.TEN; +import static java.math.BigDecimal.ZERO; +import static org.devgateway.toolkit.forms.util.tetsim.TetsimUtil.getTobaccoProductValueFromVariable; + +/** + * @author vchihai + */ +public abstract class TetsimOutputBaseCalculator implements TetsimOutputCalculator { + + public static final BigDecimal HUNDRED = TEN.scaleByPowerOfTen(1); + + public static final MathContext DEFAULT_CONTEXT = MathContext.DECIMAL64; + + protected final TetsimDataset dataset; + + protected final Double percentageChange; + + protected final Double trackTracingAdditionalCost; + + protected final Double levyPercentageChange; + + protected final Double changeInTheDeclaredCustomValue = 0.0; + + public static final Map GAIN_SWITCH_TOBACCO_PRODUCT = new ImmutableMap.Builder() + .put("Popular", "Premium") + .put("Discount", "Popular") + .put("Illicit", "Discount") + .build(); + + public static final Map CONSUMPTION_DEPENDENT_TOBACCO_PRODUCT = new ImmutableMap.Builder() + .put("Imported", "Premium") + .put("Premium", "Popular") + .put("Popular", "Discount") + .put("Discount", "Illicit") + .build(); + + public TetsimOutputBaseCalculator(TetsimDataset dataset, Double percentageChange) { + this(dataset, percentageChange, 0.0, 0.0); + } + + public TetsimOutputBaseCalculator(TetsimDataset dataset, Double percentageChange, + Double trackTracingAdditionalCost, Double levyPercentageChange) { + this.dataset = dataset; + this.percentageChange = percentageChange; + this.trackTracingAdditionalCost = trackTracingAdditionalCost; + this.levyPercentageChange = levyPercentageChange; + } + + protected abstract BigDecimal calculateAbsChangeShift(String tobaccoProduct); + + @Override + public TetsimOutput calculate() { + TetsimOutput tetsimOutput = new TetsimOutput(); + tetsimOutput.setConsumptionLegal(calculateOutputConsumptionLegal()); + tetsimOutput.setConsumptionIllicit(calculateOutputConsumptionIllicit()); + tetsimOutput.setExciseRev(calculateOutputExciseRev()); + tetsimOutput.setTotalGovRev(calculateOutputTotalGovRev()); + tetsimOutput.setExciseBurden(calculateOutputExciseBurden()); + tetsimOutput.setTotalTaxBurden(calculateOutputTotalTaxBurden()); + tetsimOutput.setRetailPrice(calculateOutputRetailPrice()); + tetsimOutput.setNot(calculateOutputNot()); + tetsimOutput.setExciseTax(calculateOutputExciseTax()); + tetsimOutput.setVat(calculateOutputVat()); + tetsimOutput.setLevy(calculateOutputLevy()); + + return tetsimOutput; + } + + public BigDecimal calculateOutputConsumptionLegal() { + return calculateTotalLegalConsumption(); + } + + private BigDecimal calculateOutputConsumptionIllicit() { + return calculateConsumption("Illicit"); + } + + private BigDecimal calculateOutputExciseRev() { + return ZERO; + } + + private BigDecimal calculateOutputTotalGovRev() { + return ZERO; + } + + /** + * Calculate the Output Excise Burden + */ + private BigDecimal calculateOutputExciseBurden() { + return calculateExciseBurden("Popular"); + } + + /** + * Calculate the Output Total Tax Burden + */ + private BigDecimal calculateOutputTotalTaxBurden() { + return calculateTotalTaxBurden("Popular"); + } + + /** + * Calculate the Output Retail Price + */ + public BigDecimal calculateOutputRetailPrice() { + return calculateRetailPrice("Popular"); + } + + /** + * Calculate the Output NOT + */ + public BigDecimal calculateOutputNot() { + return calculateNetTaxPrice("Popular"); + } + + /** + * Calculate the Output Excise Tax + */ + public BigDecimal calculateOutputExciseTax() { + return calculateExciseTaxDomesticProduction("Popular"); + } + + /** + * Calculate the Output VAT + */ + public BigDecimal calculateOutputVat() { + return calculateVat("Popular"); + } + + /** + * Calculate the Output Levy + */ + public BigDecimal calculateOutputLevy() { + return calculateTobaccoLevy("Popular"); + } + + /** + * Calculates Net of Tax Price + * + * @param tobaccoProduct + */ + public BigDecimal calculateNetTaxPrice(String tobaccoProduct) { + BigDecimal netTaxPrice = calculateBaselineNetTaxPrice(tobaccoProduct); + if (tobaccoProduct.equals("Illicit")) { + BigDecimal shift = getTobaccoProductValueFromVariable(dataset.getChangeInIllicitNot(), + tobaccoProduct); + BigDecimal discountRetailPriceDifference = calculateRetailPrice("Discount") + .subtract(calculateBaselineRetailPrice("Discount")); + return netTaxPrice.add(shift.multiply(discountRetailPriceDifference)); + } + + return netTaxPrice.add(calculateAbsChangeShift(tobaccoProduct)); + } + + /** + * Calculates Additional charges related to Track and Tracing + */ + private BigDecimal calculateAdditionalCharges() { + return BigDecimal.valueOf(trackTracingAdditionalCost); + } + + /** + * Calculate Tobacco levy + * CIF per pack * (levy rate + percentage change in levy) / 100 + */ + protected BigDecimal calculateTobaccoLevy(String tobaccoProduct) { + BigDecimal cif = getTobaccoProductValueFromVariable(dataset.getCif(), tobaccoProduct); + BigDecimal levy = getTobaccoProductValueFromVariable(dataset.getTobaccoLevy(), tobaccoProduct); + + return cif.multiply(levy.add(BigDecimal.valueOf(levyPercentageChange))) + .divide(HUNDRED, DEFAULT_CONTEXT); + }; + + /** + * Excise tax from baseline * (1 + percent increase in excise tax/100) + * + * @param tobaccoProduct + * @return + */ + protected BigDecimal calculateExciseTaxDomesticProduction(String tobaccoProduct) { + return calculateBaselineExciseTaxOnDomesticProduction(tobaccoProduct) + .multiply(ONE.add(BigDecimal.valueOf(percentageChange).divide(HUNDRED, DEFAULT_CONTEXT))); + } + + /** + * Excise tax from baseline * (1 + percent increase in excise tax/100) + * + * @param tobaccoProduct + * @return + */ + protected BigDecimal calculateExciseTaxImportedCigarettes(String tobaccoProduct) { + if (tobaccoProduct.equals("Imported")) { + return calculateBaselineExciseTaxOnImported(tobaccoProduct) + .multiply(ONE.add(BigDecimal.valueOf(percentageChange).divide(HUNDRED, DEFAULT_CONTEXT))); + } + + return ZERO; + } + + /** + * Customs value from baseline * (1 + percent increase in customs rate/100) + * + * @param tobaccoProduct + * @return + */ + protected BigDecimal calculateCustomsDutyImportedCigarettes(String tobaccoProduct) { + if (tobaccoProduct.equals("Imported")) { + return calculateBaselineCustomsDuty(tobaccoProduct) + .multiply( + ONE.add(BigDecimal.valueOf(changeInTheDeclaredCustomValue).divide(HUNDRED, DEFAULT_CONTEXT)) + ); + } + + return ZERO; + } + + /** + * Calculate the VAT with tax change + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateVat(String tobaccoProduct) { + if (tobaccoProduct.equals("Illicit")) { + return ZERO; + } + + BigDecimal vatRate = dataset.getVatRate(); + + return calculateNetTaxPrice(tobaccoProduct) + .add(calculateAdditionalCharges()) + .add(calculateTobaccoLevy(tobaccoProduct)) + .add(calculateExciseTaxDomesticProduction(tobaccoProduct)) + .add(calculateExciseTaxImportedCigarettes(tobaccoProduct)) + .add(calculateCustomsDutyImportedCigarettes(tobaccoProduct)) + .multiply(vatRate) + .divide(HUNDRED, DEFAULT_CONTEXT); + } + + /** + * Calculate the Retail Price with tax change + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateRetailPrice(String tobaccoProduct) { + return calculateNetTaxPrice(tobaccoProduct) + .add(calculateAdditionalCharges()) + .add(calculateTobaccoLevy(tobaccoProduct)) + .add(calculateExciseTaxDomesticProduction(tobaccoProduct)) + .add(calculateExciseTaxImportedCigarettes(tobaccoProduct)) + .add(calculateCustomsDutyImportedCigarettes(tobaccoProduct)) + .add(calculateVat(tobaccoProduct)); + } + + /** + * Calculate the Excise Burden with tax change + * excise tax/price * 100 + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateExciseBurden(String tobaccoProduct) { + return calculateTobaccoLevy(tobaccoProduct) + .add(calculateExciseTaxDomesticProduction(tobaccoProduct)) + .add(calculateExciseTaxImportedCigarettes(tobaccoProduct)) + .divide(calculateRetailPrice(tobaccoProduct), DEFAULT_CONTEXT) + .multiply(HUNDRED); + } + + /** + * Calculate the Total Tax Burden with tax change + * all tax/price * 100 + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateTotalTaxBurden(String tobaccoProduct) { + return calculateTobaccoLevy(tobaccoProduct) + .add(calculateExciseTaxDomesticProduction(tobaccoProduct)) + .add(calculateExciseTaxImportedCigarettes(tobaccoProduct)) + .add(calculateVat(tobaccoProduct)) + .divide(calculateRetailPrice(tobaccoProduct), DEFAULT_CONTEXT) + .multiply(HUNDRED); + } + + public BigDecimal calculateBaselineTobaccoLevy(String tobaccoProduct) { + BigDecimal cif = getTobaccoProductValueFromVariable(dataset.getCif(), tobaccoProduct); + BigDecimal levy = getTobaccoProductValueFromVariable(dataset.getTobaccoLevy(), tobaccoProduct); + + return cif.multiply(levy) + .divide(HUNDRED); + } + + /** + * calculate CIF * levy / 100 + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateBaselineExciseTaxOnDomesticProduction(String tobaccoProduct) { + if (tobaccoProduct.equals("Imported")) { + return ZERO; + } + + return getTobaccoProductValueFromVariable(dataset.getExciseTax(), tobaccoProduct); + } + + /** + * If tobacco product is imported, return excise tax + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateBaselineExciseTaxOnImported(String tobaccoProduct) { + if (tobaccoProduct.equals("Imported")) { + return getTobaccoProductValueFromVariable(dataset.getExciseTax(), tobaccoProduct); + } + + return ZERO; + } + + /** + * If tobacco product is imported, calculate CIF * customs duty / 100 + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateBaselineCustomsDuty(String tobaccoProduct) { + if (tobaccoProduct.equals("Imported")) { + BigDecimal cif = getTobaccoProductValueFromVariable(dataset.getCif(), tobaccoProduct); + BigDecimal duty = getTobaccoProductValueFromVariable(dataset.getCustomsDuty(), tobaccoProduct); + + return cif.multiply(duty) + .divide(HUNDRED); + } + + return ZERO; + } + + /** + * Calculate the Baseline Rate Price + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateBaselineRetailPrice(String tobaccoProduct) { + return getTobaccoProductValueFromVariable(dataset.getRetailPrice(), tobaccoProduct); + } + + /** + * Calculate baseeline VAT: Baseline Retail Price * VAT rate / (100 + VAT rate) + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateBaselineVAT(String tobaccoProduct) { + BigDecimal baselineRetailPrice = calculateBaselineRetailPrice(tobaccoProduct); + BigDecimal vatRate = dataset.getVatRate(); + + return baselineRetailPrice.multiply(vatRate) + .divide(HUNDRED.add(vatRate), DEFAULT_CONTEXT); + } + + /** + * Calculates the industry component of the price (the price minus all taxes). + * The first term backward calculates VAT, as price*(1+(VATrate/100)). + * It then minuses excise tax and customs and the levy + * + * Note: illicit segment differs, it is just the retail price + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateBaselineNetTaxPrice(String tobaccoProduct) { + BigDecimal baselineRetailPrice = calculateBaselineRetailPrice(tobaccoProduct); + + if (tobaccoProduct.equals("Illicit")) { + return baselineRetailPrice; + } + + return baselineRetailPrice + .divide(ONE.add(dataset.getVatRate().divide(HUNDRED)), DEFAULT_CONTEXT) + .subtract(calculateBaselineTobaccoLevy(tobaccoProduct)) + .subtract(calculateBaselineExciseTaxOnDomesticProduction(tobaccoProduct)) + .subtract(calculateBaselineExciseTaxOnImported(tobaccoProduct)) + .subtract(calculateBaselineCustomsDuty(tobaccoProduct)); + } + + /** + * Calculates excise burden: (excise) / retail price * 100 + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateBaselineExciseBurden(String tobaccoProduct) { + BigDecimal baselineTobaccoLevy = calculateBaselineTobaccoLevy(tobaccoProduct); + + return baselineTobaccoLevy + .add(calculateBaselineExciseTaxOnDomesticProduction(tobaccoProduct)) + .add(calculateBaselineExciseTaxOnImported(tobaccoProduct)) + .divide(calculateBaselineRetailPrice(tobaccoProduct), DEFAULT_CONTEXT) + .multiply(HUNDRED); + } + + /** + * Calculates total tax burden: (excise + VAT + customs) / retail price * 100 + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateBaselineTotalTaxBurden(String tobaccoProduct) { + BigDecimal baselineTobaccoLevy = calculateBaselineTobaccoLevy(tobaccoProduct); + + return baselineTobaccoLevy + .add(calculateBaselineExciseTaxOnDomesticProduction(tobaccoProduct)) + .add(calculateBaselineExciseTaxOnImported(tobaccoProduct)) + .add(calculateBaselineCustomsDuty(tobaccoProduct)) + .add(calculateBaselineVAT(tobaccoProduct)) + .divide(calculateBaselineRetailPrice(tobaccoProduct), DEFAULT_CONTEXT) + .multiply(HUNDRED); + } + + /** + * Calculate Baseline Consumption (million packs): total market * share of market for each segment / 100 + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateBaselineConsumption(String tobaccoProduct) { + BigDecimal consumption = dataset.getCigaretteConsumption(); + BigDecimal marketShare = getTobaccoProductValueFromVariable(dataset.getMarketShare(), tobaccoProduct); + + return consumption + .multiply(marketShare) + .divide(HUNDRED, DEFAULT_CONTEXT); + } + + /** + * Calculate the Baseline Total Consumption (million packs): summ of all products except illicit + * @return + */ + public BigDecimal calculateBaselineTotalLegalConsumption() { + return dataset.getRetailPrice().getValues().stream() + .filter(pv -> !pv.getProduct().isIllicit()) + .map(pv -> calculateBaselineConsumption(pv.getProduct().getLabel())) + .reduce(BigDecimal.ZERO, BigDecimal::add); + } + + + /** + * Calculate Consumption (million packs): + * Baseline Consumption *([1+price_elast*(price AT-price BT)/(price AT + price BT)] / + * [1-price_elast*(price AT-price BT)/(price AT + price BT)] + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculatePreConsumption(String tobaccoProduct) { + BigDecimal baselineConsumption = calculateBaselineConsumption(tobaccoProduct); + BigDecimal priceElasticity = getTobaccoProductValueFromVariable(dataset.getElasticityOfDemandPrice(), + tobaccoProduct); + + BigDecimal baselineRetailPrice = calculateBaselineRetailPrice(tobaccoProduct); + BigDecimal retailPrice = calculateRetailPrice(tobaccoProduct); + + BigDecimal diffRetailPrice = retailPrice.subtract(baselineRetailPrice); + BigDecimal sumRetailPrice = retailPrice.add(baselineRetailPrice); + BigDecimal multiplyElasticityRetail = priceElasticity.multiply(diffRetailPrice) + .divide(sumRetailPrice, DEFAULT_CONTEXT); + + return baselineConsumption + .multiply(ONE.add(multiplyElasticityRetail)) + .divide(ONE.subtract(multiplyElasticityRetail), DEFAULT_CONTEXT); + } + + /** + * Calculate Gain from higher price category + * As prices change, some consumers decide to shift to cheaper products in order to maintain consumption. + * This calculates these shifts between segments. We assume imported is quite a unique category, + * so there is no shifting in/out of it. The others interact. + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateGainFromPrice(String tobaccoProduct) { + if (GAIN_SWITCH_TOBACCO_PRODUCT.containsKey(tobaccoProduct)) { + String switchProduct = GAIN_SWITCH_TOBACCO_PRODUCT.get(tobaccoProduct); + + BigDecimal consumption = calculatePreConsumption(tobaccoProduct); + BigDecimal crossElasticity = getTobaccoProductValueFromVariable(dataset.getElasticityOfDemandCrossPrice(), + tobaccoProduct); + + BigDecimal baselineRetailPrice = calculateBaselineRetailPrice(switchProduct); + BigDecimal retailPrice = calculateRetailPrice(switchProduct); + + BigDecimal diffRetailPrice = retailPrice.subtract(baselineRetailPrice); + BigDecimal sumRetailPrice = retailPrice.add(baselineRetailPrice); + BigDecimal multiplyElastRetail = crossElasticity.multiply(diffRetailPrice).divide(sumRetailPrice, + DEFAULT_CONTEXT); + + return consumption + .multiply(ONE.add(multiplyElastRetail)) + .divide(ONE.subtract(multiplyElastRetail), DEFAULT_CONTEXT) + .subtract(consumption); + } + + return ZERO; + } + + /** + * Calculate the consumption + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateConsumption(String tobaccoProduct) { + BigDecimal consumption = calculatePreConsumption(tobaccoProduct); + BigDecimal gainFromPrice = calculateGainFromPrice(tobaccoProduct); + + if (CONSUMPTION_DEPENDENT_TOBACCO_PRODUCT.containsKey(tobaccoProduct)) { + BigDecimal gainFromPriceDependent = calculateGainFromPrice( + CONSUMPTION_DEPENDENT_TOBACCO_PRODUCT.get(tobaccoProduct)); + return consumption.add(gainFromPrice).subtract(gainFromPriceDependent); + } + + return consumption.add(gainFromPrice); + } + + /** + * Calculate the Total Legal Consumption (million packs): sum of all products except illicit + * @return + */ + public BigDecimal calculateTotalLegalConsumption() { + return dataset.getRetailPrice().getValues().stream() + .filter(pv -> !pv.getProduct().isIllicit()) + .map(pv -> calculateConsumption(pv.getProduct().getLabel())) + .reduce(BigDecimal.ZERO, BigDecimal::add); + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculator.java b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculator.java new file mode 100644 index 00000000..915d33de --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculator.java @@ -0,0 +1,9 @@ +package org.devgateway.toolkit.forms.util.tetsim; + +import org.devgateway.toolkit.persistence.dto.TetsimOutput; + +public interface TetsimOutputCalculator { + + TetsimOutput calculate(); + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculator.java b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculator.java new file mode 100644 index 00000000..e1f8376e --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculator.java @@ -0,0 +1,27 @@ +package org.devgateway.toolkit.forms.util.tetsim; + +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; + +import java.math.BigDecimal; + +import static org.devgateway.toolkit.forms.util.tetsim.TetsimUtil.getTobaccoProductValueFromVariable; + +/** + * @author vchihai + */ +public class TetsimOutputOvershiftCalculator extends TetsimOutputBaseCalculator { + + public TetsimOutputOvershiftCalculator(TetsimDataset dataset, Double percentageChange) { + super(dataset, percentageChange); + } + + @Override + protected BigDecimal calculateAbsChangeShift(final String tobaccoProduct) { + BigDecimal exciseTax = getTobaccoProductValueFromVariable(dataset.getExciseTax(), tobaccoProduct); + BigDecimal overshifting = getTobaccoProductValueFromVariable(dataset.getOvershifting(), tobaccoProduct); + + return exciseTax.multiply(BigDecimal.valueOf(percentageChange)) + .divide(HUNDRED) + .multiply(overshifting); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculator.java b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculator.java new file mode 100644 index 00000000..9380da3c --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculator.java @@ -0,0 +1,33 @@ +package org.devgateway.toolkit.forms.util.tetsim; + +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dto.TetsimOutput; + +import java.math.BigDecimal; + +import static org.devgateway.toolkit.forms.util.tetsim.TetsimUtil.getTobaccoProductValueFromVariable; + +/** + * @author vchihai + */ +public class TetsimOutputUndershiftCalculator extends TetsimOutputBaseCalculator { + + public TetsimOutputUndershiftCalculator(TetsimDataset dataset, Double percentageChange) { + super(dataset, percentageChange); + } + + @Override + public TetsimOutput calculate() { + return null; + } + + @Override + protected BigDecimal calculateAbsChangeShift(final String tobaccoProduct) { + BigDecimal exciseTax = getTobaccoProductValueFromVariable(dataset.getExciseTax(), tobaccoProduct); + BigDecimal undershifting = getTobaccoProductValueFromVariable(dataset.getUndershifting(), tobaccoProduct); + + return exciseTax.multiply(BigDecimal.valueOf(percentageChange)) + .divide(HUNDRED) + .multiply(undershifting); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimUtil.java b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimUtil.java new file mode 100644 index 00000000..727cde1d --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimUtil.java @@ -0,0 +1,19 @@ +package org.devgateway.toolkit.forms.util.tetsim; + +import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; + +import java.math.BigDecimal; + +public final class TetsimUtil { + + private TetsimUtil() { + + } + + public static BigDecimal getTobaccoProductValueFromVariable(TetsimPriceVariable variable, + String tobaccoProductLabel) { + return variable.getValues().stream() + .filter(t -> t.getProduct().getLabel().equalsIgnoreCase(tobaccoProductLabel)) + .findFirst().get().getValue(); + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java index fcd1ef43..f4d10a84 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java @@ -78,12 +78,12 @@ public class TetsimDataset extends Dataset { @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - private TetsimPriceVariable overShifting = new TetsimPriceVariable(this); + private TetsimPriceVariable overshifting = new TetsimPriceVariable(this); @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Audited @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - private TetsimPriceVariable underShifting = new TetsimPriceVariable(this); + private TetsimPriceVariable undershifting = new TetsimPriceVariable(this); public BigDecimal getCigaretteConsumption() { return cigaretteConsumption; @@ -197,19 +197,19 @@ public void setChangeInIllicitNot(final TetsimPriceVariable changeInIllicitNot) this.changeInIllicitNot = changeInIllicitNot; } - public TetsimPriceVariable getOverShifting() { - return overShifting; + public TetsimPriceVariable getOvershifting() { + return overshifting; } - public void setOverShifting(final TetsimPriceVariable overShifting) { - this.overShifting = overShifting; + public void setOvershifting(final TetsimPriceVariable overshifting) { + this.overshifting = overshifting; } - public TetsimPriceVariable getUnderShifting() { - return underShifting; + public TetsimPriceVariable getUndershifting() { + return undershifting; } - public void setUnderShifting(final TetsimPriceVariable underShifting) { - this.underShifting = underShifting; + public void setUndershifting(final TetsimPriceVariable undershifting) { + this.undershifting = this.undershifting; } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java new file mode 100644 index 00000000..ccb6d8c2 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java @@ -0,0 +1,132 @@ +package org.devgateway.toolkit.persistence.dto; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * + * + * @author vchihai + */ +public class TetsimOutput implements Serializable { + + private Integer baseline; + + private BigDecimal consumptionLegal; + + private BigDecimal consumptionIllicit; + + private BigDecimal exciseRev; + + private BigDecimal totalGovRev; + + private BigDecimal exciseBurden; + + private BigDecimal totalTaxBurden; + + private BigDecimal retailPrice; + + private BigDecimal not; + + private BigDecimal exciseTax; + + private BigDecimal vat; + + private BigDecimal levy; + + public Integer getBaseline() { + return baseline; + } + + public void setBaseline(final Integer baseline) { + this.baseline = baseline; + } + + public BigDecimal getConsumptionLegal() { + return consumptionLegal; + } + + public void setConsumptionLegal(final BigDecimal consumptionLegal) { + this.consumptionLegal = consumptionLegal; + } + + public BigDecimal getConsumptionIllicit() { + return consumptionIllicit; + } + + public void setConsumptionIllicit(final BigDecimal consumptionIllicit) { + this.consumptionIllicit = consumptionIllicit; + } + + public BigDecimal getExciseRev() { + return exciseRev; + } + + public void setExciseRev(final BigDecimal exciseRev) { + this.exciseRev = exciseRev; + } + + public BigDecimal getTotalGovRev() { + return totalGovRev; + } + + public void setTotalGovRev(final BigDecimal totalGovRev) { + this.totalGovRev = totalGovRev; + } + + public BigDecimal getExciseBurden() { + return exciseBurden; + } + + public void setExciseBurden(final BigDecimal exciseBurden) { + this.exciseBurden = exciseBurden; + } + + public BigDecimal getTotalTaxBurden() { + return totalTaxBurden; + } + + public void setTotalTaxBurden(final BigDecimal totalTaxBurden) { + this.totalTaxBurden = totalTaxBurden; + } + + public BigDecimal getRetailPrice() { + return retailPrice; + } + + public void setRetailPrice(final BigDecimal retailPrice) { + this.retailPrice = retailPrice; + } + + public BigDecimal getNot() { + return not; + } + + public void setNot(final BigDecimal not) { + this.not = not; + } + + public BigDecimal getExciseTax() { + return exciseTax; + } + + public void setExciseTax(final BigDecimal exciseTax) { + this.exciseTax = exciseTax; + } + + public BigDecimal getVat() { + return vat; + } + + public void setVat(final BigDecimal vat) { + this.vat = vat; + } + + public BigDecimal getLevy() { + return levy; + } + + public void setLevy(final BigDecimal levy) { + this.levy = levy; + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutputs.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutputs.java new file mode 100644 index 00000000..7babc4b6 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutputs.java @@ -0,0 +1,33 @@ +package org.devgateway.toolkit.persistence.dto; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * + * + * @author vchihai + */ +public class TetsimOutputs implements Serializable { + + private List overshift = new ArrayList<>(); + + private List undershift = new ArrayList<>(); + + public List getOvershift() { + return overshift; + } + + public void setOvershift(final List overshift) { + this.overshift = overshift; + } + + public List getUndershift() { + return undershift; + } + + public void setUndershift(final List undershift) { + this.undershift = undershift; + } +} From f3de8284654086ed48141f47b7c7c9411f54bff6 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 14 Mar 2022 14:18:22 +0200 Subject: [PATCH 059/137] TOBACCO-842: Create tests for TETSIM Output Overshift calculations --- .../TetsimOutputBaseCalculatorTest.java | 95 +++++++++++ ...imOutputCalculatorBaselineNumbersTest.java | 93 ++++++++++ ...utputCalculatorQuantityAndRevenueTest.java | 58 +++++++ ...utputOvershiftCalculatorAbsChangeTest.java | 48 ++++++ ...mOutputOvershiftCalculatorNumbersTest.java | 51 ++++++ .../TetsimOutputOvershiftCalculatorTest.java | 161 ++++++++++++++++++ .../tetsim/builder/TetsimDatasetBuilder.java | 100 +++++++++++ .../builder/TetsimPriceVariableBuilder.java | 23 +++ .../TetsimTobaccoProductValueBuilder.java | 30 ++++ .../tetsim/builder/TobaccoProductBuilder.java | 26 +++ 10 files changed, 685 insertions(+) create mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculatorTest.java create mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java create mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java create mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorAbsChangeTest.java create mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java create mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java create mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimDatasetBuilder.java create mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimPriceVariableBuilder.java create mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimTobaccoProductValueBuilder.java create mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TobaccoProductBuilder.java diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculatorTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculatorTest.java new file mode 100644 index 00000000..fb6fe356 --- /dev/null +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculatorTest.java @@ -0,0 +1,95 @@ +package org.devgateway.toolkit.forms.util.tetsim; + +import org.devgateway.toolkit.forms.util.tetsim.builder.TetsimDatasetBuilder; +import org.devgateway.toolkit.forms.util.tetsim.builder.TetsimPriceVariableBuilder; +import org.devgateway.toolkit.forms.util.tetsim.builder.TetsimTobaccoProductValueBuilder; +import org.devgateway.toolkit.forms.util.tetsim.builder.TobaccoProductBuilder; +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; +import org.junit.Before; + +import java.math.BigDecimal; + +import static java.math.BigDecimal.ZERO; + +public class TetsimOutputBaseCalculatorTest { + + protected TobaccoProduct tobaccoProductImported; + + protected TobaccoProduct tobaccoProductPremium; + + protected TobaccoProduct tobaccoProductPopular; + + protected TobaccoProduct tobaccoProductDiscount; + + protected TobaccoProduct tobaccoProductIllicit; + + protected TetsimDataset datasetWithAllTobaccoProducts; + + @Before + public void setUp() { + this.tobaccoProductImported = createTobaccoProduct("Imported", false); + this.tobaccoProductPremium = createTobaccoProduct("Premium", false); + this.tobaccoProductPopular = createTobaccoProduct("Popular", false); + this.tobaccoProductDiscount = createTobaccoProduct("Discount", false); + this.tobaccoProductIllicit = createTobaccoProduct("Illicit", true); + + this.datasetWithAllTobaccoProducts = createTetsimDatasetWithAllTobaccoProducts(); + } + + protected TobaccoProduct createTobaccoProduct(String label, Boolean illicit) { + return new TobaccoProductBuilder() + .withLabel(label) + .withIllicit(illicit) + .build(); + } + + protected TetsimDataset createTetsimDatasetWithAllTobaccoProducts() { + return new TetsimDatasetBuilder() + .withCigaretteConsumption(BigDecimal.valueOf(1150.0)) + .withVatRate(BigDecimal.valueOf(15)) + .withCigaretteDeclaredCustomValue(BigDecimal.valueOf(2.05)) + .withAdultPopulation(BigDecimal.valueOf(42571)) + .withSmokingPrevalence(BigDecimal.valueOf(16.9)) + .withRetailPrice(createPriceVariable(BigDecimal.valueOf(45), BigDecimal.valueOf(48), BigDecimal.valueOf(40), BigDecimal.valueOf(28), BigDecimal.valueOf(20))) + .withMarketShare(createPriceVariable(BigDecimal.valueOf(5), BigDecimal.valueOf(7.6), BigDecimal.valueOf(40), BigDecimal.valueOf(13), BigDecimal.valueOf(34.4))) + .withCif(createPriceVariable(BigDecimal.valueOf(2.05), BigDecimal.valueOf(2.05), BigDecimal.valueOf(2.05), BigDecimal.valueOf(2.05), BigDecimal.valueOf(2.05))) + .withTobaccoLevy(createPriceVariable(ZERO, ZERO, ZERO, ZERO, ZERO)) + .withExciseTax(createPriceVariable(BigDecimal.valueOf(18.78), BigDecimal.valueOf(18.78), BigDecimal.valueOf(18.78), BigDecimal.valueOf(18.78), ZERO)) + .withCustomDuty(createPriceVariable(BigDecimal.valueOf(45), null, null, null, null)) + .withElasticityPrice(createPriceVariable(BigDecimal.valueOf(-0.4), BigDecimal.valueOf(-0.4), BigDecimal.valueOf(-0.6), BigDecimal.valueOf(-0.8), BigDecimal.valueOf(-0.6))) + .withCrossElasticityPrice(createPriceVariable(ZERO, ZERO, BigDecimal.valueOf(0.2), BigDecimal.valueOf(0.3), BigDecimal.valueOf(0.3))) + .withChangeInIllicitNot(createPriceVariable(null, null,null, null, BigDecimal.valueOf(0.5))) + .withOvershifting(createPriceVariable(BigDecimal.valueOf(0.3), BigDecimal.valueOf(0.3), BigDecimal.valueOf(0.2), BigDecimal.valueOf(0.1), ZERO)) + .withUndershifting(createPriceVariable(BigDecimal.valueOf(-0.2), BigDecimal.valueOf(-0.2), BigDecimal.valueOf(-0.3), BigDecimal.valueOf(-0.5), ZERO)) + .build(); + } + + protected TetsimPriceVariable createPriceVariable(BigDecimal imported, BigDecimal premium, BigDecimal popular, + BigDecimal discount, BigDecimal illicit) { + return new TetsimPriceVariableBuilder() + .add(new TetsimTobaccoProductValueBuilder() + .withTobaccoProduct(tobaccoProductImported) + .withValue(imported) + .build()) + .add(new TetsimTobaccoProductValueBuilder() + .withTobaccoProduct(tobaccoProductPremium) + .withValue(premium) + .build()) + .add(new TetsimTobaccoProductValueBuilder() + .withTobaccoProduct(tobaccoProductPopular) + .withValue(popular) + .build()) + .add(new TetsimTobaccoProductValueBuilder() + .withTobaccoProduct(tobaccoProductDiscount) + .withValue(discount) + .build()) + .add(new TetsimTobaccoProductValueBuilder() + .withTobaccoProduct(tobaccoProductIllicit) + .withValue(illicit) + .build()) + .build(); + } + +} \ No newline at end of file diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java new file mode 100644 index 00000000..ea4a7dbf --- /dev/null +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java @@ -0,0 +1,93 @@ +package org.devgateway.toolkit.forms.util.tetsim; + +import org.junit.Before; +import org.junit.Test; + +import static java.math.BigDecimal.ROUND_HALF_UP; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TetsimOutputCalculatorBaselineNumbersTest extends TetsimOutputBaseCalculatorTest { + + @Before + public void setUp() { + super.setUp(); + } + + @Test + public void testBaselineNetOfTaxPrice() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + assertEquals(19.43, tetsimOutputCalculator.calculateBaselineNetTaxPrice("Imported") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Net of Tax for Imported Product"); + } + + @Test + public void testBaselineNetOfTaxPriceWithPercentageChange() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + assertEquals(16.00, tetsimOutputCalculator.calculateBaselineNetTaxPrice("Popular") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Net of Tax for Popular Product with percentage change"); + } + + @Test + public void testBaselineIllicitNetOfTaxPriceWithPercentageChange() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + assertEquals(20.00, tetsimOutputCalculator.calculateBaselineNetTaxPrice("Illicit") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Net of Tax Price for Illicit Product with percentage change"); + } + + @Test + public void testBaselineIllicitRetailPrice() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + assertEquals(20.00, tetsimOutputCalculator.calculateBaselineRetailPrice("Illicit") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Retail Price for Illicit Product"); + } + + @Test + public void testBaselineRetailPriceWithPercentageChange() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + assertEquals(40.00, tetsimOutputCalculator.calculateBaselineRetailPrice("Popular") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Retail Price for Popular Product with percentage change"); + } + + @Test + public void testBaselineIllicitExciseTaxOnDomestic() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + assertEquals(0.0, tetsimOutputCalculator.calculateBaselineExciseTaxOnDomesticProduction("Illicit") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Excise Tax for Illicit Product"); + } + + @Test + public void testBaselineImportedExciseTaxOnDomestic() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + assertEquals(0.0, tetsimOutputCalculator.calculateBaselineExciseTaxOnDomesticProduction("Imported") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Excise Tax for Imported Product"); + } + + @Test + public void testBaselinePopularExciseTaxOnDomestic() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + assertEquals(18.78, tetsimOutputCalculator.calculateBaselineExciseTaxOnDomesticProduction("Popular") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Excise Tax for Popular Product"); + } + + @Test + public void testBaselinePopularVAT() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + assertEquals(5.22, tetsimOutputCalculator.calculateBaselineVAT("Popular") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline VAT for Popular Product"); + } + + @Test + public void testBaselineDiscountExciseBurden() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + assertEquals(67.07, tetsimOutputCalculator.calculateBaselineExciseBurden("Discount") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Excise Burden for Discount Product"); + } + + @Test + public void testBaselinePremiumTotalTaxBurden() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + assertEquals(52.17, tetsimOutputCalculator.calculateBaselineTotalTaxBurden("Premium") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Total Tax Burden for Premium Product"); + } + +} \ No newline at end of file diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java new file mode 100644 index 00000000..f62d8452 --- /dev/null +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java @@ -0,0 +1,58 @@ +package org.devgateway.toolkit.forms.util.tetsim; + +import org.junit.Before; +import org.junit.Test; + +import static java.math.BigDecimal.ROUND_HALF_UP; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TetsimOutputCalculatorQuantityAndRevenueTest extends TetsimOutputBaseCalculatorTest { + + @Before + public void setUp() { + super.setUp(); + } + + @Test + public void testBaselineTotalConsumption() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.00); + assertEquals(754.4, tetsimOutputCalculator.calculateBaselineTotalLegalConsumption() + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check baseline Total Consumption"); + } + + @Test + public void testPreConsumption() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.00); + assertEquals(54.9, tetsimOutputCalculator.calculatePreConsumption("Imported") + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Pre Consumption for Imported Tobacco Product"); + } + + @Test + public void testPreConsumptionIllicit() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.00); + assertEquals(369.9, tetsimOutputCalculator.calculatePreConsumption("Illicit") + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Pre Consumption for Illicit Tobacco Product"); + } + + @Test + public void testGainFromPrice() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.00); + assertEquals(17.8, tetsimOutputCalculator.calculateGainFromPrice("Illicit") + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Gain From Price for Illicit Tobacco Product"); + } + + @Test + public void testConsumptionPopular() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.00); + assertEquals(432.2, tetsimOutputCalculator.calculateConsumption("Popular") + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption for Popular Tobacco Product"); + } + + @Test + public void testConsumptionIllicit() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.00); + assertEquals(387.6, tetsimOutputCalculator.calculateConsumption("Illicit") + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption for Illicit Tobacco Product"); + } + +} \ No newline at end of file diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorAbsChangeTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorAbsChangeTest.java new file mode 100644 index 00000000..2e47882d --- /dev/null +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorAbsChangeTest.java @@ -0,0 +1,48 @@ +package org.devgateway.toolkit.forms.util.tetsim; + +import org.devgateway.toolkit.persistence.dto.TetsimOutput; +import org.junit.Before; +import org.junit.Test; + +import static java.math.BigDecimal.ROUND_HALF_UP; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TetsimOutputOvershiftCalculatorAbsChangeTest extends TetsimOutputBaseCalculatorTest { + + @Before + public void setUp() { + super.setUp(); + } + + @Test + public void testAbsChangeImportedBaseline() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Imported") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Abs change overshift imported baseline"); + } + + @Test + public void testAbsChangePopular() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(0.75, tetsimOutputCalculator.calculateAbsChangeShift("Popular") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Abs change overshift popular"); + } + + @Test + public void testAbsChangeDiscount() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(0.38, tetsimOutputCalculator.calculateAbsChangeShift("Discount") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Abs change overshift discount"); + } + + @Test + public void testAbsChangeIllicit() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Illicit") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Abs change overshift illicit"); + } + +} \ No newline at end of file diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java new file mode 100644 index 00000000..d491c68b --- /dev/null +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java @@ -0,0 +1,51 @@ +package org.devgateway.toolkit.forms.util.tetsim; + +import org.junit.Before; +import org.junit.Test; + +import static java.math.BigDecimal.ROUND_HALF_UP; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TetsimOutputOvershiftCalculatorNumbersTest extends TetsimOutputBaseCalculatorTest { + + @Before + public void setUp() { + super.setUp(); + } + + @Test + public void testPopularNetTaxPrice() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + assertEquals(16.75, tetsimOutputCalculator.calculateNetTaxPrice("Popular") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift Net of Tax for Popular Product"); + } + + @Test + public void testIllicitNetTaxPrice() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + assertEquals(22.38, tetsimOutputCalculator.calculateNetTaxPrice("Illicit") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift Net of Tax for Illicit Product"); + } + + @Test + public void testPopularExciseTaxOnDomesticProduction() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + assertEquals(22.54, tetsimOutputCalculator.calculateExciseTaxDomesticProduction("Popular") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift Excise Tax on domestic production for Popular Product"); + } + + @Test + public void testPremiumVat() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + assertEquals(6.99, tetsimOutputCalculator.calculateVat("Premium") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift VAT for Premium Product"); + } + + @Test + public void testImportedRetailPrice() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + assertEquals(50.62, tetsimOutputCalculator.calculateRetailPrice("Imported") + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift Retail Price for Imported Product"); + } + +} \ No newline at end of file diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java new file mode 100644 index 00000000..bbd3e688 --- /dev/null +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java @@ -0,0 +1,161 @@ +package org.devgateway.toolkit.forms.util.tetsim; + +import org.devgateway.toolkit.persistence.dto.TetsimOutput; +import org.junit.Before; +import org.junit.Test; + +import static java.math.BigDecimal.ROUND_HALF_UP; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TetsimOutputOvershiftCalculatorTest extends TetsimOutputBaseCalculatorTest { + + @Before + public void setUp() { + super.setUp(); + } + + @Test + public void testConsumptionLegalNoTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(754.4, output.getConsumptionLegal() + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption Legal TETSIM Output Overshift"); + } + + @Test + public void testConsumptionLegalWithTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(680.2, output.getConsumptionLegal() + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption Legal TETSIM Output Overshift"); + } + + @Test + public void testConsumptionIllicitlNoTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(395.6, output.getConsumptionIllicit() + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption Illicit TETSIM Output Overshift"); + } + + @Test + public void testConsumptionIllicitWithTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(387.6, output.getConsumptionIllicit() + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption Illicit TETSIM Output Overshift"); + } + + @Test + public void testExciseBurdenNoTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(47.0, output.getExciseBurden() + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Excise Burden TETSIM Output Overshift"); + } + + @Test + public void testExciseBurdenWithTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(49.9, output.getExciseBurden() + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Excise Burden TETSIM Output Overshift (Tax Change)"); + } + + @Test + public void testTotalTaxBurdenNoTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(60.0, output.getTotalTaxBurden() + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Total Tax Burden TETSIM Output Overshift"); + } + + @Test + public void testTotalTaxBurdenWithTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(62.9, output.getTotalTaxBurden() + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Total Tax Burden TETSIM Output Overshift (Tax Change)"); + } + + @Test + public void testRetailPriceNoTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(40.0, output.getRetailPrice() + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Retail Price TETSIM Output Overshift (Baseline)"); + } + + @Test + public void testRetailPriceWithTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(45.18, output.getRetailPrice() + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Retail Price TETSIM Output Overshift (Tax Change)"); + } + + @Test + public void testNOTNoTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(16.0, output.getNot() + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check NOT TETSIM Output Overshift"); + } + + @Test + public void testNOTWithTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(16.75, output.getNot() + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check NOT TETSIM Output Overshift (Tax Change)"); + } + + @Test + public void testExciseTaxNoTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(18.78, output.getExciseTax() + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Excise Tax TETSIM Output Overshift"); + } + + @Test + public void testExciseTaxWithTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(22.54, output.getExciseTax() + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Excise Tax TETSIM Output Overshift (Tax Change)"); + } + + @Test + public void testVatNoTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(5.22, output.getVat() + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check VAT TETSIM Output Overshift"); + } + + @Test + public void testVatWithTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(5.89, output.getVat() + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check VAT TETSIM Output Overshift (Tax Change)"); + } + + @Test + public void testLevyNoTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(0.00, output.getLevy() + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Levy TETSIM Output Overshift"); + } + + @Test + public void testLevyWithTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(0.00, output.getLevy() + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Levy TETSIM Output Overshift (Tax Change)"); + } + +} \ No newline at end of file diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimDatasetBuilder.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimDatasetBuilder.java new file mode 100644 index 00000000..efb28bb8 --- /dev/null +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimDatasetBuilder.java @@ -0,0 +1,100 @@ +package org.devgateway.toolkit.forms.util.tetsim.builder; + +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; + +import java.math.BigDecimal; + +public class TetsimDatasetBuilder { + + private TetsimDataset dataset; + + public TetsimDatasetBuilder() { + dataset = new TetsimDataset(); + } + + public TetsimDatasetBuilder withCigaretteConsumption(BigDecimal consumption) { + dataset.setCigaretteConsumption(consumption); + return this; + } + + public TetsimDatasetBuilder withCigaretteDeclaredCustomValue(BigDecimal declaredCustomValue) { + dataset.setCigaretteDeclaredCustomValue(declaredCustomValue); + return this; + } + + public TetsimDatasetBuilder withAdultPopulation(BigDecimal adultPopulation) { + dataset.setAdultPopulation(adultPopulation); + return this; + } + + public TetsimDatasetBuilder withVatRate(BigDecimal vatRate) { + dataset.setVatRate(vatRate); + return this; + } + + public TetsimDatasetBuilder withSmokingPrevalence(BigDecimal smokingPrevalence) { + dataset.setSmokingPrevalence(smokingPrevalence); + return this; + } + + public TetsimDatasetBuilder withRetailPrice(TetsimPriceVariable retailPrice) { + dataset.setRetailPrice(retailPrice); + return this; + } + + public TetsimDatasetBuilder withMarketShare(TetsimPriceVariable marketShare) { + dataset.setMarketShare(marketShare); + return this; + } + + public TetsimDatasetBuilder withCif(TetsimPriceVariable cif) { + dataset.setCif(cif); + return this; + } + + public TetsimDatasetBuilder withTobaccoLevy(TetsimPriceVariable tobaccoLevy) { + dataset.setTobaccoLevy(tobaccoLevy); + return this; + } + + public TetsimDatasetBuilder withExciseTax(TetsimPriceVariable exciseTax) { + dataset.setExciseTax(exciseTax); + return this; + } + + public TetsimDatasetBuilder withCustomDuty(TetsimPriceVariable customDuty) { + dataset.setCustomsDuty(customDuty); + return this; + } + + public TetsimDatasetBuilder withElasticityPrice(TetsimPriceVariable elasticityPrice) { + dataset.setElasticityOfDemandPrice(elasticityPrice); + return this; + } + + public TetsimDatasetBuilder withCrossElasticityPrice(TetsimPriceVariable crossElasticityPrice) { + dataset.setElasticityOfDemandCrossPrice(crossElasticityPrice); + return this; + } + + public TetsimDatasetBuilder withChangeInIllicitNot(TetsimPriceVariable changeInIllicitNot) { + dataset.setChangeInIllicitNot(changeInIllicitNot); + return this; + } + + public TetsimDatasetBuilder withOvershifting(TetsimPriceVariable overshifting) { + dataset.setOvershifting(overshifting); + return this; + } + + public TetsimDatasetBuilder withUndershifting(TetsimPriceVariable undershifting) { + dataset.setUndershifting(undershifting); + return this; + } + + public TetsimDataset build() { + return dataset; + } + +} diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimPriceVariableBuilder.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimPriceVariableBuilder.java new file mode 100644 index 00000000..f9c18775 --- /dev/null +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimPriceVariableBuilder.java @@ -0,0 +1,23 @@ +package org.devgateway.toolkit.forms.util.tetsim.builder; + +import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; +import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; + +public class TetsimPriceVariableBuilder { + + private TetsimPriceVariable priceVariable; + + public TetsimPriceVariableBuilder() { + this.priceVariable = new TetsimPriceVariable(); + } + + public TetsimPriceVariableBuilder add(TetsimTobaccoProductValue tetsimTobaccoProductValue) { + priceVariable.getValues().add(tetsimTobaccoProductValue); + return this; + } + + public TetsimPriceVariable build() { + return priceVariable; + } + +} diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimTobaccoProductValueBuilder.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimTobaccoProductValueBuilder.java new file mode 100644 index 00000000..e41297c9 --- /dev/null +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimTobaccoProductValueBuilder.java @@ -0,0 +1,30 @@ +package org.devgateway.toolkit.forms.util.tetsim.builder; + +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; +import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; + +import java.math.BigDecimal; + +public class TetsimTobaccoProductValueBuilder { + + private TetsimTobaccoProductValue productValue; + + public TetsimTobaccoProductValueBuilder() { + this.productValue = new TetsimTobaccoProductValue(); + } + + public TetsimTobaccoProductValueBuilder withTobaccoProduct(TobaccoProduct tobaccoProduct) { + productValue.setProduct(tobaccoProduct); + return this; + } + + public TetsimTobaccoProductValueBuilder withValue(BigDecimal value) { + productValue.setValue(value); + return this; + } + + public TetsimTobaccoProductValue build() { + return productValue; + } + +} diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TobaccoProductBuilder.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TobaccoProductBuilder.java new file mode 100644 index 00000000..51169f03 --- /dev/null +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TobaccoProductBuilder.java @@ -0,0 +1,26 @@ +package org.devgateway.toolkit.forms.util.tetsim.builder; + +import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; + +public class TobaccoProductBuilder { + + private TobaccoProduct product; + + public TobaccoProductBuilder() { + this.product = new TobaccoProduct(); + } + + public TobaccoProductBuilder withLabel(String label) { + this.product.setLabel(label); + return this; + } + + public TobaccoProductBuilder withIllicit(Boolean illicit) { + this.product.setIllicit(illicit); + return this; + } + + public TobaccoProduct build() { + return this.product; + } +} From e4fc1dc7ec34dade3af70b2e39b3605a14f44639 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 14 Mar 2022 15:52:19 +0200 Subject: [PATCH 060/137] TOBACCO-840: Calculate Excise Revenue and Total Gov revenue for tetsim output --- .../tetsim/TetsimOutputBaseCalculator.java | 282 ++++++++++++------ .../TetsimOutputOvershiftCalculatorTest.java | 38 ++- 2 files changed, 225 insertions(+), 95 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java index 10e36dab..aa0fc974 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java @@ -6,7 +6,9 @@ import java.math.BigDecimal; import java.math.MathContext; +import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; @@ -86,11 +88,11 @@ private BigDecimal calculateOutputConsumptionIllicit() { } private BigDecimal calculateOutputExciseRev() { - return ZERO; + return calculateTotalExciseRevenue(); } private BigDecimal calculateOutputTotalGovRev() { - return ZERO; + return calculateTotalLegalGovernmentRevenue(); } /** @@ -292,6 +294,187 @@ public BigDecimal calculateTotalTaxBurden(String tobaccoProduct) { .multiply(HUNDRED); } + /** + * Calculate Consumption (million packs): + * Baseline Consumption *([1+price_elast*(price AT-price BT)/(price AT + price BT)] / + * [1-price_elast*(price AT-price BT)/(price AT + price BT)] + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculatePreConsumption(String tobaccoProduct) { + BigDecimal baselineConsumption = calculateBaselineConsumption(tobaccoProduct); + BigDecimal priceElasticity = getTobaccoProductValueFromVariable(dataset.getElasticityOfDemandPrice(), + tobaccoProduct); + + BigDecimal baselineRetailPrice = calculateBaselineRetailPrice(tobaccoProduct); + BigDecimal retailPrice = calculateRetailPrice(tobaccoProduct); + + BigDecimal diffRetailPrice = retailPrice.subtract(baselineRetailPrice); + BigDecimal sumRetailPrice = retailPrice.add(baselineRetailPrice); + BigDecimal multiplyElasticityRetail = priceElasticity.multiply(diffRetailPrice) + .divide(sumRetailPrice, DEFAULT_CONTEXT); + + return baselineConsumption + .multiply(ONE.add(multiplyElasticityRetail)) + .divide(ONE.subtract(multiplyElasticityRetail), DEFAULT_CONTEXT); + } + + /** + * Calculate Gain from higher price category + * As prices change, some consumers decide to shift to cheaper products in order to maintain consumption. + * This calculates these shifts between segments. We assume imported is quite a unique category, + * so there is no shifting in/out of it. The others interact. + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateGainFromPrice(String tobaccoProduct) { + if (GAIN_SWITCH_TOBACCO_PRODUCT.containsKey(tobaccoProduct)) { + String switchProduct = GAIN_SWITCH_TOBACCO_PRODUCT.get(tobaccoProduct); + + BigDecimal consumption = calculatePreConsumption(tobaccoProduct); + BigDecimal crossElasticity = getTobaccoProductValueFromVariable(dataset.getElasticityOfDemandCrossPrice(), + tobaccoProduct); + + BigDecimal baselineRetailPrice = calculateBaselineRetailPrice(switchProduct); + BigDecimal retailPrice = calculateRetailPrice(switchProduct); + + BigDecimal diffRetailPrice = retailPrice.subtract(baselineRetailPrice); + BigDecimal sumRetailPrice = retailPrice.add(baselineRetailPrice); + BigDecimal multiplyElastRetail = crossElasticity.multiply(diffRetailPrice).divide(sumRetailPrice, + DEFAULT_CONTEXT); + + return consumption + .multiply(ONE.add(multiplyElastRetail)) + .divide(ONE.subtract(multiplyElastRetail), DEFAULT_CONTEXT) + .subtract(consumption); + } + + return ZERO; + } + + /** + * Calculate the consumption + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateConsumption(String tobaccoProduct) { + BigDecimal consumption = calculatePreConsumption(tobaccoProduct); + BigDecimal gainFromPrice = calculateGainFromPrice(tobaccoProduct); + + if (CONSUMPTION_DEPENDENT_TOBACCO_PRODUCT.containsKey(tobaccoProduct)) { + BigDecimal gainFromPriceDependent = calculateGainFromPrice( + CONSUMPTION_DEPENDENT_TOBACCO_PRODUCT.get(tobaccoProduct)); + return consumption.add(gainFromPrice).subtract(gainFromPriceDependent); + } + + return consumption.add(gainFromPrice); + } + + /** + * Calculate the Total Legal Consumption (million packs): sum of all products except illicit + * @return + */ + public BigDecimal calculateTotalLegalConsumption() { + return getTetsimLegalTobaccoProducts().stream() + .map(tobaccoProduct -> calculateConsumption(tobaccoProduct)) + .reduce(BigDecimal.ZERO, BigDecimal::add); + } + + /** + * Calculate Revenue Tobacco levy: Levy per pack AT * consumption in mill packs + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateRevenueTobaccoLevy(String tobaccoProduct) { + return calculateConsumption(tobaccoProduct).multiply(calculateTobaccoLevy(tobaccoProduct)); + } + + + /** + * Calculate Revenue Excise tax on domestic production: excise tax per pack AT * consumption in mill packs + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateRevenueExciseTaxDomesticProduction(String tobaccoProduct) { + return calculateConsumption(tobaccoProduct).multiply(calculateExciseTaxDomesticProduction(tobaccoProduct)); + } + + /** + * Calculate Revenue Excise tax on imported production: excise tax (imported) per pack AT * consumption + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateRevenueExciseTaxImportedCigarettes(String tobaccoProduct) { + return calculateConsumption(tobaccoProduct).multiply(calculateExciseTaxImportedCigarettes(tobaccoProduct)); + } + + /** + * Calculate Revenue Customs Duty on Imported Cigarettes: customs per pack * consumption + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateRevenueCustomsDutyImportedCigarettes(String tobaccoProduct) { + return calculateConsumption(tobaccoProduct).multiply(calculateCustomsDutyImportedCigarettes(tobaccoProduct)); + } + + /** + * Calculate Revenue VAT: VAT per pack * consumption + * + * @param tobaccoProduct + * @return + */ + public BigDecimal calculateRevenueVat(String tobaccoProduct) { + return calculateConsumption(tobaccoProduct).multiply(calculateVat(tobaccoProduct)); + } + + /** + * Calculate Total Excise TaxesRevenue + * + * @param tobaccoProduct + */ + public BigDecimal calculateTotalExciseTaxesRevenue(String tobaccoProduct) { + return calculateRevenueExciseTaxDomesticProduction(tobaccoProduct) + .add(calculateRevenueExciseTaxImportedCigarettes(tobaccoProduct)); + } + + /** + * Calculate Total Excise Revenue: sum of excise tax + */ + public BigDecimal calculateTotalExciseRevenue() { + return getTetsimLegalTobaccoProducts().stream() + .map(tobaccoProduct -> calculateTotalExciseTaxesRevenue(tobaccoProduct)) + .reduce(BigDecimal.ZERO, BigDecimal::add); + } + + /** + * Calculate Total Revenue + * + * @param tobaccoProduct + */ + public BigDecimal calculateTotalRevenue(String tobaccoProduct) { + return calculateRevenueTobaccoLevy(tobaccoProduct) + .add(calculateRevenueExciseTaxDomesticProduction(tobaccoProduct)) + .add(calculateRevenueExciseTaxImportedCigarettes(tobaccoProduct)) + .add(calculateRevenueCustomsDutyImportedCigarettes(tobaccoProduct)) + .add(calculateRevenueVat(tobaccoProduct)); + } + + /** + * Calculate Total Government Revenue: excise tax + VAT + levy + customs + */ + public BigDecimal calculateTotalLegalGovernmentRevenue() { + return getTetsimLegalTobaccoProducts().stream() + .map(tobaccoProduct -> calculateTotalRevenue(tobaccoProduct)) + .reduce(BigDecimal.ZERO, BigDecimal::add); + } + + public BigDecimal calculateBaselineTobaccoLevy(String tobaccoProduct) { BigDecimal cif = getTobaccoProductValueFromVariable(dataset.getCif(), tobaccoProduct); BigDecimal levy = getTobaccoProductValueFromVariable(dataset.getTobaccoLevy(), tobaccoProduct); @@ -448,101 +631,16 @@ public BigDecimal calculateBaselineConsumption(String tobaccoProduct) { * @return */ public BigDecimal calculateBaselineTotalLegalConsumption() { - return dataset.getRetailPrice().getValues().stream() - .filter(pv -> !pv.getProduct().isIllicit()) - .map(pv -> calculateBaselineConsumption(pv.getProduct().getLabel())) + return getTetsimLegalTobaccoProducts().stream() + .map(tobaccoProduct -> calculateBaselineConsumption(tobaccoProduct)) .reduce(BigDecimal.ZERO, BigDecimal::add); } - - /** - * Calculate Consumption (million packs): - * Baseline Consumption *([1+price_elast*(price AT-price BT)/(price AT + price BT)] / - * [1-price_elast*(price AT-price BT)/(price AT + price BT)] - * - * @param tobaccoProduct - * @return - */ - public BigDecimal calculatePreConsumption(String tobaccoProduct) { - BigDecimal baselineConsumption = calculateBaselineConsumption(tobaccoProduct); - BigDecimal priceElasticity = getTobaccoProductValueFromVariable(dataset.getElasticityOfDemandPrice(), - tobaccoProduct); - - BigDecimal baselineRetailPrice = calculateBaselineRetailPrice(tobaccoProduct); - BigDecimal retailPrice = calculateRetailPrice(tobaccoProduct); - - BigDecimal diffRetailPrice = retailPrice.subtract(baselineRetailPrice); - BigDecimal sumRetailPrice = retailPrice.add(baselineRetailPrice); - BigDecimal multiplyElasticityRetail = priceElasticity.multiply(diffRetailPrice) - .divide(sumRetailPrice, DEFAULT_CONTEXT); - - return baselineConsumption - .multiply(ONE.add(multiplyElasticityRetail)) - .divide(ONE.subtract(multiplyElasticityRetail), DEFAULT_CONTEXT); - } - - /** - * Calculate Gain from higher price category - * As prices change, some consumers decide to shift to cheaper products in order to maintain consumption. - * This calculates these shifts between segments. We assume imported is quite a unique category, - * so there is no shifting in/out of it. The others interact. - * - * @param tobaccoProduct - * @return - */ - public BigDecimal calculateGainFromPrice(String tobaccoProduct) { - if (GAIN_SWITCH_TOBACCO_PRODUCT.containsKey(tobaccoProduct)) { - String switchProduct = GAIN_SWITCH_TOBACCO_PRODUCT.get(tobaccoProduct); - - BigDecimal consumption = calculatePreConsumption(tobaccoProduct); - BigDecimal crossElasticity = getTobaccoProductValueFromVariable(dataset.getElasticityOfDemandCrossPrice(), - tobaccoProduct); - - BigDecimal baselineRetailPrice = calculateBaselineRetailPrice(switchProduct); - BigDecimal retailPrice = calculateRetailPrice(switchProduct); - - BigDecimal diffRetailPrice = retailPrice.subtract(baselineRetailPrice); - BigDecimal sumRetailPrice = retailPrice.add(baselineRetailPrice); - BigDecimal multiplyElastRetail = crossElasticity.multiply(diffRetailPrice).divide(sumRetailPrice, - DEFAULT_CONTEXT); - - return consumption - .multiply(ONE.add(multiplyElastRetail)) - .divide(ONE.subtract(multiplyElastRetail), DEFAULT_CONTEXT) - .subtract(consumption); - } - - return ZERO; - } - - /** - * Calculate the consumption - * - * @param tobaccoProduct - * @return - */ - public BigDecimal calculateConsumption(String tobaccoProduct) { - BigDecimal consumption = calculatePreConsumption(tobaccoProduct); - BigDecimal gainFromPrice = calculateGainFromPrice(tobaccoProduct); - - if (CONSUMPTION_DEPENDENT_TOBACCO_PRODUCT.containsKey(tobaccoProduct)) { - BigDecimal gainFromPriceDependent = calculateGainFromPrice( - CONSUMPTION_DEPENDENT_TOBACCO_PRODUCT.get(tobaccoProduct)); - return consumption.add(gainFromPrice).subtract(gainFromPriceDependent); - } - - return consumption.add(gainFromPrice); - } - - /** - * Calculate the Total Legal Consumption (million packs): sum of all products except illicit - * @return - */ - public BigDecimal calculateTotalLegalConsumption() { + private List getTetsimLegalTobaccoProducts() { return dataset.getRetailPrice().getValues().stream() .filter(pv -> !pv.getProduct().isIllicit()) - .map(pv -> calculateConsumption(pv.getProduct().getLabel())) - .reduce(BigDecimal.ZERO, BigDecimal::add); + .map(pv -> pv.getProduct().getLabel()) + .collect(Collectors.toList()); } } diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java index bbd3e688..4d13c18f 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java @@ -27,11 +27,11 @@ public void testConsumptionLegalWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); TetsimOutput output = tetsimOutputCalculator.calculate(); assertEquals(680.2, output.getConsumptionLegal() - .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption Legal TETSIM Output Overshift"); + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption Legal TETSIM Output Overshift (Tax Change)"); } @Test - public void testConsumptionIllicitlNoTaxChange() { + public void testConsumptionIllicitNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); TetsimOutput output = tetsimOutputCalculator.calculate(); assertEquals(395.6, output.getConsumptionIllicit() @@ -43,7 +43,39 @@ public void testConsumptionIllicitWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); TetsimOutput output = tetsimOutputCalculator.calculate(); assertEquals(387.6, output.getConsumptionIllicit() - .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption Illicit TETSIM Output Overshift"); + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption Illicit TETSIM Output Overshift (Tax Change)"); + } + + @Test + public void testTotalExciseRevenueNoTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(14167.6, output.getExciseRev() + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Total Legal Excise Revenue TETSIM Output Overshift"); + } + + @Test + public void testTotalExciseRevenueWithTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(15328.9, output.getExciseRev() + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Total Legal Excise Revenue TETSIM Output Overshift (Tax Change)"); + } + + @Test + public void testTotalLegalGovRevenueNoTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(18051.4, output.getTotalGovRev() + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Total Legal Government Revenue TETSIM Output Overshift"); + } + + @Test + public void testTotalLegalGovRevenueWithTaxChange() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + assertEquals(19315.5, output.getTotalGovRev() + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Total Legal Government Revenue TETSIM Output Overshift (Tax Change)"); } @Test From 941dceab60f65b0495bf99f9d3cbb00c12ac1524 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Tue, 15 Mar 2022 14:54:40 +0200 Subject: [PATCH 061/137] TOBACCO-840: Update tetsim calculation. Add undershift calculations. --- .../tetsim/TetsimOutputBaseCalculator.java | 51 +++++++------- .../TetsimOutputOvershiftCalculator.java | 2 +- .../TetsimOutputUndershiftCalculator.java | 8 +-- .../persistence/dao/data/TetsimDataset.java | 2 +- .../toolkit/persistence/dto/TetsimOutput.java | 67 +++++++++---------- 5 files changed, 62 insertions(+), 68 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java index aa0fc974..1b3fa8f6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java @@ -26,7 +26,7 @@ public abstract class TetsimOutputBaseCalculator implements TetsimOutputCalculat protected final TetsimDataset dataset; - protected final Double percentageChange; + protected final Integer percentageChange; protected final Double trackTracingAdditionalCost; @@ -47,11 +47,11 @@ public abstract class TetsimOutputBaseCalculator implements TetsimOutputCalculat .put("Discount", "Illicit") .build(); - public TetsimOutputBaseCalculator(TetsimDataset dataset, Double percentageChange) { + public TetsimOutputBaseCalculator(TetsimDataset dataset, Integer percentageChange) { this(dataset, percentageChange, 0.0, 0.0); } - public TetsimOutputBaseCalculator(TetsimDataset dataset, Double percentageChange, + public TetsimOutputBaseCalculator(TetsimDataset dataset, Integer percentageChange, Double trackTracingAdditionalCost, Double levyPercentageChange) { this.dataset = dataset; this.percentageChange = percentageChange; @@ -75,73 +75,74 @@ public TetsimOutput calculate() { tetsimOutput.setExciseTax(calculateOutputExciseTax()); tetsimOutput.setVat(calculateOutputVat()); tetsimOutput.setLevy(calculateOutputLevy()); + tetsimOutput.setBaseline(percentageChange.intValue()); return tetsimOutput; } - public BigDecimal calculateOutputConsumptionLegal() { - return calculateTotalLegalConsumption(); + public Double calculateOutputConsumptionLegal() { + return calculateTotalLegalConsumption().doubleValue(); } - private BigDecimal calculateOutputConsumptionIllicit() { - return calculateConsumption("Illicit"); + private Double calculateOutputConsumptionIllicit() { + return calculateConsumption("Illicit").doubleValue(); } - private BigDecimal calculateOutputExciseRev() { - return calculateTotalExciseRevenue(); + private Double calculateOutputExciseRev() { + return calculateTotalExciseRevenue().doubleValue(); } - private BigDecimal calculateOutputTotalGovRev() { - return calculateTotalLegalGovernmentRevenue(); + private Double calculateOutputTotalGovRev() { + return calculateTotalLegalGovernmentRevenue().doubleValue(); } /** * Calculate the Output Excise Burden */ - private BigDecimal calculateOutputExciseBurden() { - return calculateExciseBurden("Popular"); + private Double calculateOutputExciseBurden() { + return calculateExciseBurden("Popular").doubleValue(); } /** * Calculate the Output Total Tax Burden */ - private BigDecimal calculateOutputTotalTaxBurden() { - return calculateTotalTaxBurden("Popular"); + private Double calculateOutputTotalTaxBurden() { + return calculateTotalTaxBurden("Popular").doubleValue(); } /** * Calculate the Output Retail Price */ - public BigDecimal calculateOutputRetailPrice() { - return calculateRetailPrice("Popular"); + public Double calculateOutputRetailPrice() { + return calculateRetailPrice("Popular").doubleValue(); } /** * Calculate the Output NOT */ - public BigDecimal calculateOutputNot() { - return calculateNetTaxPrice("Popular"); + public Double calculateOutputNot() { + return calculateNetTaxPrice("Popular").doubleValue(); } /** * Calculate the Output Excise Tax */ - public BigDecimal calculateOutputExciseTax() { - return calculateExciseTaxDomesticProduction("Popular"); + public Double calculateOutputExciseTax() { + return calculateExciseTaxDomesticProduction("Popular").doubleValue(); } /** * Calculate the Output VAT */ - public BigDecimal calculateOutputVat() { - return calculateVat("Popular"); + public Double calculateOutputVat() { + return calculateVat("Popular").doubleValue(); } /** * Calculate the Output Levy */ - public BigDecimal calculateOutputLevy() { - return calculateTobaccoLevy("Popular"); + public Double calculateOutputLevy() { + return calculateTobaccoLevy("Popular").doubleValue(); } /** diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculator.java b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculator.java index e1f8376e..51421a84 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculator.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculator.java @@ -11,7 +11,7 @@ */ public class TetsimOutputOvershiftCalculator extends TetsimOutputBaseCalculator { - public TetsimOutputOvershiftCalculator(TetsimDataset dataset, Double percentageChange) { + public TetsimOutputOvershiftCalculator(TetsimDataset dataset, Integer percentageChange) { super(dataset, percentageChange); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculator.java b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculator.java index 9380da3c..f6f2f687 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculator.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculator.java @@ -1,7 +1,6 @@ package org.devgateway.toolkit.forms.util.tetsim; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; -import org.devgateway.toolkit.persistence.dto.TetsimOutput; import java.math.BigDecimal; @@ -12,15 +11,10 @@ */ public class TetsimOutputUndershiftCalculator extends TetsimOutputBaseCalculator { - public TetsimOutputUndershiftCalculator(TetsimDataset dataset, Double percentageChange) { + public TetsimOutputUndershiftCalculator(TetsimDataset dataset, Integer percentageChange) { super(dataset, percentageChange); } - @Override - public TetsimOutput calculate() { - return null; - } - @Override protected BigDecimal calculateAbsChangeShift(final String tobaccoProduct) { BigDecimal exciseTax = getTobaccoProductValueFromVariable(dataset.getExciseTax(), tobaccoProduct); diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java index f4d10a84..9c21b41e 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java @@ -210,6 +210,6 @@ public TetsimPriceVariable getUndershifting() { } public void setUndershifting(final TetsimPriceVariable undershifting) { - this.undershifting = this.undershifting; + this.undershifting = undershifting; } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java index ccb6d8c2..a4a567a8 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java @@ -1,7 +1,6 @@ package org.devgateway.toolkit.persistence.dto; import java.io.Serializable; -import java.math.BigDecimal; /** * @@ -12,27 +11,27 @@ public class TetsimOutput implements Serializable { private Integer baseline; - private BigDecimal consumptionLegal; + private Double consumptionLegal; - private BigDecimal consumptionIllicit; + private Double consumptionIllicit; - private BigDecimal exciseRev; + private Double exciseRev; - private BigDecimal totalGovRev; + private Double totalGovRev; - private BigDecimal exciseBurden; + private Double exciseBurden; - private BigDecimal totalTaxBurden; + private Double totalTaxBurden; - private BigDecimal retailPrice; + private Double retailPrice; - private BigDecimal not; + private Double not; - private BigDecimal exciseTax; + private Double exciseTax; - private BigDecimal vat; + private Double vat; - private BigDecimal levy; + private Double levy; public Integer getBaseline() { return baseline; @@ -42,91 +41,91 @@ public void setBaseline(final Integer baseline) { this.baseline = baseline; } - public BigDecimal getConsumptionLegal() { + public Double getConsumptionLegal() { return consumptionLegal; } - public void setConsumptionLegal(final BigDecimal consumptionLegal) { + public void setConsumptionLegal(final Double consumptionLegal) { this.consumptionLegal = consumptionLegal; } - public BigDecimal getConsumptionIllicit() { + public Double getConsumptionIllicit() { return consumptionIllicit; } - public void setConsumptionIllicit(final BigDecimal consumptionIllicit) { + public void setConsumptionIllicit(final Double consumptionIllicit) { this.consumptionIllicit = consumptionIllicit; } - public BigDecimal getExciseRev() { + public Double getExciseRev() { return exciseRev; } - public void setExciseRev(final BigDecimal exciseRev) { + public void setExciseRev(final Double exciseRev) { this.exciseRev = exciseRev; } - public BigDecimal getTotalGovRev() { + public Double getTotalGovRev() { return totalGovRev; } - public void setTotalGovRev(final BigDecimal totalGovRev) { + public void setTotalGovRev(final Double totalGovRev) { this.totalGovRev = totalGovRev; } - public BigDecimal getExciseBurden() { + public Double getExciseBurden() { return exciseBurden; } - public void setExciseBurden(final BigDecimal exciseBurden) { + public void setExciseBurden(final Double exciseBurden) { this.exciseBurden = exciseBurden; } - public BigDecimal getTotalTaxBurden() { + public Double getTotalTaxBurden() { return totalTaxBurden; } - public void setTotalTaxBurden(final BigDecimal totalTaxBurden) { + public void setTotalTaxBurden(final Double totalTaxBurden) { this.totalTaxBurden = totalTaxBurden; } - public BigDecimal getRetailPrice() { + public Double getRetailPrice() { return retailPrice; } - public void setRetailPrice(final BigDecimal retailPrice) { + public void setRetailPrice(final Double retailPrice) { this.retailPrice = retailPrice; } - public BigDecimal getNot() { + public Double getNot() { return not; } - public void setNot(final BigDecimal not) { + public void setNot(final Double not) { this.not = not; } - public BigDecimal getExciseTax() { + public Double getExciseTax() { return exciseTax; } - public void setExciseTax(final BigDecimal exciseTax) { + public void setExciseTax(final Double exciseTax) { this.exciseTax = exciseTax; } - public BigDecimal getVat() { + public Double getVat() { return vat; } - public void setVat(final BigDecimal vat) { + public void setVat(final Double vat) { this.vat = vat; } - public BigDecimal getLevy() { + public Double getLevy() { return levy; } - public void setLevy(final BigDecimal levy) { + public void setLevy(final Double levy) { this.levy = levy; } } From bd4c56904b6827b00f3fbcecd531939598f75f3e Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Tue, 15 Mar 2022 14:56:06 +0200 Subject: [PATCH 062/137] TOBACCO-842: Refactor TETSIM output tests. Add undershift calculations. --- .../TetsimOutputBaseCalculatorTest.java | 2 + .../TetsimOutputCalculatorAbsChangeTest.java | 60 ++++++++++ ...imOutputCalculatorBaselineNumbersTest.java | 26 ++-- ...utputCalculatorQuantityAndRevenueTest.java | 12 +- ...utputOvershiftCalculatorAbsChangeTest.java | 48 -------- ...mOutputOvershiftCalculatorNumbersTest.java | 10 +- ...mOutputOvershiftCalculatorOverallTest.java | 55 +++++++++ .../TetsimOutputOvershiftCalculatorTest.java | 111 +++++++----------- ...OutputUndershiftCalculatorOverallTest.java | 55 +++++++++ 9 files changed, 240 insertions(+), 139 deletions(-) create mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorAbsChangeTest.java delete mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorAbsChangeTest.java create mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java create mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculatorTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculatorTest.java index fb6fe356..7abdc0ae 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculatorTest.java +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculatorTest.java @@ -27,6 +27,8 @@ public class TetsimOutputBaseCalculatorTest { protected TetsimDataset datasetWithAllTobaccoProducts; + double delta = 0.01; + @Before public void setUp() { this.tobaccoProductImported = createTobaccoProduct("Imported", false); diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorAbsChangeTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorAbsChangeTest.java new file mode 100644 index 00000000..50f8ed89 --- /dev/null +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorAbsChangeTest.java @@ -0,0 +1,60 @@ +package org.devgateway.toolkit.forms.util.tetsim; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TetsimOutputCalculatorAbsChangeTest extends TetsimOutputBaseCalculatorTest { + + @Before + public void setUp() { + super.setUp(); + } + + @Test + public void testOvershiftAbsChangeBaseline() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); + assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Imported").doubleValue(), + delta, "Check Abs change overshift imported baseline"); + assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Premium").doubleValue(), + delta, "Check Abs change overshift imported baseline"); + } + + @Test + public void testOvershiftAbsChange() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); + assertAll("TETSIM Overshift Abs Change", + () -> assertEquals(0.75, tetsimOutputCalculator.calculateAbsChangeShift("Popular").doubleValue(), + delta, "Check Abs change overshift popular"), + () -> assertEquals(0.38, tetsimOutputCalculator.calculateAbsChangeShift("Discount").doubleValue(), + delta, "Check Abs change overshift discount"), + () -> assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Illicit").doubleValue(), + delta, "Check Abs change overshift illicit") + ); + } + + @Test + public void testUndershiftAbsChangeBaseline() { + TetsimOutputUndershiftCalculator tetsimOutputCalculator = new TetsimOutputUndershiftCalculator(datasetWithAllTobaccoProducts, 0); + assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Imported").doubleValue(), + delta, "Check Abs change undershift imported baseline"); + assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Premium").doubleValue(), + delta, "Check Abs change undershift premium baseline"); + } + + @Test + public void testUndershiftAbsChange() { + TetsimOutputUndershiftCalculator tetsimOutputCalculator = new TetsimOutputUndershiftCalculator(datasetWithAllTobaccoProducts, 20); + assertAll("TETSIM Undershift Abs Change", + () -> assertEquals(-1.13, tetsimOutputCalculator.calculateAbsChangeShift("Popular").doubleValue(), + delta, "Check Abs change undershift popular"), + () -> assertEquals(-1.88, tetsimOutputCalculator.calculateAbsChangeShift("Discount").doubleValue(), + delta, "Check Abs change undershift discount"), + () -> assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Illicit").doubleValue(), + delta, "Check Abs change undershift illicit") + ); + } + +} \ No newline at end of file diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java index ea4a7dbf..b8473c50 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java @@ -15,77 +15,77 @@ public void setUp() { @Test public void testBaselineNetOfTaxPrice() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); assertEquals(19.43, tetsimOutputCalculator.calculateBaselineNetTaxPrice("Imported") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Net of Tax for Imported Product"); } @Test public void testBaselineNetOfTaxPriceWithPercentageChange() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertEquals(16.00, tetsimOutputCalculator.calculateBaselineNetTaxPrice("Popular") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Net of Tax for Popular Product with percentage change"); } @Test public void testBaselineIllicitNetOfTaxPriceWithPercentageChange() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertEquals(20.00, tetsimOutputCalculator.calculateBaselineNetTaxPrice("Illicit") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Net of Tax Price for Illicit Product with percentage change"); } @Test public void testBaselineIllicitRetailPrice() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); assertEquals(20.00, tetsimOutputCalculator.calculateBaselineRetailPrice("Illicit") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Retail Price for Illicit Product"); } @Test public void testBaselineRetailPriceWithPercentageChange() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertEquals(40.00, tetsimOutputCalculator.calculateBaselineRetailPrice("Popular") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Retail Price for Popular Product with percentage change"); } @Test public void testBaselineIllicitExciseTaxOnDomestic() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); - assertEquals(0.0, tetsimOutputCalculator.calculateBaselineExciseTaxOnDomesticProduction("Illicit") + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); + assertEquals(0, tetsimOutputCalculator.calculateBaselineExciseTaxOnDomesticProduction("Illicit") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Excise Tax for Illicit Product"); } @Test public void testBaselineImportedExciseTaxOnDomestic() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); - assertEquals(0.0, tetsimOutputCalculator.calculateBaselineExciseTaxOnDomesticProduction("Imported") + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); + assertEquals(0, tetsimOutputCalculator.calculateBaselineExciseTaxOnDomesticProduction("Imported") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Excise Tax for Imported Product"); } @Test public void testBaselinePopularExciseTaxOnDomestic() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); assertEquals(18.78, tetsimOutputCalculator.calculateBaselineExciseTaxOnDomesticProduction("Popular") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Excise Tax for Popular Product"); } @Test public void testBaselinePopularVAT() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); assertEquals(5.22, tetsimOutputCalculator.calculateBaselineVAT("Popular") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline VAT for Popular Product"); } @Test public void testBaselineDiscountExciseBurden() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); assertEquals(67.07, tetsimOutputCalculator.calculateBaselineExciseBurden("Discount") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Excise Burden for Discount Product"); } @Test public void testBaselinePremiumTotalTaxBurden() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); assertEquals(52.17, tetsimOutputCalculator.calculateBaselineTotalTaxBurden("Premium") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Total Tax Burden for Premium Product"); } diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java index f62d8452..a7b76846 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java @@ -15,42 +15,42 @@ public void setUp() { @Test public void testBaselineTotalConsumption() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.00); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertEquals(754.4, tetsimOutputCalculator.calculateBaselineTotalLegalConsumption() .setScale(1, ROUND_HALF_UP).doubleValue(), "Check baseline Total Consumption"); } @Test public void testPreConsumption() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.00); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertEquals(54.9, tetsimOutputCalculator.calculatePreConsumption("Imported") .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Pre Consumption for Imported Tobacco Product"); } @Test public void testPreConsumptionIllicit() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.00); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertEquals(369.9, tetsimOutputCalculator.calculatePreConsumption("Illicit") .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Pre Consumption for Illicit Tobacco Product"); } @Test public void testGainFromPrice() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.00); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertEquals(17.8, tetsimOutputCalculator.calculateGainFromPrice("Illicit") .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Gain From Price for Illicit Tobacco Product"); } @Test public void testConsumptionPopular() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.00); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertEquals(432.2, tetsimOutputCalculator.calculateConsumption("Popular") .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption for Popular Tobacco Product"); } @Test public void testConsumptionIllicit() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.00); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertEquals(387.6, tetsimOutputCalculator.calculateConsumption("Illicit") .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption for Illicit Tobacco Product"); } diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorAbsChangeTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorAbsChangeTest.java deleted file mode 100644 index 2e47882d..00000000 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorAbsChangeTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.devgateway.toolkit.forms.util.tetsim; - -import org.devgateway.toolkit.persistence.dto.TetsimOutput; -import org.junit.Before; -import org.junit.Test; - -import static java.math.BigDecimal.ROUND_HALF_UP; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class TetsimOutputOvershiftCalculatorAbsChangeTest extends TetsimOutputBaseCalculatorTest { - - @Before - public void setUp() { - super.setUp(); - } - - @Test - public void testAbsChangeImportedBaseline() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); - TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Imported") - .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Abs change overshift imported baseline"); - } - - @Test - public void testAbsChangePopular() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); - TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(0.75, tetsimOutputCalculator.calculateAbsChangeShift("Popular") - .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Abs change overshift popular"); - } - - @Test - public void testAbsChangeDiscount() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); - TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(0.38, tetsimOutputCalculator.calculateAbsChangeShift("Discount") - .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Abs change overshift discount"); - } - - @Test - public void testAbsChangeIllicit() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); - assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Illicit") - .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Abs change overshift illicit"); - } - -} \ No newline at end of file diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java index d491c68b..fc29ae99 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java @@ -15,35 +15,35 @@ public void setUp() { @Test public void testPopularNetTaxPrice() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertEquals(16.75, tetsimOutputCalculator.calculateNetTaxPrice("Popular") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift Net of Tax for Popular Product"); } @Test public void testIllicitNetTaxPrice() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertEquals(22.38, tetsimOutputCalculator.calculateNetTaxPrice("Illicit") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift Net of Tax for Illicit Product"); } @Test public void testPopularExciseTaxOnDomesticProduction() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertEquals(22.54, tetsimOutputCalculator.calculateExciseTaxDomesticProduction("Popular") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift Excise Tax on domestic production for Popular Product"); } @Test public void testPremiumVat() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertEquals(6.99, tetsimOutputCalculator.calculateVat("Premium") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift VAT for Premium Product"); } @Test public void testImportedRetailPrice() { - TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertEquals(50.62, tetsimOutputCalculator.calculateRetailPrice("Imported") .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift Retail Price for Imported Product"); } diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java new file mode 100644 index 00000000..92b29804 --- /dev/null +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java @@ -0,0 +1,55 @@ +package org.devgateway.toolkit.forms.util.tetsim; + +import org.devgateway.toolkit.persistence.dto.TetsimOutput; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TetsimOutputOvershiftCalculatorOverallTest extends TetsimOutputBaseCalculatorTest { + + @Before + public void setUp() { + super.setUp(); + } + + @Test + public void testOverallOutputBaseline() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + + assertAll("TETSIM Overshift Baseline", + () -> assertEquals(754.40, output.getConsumptionLegal(), delta, "TETSIM Overshift - Consumption Legal"), + () -> assertEquals(395.60, output.getConsumptionIllicit(), delta, "TETSIM Overshift - Consumption Illicit"), + () -> assertEquals(14167.63, output.getExciseRev(), delta, "TETSIM Overshift - Excise Revenue"), + () -> assertEquals(18051.37, output.getTotalGovRev(), delta, "TETSIM Overshift - Government Revenue"), + () -> assertEquals(46.95, output.getExciseBurden(), delta, "TETSIM Overshift - Excise Burden"), + () -> assertEquals(60.00, output.getTotalTaxBurden(), delta, "TETSIM Overshift - Total Tax Burden"), + () -> assertEquals(40.00, output.getRetailPrice(), delta, "TETSIM Overshift - Retail Price"), + () -> assertEquals(16.00, output.getNot(), delta, "TETSIM Overshift - NOT"), + () -> assertEquals(18.78, output.getExciseTax(), delta, "TETSIM Overshift - Excise Tax"), + () -> assertEquals(5.21, output.getVat(), delta, "TETSIM Overshift - VAT"), + () -> assertEquals(0.00, output.getLevy(), delta, "TETSIM Overshift - Levy")); + } + + @Test + public void testOverallOutputWithTaxChange() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 30); + TetsimOutput output = tetsimOutputCalculator.calculate(); + + assertAll("TETSIM Overshift With 30% Tax Change", + () -> assertEquals(648.79, output.getConsumptionLegal(), delta, "TETSIM Overshift - Consumption Legal"), + () -> assertEquals(383.73, output.getConsumptionIllicit(), delta, "TETSIM Overshift - Consumption Illicit"), + () -> assertEquals(15839.61, output.getExciseRev(), delta, "TETSIM Overshift - Excise Revenue"), + () -> assertEquals(19873.25, output.getTotalGovRev(), delta, "TETSIM Overshift - Government Revenue"), + () -> assertEquals(51.10, output.getExciseBurden(), delta, "TETSIM Overshift - Excise Burden"), + () -> assertEquals(64.15, output.getTotalTaxBurden(), delta, "TETSIM Overshift - Total Tax Burden"), + () -> assertEquals(47.77, output.getRetailPrice(), delta, "TETSIM Overshift - Retail Price"), + () -> assertEquals(17.13, output.getNot(), delta, "TETSIM Overshift - NOT"), + () -> assertEquals(24.41, output.getExciseTax(), delta, "TETSIM Overshift - Excise Tax"), + () -> assertEquals(6.23, output.getVat(), delta, "TETSIM Overshift - VAT"), + () -> assertEquals(0.00, output.getLevy(), delta, "TETSIM Overshift - Levy")); + } + +} \ No newline at end of file diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java index 4d13c18f..94b63490 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java @@ -4,7 +4,6 @@ import org.junit.Before; import org.junit.Test; -import static java.math.BigDecimal.ROUND_HALF_UP; import static org.junit.jupiter.api.Assertions.assertEquals; public class TetsimOutputOvershiftCalculatorTest extends TetsimOutputBaseCalculatorTest { @@ -16,178 +15,156 @@ public void setUp() { @Test public void testConsumptionLegalNoTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(754.4, output.getConsumptionLegal() - .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption Legal TETSIM Output Overshift"); + assertEquals(754.4, output.getConsumptionLegal(), delta, "Check Consumption Legal TETSIM Output Overshift"); } @Test public void testConsumptionLegalWithTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(680.2, output.getConsumptionLegal() - .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption Legal TETSIM Output Overshift (Tax Change)"); + assertEquals(680.19, output.getConsumptionLegal(), delta, "Check Consumption Legal TETSIM Output Overshift (Tax Change)"); } @Test public void testConsumptionIllicitNoTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(395.6, output.getConsumptionIllicit() - .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption Illicit TETSIM Output Overshift"); + assertEquals(395.6, output.getConsumptionIllicit(), delta, "Check Consumption Illicit TETSIM Output Overshift"); } @Test public void testConsumptionIllicitWithTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(387.6, output.getConsumptionIllicit() - .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption Illicit TETSIM Output Overshift (Tax Change)"); + assertEquals(387.62, output.getConsumptionIllicit(), delta, "Check Consumption Illicit TETSIM Output Overshift (Tax Change)"); } @Test public void testTotalExciseRevenueNoTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(14167.6, output.getExciseRev() - .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Total Legal Excise Revenue TETSIM Output Overshift"); + assertEquals(14167.63, output.getExciseRev(), delta, "Check Total Legal Excise Revenue TETSIM Output Overshift"); } @Test public void testTotalExciseRevenueWithTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(15328.9, output.getExciseRev() - .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Total Legal Excise Revenue TETSIM Output Overshift (Tax Change)"); + assertEquals(15328.9, output.getExciseRev(), delta, "Check Total Legal Excise Revenue TETSIM Output Overshift (Tax Change)"); } @Test public void testTotalLegalGovRevenueNoTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(18051.4, output.getTotalGovRev() - .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Total Legal Government Revenue TETSIM Output Overshift"); + assertEquals(18051.37, output.getTotalGovRev(), delta, "Check Total Legal Government Revenue TETSIM Output Overshift"); } @Test public void testTotalLegalGovRevenueWithTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(19315.5, output.getTotalGovRev() - .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Total Legal Government Revenue TETSIM Output Overshift (Tax Change)"); + assertEquals(19315.54, output.getTotalGovRev(), delta, "Check Total Legal Government Revenue TETSIM Output Overshift (Tax Change)"); } @Test public void testExciseBurdenNoTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(47.0, output.getExciseBurden() - .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Excise Burden TETSIM Output Overshift"); + assertEquals(46.95, output.getExciseBurden(), delta, "Check Excise Burden TETSIM Output Overshift"); } @Test public void testExciseBurdenWithTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(49.9, output.getExciseBurden() - .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Excise Burden TETSIM Output Overshift (Tax Change)"); + assertEquals(49.87, output.getExciseBurden(), delta, "Check Excise Burden TETSIM Output Overshift (Tax Change)"); } @Test public void testTotalTaxBurdenNoTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(60.0, output.getTotalTaxBurden() - .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Total Tax Burden TETSIM Output Overshift"); + assertEquals(60.0, output.getTotalTaxBurden(), delta, "Check Total Tax Burden TETSIM Output Overshift"); } @Test public void testTotalTaxBurdenWithTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(62.9, output.getTotalTaxBurden() - .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Total Tax Burden TETSIM Output Overshift (Tax Change)"); + assertEquals(62.92, output.getTotalTaxBurden(), delta, "Check Total Tax Burden TETSIM Output Overshift (Tax Change)"); } @Test public void testRetailPriceNoTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(40.0, output.getRetailPrice() - .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Retail Price TETSIM Output Overshift (Baseline)"); + assertEquals(40.0, output.getRetailPrice(), delta, "Check Retail Price TETSIM Output Overshift (Baseline)"); } @Test public void testRetailPriceWithTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(45.18, output.getRetailPrice() - .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Retail Price TETSIM Output Overshift (Tax Change)"); + assertEquals(45.18, output.getRetailPrice(), delta, "Check Retail Price TETSIM Output Overshift (Tax Change)"); } @Test public void testNOTNoTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(16.0, output.getNot() - .setScale(2, ROUND_HALF_UP).doubleValue(), "Check NOT TETSIM Output Overshift"); + assertEquals(16.0, output.getNot(), delta, "Check NOT TETSIM Output Overshift"); } @Test public void testNOTWithTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(16.75, output.getNot() - .setScale(2, ROUND_HALF_UP).doubleValue(), "Check NOT TETSIM Output Overshift (Tax Change)"); + assertEquals(16.75, output.getNot(), delta, "Check NOT TETSIM Output Overshift (Tax Change)"); } @Test public void testExciseTaxNoTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(18.78, output.getExciseTax() - .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Excise Tax TETSIM Output Overshift"); + assertEquals(18.78, output.getExciseTax(), delta, "Check Excise Tax TETSIM Output Overshift"); } @Test public void testExciseTaxWithTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(22.54, output.getExciseTax() - .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Excise Tax TETSIM Output Overshift (Tax Change)"); + assertEquals(22.54, output.getExciseTax(), delta, "Check Excise Tax TETSIM Output Overshift (Tax Change)"); } @Test public void testVatNoTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(5.22, output.getVat() - .setScale(2, ROUND_HALF_UP).doubleValue(), "Check VAT TETSIM Output Overshift"); + assertEquals(5.22, output.getVat(), delta, "Check VAT TETSIM Output Overshift"); } @Test public void testVatWithTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(5.89, output.getVat() - .setScale(2, ROUND_HALF_UP).doubleValue(), "Check VAT TETSIM Output Overshift (Tax Change)"); + assertEquals(5.89, output.getVat(), delta, "Check VAT TETSIM Output Overshift (Tax Change)"); } @Test public void testLevyNoTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(0.00, output.getLevy() - .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Levy TETSIM Output Overshift"); + assertEquals(0.00, output.getLevy(), delta, "Check Levy TETSIM Output Overshift"); } @Test public void testLevyWithTaxChange() { - TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20.0); + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); TetsimOutput output = tetsimOutputCalculator.calculate(); - assertEquals(0.00, output.getLevy() - .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Levy TETSIM Output Overshift (Tax Change)"); + assertEquals(0.00, output.getLevy(), delta, "Check Levy TETSIM Output Overshift (Tax Change)"); } } \ No newline at end of file diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java new file mode 100644 index 00000000..43726ae9 --- /dev/null +++ b/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java @@ -0,0 +1,55 @@ +package org.devgateway.toolkit.forms.util.tetsim; + +import org.devgateway.toolkit.persistence.dto.TetsimOutput; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TetsimOutputUndershiftCalculatorOverallTest extends TetsimOutputBaseCalculatorTest { + + @Before + public void setUp() { + super.setUp(); + } + + @Test + public void testOverallOutputBaseline() { + TetsimOutputUndershiftCalculator tetsimOutputCalculator = new TetsimOutputUndershiftCalculator(datasetWithAllTobaccoProducts, 0); + TetsimOutput output = tetsimOutputCalculator.calculate(); + + assertAll("TETSIM Undershift Baseline", + () -> assertEquals(754.40, output.getConsumptionLegal(), delta, "TETSIM Undershift - Consumption Legal"), + () -> assertEquals(395.60, output.getConsumptionIllicit(), delta, "TETSIM Undershift - Consumption Illicit"), + () -> assertEquals(14167.63, output.getExciseRev(), delta, "TETSIM Undershift - Excise Revenue"), + () -> assertEquals(18051.37, output.getTotalGovRev(), delta, "TETSIM Undershift - Government Revenue"), + () -> assertEquals(46.95, output.getExciseBurden(), delta, "TETSIM Undershift - Excise Burden"), + () -> assertEquals(60.00, output.getTotalTaxBurden(), delta, "TETSIM Undershift - Total Tax Burden"), + () -> assertEquals(40.00, output.getRetailPrice(), delta, "TETSIM Undershift - Retail Price"), + () -> assertEquals(16.00, output.getNot(), delta, "TETSIM Undershift - NOT"), + () -> assertEquals(18.78, output.getExciseTax(), delta, "TETSIM Undershift - Excise Tax"), + () -> assertEquals(5.21, output.getVat(), delta, "TETSIM Undershift - VAT"), + () -> assertEquals(0.00, output.getLevy(), delta, "TETSIM Undershift - Levy")); + } + + @Test + public void testOverallOutputWithTaxChange() { + TetsimOutputUndershiftCalculator tetsimOutputCalculator = new TetsimOutputUndershiftCalculator(datasetWithAllTobaccoProducts, 30); + TetsimOutput output = tetsimOutputCalculator.calculate(); + + assertAll("TETSIM Undershift With 30% Tax Change", + () -> assertEquals(694.62, output.getConsumptionLegal(), delta, "TETSIM Undershift - Consumption Legal"), + () -> assertEquals(390.14, output.getConsumptionIllicit(), delta, "TETSIM Undershift - Consumption Illicit"), + () -> assertEquals(16958.46, output.getExciseRev(), delta, "TETSIM Undershift - Excise Revenue"), + () -> assertEquals(20945.90, output.getTotalGovRev(), delta, "TETSIM Undershift - Government Revenue"), + () -> assertEquals(54.82, output.getExciseBurden(), delta, "TETSIM Undershift - Excise Burden"), + () -> assertEquals(67.86, output.getTotalTaxBurden(), delta, "TETSIM Undershift - Total Tax Burden"), + () -> assertEquals(44.54, output.getRetailPrice(), delta, "TETSIM Undershift - Retail Price"), + () -> assertEquals(14.31, output.getNot(), delta, "TETSIM Undershift - NOT"), + () -> assertEquals(24.41, output.getExciseTax(), delta, "TETSIM Undershift - Excise Tax"), + () -> assertEquals(5.81, output.getVat(), delta, "TETSIM Undershift - VAT"), + () -> assertEquals(0.00, output.getLevy(), delta, "TETSIM Undershift - Levy")); + } + +} \ No newline at end of file From c09728a377dca0fbef2b5906e550f1b00a3af3b4 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 21 Mar 2022 13:04:45 +0200 Subject: [PATCH 063/137] TOBACCO-841: Add Tetsim API --- .../forms/service/TetsimOutputService.java | 9 ----- .../dataset/TetsimIndustryResponsesPanel.java | 12 +++--- .../TetsimIndustryResponsesPanel.properties | 8 ++-- .../dataset/TetsimPriceAnalysisPanel.java | 2 +- .../converter/DefaultDecimalFormatter.java | 3 +- .../service/tetsim/TetsimOutputService.java | 30 +++++++++++++++ .../tetsim/TetsimOutputBaseCalculator.java | 10 +++-- .../util/tetsim/TetsimOutputCalculator.java | 2 +- .../TetsimOutputOvershiftCalculator.java | 6 +-- .../TetsimOutputUndershiftCalculator.java | 7 ++-- .../persistence}/util/tetsim/TetsimUtil.java | 2 +- .../TetsimOutputBaseCalculatorTest.java | 10 ++--- .../TetsimOutputCalculatorAbsChangeTest.java | 4 +- ...imOutputCalculatorBaselineNumbersTest.java | 3 +- ...utputCalculatorQuantityAndRevenueTest.java | 3 +- ...mOutputOvershiftCalculatorNumbersTest.java | 3 +- ...mOutputOvershiftCalculatorOverallTest.java | 3 +- .../TetsimOutputOvershiftCalculatorTest.java | 4 +- ...OutputUndershiftCalculatorOverallTest.java | 3 +- .../tetsim/builder/TetsimDatasetBuilder.java | 2 +- .../builder/TetsimPriceVariableBuilder.java | 2 +- .../TetsimTobaccoProductValueBuilder.java | 2 +- .../tetsim/builder/TobaccoProductBuilder.java | 2 +- .../web/rest/controller/TestController.java | 4 -- .../web/rest/controller/TetsimController.java | 37 +++++++++++++++++++ .../toolkit/web/spring/WebSecurityConfig.java | 15 +++++++- 26 files changed, 135 insertions(+), 53 deletions(-) delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/TetsimOutputService.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java rename {forms/src/main/java/org/devgateway/toolkit/forms => persistence/src/main/java/org/devgateway/toolkit/persistence}/util/tetsim/TetsimOutputBaseCalculator.java (98%) rename {forms/src/main/java/org/devgateway/toolkit/forms => persistence/src/main/java/org/devgateway/toolkit/persistence}/util/tetsim/TetsimOutputCalculator.java (71%) rename {forms/src/main/java/org/devgateway/toolkit/forms => persistence/src/main/java/org/devgateway/toolkit/persistence}/util/tetsim/TetsimOutputOvershiftCalculator.java (75%) rename {forms/src/main/java/org/devgateway/toolkit/forms => persistence/src/main/java/org/devgateway/toolkit/persistence}/util/tetsim/TetsimOutputUndershiftCalculator.java (75%) rename {forms/src/main/java/org/devgateway/toolkit/forms => persistence/src/main/java/org/devgateway/toolkit/persistence}/util/tetsim/TetsimUtil.java (90%) rename {forms/src/test/java/org/devgateway/toolkit/forms/util => persistence/src/test/java/org/devgateway/toolkit/persistence}/tetsim/TetsimOutputBaseCalculatorTest.java (92%) rename {forms/src/test/java/org/devgateway/toolkit/forms/util => persistence/src/test/java/org/devgateway/toolkit/persistence}/tetsim/TetsimOutputCalculatorAbsChangeTest.java (93%) rename {forms/src/test/java/org/devgateway/toolkit/forms/util => persistence/src/test/java/org/devgateway/toolkit/persistence}/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java (97%) rename {forms/src/test/java/org/devgateway/toolkit/forms/util => persistence/src/test/java/org/devgateway/toolkit/persistence}/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java (95%) rename {forms/src/test/java/org/devgateway/toolkit/forms/util => persistence/src/test/java/org/devgateway/toolkit/persistence}/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java (94%) rename {forms/src/test/java/org/devgateway/toolkit/forms/util => persistence/src/test/java/org/devgateway/toolkit/persistence}/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java (96%) rename {forms/src/test/java/org/devgateway/toolkit/forms/util => persistence/src/test/java/org/devgateway/toolkit/persistence}/tetsim/TetsimOutputOvershiftCalculatorTest.java (97%) rename {forms/src/test/java/org/devgateway/toolkit/forms/util => persistence/src/test/java/org/devgateway/toolkit/persistence}/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java (96%) rename {forms/src/test/java/org/devgateway/toolkit/forms/util => persistence/src/test/java/org/devgateway/toolkit/persistence}/tetsim/builder/TetsimDatasetBuilder.java (98%) rename {forms/src/test/java/org/devgateway/toolkit/forms/util => persistence/src/test/java/org/devgateway/toolkit/persistence}/tetsim/builder/TetsimPriceVariableBuilder.java (91%) rename {forms/src/test/java/org/devgateway/toolkit/forms/util => persistence/src/test/java/org/devgateway/toolkit/persistence}/tetsim/builder/TetsimTobaccoProductValueBuilder.java (93%) rename {forms/src/test/java/org/devgateway/toolkit/forms/util => persistence/src/test/java/org/devgateway/toolkit/persistence}/tetsim/builder/TobaccoProductBuilder.java (90%) create mode 100644 web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/TetsimOutputService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/TetsimOutputService.java deleted file mode 100644 index e494ad5b..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/TetsimOutputService.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.devgateway.toolkit.forms.service; - -import org.springframework.stereotype.Service; - -@Service -public class TetsimOutputService { - - -} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.java index 35dcc273..f587ff4e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.java @@ -70,9 +70,9 @@ private Component getIndustryResponsesVariables() { */ private TetsimTobaccoProductsVariable getOverShifting(final String id) { return new TetsimTobaccoProductsVariable(id, - new StringResourceModel("overShifting.label"), - new StringResourceModel("overShifting.unit"), - new PropertyModel<>(tetsimDatasetIModel, "overShifting"), true) { + new StringResourceModel("overshifting.label"), + new StringResourceModel("overshifting.unit"), + new PropertyModel<>(tetsimDatasetIModel, "overshifting"), true) { }; } @@ -85,9 +85,9 @@ private TetsimTobaccoProductsVariable getOverShifting(final String id) { */ private TetsimTobaccoProductsVariable getUnderShifting(final String id) { return new TetsimTobaccoProductsVariable(id, - new StringResourceModel("underShifting.label"), - new StringResourceModel("underShifting.unit"), - new PropertyModel<>(tetsimDatasetIModel, "underShifting"), true) { + new StringResourceModel("undershifting.label"), + new StringResourceModel("undershifting.unit"), + new PropertyModel<>(tetsimDatasetIModel, "undershifting"), true) { }; } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.properties index c4f11b14..d2fde381 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.properties @@ -1,6 +1,6 @@ -overShifting.label=Overshifting (% change above excise tax increase) -overShifting.unit=Percentage change above excise tax increase +overshifting.label=Overshifting (% change above excise tax increase) +overshifting.unit=Percentage change above excise tax increase -underShifting.label=Change in illicit NOT (proportion of change in discount price): sensitivity factor -underShifting.unit=Undershifting (% change below excise tax increase) +undershifting.label=Change in illicit NOT (proportion of change in discount price): sensitivity factor +undershifting.unit=Undershifting (% change below excise tax increase) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java index 43074d46..f88f29dd 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java @@ -238,7 +238,7 @@ private TetsimTobaccoProductsVariable getElasticityOfDemandCrossPrice(final Stri return new TetsimTobaccoProductsVariable(id, new StringResourceModel("elasticityOfDemandCrossPrice.label"), new StringResourceModel("elasticityOfDemandCrossPrice.unit"), - new PropertyModel<>(tetsimDatasetIModel, "elasticityOfDemandPrice")) { + new PropertyModel<>(tetsimDatasetIModel, "elasticityOfDemandCrossPrice")) { @Override protected void addBehavioursToTobaccoProductVariable(final TextFieldBootstrapFormComponent variable1) { diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/converter/DefaultDecimalFormatter.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/converter/DefaultDecimalFormatter.java index c9bac36e..e5a6d926 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/converter/DefaultDecimalFormatter.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/converter/DefaultDecimalFormatter.java @@ -1,5 +1,6 @@ package org.devgateway.toolkit.persistence.converter; +import java.io.Serializable; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; @@ -9,7 +10,7 @@ /** * @author Nadejda Mandrescu */ -public class DefaultDecimalFormatter implements INumberFormatter { +public class DefaultDecimalFormatter implements INumberFormatter, Serializable { private final ConcurrentHashMap decimalFormats = new ConcurrentHashMap<>(); diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java new file mode 100644 index 00000000..52122b1a --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java @@ -0,0 +1,30 @@ +package org.devgateway.toolkit.persistence.service.tetsim; + +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dto.TetsimOutputs; +import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; +import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; +import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputUndershiftCalculator; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class TetsimOutputService { + + @Autowired + private TetsimDatasetService tetsimDatasetService; + + public TetsimOutputs getTetsimOutputs(Long datasetId) { + TetsimDataset dataset = tetsimDatasetService.findById(datasetId).get(); + TetsimOutputs outputs = new TetsimOutputs(); + + for (int i = 0; i <= 100; i++) { + outputs.getOvershift().add(new TetsimOutputOvershiftCalculator(dataset, i).calculate()); + outputs.getUndershift().add(new TetsimOutputUndershiftCalculator(dataset, i).calculate()); + } + + return outputs; + } + + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java similarity index 98% rename from forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java rename to persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java index 1b3fa8f6..bf586d18 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java @@ -1,4 +1,4 @@ -package org.devgateway.toolkit.forms.util.tetsim; +package org.devgateway.toolkit.persistence.util.tetsim; import com.google.common.collect.ImmutableMap; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; @@ -13,7 +13,7 @@ import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static java.math.BigDecimal.ZERO; -import static org.devgateway.toolkit.forms.util.tetsim.TetsimUtil.getTobaccoProductValueFromVariable; +import static org.devgateway.toolkit.persistence.util.tetsim.TetsimUtil.getTobaccoProductValueFromVariable; /** * @author vchihai @@ -188,7 +188,7 @@ protected BigDecimal calculateTobaccoLevy(String tobaccoProduct) { * @param tobaccoProduct * @return */ - protected BigDecimal calculateExciseTaxDomesticProduction(String tobaccoProduct) { + public BigDecimal calculateExciseTaxDomesticProduction(String tobaccoProduct) { return calculateBaselineExciseTaxOnDomesticProduction(tobaccoProduct) .multiply(ONE.add(BigDecimal.valueOf(percentageChange).divide(HUNDRED, DEFAULT_CONTEXT))); } @@ -523,6 +523,10 @@ public BigDecimal calculateBaselineCustomsDuty(String tobaccoProduct) { BigDecimal cif = getTobaccoProductValueFromVariable(dataset.getCif(), tobaccoProduct); BigDecimal duty = getTobaccoProductValueFromVariable(dataset.getCustomsDuty(), tobaccoProduct); + if (duty == null) { + return ZERO; + } + return cif.multiply(duty) .divide(HUNDRED); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputCalculator.java similarity index 71% rename from forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculator.java rename to persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputCalculator.java index 915d33de..13fd0daf 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputCalculator.java @@ -1,4 +1,4 @@ -package org.devgateway.toolkit.forms.util.tetsim; +package org.devgateway.toolkit.persistence.util.tetsim; import org.devgateway.toolkit.persistence.dto.TetsimOutput; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputOvershiftCalculator.java similarity index 75% rename from forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculator.java rename to persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputOvershiftCalculator.java index 51421a84..d6136c31 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputOvershiftCalculator.java @@ -1,10 +1,10 @@ -package org.devgateway.toolkit.forms.util.tetsim; +package org.devgateway.toolkit.persistence.util.tetsim; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import java.math.BigDecimal; -import static org.devgateway.toolkit.forms.util.tetsim.TetsimUtil.getTobaccoProductValueFromVariable; +import static org.devgateway.toolkit.persistence.util.tetsim.TetsimUtil.getTobaccoProductValueFromVariable; /** * @author vchihai @@ -16,7 +16,7 @@ public TetsimOutputOvershiftCalculator(TetsimDataset dataset, Integer percentage } @Override - protected BigDecimal calculateAbsChangeShift(final String tobaccoProduct) { + public BigDecimal calculateAbsChangeShift(final String tobaccoProduct) { BigDecimal exciseTax = getTobaccoProductValueFromVariable(dataset.getExciseTax(), tobaccoProduct); BigDecimal overshifting = getTobaccoProductValueFromVariable(dataset.getOvershifting(), tobaccoProduct); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputUndershiftCalculator.java similarity index 75% rename from forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculator.java rename to persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputUndershiftCalculator.java index f6f2f687..2e120457 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputUndershiftCalculator.java @@ -1,10 +1,10 @@ -package org.devgateway.toolkit.forms.util.tetsim; +package org.devgateway.toolkit.persistence.util.tetsim; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import java.math.BigDecimal; -import static org.devgateway.toolkit.forms.util.tetsim.TetsimUtil.getTobaccoProductValueFromVariable; +import static org.devgateway.toolkit.persistence.util.tetsim.TetsimUtil.getTobaccoProductValueFromVariable; /** * @author vchihai @@ -16,7 +16,7 @@ public TetsimOutputUndershiftCalculator(TetsimDataset dataset, Integer percentag } @Override - protected BigDecimal calculateAbsChangeShift(final String tobaccoProduct) { + public BigDecimal calculateAbsChangeShift(final String tobaccoProduct) { BigDecimal exciseTax = getTobaccoProductValueFromVariable(dataset.getExciseTax(), tobaccoProduct); BigDecimal undershifting = getTobaccoProductValueFromVariable(dataset.getUndershifting(), tobaccoProduct); @@ -24,4 +24,5 @@ protected BigDecimal calculateAbsChangeShift(final String tobaccoProduct) { .divide(HUNDRED) .multiply(undershifting); } + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimUtil.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimUtil.java similarity index 90% rename from forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimUtil.java rename to persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimUtil.java index 727cde1d..e9f4ac2f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/util/tetsim/TetsimUtil.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimUtil.java @@ -1,4 +1,4 @@ -package org.devgateway.toolkit.forms.util.tetsim; +package org.devgateway.toolkit.persistence.util.tetsim; import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculatorTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputBaseCalculatorTest.java similarity index 92% rename from forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculatorTest.java rename to persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputBaseCalculatorTest.java index 7abdc0ae..1061d67f 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputBaseCalculatorTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputBaseCalculatorTest.java @@ -1,9 +1,9 @@ -package org.devgateway.toolkit.forms.util.tetsim; +package org.devgateway.toolkit.persistence.tetsim; -import org.devgateway.toolkit.forms.util.tetsim.builder.TetsimDatasetBuilder; -import org.devgateway.toolkit.forms.util.tetsim.builder.TetsimPriceVariableBuilder; -import org.devgateway.toolkit.forms.util.tetsim.builder.TetsimTobaccoProductValueBuilder; -import org.devgateway.toolkit.forms.util.tetsim.builder.TobaccoProductBuilder; +import org.devgateway.toolkit.persistence.tetsim.builder.TetsimDatasetBuilder; +import org.devgateway.toolkit.persistence.tetsim.builder.TetsimPriceVariableBuilder; +import org.devgateway.toolkit.persistence.tetsim.builder.TetsimTobaccoProductValueBuilder; +import org.devgateway.toolkit.persistence.tetsim.builder.TobaccoProductBuilder; import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorAbsChangeTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorAbsChangeTest.java similarity index 93% rename from forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorAbsChangeTest.java rename to persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorAbsChangeTest.java index 50f8ed89..6e246a26 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorAbsChangeTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorAbsChangeTest.java @@ -1,5 +1,7 @@ -package org.devgateway.toolkit.forms.util.tetsim; +package org.devgateway.toolkit.persistence.tetsim; +import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; +import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputUndershiftCalculator; import org.junit.Before; import org.junit.Test; diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java similarity index 97% rename from forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java rename to persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java index b8473c50..933a3d2a 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java @@ -1,5 +1,6 @@ -package org.devgateway.toolkit.forms.util.tetsim; +package org.devgateway.toolkit.persistence.tetsim; +import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; import org.junit.Before; import org.junit.Test; diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java similarity index 95% rename from forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java rename to persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java index a7b76846..2133fc84 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java @@ -1,5 +1,6 @@ -package org.devgateway.toolkit.forms.util.tetsim; +package org.devgateway.toolkit.persistence.tetsim; +import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; import org.junit.Before; import org.junit.Test; diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java similarity index 94% rename from forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java rename to persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java index fc29ae99..5416a561 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java @@ -1,5 +1,6 @@ -package org.devgateway.toolkit.forms.util.tetsim; +package org.devgateway.toolkit.persistence.tetsim; +import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; import org.junit.Before; import org.junit.Test; diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java similarity index 96% rename from forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java rename to persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java index 92b29804..f117f52f 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java @@ -1,6 +1,7 @@ -package org.devgateway.toolkit.forms.util.tetsim; +package org.devgateway.toolkit.persistence.tetsim; import org.devgateway.toolkit.persistence.dto.TetsimOutput; +import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; import org.junit.Before; import org.junit.Test; diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java similarity index 97% rename from forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java rename to persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java index 94b63490..6e83d0fa 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputOvershiftCalculatorTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java @@ -1,6 +1,8 @@ -package org.devgateway.toolkit.forms.util.tetsim; +package org.devgateway.toolkit.persistence.tetsim; import org.devgateway.toolkit.persistence.dto.TetsimOutput; +import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputCalculator; +import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; import org.junit.Before; import org.junit.Test; diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java similarity index 96% rename from forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java rename to persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java index 43726ae9..f4b21728 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java @@ -1,6 +1,7 @@ -package org.devgateway.toolkit.forms.util.tetsim; +package org.devgateway.toolkit.persistence.tetsim; import org.devgateway.toolkit.persistence.dto.TetsimOutput; +import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputUndershiftCalculator; import org.junit.Before; import org.junit.Test; diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimDatasetBuilder.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TetsimDatasetBuilder.java similarity index 98% rename from forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimDatasetBuilder.java rename to persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TetsimDatasetBuilder.java index efb28bb8..c71a83c2 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimDatasetBuilder.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TetsimDatasetBuilder.java @@ -1,4 +1,4 @@ -package org.devgateway.toolkit.forms.util.tetsim.builder; +package org.devgateway.toolkit.persistence.tetsim.builder; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimPriceVariableBuilder.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TetsimPriceVariableBuilder.java similarity index 91% rename from forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimPriceVariableBuilder.java rename to persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TetsimPriceVariableBuilder.java index f9c18775..e58385e1 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimPriceVariableBuilder.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TetsimPriceVariableBuilder.java @@ -1,4 +1,4 @@ -package org.devgateway.toolkit.forms.util.tetsim.builder; +package org.devgateway.toolkit.persistence.tetsim.builder; import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimTobaccoProductValueBuilder.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TetsimTobaccoProductValueBuilder.java similarity index 93% rename from forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimTobaccoProductValueBuilder.java rename to persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TetsimTobaccoProductValueBuilder.java index e41297c9..994abe9f 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TetsimTobaccoProductValueBuilder.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TetsimTobaccoProductValueBuilder.java @@ -1,4 +1,4 @@ -package org.devgateway.toolkit.forms.util.tetsim.builder; +package org.devgateway.toolkit.persistence.tetsim.builder; import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TobaccoProductBuilder.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TobaccoProductBuilder.java similarity index 90% rename from forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TobaccoProductBuilder.java rename to persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TobaccoProductBuilder.java index 51169f03..7032c666 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/util/tetsim/builder/TobaccoProductBuilder.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TobaccoProductBuilder.java @@ -1,4 +1,4 @@ -package org.devgateway.toolkit.forms.util.tetsim.builder; +package org.devgateway.toolkit.persistence.tetsim.builder; import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; diff --git a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TestController.java b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TestController.java index 41c7627a..53d2f333 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TestController.java +++ b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TestController.java @@ -3,8 +3,6 @@ import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.cache.annotation.CacheConfig; -import org.springframework.cache.annotation.Cacheable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @@ -15,8 +13,6 @@ */ @RestController -@CacheConfig(cacheNames = "reportsApiCache") -@Cacheable public class TestController { private static final Logger logger = LoggerFactory.getLogger(TestController.class); diff --git a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java new file mode 100644 index 00000000..cf565e98 --- /dev/null +++ b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java @@ -0,0 +1,37 @@ +package org.devgateway.toolkit.web.rest.controller; + +import io.swagger.annotations.ApiOperation; +import org.devgateway.toolkit.persistence.dto.TetsimOutputs; +import org.devgateway.toolkit.persistence.service.tetsim.TetsimOutputService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author vchihai + */ + +@RestController +public class TetsimController { + + private static final Logger logger = LoggerFactory.getLogger(TetsimController.class); + + private final TetsimOutputService tetsimOutputService; + + public TetsimController(final TetsimOutputService tetsimOutputService) { + this.tetsimOutputService = tetsimOutputService; + } + + @ApiOperation(value = "TETSIM Output API") + @RequestMapping(value = "{dg-toolkit.forms.base-path}/api/tetsim/output", method = RequestMethod.GET, + produces = "application/json") + public TetsimOutputs getTetsimOutput(@RequestParam() final Long id) { + TetsimOutputs outputs = tetsimOutputService.getTetsimOutputs(id); + + return outputs; + } + +} diff --git a/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java b/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java index 849b7056..b7f88982 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java +++ b/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java @@ -37,6 +37,9 @@ import org.springframework.security.web.firewall.HttpFirewall; import org.springframework.security.web.firewall.StrictHttpFirewall; +import java.util.Arrays; +import java.util.stream.Collectors; + /** * @author mpostelnicu This configures the spring security for the Web project. * An @@ -89,12 +92,22 @@ public SecurityContextPersistenceFilter securityContextPersistenceFilter() { @Override public void configure(final WebSecurity web) throws Exception { web.httpFirewall(allowUrlEncodedSlashHttpFirewall()) - .ignoring().antMatchers(allowedApiEndpoints).and() + .ignoring().antMatchers(getAllowedAPIEndpointsWithBasePath()).and() .ignoring().antMatchers( settingsUtils.getFormsBasePath() + "/login", settingsUtils.getFormsBasePath() + "/forgotPassword/**"); } + private String[] getAllowedAPIEndpointsWithBasePath() { + if (allowedApiEndpoints != null) { + return Arrays.stream(allowedApiEndpoints) + .map(s -> settingsUtils.getFormsBasePath() + s) + .collect(Collectors.toList()).toArray(new String[allowedApiEndpoints.length]); + } + + return new String[]{}; + } + @Override protected void configure(final HttpSecurity http) throws Exception { http.authorizeRequests().expressionHandler(webExpressionHandler()) // inject role hierarchy From 8111e026b8b225e0f518e0c995cb46f8f88d23a5 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Tue, 5 Apr 2022 18:21:22 +0300 Subject: [PATCH 064/137] TCDIKE-85: Enable remote ip valve for fixing forwarding --- .../java/org/devgateway/toolkit/forms/application.properties | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/application.properties b/forms/src/main/java/org/devgateway/toolkit/forms/application.properties index 59cd8613..8667675a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/application.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/application.properties @@ -18,3 +18,8 @@ javamelody.spring-monitoring-enabled=true javamelody.init-parameters.log=true javamelody.advisor-auto-proxy-creator-enabled=false spring.aop.proxy-target-class=true + +# The presence of either of those properties switches on the RemoteIpValve. +# This presence of valve will fix issue with reverse proxy +server.tomcat.remote-ip-header=x-forwarded-for +server.tomcat.protocol-header=x-forwarded-proto \ No newline at end of file From 69fa3c67f5cf4ca3ac076c01ae77c5c7487de481 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 30 May 2022 18:12:24 +0300 Subject: [PATCH 065/137] TOBACCO-908: Generate tetsim csv dataset output --- persistence/pom.xml | 6 ++ .../persistence/application-dev.properties | 4 +- .../toolkit/persistence/dto/TetsimOutput.java | 30 +++++-- .../persistence/dto/TetsimOutputs.java | 33 -------- .../service/tetsim/TetsimOutputService.java | 79 +++++++++++++++++-- .../tetsim/TetsimOutputBaseCalculator.java | 52 ++++++------ .../util/tetsim/TetsimOutputCalculator.java | 2 +- .../TetsimOutputOvershiftCalculator.java | 5 ++ .../TetsimOutputUndershiftCalculator.java | 5 ++ ...mOutputOvershiftCalculatorOverallTest.java | 4 +- .../TetsimOutputOvershiftCalculatorTest.java | 44 +++++------ ...OutputUndershiftCalculatorOverallTest.java | 4 +- .../web/rest/controller/TetsimController.java | 28 +++++-- 13 files changed, 194 insertions(+), 102 deletions(-) delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutputs.java diff --git a/persistence/pom.xml b/persistence/pom.xml index fbba99ef..9c275168 100644 --- a/persistence/pom.xml +++ b/persistence/pom.xml @@ -206,6 +206,12 @@ poi-ooxml ${poi.version} + + + com.opencsv + opencsv + 5.6 + diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties index cb51f917..26d0ffb2 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties @@ -11,8 +11,8 @@ ############################################################################### spring.config.activate.on-profile=dev spring.datasource.username=postgres -spring.datasource.password=admin -spring.datasource.jdbc-url=jdbc:postgresql://localhost:5432/tcdi_admin +spring.datasource.password=postgres +spring.datasource.jdbc-url=jdbc:postgresql://localhost:5432/tcdi-admin management.health.mail.enabled=false dg-toolkit.forms.base-path=/admin \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java index a4a567a8..3d9ec7df 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java @@ -9,7 +9,11 @@ */ public class TetsimOutput implements Serializable { - private Integer baseline; + private Integer taxChange; + + private String tobaccoProduct; + + private String shifting; private Double consumptionLegal; @@ -33,12 +37,28 @@ public class TetsimOutput implements Serializable { private Double levy; - public Integer getBaseline() { - return baseline; + public Integer getTaxChange() { + return taxChange; + } + + public void setTaxChange(final Integer taxChange) { + this.taxChange = taxChange; + } + + public String getTobaccoProduct() { + return tobaccoProduct; + } + + public void setTobaccoProduct(final String tobaccoProduct) { + this.tobaccoProduct = tobaccoProduct; + } + + public String getShifting() { + return shifting; } - public void setBaseline(final Integer baseline) { - this.baseline = baseline; + public void setShifting(final String shifting) { + this.shifting = shifting; } public Double getConsumptionLegal() { diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutputs.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutputs.java deleted file mode 100644 index 7babc4b6..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutputs.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.devgateway.toolkit.persistence.dto; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -/** - * - * - * @author vchihai - */ -public class TetsimOutputs implements Serializable { - - private List overshift = new ArrayList<>(); - - private List undershift = new ArrayList<>(); - - public List getOvershift() { - return overshift; - } - - public void setOvershift(final List overshift) { - this.overshift = overshift; - } - - public List getUndershift() { - return undershift; - } - - public void setUndershift(final List undershift) { - this.undershift = undershift; - } -} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java index 52122b1a..d6a414d5 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java @@ -1,30 +1,97 @@ package org.devgateway.toolkit.persistence.service.tetsim; +import com.google.common.collect.ImmutableList; +import com.opencsv.CSVWriter; +import com.opencsv.bean.HeaderColumnNameMappingStrategy; +import com.opencsv.bean.StatefulBeanToCsv; +import com.opencsv.bean.StatefulBeanToCsvBuilder; +import com.opencsv.exceptions.CsvDataTypeMismatchException; +import com.opencsv.exceptions.CsvRequiredFieldEmptyException; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; -import org.devgateway.toolkit.persistence.dto.TetsimOutputs; +import org.devgateway.toolkit.persistence.dto.TetsimOutput; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputUndershiftCalculator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + @Service public class TetsimOutputService { + public static final int MAX_TAX_CHANGE = 100; + + public static final List TOBACCO_PRODUCTS = new ImmutableList.Builder() + .add("Imported", "Premium", "Popular", "Discount", "Illicit") + .build(); + + public static final List TETSIM_CSV_FIELDS = new ImmutableList.Builder() + .add("taxChange", "tobaccoProduct", "shifting", "consumptionLegal", "consumptionIllicit", "exciseRev", + "totalGovRev", "exciseBurden", "totalTaxBurden", "retailPrice", "not", "exciseTax", "vat", "levy") + .build(); @Autowired private TetsimDatasetService tetsimDatasetService; - public TetsimOutputs getTetsimOutputs(Long datasetId) { + /** + * Get the tetsim outputs + * + * @param datasetId + * @return + */ + public List getTetsimOutputs(Long datasetId) { TetsimDataset dataset = tetsimDatasetService.findById(datasetId).get(); - TetsimOutputs outputs = new TetsimOutputs(); + List outputs = new ArrayList<>(); - for (int i = 0; i <= 100; i++) { - outputs.getOvershift().add(new TetsimOutputOvershiftCalculator(dataset, i).calculate()); - outputs.getUndershift().add(new TetsimOutputUndershiftCalculator(dataset, i).calculate()); + for (int i = 0; i <= MAX_TAX_CHANGE; i++) { + for (String t : TOBACCO_PRODUCTS) { + outputs.add(new TetsimOutputOvershiftCalculator(dataset, i).calculate(t)); + outputs.add(new TetsimOutputUndershiftCalculator(dataset, i).calculate(t)); + } } return outputs; } + /** + * Get the tetsim outputs in csv format + * @param datasetId + * @return + * @throws IOException + * @throws CsvRequiredFieldEmptyException + * @throws CsvDataTypeMismatchException + */ + public byte[] getTetsimCSVDatasetOutputs(Long datasetId) throws IOException, CsvRequiredFieldEmptyException, + CsvDataTypeMismatchException { + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + OutputStreamWriter streamWriter = new OutputStreamWriter(stream); + + final List columns = TETSIM_CSV_FIELDS.stream() + .map(String::toUpperCase) + .collect(Collectors.toList()); + + HeaderColumnNameMappingStrategy columnStrategy = new HeaderColumnNameMappingStrategy<>(); + columnStrategy.setType(TetsimOutput.class); + columnStrategy.setColumnOrderOnWrite(Comparator.comparingInt(columns::indexOf)); + + StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(streamWriter) + .withSeparator(CSVWriter.DEFAULT_SEPARATOR) + .withApplyQuotesToAll(false) + .withMappingStrategy(columnStrategy) + .build(); + + sbc.write(getTetsimOutputs(datasetId)); + streamWriter.flush(); + + return stream.toByteArray(); + } + } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java index bf586d18..09a2f856 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java @@ -59,23 +59,29 @@ public TetsimOutputBaseCalculator(TetsimDataset dataset, Integer percentageChang this.levyPercentageChange = levyPercentageChange; } + protected abstract String getShifting(); + protected abstract BigDecimal calculateAbsChangeShift(String tobaccoProduct); @Override - public TetsimOutput calculate() { + public TetsimOutput calculate(String tobaccoProduct) { TetsimOutput tetsimOutput = new TetsimOutput(); + + tetsimOutput.setShifting(getShifting()); + tetsimOutput.setTobaccoProduct(tobaccoProduct); + tetsimOutput.setTaxChange(percentageChange.intValue()); tetsimOutput.setConsumptionLegal(calculateOutputConsumptionLegal()); tetsimOutput.setConsumptionIllicit(calculateOutputConsumptionIllicit()); tetsimOutput.setExciseRev(calculateOutputExciseRev()); tetsimOutput.setTotalGovRev(calculateOutputTotalGovRev()); - tetsimOutput.setExciseBurden(calculateOutputExciseBurden()); - tetsimOutput.setTotalTaxBurden(calculateOutputTotalTaxBurden()); - tetsimOutput.setRetailPrice(calculateOutputRetailPrice()); - tetsimOutput.setNot(calculateOutputNot()); - tetsimOutput.setExciseTax(calculateOutputExciseTax()); - tetsimOutput.setVat(calculateOutputVat()); - tetsimOutput.setLevy(calculateOutputLevy()); - tetsimOutput.setBaseline(percentageChange.intValue()); + + tetsimOutput.setExciseBurden(calculateOutputExciseBurden(tobaccoProduct)); + tetsimOutput.setTotalTaxBurden(calculateOutputTotalTaxBurden(tobaccoProduct)); + tetsimOutput.setRetailPrice(calculateOutputRetailPrice(tobaccoProduct)); + tetsimOutput.setNot(calculateOutputNot(tobaccoProduct)); + tetsimOutput.setExciseTax(calculateOutputExciseTax(tobaccoProduct)); + tetsimOutput.setVat(calculateOutputVat(tobaccoProduct)); + tetsimOutput.setLevy(calculateOutputLevy(tobaccoProduct)); return tetsimOutput; } @@ -99,50 +105,50 @@ private Double calculateOutputTotalGovRev() { /** * Calculate the Output Excise Burden */ - private Double calculateOutputExciseBurden() { - return calculateExciseBurden("Popular").doubleValue(); + private Double calculateOutputExciseBurden(String tobaccoProduct) { + return calculateExciseBurden(tobaccoProduct).doubleValue(); } /** * Calculate the Output Total Tax Burden */ - private Double calculateOutputTotalTaxBurden() { - return calculateTotalTaxBurden("Popular").doubleValue(); + private Double calculateOutputTotalTaxBurden(String tobaccoProduct) { + return calculateTotalTaxBurden(tobaccoProduct).doubleValue(); } /** * Calculate the Output Retail Price */ - public Double calculateOutputRetailPrice() { - return calculateRetailPrice("Popular").doubleValue(); + public Double calculateOutputRetailPrice(String tobaccoProduct) { + return calculateRetailPrice(tobaccoProduct).doubleValue(); } /** * Calculate the Output NOT */ - public Double calculateOutputNot() { - return calculateNetTaxPrice("Popular").doubleValue(); + public Double calculateOutputNot(String tobaccoProduct) { + return calculateNetTaxPrice(tobaccoProduct).doubleValue(); } /** * Calculate the Output Excise Tax */ - public Double calculateOutputExciseTax() { - return calculateExciseTaxDomesticProduction("Popular").doubleValue(); + public Double calculateOutputExciseTax(String tobaccoProduct) { + return calculateExciseTaxDomesticProduction(tobaccoProduct).doubleValue(); } /** * Calculate the Output VAT */ - public Double calculateOutputVat() { - return calculateVat("Popular").doubleValue(); + public Double calculateOutputVat(String tobaccoProduct) { + return calculateVat(tobaccoProduct).doubleValue(); } /** * Calculate the Output Levy */ - public Double calculateOutputLevy() { - return calculateTobaccoLevy("Popular").doubleValue(); + public Double calculateOutputLevy(String tobaccoProduct) { + return calculateTobaccoLevy(tobaccoProduct).doubleValue(); } /** diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputCalculator.java index 13fd0daf..6489176b 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputCalculator.java @@ -4,6 +4,6 @@ public interface TetsimOutputCalculator { - TetsimOutput calculate(); + TetsimOutput calculate(String tobaccoProduct); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputOvershiftCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputOvershiftCalculator.java index d6136c31..0552834c 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputOvershiftCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputOvershiftCalculator.java @@ -15,6 +15,11 @@ public TetsimOutputOvershiftCalculator(TetsimDataset dataset, Integer percentage super(dataset, percentageChange); } + @Override + protected String getShifting() { + return "Overshift"; + } + @Override public BigDecimal calculateAbsChangeShift(final String tobaccoProduct) { BigDecimal exciseTax = getTobaccoProductValueFromVariable(dataset.getExciseTax(), tobaccoProduct); diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputUndershiftCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputUndershiftCalculator.java index 2e120457..8ecef8ec 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputUndershiftCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputUndershiftCalculator.java @@ -15,6 +15,11 @@ public TetsimOutputUndershiftCalculator(TetsimDataset dataset, Integer percentag super(dataset, percentageChange); } + @Override + protected String getShifting() { + return "Undershift"; + } + @Override public BigDecimal calculateAbsChangeShift(final String tobaccoProduct) { BigDecimal exciseTax = getTobaccoProductValueFromVariable(dataset.getExciseTax(), tobaccoProduct); diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java index f117f52f..e09e92c1 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java @@ -18,7 +18,7 @@ public void setUp() { @Test public void testOverallOutputBaseline() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertAll("TETSIM Overshift Baseline", () -> assertEquals(754.40, output.getConsumptionLegal(), delta, "TETSIM Overshift - Consumption Legal"), @@ -37,7 +37,7 @@ public void testOverallOutputBaseline() { @Test public void testOverallOutputWithTaxChange() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 30); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertAll("TETSIM Overshift With 30% Tax Change", () -> assertEquals(648.79, output.getConsumptionLegal(), delta, "TETSIM Overshift - Consumption Legal"), diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java index 6e83d0fa..506b589d 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java @@ -18,154 +18,154 @@ public void setUp() { @Test public void testConsumptionLegalNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(754.4, output.getConsumptionLegal(), delta, "Check Consumption Legal TETSIM Output Overshift"); } @Test public void testConsumptionLegalWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(680.19, output.getConsumptionLegal(), delta, "Check Consumption Legal TETSIM Output Overshift (Tax Change)"); } @Test public void testConsumptionIllicitNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(395.6, output.getConsumptionIllicit(), delta, "Check Consumption Illicit TETSIM Output Overshift"); } @Test public void testConsumptionIllicitWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(387.62, output.getConsumptionIllicit(), delta, "Check Consumption Illicit TETSIM Output Overshift (Tax Change)"); } @Test public void testTotalExciseRevenueNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(14167.63, output.getExciseRev(), delta, "Check Total Legal Excise Revenue TETSIM Output Overshift"); } @Test public void testTotalExciseRevenueWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(15328.9, output.getExciseRev(), delta, "Check Total Legal Excise Revenue TETSIM Output Overshift (Tax Change)"); } @Test public void testTotalLegalGovRevenueNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(18051.37, output.getTotalGovRev(), delta, "Check Total Legal Government Revenue TETSIM Output Overshift"); } @Test public void testTotalLegalGovRevenueWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(19315.54, output.getTotalGovRev(), delta, "Check Total Legal Government Revenue TETSIM Output Overshift (Tax Change)"); } @Test public void testExciseBurdenNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(46.95, output.getExciseBurden(), delta, "Check Excise Burden TETSIM Output Overshift"); } @Test public void testExciseBurdenWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(49.87, output.getExciseBurden(), delta, "Check Excise Burden TETSIM Output Overshift (Tax Change)"); } @Test public void testTotalTaxBurdenNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(60.0, output.getTotalTaxBurden(), delta, "Check Total Tax Burden TETSIM Output Overshift"); } @Test public void testTotalTaxBurdenWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(62.92, output.getTotalTaxBurden(), delta, "Check Total Tax Burden TETSIM Output Overshift (Tax Change)"); } @Test public void testRetailPriceNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(40.0, output.getRetailPrice(), delta, "Check Retail Price TETSIM Output Overshift (Baseline)"); } @Test public void testRetailPriceWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(45.18, output.getRetailPrice(), delta, "Check Retail Price TETSIM Output Overshift (Tax Change)"); } @Test public void testNOTNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(16.0, output.getNot(), delta, "Check NOT TETSIM Output Overshift"); } @Test public void testNOTWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(16.75, output.getNot(), delta, "Check NOT TETSIM Output Overshift (Tax Change)"); } @Test public void testExciseTaxNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(18.78, output.getExciseTax(), delta, "Check Excise Tax TETSIM Output Overshift"); } @Test public void testExciseTaxWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(22.54, output.getExciseTax(), delta, "Check Excise Tax TETSIM Output Overshift (Tax Change)"); } @Test public void testVatNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(5.22, output.getVat(), delta, "Check VAT TETSIM Output Overshift"); } @Test public void testVatWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(5.89, output.getVat(), delta, "Check VAT TETSIM Output Overshift (Tax Change)"); } @Test public void testLevyNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(0.00, output.getLevy(), delta, "Check Levy TETSIM Output Overshift"); } @Test public void testLevyWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertEquals(0.00, output.getLevy(), delta, "Check Levy TETSIM Output Overshift (Tax Change)"); } diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java index f4b21728..55debe6e 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java @@ -18,7 +18,7 @@ public void setUp() { @Test public void testOverallOutputBaseline() { TetsimOutputUndershiftCalculator tetsimOutputCalculator = new TetsimOutputUndershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertAll("TETSIM Undershift Baseline", () -> assertEquals(754.40, output.getConsumptionLegal(), delta, "TETSIM Undershift - Consumption Legal"), @@ -37,7 +37,7 @@ public void testOverallOutputBaseline() { @Test public void testOverallOutputWithTaxChange() { TetsimOutputUndershiftCalculator tetsimOutputCalculator = new TetsimOutputUndershiftCalculator(datasetWithAllTobaccoProducts, 30); - TetsimOutput output = tetsimOutputCalculator.calculate(); + TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertAll("TETSIM Undershift With 30% Tax Change", () -> assertEquals(694.62, output.getConsumptionLegal(), delta, "TETSIM Undershift - Consumption Legal"), diff --git a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java index cf565e98..657b85e8 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java +++ b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java @@ -1,20 +1,27 @@ package org.devgateway.toolkit.web.rest.controller; +import com.opencsv.exceptions.CsvDataTypeMismatchException; +import com.opencsv.exceptions.CsvRequiredFieldEmptyException; import io.swagger.annotations.ApiOperation; -import org.devgateway.toolkit.persistence.dto.TetsimOutputs; +import org.devgateway.toolkit.persistence.dto.TetsimOutput; import org.devgateway.toolkit.persistence.service.tetsim.TetsimOutputService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.List; + /** * @author vchihai */ @RestController +@RequestMapping("{dg-toolkit.forms.base-path}/api/tetsim") public class TetsimController { private static final Logger logger = LoggerFactory.getLogger(TetsimController.class); @@ -26,12 +33,21 @@ public TetsimController(final TetsimOutputService tetsimOutputService) { } @ApiOperation(value = "TETSIM Output API") - @RequestMapping(value = "{dg-toolkit.forms.base-path}/api/tetsim/output", method = RequestMethod.GET, - produces = "application/json") - public TetsimOutputs getTetsimOutput(@RequestParam() final Long id) { - TetsimOutputs outputs = tetsimOutputService.getTetsimOutputs(id); + @GetMapping(value = "/output", produces = "application/json") + public List getTetsimOutput(@RequestParam() final Long id) { + List outputs = tetsimOutputService.getTetsimOutputs(id); return outputs; } + @ApiOperation(value = "Download TETSIM dataset in csv format") + @GetMapping(value = "/output/csv", produces = "text/csv") + public void exportTetsimOutput(HttpServletResponse response, @RequestParam() final Long id) + throws CsvRequiredFieldEmptyException, CsvDataTypeMismatchException, IOException { + + response.setContentType("text/csv"); + response.setHeader("Content-Disposition", "attachment; filename=\"dataset.csv\""); + response.getOutputStream().write(tetsimOutputService.getTetsimCSVDatasetOutputs(id)); + } + } From c23cf2402f673543e83ffca40fdad481c850f728 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 4 Jul 2022 16:11:42 +0300 Subject: [PATCH 066/137] TOBACCO-915: Add service management --- .../toolkit/forms/wicket/page/BasePage.java | 5 ++ .../forms/wicket/page/BasePage.properties | 1 + .../page/edit/admin/EditServicePage.html | 16 ++++++ .../page/edit/admin/EditServicePage.java | 32 ++++++++++++ .../edit/admin/EditServicePage.properties | 5 ++ .../page/lists/admin/ListServicePage.java | 52 +++++++++++++++++++ .../lists/admin/ListServicePage.properties | 1 + .../persistence/dao/ServiceMetadata.java | 30 +++++++++++ .../repository/ServiceMetadataRepository.java | 12 +++++ .../service/ServiceMetadataService.java | 8 +++ .../service/ServiceMetadataServiceImpl.java | 30 +++++++++++ pom.xml | 2 +- 12 files changed, 193 insertions(+), 1 deletion(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.properties create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dao/ServiceMetadata.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/repository/ServiceMetadataRepository.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataService.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataServiceImpl.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index c9e0f4d6..9f6f3257 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -52,6 +52,7 @@ import org.devgateway.toolkit.forms.wicket.page.lists.ListGroupPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListTestFormPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListUserPage; +import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServicePage; import org.devgateway.toolkit.forms.wicket.page.user.EditUserPage; import org.devgateway.toolkit.forms.wicket.page.user.LogoutPage; import org.devgateway.toolkit.forms.wicket.styles.BaseStyles; @@ -258,6 +259,10 @@ protected List newSubMenuButtons(final String arg0) { new StringResourceModel("navbar.groups", this, null)) .setIconType(FontAwesome5IconType.tags_s)); + list.add(new MenuBookmarkablePageLink(ListServicePage.class, null, + new StringResourceModel("navbar.services", this, null)) + .setIconType(FontAwesome5IconType.servicestack)); + // list.add(new MenuBookmarkablePageLink(ListTestFormPage.class, null, // new StringResourceModel("navbar.testcomponents", this, null)) // .setIconType(FontAwesome5IconType.android)); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties index a0fe0e79..6916443c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties @@ -13,6 +13,7 @@ navbar.home=Home navbar.logout=Logout navbar.users=Users navbar.groups=Groups +navbar.services=Services navbar.admin=Admin navbar.datasets=Datasets navbar.tetsim=TETSIM diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.html new file mode 100644 index 00000000..2a7b9e1c --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.html @@ -0,0 +1,16 @@ + + + + + Edit Service + + + +

+
+
+
+
+
+ + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.java new file mode 100644 index 00000000..6e993048 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.java @@ -0,0 +1,32 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.admin; + +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; +import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServicePage; +import org.devgateway.toolkit.persistence.dao.ServiceMetadata; +import org.devgateway.toolkit.persistence.service.ServiceMetadataService; + +public class EditServicePage extends AbstractEditPage { + + @SpringBean + protected ServiceMetadataService serviceMetadataService; + + public EditServicePage(final PageParameters parameters) { + super(parameters); + this.jpaService = serviceMetadataService; + this.listPageClass = ListServicePage.class; + + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + editForm.add(new TextFieldBootstrapFormComponent<>("name").required()); + editForm.add(new TextFieldBootstrapFormComponent<>("description")); + editForm.add(new TextFieldBootstrapFormComponent<>("url")); + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.properties new file mode 100644 index 00000000..5ffb9d1a --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.properties @@ -0,0 +1,5 @@ +page.title.add=Add Service +page.title.edit=Edit Service +name.label=Name +description.label=Description +url.label=URL \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java new file mode 100644 index 00000000..f88935c2 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (c) 2015 Development Gateway, Inc and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the MIT License (MIT) + * which accompanies this distribution, and is available at + * https://opensource.org/licenses/MIT + * + * Contributors: + * Development Gateway - initial API and implementation + *******************************************************************************/ +package org.devgateway.toolkit.forms.wicket.page.lists.admin; + +import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServicePage; +import org.devgateway.toolkit.forms.wicket.page.lists.AbstractListPage; +import org.devgateway.toolkit.persistence.dao.ServiceMetadata; +import org.devgateway.toolkit.persistence.service.ServiceMetadataService; +import org.wicketstuff.annotation.mount.MountPath; + +@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) +@MountPath(value = "/listservices") +public class ListServicePage extends AbstractListPage { + + private static final long serialVersionUID = -6132847935476573446L; + + @SpringBean + private ServiceMetadataService serviceMetadataService; + + public ListServicePage(final PageParameters pageParameters) { + super(pageParameters); + + this.jpaService = serviceMetadataService; + + this.editPageClass = EditServicePage.class; + columns.add(new PropertyColumn<>(new Model<>("Name"), "name", "name")); + columns.add(new PropertyColumn<>(new Model<>("Description"), "description", "description")); + columns.add(new PropertyColumn<>(new Model<>("URL"), "url", "url")); + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + excelForm.setVisibilityAllowed(false); + } +} \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.properties new file mode 100644 index 00000000..146720a7 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.properties @@ -0,0 +1 @@ +page.title=Service List \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/ServiceMetadata.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/ServiceMetadata.java new file mode 100644 index 00000000..682ea242 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/ServiceMetadata.java @@ -0,0 +1,30 @@ +package org.devgateway.toolkit.persistence.dao; + +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; +import org.hibernate.envers.Audited; + +import javax.persistence.Entity; +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) +@Entity +@Audited +public class ServiceMetadata extends AbstractStatusAuditableEntity implements Serializable { + + @NotNull + @Audited + private String name; + + @Audited + private String description; + + @Audited + private String url; + + @Override + public AbstractAuditableEntity getParent() { + return null; + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/ServiceMetadataRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/ServiceMetadataRepository.java new file mode 100644 index 00000000..378f1a9b --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/ServiceMetadataRepository.java @@ -0,0 +1,12 @@ +package org.devgateway.toolkit.persistence.repository; + +import org.devgateway.toolkit.persistence.dao.ServiceMetadata; +import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public interface ServiceMetadataRepository extends BaseJpaRepository { + + ServiceMetadata findByName(String name); + +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataService.java new file mode 100644 index 00000000..1e7cd1d2 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataService.java @@ -0,0 +1,8 @@ +package org.devgateway.toolkit.persistence.service; + +import org.devgateway.toolkit.persistence.dao.ServiceMetadata; + +public interface ServiceMetadataService extends BaseJpaService { + + ServiceMetadata findByName(String name); +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataServiceImpl.java new file mode 100644 index 00000000..71250137 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataServiceImpl.java @@ -0,0 +1,30 @@ +package org.devgateway.toolkit.persistence.service; + +import org.devgateway.toolkit.persistence.dao.ServiceMetadata; +import org.devgateway.toolkit.persistence.repository.ServiceMetadataRepository; +import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional(readOnly = true) +public class ServiceMetadataServiceImpl extends BaseJpaServiceImpl implements ServiceMetadataService { + @Autowired + private ServiceMetadataRepository serviceMetadataRepository; + + @Override + public ServiceMetadata findByName(final String name) { + return serviceMetadataRepository.findByName(name); + } + + @Override + protected BaseJpaRepository repository() { + return serviceMetadataRepository; + } + + @Override + public ServiceMetadata newInstance() { + return new ServiceMetadata(); + } +} diff --git a/pom.xml b/pom.xml index 4a5dff4d..57c94fc7 100644 --- a/pom.xml +++ b/pom.xml @@ -80,7 +80,7 @@ jcenter-snapshots jcenter - http://oss.jfrog.org/artifactory/oss-snapshot-local/ + https://oss.jfrog.org/artifactory/oss-snapshot-local/ devgateway-open-source From 55b0d87b76a262c1f16847305b3874a8220c389f Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 4 Jul 2022 16:12:43 +0300 Subject: [PATCH 067/137] TOBACCO-921: Add client to send request to microservices --- forms/pom.xml | 23 +++++++ .../forms/client/DataSetClientException.java | 7 +++ .../toolkit/forms/client/DatasetClient.java | 62 +++++++++++++++++++ .../forms/client/DatasetJobStatus.java | 5 ++ .../forms/client/ServiceHealthStatus.java | 18 ++++++ .../edit/AbstractEditStatusEntityPage.java | 7 ++- .../toolkit/persistence/dao/DBConstants.java | 5 +- .../repository/data/DatasetRepository.java | 7 +++ .../service/data/TetsimDatasetService.java | 2 + .../data/TetsimDatasetServiceImpl.java | 5 ++ 10 files changed, 137 insertions(+), 4 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/client/DataSetClientException.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetJobStatus.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceHealthStatus.java diff --git a/forms/pom.xml b/forms/pom.xml index e919bf10..f2c121ca 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -40,6 +40,7 @@ 2.4.8 1.86.0 5.15.3 + 2.36 @@ -259,6 +260,28 @@ 2.0.0 pom + + + org.glassfish.jersey.core + jersey-client + ${jersey.version} + + + + org.glassfish.jersey.core + jersey-common + ${jersey.version} + + + org.glassfish.jersey.inject + jersey-hk2 + ${jersey.version} + + + org.glassfish.jersey.media + jersey-media-json-jackson + ${jersey.version} + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DataSetClientException.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DataSetClientException.java new file mode 100644 index 00000000..8fb4642d --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DataSetClientException.java @@ -0,0 +1,7 @@ +package org.devgateway.toolkit.forms.client; + +public class DataSetClientException extends Throwable { + public DataSetClientException(final String message) { + super(message); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java new file mode 100644 index 00000000..cb700e23 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java @@ -0,0 +1,62 @@ +package org.devgateway.toolkit.forms.client; + +import org.glassfish.jersey.client.JerseyClient; +import org.glassfish.jersey.client.JerseyClientBuilder; + +import javax.ws.rs.core.Response; + +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL; + + +public class DatasetClient { + + private final JerseyClient client; + + private final String baseUrl; + + private final static String PATH_HEALTH = "actuator/health"; + + private final static String PATH_JOBS = "admin/jobs/"; + + public DatasetClient(final String baseUrl) { + this.baseUrl = baseUrl; + this.client = JerseyClientBuilder.createClient(); + } + + public DatasetJobStatus getDatasetStatus(String jobId) throws DataSetClientException { + if (isUp()) { + Response jobStatusResponse = client.target(baseUrl) + .path(PATH_JOBS) + .path(jobId) + .request(APPLICATION_JSON) + .get(); + + if (jobStatusResponse.getStatusInfo().getFamily() == SUCCESSFUL) { + return jobStatusResponse.readEntity(DatasetJobStatus.class); + } + + throw new DataSetClientException(jobStatusResponse.toString()); + } + + throw new RuntimeException(("Service is not up")); + } + + public boolean isUp() { + Response healthResponse = client.target(baseUrl).path(PATH_HEALTH) + .request(APPLICATION_JSON).get(); + + if (healthResponse.getStatusInfo().getFamily() == SUCCESSFUL) { + return healthResponse.readEntity(ServiceHealthStatus.class).isUp(); + } + + return false; + } + +// List> response = client.resource(uri) +// .type(MediaType.APPLICATION_JSON_TYPE) +// .accept(MediaType.APPLICATION_JSON_TYPE) +// .post(new GenericType>>() { }, jsonActivities); +// +// List queueIds = new ArrayList<>(); +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetJobStatus.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetJobStatus.java new file mode 100644 index 00000000..fe24755f --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetJobStatus.java @@ -0,0 +1,5 @@ +package org.devgateway.toolkit.forms.client; + +public class DatasetJobStatus { + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceHealthStatus.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceHealthStatus.java new file mode 100644 index 00000000..f240a5ca --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceHealthStatus.java @@ -0,0 +1,18 @@ +package org.devgateway.toolkit.forms.client; + +public class ServiceHealthStatus { + + private String status; + + public String getStatus() { + return status; + } + + public void setStatus(final String status) { + this.status = status; + } + + public boolean isUp() { + return "UP".equalsIgnoreCase(status); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index 96af593f..af0d01d0 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -64,6 +64,7 @@ import static org.devgateway.toolkit.forms.WebConstants.PARAM_AUTO_SAVE; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DRAFT; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.SAVED; /** @@ -173,7 +174,7 @@ protected String getOnClickScript() { @Override protected void onSubmit(final AjaxRequestTarget target) { - setStatusAppendComment(PUBLISHED); + setStatusAppendComment(PUBLISHING); super.onSubmit(target); } }; @@ -477,6 +478,8 @@ private String getStatusLabelClass() { case DRAFT: return "label-danger"; case SAVED: + return "label-primary"; + case PUBLISHING: return "label-warning"; default: return ""; @@ -683,7 +686,7 @@ protected String getOnClickScript() { @Override protected void onSubmit(final AjaxRequestTarget target) { - setStatusAppendComment(PUBLISHED); + setStatusAppendComment(PUBLISHING); super.onSubmit(target); } }; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java index 93b28c05..ec73a100 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java @@ -24,10 +24,11 @@ private DBConstants() { public static final class Status { public static final String DRAFT = "DRAFT"; public static final String SAVED = "SAVED"; + public static final String PUBLISHING = "PUBLISHING"; public static final String PUBLISHED = "PUBLISHED"; + public static final String NOT_PUBLISHED = "NOT_PUBLISHED"; public static final String DELETED = "DELETED"; - - public static final String[] ALL = {DRAFT, SAVED, PUBLISHED}; + public static final String[] ALL = {DRAFT, SAVED, PUBLISHING, PUBLISHED, NOT_PUBLISHED}; public static final List ALL_LIST = Collections.unmodifiableList(Arrays.asList(ALL)); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java index 477c9118..00151771 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java @@ -1,10 +1,17 @@ package org.devgateway.toolkit.persistence.repository.data; import org.devgateway.toolkit.persistence.dao.data.Dataset; +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; +import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.NoRepositoryBean; +import java.util.List; + @NoRepositoryBean public interface DatasetRepository extends BaseJpaRepository { + @Query("select td from TetsimDataset td where td.status like 'PUBLISHING'") + List findAllPublishing(); + } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java index c9c912ca..dbfb1f66 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java @@ -10,5 +10,7 @@ public interface TetsimDatasetService extends BaseJpaService, Uni List findAllDeleted(); + List findAllPublishing(); + long countByNonPublished(Integer year); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java index ad37141d..a334e7de 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java @@ -40,6 +40,11 @@ public List findAllDeleted() { return tetsimDatasetRepository.findAllDeleted(); } + @Override + public List findAllPublishing() { + return null; + } + @Override public long countByNonPublished(final Integer year) { return tetsimDatasetRepository.countByNonPublished(year); From f4122f50614a8d7a8001e7f162cbb315dc121e40 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Tue, 5 Jul 2022 16:02:43 +0300 Subject: [PATCH 068/137] TOBACCO-945: Add service dropdown in tetsim form --- .../edit/AbstractEditStatusEntityPage.java | 6 ++-- .../edit/dataset/EditTetsimDatasetPage.html | 4 +++ .../edit/dataset/EditTetsimDatasetPage.java | 17 +++++++++++ .../dataset/EditTetsimDatasetPage.properties | 1 + .../persistence/dao/ServiceMetadata.java | 29 +++++++++++++++++++ .../toolkit/persistence/dao/data/Dataset.java | 13 +++++++++ 6 files changed, 68 insertions(+), 2 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index af0d01d0..e8c042bc 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -779,7 +779,8 @@ protected void setButtonsPermissions() { protected void addDeleteButtonPermissions(final Component button) { MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, SecurityConstants.Roles.ROLE_ADMIN); button.setVisibilityAllowed(entityId != null && !isViewMode() - && !PUBLISHED.equals(editForm.getModelObject().getStatus())); + && (!PUBLISHING.equals(editForm.getModelObject().getStatus()) + || !PUBLISHED.equals(editForm.getModelObject().getStatus()))); MetaDataRoleAuthorizationStrategy.authorize( button, Component.RENDER, getCommaCombinedRoles()); } @@ -789,7 +790,8 @@ protected void addSaveRevertButtonPermissions(final Component button) { MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, getValidatorRole()); MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, getCommaCombinedRoles()); button.setVisibilityAllowed(button.isVisibilityAllowed() - && PUBLISHED.equals(editForm.getModelObject().getStatus())); + && (PUBLISHING.equals(editForm.getModelObject().getStatus()) + || PUBLISHED.equals(editForm.getModelObject().getStatus()))); } protected void addSaveApproveButtonPermissions(final Component button) { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html index 20227b90..bc586537 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html @@ -27,6 +27,10 @@

Industry responses to the change in taxation:

diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java index 723322d1..68d36bc4 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java @@ -121,6 +121,8 @@ private T newInstance() { protected TextContentModal saveFailedModal; + protected TextContentModal approveFailedModal; + @SpringBean protected EntityManager entityManager; @@ -243,6 +245,30 @@ protected void onEvent(final AjaxRequestTarget target) { return modal; } + protected TextContentModal createApproveFailedModal() { + final TextContentModal modal = new TextContentModal("approveFailedModal", + new ResourceModel("optimistic_lock_error_message")); + modal.header(new ResourceModel("error")); + final LaddaAjaxButton okButton = new LaddaAjaxButton("button", Buttons.Type.Info) { + @Override + protected void onSubmit(final AjaxRequestTarget target) { + setResponsePage(listPageClass); + } + }; + okButton.setDefaultFormProcessing(false); + okButton.setLabel(Model.of("OK")); + modal.addButton(okButton); + + modal.add(new AjaxEventBehavior("hidden.bs.modal") { + @Override + protected void onEvent(final AjaxRequestTarget target) { + setResponsePage(listPageClass); + } + }); + + return modal; + } + protected void afterSaveEntity(final T saveable) { } @@ -288,6 +314,9 @@ public EditForm(final String id) { saveFailedModal = createSaveFailedModal(); add(saveFailedModal); + approveFailedModal = createApproveFailedModal(); + add(approveFailedModal); + // don't display the delete button if we just create a new entity if (entityId == null) { deleteButton.setVisibilityAllowed(false); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index e8c042bc..cb7e15e6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -174,7 +174,7 @@ protected String getOnClickScript() { @Override protected void onSubmit(final AjaxRequestTarget target) { - setStatusAppendComment(PUBLISHING); + onApprove(target); super.onSubmit(target); } }; @@ -686,8 +686,14 @@ protected String getOnClickScript() { @Override protected void onSubmit(final AjaxRequestTarget target) { - setStatusAppendComment(PUBLISHING); - super.onSubmit(target); + approveModal.show(true); + target.add(approveModal); + } + + @Override + protected void onError(final AjaxRequestTarget target) { + super.onError(target); + target.add(feedbackPanel); } }; saveEditPageButton.setIconType(FontAwesome5IconType.thumbs_up_s); @@ -739,6 +745,10 @@ protected void onAfterRevertToDraft(AjaxRequestTarget target) { } + protected void onApprove(AjaxRequestTarget target) { + + } + protected void setStatusAppendComment(final String status) { final T saveable = editForm.getModelObject(); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html index bc586537..00aeef1e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html @@ -28,7 +28,7 @@

Industry responses to the change in taxation:

-
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index 5113a79f..37c2f08e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -7,13 +7,15 @@ import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.form.validation.AbstractFormValidator; import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.client.DataSetClientException; +import org.devgateway.toolkit.forms.service.DatasetPublishingService; import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditStatusEntityPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; @@ -24,6 +26,8 @@ import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.devgateway.toolkit.web.util.SettingsUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.wicketstuff.annotation.mount.MountPath; @@ -33,6 +37,8 @@ import static org.devgateway.toolkit.forms.WebConstants.MAXIMUM_PERCENTAGE; import static org.devgateway.toolkit.forms.WebConstants.PARAM_YEAR; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.SAVED; /** * @author vchihai @@ -42,11 +48,11 @@ public class EditTetsimDatasetPage extends AbstractEditStatusEntityPage year; + private static final Logger logger = LoggerFactory.getLogger(EditTetsimDatasetPage.class); - protected Select2ChoiceBootstrapFormComponent service; + protected Select2ChoiceBootstrapFormComponent year; - private Model serviceModel = Model.of(""); + protected Select2ChoiceBootstrapFormComponent destinationService; @SpringBean protected TetsimDatasetService tetsimDatasetService; @@ -54,6 +60,9 @@ public class EditTetsimDatasetPage extends AbstractEditStatusEntityPage getYear() { } private Select2ChoiceBootstrapFormComponent getService() { - service = new Select2ChoiceBootstrapFormComponent("service", + destinationService = new Select2ChoiceBootstrapFormComponent("destinationService", new GenericChoiceProvider<>(eurekaClientService.findAllWithData().stream() .map(ServiceMetadata::getName) - .collect(Collectors.toList())), serviceModel) { + .collect(Collectors.toList()))) { @Override protected void onUpdate(final AjaxRequestTarget target) { super.onUpdate(target); - if (serviceModel.getObject() != null) { + if (editForm.getModelObject().getDestinationService() != null) { saveApproveButton.setEnabled(true); approveButton.setEnabled(true); } else { @@ -115,10 +124,9 @@ protected void onUpdate(final AjaxRequestTarget target) { }; - service.setEnabled(true); - editForm.add(service); + destinationService.setEnabled(true); - return service; + return destinationService; } @Override @@ -145,6 +153,22 @@ protected void onDelete(final AjaxRequestTarget target) { setResponsePage(listPageClass); } + protected void onApprove(final AjaxRequestTarget target) { + try { + TetsimDataset dataset = editForm.getModelObject(); + String destinationService = dataset.getDestinationService(); + ServiceMetadata serviceMetadata = eurekaClientService.getServiceByName(destinationService); + + datasetPublishingService.publish(serviceMetadata, dataset); + + dataset.setStatus(PUBLISHING); + } catch (DataSetClientException | Exception e) { + logger.error(e.getMessage(), e); + approveFailedModal.show(target); + } + setResponsePage(listPageClass); + } + protected BootstrapCancelButton getCancelButton(final String id) { return new CancelEditPageButton(id, new StringResourceModel("cancelButton", this, null)); } @@ -208,6 +232,15 @@ private boolean tobaccoProductsNotDefined() { return tobaccoProductService.count() == 0; } + @Override + protected void onBeforeRender() { + super.onBeforeRender(); + + if (SAVED.equals(editForm.getModelObject().getStatus())) { + destinationService.setEnabled(true); + } + } + @Override protected void enableDisableAutosaveFields(final AjaxRequestTarget target) { super.enableDisableAutosaveFields(target); @@ -222,7 +255,7 @@ protected void enableDisableAutosaveFields(final AjaxRequestTarget target) { revertToDraftPageButton.setEnabled(false); } - if (StringUtils.isBlank(serviceModel.getObject())) { + if (StringUtils.isBlank(editForm.getModelObject().getDestinationService())) { saveApproveButton.setEnabled(false); approveButton.setEnabled(false); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties index 6fc82052..9b5bf214 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties @@ -1,6 +1,6 @@ page.title.add=Add TETSIM Dataset page.title.edit=Edit TETSIM Dataset year.label=Year -service.label=Service +destinationService.label=Destination Service error.form.validation.marketShare.percentage=The total of all the market share values should add up to 100 \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java index 5b967868..ecdad99e 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java @@ -15,6 +15,9 @@ public abstract class Dataset extends AbstractStatusAuditableEntity implements S @Audited private Integer year; + @Audited + private String destinationService; + @Override public AbstractAuditableEntity getParent() { return null; @@ -28,4 +31,11 @@ public void setYear(final Integer year) { this.year = year; } + public String getDestinationService() { + return destinationService; + } + + public void setDestinationService(final String destinationService) { + this.destinationService = destinationService; + } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java index 3d9ec7df..98e121e2 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java @@ -9,6 +9,8 @@ */ public class TetsimOutput implements Serializable { + private Integer year; + private Integer taxChange; private String tobaccoProduct; @@ -37,6 +39,14 @@ public class TetsimOutput implements Serializable { private Double levy; + public Integer getYear() { + return year; + } + + public void setYear(final Integer year) { + this.year = year; + } + public Integer getTaxChange() { return taxChange; } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java index d6a414d5..3454b396 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java @@ -33,7 +33,7 @@ public class TetsimOutputService { .build(); public static final List TETSIM_CSV_FIELDS = new ImmutableList.Builder() - .add("taxChange", "tobaccoProduct", "shifting", "consumptionLegal", "consumptionIllicit", "exciseRev", + .add("year", "taxChange", "tobaccoProduct", "shifting", "consumptionLegal", "consumptionIllicit", "exciseRev", "totalGovRev", "exciseBurden", "totalTaxBurden", "retailPrice", "not", "exciseTax", "vat", "levy") .build(); @Autowired diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java index 09a2f856..89fe5fd6 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java @@ -67,6 +67,7 @@ public TetsimOutputBaseCalculator(TetsimDataset dataset, Integer percentageChang public TetsimOutput calculate(String tobaccoProduct) { TetsimOutput tetsimOutput = new TetsimOutput(); + tetsimOutput.setYear(this.dataset.getYear()); tetsimOutput.setShifting(getShifting()); tetsimOutput.setTobaccoProduct(tobaccoProduct); tetsimOutput.setTaxChange(percentageChange.intValue()); From d005fa6463a3d98e2d1acfe88cdbf2e408b9b4c6 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 14 Jul 2022 14:47:41 +0300 Subject: [PATCH 072/137] TOBACCO-947: Update externalId with code. --- .../toolkit/forms/client/ClientConstants.java | 4 ++-- .../toolkit/forms/client/DatasetClient.java | 13 ++++++------- .../toolkit/forms/client/DatasetJobStatus.java | 12 ++++++------ .../forms/service/DatasetPublishingService.java | 4 ++-- 4 files changed, 16 insertions(+), 17 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java index 3369c1d4..b37fed8b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java @@ -10,8 +10,8 @@ public static final class JobStatus { public final static String PATH_HEALTH = "/actuator/health"; public final static String PATH_JOBS = "/admin/jobs"; public final static String PATH_DATASETS = "/admin/datasets"; - public final static String PATH_EXTERNAL = "/external"; + public final static String PATH_CODE = "/code"; - public final static String EXTERNAL_ID_PREFIX = "tcdi-"; + public final static String CODE_PREFIX = "tcdi-"; } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java index ee30e2db..207ac1d8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java @@ -19,9 +19,9 @@ import static javax.ws.rs.core.MediaType.MULTIPART_FORM_DATA_TYPE; import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE; import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL; -import static org.devgateway.toolkit.forms.client.ClientConstants.EXTERNAL_ID_PREFIX; +import static org.devgateway.toolkit.forms.client.ClientConstants.CODE_PREFIX; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_DATASETS; -import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_EXTERNAL; +import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_CODE; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_HEALTH; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_JOBS; @@ -68,8 +68,7 @@ public DatasetJobStatus publishDataset(TetsimDataset dataset, byte[] datasetCont FormDataMultiPart multiPart = new FormDataMultiPart(); multiPart.field("name", "TETSIM dataset " + dataset.getYear()); - multiPart.field("externalId", EXTERNAL_ID_PREFIX + dataset.getId()); - multiPart.field("year", dataset.getYear().toString()); + multiPart.field("code", CODE_PREFIX + dataset.getId()); multiPart.field("file", tempUploadFile.getName(), TEXT_PLAIN_TYPE) .bodyPart(fileDataBodyPart); @@ -91,11 +90,11 @@ public DatasetJobStatus publishDataset(TetsimDataset dataset, byte[] datasetCont throw new RuntimeException(("Service is not up")); } - public DatasetJobStatus getDatasetJobStatus(String externalId) { + public DatasetJobStatus getDatasetJobStatus(String code) { Response jobStatusResponse = client.target(baseUrl) .path(PATH_JOBS) - .path(PATH_EXTERNAL) - .path(externalId) + .path(PATH_CODE) + .path(code) .request(APPLICATION_JSON).get(); if (jobStatusResponse.getStatusInfo().getFamily() == SUCCESSFUL) { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetJobStatus.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetJobStatus.java index 5910b143..6687724a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetJobStatus.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetJobStatus.java @@ -12,7 +12,7 @@ public class DatasetJobStatus { private String status; - private String externalId; + private String code; private String message; @@ -48,12 +48,12 @@ public void setStatus(final String status) { this.status = status; } - public String getExternalId() { - return externalId; + public String getCode() { + return code; } - public void setExternalId(final String externalId) { - this.externalId = externalId; + public void setCode(final String code) { + this.code = code; } public String getMessage() { @@ -71,7 +71,7 @@ public String toString() { ", createdDate=" + createdDate + ", endDate=" + endDate + ", status='" + status + '\'' + - ", externalId='" + externalId + '\'' + + ", code='" + code + '\'' + ", message='" + message + '\'' + '}'; } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java index 70952eb4..5e76558e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java @@ -16,7 +16,7 @@ import java.io.IOException; -import static org.devgateway.toolkit.forms.client.ClientConstants.EXTERNAL_ID_PREFIX; +import static org.devgateway.toolkit.forms.client.ClientConstants.CODE_PREFIX; import static org.devgateway.toolkit.forms.client.ClientConstants.JobStatus.COMPLETED; import static org.devgateway.toolkit.forms.client.ClientConstants.JobStatus.ERROR; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.NOT_PUBLISHED; @@ -44,7 +44,7 @@ public void triggerCheckDatasetsJob() { tetsimDatasetService.findAllPublishing().forEach(d -> { ServiceMetadata serviceMetadata = eurekaClientService.getServiceByName(d.getDestinationService()); DatasetClient client = new DatasetClient(serviceMetadata.getUrl()); - String status = client.getDatasetJobStatus(EXTERNAL_ID_PREFIX + d.getId()).getStatus(); + String status = client.getDatasetJobStatus(CODE_PREFIX + d.getId()).getStatus(); if (COMPLETED.equals(status)) { d.setStatus(PUBLISHED); logger.info(String.format("The dataset with id %s changed the status from %s to %s", From f187d4af4924767e80c3399099bc83d80da7c896 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 14 Jul 2022 15:07:08 +0300 Subject: [PATCH 073/137] TOBACCO-950: Unpublish the dataset by deleting it from the microservice --- .../toolkit/forms/client/DatasetClient.java | 22 +++++++++++++++++-- .../service/DatasetPublishingService.java | 9 ++++++-- .../edit/dataset/EditTetsimDatasetPage.java | 17 ++++++++++++-- 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java index 207ac1d8..cd3d9b93 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java @@ -20,8 +20,8 @@ import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE; import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL; import static org.devgateway.toolkit.forms.client.ClientConstants.CODE_PREFIX; -import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_DATASETS; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_CODE; +import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_DATASETS; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_HEALTH; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_JOBS; @@ -55,7 +55,25 @@ public DatasetJobStatus getDatasetStatus(String jobId) throws DataSetClientExcep throw new RuntimeException(("Service is not up")); } - public DatasetJobStatus publishDataset(TetsimDataset dataset, byte[] datasetContent) throws DataSetClientException { + public void unpublishDataset(TetsimDataset dataset) throws DataSetClientException { + if (isUp()) { + String code = CODE_PREFIX + dataset.getId(); + + Response jobStatusResponse = client.target(baseUrl) + .path(PATH_DATASETS) + .path(code) + .request() + .delete(); + + if (jobStatusResponse.getStatusInfo().getFamily() != SUCCESSFUL) { + throw new DataSetClientException("Error in unpublishing a dataset with code " + code); + } + } else { + throw new RuntimeException(("Service is not up")); + } + } + + public DatasetJobStatus unpublishDataset(TetsimDataset dataset, byte[] datasetContent) throws DataSetClientException { if (isUp()) { File tempUploadFile; try { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java index 5e76558e..5ca67789 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java @@ -62,10 +62,15 @@ public void triggerCheckDatasetsJob() { } - public void publish(ServiceMetadata service, TetsimDataset dataset) throws DataSetClientException, CsvRequiredFieldEmptyException, CsvDataTypeMismatchException, IOException { + public void publishDataset(ServiceMetadata service, TetsimDataset dataset) + throws DataSetClientException, CsvRequiredFieldEmptyException, CsvDataTypeMismatchException, IOException { byte[] tetsimCSVDatasetOutputs = tetsimOutputService.getTetsimCSVDatasetOutputs(dataset.getId()); DatasetClient client = new DatasetClient(service.getUrl()); - client.publishDataset(dataset, tetsimCSVDatasetOutputs); + client.unpublishDataset(dataset, tetsimCSVDatasetOutputs); + } + + public void unpublishDataset(ServiceMetadata service, TetsimDataset dataset) throws DataSetClientException { + new DatasetClient(service.getUrl()).unpublishDataset(dataset); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index 37c2f08e..03f775e1 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -15,7 +15,6 @@ import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; -import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditStatusEntityPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; @@ -153,13 +152,27 @@ protected void onDelete(final AjaxRequestTarget target) { setResponsePage(listPageClass); } + @Override + protected void onAfterRevertToDraft(final AjaxRequestTarget target) { + try { + TetsimDataset dataset = editForm.getModelObject(); + String destinationService = dataset.getDestinationService(); + ServiceMetadata serviceMetadata = eurekaClientService.getServiceByName(destinationService); + + datasetPublishingService.unpublishDataset(serviceMetadata, dataset); + + } catch (DataSetClientException | Exception e) { + logger.error(e.getMessage(), e); + } + } + protected void onApprove(final AjaxRequestTarget target) { try { TetsimDataset dataset = editForm.getModelObject(); String destinationService = dataset.getDestinationService(); ServiceMetadata serviceMetadata = eurekaClientService.getServiceByName(destinationService); - datasetPublishingService.publish(serviceMetadata, dataset); + datasetPublishingService.publishDataset(serviceMetadata, dataset); dataset.setStatus(PUBLISHING); } catch (DataSetClientException | Exception e) { From 032839cc3476cdef5c9c84fe8421097358666e55 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Tue, 19 Jul 2022 16:08:37 +0300 Subject: [PATCH 074/137] TOBACCO-951: Implement CSV dataset uploads --- forms/pom.xml | 2 +- .../toolkit/forms/client/DatasetClient.java | 37 ++- .../service/DatasetPublishingService.java | 66 ++++-- .../service/DerbyDatabaseBackupService.java | 1 - .../CheckBoxPickerBootstrapFormComponent.java | 3 +- ...ileInputBootstrapFormComponentWrapper.html | 6 +- ...ileInputBootstrapFormComponentWrapper.java | 26 +- .../table/filter/CSVDatasetFilterState.java | 33 +++ .../forms/wicket/page/DatasetsHomepage.java | 3 + .../wicket/page/DatasetsHomepage.properties | 5 +- .../edit/AbstractEditStatusEntityPage.java | 7 +- .../page/edit/dataset/EditCSVDatasetPage.html | 29 +++ .../page/edit/dataset/EditCSVDatasetPage.java | 223 ++++++++++++++++++ .../dataset/EditCSVDatasetPage.properties | 9 + .../edit/dataset/EditTetsimDatasetPage.html | 2 +- .../edit/dataset/EditTetsimDatasetPage.java | 26 +- .../lists/dataset/ListCSVDatasetPage.java | 88 +++++++ .../dataset/ListCSVDatasetPage.properties | 9 + .../wicket/styles/assets/js/fileupload.js | 4 + .../persistence/dao/data/CSVDataset.java | 41 ++++ .../toolkit/persistence/dao/data/Dataset.java | 8 +- .../repository/data/CSVDatasetRepository.java | 25 ++ .../repository/data/DatasetRepository.java | 3 - .../data/TetsimDatasetRepository.java | 3 + .../service/data/CSVDatasetService.java | 7 + .../service/data/CSVDatasetServiceImpl.java | 53 +++++ .../service/data/DatasetService.java | 17 ++ .../service/data/TetsimDatasetService.java | 12 +- .../data/TetsimDatasetServiceImpl.java | 1 + 29 files changed, 689 insertions(+), 60 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/CSVDataset.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetService.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetServiceImpl.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/DatasetService.java diff --git a/forms/pom.xml b/forms/pom.xml index 6868b0ab..5cacf45f 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -32,7 +32,7 @@ 1.8 8.10.0 8.10.0 - 2.0.15 + 2.0.11 1.13 2.0.19 v20200406 diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java index cd3d9b93..d205f733 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java @@ -1,7 +1,7 @@ package org.devgateway.toolkit.forms.client; import org.apache.commons.io.FileUtils; -import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dao.data.Dataset; import org.glassfish.jersey.client.JerseyClient; import org.glassfish.jersey.client.JerseyClientBuilder; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; @@ -55,10 +55,8 @@ public DatasetJobStatus getDatasetStatus(String jobId) throws DataSetClientExcep throw new RuntimeException(("Service is not up")); } - public void unpublishDataset(TetsimDataset dataset) throws DataSetClientException { + public void unpublishDataset(String code) throws DataSetClientException { if (isUp()) { - String code = CODE_PREFIX + dataset.getId(); - Response jobStatusResponse = client.target(baseUrl) .path(PATH_DATASETS) .path(code) @@ -73,11 +71,11 @@ public void unpublishDataset(TetsimDataset dataset) throws DataSetClientExceptio } } - public DatasetJobStatus unpublishDataset(TetsimDataset dataset, byte[] datasetContent) throws DataSetClientException { + public DatasetJobStatus publishDataset(Dataset dataset, byte[] datasetContent) throws DataSetClientException { if (isUp()) { File tempUploadFile; try { - tempUploadFile = File.createTempFile(dataset.getYear() + "_tetsim.csv", ".csv"); + tempUploadFile = File.createTempFile(dataset.getYear() + "_tetsim", "csv"); tempUploadFile.deleteOnExit(); FileUtils.writeByteArrayToFile(tempUploadFile, datasetContent); @@ -108,6 +106,33 @@ public DatasetJobStatus unpublishDataset(TetsimDataset dataset, byte[] datasetCo throw new RuntimeException(("Service is not up")); } + public DatasetJobStatus publishDataset(String name, String code, File file) throws DataSetClientException { + if (isUp()) { + FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file", file, APPLICATION_OCTET_STREAM_TYPE); + fileDataBodyPart.setContentDisposition(FormDataContentDisposition.name("file") + .fileName(file.getName()) + .build()); + + FormDataMultiPart multiPart = new FormDataMultiPart(); + multiPart.field("name", name); + multiPart.field("code", code); + multiPart.field("file", file.getName(), TEXT_PLAIN_TYPE).bodyPart(fileDataBodyPart); + + Response jobStatusResponse = client.target(baseUrl) + .path(PATH_DATASETS) + .request() + .post(Entity.entity(multiPart, MULTIPART_FORM_DATA_TYPE)); + + if (jobStatusResponse.getStatusInfo().getFamily() == SUCCESSFUL) { + return jobStatusResponse.readEntity(DatasetJobStatus.class); + } + + throw new DataSetClientException(jobStatusResponse.toString()); + } + + throw new RuntimeException(("Service is not up")); + } + public DatasetJobStatus getDatasetJobStatus(String code) { Response jobStatusResponse = client.target(baseUrl) .path(PATH_JOBS) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java index 5ca67789..5c3980e3 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java @@ -1,20 +1,24 @@ package org.devgateway.toolkit.forms.service; -import com.opencsv.exceptions.CsvDataTypeMismatchException; -import com.opencsv.exceptions.CsvRequiredFieldEmptyException; +import org.apache.commons.io.FileUtils; import org.devgateway.toolkit.forms.client.DataSetClientException; import org.devgateway.toolkit.forms.client.DatasetClient; +import org.devgateway.toolkit.persistence.dao.data.CSVDataset; +import org.devgateway.toolkit.persistence.dao.data.Dataset; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.dto.ServiceMetadata; +import org.devgateway.toolkit.persistence.service.data.CSVDatasetService; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; -import org.devgateway.toolkit.persistence.service.tetsim.TetsimOutputService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +import java.io.File; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import static org.devgateway.toolkit.forms.client.ClientConstants.CODE_PREFIX; import static org.devgateway.toolkit.forms.client.ClientConstants.JobStatus.COMPLETED; @@ -29,19 +33,26 @@ public class DatasetPublishingService { private static final Logger logger = LoggerFactory.getLogger(DatasetPublishingService.class); @Autowired - private TetsimOutputService tetsimOutputService; + private TetsimDatasetService tetsimDatasetService; @Autowired - private TetsimDatasetService tetsimDatasetService; + private CSVDatasetService csvDatasetService; @Autowired private EurekaClientService eurekaClientService; @Scheduled(cron = "0 * * * * *") public void triggerCheckDatasetsJob() { - logger.info("Fired triggerCheckDatasetsJob"); + logger.debug("Fired triggerCheckDatasetsJob"); + List datasets = new ArrayList<>(); + datasets.addAll(tetsimDatasetService.findAllPublishing()); + datasets.addAll(csvDatasetService.findAllPublishing()); - tetsimDatasetService.findAllPublishing().forEach(d -> { + checkDatasetJobs(datasets); + } + + private void checkDatasetJobs(List datasets) { + datasets.forEach(d -> { ServiceMetadata serviceMetadata = eurekaClientService.getServiceByName(d.getDestinationService()); DatasetClient client = new DatasetClient(serviceMetadata.getUrl()); String status = client.getDatasetJobStatus(CODE_PREFIX + d.getId()).getStatus(); @@ -56,21 +67,46 @@ public void triggerCheckDatasetsJob() { } if (!PUBLISHING.equals(d.getStatus())) { - tetsimDatasetService.save(d); + if (d instanceof TetsimDataset) { + tetsimDatasetService.save((TetsimDataset) d); + } else if (d instanceof CSVDataset) { + csvDatasetService.save((CSVDataset) d); + } else { + throw new RuntimeException("Invalid dataset class"); + } } }); + } + + public void publishDataset(Dataset dataset, String fileName, byte[] content) throws DataSetClientException { + + String serviceURL = getDestinationService(dataset).getUrl(); + DatasetClient client = new DatasetClient(serviceURL); + + String name = "Dataset " + dataset.getYear(); + String code = CODE_PREFIX + dataset.getId(); + + File tempUploadFile; + try { + tempUploadFile = File.createTempFile(fileName, null); + tempUploadFile.deleteOnExit(); + FileUtils.writeByteArrayToFile(tempUploadFile, content); + } catch (IOException e) { + throw new RuntimeException(e); + } + client.publishDataset(name, code, tempUploadFile); } - public void publishDataset(ServiceMetadata service, TetsimDataset dataset) - throws DataSetClientException, CsvRequiredFieldEmptyException, CsvDataTypeMismatchException, IOException { - byte[] tetsimCSVDatasetOutputs = tetsimOutputService.getTetsimCSVDatasetOutputs(dataset.getId()); + public void unpublishDataset(Dataset dataset) throws DataSetClientException { + String code = CODE_PREFIX + dataset.getId(); + String serviceURL = getDestinationService(dataset).getUrl(); - DatasetClient client = new DatasetClient(service.getUrl()); - client.unpublishDataset(dataset, tetsimCSVDatasetOutputs); + new DatasetClient(serviceURL).unpublishDataset(code); } - public void unpublishDataset(ServiceMetadata service, TetsimDataset dataset) throws DataSetClientException { - new DatasetClient(service.getUrl()).unpublishDataset(dataset); + private ServiceMetadata getDestinationService(Dataset dataset) { + String destinationService = dataset.getDestinationService(); + return eurekaClientService.getServiceByName(destinationService); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/DerbyDatabaseBackupService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/DerbyDatabaseBackupService.java index 3352a52a..cd3065e6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/DerbyDatabaseBackupService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/DerbyDatabaseBackupService.java @@ -53,7 +53,6 @@ public class DerbyDatabaseBackupService { * use a cron format and invoke it every day at 21:00 server time. That * should be a good time for backup for both EST and CET */ - @Scheduled(cron = "0 0 21 * * ?") public void backupDatabase() { String databaseProductName; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxPickerBootstrapFormComponent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxPickerBootstrapFormComponent.java index 2d159ed8..a47eb312 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxPickerBootstrapFormComponent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/CheckBoxPickerBootstrapFormComponent.java @@ -11,6 +11,7 @@ *******************************************************************************/ package org.devgateway.toolkit.forms.wicket.components.form; +import de.agilecoders.wicket.core.markup.html.bootstrap.button.ButtonGroup; import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.checkbox.bootstrapcheckbox.BootstrapCheckBoxPicker; import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.checkbox.bootstrapcheckbox.BootstrapCheckBoxPickerConfig; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; @@ -49,7 +50,7 @@ protected BootstrapCheckBoxPicker inputField(final String id, final IModel - + @@ -45,6 +45,10 @@
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/FileInputBootstrapFormComponentWrapper.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/FileInputBootstrapFormComponentWrapper.java index 3e3891f2..c61add4d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/FileInputBootstrapFormComponentWrapper.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/FileInputBootstrapFormComponentWrapper.java @@ -96,6 +96,8 @@ public class FileInputBootstrapFormComponentWrapper extends FormComponentPane private Boolean disableDeleteButton = false; + private boolean allowDownloadWhenReadonly = true; + private boolean requireAtLeastOneItem = false; /** @@ -133,7 +135,7 @@ protected void onInitialize() { addFileUploadFeedbackComponent(); addBootstrapFileInputComponent(); - bootstrapFileInput.withShowUpload(true).withShowRemove(false).withShowPreview(true).withShowCaption(true); + bootstrapFileInput.withShowUpload(true).withShowRemove(false).withShowPreview(false).withShowCaption(true); } public boolean isVisibleAlreadyUploadedFiles() { @@ -209,11 +211,17 @@ public String getContentType() { } }; + ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(rstream, modelObject.getName()); handler.setContentDisposition(ContentDisposition.ATTACHMENT); getRequestCycle().scheduleRequestHandlerAfterCurrent(handler); } + + @Override + public boolean isEnabledInHierarchy() { + return isLinkEnabledInHierarchy(this, super.isEnabledInHierarchy()); + } }; downloadLink.add(new Label("downloadText", item.getModelObject().getName())); downloadLink.add(new TooltipBehavior(new StringResourceModel("downloadUploadedFileTooltip", @@ -457,6 +465,7 @@ protected void onSubmit(final AjaxRequestTarget target) { target.add(fileUploadFeedback); target.add(pendingFiles); + target.appendJavaScript("$('.cover-buttons-div').css(\"z-index\", -1);"); FileInputBootstrapFormComponentWrapper.this.onUpdate(target); } }; @@ -564,6 +573,21 @@ public void requireAtLeastOneItem() { requireAtLeastOneItem = true; } + public boolean isAllowDownloadWhenReadonly() { + return allowDownloadWhenReadonly; + } + + public void setAllowDownloadWhenReadonly(final boolean allowDownloadWhenReadonly) { + this.allowDownloadWhenReadonly = allowDownloadWhenReadonly; + } + + private boolean isLinkEnabledInHierarchy(final Component component, final boolean defaultState) { + if (allowDownloadWhenReadonly) { + return component.isEnableAllowed() && component.isEnabled(); + } + return defaultState; + } + @Override public boolean checkRequired() { return !requireAtLeastOneItem || !ObjectUtils.isEmpty(getModelObject()); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java new file mode 100644 index 00000000..631e0185 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java @@ -0,0 +1,33 @@ +package org.devgateway.toolkit.forms.wicket.components.table.filter; + +import org.devgateway.toolkit.persistence.dao.AbstractStatusAuditableEntity_; +import org.devgateway.toolkit.persistence.dao.data.CSVDataset; +import org.devgateway.toolkit.persistence.repository.SpecificationContext; +import org.springframework.data.jpa.domain.Specification; + +import javax.persistence.criteria.Predicate; +import java.util.ArrayList; +import java.util.List; + +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; + +/** + * Created by Viorel Chihai + */ +public class CSVDatasetFilterState extends JpaFilterState { + + private static final long serialVersionUID = -3419455862012018431L; + + @Override + public Specification getSpecification() { + return (root, query, cb) -> { + List predicates = new ArrayList<>(); + SpecificationContext sc = new SpecificationContext<>(root, query, cb); + + predicates.add(sc.cb().notLike(sc.root().get(AbstractStatusAuditableEntity_.status), DELETED)); + + return cb.and(predicates.toArray(new Predicate[predicates.size()])); + }; + } + +} \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.java index a223c780..74c1ccc3 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.java @@ -22,6 +22,7 @@ import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; +import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListCSVDatasetPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; import org.wicketstuff.annotation.mount.MountPath; @@ -37,6 +38,8 @@ public class DatasetsHomepage extends BasePage { private static final List LINKS = new ImmutableList.Builder() .add(new BigLinkDefinition("tetsimDataset", ListTetsimDatasetPage.class, FontAwesome5IconType.percentage_s)) + .add(new BigLinkDefinition("csvDataset", ListCSVDatasetPage.class, + FontAwesome5IconType.file_csv_s)) .build(); public DatasetsHomepage(final PageParameters parameters) { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties index 8771a822..e3dbb02b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties @@ -1,4 +1,7 @@ page.title=South Africa Datasets tetsimDataset.label=TETSIM -tetsimDataset.desc=Manage the TETSIM Dataset \ No newline at end of file +tetsimDataset.desc=Manage the TETSIM Dataset + +csvDataset.label=CSV +csvDataset.desc=Manage the CSV Dataset \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index cb7e15e6..22f05ff5 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -63,6 +63,7 @@ import static org.devgateway.toolkit.forms.WebConstants.PARAM_AUTO_SAVE; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DRAFT; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.NOT_PUBLISHED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.SAVED; @@ -476,6 +477,7 @@ private String getStatusLabelClass() { case PUBLISHED: return "label-success"; case DRAFT: + case NOT_PUBLISHED: return "label-danger"; case SAVED: return "label-primary"; @@ -800,7 +802,7 @@ protected void addSaveRevertButtonPermissions(final Component button) { MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, getValidatorRole()); MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, getCommaCombinedRoles()); button.setVisibilityAllowed(button.isVisibilityAllowed() - && (PUBLISHING.equals(editForm.getModelObject().getStatus()) + && (NOT_PUBLISHED.equals(editForm.getModelObject().getStatus()) || PUBLISHED.equals(editForm.getModelObject().getStatus()))); } @@ -817,7 +819,8 @@ protected void addApproveButtonPermissions(final Component button) { MetaDataRoleAuthorizationStrategy.authorize( button, Component.RENDER, getValidatorRole()); button.setVisibilityAllowed(button.isVisibilityAllowed() - && SAVED.equals(editForm.getModelObject().getStatus())); + && (SAVED.equals(editForm.getModelObject().getStatus()) + || NOT_PUBLISHED.equals(editForm.getModelObject().getStatus()))); } protected void addSaveButtonsPermissions(final Component button) { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.html new file mode 100644 index 00000000..10bea360 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.html @@ -0,0 +1,29 @@ + + + + + Edit CSV Dataset + + + +
+ +
+
+
+ +
+
+
+
+
+
+ +
+
+
+ +
+ + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java new file mode 100644 index 00000000..5c721701 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java @@ -0,0 +1,223 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.dataset; + +import org.apache.commons.lang3.StringUtils; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.WebConstants; +import org.devgateway.toolkit.forms.client.DataSetClientException; +import org.devgateway.toolkit.forms.service.DatasetPublishingService; +import org.devgateway.toolkit.forms.service.EurekaClientService; +import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; +import org.devgateway.toolkit.forms.wicket.components.form.FileInputBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.components.form.TextAreaFieldBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditStatusEntityPage; +import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListCSVDatasetPage; +import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; +import org.devgateway.toolkit.persistence.dao.FileMetadata; +import org.devgateway.toolkit.persistence.dao.data.CSVDataset; +import org.devgateway.toolkit.persistence.dao.data.Dataset; +import org.devgateway.toolkit.persistence.dto.ServiceMetadata; +import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; +import org.devgateway.toolkit.persistence.service.data.CSVDatasetService; +import org.devgateway.toolkit.web.util.SettingsUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.orm.ObjectOptimisticLockingFailureException; +import org.wicketstuff.annotation.mount.MountPath; + +import java.io.File; +import java.util.stream.Collectors; + +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.SAVED; + +/** + * @author vchihai + */ +@MountPath(value = "/editCSVDataset") +public class EditCSVDatasetPage extends AbstractEditStatusEntityPage { + + private static final long serialVersionUID = -5231470856974604314L; + + private static final Logger logger = LoggerFactory.getLogger(EditCSVDatasetPage.class); + + protected Select2ChoiceBootstrapFormComponent year; + + protected Select2ChoiceBootstrapFormComponent destinationService; + + @SpringBean + protected CSVDatasetService csvDatasetService; + + @SpringBean + protected EurekaClientService eurekaClientService; + + @SpringBean + protected DatasetPublishingService datasetPublishingService; + + @SpringBean + protected SettingsUtils settingsUtils; + + @SpringBean + protected TobaccoProductService tobaccoProductService; + + public EditCSVDatasetPage(final PageParameters parameters) { + super(parameters); + this.jpaService = csvDatasetService; + this.listPageClass = ListCSVDatasetPage.class; + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + editForm.add(getYear()); + + final TextFieldBootstrapFormComponent description = + new TextFieldBootstrapFormComponent<>("description"); + description.getField().add(WebConstants.StringValidators.MAXIMUM_LENGTH_VALIDATOR_ONE_LINE_TEXT); + editForm.add(description); + + final FileInputBootstrapFormComponent files = new FileInputBootstrapFormComponent("files"); + files.allowedFileExtensions("csv"); + files.required(); + files.maxFiles(1); + files.getFileInputBootstrapFormComponentWrapper().setAllowDownloadWhenReadonly(true); + editForm.add(files); + editForm.add(getService()); + + } + + private Select2ChoiceBootstrapFormComponent getYear() { + year = new Select2ChoiceBootstrapFormComponent<>("year", + new GenericChoiceProvider<>(settingsUtils.getYearsRange())); + editForm.add(year); + year.required(); + + return year; + } + + private Select2ChoiceBootstrapFormComponent getService() { + destinationService = new Select2ChoiceBootstrapFormComponent("destinationService", + new GenericChoiceProvider<>(eurekaClientService.findAllWithData().stream() + .map(ServiceMetadata::getName) + .collect(Collectors.toList()))) { + @Override + protected void onUpdate(final AjaxRequestTarget target) { + super.onUpdate(target); + if (editForm.getModelObject().getDestinationService() != null) { + saveApproveButton.setEnabled(true); + approveButton.setEnabled(true); + } else { + saveApproveButton.setEnabled(false); + approveButton.setEnabled(false); + } + + target.add(approveButton); + target.add(saveApproveButton); + } + + + }; + destinationService.setEnabled(true); + + return destinationService; + } + + @Override + protected void onDelete(final AjaxRequestTarget target) { + try { + // save the object and go back to the list page + CSVDataset saveable = editForm.getModelObject(); + saveable.setStatus(DELETED); + + beforeSaveEntity(saveable); + // saves the entity and flushes the changes + jpaService.saveAndFlush(saveable); + + // clears session and detaches all entities that are currently attached + entityManager.clear(); + + // we flush the mondrian/wicket/reports cache to ensure it gets rebuilt + flushReportingCaches(); + afterSaveEntity(saveable); + } catch (ObjectOptimisticLockingFailureException e) { + deleteFailedModal.show(target); + target.add(deleteFailedModal); + } + setResponsePage(listPageClass); + } + + @Override + protected void onAfterRevertToDraft(final AjaxRequestTarget target) { + if (PUBLISHED.equals(editForm.getModelObject().getStatus())) { + try { + datasetPublishingService.unpublishDataset(editForm.getModelObject()); + } catch (DataSetClientException | Exception e) { + logger.error(e.getMessage(), e); + } + } + } + + protected void onApprove(final AjaxRequestTarget target) { + try { + CSVDataset dataset = editForm.getModelObject(); + + FileMetadata fileMetadata = dataset.getFiles().stream().findFirst().get(); + String fileName = fileMetadata.getName(); + byte[] content = fileMetadata.getContent().getBytes(); + + datasetPublishingService.publishDataset(dataset, fileName, content); + dataset.setStatus(PUBLISHING); + } catch (DataSetClientException | Exception e) { + logger.error(e.getMessage(), e); + approveFailedModal.show(target); + } + setResponsePage(listPageClass); + } + + protected BootstrapCancelButton getCancelButton(final String id) { + return new CancelEditPageButton(id, new StringResourceModel("cancelButton", this, null)); + } + + public class CancelEditPageButton extends BootstrapCancelButton { + private static final long serialVersionUID = -1474498211555760931L; + + public CancelEditPageButton(final String id, final IModel model) { + super(id, model); + } + + @Override + protected void onSubmit(final AjaxRequestTarget target) { + cancelModal.show(true); + target.add(cancelModal); + } + } + + @Override + protected void onBeforeRender() { + super.onBeforeRender(); + + if (SAVED.equals(editForm.getModelObject().getStatus())) { + destinationService.setEnabled(true); + } + } + + @Override + protected void enableDisableAutosaveFields(final AjaxRequestTarget target) { + super.enableDisableAutosaveFields(target); + + if (StringUtils.isBlank(editForm.getModelObject().getDestinationService())) { + saveApproveButton.setEnabled(false); + approveButton.setEnabled(false); + } + } + + // upload file +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.properties new file mode 100644 index 00000000..35b3f180 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.properties @@ -0,0 +1,9 @@ +page.title.add=Add CSV Dataset +page.title.edit=Edit CSV Dataset +year.label=Year +destinationService.label=Destination Service + +description.label=Description +files.label=Dataset File +uploadedFilesTitle=Uploaded File +note=* The uploaded document can be accessed by admin, neiti, and auditor users. \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html index 00aeef1e..d010ef4e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.html @@ -2,7 +2,7 @@ - Edit TETSIM Datasets + Edit TETSIM Dataset diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index 03f775e1..26be64dc 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -24,6 +24,7 @@ import org.devgateway.toolkit.persistence.dto.ServiceMetadata; import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; +import org.devgateway.toolkit.persistence.service.tetsim.TetsimOutputService; import org.devgateway.toolkit.web.util.SettingsUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,6 +37,7 @@ import static org.devgateway.toolkit.forms.WebConstants.MAXIMUM_PERCENTAGE; import static org.devgateway.toolkit.forms.WebConstants.PARAM_YEAR; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.SAVED; @@ -56,6 +58,9 @@ public class EditTetsimDatasetPage extends AbstractEditStatusEntityPage { + private static final long serialVersionUID = -7425220174797515101L; + + @SpringBean + private CSVDatasetService datasetService; + + public ListCSVDatasetPage(final PageParameters pageParameters) { + super(pageParameters); + this.jpaService = datasetService; + this.editPageClass = EditCSVDatasetPage.class; + + columns.clear(); + + columns.add(new PropertyColumn<>(new StringResourceModel("year"), "year", "year")); + columns.add(new PropertyColumn<>(new StringResourceModel("lastModifiedBy"), "lastModifiedBy", + "lastModifiedBy.get")); + columns.add(new PropertyColumn(new StringResourceModel("lastModifiedDate"), + "lastModifiedDate", + "lastModifiedDate.get") { + + @Override + public IModel getDataModel(final IModel rowModel) { + IModel model = super.getDataModel(rowModel); + ZonedDateTime modifiedDate = (ZonedDateTime) model.getObject(); + return Model.of(modifiedDate.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"))); + } + }); + columns.add(new PropertyColumn<>(new StringResourceModel("destinationService"), "destinationService", "destinationService")); + columns.add(new PropertyColumn<>(new StringResourceModel("status"), "status", "status")); + + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + dataProvider.setSort("year", SortOrder.DESCENDING); + + excelForm.setVisibilityAllowed(false); + } + + @Override + protected Component getRevisionsLink(final CSVDataset entity) { + return new WebMarkupContainer("revisions").setVisibilityAllowed(false); + } + + @Override + public JpaFilterState newFilterState() { + return new CSVDatasetFilterState(); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties new file mode 100644 index 00000000..85da4361 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties @@ -0,0 +1,9 @@ +page.title=CSV Datasets +year=Year +lastModifiedBy=Editor +lastModifiedDate=Latest Modification +status=Status +destinationService=Destination Service +actionsColumn=Action + +new=Add new dataset \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/assets/js/fileupload.js b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/assets/js/fileupload.js index 7030a553..e7f2b067 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/assets/js/fileupload.js +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/assets/js/fileupload.js @@ -31,8 +31,12 @@ // disable the upload button $(this).closest('.file-input').find('.fileinput-upload-button').show(); $(this).closest('.file-input').find('.fileinput-upload-button').prop("disabled", true); + + // Cover form buttons with a div (will be hidden again in FileInputBootstrapFormComponentWrapper.html) + $('.cover-buttons-div').css("z-index", 100); } else { $(this).closest('.file-input').find('.fileinput-upload-button').hide(); + $('.cover-buttons-div').css("z-index", -1); } }); })(); diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/CSVDataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/CSVDataset.java new file mode 100644 index 00000000..d1bd1758 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/CSVDataset.java @@ -0,0 +1,41 @@ +package org.devgateway.toolkit.persistence.dao.data; + +import org.devgateway.toolkit.persistence.dao.FileMetadata; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; +import org.hibernate.envers.Audited; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.OneToMany; +import java.util.Set; + +@Entity +@Audited +@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) +public class CSVDataset extends Dataset { + + @Audited + private String description; + + @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) + @OneToMany(cascade = CascadeType.ALL) + @Audited + private Set files; + + public Set getFiles() { + return files; + } + + public void setFiles(final Set files) { + this.files = files; + } + + public String getDescription() { + return description; + } + + public void setDescription(final String description) { + this.description = description; + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java index ecdad99e..4af2bf54 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java @@ -31,11 +31,11 @@ public void setYear(final Integer year) { this.year = year; } - public String getDestinationService() { - return destinationService; - } - public void setDestinationService(final String destinationService) { this.destinationService = destinationService; } + + public String getDestinationService() { + return destinationService; + } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java new file mode 100644 index 00000000..e83f89ee --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java @@ -0,0 +1,25 @@ +package org.devgateway.toolkit.persistence.repository.data; + +import org.devgateway.toolkit.persistence.dao.data.CSVDataset; +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.repository.norepository.UniquePropertyRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import javax.transaction.Transactional; +import java.util.List; + +@Transactional +public interface CSVDatasetRepository extends DatasetRepository, + UniquePropertyRepository { + + @Query("select td from CSVDataset td where td.status like 'DELETED'") + List findAllDeleted(); + + @Query("select td from CSVDataset td where td.status like 'PUBLISHING'") + List findAllPublishing(); + + @Query ("select count(e) from #{#entityName} e where (:year is null or e.year=:year) " + + "and e.status not in ('DELETED')") + long countByNonPublished(@Param("year") Integer year); +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java index 00151771..b5247d10 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java @@ -11,7 +11,4 @@ @NoRepositoryBean public interface DatasetRepository extends BaseJpaRepository { - @Query("select td from TetsimDataset td where td.status like 'PUBLISHING'") - List findAllPublishing(); - } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java index 8f6fbc30..35128777 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java @@ -15,6 +15,9 @@ public interface TetsimDatasetRepository extends DatasetRepository findAllDeleted(); + @Query("select td from TetsimDataset td where td.status like 'PUBLISHING'") + List findAllPublishing(); + @Query ("select count(e) from #{#entityName} e where (:year is null or e.year=:year) " + "and e.status not in ('DELETED')") long countByNonPublished(@Param("year") Integer year); diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetService.java new file mode 100644 index 00000000..4734870f --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetService.java @@ -0,0 +1,7 @@ +package org.devgateway.toolkit.persistence.service.data; + +import org.devgateway.toolkit.persistence.dao.data.CSVDataset; + +public interface CSVDatasetService extends DatasetService { + +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetServiceImpl.java new file mode 100644 index 00000000..77519019 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetServiceImpl.java @@ -0,0 +1,53 @@ +package org.devgateway.toolkit.persistence.service.data; + +import org.devgateway.toolkit.persistence.dao.data.CSVDataset; +import org.devgateway.toolkit.persistence.repository.data.CSVDatasetRepository; +import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; +import org.devgateway.toolkit.persistence.repository.norepository.UniquePropertyRepository; +import org.devgateway.toolkit.persistence.service.BaseJpaServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheConfig; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@CacheConfig(cacheNames = "servicesCache") +@Transactional(readOnly = true) +public class CSVDatasetServiceImpl extends BaseJpaServiceImpl implements CSVDatasetService { + + @Autowired + private CSVDatasetRepository csvDatasetRepository; + + @Override + public CSVDataset newInstance() { + return new CSVDataset(); + } + + @Override + protected BaseJpaRepository repository() { + return csvDatasetRepository; + } + + @Override + public UniquePropertyRepository uniquePropertyRepository() { + return csvDatasetRepository; + } + + @Override + public List findAllDeleted() { + return csvDatasetRepository.findAllDeleted(); + } + + @Override + public List findAllPublishing() { + return csvDatasetRepository.findAllPublishing(); + } + + @Override + public long countByNonPublished(final Integer year) { + return csvDatasetRepository.countByNonPublished(year); + } + +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/DatasetService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/DatasetService.java new file mode 100644 index 00000000..9e5ee796 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/DatasetService.java @@ -0,0 +1,17 @@ +package org.devgateway.toolkit.persistence.service.data; + +import org.devgateway.toolkit.persistence.dao.data.Dataset; +import org.devgateway.toolkit.persistence.service.BaseJpaService; +import org.devgateway.toolkit.persistence.service.UniquePropertyService; + +import java.util.List; + +public interface DatasetService extends BaseJpaService, UniquePropertyService { + + List findAllDeleted(); + + List findAllPublishing(); + + long countByNonPublished(Integer year); + +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java index 99a44d1d..2ac24018 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java @@ -1,17 +1,7 @@ package org.devgateway.toolkit.persistence.service.data; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; -import org.devgateway.toolkit.persistence.dto.ServiceMetadata; -import org.devgateway.toolkit.persistence.service.BaseJpaService; -import org.devgateway.toolkit.persistence.service.UniquePropertyService; -import java.util.List; +public interface TetsimDatasetService extends DatasetService { -public interface TetsimDatasetService extends BaseJpaService, UniquePropertyService { - - List findAllDeleted(); - - List findAllPublishing(); - - long countByNonPublished(Integer year); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java index 69ebf968..a236872a 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java @@ -49,4 +49,5 @@ public List findAllPublishing() { public long countByNonPublished(final Integer year) { return tetsimDatasetRepository.countByNonPublished(year); } + } From 5a39d245ab05172b4cc59383f7e1c16b838b3ff6 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 25 Jul 2022 14:28:46 +0300 Subject: [PATCH 075/137] TOBACCO-952: Add action buttons to service page --- .../toolkit/forms/WebConstants.java | 4 ++ .../admin/ListServicePage$ActionPanel.html | 11 ++++ .../page/lists/admin/ListServicePage.java | 57 +++++++++++++++++++ .../lists/admin/ListServicePage.properties | 7 ++- 4 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage$ActionPanel.html diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java index ae58d7be..56d172fb 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java @@ -39,6 +39,10 @@ private WebConstants() { public static final String PARAM_YEAR = "year"; public static final String PARAM_ID = "id"; + + public static final String PARAM_SERVICE = "service"; + + public static final String PARAM_ENTITY = "entity"; public static final String V_POSITION = "vPosition"; public static final String MAX_HEIGHT = "maxPosition"; public static final String PARAM_REVISION_ID = "revisionId"; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage$ActionPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage$ActionPanel.html new file mode 100644 index 00000000..cf2e29d7 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage$ActionPanel.html @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java index d4870985..1f7ee9bf 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java @@ -11,23 +11,33 @@ *******************************************************************************/ package org.devgateway.toolkit.forms.wicket.page.lists.admin; +import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapBookmarkablePageLink; +import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; +import org.apache.wicket.Component; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.LinkTargetBlankPanel; import org.devgateway.toolkit.forms.wicket.components.table.AjaxFallbackBootstrapDataTable; import org.devgateway.toolkit.forms.wicket.page.BasePage; +import org.devgateway.toolkit.forms.wicket.page.RevisionsPage; +import org.devgateway.toolkit.forms.wicket.page.lists.AbstractListPage; import org.devgateway.toolkit.persistence.dto.ServiceMetadata; import org.wicketstuff.annotation.mount.MountPath; @@ -79,6 +89,7 @@ public void populateItem(final Item> item, final item.add(label); } }); + } @Override @@ -94,10 +105,56 @@ protected void onPageChanged() { pageRowNo = 0; } }; + + columns.add(new AbstractColumn(new StringResourceModel("actionsColumn", this, null)) { + private static final long serialVersionUID = -7447601118569862123L; + + @Override + public void populateItem(final Item> cellItem, final String componentId, + final IModel model) { + cellItem.add(getActionPanel(componentId, model)); + } + }); + add(dataTable); } protected int getPageSize() { return PAGE_SIZE; } + + public ActionPanel getActionPanel(final String id, final IModel model) { + return new ActionPanel(id, model); + } + + public class ActionPanel extends GenericPanel { + private static final long serialVersionUID = 5821419128121941939L; + + /** + * @param id + * @param model + */ + public ActionPanel(final String id, final IModel model) { + super(id, model); + + String serviceName = model.getObject().getName(); + add(getLink("dimensions", serviceName)); + add(getLink("measures", serviceName)); + add(getLink("filters", serviceName)); + add(getLink("categories", serviceName)); + } + + protected Component getLink(final String entity, final String serviceName) { + PageParameters serviceEntityPageParameters = new PageParameters(); + serviceEntityPageParameters.set(WebConstants.PARAM_SERVICE, serviceName); + serviceEntityPageParameters.set(WebConstants.PARAM_ENTITY, entity); + + BootstrapBookmarkablePageLink entityLink = new BootstrapBookmarkablePageLink<>(entity, + ListServicePage.class, serviceEntityPageParameters, Buttons.Type.Info); + entityLink.setIconType(FontAwesome5IconType.clock_s).setSize(Buttons.Size.Small) + .setLabel(new StringResourceModel(entity, ListServicePage.this, null)); + + return entityLink; + } + } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.properties index 146720a7..8f019001 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.properties @@ -1 +1,6 @@ -page.title=Service List \ No newline at end of file +page.title=Service List +actionsColumn=Actions +dimensions=Dimensions +measures=Measures +filters=Filters +categories=Categories \ No newline at end of file From ef7167ce8b2091f5d5859ff8f9899efe3b8ef032 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 3 Aug 2022 15:39:19 +0300 Subject: [PATCH 076/137] TOBACCO-957: Create page to view service dimensions --- forms/pom.xml | 6 + .../toolkit/forms/client/ClientConstants.java | 2 + .../toolkit/forms/client/DatasetClient.java | 20 ++++ ...Service.java => DatasetClientService.java} | 11 +- .../page/edit/dataset/EditCSVDatasetPage.java | 20 ++-- .../edit/dataset/EditTetsimDatasetPage.java | 17 ++- .../admin/ListServiceDimensionsPage.html | 13 +++ .../admin/ListServiceDimensionsPage.java | 107 ++++++++++++++++++ .../ListServiceDimensionsPage.properties | 4 + .../page/lists/admin/ListServicePage.java | 4 +- .../lists/admin/ServiceMetadataProvider.java | 6 +- .../forms/client/DatasetClientTest.java | 52 +++++++++ .../persistence/dto/ServiceMetadata.java | 14 ++- .../dto/ServiceMetadataDimension.java | 56 +++++++++ 14 files changed, 299 insertions(+), 33 deletions(-) rename forms/src/main/java/org/devgateway/toolkit/forms/service/{DatasetPublishingService.java => DatasetClientService.java} (92%) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties create mode 100644 forms/src/test/java/org/devgateway/toolkit/forms/client/DatasetClientTest.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadataDimension.java diff --git a/forms/pom.xml b/forms/pom.xml index 5cacf45f..c2d52c4e 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -163,6 +163,12 @@ ${wicketstuff.version} + + org.wicketstuff + wicketstuff-editable-grid + ${wicketstuff.version} + + org.apache.wicket diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java index b37fed8b..eb75cf0d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java @@ -10,6 +10,8 @@ public static final class JobStatus { public final static String PATH_HEALTH = "/actuator/health"; public final static String PATH_JOBS = "/admin/jobs"; public final static String PATH_DATASETS = "/admin/datasets"; + + public final static String PATH_DIMENSIONS = "/admin/dimensions"; public final static String PATH_CODE = "/code"; public final static String CODE_PREFIX = "tcdi-"; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java index d205f733..99f0554d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java @@ -2,6 +2,7 @@ import org.apache.commons.io.FileUtils; import org.devgateway.toolkit.persistence.dao.data.Dataset; +import org.devgateway.toolkit.persistence.dto.ServiceMetadataDimension; import org.glassfish.jersey.client.JerseyClient; import org.glassfish.jersey.client.JerseyClientBuilder; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; @@ -10,9 +11,11 @@ import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; import javax.ws.rs.client.Entity; +import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; import java.io.File; import java.io.IOException; +import java.util.List; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM_TYPE; @@ -22,6 +25,7 @@ import static org.devgateway.toolkit.forms.client.ClientConstants.CODE_PREFIX; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_CODE; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_DATASETS; +import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_DIMENSIONS; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_HEALTH; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_JOBS; @@ -157,4 +161,20 @@ public boolean isUp() { return false; } + + public List getDimensions() { + if (isUp()) { + Response dimensionsResponse = client.target(baseUrl) + .path(PATH_DIMENSIONS) + .request(APPLICATION_JSON).get(); + + if (dimensionsResponse.getStatusInfo().getFamily() == SUCCESSFUL) { + return dimensionsResponse.readEntity(new GenericType>() {}); + } + + return null; + } + + throw new RuntimeException(("Service is not up")); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java similarity index 92% rename from forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java rename to forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java index 5c3980e3..8aad1926 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java @@ -7,6 +7,7 @@ import org.devgateway.toolkit.persistence.dao.data.Dataset; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.dto.ServiceMetadata; +import org.devgateway.toolkit.persistence.dto.ServiceMetadataDimension; import org.devgateway.toolkit.persistence.service.data.CSVDatasetService; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.slf4j.Logger; @@ -28,9 +29,9 @@ import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; @Service -public class DatasetPublishingService { +public class DatasetClientService { - private static final Logger logger = LoggerFactory.getLogger(DatasetPublishingService.class); + private static final Logger logger = LoggerFactory.getLogger(DatasetClientService.class); @Autowired private TetsimDatasetService tetsimDatasetService; @@ -79,7 +80,6 @@ private void checkDatasetJobs(List datasets) { } public void publishDataset(Dataset dataset, String fileName, byte[] content) throws DataSetClientException { - String serviceURL = getDestinationService(dataset).getUrl(); DatasetClient client = new DatasetClient(serviceURL); @@ -109,4 +109,9 @@ private ServiceMetadata getDestinationService(Dataset dataset) { String destinationService = dataset.getDestinationService(); return eurekaClientService.getServiceByName(destinationService); } + + public List getDimensions(final String serviceName) { + ServiceMetadata service = eurekaClientService.getServiceByName(serviceName); + return new DatasetClient(service.getUrl()).getDimensions(); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java index 5c721701..a5fa27d4 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java @@ -8,19 +8,17 @@ import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.client.DataSetClientException; -import org.devgateway.toolkit.forms.service.DatasetPublishingService; +import org.devgateway.toolkit.forms.service.DatasetClientService; import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; import org.devgateway.toolkit.forms.wicket.components.form.FileInputBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; -import org.devgateway.toolkit.forms.wicket.components.form.TextAreaFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditStatusEntityPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListCSVDatasetPage; import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; import org.devgateway.toolkit.persistence.dao.FileMetadata; import org.devgateway.toolkit.persistence.dao.data.CSVDataset; -import org.devgateway.toolkit.persistence.dao.data.Dataset; import org.devgateway.toolkit.persistence.dto.ServiceMetadata; import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; import org.devgateway.toolkit.persistence.service.data.CSVDatasetService; @@ -30,11 +28,9 @@ import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.wicketstuff.annotation.mount.MountPath; -import java.io.File; import java.util.stream.Collectors; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; -import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.SAVED; @@ -59,7 +55,7 @@ public class EditCSVDatasetPage extends AbstractEditStatusEntityPage protected EurekaClientService eurekaClientService; @SpringBean - protected DatasetPublishingService datasetPublishingService; + protected DatasetClientService datasetClientService; @SpringBean protected SettingsUtils settingsUtils; @@ -156,12 +152,10 @@ protected void onDelete(final AjaxRequestTarget target) { @Override protected void onAfterRevertToDraft(final AjaxRequestTarget target) { - if (PUBLISHED.equals(editForm.getModelObject().getStatus())) { - try { - datasetPublishingService.unpublishDataset(editForm.getModelObject()); - } catch (DataSetClientException | Exception e) { - logger.error(e.getMessage(), e); - } + try { + datasetClientService.unpublishDataset(editForm.getModelObject()); + } catch (DataSetClientException | Exception e) { + logger.error(e.getMessage(), e); } } @@ -173,7 +167,7 @@ protected void onApprove(final AjaxRequestTarget target) { String fileName = fileMetadata.getName(); byte[] content = fileMetadata.getContent().getBytes(); - datasetPublishingService.publishDataset(dataset, fileName, content); + datasetClientService.publishDataset(dataset, fileName, content); dataset.setStatus(PUBLISHING); } catch (DataSetClientException | Exception e) { logger.error(e.getMessage(), e); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index 26be64dc..9fe1b813 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -11,7 +11,7 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.client.DataSetClientException; -import org.devgateway.toolkit.forms.service.DatasetPublishingService; +import org.devgateway.toolkit.forms.service.DatasetClientService; import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; @@ -37,7 +37,6 @@ import static org.devgateway.toolkit.forms.WebConstants.MAXIMUM_PERCENTAGE; import static org.devgateway.toolkit.forms.WebConstants.PARAM_YEAR; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; -import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.SAVED; @@ -65,7 +64,7 @@ public class EditTetsimDatasetPage extends AbstractEditStatusEntityPage + + + + +
+
+
+
+
+
+ + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java new file mode 100644 index 00000000..e473844c --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java @@ -0,0 +1,107 @@ +/******************************************************************************* + * Copyright (c) 2015 Development Gateway, Inc and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the MIT License (MIT) + * which accompanies this distribution, and is available at + * https://opensource.org/licenses/MIT + * + * Contributors: + * Development Gateway - initial API and implementation + *******************************************************************************/ +package org.devgateway.toolkit.forms.wicket.page.lists.admin; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.WebConstants; +import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.service.DatasetClientService; +import org.devgateway.toolkit.forms.wicket.page.BasePage; +import org.devgateway.toolkit.persistence.dto.ServiceMetadataDimension; +import org.springframework.beans.factory.annotation.Autowired; +import org.wicketstuff.annotation.mount.MountPath; +import org.wicketstuff.egrid.EditableGrid; +import org.wicketstuff.egrid.column.RequiredEditableTextFieldColumn; +import org.wicketstuff.egrid.provider.EditableListDataProvider; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author mpostelnicu + */ +@MountPath(value = "/dimensions") +@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) +public class ListServiceDimensionsPage extends BasePage { + + private static final long serialVersionUID = 1302443729452089592L; + + private EditableGrid editableGrid; + + private String serviceName; + + @SpringBean + private DatasetClientService datasetClientService; + + /** + * @param parameters + */ + public ListServiceDimensionsPage(final PageParameters parameters) { + super(parameters); + + this.serviceName = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + editableGrid = new EditableGrid("grid", getColumns(), + new EditableListDataProvider(getObjectList()), 5, ServiceMetadataDimension.class) { + private static final long serialVersionUID = 1L; + + @Override + protected void onError(AjaxRequestTarget target) { + target.add(feedbackPanel); + } + + @Override + protected void onCancel(AjaxRequestTarget target) { + target.add(feedbackPanel); + } + + @Override + protected void onDelete(AjaxRequestTarget target, IModel rowModel) { + target.add(feedbackPanel); + } + + @Override + protected void onSave(AjaxRequestTarget target, IModel rowModel) { + target.add(feedbackPanel); + } + + @Override + protected boolean displayAddFeature() { + return false; + } + }; + editableGrid.setTableCss("dataview table"); + add(editableGrid); + } + + private List getObjectList() { + return datasetClientService.getDimensions(serviceName); + } + + private List> getColumns() { + List> columns = new ArrayList<>(); + columns.add(new PropertyColumn<>(new Model("Name"), "name")); + columns.add(new RequiredEditableTextFieldColumn(new Model("Label"), "label")); + return columns; + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties new file mode 100644 index 00000000..fcfd3d67 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties @@ -0,0 +1,4 @@ +page.title=Service Dimensions +id=ID +name=Name +label=Label \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java index 1f7ee9bf..9e6c891d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java @@ -36,8 +36,6 @@ import org.devgateway.toolkit.forms.wicket.components.LinkTargetBlankPanel; import org.devgateway.toolkit.forms.wicket.components.table.AjaxFallbackBootstrapDataTable; import org.devgateway.toolkit.forms.wicket.page.BasePage; -import org.devgateway.toolkit.forms.wicket.page.RevisionsPage; -import org.devgateway.toolkit.forms.wicket.page.lists.AbstractListPage; import org.devgateway.toolkit.persistence.dto.ServiceMetadata; import org.wicketstuff.annotation.mount.MountPath; @@ -150,7 +148,7 @@ protected Component getLink(final String entity, final String serviceName) { serviceEntityPageParameters.set(WebConstants.PARAM_ENTITY, entity); BootstrapBookmarkablePageLink entityLink = new BootstrapBookmarkablePageLink<>(entity, - ListServicePage.class, serviceEntityPageParameters, Buttons.Type.Info); + ListServiceDimensionsPage.class, serviceEntityPageParameters, Buttons.Type.Info); entityLink.setIconType(FontAwesome5IconType.clock_s).setSize(Buttons.Size.Small) .setLabel(new StringResourceModel(entity, ListServicePage.this, null)); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMetadataProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMetadataProvider.java index cba6abfe..6f2a5eb9 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMetadataProvider.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMetadataProvider.java @@ -13,7 +13,7 @@ import java.util.List; /** - * Data provider used to provide information about the data submissions + * Data provider used to provide information about the services * * @author Viorel Chihai */ @@ -28,7 +28,7 @@ public ServiceMetadataProvider(final EurekaClientService eurekaClientService) { @Override public Iterator iterator(final long first, final long count) { - List services = eurekaClientService.findAll(); + List services = eurekaClientService.findAllWithData(); if (first > services.size()) { return Collections.emptyIterator(); @@ -54,7 +54,7 @@ public SortParam getSort() { @Override public long size() { - return eurekaClientService.findAll().size(); + return eurekaClientService.findAllWithData().size(); } @Override diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/client/DatasetClientTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/client/DatasetClientTest.java new file mode 100644 index 00000000..7f4a6bb8 --- /dev/null +++ b/forms/src/test/java/org/devgateway/toolkit/forms/client/DatasetClientTest.java @@ -0,0 +1,52 @@ +package org.devgateway.toolkit.forms.client; + + +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class DatasetClientTest { + + private DatasetClient client; + + private String baseUrl = "http://localhost:8084/"; + + @Before + public void initClient() { + this.client = new DatasetClient(baseUrl); + } + + @Test + public void testJobStatus() throws DataSetClientException { + System.out.println(client.getDatasetStatus("1142").toString()); + } + + @Test + public void testTetsimDataset() { + TetsimDataset dataset = new TetsimDataset(); + dataset.setYear(2020); + try { + System.out.println(client.publishDataset(dataset, Files.readAllBytes(Paths.get("./src/test/resources/2020_tetsim.csv")))); + } catch (DataSetClientException e) { + throw new RuntimeException(e); + } catch (FileNotFoundException e) { + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Test + public void testClient() { + DatasetClient client = new DatasetClient(baseUrl); + assertTrue(client.isUp()); + } + +} \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java index d0f596e7..3012ed84 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java @@ -1,8 +1,10 @@ package org.devgateway.toolkit.persistence.dto; import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; -public class ServiceMetadata implements Serializable { +public class ServiceMetadata implements Serializable { private String id; @@ -16,6 +18,8 @@ public class ServiceMetadata implements Serializable { private String status; + private List dimensions = new ArrayList<>(); + public String getId() { return id; } @@ -68,4 +72,12 @@ public String getStatus() { public void setStatus(final String status) { this.status = status; } + + public List getDimensions() { + return dimensions; + } + + public void setDimensions(final List dimensions) { + this.dimensions = dimensions; + } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadataDimension.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadataDimension.java new file mode 100644 index 00000000..ca6dae60 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadataDimension.java @@ -0,0 +1,56 @@ +package org.devgateway.toolkit.persistence.dto; + +import java.io.Serializable; + +public class ServiceMetadataDimension implements Serializable { + + private Long id; + + private String name; + + private String label; + + private String type; + + public ServiceMetadataDimension() { + + } + + public ServiceMetadataDimension(final Long id, final String name, final String label) { + this.id = id; + this.name = name; + this.label = label; + } + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getLabel() { + return label; + } + + public void setLabel(final String label) { + this.label = label; + } + + public String getType() { + return type; + } + + public void setType(final String type) { + this.type = type; + } +} From b0ed0c3d4de10d91076d4136bf0f79559bccc206 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 4 Aug 2022 16:06:24 +0300 Subject: [PATCH 077/137] TOBACCO-954: Add new variables for tetsim outputs --- .../toolkit/persistence/dto/TetsimOutput.java | 30 +++++++++-- .../service/tetsim/TetsimOutputService.java | 5 +- .../tetsim/TetsimOutputBaseCalculator.java | 51 ++++++++++++++++++- ...imOutputCalculatorBaselineNumbersTest.java | 12 +++++ ...mOutputOvershiftCalculatorOverallTest.java | 8 ++- .../TetsimOutputOvershiftCalculatorTest.java | 4 +- ...OutputUndershiftCalculatorOverallTest.java | 8 ++- 7 files changed, 103 insertions(+), 15 deletions(-) diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java index 98e121e2..daf3a964 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java @@ -17,12 +17,16 @@ public class TetsimOutput implements Serializable { private String shifting; - private Double consumptionLegal; + private Double legalConsumption; + + private Double legalConsumptionChange; private Double consumptionIllicit; private Double exciseRev; + private Double exciseRevChange; + private Double totalGovRev; private Double exciseBurden; @@ -71,12 +75,12 @@ public void setShifting(final String shifting) { this.shifting = shifting; } - public Double getConsumptionLegal() { - return consumptionLegal; + public Double getLegalConsumption() { + return legalConsumption; } - public void setConsumptionLegal(final Double consumptionLegal) { - this.consumptionLegal = consumptionLegal; + public void setLegalConsumption(final Double legalConsumption) { + this.legalConsumption = legalConsumption; } public Double getConsumptionIllicit() { @@ -158,4 +162,20 @@ public Double getLevy() { public void setLevy(final Double levy) { this.levy = levy; } + + public Double getLegalConsumptionChange() { + return legalConsumptionChange; + } + + public void setLegalConsumptionChange(final Double legalConsumptionChange) { + this.legalConsumptionChange = legalConsumptionChange; + } + + public Double getExciseRevChange() { + return exciseRevChange; + } + + public void setExciseRevChange(final Double exciseRevChange) { + this.exciseRevChange = exciseRevChange; + } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java index 3454b396..fec208f7 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java @@ -33,8 +33,9 @@ public class TetsimOutputService { .build(); public static final List TETSIM_CSV_FIELDS = new ImmutableList.Builder() - .add("year", "taxChange", "tobaccoProduct", "shifting", "consumptionLegal", "consumptionIllicit", "exciseRev", - "totalGovRev", "exciseBurden", "totalTaxBurden", "retailPrice", "not", "exciseTax", "vat", "levy") + .add("year", "taxChange", "tobaccoProduct", "shifting", "legalConsumption", "legalConsumptionChange", + "consumptionIllicit", "exciseRev", "exciseRevChange", "totalGovRev", "exciseBurden", + "totalTaxBurden", "retailPrice", "not", "exciseTax", "vat", "levy") .build(); @Autowired private TetsimDatasetService tetsimDatasetService; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java index 89fe5fd6..fcd3c446 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java @@ -71,9 +71,11 @@ public TetsimOutput calculate(String tobaccoProduct) { tetsimOutput.setShifting(getShifting()); tetsimOutput.setTobaccoProduct(tobaccoProduct); tetsimOutput.setTaxChange(percentageChange.intValue()); - tetsimOutput.setConsumptionLegal(calculateOutputConsumptionLegal()); + tetsimOutput.setLegalConsumption(calculateOutputLegalConsumption()); + tetsimOutput.setLegalConsumptionChange(calculateOutputLegalConsumptionChange()); tetsimOutput.setConsumptionIllicit(calculateOutputConsumptionIllicit()); tetsimOutput.setExciseRev(calculateOutputExciseRev()); + tetsimOutput.setExciseRevChange(calculateOutputExciseRevChange()); tetsimOutput.setTotalGovRev(calculateOutputTotalGovRev()); tetsimOutput.setExciseBurden(calculateOutputExciseBurden(tobaccoProduct)); @@ -87,10 +89,14 @@ public TetsimOutput calculate(String tobaccoProduct) { return tetsimOutput; } - public Double calculateOutputConsumptionLegal() { + public Double calculateOutputLegalConsumption() { return calculateTotalLegalConsumption().doubleValue(); } + public Double calculateOutputLegalConsumptionChange() { + return calculateTotalLegalConsumptionChange().doubleValue(); + } + private Double calculateOutputConsumptionIllicit() { return calculateConsumption("Illicit").doubleValue(); } @@ -99,6 +105,10 @@ private Double calculateOutputExciseRev() { return calculateTotalExciseRevenue().doubleValue(); } + private Double calculateOutputExciseRevChange() { + return calculateTotalExciseRevenueChange().doubleValue(); + } + private Double calculateOutputTotalGovRev() { return calculateTotalLegalGovernmentRevenue().doubleValue(); } @@ -391,6 +401,14 @@ public BigDecimal calculateTotalLegalConsumption() { .reduce(BigDecimal.ZERO, BigDecimal::add); } + public BigDecimal calculateTotalLegalConsumptionChange() { + BigDecimal totalLegalConsumption = calculateTotalLegalConsumption(); + BigDecimal totalLegalConsumptionBaseline = calculateBaselineTotalLegalConsumption(); + return totalLegalConsumption.divide(totalLegalConsumptionBaseline, DEFAULT_CONTEXT) + .subtract(ONE) + .multiply(HUNDRED); + } + /** * Calculate Revenue Tobacco levy: Levy per pack AT * consumption in mill packs * @param tobaccoProduct @@ -411,6 +429,16 @@ public BigDecimal calculateRevenueExciseTaxDomesticProduction(String tobaccoProd return calculateConsumption(tobaccoProduct).multiply(calculateExciseTaxDomesticProduction(tobaccoProduct)); } + public BigDecimal calculateBaselineExciseRevenueDomesticProduction(String tobaccoProduct) { + return calculateBaselineConsumption(tobaccoProduct) + .multiply(calculateBaselineExciseTaxOnDomesticProduction(tobaccoProduct)); + } + + public BigDecimal calculateBaselineExciseRevenueImportedCigarettes(String tobaccoProduct) { + return calculateBaselineConsumption(tobaccoProduct) + .multiply(calculateBaselineExciseTaxOnImported(tobaccoProduct)); + } + /** * Calculate Revenue Excise tax on imported production: excise tax (imported) per pack AT * consumption * @@ -451,6 +479,11 @@ public BigDecimal calculateTotalExciseTaxesRevenue(String tobaccoProduct) { .add(calculateRevenueExciseTaxImportedCigarettes(tobaccoProduct)); } + public BigDecimal calculateBaselineTotalExciseTaxesRevenue(String tobaccoProduct) { + return calculateBaselineExciseRevenueDomesticProduction(tobaccoProduct) + .add(calculateBaselineExciseRevenueImportedCigarettes(tobaccoProduct)); + } + /** * Calculate Total Excise Revenue: sum of excise tax */ @@ -460,6 +493,14 @@ public BigDecimal calculateTotalExciseRevenue() { .reduce(BigDecimal.ZERO, BigDecimal::add); } + public BigDecimal calculateTotalExciseRevenueChange() { + BigDecimal totalExciseRevenue = calculateTotalExciseRevenue(); + BigDecimal totalExciseRevenueBaseline = calculateBaselineTotalExciseRevenue(); + return totalExciseRevenue.divide(totalExciseRevenueBaseline, DEFAULT_CONTEXT) + .subtract(ONE) + .multiply(HUNDRED); + } + /** * Calculate Total Revenue * @@ -648,6 +689,12 @@ public BigDecimal calculateBaselineTotalLegalConsumption() { .reduce(BigDecimal.ZERO, BigDecimal::add); } + public BigDecimal calculateBaselineTotalExciseRevenue() { + return getTetsimLegalTobaccoProducts().stream() + .map(tobaccoProduct -> calculateBaselineTotalExciseTaxesRevenue(tobaccoProduct)) + .reduce(BigDecimal.ZERO, BigDecimal::add); + } + private List getTetsimLegalTobaccoProducts() { return dataset.getRetailPrice().getValues().stream() .filter(pv -> !pv.getProduct().isIllicit()) diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java index 933a3d2a..1b939c07 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java @@ -91,4 +91,16 @@ public void testBaselinePremiumTotalTaxBurden() { .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Total Tax Burden for Premium Product"); } + public void testBaselineTotalLegalConsumption() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); + assertEquals(754.4, tetsimOutputCalculator.calculateBaselineTotalLegalConsumption() + .setScale(1, ROUND_HALF_UP).doubleValue(), "Check baseline Total Legal Consumption"); + } + + public void testBaselineExciseRevenue() { + TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); + assertEquals(14167.6, tetsimOutputCalculator.calculateBaselineTotalExciseRevenue() + .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Total Excise Revenue"); + } + } \ No newline at end of file diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java index e09e92c1..287e3eb8 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java @@ -21,9 +21,11 @@ public void testOverallOutputBaseline() { TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertAll("TETSIM Overshift Baseline", - () -> assertEquals(754.40, output.getConsumptionLegal(), delta, "TETSIM Overshift - Consumption Legal"), + () -> assertEquals(754.40, output.getLegalConsumption(), delta, "TETSIM Overshift - Consumption Legal"), + () -> assertEquals(0, output.getLegalConsumptionChange(), delta, "TETSIM Overshift - Consumption Legal Change"), () -> assertEquals(395.60, output.getConsumptionIllicit(), delta, "TETSIM Overshift - Consumption Illicit"), () -> assertEquals(14167.63, output.getExciseRev(), delta, "TETSIM Overshift - Excise Revenue"), + () -> assertEquals(0, output.getExciseRevChange(), delta, "TETSIM Overshift - Excise Revenue Change"), () -> assertEquals(18051.37, output.getTotalGovRev(), delta, "TETSIM Overshift - Government Revenue"), () -> assertEquals(46.95, output.getExciseBurden(), delta, "TETSIM Overshift - Excise Burden"), () -> assertEquals(60.00, output.getTotalTaxBurden(), delta, "TETSIM Overshift - Total Tax Burden"), @@ -40,9 +42,11 @@ public void testOverallOutputWithTaxChange() { TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertAll("TETSIM Overshift With 30% Tax Change", - () -> assertEquals(648.79, output.getConsumptionLegal(), delta, "TETSIM Overshift - Consumption Legal"), + () -> assertEquals(648.79, output.getLegalConsumption(), delta, "TETSIM Overshift - Consumption Legal"), + () -> assertEquals(-13.99, output.getLegalConsumptionChange(), delta, "TETSIM Overshift - Consumption Legal Change"), () -> assertEquals(383.73, output.getConsumptionIllicit(), delta, "TETSIM Overshift - Consumption Illicit"), () -> assertEquals(15839.61, output.getExciseRev(), delta, "TETSIM Overshift - Excise Revenue"), + () -> assertEquals(11.80, output.getExciseRevChange(), delta, "TETSIM Overshift - Excise Revenue Change"), () -> assertEquals(19873.25, output.getTotalGovRev(), delta, "TETSIM Overshift - Government Revenue"), () -> assertEquals(51.10, output.getExciseBurden(), delta, "TETSIM Overshift - Excise Burden"), () -> assertEquals(64.15, output.getTotalTaxBurden(), delta, "TETSIM Overshift - Total Tax Burden"), diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java index 506b589d..ecb72bf6 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java @@ -19,14 +19,14 @@ public void setUp() { public void testConsumptionLegalNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); - assertEquals(754.4, output.getConsumptionLegal(), delta, "Check Consumption Legal TETSIM Output Overshift"); + assertEquals(754.4, output.getLegalConsumption(), delta, "Check Consumption Legal TETSIM Output Overshift"); } @Test public void testConsumptionLegalWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); - assertEquals(680.19, output.getConsumptionLegal(), delta, "Check Consumption Legal TETSIM Output Overshift (Tax Change)"); + assertEquals(680.19, output.getLegalConsumption(), delta, "Check Consumption Legal TETSIM Output Overshift (Tax Change)"); } @Test diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java index 55debe6e..e6f3632b 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java @@ -21,9 +21,11 @@ public void testOverallOutputBaseline() { TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertAll("TETSIM Undershift Baseline", - () -> assertEquals(754.40, output.getConsumptionLegal(), delta, "TETSIM Undershift - Consumption Legal"), + () -> assertEquals(754.40, output.getLegalConsumption(), delta, "TETSIM Undershift - Consumption Legal"), + () -> assertEquals(0, output.getLegalConsumptionChange(), delta, "TETSIM Undershift - Consumption Legal Change"), () -> assertEquals(395.60, output.getConsumptionIllicit(), delta, "TETSIM Undershift - Consumption Illicit"), () -> assertEquals(14167.63, output.getExciseRev(), delta, "TETSIM Undershift - Excise Revenue"), + () -> assertEquals(0, output.getExciseRevChange(), delta, "TETSIM Undershift - Excise Revenue Change"), () -> assertEquals(18051.37, output.getTotalGovRev(), delta, "TETSIM Undershift - Government Revenue"), () -> assertEquals(46.95, output.getExciseBurden(), delta, "TETSIM Undershift - Excise Burden"), () -> assertEquals(60.00, output.getTotalTaxBurden(), delta, "TETSIM Undershift - Total Tax Burden"), @@ -40,9 +42,11 @@ public void testOverallOutputWithTaxChange() { TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); assertAll("TETSIM Undershift With 30% Tax Change", - () -> assertEquals(694.62, output.getConsumptionLegal(), delta, "TETSIM Undershift - Consumption Legal"), + () -> assertEquals(694.62, output.getLegalConsumption(), delta, "TETSIM Undershift - Consumption Legal"), + () -> assertEquals(-7.92, output.getLegalConsumptionChange(), delta, "TETSIM Undershift - Consumption Legal Change"), () -> assertEquals(390.14, output.getConsumptionIllicit(), delta, "TETSIM Undershift - Consumption Illicit"), () -> assertEquals(16958.46, output.getExciseRev(), delta, "TETSIM Undershift - Excise Revenue"), + () -> assertEquals(19.69, output.getExciseRevChange(), delta, "TETSIM Undershift - Excise Revenue Change"), () -> assertEquals(20945.90, output.getTotalGovRev(), delta, "TETSIM Undershift - Government Revenue"), () -> assertEquals(54.82, output.getExciseBurden(), delta, "TETSIM Undershift - Excise Burden"), () -> assertEquals(67.86, output.getTotalTaxBurden(), delta, "TETSIM Undershift - Total Tax Burden"), From ddf878220c9d45941932421869b0954014f6d211 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Tue, 6 Sep 2022 15:57:03 +0300 Subject: [PATCH 078/137] TOBACCO-986: Remove the hardcoded country name and retreive from DB --- .../toolkit/forms/wicket/page/BasePage.java | 6 +++++- .../forms/wicket/page/CategoriesHomepage.java | 14 ++++++++++++++ .../wicket/page/CategoriesHomepage.properties | 2 +- .../forms/wicket/page/DatasetsHomepage.java | 12 ++++++++++++ .../forms/wicket/page/DatasetsHomepage.properties | 2 +- .../forms/wicket/page/EditAdminSettingsPage.html | 5 +++++ .../forms/wicket/page/EditAdminSettingsPage.java | 2 ++ .../wicket/page/EditAdminSettingsPage.properties | 3 ++- .../toolkit/forms/wicket/page/Homepage.java | 11 +++++++++++ .../toolkit/forms/wicket/page/Homepage.properties | 3 +-- .../page/lists/dataset/ListTetsimDatasetPage.java | 6 ++++++ .../lists/dataset/ListTetsimDatasetPage.properties | 2 +- .../toolkit/persistence/application.properties | 2 +- .../toolkit/persistence/dao/AdminSettings.java | 10 ++++++++++ 14 files changed, 72 insertions(+), 8 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 9f6f3257..677bac09 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -161,11 +161,15 @@ public BasePage(final PageParameters parameters) { mainFooter = new Footer("mainFooter"); add(mainFooter); - pageTitle = new Label("pageTitle", new ResourceModel("page.title")); + pageTitle = getPageTitle(); add(pageTitle); } + protected Label getPageTitle() { + return new Label("pageTitle", new ResourceModel("page.title")); + } + protected NotificationPanel createFeedbackPanel() { final NotificationPanel notificationPanel = new NotificationPanel("feedback"); notificationPanel.setOutputMarkupId(true); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.java index 848be210..fca31d61 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.java @@ -3,12 +3,17 @@ import com.google.common.collect.ImmutableList; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.Model; +import org.apache.wicket.model.ResourceModel; +import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; import org.devgateway.toolkit.forms.wicket.page.lists.ListTobaccoProductPage; +import org.devgateway.toolkit.web.util.SettingsUtils; import org.wicketstuff.annotation.mount.MountPath; import java.util.List; @@ -20,6 +25,9 @@ @MountPath public class CategoriesHomepage extends BasePage { + @SpringBean + protected SettingsUtils settingsUtils; + private static final List LINKS = new ImmutableList.Builder() .add(new BigLinkDefinition("tobaccoProducts", ListTobaccoProductPage.class, FontAwesome5IconType.smoking_s)) @@ -30,4 +38,10 @@ public CategoriesHomepage(final PageParameters parameters) { add(new BigLinksPanel("links", Model.ofList(LINKS))); } + + @Override + protected Label getPageTitle() { + return new Label("pageTitle", new StringResourceModel("page.title", this, + Model.of(settingsUtils.getSetting()))); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties index 6ed88622..8e44e1eb 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties @@ -1,4 +1,4 @@ -page.title=South Africa Categories +page.title=${countryName} Categories tobaccoProducts.label=Tobacco Products tobaccoProducts.desc=Manage the tobacco products used in the system \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.java index 74c1ccc3..a9f5ac8d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.java @@ -17,13 +17,17 @@ import com.google.common.collect.ImmutableList; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListCSVDatasetPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; +import org.devgateway.toolkit.web.util.SettingsUtils; import org.wicketstuff.annotation.mount.MountPath; import java.util.List; @@ -35,6 +39,9 @@ @MountPath public class DatasetsHomepage extends BasePage { + @SpringBean + protected SettingsUtils settingsUtils; + private static final List LINKS = new ImmutableList.Builder() .add(new BigLinkDefinition("tetsimDataset", ListTetsimDatasetPage.class, FontAwesome5IconType.percentage_s)) @@ -47,4 +54,9 @@ public DatasetsHomepage(final PageParameters parameters) { add(new BigLinksPanel("links", Model.ofList(LINKS))); } + + protected Label getPageTitle() { + return new Label("pageTitle", new StringResourceModel("page.title", this, + Model.of(settingsUtils.getSetting()))); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties index e3dbb02b..279ab4cb 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DatasetsHomepage.properties @@ -1,4 +1,4 @@ -page.title=South Africa Datasets +page.title=${countryName} Datasets tetsimDataset.label=TETSIM tetsimDataset.desc=Manage the TETSIM Dataset diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html index d9f0152e..7318bee7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html @@ -32,6 +32,11 @@
+
+
+
+
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java index b269c888..d28910d6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java @@ -73,6 +73,8 @@ protected void onInitialize() { currency.required(); editForm.add(currency); + editForm.add(new TextFieldBootstrapFormComponent<>("countryName")); + autosaveTime = new TextFieldBootstrapFormComponent<>("autosaveTime"); autosaveTime.integer().required(); autosaveTime.getField().add(RangeValidator.range(0, 60)); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties index 8eeab44e..9a5818fe 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties @@ -5,4 +5,5 @@ appSettingsTitle=Application Settings rebootServer.label=Enable server reboot warning autosaveTime.label=Autosave Time (minutes) autosaveTime.help=Set to 0 to disable -defaultCurrency.label=Default Currency \ No newline at end of file +defaultCurrency.label=Default Currency +countryName.label=Country Name \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java index 8f95c00c..f9cfd5db 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java @@ -3,11 +3,15 @@ import com.google.common.collect.ImmutableList; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; +import org.devgateway.toolkit.web.util.SettingsUtils; import java.util.List; @@ -18,6 +22,8 @@ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) public class Homepage extends BasePage { + @SpringBean + protected SettingsUtils settingsUtils; private static final List LINKS = new ImmutableList.Builder() .add(new BigLinkDefinition("datasets", DatasetsHomepage.class, FontAwesome5IconType.table_s)) .add(new BigLinkDefinition("categories", CategoriesHomepage.class, FontAwesome5IconType.list_alt_r)) @@ -32,4 +38,9 @@ public Homepage(final PageParameters parameters) { add(new BigLinksPanel("links", Model.ofList(LINKS))); } + + protected Label getPageTitle() { + return new Label("pageTitle", new StringResourceModel("page.title", this, + Model.of(settingsUtils.getSetting()))); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties index 1cde229f..2fd272e8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties @@ -1,5 +1,4 @@ -page.title=South Africa Data Admin Module -welcome=South Africa Data Admin Module +page.title=${countryName} Data Admin Module datasets.label=Datasets datasets.desc=Upload, edit, revert to draft and validate Datasets diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java index b3150e9a..dc266fff 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java @@ -51,6 +51,7 @@ public class ListTetsimDatasetPage extends AbstractListPage { private static final long serialVersionUID = -324298525712620234L; @SpringBean protected SettingsUtils settingsUtils; + protected Select2ChoiceBootstrapFormComponent year; protected Fragment yearSelectorFragment; private Integer selectedYear; @@ -193,4 +194,9 @@ protected Component getRevisionsLink(final TetsimDataset entity) { public JpaFilterState newFilterState() { return new TetsimDatasetFilterState(); } + + protected Label getPageTitle() { + return new Label("pageTitle", new StringResourceModel("page.title", this, + Model.of(settingsUtils.getSetting()))); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties index 214c43e5..0612db49 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties @@ -1,4 +1,4 @@ -page.title=South Africa TETSIM +page.title=${countryName} TETSIM year=Year lastModifiedBy=Editor lastModifiedDate=Latest Modification diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties index 6549bea8..16ee44ce 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties @@ -44,7 +44,7 @@ spring.datasource.min-idle=8 spring.datasource.initial-size=20 spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.username=postgres -spring.datasource.password=admin +spring.datasource.password=postgres spring.datasource.jdbc-url=jdbc:postgresql://postgresql:5432/tcdi-admin spring.datasource.transaction-isolation=2 dg-toolkit.datasource.jndi-name=toolkitDS diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java index 05c4997d..de73ca52 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java @@ -30,6 +30,8 @@ public class AdminSettings extends AbstractAuditableEntity { private Currency defaultCurrency; + private String countryName; + @Override public AbstractAuditableEntity getParent() { return null; @@ -70,4 +72,12 @@ public Currency getDefaultCurrency() { public void setDefaultCurrency(final Currency defaultCurrency) { this.defaultCurrency = defaultCurrency; } + + public String getCountryName() { + return countryName; + } + + public void setCountryName(final String countryName) { + this.countryName = countryName; + } } From 9cd37ee36cbd343ca30b184054285d0080e71a88 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Tue, 6 Sep 2022 16:35:16 +0300 Subject: [PATCH 079/137] TOBACCO-988: Rename admin menu --- .../devgateway/toolkit/forms/wicket/page/BasePage.java | 8 ++++---- .../toolkit/forms/wicket/page/BasePage.properties | 2 +- .../toolkit/forms/wicket/page/Homepage.properties | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 677bac09..f8a0389a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -249,7 +249,7 @@ protected NavbarButton newHomeMenu() { protected NavbarDropDownButton newAdminMenu() { // admin menu - NavbarDropDownButton adminMenu = new NavbarDropDownButton(new StringResourceModel("navbar.admin", this, null)) { + NavbarDropDownButton configurationsMenu = new NavbarDropDownButton(new StringResourceModel("navbar.configurations", this, null)) { private static final long serialVersionUID = 1L; @Override @@ -301,10 +301,10 @@ protected List newSubMenuButtons(final String arg0) { } }; - adminMenu.setIconType(FontAwesome5IconType.cog_s); - MetaDataRoleAuthorizationStrategy.authorize(adminMenu, RENDER, ROLE_USER); + configurationsMenu.setIconType(FontAwesome5IconType.cog_s); + MetaDataRoleAuthorizationStrategy.authorize(configurationsMenu, RENDER, ROLE_USER); - return adminMenu; + return configurationsMenu; } protected NavbarButton newDatasetsMenu() { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties index 6916443c..9e670a4b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties @@ -14,7 +14,7 @@ navbar.logout=Logout navbar.users=Users navbar.groups=Groups navbar.services=Services -navbar.admin=Admin +navbar.configurations=Configurations navbar.datasets=Datasets navbar.tetsim=TETSIM navbar.prevalence=Prevalence diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties index 2fd272e8..5d3c1002 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties @@ -1,4 +1,4 @@ -page.title=${countryName} Data Admin Module +page.title=${countryName} TCDI Admin Module datasets.label=Datasets datasets.desc=Upload, edit, revert to draft and validate Datasets From ecee5f7b98f5e3ad9ab90a6d28a023a5cfb97125 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 12 Sep 2022 15:35:36 +0300 Subject: [PATCH 080/137] TOBACCO-989: Create the data page with icons --- .../wicket/components/BigLinkDefinition.java | 16 ++++ .../wicket/components/BigLinksPanel.java | 3 +- .../components/buttons/HomepageButton.java | 9 +- .../toolkit/forms/wicket/page/BasePage.java | 51 ++---------- .../forms/wicket/page/BasePage.properties | 2 +- .../wicket/page/ConfigurationsHomepage.html | 12 +++ .../wicket/page/ConfigurationsHomepage.java | 49 +++++++++++ .../page/ConfigurationsHomepage.properties | 10 +++ .../toolkit/forms/wicket/page/DataPage.html | 12 +++ .../toolkit/forms/wicket/page/DataPage.java | 83 +++++++++++++++++++ .../forms/wicket/page/DataPage.properties | 1 + .../forms/wicket/page/DataServicePage.html | 12 +++ .../forms/wicket/page/DataServicePage.java | 68 +++++++++++++++ .../wicket/page/DataServicePage.properties | 13 +++ .../toolkit/forms/wicket/page/Homepage.java | 6 +- .../forms/wicket/page/Homepage.properties | 11 +-- .../admin/ListServiceDimensionsPage.java | 4 +- .../dto/ServiceMetadataDimension.java | 23 +++++ 18 files changed, 325 insertions(+), 60 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinkDefinition.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinkDefinition.java index 63fea463..7e080d64 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinkDefinition.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinkDefinition.java @@ -4,6 +4,7 @@ import org.apache.wicket.Page; import org.apache.wicket.model.IModel; import org.apache.wicket.model.ResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; import java.io.Serializable; @@ -16,10 +17,21 @@ public class BigLinkDefinition implements Serializable { private final Class pageClass; private final IconType iconType; + private final PageParameters pageParameters; + public BigLinkDefinition(String id, Class pageClass, IconType iconType) { this.id = id; this.pageClass = pageClass; this.iconType = iconType; + this.pageParameters = new PageParameters(); + } + + public BigLinkDefinition(String id, Class pageClass, PageParameters pageParameters, + IconType iconType) { + this.id = id; + this.pageClass = pageClass; + this.iconType = iconType; + this.pageParameters = pageParameters; } public IModel getLabelModel() { @@ -37,4 +49,8 @@ public Class getPageClass() { public IconType getIconType() { return iconType; } + + public PageParameters getPageParameters() { + return pageParameters; + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.java index 9ce32297..2bf7b463 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.java @@ -27,7 +27,8 @@ protected void populateItem(ListItem item) { BigLinkDefinition def = item.getModelObject(); item.add(new AttributeAppender("class", "col-md-" + colSpan, " ")); item.add(new HomepageButton<>("button", - def.getPageClass(), def.getLabelModel(), def.getDescModel(), def.getIconType())); + def.getPageClass(), def.getPageParameters(), + def.getLabelModel(), def.getDescModel(), def.getIconType())); } }); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/HomepageButton.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/HomepageButton.java index 33228ef5..9c727459 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/HomepageButton.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/HomepageButton.java @@ -8,6 +8,7 @@ import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.IModel; import org.apache.wicket.model.ResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; public class HomepageButton extends BootstrapBookmarkablePageLink { @@ -18,7 +19,13 @@ public

HomepageButton(final String componentId, final Class

public

HomepageButton(String componentId, Class

pageClass, IModel labelModel, IModel descriptionModel, IconType iconType) { - super(componentId, pageClass, Buttons.Type.Default); + this(componentId, pageClass, new PageParameters(), labelModel, descriptionModel, iconType); + } + + public

HomepageButton(String componentId, Class

pageClass, PageParameters pageParameters, + IModel labelModel, + IModel descriptionModel, IconType iconType) { + super(componentId, pageClass, pageParameters, Buttons.Type.Default); setLabel(labelModel == null ? new ResourceModel(componentId + ".label") diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index f8a0389a..7035d415 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -246,7 +246,7 @@ protected NavbarButton newHomeMenu() { return homeMenu; } - protected NavbarDropDownButton newAdminMenu() { + protected NavbarDropDownButton newConifugrationsMenu() { // admin menu NavbarDropDownButton configurationsMenu = new NavbarDropDownButton(new StringResourceModel("navbar.configurations", this, null)) { @@ -263,34 +263,6 @@ protected List newSubMenuButtons(final String arg0) { new StringResourceModel("navbar.groups", this, null)) .setIconType(FontAwesome5IconType.tags_s)); - list.add(new MenuBookmarkablePageLink(ListServicePage.class, null, - new StringResourceModel("navbar.services", this, null)) - .setIconType(FontAwesome5IconType.servicestack)); - -// list.add(new MenuBookmarkablePageLink(ListTestFormPage.class, null, -// new StringResourceModel("navbar.testcomponents", this, null)) -// .setIconType(FontAwesome5IconType.android)); - -// list.add(new MenuDivider()); -// -// final BootstrapBookmarkablePageLink swagger = new MenuBookmarkablePageLink(SwaggerPage.class, -// new StringResourceModel("navbar.swagger", BasePage.this, null)) -// .setIconType(FontAwesome5IconType.code_s); -// MetaDataRoleAuthorizationStrategy.authorize(swagger, Component.RENDER, -// SecurityConstants.Roles.ROLE_ADMIN); -// list.add(swagger); -// -// final BootstrapBookmarkablePageLink javamelody = new MenuBookmarkablePageLink( -// JavamelodyPage.class, new StringResourceModel("navbar.javamelody", -// BasePage.this, null)).setIconType(FontAwesome5IconType.eye_s); -// MetaDataRoleAuthorizationStrategy.authorize(javamelody, Component.RENDER, -// SecurityConstants.Roles.ROLE_ADMIN); -// list.add(javamelody); -// -// list.add(new MenuBookmarkablePageLink(SpringEndpointsPage.class, null, -// new StringResourceModel("navbar.springendpoints", this, null)) -// .setIconType(FontAwesome5IconType.anchor_s)); -// list.add(new MenuDivider()); list.add(new MenuBookmarkablePageLink(EditAdminSettingsPage.class, @@ -307,9 +279,9 @@ protected List newSubMenuButtons(final String arg0) { return configurationsMenu; } - protected NavbarButton newDatasetsMenu() { - NavbarButton dataSetsMenu = new NavbarButton(DatasetsHomepage.class, - new StringResourceModel("navbar.datasets", this, null)) + protected NavbarButton newDataMenu() { + NavbarButton dataSetsMenu = new NavbarButton(DataPage.class, + new StringResourceModel("navbar.data", this, null)) .setIconType(FontAwesome5IconType.table_s); dataSetsMenu.setIconType(FontAwesome5IconType.table_s); @@ -318,16 +290,6 @@ protected NavbarButton newDatasetsMenu() { return dataSetsMenu; } - protected NavbarButton newCategoriesMenu() { - NavbarButton categoriesMenu = new NavbarButton(CategoriesHomepage.class, - new StringResourceModel("navbar.categories", this, null)) - .setIconType(FontAwesome5IconType.list_alt_r); - - MetaDataRoleAuthorizationStrategy.authorize(categoriesMenu, RENDER, ROLE_USER); - - return categoriesMenu; - } - /** * creates a new {@link Navbar} instance * @@ -347,9 +309,8 @@ protected Navbar newNavbar(final String markupId) { navbar.setBrandImage(new PackageResourceReference(BaseStyles.class, "assets/img/tcdi-horizontal-logo.svg"), new StringResourceModel("brandImageAltText", this, null)); - navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.RIGHT, newHomeMenu(), newAdminMenu(), - newDatasetsMenu(), newCategoriesMenu(), - newAccountMenu(), newLogoutMenu())); + navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.RIGHT, newHomeMenu(), newConifugrationsMenu(), + newDataMenu(), newAccountMenu(), newLogoutMenu())); // navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.RIGHT, newLanguageMenu())); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties index 9e670a4b..dd4fb2f5 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties @@ -15,7 +15,7 @@ navbar.users=Users navbar.groups=Groups navbar.services=Services navbar.configurations=Configurations -navbar.datasets=Datasets +navbar.data=Data navbar.tetsim=TETSIM navbar.prevalence=Prevalence navbar.policy=Policy diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.html new file mode 100644 index 00000000..2455643c --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.html @@ -0,0 +1,12 @@ + + + + + Configurations + + + +

+ + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java new file mode 100644 index 00000000..d9f1a17a --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java @@ -0,0 +1,49 @@ +package org.devgateway.toolkit.forms.wicket.page; + +import com.google.common.collect.ImmutableList; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; +import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; +import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; +import org.devgateway.toolkit.forms.wicket.page.lists.ListGroupPage; +import org.devgateway.toolkit.forms.wicket.page.lists.ListUserPage; +import org.devgateway.toolkit.web.util.SettingsUtils; + +import java.util.List; + +/** + * @author mpostelnicu + * + */ +@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) +public class ConfigurationsHomepage extends BasePage { + + @SpringBean + protected SettingsUtils settingsUtils; + + private static final List LINKS = new ImmutableList.Builder() + .add(new BigLinkDefinition("users", ListUserPage.class, FontAwesome5IconType.users_s)) + .add(new BigLinkDefinition("groups", ListGroupPage.class, FontAwesome5IconType.tags_s)) + .add(new BigLinkDefinition("settings", EditAdminSettingsPage.class, FontAwesome5IconType.cogs_s)) + .build(); + + /** + * @param parameters + */ + public ConfigurationsHomepage(final PageParameters parameters) { + super(parameters); + + add(new BigLinksPanel("links", Model.ofList(LINKS))); + } + + protected Label getPageTitle() { + return new Label("pageTitle", new StringResourceModel("page.title", this, + Model.of(settingsUtils.getSetting()))); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.properties new file mode 100644 index 00000000..086d7c46 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.properties @@ -0,0 +1,10 @@ +page.title=Configurations + +users.label=Users +users.desc=Manage the Users + +groups.label=Groups +groups.desc=Manage the Groups + +settings.label=Settings +settings.desc=Manage the general settings of the system \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.html new file mode 100644 index 00000000..b0e96a79 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.html @@ -0,0 +1,12 @@ + + + + + Datasets + + + +
+
+ + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java new file mode 100644 index 00000000..88e01c1b --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java @@ -0,0 +1,83 @@ +/** + * Copyright (c) 2015 Development Gateway, Inc and others. + *

+ * All rights reserved. This program and the accompanying materials + * are made available under the terms of the MIT License (MIT) + * which accompanies this distribution, and is available at + * https://opensource.org/licenses/MIT + *

+ * Contributors: + * Development Gateway - initial API and implementation + */ +/** + * + */ +package org.devgateway.toolkit.forms.wicket.page; + +import com.google.common.collect.ImmutableList; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; +import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.service.EurekaClientService; +import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; +import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; +import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListCSVDatasetPage; +import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; +import org.devgateway.toolkit.persistence.dto.ServiceMetadata; +import org.devgateway.toolkit.web.util.SettingsUtils; +import org.wicketstuff.annotation.mount.MountPath; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Viorel Chihai + */ +@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) +@MountPath +public class DataPage extends BasePage { + + @SpringBean + protected SettingsUtils settingsUtils; + + @SpringBean + private EurekaClientService eurekaClientService; + + public DataPage(final PageParameters parameters) { + super(parameters); + + List services = eurekaClientService.findAllWithData(); + + List links = new ArrayList<>(); + for (ServiceMetadata service : services) { + PageParameters pageParameters = new PageParameters(); + pageParameters.add("service", service.getName()); + links.add(new BigLinkDefinition(service.getId(), DataServicePage.class, pageParameters, + FontAwesome5IconType.table_s) { + + @Override + public IModel getLabelModel() { + return Model.of(service.getName()); + } + + @Override + public IModel getDescModel() { + return Model.of(service.getDescription()); + } + }); + } + + add(new BigLinksPanel("links", Model.ofList(links))); + } + + protected Label getPageTitle() { + return new Label("pageTitle", new StringResourceModel("page.title", this, + Model.of(settingsUtils.getSetting()))); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.properties new file mode 100644 index 00000000..bf0a3b25 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.properties @@ -0,0 +1 @@ +page.title=${countryName} Data \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.html new file mode 100644 index 00000000..b0e96a79 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.html @@ -0,0 +1,12 @@ + + + + + Datasets + + + +

+ + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java new file mode 100644 index 00000000..1fddb222 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java @@ -0,0 +1,68 @@ +/** + * Copyright (c) 2015 Development Gateway, Inc and others. + *

+ * All rights reserved. This program and the accompanying materials + * are made available under the terms of the MIT License (MIT) + * which accompanies this distribution, and is available at + * https://opensource.org/licenses/MIT + *

+ * Contributors: + * Development Gateway - initial API and implementation + */ +/** + * + */ +package org.devgateway.toolkit.forms.wicket.page; + +import de.agilecoders.wicket.core.markup.html.bootstrap.image.IconType; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; +import org.apache.wicket.Page; +import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; +import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; +import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceDimensionsPage; +import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListCSVDatasetPage; +import org.wicketstuff.annotation.mount.MountPath; + +import java.util.ArrayList; +import java.util.List; + +import static org.devgateway.toolkit.forms.WebConstants.PARAM_ENTITY; +import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; + +/** + * @author Viorel Chihai + */ +@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) +@MountPath +public class DataServicePage extends BasePage { + + public DataServicePage(final PageParameters parameters) { + super(parameters); + + List links = new ArrayList<>(); + links.add(getEntityLink("datasets", ListCSVDatasetPage.class, FontAwesome5IconType.database_s)); + links.add(getEntityLink("measures", ListServiceDimensionsPage.class, FontAwesome5IconType.ruler_s)); + links.add(getEntityLink("dimensions", ListServiceDimensionsPage.class, FontAwesome5IconType.chart_bar_s)); + links.add(getEntityLink("categories", ListServiceDimensionsPage.class, FontAwesome5IconType.layer_group_s)); + + add(new BigLinksPanel("links", Model.ofList(links))); + } + + private BigLinkDefinition getEntityLink(final String entity, Class pageClass, IconType iconType) { + PageParameters pageParams = new PageParameters(); + pageParams.set(PARAM_SERVICE, getPageParameters().get(PARAM_SERVICE).toString()); + pageParams.set(PARAM_ENTITY, entity); + + return new BigLinkDefinition(entity, pageClass, pageParams, iconType); + } + + protected Label getPageTitle() { + String service = getPageParameters().get("service").toString(); + return new Label("pageTitle", Model.of(service)); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties new file mode 100644 index 00000000..47f6d542 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties @@ -0,0 +1,13 @@ +page.title=${serviceName} + +datasets.label=Data entry or upload +datasets.desc=Manage datasets + +measures.label=Measures +measures.desc=Manage measures + +dimensions.label=Dimensions +dimensions.desc=Manage dimensions + +categories.label=Categories +categories.desc=Manage categories \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java index f9cfd5db..891e021a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java @@ -11,6 +11,7 @@ import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; +import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServicePage; import org.devgateway.toolkit.web.util.SettingsUtils; import java.util.List; @@ -25,9 +26,8 @@ public class Homepage extends BasePage { @SpringBean protected SettingsUtils settingsUtils; private static final List LINKS = new ImmutableList.Builder() - .add(new BigLinkDefinition("datasets", DatasetsHomepage.class, FontAwesome5IconType.table_s)) - .add(new BigLinkDefinition("categories", CategoriesHomepage.class, FontAwesome5IconType.list_alt_r)) - .add(new BigLinkDefinition("settings", EditAdminSettingsPage.class, FontAwesome5IconType.cogs_s)) + .add(new BigLinkDefinition("data", DataPage.class, FontAwesome5IconType.table_s)) + .add(new BigLinkDefinition("configurations", ConfigurationsHomepage.class, FontAwesome5IconType.cogs_s)) .build(); /** diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties index 5d3c1002..bafcdb2f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties @@ -1,10 +1,7 @@ page.title=${countryName} TCDI Admin Module -datasets.label=Datasets -datasets.desc=Upload, edit, revert to draft and validate Datasets +data.label=Data +data.desc=Upload, edit, revert to draft and validate Data -categories.label=Categories -categories.desc=Edit categories in the system like Tobacco Products - -settings.label=Settings -settings.desc=Manage the general settings of the system \ No newline at end of file +configurations.label=Configurations +configurations.desc=Manage the general configurations of the system \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java index e473844c..d5181803 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java @@ -100,8 +100,8 @@ private List getObjectList() { private List> getColumns() { List> columns = new ArrayList<>(); - columns.add(new PropertyColumn<>(new Model("Name"), "name")); - columns.add(new RequiredEditableTextFieldColumn(new Model("Label"), "label")); + columns.add(new PropertyColumn<>(new Model("Name"), "code")); + columns.add(new RequiredEditableTextFieldColumn(new Model("Label"), "value")); return columns; } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadataDimension.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadataDimension.java index ca6dae60..5b024116 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadataDimension.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadataDimension.java @@ -1,7 +1,10 @@ package org.devgateway.toolkit.persistence.dto; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import java.io.Serializable; +@JsonIgnoreProperties({"position", "labels", "descriptions", "field", "fieldType", "aClass", "categoryStyle"}) public class ServiceMetadataDimension implements Serializable { private Long id; @@ -12,6 +15,10 @@ public class ServiceMetadataDimension implements Serializable { private String type; + private String code; + + private String value; + public ServiceMetadataDimension() { } @@ -53,4 +60,20 @@ public String getType() { public void setType(final String type) { this.type = type; } + + public String getCode() { + return code; + } + + public void setCode(final String code) { + this.code = code; + } + + public String getValue() { + return value; + } + + public void setValue(final String value) { + this.value = value; + } } From 0ec1cfb1879a0911024440d9ea05393a01b867d4 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 15 Sep 2022 16:47:23 +0300 Subject: [PATCH 081/137] TOBACCO-998: Update the datasets pages --- .../toolkit/forms/WebConstants.java | 7 ++ .../forms/service/DatasetClientService.java | 6 +- .../forms/service/EurekaClientService.java | 23 ++----- .../table/filter/CSVDatasetFilterState.java | 15 ++++ .../filter/TetsimDatasetFilterState.java | 15 ++++ .../toolkit/forms/wicket/page/DataPage.html | 1 + .../toolkit/forms/wicket/page/DataPage.java | 21 +++++- .../forms/wicket/page/DataPage.properties | 4 +- .../forms/wicket/page/DataServicePage.java | 34 ++++++++-- .../wicket/page/edit/AbstractEditPage.java | 12 +++- .../page/edit/dataset/EditCSVDatasetPage.java | 54 +++++++-------- .../edit/dataset/EditTetsimDatasetPage.java | 68 ++++++++----------- .../wicket/page/lists/AbstractListPage.java | 9 ++- .../lists/dataset/ListCSVDatasetPage.java | 28 +++++++- .../dataset/ListCSVDatasetPage.properties | 3 +- .../lists/dataset/ListTetsimDatasetPage.java | 21 +++++- .../dataset/ListTetsimDatasetPage.properties | 2 +- 17 files changed, 215 insertions(+), 108 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java index 56d172fb..9629b3c8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java @@ -51,6 +51,10 @@ private WebConstants() { public static final String LANGUAGE_PARAM = "lang"; + public static final String SERVICE_DATA_TYPE = "data"; + + public static final String SERVICE_TETSIM_TYPE = "tetsim"; + public static final class StringValidators { public static final StringValidator MAXIMUM_LENGTH_VALIDATOR_STD_DEFAULT_TEXT = StringValidator.maximumLength(DBConstants.STD_DEFAULT_TEXT_LENGTH); @@ -67,4 +71,7 @@ public static final class StringValidators { // to change the src code anyway. public static final List AVAILABLE_LOCALES = Collections.unmodifiableList(Arrays.asList(new Locale("en"))); + public static final List ALLOWED_SERVICES_TYPES = Collections.unmodifiableList( + Arrays.asList(SERVICE_DATA_TYPE, SERVICE_TETSIM_TYPE)); + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java index 8aad1926..8d69542b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java @@ -54,7 +54,7 @@ public void triggerCheckDatasetsJob() { private void checkDatasetJobs(List datasets) { datasets.forEach(d -> { - ServiceMetadata serviceMetadata = eurekaClientService.getServiceByName(d.getDestinationService()); + ServiceMetadata serviceMetadata = eurekaClientService.findByName(d.getDestinationService()); DatasetClient client = new DatasetClient(serviceMetadata.getUrl()); String status = client.getDatasetJobStatus(CODE_PREFIX + d.getId()).getStatus(); if (COMPLETED.equals(status)) { @@ -107,11 +107,11 @@ public void unpublishDataset(Dataset dataset) throws DataSetClientException { private ServiceMetadata getDestinationService(Dataset dataset) { String destinationService = dataset.getDestinationService(); - return eurekaClientService.getServiceByName(destinationService); + return eurekaClientService.findByName(destinationService); } public List getDimensions(final String serviceName) { - ServiceMetadata service = eurekaClientService.getServiceByName(serviceName); + ServiceMetadata service = eurekaClientService.findByName(serviceName); return new DatasetClient(service.getUrl()).getDimensions(); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java index 5daf700c..cbd4cf90 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java @@ -8,11 +8,11 @@ import org.springframework.stereotype.Service; import java.util.ArrayList; -import java.util.HashSet; import java.util.List; -import java.util.Set; import java.util.stream.Collectors; +import static org.devgateway.toolkit.forms.WebConstants.ALLOWED_SERVICES_TYPES; + @Service public class EurekaClientService { @@ -39,26 +39,11 @@ public List findAll() { public List findAllWithData() { return findAll().stream() - .filter(s -> "data".equals(s.getType())) + .filter(s -> ALLOWED_SERVICES_TYPES.contains(s.getType())) .collect(Collectors.toList()); } - - public Set getServiceByMetadataType(String type) { - Set services = new HashSet<>(); - discoveryClient.getServices().forEach(s -> { - System.out.print(s + "-"); - discoveryClient.getInstances(s).stream().forEach(instance -> { - if ("data".equals(instance.getMetadata().getOrDefault("type", ""))) { - services.add(s); - } - }); - }); - - return services; - } - - public ServiceMetadata getServiceByName(String name) { + public ServiceMetadata findByName(String name) { return findAll().stream() .filter(s -> s.getName().equals(name)) .findFirst().get(); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java index 631e0185..3a9af2b4 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java @@ -1,7 +1,9 @@ package org.devgateway.toolkit.forms.wicket.components.table.filter; +import org.apache.commons.lang3.StringUtils; import org.devgateway.toolkit.persistence.dao.AbstractStatusAuditableEntity_; import org.devgateway.toolkit.persistence.dao.data.CSVDataset; +import org.devgateway.toolkit.persistence.dao.data.CSVDataset_; import org.devgateway.toolkit.persistence.repository.SpecificationContext; import org.springframework.data.jpa.domain.Specification; @@ -18,6 +20,8 @@ public class CSVDatasetFilterState extends JpaFilterState { private static final long serialVersionUID = -3419455862012018431L; + private String service; + @Override public Specification getSpecification() { return (root, query, cb) -> { @@ -26,8 +30,19 @@ public Specification getSpecification() { predicates.add(sc.cb().notLike(sc.root().get(AbstractStatusAuditableEntity_.status), DELETED)); + if (StringUtils.isNotBlank(service)) { + predicates.add(sc.cb().equal(sc.cb().lower(sc.root().get(CSVDataset_.destinationService)), service.toLowerCase())); + } + return cb.and(predicates.toArray(new Predicate[predicates.size()])); }; } + public String getService() { + return service; + } + + public void setService(final String service) { + this.service = service; + } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java index 185fba9a..ca895278 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java @@ -1,6 +1,8 @@ package org.devgateway.toolkit.forms.wicket.components.table.filter; +import org.apache.commons.lang3.StringUtils; import org.devgateway.toolkit.persistence.dao.AbstractStatusAuditableEntity_; +import org.devgateway.toolkit.persistence.dao.data.CSVDataset_; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.repository.SpecificationContext; import org.springframework.data.jpa.domain.Specification; @@ -18,16 +20,29 @@ public class TetsimDatasetFilterState extends JpaFilterState { private static final long serialVersionUID = 6655165533257383853L; + private String service; + @Override public Specification getSpecification() { return (root, query, cb) -> { List predicates = new ArrayList<>(); SpecificationContext sc = new SpecificationContext<>(root, query, cb); + if (StringUtils.isNotBlank(service)) { + predicates.add(sc.cb().equal(sc.cb().lower(sc.root().get(CSVDataset_.destinationService)), service.toLowerCase())); + } + predicates.add(sc.cb().notLike(sc.root().get(AbstractStatusAuditableEntity_.status), DELETED)); return cb.and(predicates.toArray(new Predicate[predicates.size()])); }; } + public String getService() { + return service; + } + + public void setService(final String service) { + this.service = service; + } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.html index b0e96a79..b7b222d9 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.html @@ -7,6 +7,7 @@

+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java index 88e01c1b..c79029e3 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java @@ -23,6 +23,7 @@ import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; @@ -58,8 +59,10 @@ public DataPage(final PageParameters parameters) { for (ServiceMetadata service : services) { PageParameters pageParameters = new PageParameters(); pageParameters.add("service", service.getName()); - links.add(new BigLinkDefinition(service.getId(), DataServicePage.class, pageParameters, - FontAwesome5IconType.table_s) { + + FontAwesome5IconType serviceIcon = getServiceIcon(service.getType()); + + links.add(new BigLinkDefinition(service.getId(), DataServicePage.class, pageParameters, serviceIcon) { @Override public IModel getLabelModel() { @@ -74,10 +77,24 @@ public IModel getDescModel() { } add(new BigLinksPanel("links", Model.ofList(links))); + Label noServiceError = new Label("noServiceError", new StringResourceModel("noServiceError", this, null)); + noServiceError.setVisible(links.isEmpty()); + add(noServiceError); + } + + private FontAwesome5IconType getServiceIcon(final String type) { + if (type.equals(WebConstants.SERVICE_TETSIM_TYPE)) { + return FontAwesome5IconType.wpforms; + } else if (type.equals(WebConstants.SERVICE_DATA_TYPE)) { + return FontAwesome5IconType.table_s; + } + + throw new IllegalArgumentException("Unknown service type: " + type); } protected Label getPageTitle() { return new Label("pageTitle", new StringResourceModel("page.title", this, Model.of(settingsUtils.getSetting()))); } + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.properties index bf0a3b25..f33f4276 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.properties @@ -1 +1,3 @@ -page.title=${countryName} Data \ No newline at end of file +page.title=${countryName} Data + +noServiceError=No data service available. \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java index 1fddb222..8d3b5c34 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java @@ -15,22 +15,30 @@ package org.devgateway.toolkit.forms.wicket.page; import de.agilecoders.wicket.core.markup.html.bootstrap.image.IconType; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.Page; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceDimensionsPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListCSVDatasetPage; +import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; +import org.devgateway.toolkit.persistence.dto.ServiceMetadata; import org.wicketstuff.annotation.mount.MountPath; import java.util.ArrayList; import java.util.List; +import static de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType.chart_bar_s; +import static de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType.database_s; +import static de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType.layer_group_s; +import static de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType.ruler_s; import static org.devgateway.toolkit.forms.WebConstants.PARAM_ENTITY; import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; @@ -41,14 +49,19 @@ @MountPath public class DataServicePage extends BasePage { + @SpringBean + private EurekaClientService eurekaClientService; + public DataServicePage(final PageParameters parameters) { super(parameters); + ServiceMetadata serviceMetadata = eurekaClientService.findByName(parameters.get(PARAM_SERVICE).toString()); + List links = new ArrayList<>(); - links.add(getEntityLink("datasets", ListCSVDatasetPage.class, FontAwesome5IconType.database_s)); - links.add(getEntityLink("measures", ListServiceDimensionsPage.class, FontAwesome5IconType.ruler_s)); - links.add(getEntityLink("dimensions", ListServiceDimensionsPage.class, FontAwesome5IconType.chart_bar_s)); - links.add(getEntityLink("categories", ListServiceDimensionsPage.class, FontAwesome5IconType.layer_group_s)); + links.add(getEntityLink("datasets", getServicePageClass(serviceMetadata.getType()), database_s)); + links.add(getEntityLink("measures", ListServiceDimensionsPage.class, ruler_s)); + links.add(getEntityLink("dimensions", ListServiceDimensionsPage.class, chart_bar_s)); + links.add(getEntityLink("categories", ListServiceDimensionsPage.class, layer_group_s)); add(new BigLinksPanel("links", Model.ofList(links))); } @@ -61,8 +74,19 @@ private BigLinkDefinition getEntityLink(final String entity, Class getServicePageClass(final String type) { + if (type.equals(WebConstants.SERVICE_TETSIM_TYPE)) { + return ListTetsimDatasetPage.class; + } else if (type.equals(WebConstants.SERVICE_DATA_TYPE)) { + return ListCSVDatasetPage.class; + } + + throw new IllegalArgumentException("Unknown service type: " + type); + } + protected Label getPageTitle() { String service = getPageParameters().get("service").toString(); return new Label("pageTitle", Model.of(service)); } + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java index 68d36bc4..187ca943 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java @@ -186,7 +186,7 @@ protected TextContentModal createCancelModal() { @Override protected void onSubmit(final AjaxRequestTarget target) { cancelModal.appendCloseDialogJavaScript(target); - setResponsePage(listPageClass); + setResponsePage(listPageClass, getCancelPageParameters()); } }; @@ -407,7 +407,7 @@ protected Class getResponsePage() { * @return */ protected PageParameters getParameterPage() { - return null; + return getSaveEditParameters(); } @Override @@ -455,6 +455,14 @@ public boolean isRedirectToSelf() { } } + protected PageParameters getSaveEditParameters() { + return null; + } + + protected PageParameters getCancelPageParameters() { + return null; + } + protected void beforeSaveEntity(final T saveable) { } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java index a5fa27d4..7383d32c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java @@ -19,7 +19,6 @@ import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; import org.devgateway.toolkit.persistence.dao.FileMetadata; import org.devgateway.toolkit.persistence.dao.data.CSVDataset; -import org.devgateway.toolkit.persistence.dto.ServiceMetadata; import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; import org.devgateway.toolkit.persistence.service.data.CSVDatasetService; import org.devgateway.toolkit.web.util.SettingsUtils; @@ -28,8 +27,6 @@ import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.wicketstuff.annotation.mount.MountPath; -import java.util.stream.Collectors; - import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.SAVED; @@ -46,7 +43,7 @@ public class EditCSVDatasetPage extends AbstractEditStatusEntityPage protected Select2ChoiceBootstrapFormComponent year; - protected Select2ChoiceBootstrapFormComponent destinationService; + protected TextFieldBootstrapFormComponent destinationService; @SpringBean protected CSVDatasetService csvDatasetService; @@ -73,6 +70,11 @@ public EditCSVDatasetPage(final PageParameters parameters) { protected void onInitialize() { super.onInitialize(); + if (entityId == null) { + String service = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + editForm.getModelObject().setDestinationService(service); + } + editForm.add(getYear()); final TextFieldBootstrapFormComponent description = @@ -99,29 +101,9 @@ private Select2ChoiceBootstrapFormComponent getYear() { return year; } - private Select2ChoiceBootstrapFormComponent getService() { - destinationService = new Select2ChoiceBootstrapFormComponent("destinationService", - new GenericChoiceProvider<>(eurekaClientService.findAllWithData().stream() - .map(ServiceMetadata::getName) - .collect(Collectors.toList()))) { - @Override - protected void onUpdate(final AjaxRequestTarget target) { - super.onUpdate(target); - if (editForm.getModelObject().getDestinationService() != null) { - saveApproveButton.setEnabled(true); - approveButton.setEnabled(true); - } else { - saveApproveButton.setEnabled(false); - approveButton.setEnabled(false); - } - - target.add(approveButton); - target.add(saveApproveButton); - } - - - }; - destinationService.setEnabled(true); + private TextFieldBootstrapFormComponent getService() { + destinationService = new TextFieldBootstrapFormComponent("destinationService"); + destinationService.setEnabled(false); return destinationService; } @@ -213,5 +195,21 @@ protected void enableDisableAutosaveFields(final AjaxRequestTarget target) { } } - // upload file + @Override + protected PageParameters getSaveEditParameters() { + return getParamsWithServiceInformation(); + } + + @Override + protected PageParameters getCancelPageParameters() { + return getParamsWithServiceInformation(); + } + + protected PageParameters getParamsWithServiceInformation() { + PageParameters pageParams = new PageParameters(); + // add service to the page parameters + pageParams.add(WebConstants.PARAM_SERVICE, editForm.getModelObject().getDestinationService()); + + return pageParams; + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index 9fe1b813..f42ab263 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -10,11 +10,13 @@ import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.client.DataSetClientException; import org.devgateway.toolkit.forms.service.DatasetClientService; import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditStatusEntityPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; @@ -52,7 +54,7 @@ public class EditTetsimDatasetPage extends AbstractEditStatusEntityPage year; - protected Select2ChoiceBootstrapFormComponent destinationService; + protected TextFieldBootstrapFormComponent destinationService; @SpringBean protected TetsimDatasetService tetsimDatasetService; @@ -90,6 +92,11 @@ protected void onInitialize() { editForm.add(new TetsimMarketSharePercentageValidator()); + if (editForm.getModelObject().getDestinationService() == null) { + String service = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + editForm.getModelObject().setDestinationService(service); + } + if (editForm.getModelObject().isNew() && getYearParam() != null) { editForm.getModelObject().setYear(getYearParam()); } @@ -105,30 +112,9 @@ private Select2ChoiceBootstrapFormComponent getYear() { return year; } - private Select2ChoiceBootstrapFormComponent getService() { - destinationService = new Select2ChoiceBootstrapFormComponent("destinationService", - new GenericChoiceProvider<>(eurekaClientService.findAllWithData().stream() - .map(ServiceMetadata::getName) - .collect(Collectors.toList()))) { - @Override - protected void onUpdate(final AjaxRequestTarget target) { - super.onUpdate(target); - if (editForm.getModelObject().getDestinationService() != null) { - saveApproveButton.setEnabled(true); - approveButton.setEnabled(true); - } else { - saveApproveButton.setEnabled(false); - approveButton.setEnabled(false); - } - - target.add(approveButton); - target.add(saveApproveButton); - } - - - }; - destinationService.setEnabled(true); - + private TextFieldBootstrapFormComponent getService() { + destinationService = new TextFieldBootstrapFormComponent<>("destinationService"); + destinationService.setEnabled(false); return destinationService; } @@ -244,15 +230,6 @@ private boolean tobaccoProductsNotDefined() { return tobaccoProductService.count() == 0; } - @Override - protected void onBeforeRender() { - super.onBeforeRender(); - - if (SAVED.equals(editForm.getModelObject().getStatus())) { - destinationService.setEnabled(true); - } - } - @Override protected void enableDisableAutosaveFields(final AjaxRequestTarget target) { super.enableDisableAutosaveFields(target); @@ -266,11 +243,6 @@ protected void enableDisableAutosaveFields(final AjaxRequestTarget target) { approveButton.setEnabled(false); revertToDraftPageButton.setEnabled(false); } - - if (StringUtils.isBlank(editForm.getModelObject().getDestinationService())) { - saveApproveButton.setEnabled(false); - approveButton.setEnabled(false); - } } @@ -278,4 +250,22 @@ protected Integer getYearParam() { return getPageParameters().get(PARAM_YEAR).toOptionalInteger(); } + @Override + protected PageParameters getSaveEditParameters() { + return getParamsWithServiceInformation(); + } + + @Override + protected PageParameters getCancelPageParameters() { + return getParamsWithServiceInformation(); + } + + protected PageParameters getParamsWithServiceInformation() { + PageParameters pageParams = new PageParameters(); + // add service to the page parameters + pageParams.add(WebConstants.PARAM_SERVICE, editForm.getModelObject().getDestinationService()); + + return pageParams; + } + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java index 6f76ffc7..11da8f7b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java @@ -156,8 +156,7 @@ public void populateItem(final Item> cellItem, final String co setDataTableForFilteredColumns(); } - PageParameters pageParameters = new PageParameters(); - pageParameters.set(WebConstants.PARAM_ID, null); + PageParameters pageParameters = getEditPageParameters(); editPageLink = new BootstrapBookmarkablePageLink("new", editPageClass, pageParameters, Buttons.Type.Success); editPageLink.setIconType(FontAwesome5IconType.plus_circle_s).setSize(Size.Large) @@ -167,6 +166,12 @@ public void populateItem(final Item> cellItem, final String co add(editPageLink); } + protected PageParameters getEditPageParameters() { + PageParameters pageParameters = new PageParameters(); + pageParameters.set(WebConstants.PARAM_ID, null); + return pageParameters; + } + public class ActionPanel extends GenericPanel { private static final long serialVersionUID = 5821419128121941939L; protected PageParameters pageParameters; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java index 17bbb432..b25a0d30 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java @@ -16,6 +16,7 @@ import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.StringResourceModel; @@ -30,9 +31,12 @@ import org.devgateway.toolkit.persistence.service.data.CSVDatasetService; import org.wicketstuff.annotation.mount.MountPath; +import java.text.MessageFormat; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; +import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; + @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) @MountPath(value = "/listCSVDataset") public class ListCSVDatasetPage extends AbstractListPage { @@ -41,8 +45,13 @@ public class ListCSVDatasetPage extends AbstractListPage { @SpringBean private CSVDatasetService datasetService; + CSVDatasetFilterState filterState; + public ListCSVDatasetPage(final PageParameters pageParameters) { super(pageParameters); + + String service = pageParameters.get("service").toString(); + this.jpaService = datasetService; this.editPageClass = EditCSVDatasetPage.class; @@ -62,9 +71,18 @@ public IModel getDataModel(final IModel rowModel) { return Model.of(modifiedDate.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"))); } }); - columns.add(new PropertyColumn<>(new StringResourceModel("destinationService"), "destinationService", "destinationService")); columns.add(new PropertyColumn<>(new StringResourceModel("status"), "status", "status")); + filterState = new CSVDatasetFilterState(); + filterState.setService(service); + + } + + @Override + protected PageParameters getEditPageParameters() { + PageParameters pageParams = super.getEditPageParameters(); + pageParams.set(PARAM_SERVICE, getPageParameters().get(PARAM_SERVICE).toString()); + return pageParams; } @Override @@ -83,6 +101,12 @@ protected Component getRevisionsLink(final CSVDataset entity) { @Override public JpaFilterState newFilterState() { - return new CSVDatasetFilterState(); + return filterState; } + + protected Label getPageTitle() { + String service = getPageParameters().get("service").toString(); + return new Label("pageTitle", Model.of(MessageFormat.format(getString("page.title"), service))); + } + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties index 85da4361..ed13b069 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties @@ -1,9 +1,8 @@ -page.title=CSV Datasets +page.title={0} Datasets year=Year lastModifiedBy=Editor lastModifiedDate=Latest Modification status=Status -destinationService=Destination Service actionsColumn=Action new=Add new dataset \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java index dc266fff..fd8d0058 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java @@ -38,11 +38,13 @@ import org.springframework.util.ObjectUtils; import org.wicketstuff.annotation.mount.MountPath; +import java.text.MessageFormat; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.List; +import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; import static org.devgateway.toolkit.forms.WebConstants.PARAM_YEAR; @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) @@ -52,6 +54,8 @@ public class ListTetsimDatasetPage extends AbstractListPage { @SpringBean protected SettingsUtils settingsUtils; + TetsimDatasetFilterState filterState; + protected Select2ChoiceBootstrapFormComponent year; protected Fragment yearSelectorFragment; private Integer selectedYear; @@ -82,6 +86,11 @@ public IModel getDataModel(final IModel rowModel) { }); columns.add(new PropertyColumn<>(new StringResourceModel("status"), "status", "status")); + + String service = pageParameters.get(PARAM_SERVICE).toString(); + filterState = new TetsimDatasetFilterState(); + filterState.setService(service); + } @Override @@ -166,6 +175,13 @@ protected void preparePageLinkButton(final AjaxRequestTarget target) { target.add(editPageLink); } + @Override + protected PageParameters getEditPageParameters() { + PageParameters pageParams = super.getEditPageParameters(); + pageParams.set(PARAM_SERVICE, getPageParameters().get(PARAM_SERVICE).toString()); + return pageParams; + } + protected List getAddButtonErrors() { long c = countByNonPublished(); if (c > 0) { @@ -196,7 +212,8 @@ public JpaFilterState newFilterState() { } protected Label getPageTitle() { - return new Label("pageTitle", new StringResourceModel("page.title", this, - Model.of(settingsUtils.getSetting()))); + String service = getPageParameters().get("service").toString(); + return new Label("pageTitle", Model.of(MessageFormat.format(getString("page.title"), service))); } + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties index 0612db49..7bb3c79c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties @@ -1,4 +1,4 @@ -page.title=${countryName} TETSIM +page.title={0} Datasets year=Year lastModifiedBy=Editor lastModifiedDate=Latest Modification From 3d5beba26a5a81330b33d2f2a7ff33595ce06b3c Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 26 Sep 2022 15:37:56 +0300 Subject: [PATCH 082/137] TOBACCO-999: Manage dimensions of a service --- .../toolkit/forms/client/DatasetClient.java | 55 ++- .../forms/service/DatasetClientService.java | 19 +- .../forms/wicket/page/DataServicePage.java | 1 - .../edit/admin/EditServiceDimensionPage.html | 33 ++ .../edit/admin/EditServiceDimensionPage.java | 409 ++++++++++++++++++ .../admin/EditServiceDimensionPage.properties | 21 + ...ListServiceDimensionsPage$ActionPanel.html | 8 + .../admin/ListServiceDimensionsPage.html | 8 +- .../admin/ListServiceDimensionsPage.java | 127 +++--- .../ListServiceDimensionsPage.properties | 8 +- .../lists/admin/ServiceDimensionProvider.java | 75 ++++ .../toolkit/persistence/dto/CssStyle.java | 43 ++ .../persistence/dto/ServiceDimension.java | 117 +++++ .../persistence/dto/ServiceMetadata.java | 6 +- .../dto/ServiceMetadataDimension.java | 79 ---- 15 files changed, 865 insertions(+), 144 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage$ActionPanel.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDimensionProvider.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dto/CssStyle.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceDimension.java delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadataDimension.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java index 99f0554d..bed8e8bb 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java @@ -2,7 +2,7 @@ import org.apache.commons.io.FileUtils; import org.devgateway.toolkit.persistence.dao.data.Dataset; -import org.devgateway.toolkit.persistence.dto.ServiceMetadataDimension; +import org.devgateway.toolkit.persistence.dto.ServiceDimension; import org.glassfish.jersey.client.JerseyClient; import org.glassfish.jersey.client.JerseyClientBuilder; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; @@ -162,14 +162,14 @@ public boolean isUp() { return false; } - public List getDimensions() { + public List getDimensions() { if (isUp()) { Response dimensionsResponse = client.target(baseUrl) .path(PATH_DIMENSIONS) .request(APPLICATION_JSON).get(); if (dimensionsResponse.getStatusInfo().getFamily() == SUCCESSFUL) { - return dimensionsResponse.readEntity(new GenericType>() {}); + return dimensionsResponse.readEntity(new GenericType>() {}); } return null; @@ -177,4 +177,53 @@ public List getDimensions() { throw new RuntimeException(("Service is not up")); } + + public ServiceDimension getDimensionById(final Long id) { + if (isUp()) { + Response dimensionsResponse = client.target(baseUrl) + .path(PATH_DIMENSIONS) + .path(id.toString()) + .request(APPLICATION_JSON).get(); + + if (dimensionsResponse.getStatusInfo().getFamily() == SUCCESSFUL) { + return dimensionsResponse.readEntity(new GenericType() {}); + } + + return null; + } + + throw new RuntimeException(("Service is not up")); + } + + public void addDimension(final ServiceDimension dimension) { + if (isUp()) { + Response dimensionsResponse = client.target(baseUrl) + .path(PATH_DIMENSIONS) + .request(APPLICATION_JSON) + .post(Entity.entity(dimension, APPLICATION_JSON)); + + if (dimensionsResponse.getStatusInfo().getFamily() != SUCCESSFUL) { + throw new RuntimeException("Error in adding dimension"); + } + } else { + throw new RuntimeException(("Service is not up")); + } + } + + + public void updateDimension(final ServiceDimension dimension) { + if (isUp()) { + Response dimensionsResponse = client.target(baseUrl) + .path(PATH_DIMENSIONS) + .path(dimension.getId().toString()) + .request(APPLICATION_JSON) + .put(Entity.entity(dimension, APPLICATION_JSON)); + + if (dimensionsResponse.getStatusInfo().getFamily() != SUCCESSFUL) { + throw new RuntimeException("Error in updating dimension"); + } + } else { + throw new RuntimeException(("Service is not up")); + } + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java index 8d69542b..807fdbbf 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java @@ -7,7 +7,7 @@ import org.devgateway.toolkit.persistence.dao.data.Dataset; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.dto.ServiceMetadata; -import org.devgateway.toolkit.persistence.dto.ServiceMetadataDimension; +import org.devgateway.toolkit.persistence.dto.ServiceDimension; import org.devgateway.toolkit.persistence.service.data.CSVDatasetService; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.slf4j.Logger; @@ -110,8 +110,23 @@ private ServiceMetadata getDestinationService(Dataset dataset) { return eurekaClientService.findByName(destinationService); } - public List getDimensions(final String serviceName) { + public List getDimensions(final String serviceName) { ServiceMetadata service = eurekaClientService.findByName(serviceName); return new DatasetClient(service.getUrl()).getDimensions(); } + + public ServiceDimension getDimensionById(final String serviceName, final long id) { + ServiceMetadata service = eurekaClientService.findByName(serviceName); + return new DatasetClient(service.getUrl()).getDimensionById(id); + } + + public void updateDimension(final String serviceName, final ServiceDimension dimension) { + ServiceMetadata service = eurekaClientService.findByName(serviceName); + new DatasetClient(service.getUrl()).updateDimension(dimension); + } + + public void addDimensionToService(final String service, final ServiceDimension serviceDimension) { + ServiceMetadata serviceMetadata = eurekaClientService.findByName(service); + new DatasetClient(serviceMetadata.getUrl()).addDimension(serviceDimension); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java index 8d3b5c34..df0c7324 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java @@ -69,7 +69,6 @@ public DataServicePage(final PageParameters parameters) { private BigLinkDefinition getEntityLink(final String entity, Class pageClass, IconType iconType) { PageParameters pageParams = new PageParameters(); pageParams.set(PARAM_SERVICE, getPageParameters().get(PARAM_SERVICE).toString()); - pageParams.set(PARAM_ENTITY, entity); return new BigLinkDefinition(entity, pageClass, pageParams, iconType); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.html new file mode 100644 index 00000000..6d1a9260 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.html @@ -0,0 +1,33 @@ + + + + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +
+
+
+
+
+
+ +
+
+ + + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java new file mode 100644 index 00000000..83399655 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java @@ -0,0 +1,409 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.admin; + +import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; +import de.agilecoders.wicket.core.markup.html.bootstrap.dialog.TextContentModal; +import de.agilecoders.wicket.core.markup.html.bootstrap.form.BootstrapForm; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; +import nl.dries.wicket.hibernate.dozer.DozerModel; +import org.apache.wicket.Page; +import org.apache.wicket.ajax.AjaxEventBehavior; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.model.CompoundPropertyModel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.ResourceModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.validation.ValidationError; +import org.devgateway.toolkit.forms.WebConstants; +import org.devgateway.toolkit.forms.exceptions.NullListPageClassException; +import org.devgateway.toolkit.forms.service.DatasetClientService; +import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; +import org.devgateway.toolkit.forms.wicket.components.form.BootstrapSubmitButton; +import org.devgateway.toolkit.forms.wicket.components.form.GenericBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.components.form.visitors.GenericBootstrapValidationVisitor; +import org.devgateway.toolkit.forms.wicket.page.BasePage; +import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceDimensionsPage; +import org.devgateway.toolkit.persistence.dto.ServiceDimension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.orm.ObjectOptimisticLockingFailureException; +import org.wicketstuff.annotation.mount.MountPath; + +/** + * @author mpostelnicu Page used to make editing easy, extend to get easy access + * to one entity for editing + */ +@MountPath(value = "/editServiceDimension") +public class EditServiceDimensionPage extends BasePage { + private static final long serialVersionUID = -1594571319284288551L; + + private static final Logger logger = LoggerFactory.getLogger(EditServiceDimensionPage.class); + + /** + * Factory method for the new instance of the entity being editing. This + * will be invoked only when the parameter PARAM_ID is null + * + * @return + */ + /** + * The repository used to fetch and save the entity, this is initialized in + * subclasses + */ + /** + * The page that is responsible for listing the entities (used here as a + * return reference after successful save) + */ + protected Class listPageClass; + + @SpringBean + DatasetClientService datasetClientService; + + /** + * The form used by all subclasses + */ + protected EditForm editForm; + + private CompoundPropertyModel compoundModel; + + /** + * the entity id, or null if a new entity is requested + */ + protected Long entityId; + + /** + * This is a wrapper model that ensures we can easily edit the properties of + * the entity + */ + /** + * generic submit button for the form + */ + protected BootstrapSubmitButton saveButton; + + /** + * generic delete button for the form + */ + protected TextContentModal cancelModal; + + protected TextContentModal saveFailedModal; + + public EditForm getEditForm() { + return editForm; + } + + public GenericBootstrapValidationVisitor getBootstrapValidationVisitor(final AjaxRequestTarget target) { + return new GenericBootstrapValidationVisitor(target); + } + + protected TextContentModal createCancelModal() { + final TextContentModal cancelModal = new TextContentModal("cancelModal", + Model.of("Are you sure you want to cancel? Any changes made will be lost.")); + + final LaddaAjaxButton cancelButton = new BootstrapCancelButton("button", Model.of("Yes")) { + private static final long serialVersionUID = -9144254663723097155L; + + @Override + protected void onSubmit(final AjaxRequestTarget target) { + cancelModal.appendCloseDialogJavaScript(target); + setResponsePage(listPageClass, getCancelPageParameters()); + } + }; + + cancelButton.setType(Buttons.Type.Success); + cancelModal.addButton(cancelButton); + cancelModal.addCloseButton(Model.of("No")); + + return cancelModal; + } + + protected TextContentModal createSaveFailedModal() { + final TextContentModal modal = new TextContentModal("saveFailedModal", Model.of("Save failed!")); + modal.header(new ResourceModel("error")); + final LaddaAjaxButton okButton = new LaddaAjaxButton("button", Buttons.Type.Info) { + @Override + protected void onSubmit(final AjaxRequestTarget target) { + setResponsePage(listPageClass); + } + }; + okButton.setDefaultFormProcessing(false); + okButton.setLabel(Model.of("OK")); + modal.addButton(okButton); + + modal.add(new AjaxEventBehavior("hidden.bs.modal") { + @Override + protected void onEvent(final AjaxRequestTarget target) { + setResponsePage(listPageClass); + } + }); + + return modal; + } + + + public class EditForm extends BootstrapForm { + private static final long serialVersionUID = -9127043819229346784L; + + /** + * wrap the model with a {@link CompoundPropertyModel} to ease editing + * of fields + * + * @param model + */ + public void setCompoundPropertyModel(final IModel model) { + compoundModel = new CompoundPropertyModel(model); + setModel(compoundModel); + } + + public EditForm(final String id, final IModel model) { + this(id); + setCompoundPropertyModel(model); + } + + public EditForm(final String id) { + super(id); + + setOutputMarkupId(true); + + saveButton = getSaveEditPageButton(); + add(saveButton); + + cancelModal = createCancelModal(); + add(cancelModal); + + saveFailedModal = createSaveFailedModal(); + add(saveFailedModal); + + add(getCancelButton("cancel")); + } + } + + protected BootstrapCancelButton getCancelButton(final String id) { + return new BootstrapCancelButton(id, new StringResourceModel("cancelButton", this, null)) { + private static final long serialVersionUID = -249084359200507749L; + + @Override + protected void onSubmit(final AjaxRequestTarget target) { + setResponsePage(listPageClass, getCancelPageParameters()); + } + }; + } + + /** + * Generic functionality for the save page button, this can be extended + * further by subclasses + * + */ + public class SaveEditPageButton extends BootstrapSubmitButton { + private static final long serialVersionUID = 9075809391795974349L; + + private boolean redirect = true; + + private boolean redirectToSelf = false; + + public SaveEditPageButton(final String id, final IModel model) { + super(id, model); + } + + @Override + protected void onSubmit(final AjaxRequestTarget target) { + try { + // save the object and go back to the list page + ServiceDimension dimension = editForm.getModelObject(); + + if (editForm.getModelObject().getId() != null) { + updateDimension(dimension); + } else { + createDimension(dimension); + } + + // only redirect if redirect is true + if (redirectToSelf) { + // we need to close the blockUI if it's opened and enable all + // the buttons + target.appendJavaScript("$.unblockUI();"); + target.appendJavaScript("$('#" + editForm.getMarkupId() + " button').prop('disabled', false);"); + } else if (redirect) { + setResponsePage(getResponsePage(), getParameterPage()); + } + + // redirect is set back to true, which is the default behavior + redirect = true; + redirectToSelf = false; + } catch (ObjectOptimisticLockingFailureException e) { + saveFailedModal.show(target); + } + } + + /** + * by default, submit button returns back to listPage + * + * @return + */ + protected Class getResponsePage() { + return listPageClass; + } + + /** + * no params by default + * + * @return + */ + protected PageParameters getParameterPage() { + return getSaveEditParameters(); + } + + @Override + protected void onError(final AjaxRequestTarget target) { + // make all errors visible + GenericBootstrapValidationVisitor genericBootstrapValidationVisitor = getBootstrapValidationVisitor(target); + editForm.visitChildren(GenericBootstrapFormComponent.class, genericBootstrapValidationVisitor); + + ValidationError error = new ValidationError(); + error.addKey("formHasErrors"); + error(error); + + target.add(feedbackPanel); + + // autoscroll down to the feedback panel + target.appendJavaScript("$('html, body').animate({scrollTop: $(\".feedbackPanel\").offset().top}, 500);"); + } + + /** + * @return the redirect + */ + public boolean isRedirect() { + return redirect; + } + + /** + * @param redirect the redirect to set + */ + public void setRedirect(final boolean redirect) { + this.redirect = redirect; + } + + /** + * @param redirectToSelf the redirectToSelf to set + */ + public void setRedirectToSelf(final boolean redirectToSelf) { + this.redirectToSelf = redirectToSelf; + } + + /** + * @return the redirectToSelf + */ + public boolean isRedirectToSelf() { + return redirectToSelf; + } + } + + protected PageParameters getSaveEditParameters() { + return getParamsWithServiceInformation(); + } + + protected PageParameters getCancelPageParameters() { + return getParamsWithServiceInformation(); + } + + /** + * Override this to create new save buttons with additional behaviors + * + * @return + */ + protected SaveEditPageButton getSaveEditPageButton() { + return new SaveEditPageButton("save", new StringResourceModel("saveButton", this, null)); + } + + public EditServiceDimensionPage(final PageParameters parameters) { + super(parameters); + + if (!parameters.get(WebConstants.PARAM_ID).isNull()) { + entityId = parameters.get(WebConstants.PARAM_ID).toLongObject(); + } + + editForm = new EditForm("editForm"); + + // use this in order to avoid "ServletRequest does not contain multipart + // content" error + // this error appears when we have a file upload component that is + // hidden or not present in the page when the form is created + editForm.setMultiPart(true); + + add(editForm); + + // section in child + pageTitle.setDefaultModel(getTitleModel()); + + this.listPageClass = ListServiceDimensionsPage.class; + + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + // we dont like receiving null list pages + if (listPageClass == null) { + throw new NullListPageClassException(); + } + + IModel model = null; + String service = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + + if (entityId != null) { + ServiceDimension serviceDimension = datasetClientService.getDimensionById(service, entityId); + model = new DozerModel<>(serviceDimension); + } else { + ServiceDimension serviceDimension = new ServiceDimension(); + if (serviceDimension != null) { + model = new DozerModel<>(serviceDimension); + } + } + + if (model != null) { + editForm.setCompoundPropertyModel(model); + } + + final TextFieldBootstrapFormComponent code = new TextFieldBootstrapFormComponent<>("code"); + code.setEnabled(false); + editForm.add(code); + + final TextFieldBootstrapFormComponent value = new TextFieldBootstrapFormComponent<>("value"); + value.getField().setRequired(true); + editForm.add(value); + + final TextFieldBootstrapFormComponent position = new TextFieldBootstrapFormComponent<>("position"); + position.getField().setRequired(true); + editForm.add(position); + } + + protected StringResourceModel getTitleModel() { + if (entityId == null) { + return new StringResourceModel("page.title.add", this, null); + } else { + return new StringResourceModel("page.title.edit", this, null); + } + } + + protected PageParameters getParamsWithServiceInformation() { + String service = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + + PageParameters pageParams = new PageParameters(); + pageParams.add(WebConstants.PARAM_SERVICE, service); + + return pageParams; + } + + private void createDimension(ServiceDimension serviceDimension) { + String service = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + datasetClientService.addDimensionToService(service, serviceDimension); + } + + private void updateDimension(ServiceDimension serviceDimension) { + String service = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + datasetClientService.updateDimension(service, serviceDimension); + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties new file mode 100644 index 00000000..1071a3d2 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties @@ -0,0 +1,21 @@ +############################################################################### +# Copyright (c) 2015 Development Gateway, Inc and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the MIT License (MIT) +# which accompanies this distribution, and is available at +# https://opensource.org/licenses/MIT +# +# Contributors: +# Development Gateway - initial API and implementation +############################################################################### +page.title=Edit Dimension +page.title.add=Add Dimension +page.title.edit=Edit Dimension +code.label=Code +value.label=Value +position.label=Position +cancelButton=Cancel +saveButton=Save +formHasErrors=The form has errors or is missing information and cannot be submitted. Please scroll up, fix all the errors (highlighted in red) and re-submit! +error=Error \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage$ActionPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage$ActionPanel.html new file mode 100644 index 00000000..ad387fd1 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage$ActionPanel.html @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.html index e7e94079..3eaf2050 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.html @@ -3,11 +3,13 @@ +
-
-
+
+
+ - + \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java index d5181803..1410f67d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java @@ -11,97 +11,126 @@ *******************************************************************************/ package org.devgateway.toolkit.forms.wicket.page.lists.admin; -import org.apache.wicket.ajax.AjaxRequestTarget; +import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapBookmarkablePageLink; +import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.markup.html.panel.GenericPanel; +import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.service.DatasetClientService; +import org.devgateway.toolkit.forms.wicket.components.table.AjaxFallbackBootstrapDataTable; import org.devgateway.toolkit.forms.wicket.page.BasePage; -import org.devgateway.toolkit.persistence.dto.ServiceMetadataDimension; -import org.springframework.beans.factory.annotation.Autowired; +import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServiceDimensionPage; +import org.devgateway.toolkit.forms.wicket.page.edit.dataset.EditTetsimDatasetPage; +import org.devgateway.toolkit.persistence.dto.ServiceDimension; import org.wicketstuff.annotation.mount.MountPath; -import org.wicketstuff.egrid.EditableGrid; -import org.wicketstuff.egrid.column.RequiredEditableTextFieldColumn; -import org.wicketstuff.egrid.provider.EditableListDataProvider; import java.util.ArrayList; import java.util.List; -/** - * @author mpostelnicu - */ -@MountPath(value = "/dimensions") +import static org.devgateway.toolkit.forms.WebConstants.PAGE_SIZE; + @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) +@MountPath(value = "/dimensions") public class ListServiceDimensionsPage extends BasePage { - private static final long serialVersionUID = 1302443729452089592L; + private static final long serialVersionUID = -6132847935476573446L; - private EditableGrid editableGrid; + protected AjaxFallbackBootstrapDataTable dataTable; - private String serviceName; + protected ServiceDimensionProvider dataProvider; + + protected List> columns; @SpringBean private DatasetClientService datasetClientService; - /** - * @param parameters - */ - public ListServiceDimensionsPage(final PageParameters parameters) { - super(parameters); + protected int pageRowNo = 0; + + public ListServiceDimensionsPage(final PageParameters pageParameters) { + super(pageParameters); - this.serviceName = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + String service = pageParameters.get(WebConstants.PARAM_SERVICE).toString(); + dataProvider = new ServiceDimensionProvider(datasetClientService, service); + + columns = new ArrayList<>(); + columns.add(new PropertyColumn<>(new Model<>("Code"), "code", "code")); + columns.add(new PropertyColumn<>(new Model<>("Value"), "value", "value")); + columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); } @Override protected void onInitialize() { super.onInitialize(); - editableGrid = new EditableGrid("grid", getColumns(), - new EditableListDataProvider(getObjectList()), 5, ServiceMetadataDimension.class) { - private static final long serialVersionUID = 1L; + dataTable = new AjaxFallbackBootstrapDataTable( + "table", columns, dataProvider, getPageSize()) { + private static final long serialVersionUID = -7263599298497560059L; @Override - protected void onError(AjaxRequestTarget target) { - target.add(feedbackPanel); + protected void onPageChanged() { + pageRowNo = 0; } + }; - @Override - protected void onCancel(AjaxRequestTarget target) { - target.add(feedbackPanel); - } + columns.add(new AbstractColumn(new StringResourceModel("actionsColumn", this, null)) { + private static final long serialVersionUID = -7447601118569862123L; @Override - protected void onDelete(AjaxRequestTarget target, IModel rowModel) { - target.add(feedbackPanel); + public void populateItem(final Item> cellItem, final String componentId, + final IModel model) { + cellItem.add(getActionPanel(componentId, model)); } + }); - @Override - protected void onSave(AjaxRequestTarget target, IModel rowModel) { - target.add(feedbackPanel); - } + add(dataTable); + } - @Override - protected boolean displayAddFeature() { - return false; - } - }; - editableGrid.setTableCss("dataview table"); - add(editableGrid); + protected int getPageSize() { + return PAGE_SIZE; } - private List getObjectList() { - return datasetClientService.getDimensions(serviceName); + public ActionPanel getActionPanel(final String id, final IModel model) { + return new ActionPanel(id, model); } - private List> getColumns() { - List> columns = new ArrayList<>(); - columns.add(new PropertyColumn<>(new Model("Name"), "code")); - columns.add(new RequiredEditableTextFieldColumn(new Model("Label"), "value")); - return columns; + public class ActionPanel extends GenericPanel { + private static final long serialVersionUID = 5821419128121941939L; + + protected BootstrapBookmarkablePageLink editItemPageLink; + + /** + * @param id + * @param model + */ + public ActionPanel(final String id, final IModel model) { + super(id, model); + + final PageParameters pageParameters = new PageParameters(); + + @SuppressWarnings("unchecked") + ServiceDimension entity = (ServiceDimension) ActionPanel.this.getDefaultModelObject(); + if (entity != null) { + pageParameters.set(WebConstants.PARAM_ID, entity.getId()); + } + pageParameters.set(WebConstants.PARAM_SERVICE, getPageParameters().get(WebConstants.PARAM_SERVICE)); + + editItemPageLink = + new BootstrapBookmarkablePageLink<>("edit", EditServiceDimensionPage.class, pageParameters, Buttons.Type.Info); + editItemPageLink.setIconType(FontAwesome5IconType.edit_s).setSize(Buttons.Size.Small) + .setLabel(new StringResourceModel("edit", this, null)); + add(editItemPageLink); + } } -} +} \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties index fcfd3d67..bd208f37 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties @@ -1,4 +1,4 @@ -page.title=Service Dimensions -id=ID -name=Name -label=Label \ No newline at end of file +page.title=Dimensions +actionsColumn=Edit +dimensions=Dimensions +edit=Edit \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDimensionProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDimensionProvider.java new file mode 100644 index 00000000..482c28e7 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDimensionProvider.java @@ -0,0 +1,75 @@ +package org.devgateway.toolkit.forms.wicket.page.lists.admin; + +import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; +import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.devgateway.toolkit.forms.service.DatasetClientService; +import org.devgateway.toolkit.persistence.dto.ServiceDimension; + +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + +/** + * Data provider used to provide information about the services + * + * @author Viorel Chihai + */ +public class ServiceDimensionProvider extends SortableDataProvider { + private static final long serialVersionUID = 1858130875067823547L; + + protected DatasetClientService datasetClientService; + + private final String serviceName; + + public ServiceDimensionProvider(final DatasetClientService datasetClientService, final String serviceName) { + this.datasetClientService = datasetClientService; + this.serviceName = serviceName; + } + + @Override + public Iterator iterator(final long first, final long count) { + List services = datasetClientService.getDimensions(serviceName); + + if (first > services.size()) { + return Collections.emptyIterator(); + } + + if (getSort() == null || getSort().getProperty().equals("label")) { + Comparator comparator = new ServiceDimensionComparator(); + + if (getSort() != null && getSort().isAscending()) { + comparator = comparator.reversed(); + } + + Collections.sort(services, comparator); + } + + return services.subList((int) first, (int) Math.min(first + count, services.size())).iterator(); + } + + @Override + public SortParam getSort() { + return super.getSort(); + } + + @Override + public long size() { + return datasetClientService.getDimensions(serviceName).size(); + } + + @Override + public IModel model(final ServiceDimension serviceDimension) { + return Model.of(serviceDimension); + } + + protected class ServiceDimensionComparator implements Comparator { + @Override + public int compare(final ServiceDimension s1, final ServiceDimension s2) { + return String.CASE_INSENSITIVE_ORDER.compare(s1.getCode(), s2.getCode()); + } + } + +} \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/CssStyle.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/CssStyle.java new file mode 100644 index 00000000..664a01e5 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/CssStyle.java @@ -0,0 +1,43 @@ +package org.devgateway.toolkit.persistence.dto; + +public class CssStyle { + private String backgroundColor; + + private String textColor; + + private String className; + + private String color; + + public String getBackgroundColor() { + return backgroundColor; + } + + public void setBackgroundColor(final String backgroundColor) { + this.backgroundColor = backgroundColor; + } + + public String getTextColor() { + return textColor; + } + + public void setTextColor(final String textColor) { + this.textColor = textColor; + } + + public String getClassName() { + return className; + } + + public void setClassName(final String className) { + this.className = className; + } + + public String getColor() { + return color; + } + + public void setColor(final String color) { + this.color = color; + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceDimension.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceDimension.java new file mode 100644 index 00000000..b8a0a117 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceDimension.java @@ -0,0 +1,117 @@ +package org.devgateway.toolkit.persistence.dto; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.io.Serializable; + +@JsonIgnoreProperties({"labels", "descriptions"}) +public class ServiceDimension implements Serializable { + + private Long id; + + private String code; + + private String label; + + private String type; + + private String value; + + private Integer position; + + private CssStyle categoryStyle; + + private String field; + + private String fieldType; + + private Class aClass; + + public ServiceDimension() { + } + + public ServiceDimension(final Long id, final String label) { + this.id = id; + this.label = label; + } + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getLabel() { + return label; + } + + public void setLabel(final String label) { + this.label = label; + } + + public String getType() { + return type; + } + + public void setType(final String type) { + this.type = type; + } + + public String getCode() { + return code; + } + + public void setCode(final String code) { + this.code = code; + } + + public String getValue() { + return value; + } + + public void setValue(final String value) { + this.value = value; + } + + public Integer getPosition() { + return position; + } + + public void setPosition(final Integer position) { + this.position = position; + } + + public CssStyle getCategoryStyle() { + return categoryStyle; + } + + public void setCategoryStyle(final CssStyle categoryStyle) { + this.categoryStyle = categoryStyle; + } + + public String getField() { + return field; + } + + public void setField(final String field) { + this.field = field; + } + + public String getFieldType() { + return fieldType; + } + + public void setFieldType(final String fieldType) { + this.fieldType = fieldType; + } + + public Class getaClass() { + return aClass; + } + + public void setaClass(final Class aClass) { + this.aClass = aClass; + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java index 3012ed84..b93b8fdd 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java @@ -18,7 +18,7 @@ public class ServiceMetadata implements Serializable { private String status; - private List dimensions = new ArrayList<>(); + private List dimensions = new ArrayList<>(); public String getId() { return id; @@ -73,11 +73,11 @@ public void setStatus(final String status) { this.status = status; } - public List getDimensions() { + public List getDimensions() { return dimensions; } - public void setDimensions(final List dimensions) { + public void setDimensions(final List dimensions) { this.dimensions = dimensions; } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadataDimension.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadataDimension.java deleted file mode 100644 index 5b024116..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadataDimension.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.devgateway.toolkit.persistence.dto; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import java.io.Serializable; - -@JsonIgnoreProperties({"position", "labels", "descriptions", "field", "fieldType", "aClass", "categoryStyle"}) -public class ServiceMetadataDimension implements Serializable { - - private Long id; - - private String name; - - private String label; - - private String type; - - private String code; - - private String value; - - public ServiceMetadataDimension() { - - } - - public ServiceMetadataDimension(final Long id, final String name, final String label) { - this.id = id; - this.name = name; - this.label = label; - } - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getLabel() { - return label; - } - - public void setLabel(final String label) { - this.label = label; - } - - public String getType() { - return type; - } - - public void setType(final String type) { - this.type = type; - } - - public String getCode() { - return code; - } - - public void setCode(final String code) { - this.code = code; - } - - public String getValue() { - return value; - } - - public void setValue(final String value) { - this.value = value; - } -} From 778f5e7608fa906c5a94d16430ecf20c925c250c Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Tue, 27 Sep 2022 16:26:04 +0300 Subject: [PATCH 083/137] TOBACCO-990: Manage measures of a service --- .../toolkit/forms/client/ClientConstants.java | 3 + .../toolkit/forms/client/DatasetClient.java | 66 ++++ .../forms/service/DatasetClientService.java | 23 ++ .../forms/wicket/page/DataServicePage.java | 4 +- .../admin/AbstractEditServiceEntityPage.html | 25 ++ .../admin/AbstractEditServiceEntityPage.java | 373 ++++++++++++++++++ .../AbstractEditServiceEntityPage.properties | 18 + .../edit/admin/EditServiceDimensionPage.html | 31 +- .../edit/admin/EditServiceDimensionPage.java | 350 +--------------- .../admin/EditServiceDimensionPage.properties | 6 +- .../edit/admin/EditServiceMeasurePage.html | 16 + .../edit/admin/EditServiceMeasurePage.java | 60 +++ .../admin/EditServiceMeasurePage.properties | 17 + .../admin/ListServiceDimensionsPage.html | 3 - .../ListServiceDimensionsPage.properties | 1 - .../ListServiceMeasuresPage$ActionPanel.html | 8 + .../lists/admin/ListServiceMeasuresPage.html | 12 + .../lists/admin/ListServiceMeasuresPage.java | 135 +++++++ .../admin/ListServiceMeasuresPage.properties | 3 + .../lists/admin/ServiceMeasureProvider.java | 76 ++++ .../persistence/dto/ServiceCategory.java | 50 +++ .../persistence/dto/ServiceDimension.java | 113 +----- .../persistence/dto/ServiceEntity.java | 23 ++ .../persistence/dto/ServiceMeasure.java | 38 ++ 24 files changed, 971 insertions(+), 483 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage$ActionPanel.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMeasureProvider.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceEntity.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMeasure.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java index eb75cf0d..2f36e44f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java @@ -12,6 +12,9 @@ public static final class JobStatus { public final static String PATH_DATASETS = "/admin/datasets"; public final static String PATH_DIMENSIONS = "/admin/dimensions"; + + public final static String PATH_MEASURES = "/admin/measures"; + public final static String PATH_CODE = "/code"; public final static String CODE_PREFIX = "tcdi-"; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java index bed8e8bb..114a6b7c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java @@ -3,6 +3,7 @@ import org.apache.commons.io.FileUtils; import org.devgateway.toolkit.persistence.dao.data.Dataset; import org.devgateway.toolkit.persistence.dto.ServiceDimension; +import org.devgateway.toolkit.persistence.dto.ServiceMeasure; import org.glassfish.jersey.client.JerseyClient; import org.glassfish.jersey.client.JerseyClientBuilder; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; @@ -28,6 +29,7 @@ import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_DIMENSIONS; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_HEALTH; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_JOBS; +import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_MEASURES; public class DatasetClient { @@ -226,4 +228,68 @@ public void updateDimension(final ServiceDimension dimension) { throw new RuntimeException(("Service is not up")); } } + + public ServiceMeasure getMeasureById(final Long id) { + if (isUp()) { + Response measuresResponse = client.target(baseUrl) + .path(PATH_MEASURES) + .path(id.toString()) + .request(APPLICATION_JSON).get(); + + if (measuresResponse.getStatusInfo().getFamily() == SUCCESSFUL) { + return measuresResponse.readEntity(new GenericType() {}); + } + + return null; + } + + throw new RuntimeException(("Service is not up")); + } + + public void addMeasure(final ServiceMeasure measure) { + if (isUp()) { + Response measuresResponse = client.target(baseUrl) + .path(PATH_MEASURES) + .request(APPLICATION_JSON) + .post(Entity.entity(measure, APPLICATION_JSON)); + + if (measuresResponse.getStatusInfo().getFamily() != SUCCESSFUL) { + throw new RuntimeException("Error in adding measure"); + } + } else { + throw new RuntimeException(("Service is not up")); + } + } + + public void updateMeasure(final ServiceMeasure measure) { + if (isUp()) { + Response measuresResponse = client.target(baseUrl) + .path(PATH_MEASURES) + .path(measure.getId().toString()) + .request(APPLICATION_JSON) + .put(Entity.entity(measure, APPLICATION_JSON)); + + if (measuresResponse.getStatusInfo().getFamily() != SUCCESSFUL) { + throw new RuntimeException("Error in updating measure"); + } + } else { + throw new RuntimeException(("Service is not up")); + } + } + + public List getMeasures() { + if (isUp()) { + Response measuresResponse = client.target(baseUrl) + .path(PATH_MEASURES) + .request(APPLICATION_JSON).get(); + + if (measuresResponse.getStatusInfo().getFamily() == SUCCESSFUL) { + return measuresResponse.readEntity(new GenericType>() {}); + } + + return null; + } + + throw new RuntimeException(("Service is not up")); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java index 807fdbbf..46aa14e2 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java @@ -6,6 +6,7 @@ import org.devgateway.toolkit.persistence.dao.data.CSVDataset; import org.devgateway.toolkit.persistence.dao.data.Dataset; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dto.ServiceMeasure; import org.devgateway.toolkit.persistence.dto.ServiceMetadata; import org.devgateway.toolkit.persistence.dto.ServiceDimension; import org.devgateway.toolkit.persistence.service.data.CSVDatasetService; @@ -19,6 +20,7 @@ import java.io.File; import java.io.IOException; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import static org.devgateway.toolkit.forms.client.ClientConstants.CODE_PREFIX; @@ -129,4 +131,25 @@ public void addDimensionToService(final String service, final ServiceDimension s ServiceMetadata serviceMetadata = eurekaClientService.findByName(service); new DatasetClient(serviceMetadata.getUrl()).addDimension(serviceDimension); } + + public List getMeasures(final String serviceName) { + ServiceMetadata service = eurekaClientService.findByName(serviceName); + return new DatasetClient(service.getUrl()).getMeasures(); + } + + public ServiceMeasure getMeasureById(final String serviceName, final long id) { + ServiceMetadata service = eurekaClientService.findByName(serviceName); + return new DatasetClient(service.getUrl()).getMeasureById(id); + } + + public void updateMeasure(final String serviceName, final ServiceMeasure measure) { + ServiceMetadata service = eurekaClientService.findByName(serviceName); + new DatasetClient(service.getUrl()).updateMeasure(measure); + } + + public void addMeasureToService(final String service, final ServiceMeasure serviceMeasure) { + ServiceMetadata serviceMetadata = eurekaClientService.findByName(service); + new DatasetClient(serviceMetadata.getUrl()).addMeasure(serviceMeasure); + } + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java index df0c7324..a088fded 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java @@ -27,6 +27,7 @@ import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceDimensionsPage; +import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceMeasuresPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListCSVDatasetPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; import org.devgateway.toolkit.persistence.dto.ServiceMetadata; @@ -39,7 +40,6 @@ import static de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType.database_s; import static de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType.layer_group_s; import static de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType.ruler_s; -import static org.devgateway.toolkit.forms.WebConstants.PARAM_ENTITY; import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; /** @@ -59,7 +59,7 @@ public DataServicePage(final PageParameters parameters) { List links = new ArrayList<>(); links.add(getEntityLink("datasets", getServicePageClass(serviceMetadata.getType()), database_s)); - links.add(getEntityLink("measures", ListServiceDimensionsPage.class, ruler_s)); + links.add(getEntityLink("measures", ListServiceMeasuresPage.class, ruler_s)); links.add(getEntityLink("dimensions", ListServiceDimensionsPage.class, chart_bar_s)); links.add(getEntityLink("categories", ListServiceDimensionsPage.class, layer_group_s)); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.html new file mode 100644 index 00000000..fe0bf964 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.html @@ -0,0 +1,25 @@ + + + + +
+
+
+ +
+
+ + +
+
+
+
+
+
+ +
+
+
+ + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java new file mode 100644 index 00000000..d0c984a1 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java @@ -0,0 +1,373 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.admin; + +import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; +import de.agilecoders.wicket.core.markup.html.bootstrap.dialog.TextContentModal; +import de.agilecoders.wicket.core.markup.html.bootstrap.form.BootstrapForm; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; +import org.apache.wicket.Page; +import org.apache.wicket.ajax.AjaxEventBehavior; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.model.CompoundPropertyModel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.ResourceModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.validation.ValidationError; +import org.devgateway.toolkit.forms.WebConstants; +import org.devgateway.toolkit.forms.exceptions.NullListPageClassException; +import org.devgateway.toolkit.forms.service.DatasetClientService; +import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; +import org.devgateway.toolkit.forms.wicket.components.form.BootstrapSubmitButton; +import org.devgateway.toolkit.forms.wicket.components.form.GenericBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.components.form.visitors.GenericBootstrapValidationVisitor; +import org.devgateway.toolkit.forms.wicket.page.BasePage; +import org.devgateway.toolkit.persistence.dto.ServiceEntity; +import org.springframework.orm.ObjectOptimisticLockingFailureException; + +public abstract class AbstractEditServiceEntityPage extends BasePage { + private static final long serialVersionUID = -2184956023986944919L; + + /** + * Factory method for the new instance of the entity being editing. This + * will be invoked only when the parameter PARAM_ID is null + * + * @return + */ + /** + * The repository used to fetch and save the entity, this is initialized in + * subclasses + */ + protected Class listPageClass; + + @SpringBean + protected DatasetClientService datasetClientService; + + /** + * The form used by all subclasses + */ + protected EditForm editForm; + + private CompoundPropertyModel compoundModel; + + /** + * the entity id, or null if a new entity is requested + */ + protected Long entityId; + + protected String serviceName; + + /** + * This is a wrapper model that ensures we can easily edit the properties of + * the entity + */ + /** + * generic submit button for the form + */ + protected BootstrapSubmitButton saveButton; + + /** + * generic delete button for the form + */ + protected TextContentModal cancelModal; + + protected TextContentModal saveFailedModal; + + public EditForm getEditForm() { + return editForm; + } + + public GenericBootstrapValidationVisitor getBootstrapValidationVisitor(final AjaxRequestTarget target) { + return new GenericBootstrapValidationVisitor(target); + } + + protected TextContentModal createCancelModal() { + final TextContentModal cancelModal = new TextContentModal("cancelModal", + Model.of("Are you sure you want to cancel? Any changes made will be lost.")); + + final LaddaAjaxButton cancelButton = new BootstrapCancelButton("button", Model.of("Yes")) { + private static final long serialVersionUID = -9144254663723097155L; + + @Override + protected void onSubmit(final AjaxRequestTarget target) { + cancelModal.appendCloseDialogJavaScript(target); + setResponsePage(listPageClass, getCancelPageParameters()); + } + }; + + cancelButton.setType(Buttons.Type.Success); + cancelModal.addButton(cancelButton); + cancelModal.addCloseButton(Model.of("No")); + + return cancelModal; + } + + protected TextContentModal createSaveFailedModal() { + final TextContentModal modal = new TextContentModal("saveFailedModal", Model.of("Save failed!")); + modal.header(new ResourceModel("error")); + final LaddaAjaxButton okButton = new LaddaAjaxButton("button", Buttons.Type.Info) { + @Override + protected void onSubmit(final AjaxRequestTarget target) { + setResponsePage(listPageClass); + } + }; + okButton.setDefaultFormProcessing(false); + okButton.setLabel(Model.of("OK")); + modal.addButton(okButton); + + modal.add(new AjaxEventBehavior("hidden.bs.modal") { + @Override + protected void onEvent(final AjaxRequestTarget target) { + setResponsePage(listPageClass); + } + }); + + return modal; + } + + public class EditForm extends BootstrapForm { + private static final long serialVersionUID = -9127043819229346784L; + + /** + * wrap the model with a {@link CompoundPropertyModel} to ease editing + * of fields + * + * @param model + */ + public void setCompoundPropertyModel(final IModel model) { + compoundModel = new CompoundPropertyModel(model); + setModel(compoundModel); + } + + public EditForm(final String id, final IModel model) { + this(id); + setCompoundPropertyModel(model); + } + + public EditForm(final String id) { + super(id); + + setOutputMarkupId(true); + + saveButton = getSaveEditPageButton(); + add(saveButton); + + cancelModal = createCancelModal(); + add(cancelModal); + + saveFailedModal = createSaveFailedModal(); + add(saveFailedModal); + + add(getCancelButton("cancel")); + } + } + + protected BootstrapCancelButton getCancelButton(final String id) { + return new BootstrapCancelButton(id, new StringResourceModel("cancelButton", this, null)) { + private static final long serialVersionUID = -249084359200507749L; + + @Override + protected void onSubmit(final AjaxRequestTarget target) { + setResponsePage(listPageClass, getCancelPageParameters()); + } + }; + } + + /** + * Generic functionality for the save page button, this can be extended + * further by subclasses + * + */ + public class SaveEditPageButton extends BootstrapSubmitButton { + private static final long serialVersionUID = 9075809391795974349L; + + private boolean redirect = true; + + private boolean redirectToSelf = false; + + public SaveEditPageButton(final String id, final IModel model) { + super(id, model); + } + + @Override + protected void onSubmit(final AjaxRequestTarget target) { + try { + // save the object and go back to the list page + T entity = editForm.getModelObject(); + + if (editForm.getModelObject().getId() != null) { + updateEntity(entity); + } else { + createEntity(entity); + } + + // only redirect if redirect is true + if (redirectToSelf) { + // we need to close the blockUI if it's opened and enable all + // the buttons + target.appendJavaScript("$.unblockUI();"); + target.appendJavaScript("$('#" + editForm.getMarkupId() + " button').prop('disabled', false);"); + } else if (redirect) { + setResponsePage(getResponsePage(), getParameterPage()); + } + + // redirect is set back to true, which is the default behavior + redirect = true; + redirectToSelf = false; + } catch (ObjectOptimisticLockingFailureException e) { + saveFailedModal.show(target); + } + } + + /** + * by default, submit button returns back to listPage + * + * @return + */ + protected Class getResponsePage() { + return listPageClass; + } + + /** + * no params by default + * + * @return + */ + protected PageParameters getParameterPage() { + return getSaveEditParameters(); + } + + @Override + protected void onError(final AjaxRequestTarget target) { + // make all errors visible + GenericBootstrapValidationVisitor genericBootstrapValidationVisitor = getBootstrapValidationVisitor(target); + editForm.visitChildren(GenericBootstrapFormComponent.class, genericBootstrapValidationVisitor); + + ValidationError error = new ValidationError(); + error.addKey("formHasErrors"); + error(error); + + target.add(feedbackPanel); + + // autoscroll down to the feedback panel + target.appendJavaScript("$('html, body').animate({scrollTop: $(\".feedbackPanel\").offset().top}, 500);"); + } + + /** + * @return the redirect + */ + public boolean isRedirect() { + return redirect; + } + + /** + * @param redirect the redirect to set + */ + public void setRedirect(final boolean redirect) { + this.redirect = redirect; + } + + /** + * @param redirectToSelf the redirectToSelf to set + */ + public void setRedirectToSelf(final boolean redirectToSelf) { + this.redirectToSelf = redirectToSelf; + } + + /** + * @return the redirectToSelf + */ + public boolean isRedirectToSelf() { + return redirectToSelf; + } + } + + protected PageParameters getSaveEditParameters() { + return getParamsWithServiceInformation(); + } + + protected PageParameters getCancelPageParameters() { + return getParamsWithServiceInformation(); + } + + /** + * Override this to create new save buttons with additional behaviors + * + * @return + */ + protected SaveEditPageButton getSaveEditPageButton() { + return new SaveEditPageButton("save", new StringResourceModel("saveButton", this, null)); + } + + public AbstractEditServiceEntityPage(final PageParameters parameters) { + super(parameters); + + if (!parameters.get(WebConstants.PARAM_ID).isNull()) { + entityId = parameters.get(WebConstants.PARAM_ID).toLongObject(); + } + + editForm = new EditForm("editForm"); + editForm.setMultiPart(true); + + add(editForm); + + // section in child + pageTitle.setDefaultModel(getTitleModel()); + + serviceName = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + // we dont like receiving null list pages + if (listPageClass == null) { + throw new NullListPageClassException(); + } + + IModel model = null; + + if (entityId != null) { + T entity = getEntityById(entityId); + model = Model.of(entity); + } else { + T entity = newInstance(); + if (entity != null) { + model = Model.of(entity); + } + } + + if (model != null) { + editForm.setCompoundPropertyModel(model); + } + + } + + protected StringResourceModel getTitleModel() { + if (entityId == null) { + return new StringResourceModel("page.title.add", this, null); + } else { + return new StringResourceModel("page.title.edit", this, null); + } + } + + protected PageParameters getParamsWithServiceInformation() { + String service = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + + PageParameters pageParams = new PageParameters(); + pageParams.add(WebConstants.PARAM_SERVICE, service); + + return pageParams; + } + + protected abstract T newInstance(); + + protected abstract T getEntityById(Long id); + + protected abstract void createEntity(T entity); + + protected abstract void updateEntity(T entity); + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.properties new file mode 100644 index 00000000..ed79a5cc --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.properties @@ -0,0 +1,18 @@ +############################################################################### +# Copyright (c) 2015 Development Gateway, Inc and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the MIT License (MIT) +# which accompanies this distribution, and is available at +# https://opensource.org/licenses/MIT +# +# Contributors: +# Development Gateway - initial API and implementation +############################################################################### +page.title=Edit Entity +page.title.add=Add Entity +page.title.edit=Edit Entity +cancelButton=Cancel +saveButton=Save +formHasErrors=The form has errors or is missing information and cannot be submitted. Please scroll up, fix all the errors (highlighted in red) and re-submit! +error=Error \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.html index 6d1a9260..dd815028 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.html @@ -3,31 +3,14 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -
-
-
-
-
-
- -
+
+
+
+
+
+
+
- diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java index 83399655..52e7d59a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java @@ -37,335 +37,18 @@ * to one entity for editing */ @MountPath(value = "/editServiceDimension") -public class EditServiceDimensionPage extends BasePage { +public class EditServiceDimensionPage extends AbstractEditServiceEntityPage { private static final long serialVersionUID = -1594571319284288551L; - private static final Logger logger = LoggerFactory.getLogger(EditServiceDimensionPage.class); - - /** - * Factory method for the new instance of the entity being editing. This - * will be invoked only when the parameter PARAM_ID is null - * - * @return - */ - /** - * The repository used to fetch and save the entity, this is initialized in - * subclasses - */ - /** - * The page that is responsible for listing the entities (used here as a - * return reference after successful save) - */ - protected Class listPageClass; - - @SpringBean - DatasetClientService datasetClientService; - - /** - * The form used by all subclasses - */ - protected EditForm editForm; - - private CompoundPropertyModel compoundModel; - - /** - * the entity id, or null if a new entity is requested - */ - protected Long entityId; - - /** - * This is a wrapper model that ensures we can easily edit the properties of - * the entity - */ - /** - * generic submit button for the form - */ - protected BootstrapSubmitButton saveButton; - - /** - * generic delete button for the form - */ - protected TextContentModal cancelModal; - - protected TextContentModal saveFailedModal; - - public EditForm getEditForm() { - return editForm; - } - - public GenericBootstrapValidationVisitor getBootstrapValidationVisitor(final AjaxRequestTarget target) { - return new GenericBootstrapValidationVisitor(target); - } - - protected TextContentModal createCancelModal() { - final TextContentModal cancelModal = new TextContentModal("cancelModal", - Model.of("Are you sure you want to cancel? Any changes made will be lost.")); - - final LaddaAjaxButton cancelButton = new BootstrapCancelButton("button", Model.of("Yes")) { - private static final long serialVersionUID = -9144254663723097155L; - - @Override - protected void onSubmit(final AjaxRequestTarget target) { - cancelModal.appendCloseDialogJavaScript(target); - setResponsePage(listPageClass, getCancelPageParameters()); - } - }; - - cancelButton.setType(Buttons.Type.Success); - cancelModal.addButton(cancelButton); - cancelModal.addCloseButton(Model.of("No")); - - return cancelModal; - } - - protected TextContentModal createSaveFailedModal() { - final TextContentModal modal = new TextContentModal("saveFailedModal", Model.of("Save failed!")); - modal.header(new ResourceModel("error")); - final LaddaAjaxButton okButton = new LaddaAjaxButton("button", Buttons.Type.Info) { - @Override - protected void onSubmit(final AjaxRequestTarget target) { - setResponsePage(listPageClass); - } - }; - okButton.setDefaultFormProcessing(false); - okButton.setLabel(Model.of("OK")); - modal.addButton(okButton); - - modal.add(new AjaxEventBehavior("hidden.bs.modal") { - @Override - protected void onEvent(final AjaxRequestTarget target) { - setResponsePage(listPageClass); - } - }); - - return modal; - } - - - public class EditForm extends BootstrapForm { - private static final long serialVersionUID = -9127043819229346784L; - - /** - * wrap the model with a {@link CompoundPropertyModel} to ease editing - * of fields - * - * @param model - */ - public void setCompoundPropertyModel(final IModel model) { - compoundModel = new CompoundPropertyModel(model); - setModel(compoundModel); - } - - public EditForm(final String id, final IModel model) { - this(id); - setCompoundPropertyModel(model); - } - - public EditForm(final String id) { - super(id); - - setOutputMarkupId(true); - - saveButton = getSaveEditPageButton(); - add(saveButton); - - cancelModal = createCancelModal(); - add(cancelModal); - - saveFailedModal = createSaveFailedModal(); - add(saveFailedModal); - - add(getCancelButton("cancel")); - } - } - - protected BootstrapCancelButton getCancelButton(final String id) { - return new BootstrapCancelButton(id, new StringResourceModel("cancelButton", this, null)) { - private static final long serialVersionUID = -249084359200507749L; - - @Override - protected void onSubmit(final AjaxRequestTarget target) { - setResponsePage(listPageClass, getCancelPageParameters()); - } - }; - } - - /** - * Generic functionality for the save page button, this can be extended - * further by subclasses - * - */ - public class SaveEditPageButton extends BootstrapSubmitButton { - private static final long serialVersionUID = 9075809391795974349L; - - private boolean redirect = true; - - private boolean redirectToSelf = false; - - public SaveEditPageButton(final String id, final IModel model) { - super(id, model); - } - - @Override - protected void onSubmit(final AjaxRequestTarget target) { - try { - // save the object and go back to the list page - ServiceDimension dimension = editForm.getModelObject(); - - if (editForm.getModelObject().getId() != null) { - updateDimension(dimension); - } else { - createDimension(dimension); - } - - // only redirect if redirect is true - if (redirectToSelf) { - // we need to close the blockUI if it's opened and enable all - // the buttons - target.appendJavaScript("$.unblockUI();"); - target.appendJavaScript("$('#" + editForm.getMarkupId() + " button').prop('disabled', false);"); - } else if (redirect) { - setResponsePage(getResponsePage(), getParameterPage()); - } - - // redirect is set back to true, which is the default behavior - redirect = true; - redirectToSelf = false; - } catch (ObjectOptimisticLockingFailureException e) { - saveFailedModal.show(target); - } - } - - /** - * by default, submit button returns back to listPage - * - * @return - */ - protected Class getResponsePage() { - return listPageClass; - } - - /** - * no params by default - * - * @return - */ - protected PageParameters getParameterPage() { - return getSaveEditParameters(); - } - - @Override - protected void onError(final AjaxRequestTarget target) { - // make all errors visible - GenericBootstrapValidationVisitor genericBootstrapValidationVisitor = getBootstrapValidationVisitor(target); - editForm.visitChildren(GenericBootstrapFormComponent.class, genericBootstrapValidationVisitor); - - ValidationError error = new ValidationError(); - error.addKey("formHasErrors"); - error(error); - - target.add(feedbackPanel); - - // autoscroll down to the feedback panel - target.appendJavaScript("$('html, body').animate({scrollTop: $(\".feedbackPanel\").offset().top}, 500);"); - } - - /** - * @return the redirect - */ - public boolean isRedirect() { - return redirect; - } - - /** - * @param redirect the redirect to set - */ - public void setRedirect(final boolean redirect) { - this.redirect = redirect; - } - - /** - * @param redirectToSelf the redirectToSelf to set - */ - public void setRedirectToSelf(final boolean redirectToSelf) { - this.redirectToSelf = redirectToSelf; - } - - /** - * @return the redirectToSelf - */ - public boolean isRedirectToSelf() { - return redirectToSelf; - } - } - - protected PageParameters getSaveEditParameters() { - return getParamsWithServiceInformation(); - } - - protected PageParameters getCancelPageParameters() { - return getParamsWithServiceInformation(); - } - - /** - * Override this to create new save buttons with additional behaviors - * - * @return - */ - protected SaveEditPageButton getSaveEditPageButton() { - return new SaveEditPageButton("save", new StringResourceModel("saveButton", this, null)); - } - public EditServiceDimensionPage(final PageParameters parameters) { super(parameters); - - if (!parameters.get(WebConstants.PARAM_ID).isNull()) { - entityId = parameters.get(WebConstants.PARAM_ID).toLongObject(); - } - - editForm = new EditForm("editForm"); - - // use this in order to avoid "ServletRequest does not contain multipart - // content" error - // this error appears when we have a file upload component that is - // hidden or not present in the page when the form is created - editForm.setMultiPart(true); - - add(editForm); - - // section in child - pageTitle.setDefaultModel(getTitleModel()); - this.listPageClass = ListServiceDimensionsPage.class; - } @Override protected void onInitialize() { super.onInitialize(); - // we dont like receiving null list pages - if (listPageClass == null) { - throw new NullListPageClassException(); - } - - IModel model = null; - String service = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); - - if (entityId != null) { - ServiceDimension serviceDimension = datasetClientService.getDimensionById(service, entityId); - model = new DozerModel<>(serviceDimension); - } else { - ServiceDimension serviceDimension = new ServiceDimension(); - if (serviceDimension != null) { - model = new DozerModel<>(serviceDimension); - } - } - - if (model != null) { - editForm.setCompoundPropertyModel(model); - } - final TextFieldBootstrapFormComponent code = new TextFieldBootstrapFormComponent<>("code"); code.setEnabled(false); editForm.add(code); @@ -379,31 +62,24 @@ protected void onInitialize() { editForm.add(position); } - protected StringResourceModel getTitleModel() { - if (entityId == null) { - return new StringResourceModel("page.title.add", this, null); - } else { - return new StringResourceModel("page.title.edit", this, null); - } + @Override + protected ServiceDimension newInstance() { + return new ServiceDimension(); } - protected PageParameters getParamsWithServiceInformation() { - String service = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); - - PageParameters pageParams = new PageParameters(); - pageParams.add(WebConstants.PARAM_SERVICE, service); - - return pageParams; + @Override + protected ServiceDimension getEntityById(final Long id) { + return datasetClientService.getDimensionById(serviceName, id); } - private void createDimension(ServiceDimension serviceDimension) { - String service = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); - datasetClientService.addDimensionToService(service, serviceDimension); + @Override + protected void createEntity(final ServiceDimension entity) { + datasetClientService.addDimensionToService(serviceName, entity); } - private void updateDimension(ServiceDimension serviceDimension) { - String service = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); - datasetClientService.updateDimension(service, serviceDimension); + @Override + protected void updateEntity(final ServiceDimension entity) { + datasetClientService.updateDimension(serviceName, entity); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties index 1071a3d2..a6b232ca 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties @@ -14,8 +14,4 @@ page.title.add=Add Dimension page.title.edit=Edit Dimension code.label=Code value.label=Value -position.label=Position -cancelButton=Cancel -saveButton=Save -formHasErrors=The form has errors or is missing information and cannot be submitted. Please scroll up, fix all the errors (highlighted in red) and re-submit! -error=Error \ No newline at end of file +position.label=Position \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html new file mode 100644 index 00000000..dd815028 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html @@ -0,0 +1,16 @@ + + + + +
+
+
+
+
+
+
+
+
+ + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java new file mode 100644 index 00000000..67482e4c --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java @@ -0,0 +1,60 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.admin; + +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceDimensionsPage; +import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceMeasuresPage; +import org.devgateway.toolkit.persistence.dto.ServiceMeasure; +import org.wicketstuff.annotation.mount.MountPath; + +/** + * @author mpostelnicu Page used to make editing easy, extend to get easy access + * to one entity for editing + */ +@MountPath(value = "/editServiceMeasure") +public class EditServiceMeasurePage extends AbstractEditServiceEntityPage { + private static final long serialVersionUID = -9013029067860834250L; + + public EditServiceMeasurePage(final PageParameters parameters) { + super(parameters); + this.listPageClass = ListServiceMeasuresPage.class; + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + final TextFieldBootstrapFormComponent code = new TextFieldBootstrapFormComponent<>("code"); + code.setEnabled(false); + editForm.add(code); + + final TextFieldBootstrapFormComponent value = new TextFieldBootstrapFormComponent<>("value"); + value.getField().setRequired(true); + editForm.add(value); + + final TextFieldBootstrapFormComponent position = new TextFieldBootstrapFormComponent<>("position"); + position.getField().setRequired(true); + editForm.add(position); + } + + @Override + protected ServiceMeasure newInstance() { + return new ServiceMeasure(); + } + + @Override + protected ServiceMeasure getEntityById(final Long id) { + return datasetClientService.getMeasureById(serviceName, id); + } + + @Override + protected void createEntity(final ServiceMeasure entity) { + datasetClientService.addMeasureToService(serviceName, entity); + } + + @Override + protected void updateEntity(final ServiceMeasure entity) { + datasetClientService.updateMeasure(serviceName, entity); + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties new file mode 100644 index 00000000..c206dd70 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties @@ -0,0 +1,17 @@ +############################################################################### +# Copyright (c) 2022 Development Gateway, Inc and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the MIT License (MIT) +# which accompanies this distribution, and is available at +# https://opensource.org/licenses/MIT +# +# Contributors: +# Development Gateway - initial API and implementation +############################################################################### +page.title=Edit Measure +page.title.add=Add Measure +page.title.edit=Edit Measure +code.label=Code +value.label=Value +position.label=Position \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.html index 3eaf2050..da324d7e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.html @@ -2,14 +2,11 @@ - -
-
\ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties index bd208f37..c98adaf7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties @@ -1,4 +1,3 @@ page.title=Dimensions actionsColumn=Edit -dimensions=Dimensions edit=Edit \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage$ActionPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage$ActionPanel.html new file mode 100644 index 00000000..ad387fd1 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage$ActionPanel.html @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.html new file mode 100644 index 00000000..da324d7e --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.html @@ -0,0 +1,12 @@ + + + + +
+
+
+
+
+
+ + \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java new file mode 100644 index 00000000..fd01e749 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java @@ -0,0 +1,135 @@ +/******************************************************************************* + * Copyright (c) 2015 Development Gateway, Inc and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the MIT License (MIT) + * which accompanies this distribution, and is available at + * https://opensource.org/licenses/MIT + * + * Contributors: + * Development Gateway - initial API and implementation + *******************************************************************************/ +package org.devgateway.toolkit.forms.wicket.page.lists.admin; + +import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapBookmarkablePageLink; +import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; +import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.markup.html.panel.GenericPanel; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.WebConstants; +import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.service.DatasetClientService; +import org.devgateway.toolkit.forms.wicket.components.table.AjaxFallbackBootstrapDataTable; +import org.devgateway.toolkit.forms.wicket.page.BasePage; +import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServiceMeasurePage; +import org.devgateway.toolkit.persistence.dto.ServiceMeasure; +import org.wicketstuff.annotation.mount.MountPath; + +import java.util.ArrayList; +import java.util.List; + +import static org.devgateway.toolkit.forms.WebConstants.PAGE_SIZE; + +@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) +@MountPath(value = "/measures") +public class ListServiceMeasuresPage extends BasePage { + + private static final long serialVersionUID = -6132847935476573446L; + + protected AjaxFallbackBootstrapDataTable dataTable; + + protected ServiceMeasureProvider dataProvider; + + protected List> columns; + + @SpringBean + private DatasetClientService datasetClientService; + + protected int pageRowNo = 0; + + public ListServiceMeasuresPage(final PageParameters pageParameters) { + super(pageParameters); + + String service = pageParameters.get(WebConstants.PARAM_SERVICE).toString(); + dataProvider = new ServiceMeasureProvider(datasetClientService, service); + + columns = new ArrayList<>(); + columns.add(new PropertyColumn<>(new Model<>("Code"), "code", "code")); + columns.add(new PropertyColumn<>(new Model<>("Value"), "value", "value")); + columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + dataTable = new AjaxFallbackBootstrapDataTable( + "table", columns, dataProvider, getPageSize()) { + private static final long serialVersionUID = -7263599298497560059L; + + @Override + protected void onPageChanged() { + pageRowNo = 0; + } + }; + + columns.add(new AbstractColumn(new StringResourceModel("actionsColumn", this, null)) { + private static final long serialVersionUID = -7447601118569862123L; + + @Override + public void populateItem(final Item> cellItem, final String componentId, + final IModel model) { + cellItem.add(getActionPanel(componentId, model)); + } + }); + + add(dataTable); + } + + protected int getPageSize() { + return PAGE_SIZE; + } + + public ActionPanel getActionPanel(final String id, final IModel model) { + return new ActionPanel(id, model); + } + + public class ActionPanel extends GenericPanel { + private static final long serialVersionUID = -4547406060736744071L; + + protected BootstrapBookmarkablePageLink editItemPageLink; + + /** + * @param id + * @param model + */ + public ActionPanel(final String id, final IModel model) { + super(id, model); + + final PageParameters pageParameters = new PageParameters(); + + @SuppressWarnings("unchecked") + ServiceMeasure entity = (ServiceMeasure) ActionPanel.this.getDefaultModelObject(); + if (entity != null) { + pageParameters.set(WebConstants.PARAM_ID, entity.getId()); + } + pageParameters.set(WebConstants.PARAM_SERVICE, getPageParameters().get(WebConstants.PARAM_SERVICE)); + + editItemPageLink = + new BootstrapBookmarkablePageLink<>("edit", EditServiceMeasurePage.class, pageParameters, Buttons.Type.Info); + editItemPageLink.setIconType(FontAwesome5IconType.edit_s).setSize(Buttons.Size.Small) + .setLabel(new StringResourceModel("edit", this, null)); + add(editItemPageLink); + } + } +} \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties new file mode 100644 index 00000000..0be2f34b --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties @@ -0,0 +1,3 @@ +page.title=Measures +actionsColumn=Edit +edit=Edit \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMeasureProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMeasureProvider.java new file mode 100644 index 00000000..47eb8238 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMeasureProvider.java @@ -0,0 +1,76 @@ +package org.devgateway.toolkit.forms.wicket.page.lists.admin; + +import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; +import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.devgateway.toolkit.forms.service.DatasetClientService; +import org.devgateway.toolkit.persistence.dto.ServiceDimension; +import org.devgateway.toolkit.persistence.dto.ServiceMeasure; + +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + +/** + * Data provider used to provide information about the services + * + * @author Viorel Chihai + */ +public class ServiceMeasureProvider extends SortableDataProvider { + private static final long serialVersionUID = 1858130875067823547L; + + protected DatasetClientService datasetClientService; + + private final String serviceName; + + public ServiceMeasureProvider(final DatasetClientService datasetClientService, final String serviceName) { + this.datasetClientService = datasetClientService; + this.serviceName = serviceName; + } + + @Override + public Iterator iterator(final long first, final long count) { + List services = datasetClientService.getMeasures(serviceName); + + if (first > services.size()) { + return Collections.emptyIterator(); + } + + if (getSort() == null || getSort().getProperty().equals("label")) { + Comparator comparator = new ServiceMeasureComparator(); + + if (getSort() != null && getSort().isAscending()) { + comparator = comparator.reversed(); + } + + Collections.sort(services, comparator); + } + + return services.subList((int) first, (int) Math.min(first + count, services.size())).iterator(); + } + + @Override + public SortParam getSort() { + return super.getSort(); + } + + @Override + public long size() { + return datasetClientService.getMeasures(serviceName).size(); + } + + @Override + public IModel model(final ServiceMeasure serviceMeasure) { + return Model.of(serviceMeasure); + } + + protected class ServiceMeasureComparator implements Comparator { + @Override + public int compare(final ServiceMeasure s1, final ServiceMeasure s2) { + return String.CASE_INSENSITIVE_ORDER.compare(s1.getCode(), s2.getCode()); + } + } + +} \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java new file mode 100644 index 00000000..10aba2d1 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java @@ -0,0 +1,50 @@ +package org.devgateway.toolkit.persistence.dto; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.io.Serializable; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServiceCategory extends ServiceEntity { + + private String code; + + private String value; + + private Integer position; + + private CssStyle categoryStyle; + + public String getCode() { + return code; + } + + public void setCode(final String code) { + this.code = code; + } + + public String getValue() { + return value; + } + + public void setValue(final String value) { + this.value = value; + } + + public Integer getPosition() { + return position; + } + + public void setPosition(final Integer position) { + this.position = position; + } + + public CssStyle getCategoryStyle() { + return categoryStyle; + } + + public void setCategoryStyle(final CssStyle categoryStyle) { + this.categoryStyle = categoryStyle; + } + +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceDimension.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceDimension.java index b8a0a117..92e90d9f 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceDimension.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceDimension.java @@ -2,116 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import java.io.Serializable; +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServiceDimension extends ServiceCategory { -@JsonIgnoreProperties({"labels", "descriptions"}) -public class ServiceDimension implements Serializable { - - private Long id; - - private String code; - - private String label; - - private String type; - - private String value; - - private Integer position; - - private CssStyle categoryStyle; - - private String field; - - private String fieldType; - - private Class aClass; - - public ServiceDimension() { - } - - public ServiceDimension(final Long id, final String label) { - this.id = id; - this.label = label; - } - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public String getLabel() { - return label; - } - - public void setLabel(final String label) { - this.label = label; - } - - public String getType() { - return type; - } - - public void setType(final String type) { - this.type = type; - } - - public String getCode() { - return code; - } - - public void setCode(final String code) { - this.code = code; - } - - public String getValue() { - return value; - } - - public void setValue(final String value) { - this.value = value; - } - - public Integer getPosition() { - return position; - } - - public void setPosition(final Integer position) { - this.position = position; - } - - public CssStyle getCategoryStyle() { - return categoryStyle; - } - - public void setCategoryStyle(final CssStyle categoryStyle) { - this.categoryStyle = categoryStyle; - } - - public String getField() { - return field; - } - - public void setField(final String field) { - this.field = field; - } - - public String getFieldType() { - return fieldType; - } - - public void setFieldType(final String fieldType) { - this.fieldType = fieldType; - } - - public Class getaClass() { - return aClass; - } - - public void setaClass(final Class aClass) { - this.aClass = aClass; - } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceEntity.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceEntity.java new file mode 100644 index 00000000..2599a8ce --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceEntity.java @@ -0,0 +1,23 @@ +package org.devgateway.toolkit.persistence.dto; + +import java.io.Serializable; + +public class ServiceEntity implements Serializable { + + private Long id; + + ServiceEntity() { + } + + public ServiceEntity(final Long id) { + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMeasure.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMeasure.java new file mode 100644 index 00000000..7d878333 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMeasure.java @@ -0,0 +1,38 @@ +package org.devgateway.toolkit.persistence.dto; + +public class ServiceMeasure extends ServiceCategory { + + private String filter; + + private String expression; + + private String delegate; + + public ServiceMeasure() { + } + + public String getFilter() { + return filter; + } + + public void setFilter(final String filter) { + this.filter = filter; + } + + public String getExpression() { + return expression; + } + + public void setExpression(final String expression) { + this.expression = expression; + } + + public String getDelegate() { + return delegate; + } + + public void setDelegate(final String delegate) { + this.delegate = delegate; + } + +} From 364e0c9f1f5816614fbc5fda8754ea604438aa9a Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 29 Sep 2022 17:59:46 +0300 Subject: [PATCH 084/137] TOBACCO-990: Add editing colors in measures --- .../admin/AbstractEditServiceEntityPage.java | 18 ++++++++++----- .../AbstractEditServiceEntityPage.properties | 6 ++--- .../admin/EditServiceDimensionPage.properties | 6 ++--- .../edit/admin/EditServiceMeasurePage.html | 11 ++++++++++ .../edit/admin/EditServiceMeasurePage.java | 22 +++++++++++++++++++ .../admin/EditServiceMeasurePage.properties | 13 +++++++---- .../admin/ListServiceDimensionsPage.java | 7 ++++++ .../ListServiceDimensionsPage.properties | 2 +- .../lists/admin/ListServiceMeasuresPage.java | 19 ++++++++++++++++ .../admin/ListServiceMeasuresPage.properties | 2 +- .../forms/wicket/styles/BaseStyles.css | 7 ++++++ .../toolkit/persistence/dto/CssStyle.java | 4 +++- .../persistence/dto/ServiceCategory.java | 2 -- 13 files changed, 98 insertions(+), 21 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java index d0c984a1..b931fcbb 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java @@ -7,6 +7,7 @@ import org.apache.wicket.Page; import org.apache.wicket.ajax.AjaxEventBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; @@ -26,6 +27,10 @@ import org.devgateway.toolkit.persistence.dto.ServiceEntity; import org.springframework.orm.ObjectOptimisticLockingFailureException; +import java.text.MessageFormat; + +import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; + public abstract class AbstractEditServiceEntityPage extends BasePage { private static final long serialVersionUID = -2184956023986944919L; @@ -315,7 +320,7 @@ public AbstractEditServiceEntityPage(final PageParameters parameters) { // section in child pageTitle.setDefaultModel(getTitleModel()); - serviceName = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + serviceName = getPageParameters().get(PARAM_SERVICE).toString(); } @Override @@ -345,19 +350,20 @@ protected void onInitialize() { } - protected StringResourceModel getTitleModel() { + protected Model getTitleModel() { + String service = getPageParameters().get(PARAM_SERVICE).toString(); if (entityId == null) { - return new StringResourceModel("page.title.add", this, null); + return Model.of(MessageFormat.format(getString("page.title.add"), service)); } else { - return new StringResourceModel("page.title.edit", this, null); + return Model.of(MessageFormat.format(getString("page.title.edit"), service)); } } protected PageParameters getParamsWithServiceInformation() { - String service = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + String service = getPageParameters().get(PARAM_SERVICE).toString(); PageParameters pageParams = new PageParameters(); - pageParams.add(WebConstants.PARAM_SERVICE, service); + pageParams.add(PARAM_SERVICE, service); return pageParams; } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.properties index ed79a5cc..7e2a62e7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.properties @@ -9,9 +9,9 @@ # Contributors: # Development Gateway - initial API and implementation ############################################################################### -page.title=Edit Entity -page.title.add=Add Entity -page.title.edit=Edit Entity +page.title=Edit {0} Entity +page.title.add=Add {0} Entity +page.title.edit=Edit {0} Entity cancelButton=Cancel saveButton=Save formHasErrors=The form has errors or is missing information and cannot be submitted. Please scroll up, fix all the errors (highlighted in red) and re-submit! diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties index a6b232ca..07e531c8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties @@ -9,9 +9,9 @@ # Contributors: # Development Gateway - initial API and implementation ############################################################################### -page.title=Edit Dimension -page.title.add=Add Dimension -page.title.edit=Edit Dimension +page.title=Edit {0} Dimension +page.title.add=Add {0} Dimension +page.title.edit=Edit {0} Dimension code.label=Code value.label=Value position.label=Position \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html index dd815028..6a20430d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html @@ -11,6 +11,17 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java index 67482e4c..36d3e5b1 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java @@ -1,6 +1,8 @@ package org.devgateway.toolkit.forms.wicket.page.edit.admin; +import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.devgateway.toolkit.forms.wicket.components.form.ColorPickerBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceDimensionsPage; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceMeasuresPage; @@ -35,6 +37,26 @@ protected void onInitialize() { final TextFieldBootstrapFormComponent position = new TextFieldBootstrapFormComponent<>("position"); position.getField().setRequired(true); editForm.add(position); + + final TextFieldBootstrapFormComponent expression = new TextFieldBootstrapFormComponent<>("expression"); + expression.setEnabled(false); + editForm.add(expression); + + ColorPickerBootstrapFormComponent colorPicker = new ColorPickerBootstrapFormComponent("color", + new PropertyModel<>(editForm.getModelObject(), "categoryStyle.color")); + editForm.add(colorPicker); + + final TextFieldBootstrapFormComponent className = new TextFieldBootstrapFormComponent<>("className", + new PropertyModel<>(editForm.getModelObject(), "categoryStyle.className")); + editForm.add(className); + + ColorPickerBootstrapFormComponent textColorPicker = new ColorPickerBootstrapFormComponent("textColor", + new PropertyModel<>(editForm.getModelObject(), "categoryStyle.textColor")); + editForm.add(textColorPicker); + + ColorPickerBootstrapFormComponent bckColorPicker = new ColorPickerBootstrapFormComponent("backgroundColor", + new PropertyModel<>(editForm.getModelObject(), "categoryStyle.backgroundColor")); + editForm.add(bckColorPicker); } @Override diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties index c206dd70..6f5227df 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties @@ -9,9 +9,14 @@ # Contributors: # Development Gateway - initial API and implementation ############################################################################### -page.title=Edit Measure -page.title.add=Add Measure -page.title.edit=Edit Measure +page.title=Edit {0} Measure +page.title.add=Add {0} Measure +page.title.edit=Edit {0} Measure code.label=Code value.label=Value -position.label=Position \ No newline at end of file +position.label=Position +expression.label=Expression +color.label=Color +className.label=CSS Class Name +textColor.label=Text Color +backgroundColor.label=Background Color \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java index 1410f67d..3f67c9c5 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java @@ -19,6 +19,7 @@ import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.IModel; @@ -36,6 +37,7 @@ import org.devgateway.toolkit.persistence.dto.ServiceDimension; import org.wicketstuff.annotation.mount.MountPath; +import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; @@ -133,4 +135,9 @@ public ActionPanel(final String id, final IModel model) { add(editItemPageLink); } } + + protected Label getPageTitle() { + String service = getPageParameters().get("service").toString(); + return new Label("pageTitle", Model.of(MessageFormat.format(getString("page.title"), service))); + } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties index c98adaf7..c6bf6a36 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties @@ -1,3 +1,3 @@ -page.title=Dimensions +page.title={0} Dimensions actionsColumn=Edit edit=Edit \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java index fd01e749..75e71237 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java @@ -11,14 +11,17 @@ *******************************************************************************/ package org.devgateway.toolkit.forms.wicket.page.lists.admin; +import de.agilecoders.wicket.core.markup.html.bootstrap.behavior.CssClassNameAppender; import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapBookmarkablePageLink; import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; +import org.apache.wicket.AttributeModifier; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.IModel; @@ -35,6 +38,7 @@ import org.devgateway.toolkit.persistence.dto.ServiceMeasure; import org.wicketstuff.annotation.mount.MountPath; +import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; @@ -67,6 +71,16 @@ public ListServiceMeasuresPage(final PageParameters pageParameters) { columns.add(new PropertyColumn<>(new Model<>("Code"), "code", "code")); columns.add(new PropertyColumn<>(new Model<>("Value"), "value", "value")); columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); + columns.add(new PropertyColumn(new Model<>("Color"), "categoryStyle.color", + "categoryStyle.color") { + @Override + public void populateItem(final Item> item, final String componentId, final IModel rowModel) { + item.add(new Label(componentId, "") + .add(new AttributeModifier("style", "background-color: " + rowModel.getObject().getCategoryStyle().getColor())) + .add(new CssClassNameAppender("color-box")) + ); + } + }); } @Override @@ -132,4 +146,9 @@ public ActionPanel(final String id, final IModel model) { add(editItemPageLink); } } + + protected Label getPageTitle() { + String service = getPageParameters().get("service").toString(); + return new Label("pageTitle", Model.of(MessageFormat.format(getString("page.title"), service))); + } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties index 0be2f34b..1d1c08e8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties @@ -1,3 +1,3 @@ -page.title=Measures +page.title={0} Measures actionsColumn=Edit edit=Edit \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css index 8f44b972..13bb937b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css @@ -287,4 +287,11 @@ button .btn-home-label { .error-row { color: red; +} + +.color-box { + width: 40px; + height: 30px; + display: inline-block; + margin-right: 5px; } \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/CssStyle.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/CssStyle.java index 664a01e5..bf35df37 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/CssStyle.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/CssStyle.java @@ -1,6 +1,8 @@ package org.devgateway.toolkit.persistence.dto; -public class CssStyle { +import java.io.Serializable; + +public class CssStyle implements Serializable { private String backgroundColor; private String textColor; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java index 10aba2d1..549c37c0 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java @@ -2,8 +2,6 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import java.io.Serializable; - @JsonIgnoreProperties(ignoreUnknown = true) public class ServiceCategory extends ServiceEntity { From 29117b843a16e9af26afa294e13ff88883a65a42 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 5 Oct 2022 15:25:37 +0300 Subject: [PATCH 085/137] TOBACCO-1000: Add list and edit categories page. Refactoring the service entity services. --- .../toolkit/forms/client/ClientConstants.java | 3 + .../forms/client/ServiceCategoryClient.java | 29 ++++ .../forms/client/ServiceDimensionClient.java | 29 ++++ .../forms/client/ServiceEntityClient.java | 109 ++++++++++++++ .../forms/client/ServiceMeasureClient.java | 29 ++++ .../NullServiceEntityServiceException.java | 27 ++++ .../admin/BaseServiceEntityService.java | 23 +++ .../admin/BaseServiceEntityServiceImpl.java | 42 ++++++ .../service/admin/ServiceCategoryService.java | 6 + .../admin/ServiceCategoryServiceImpl.java | 25 ++++ .../admin/ServiceDimensionService.java | 6 + .../admin/ServiceDimensionServiceImpl.java | 25 ++++ .../service/admin/ServiceMeasureService.java | 6 + .../admin/ServiceMeasureServiceImpl.java | 25 ++++ .../forms/wicket/page/DataServicePage.java | 3 +- .../admin/AbstractEditServiceEntityPage.java | 23 ++- .../edit/admin/EditServiceCategoryPage.html | 27 ++++ .../edit/admin/EditServiceCategoryPage.java | 65 +++++++++ .../admin/EditServiceCategoryPage.properties | 22 +++ .../edit/admin/EditServiceDimensionPage.java | 55 +------ .../edit/admin/EditServiceMeasurePage.java | 32 +---- ...actListServiceEntityPage$ActionPanel.html} | 0 ...tml => AbstractListServiceEntityPage.html} | 0 .../admin/AbstractListServiceEntityPage.java | 134 ++++++++++++++++++ .../AbstractListServiceEntityPage.properties | 3 + .../admin/ListServiceCategoriesPage.java | 71 ++++++++++ .../ListServiceCategoriesPage.properties | 1 + .../admin/ListServiceDimensionsPage.java | 106 ++------------ .../ListServiceDimensionsPage.properties | 4 +- .../ListServiceMeasuresPage$ActionPanel.html | 8 -- .../lists/admin/ListServiceMeasuresPage.html | 12 -- .../lists/admin/ListServiceMeasuresPage.java | 101 +------------ .../admin/ListServiceMeasuresPage.properties | 4 +- .../lists/admin/ServiceCategoryProvider.java | 33 +++++ .../lists/admin/ServiceDimensionProvider.java | 50 ++----- .../admin/SortableServiceEntityProvider.java | 69 +++++++++ .../persistence/dto/ServiceCategory.java | 9 ++ 37 files changed, 864 insertions(+), 352 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceCategoryClient.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDimensionClient.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceEntityClient.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceMeasureClient.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/exceptions/NullServiceEntityServiceException.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityService.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityServiceImpl.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceCategoryService.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceCategoryServiceImpl.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDimensionService.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDimensionServiceImpl.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceMeasureService.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceMeasureServiceImpl.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties rename forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/{ListServiceDimensionsPage$ActionPanel.html => AbstractListServiceEntityPage$ActionPanel.html} (100%) rename forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/{ListServiceDimensionsPage.html => AbstractListServiceEntityPage.html} (100%) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.properties delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage$ActionPanel.html delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceCategoryProvider.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/SortableServiceEntityProvider.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java index 2f36e44f..536a0e11 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java @@ -15,6 +15,9 @@ public static final class JobStatus { public final static String PATH_MEASURES = "/admin/measures"; + public static final String PATH_CATEGORIES = "/admin/categories"; + + public final static String PATH_CODE = "/code"; public final static String CODE_PREFIX = "tcdi-"; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceCategoryClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceCategoryClient.java new file mode 100644 index 00000000..53701cfb --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceCategoryClient.java @@ -0,0 +1,29 @@ +package org.devgateway.toolkit.forms.client; + +import org.devgateway.toolkit.persistence.dto.ServiceCategory; + +import javax.ws.rs.core.GenericType; +import java.util.List; + +public class ServiceCategoryClient extends ServiceEntityClient { + + public ServiceCategoryClient(final String baseUrl) { + super(baseUrl); + } + + @Override + public String getEntitiesPath() { + return ClientConstants.PATH_CATEGORIES; + } + + @Override + protected GenericType getGenericType() { + return new GenericType() {}; + } + + @Override + protected GenericType> getGenericListType() { + return new GenericType>() {}; + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDimensionClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDimensionClient.java new file mode 100644 index 00000000..2e8a8002 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDimensionClient.java @@ -0,0 +1,29 @@ +package org.devgateway.toolkit.forms.client; + +import org.devgateway.toolkit.persistence.dto.ServiceDimension; + +import javax.ws.rs.core.GenericType; +import java.util.List; + +public class ServiceDimensionClient extends ServiceEntityClient { + + public ServiceDimensionClient(final String baseUrl) { + super(baseUrl); + } + + @Override + public String getEntitiesPath() { + return ClientConstants.PATH_DIMENSIONS; + } + + @Override + protected GenericType getGenericType() { + return new GenericType() {}; + } + + @Override + protected GenericType> getGenericListType() { + return new GenericType>() {}; + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceEntityClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceEntityClient.java new file mode 100644 index 00000000..9fd025fb --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceEntityClient.java @@ -0,0 +1,109 @@ +package org.devgateway.toolkit.forms.client; + +import org.devgateway.toolkit.persistence.dto.ServiceEntity; +import org.glassfish.jersey.client.JerseyClient; +import org.glassfish.jersey.client.JerseyClientBuilder; +import org.glassfish.jersey.media.multipart.MultiPartFeature; + +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.Response; +import java.util.List; + +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL; +import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_HEALTH; + +public abstract class ServiceEntityClient { + + private final JerseyClient client; + + private final String baseUrl; + + public ServiceEntityClient(final String baseUrl) { + this.baseUrl = baseUrl; + this.client = JerseyClientBuilder.createClient(); + this.client.register(MultiPartFeature.class); + } + + public abstract String getEntitiesPath(); + + public List findAll() { + if (isUp()) { + Response response = client.target(baseUrl) + .path(getEntitiesPath()) + .request(APPLICATION_JSON).get(); + + if (response.getStatusInfo().getFamily() == SUCCESSFUL) { + return response.readEntity(getGenericListType()); + } + return null; + } + + throw new RuntimeException(("Service is not up")); + } + + public T findOne(final Long id) { + if (isUp()) { + Response response = client.target(baseUrl) + .path(getEntitiesPath()) + .path(id.toString()) + .request(APPLICATION_JSON).get(); + + if (response.getStatusInfo().getFamily() == SUCCESSFUL) { + return response.readEntity(getGenericType()); + } + + return null; + } + + throw new RuntimeException(("Service is not up")); + } + + public void save(final T entity) { + if (isUp()) { + Response measuresResponse = client.target(baseUrl) + .path(getEntitiesPath()) + .request(APPLICATION_JSON) + .post(Entity.entity(entity, APPLICATION_JSON)); + + if (measuresResponse.getStatusInfo().getFamily() != SUCCESSFUL) { + throw new RuntimeException("Error in updating the entity"); + } + } else { + throw new RuntimeException(("Service is not up")); + } + } + + public void update(final T entity) { + if (isUp()) { + Response measuresResponse = client.target(baseUrl) + .path(getEntitiesPath()) + .path(entity.getId().toString()) + .request(APPLICATION_JSON) + .put(Entity.entity(entity, APPLICATION_JSON)); + + if (measuresResponse.getStatusInfo().getFamily() != SUCCESSFUL) { + throw new RuntimeException("Error in updating the entity"); + } + } else { + throw new RuntimeException(("Service is not up")); + } + } + + public boolean isUp() { + Response healthResponse = client.target(baseUrl).path(PATH_HEALTH) + .request(APPLICATION_JSON).get(); + + if (healthResponse.getStatusInfo().getFamily() == SUCCESSFUL) { + return healthResponse.readEntity(ServiceHealthStatus.class).isUp(); + } + + return false; + } + + protected abstract GenericType getGenericType(); + + protected abstract GenericType> getGenericListType(); + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceMeasureClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceMeasureClient.java new file mode 100644 index 00000000..274d29d4 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceMeasureClient.java @@ -0,0 +1,29 @@ +package org.devgateway.toolkit.forms.client; + +import org.devgateway.toolkit.persistence.dto.ServiceMeasure; + +import javax.ws.rs.core.GenericType; +import java.util.List; + +public class ServiceMeasureClient extends ServiceEntityClient { + + public ServiceMeasureClient(final String baseUrl) { + super(baseUrl); + } + + @Override + public String getEntitiesPath() { + return ClientConstants.PATH_MEASURES; + } + + @Override + protected GenericType getGenericType() { + return new GenericType() {}; + } + + @Override + protected GenericType> getGenericListType() { + return new GenericType>() {}; + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/exceptions/NullServiceEntityServiceException.java b/forms/src/main/java/org/devgateway/toolkit/forms/exceptions/NullServiceEntityServiceException.java new file mode 100644 index 00000000..05656e00 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/exceptions/NullServiceEntityServiceException.java @@ -0,0 +1,27 @@ +/** + * Copyright (c) 2015 Development Gateway, Inc and others. + *

+ * All rights reserved. This program and the accompanying materials + * are made available under the terms of the MIT License (MIT) + * which accompanies this distribution, and is available at + * https://opensource.org/licenses/MIT + *

+ * Contributors: + * Development Gateway - initial API and implementation + */ +/** + * + */ +package org.devgateway.toolkit.forms.exceptions; + +/** + * @author vchihai + */ +public class NullServiceEntityServiceException extends RuntimeException { + private static final long serialVersionUID = 7516874812755335131L; + + public NullServiceEntityServiceException() { + super("serviceEntityService is null! Please set the serviceEntityService in your constructor"); + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityService.java new file mode 100644 index 00000000..2c016e59 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityService.java @@ -0,0 +1,23 @@ +package org.devgateway.toolkit.forms.service.admin; + +import org.devgateway.toolkit.persistence.dto.ServiceEntity; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public interface BaseServiceEntityService { + + List findAll(String serviceName); + + T findOne(String serviceName, Long id); + + void save(String serviceName, T entity); + + void update(String serviceName, T entity); + + long count(String serviceName); + + T newInstance(); + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityServiceImpl.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityServiceImpl.java new file mode 100644 index 00000000..df2ee4de --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityServiceImpl.java @@ -0,0 +1,42 @@ +package org.devgateway.toolkit.forms.service.admin; + +import org.devgateway.toolkit.forms.client.ServiceEntityClient; +import org.devgateway.toolkit.forms.service.EurekaClientService; +import org.devgateway.toolkit.persistence.dto.ServiceEntity; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.List; + +public abstract class BaseServiceEntityServiceImpl implements BaseServiceEntityService { + + @Override + public List findAll(final String serviceName) { + return serviceEntityClient(serviceName).findAll(); + } + + @Override + public T findOne(final String serviceName, final Long id) { + return serviceEntityClient(serviceName).findOne(id); + } + + @Override + public void save(final String serviceName, final T entity) { + serviceEntityClient(serviceName).save(entity); + } + + public void update(final String serviceName, final T entity) { + serviceEntityClient(serviceName).update(entity); + } + + @Override + public long count(String serviceName) { + return 0; + } + + @Override + public T newInstance() { + return null; + } + + protected abstract ServiceEntityClient serviceEntityClient(final String serviceName); +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceCategoryService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceCategoryService.java new file mode 100644 index 00000000..0035bcdb --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceCategoryService.java @@ -0,0 +1,6 @@ +package org.devgateway.toolkit.forms.service.admin; + +import org.devgateway.toolkit.persistence.dto.ServiceCategory; + +public interface ServiceCategoryService extends BaseServiceEntityService { +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceCategoryServiceImpl.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceCategoryServiceImpl.java new file mode 100644 index 00000000..17999c89 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceCategoryServiceImpl.java @@ -0,0 +1,25 @@ +package org.devgateway.toolkit.forms.service.admin; + +import org.devgateway.toolkit.forms.client.ServiceCategoryClient; +import org.devgateway.toolkit.forms.client.ServiceEntityClient; +import org.devgateway.toolkit.forms.service.EurekaClientService; +import org.devgateway.toolkit.persistence.dto.ServiceCategory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ServiceCategoryServiceImpl extends BaseServiceEntityServiceImpl implements ServiceCategoryService { + + @Autowired + private EurekaClientService eurekaClientService; + + @Override + public ServiceCategory newInstance() { + return new ServiceCategory(); + } + + @Override + protected ServiceEntityClient serviceEntityClient(final String serviceName) { + return new ServiceCategoryClient(eurekaClientService.findByName(serviceName).getUrl()); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDimensionService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDimensionService.java new file mode 100644 index 00000000..e27c371f --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDimensionService.java @@ -0,0 +1,6 @@ +package org.devgateway.toolkit.forms.service.admin; + +import org.devgateway.toolkit.persistence.dto.ServiceDimension; + +public interface ServiceDimensionService extends BaseServiceEntityService { +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDimensionServiceImpl.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDimensionServiceImpl.java new file mode 100644 index 00000000..eef58eab --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDimensionServiceImpl.java @@ -0,0 +1,25 @@ +package org.devgateway.toolkit.forms.service.admin; + +import org.devgateway.toolkit.forms.client.ServiceDimensionClient; +import org.devgateway.toolkit.forms.client.ServiceEntityClient; +import org.devgateway.toolkit.forms.service.EurekaClientService; +import org.devgateway.toolkit.persistence.dto.ServiceDimension; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ServiceDimensionServiceImpl extends BaseServiceEntityServiceImpl implements ServiceDimensionService { + + @Autowired + private EurekaClientService eurekaClientService; + + @Override + public ServiceDimension newInstance() { + return new ServiceDimension(); + } + + @Override + protected ServiceEntityClient serviceEntityClient(final String serviceName) { + return new ServiceDimensionClient(eurekaClientService.findByName(serviceName).getUrl()); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceMeasureService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceMeasureService.java new file mode 100644 index 00000000..67efddfb --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceMeasureService.java @@ -0,0 +1,6 @@ +package org.devgateway.toolkit.forms.service.admin; + +import org.devgateway.toolkit.persistence.dto.ServiceMeasure; + +public interface ServiceMeasureService extends BaseServiceEntityService { +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceMeasureServiceImpl.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceMeasureServiceImpl.java new file mode 100644 index 00000000..1ab90f22 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceMeasureServiceImpl.java @@ -0,0 +1,25 @@ +package org.devgateway.toolkit.forms.service.admin; + +import org.devgateway.toolkit.forms.client.ServiceEntityClient; +import org.devgateway.toolkit.forms.client.ServiceMeasureClient; +import org.devgateway.toolkit.forms.service.EurekaClientService; +import org.devgateway.toolkit.persistence.dto.ServiceMeasure; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ServiceMeasureServiceImpl extends BaseServiceEntityServiceImpl implements ServiceMeasureService { + + @Autowired + private EurekaClientService eurekaClientService; + + @Override + public ServiceMeasure newInstance() { + return new ServiceMeasure(); + } + + @Override + protected ServiceEntityClient serviceEntityClient(final String serviceName) { + return new ServiceMeasureClient(eurekaClientService.findByName(serviceName).getUrl()); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java index a088fded..dcf2b251 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java @@ -26,6 +26,7 @@ import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; +import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceCategoriesPage; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceDimensionsPage; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceMeasuresPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListCSVDatasetPage; @@ -61,7 +62,7 @@ public DataServicePage(final PageParameters parameters) { links.add(getEntityLink("datasets", getServicePageClass(serviceMetadata.getType()), database_s)); links.add(getEntityLink("measures", ListServiceMeasuresPage.class, ruler_s)); links.add(getEntityLink("dimensions", ListServiceDimensionsPage.class, chart_bar_s)); - links.add(getEntityLink("categories", ListServiceDimensionsPage.class, layer_group_s)); + links.add(getEntityLink("categories", ListServiceCategoriesPage.class, layer_group_s)); add(new BigLinksPanel("links", Model.ofList(links))); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java index b931fcbb..41adb81a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java @@ -19,12 +19,14 @@ import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.exceptions.NullListPageClassException; import org.devgateway.toolkit.forms.service.DatasetClientService; +import org.devgateway.toolkit.forms.service.admin.BaseServiceEntityService; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapSubmitButton; import org.devgateway.toolkit.forms.wicket.components.form.GenericBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.visitors.GenericBootstrapValidationVisitor; import org.devgateway.toolkit.forms.wicket.page.BasePage; import org.devgateway.toolkit.persistence.dto.ServiceEntity; +import org.devgateway.toolkit.persistence.service.BaseJpaService; import org.springframework.orm.ObjectOptimisticLockingFailureException; import java.text.MessageFormat; @@ -46,14 +48,13 @@ public abstract class AbstractEditServiceEntityPage ext */ protected Class listPageClass; - @SpringBean - protected DatasetClientService datasetClientService; - /** * The form used by all subclasses */ protected EditForm editForm; + protected BaseServiceEntityService entityService; + private CompoundPropertyModel compoundModel; /** @@ -202,9 +203,9 @@ protected void onSubmit(final AjaxRequestTarget target) { T entity = editForm.getModelObject(); if (editForm.getModelObject().getId() != null) { - updateEntity(entity); + entityService.update(serviceName, entity); } else { - createEntity(entity); + entityService.save(serviceName, entity); } // only redirect if redirect is true @@ -335,10 +336,10 @@ protected void onInitialize() { IModel model = null; if (entityId != null) { - T entity = getEntityById(entityId); + T entity = entityService.findOne(serviceName, entityId); model = Model.of(entity); } else { - T entity = newInstance(); + T entity = entityService.newInstance(); if (entity != null) { model = Model.of(entity); } @@ -368,12 +369,4 @@ protected PageParameters getParamsWithServiceInformation() { return pageParams; } - protected abstract T newInstance(); - - protected abstract T getEntityById(Long id); - - protected abstract void createEntity(T entity); - - protected abstract void updateEntity(T entity); - } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.html new file mode 100644 index 00000000..ebe7c3ce --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.html @@ -0,0 +1,27 @@ + + + + +

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java new file mode 100644 index 00000000..317c9eb7 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java @@ -0,0 +1,65 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.admin; + +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.service.admin.ServiceCategoryService; +import org.devgateway.toolkit.forms.wicket.components.form.ColorPickerBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceCategoriesPage; +import org.devgateway.toolkit.persistence.dto.ServiceCategory; +import org.hibernate.envers.Audited; +import org.springframework.beans.factory.annotation.Autowired; +import org.wicketstuff.annotation.mount.MountPath; + +@MountPath(value = "/editServiceCategory") +public class EditServiceCategoryPage extends AbstractEditServiceEntityPage { + private static final long serialVersionUID = -9013029067860834250L; + + @SpringBean + private ServiceCategoryService serviceCategoryService; + + public EditServiceCategoryPage(final PageParameters parameters) { + super(parameters); + this.listPageClass = ListServiceCategoriesPage.class; + this.entityService = serviceCategoryService; + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + final TextFieldBootstrapFormComponent type = new TextFieldBootstrapFormComponent<>("type"); + type.setEnabled(false); + editForm.add(type); + + final TextFieldBootstrapFormComponent code = new TextFieldBootstrapFormComponent<>("code"); + code.setEnabled(false); + editForm.add(code); + + final TextFieldBootstrapFormComponent value = new TextFieldBootstrapFormComponent<>("value"); + value.getField().setRequired(true); + editForm.add(value); + + final TextFieldBootstrapFormComponent position = new TextFieldBootstrapFormComponent<>("position"); + position.getField().setRequired(true); + editForm.add(position); + + ColorPickerBootstrapFormComponent colorPicker = new ColorPickerBootstrapFormComponent("color", + new PropertyModel<>(editForm.getModelObject(), "categoryStyle.color")); + editForm.add(colorPicker); + + final TextFieldBootstrapFormComponent className = new TextFieldBootstrapFormComponent<>("className", + new PropertyModel<>(editForm.getModelObject(), "categoryStyle.className")); + editForm.add(className); + + ColorPickerBootstrapFormComponent textColorPicker = new ColorPickerBootstrapFormComponent("textColor", + new PropertyModel<>(editForm.getModelObject(), "categoryStyle.textColor")); + editForm.add(textColorPicker); + + ColorPickerBootstrapFormComponent bckColorPicker = new ColorPickerBootstrapFormComponent("backgroundColor", + new PropertyModel<>(editForm.getModelObject(), "categoryStyle.backgroundColor")); + editForm.add(bckColorPicker); + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties new file mode 100644 index 00000000..5d30c46e --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties @@ -0,0 +1,22 @@ +############################################################################### +# Copyright (c) 2022 Development Gateway, Inc and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the MIT License (MIT) +# which accompanies this distribution, and is available at +# https://opensource.org/licenses/MIT +# +# Contributors: +# Development Gateway - initial API and implementation +############################################################################### +page.title=Edit {0} Measure +page.title.add=Add {0} Measure +page.title.edit=Edit {0} Measure +code.label=Code +value.label=Value +position.label=Position +color.label=Color +className.label=CSS Class Name +textColor.label=Text Color +backgroundColor.label=Background Color +type.label=Type \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java index 52e7d59a..ecfcf58b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java @@ -1,48 +1,25 @@ package org.devgateway.toolkit.forms.wicket.page.edit.admin; -import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; -import de.agilecoders.wicket.core.markup.html.bootstrap.dialog.TextContentModal; -import de.agilecoders.wicket.core.markup.html.bootstrap.form.BootstrapForm; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; -import nl.dries.wicket.hibernate.dozer.DozerModel; -import org.apache.wicket.Page; -import org.apache.wicket.ajax.AjaxEventBehavior; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.model.CompoundPropertyModel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.ResourceModel; -import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.validation.ValidationError; -import org.devgateway.toolkit.forms.WebConstants; -import org.devgateway.toolkit.forms.exceptions.NullListPageClassException; -import org.devgateway.toolkit.forms.service.DatasetClientService; -import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; -import org.devgateway.toolkit.forms.wicket.components.form.BootstrapSubmitButton; -import org.devgateway.toolkit.forms.wicket.components.form.GenericBootstrapFormComponent; +import org.devgateway.toolkit.forms.service.admin.ServiceDimensionService; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; -import org.devgateway.toolkit.forms.wicket.components.form.visitors.GenericBootstrapValidationVisitor; -import org.devgateway.toolkit.forms.wicket.page.BasePage; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceDimensionsPage; import org.devgateway.toolkit.persistence.dto.ServiceDimension; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.orm.ObjectOptimisticLockingFailureException; +import org.springframework.beans.factory.annotation.Autowired; import org.wicketstuff.annotation.mount.MountPath; -/** - * @author mpostelnicu Page used to make editing easy, extend to get easy access - * to one entity for editing - */ @MountPath(value = "/editServiceDimension") public class EditServiceDimensionPage extends AbstractEditServiceEntityPage { private static final long serialVersionUID = -1594571319284288551L; + @SpringBean + private ServiceDimensionService serviceDimensionService; + public EditServiceDimensionPage(final PageParameters parameters) { super(parameters); this.listPageClass = ListServiceDimensionsPage.class; + this.entityService = serviceDimensionService; } @Override @@ -62,24 +39,4 @@ protected void onInitialize() { editForm.add(position); } - @Override - protected ServiceDimension newInstance() { - return new ServiceDimension(); - } - - @Override - protected ServiceDimension getEntityById(final Long id) { - return datasetClientService.getDimensionById(serviceName, id); - } - - @Override - protected void createEntity(final ServiceDimension entity) { - datasetClientService.addDimensionToService(serviceName, entity); - } - - @Override - protected void updateEntity(final ServiceDimension entity) { - datasetClientService.updateDimension(serviceName, entity); - } - } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java index 36d3e5b1..1114a26f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java @@ -2,24 +2,26 @@ import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.service.admin.ServiceMeasureService; import org.devgateway.toolkit.forms.wicket.components.form.ColorPickerBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; -import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceDimensionsPage; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceMeasuresPage; import org.devgateway.toolkit.persistence.dto.ServiceMeasure; +import org.springframework.beans.factory.annotation.Autowired; import org.wicketstuff.annotation.mount.MountPath; -/** - * @author mpostelnicu Page used to make editing easy, extend to get easy access - * to one entity for editing - */ @MountPath(value = "/editServiceMeasure") public class EditServiceMeasurePage extends AbstractEditServiceEntityPage { private static final long serialVersionUID = -9013029067860834250L; + @SpringBean + private ServiceMeasureService serviceMeasureService; + public EditServiceMeasurePage(final PageParameters parameters) { super(parameters); this.listPageClass = ListServiceMeasuresPage.class; + this.entityService = serviceMeasureService; } @Override @@ -59,24 +61,4 @@ protected void onInitialize() { editForm.add(bckColorPicker); } - @Override - protected ServiceMeasure newInstance() { - return new ServiceMeasure(); - } - - @Override - protected ServiceMeasure getEntityById(final Long id) { - return datasetClientService.getMeasureById(serviceName, id); - } - - @Override - protected void createEntity(final ServiceMeasure entity) { - datasetClientService.addMeasureToService(serviceName, entity); - } - - @Override - protected void updateEntity(final ServiceMeasure entity) { - datasetClientService.updateMeasure(serviceName, entity); - } - } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage$ActionPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage$ActionPanel.html similarity index 100% rename from forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage$ActionPanel.html rename to forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage$ActionPanel.html diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.html similarity index 100% rename from forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.html rename to forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.html diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java new file mode 100644 index 00000000..1ef1bde4 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java @@ -0,0 +1,134 @@ +package org.devgateway.toolkit.forms.wicket.page.lists.admin; + +import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapBookmarkablePageLink; +import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; +import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.GenericPanel; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.devgateway.toolkit.forms.WebConstants; +import org.devgateway.toolkit.forms.exceptions.NullServiceEntityServiceException; +import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.service.admin.BaseServiceEntityService; +import org.devgateway.toolkit.forms.wicket.components.table.AjaxFallbackBootstrapDataTable; +import org.devgateway.toolkit.forms.wicket.page.BasePage; +import org.devgateway.toolkit.forms.wicket.page.edit.admin.AbstractEditServiceEntityPage; +import org.devgateway.toolkit.persistence.dto.ServiceEntity; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.List; + +import static org.devgateway.toolkit.forms.WebConstants.PAGE_SIZE; + +@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) +public class AbstractListServiceEntityPage extends BasePage { + + private static final long serialVersionUID = 652587400391540726L; + + protected Class> editPageClass; + + protected AjaxFallbackBootstrapDataTable dataTable; + + protected SortableServiceEntityProvider dataProvider; + + protected List> columns; + + protected BaseServiceEntityService serviceEntityService; + + protected int pageRowNo = 0; + + public AbstractListServiceEntityPage(final PageParameters pageParameters) { + super(pageParameters); + + columns = new ArrayList<>(); + columns.add(new PropertyColumn<>(new Model<>("Code"), "code", "code")); + columns.add(new PropertyColumn<>(new Model<>("Value"), "value", "value")); + columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + if (serviceEntityService == null) { + throw new NullServiceEntityServiceException(); + } + + String serviceName = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + dataProvider = new SortableServiceEntityProvider<>(serviceEntityService, serviceName); + + dataTable = new AjaxFallbackBootstrapDataTable( + "table", columns, dataProvider, getPageSize()) { + private static final long serialVersionUID = 632539691822305263L; + + @Override + protected void onPageChanged() { + pageRowNo = 0; + } + }; + + columns.add(new AbstractColumn(new StringResourceModel("actionsColumn", this, null)) { + private static final long serialVersionUID = -7447601118569862123L; + + @Override + public void populateItem(final Item> cellItem, final String componentId, + final IModel model) { + cellItem.add(getActionPanel(componentId, model)); + } + }); + + add(dataTable); + } + + protected int getPageSize() { + return PAGE_SIZE; + } + + public ActionPanel getActionPanel(final String id, final IModel model) { + return new ActionPanel(id, model); + } + + public class ActionPanel extends GenericPanel { + private static final long serialVersionUID = 5821419128121941939L; + + protected BootstrapBookmarkablePageLink editItemPageLink; + + /** + * @param id + * @param model + */ + public ActionPanel(final String id, final IModel model) { + super(id, model); + + final PageParameters pageParameters = new PageParameters(); + + @SuppressWarnings("unchecked") + T entity = (T) ActionPanel.this.getDefaultModelObject(); + if (entity != null) { + pageParameters.set(WebConstants.PARAM_ID, entity.getId()); + } + pageParameters.set(WebConstants.PARAM_SERVICE, getPageParameters().get(WebConstants.PARAM_SERVICE)); + + editItemPageLink = + new BootstrapBookmarkablePageLink<>("edit", editPageClass, pageParameters, Buttons.Type.Info); + editItemPageLink.setIconType(FontAwesome5IconType.edit_s).setSize(Buttons.Size.Small) + .setLabel(new StringResourceModel("edit", this, null)); + add(editItemPageLink); + } + } + + protected Label getPageTitle() { + String service = getPageParameters().get("service").toString(); + return new Label("pageTitle", Model.of(MessageFormat.format(getString("page.title"), service))); + } +} \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.properties new file mode 100644 index 00000000..e25ddcf7 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.properties @@ -0,0 +1,3 @@ +page.title={0} Entities +actionsColumn=Edit +edit=Edit \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java new file mode 100644 index 00000000..98593598 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java @@ -0,0 +1,71 @@ +/******************************************************************************* + * Copyright (c) 2015 Development Gateway, Inc and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the MIT License (MIT) + * which accompanies this distribution, and is available at + * https://opensource.org/licenses/MIT + * + * Contributors: + * Development Gateway - initial API and implementation + *******************************************************************************/ +package org.devgateway.toolkit.forms.wicket.page.lists.admin; + +import de.agilecoders.wicket.core.markup.html.bootstrap.behavior.CssClassNameAppender; +import org.apache.wicket.AttributeModifier; +import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.WebConstants; +import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.service.admin.ServiceCategoryService; +import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServiceCategoryPage; +import org.devgateway.toolkit.persistence.dto.ServiceCategory; +import org.devgateway.toolkit.persistence.dto.ServiceMeasure; +import org.wicketstuff.annotation.mount.MountPath; + +import java.util.ArrayList; + +@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) +@MountPath(value = "/categories") +public class ListServiceCategoriesPage extends AbstractListServiceEntityPage { + + private static final long serialVersionUID = -6132847935476573446L; + + @SpringBean + private ServiceCategoryService serviceCategoryService; + + public ListServiceCategoriesPage(final PageParameters pageParameters) { + super(pageParameters); + + this.serviceEntityService = serviceCategoryService; + this.editPageClass = EditServiceCategoryPage.class; + + String service = pageParameters.get(WebConstants.PARAM_SERVICE).toString(); + dataProvider = new ServiceCategoryProvider(serviceCategoryService, service); + + columns = new ArrayList<>(); + columns.add(new PropertyColumn<>(new Model<>("Type"), "type", "type")); + columns.add(new PropertyColumn<>(new Model<>("Code"), "code", "code")); + columns.add(new PropertyColumn<>(new Model<>("Value"), "value", "value")); + columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); + columns.add(new PropertyColumn(new Model<>("Color"), "categoryStyle.color", + "categoryStyle.color") { + @Override + public void populateItem(final Item> item, final String componentId, final IModel rowModel) { + String color = rowModel.getObject().getCategoryStyle() == null ? "" : rowModel.getObject().getCategoryStyle().getColor(); + item.add(new Label(componentId, "") + .add(new AttributeModifier("style", "background-color: " + color)) + .add(new CssClassNameAppender("color-box")) + ); + } + }); + } + +} \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.properties new file mode 100644 index 00000000..177202fd --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.properties @@ -0,0 +1 @@ +page.title={0} Categories \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java index 3f67c9c5..3640aabd 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java @@ -11,60 +11,38 @@ *******************************************************************************/ package org.devgateway.toolkit.forms.wicket.page.lists.admin; -import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapBookmarkablePageLink; -import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; -import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; -import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.panel.GenericPanel; -import org.apache.wicket.markup.repeater.Item; -import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; -import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityConstants; -import org.devgateway.toolkit.forms.service.DatasetClientService; -import org.devgateway.toolkit.forms.wicket.components.table.AjaxFallbackBootstrapDataTable; -import org.devgateway.toolkit.forms.wicket.page.BasePage; +import org.devgateway.toolkit.forms.service.admin.ServiceDimensionService; import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServiceDimensionPage; -import org.devgateway.toolkit.forms.wicket.page.edit.dataset.EditTetsimDatasetPage; +import org.devgateway.toolkit.forms.wicket.page.edit.dataset.EditCSVDatasetPage; import org.devgateway.toolkit.persistence.dto.ServiceDimension; import org.wicketstuff.annotation.mount.MountPath; -import java.text.MessageFormat; import java.util.ArrayList; -import java.util.List; - -import static org.devgateway.toolkit.forms.WebConstants.PAGE_SIZE; @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) @MountPath(value = "/dimensions") -public class ListServiceDimensionsPage extends BasePage { +public class ListServiceDimensionsPage extends AbstractListServiceEntityPage { private static final long serialVersionUID = -6132847935476573446L; - protected AjaxFallbackBootstrapDataTable dataTable; - - protected ServiceDimensionProvider dataProvider; - - protected List> columns; - @SpringBean - private DatasetClientService datasetClientService; - - protected int pageRowNo = 0; + private ServiceDimensionService serviceDimensionService; public ListServiceDimensionsPage(final PageParameters pageParameters) { super(pageParameters); + this.serviceEntityService = serviceDimensionService; + this.editPageClass = EditServiceDimensionPage.class; + String service = pageParameters.get(WebConstants.PARAM_SERVICE).toString(); - dataProvider = new ServiceDimensionProvider(datasetClientService, service); + dataProvider = new ServiceDimensionProvider(serviceDimensionService, service); columns = new ArrayList<>(); columns.add(new PropertyColumn<>(new Model<>("Code"), "code", "code")); @@ -72,72 +50,4 @@ public ListServiceDimensionsPage(final PageParameters pageParameters) { columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); } - @Override - protected void onInitialize() { - super.onInitialize(); - - dataTable = new AjaxFallbackBootstrapDataTable( - "table", columns, dataProvider, getPageSize()) { - private static final long serialVersionUID = -7263599298497560059L; - - @Override - protected void onPageChanged() { - pageRowNo = 0; - } - }; - - columns.add(new AbstractColumn(new StringResourceModel("actionsColumn", this, null)) { - private static final long serialVersionUID = -7447601118569862123L; - - @Override - public void populateItem(final Item> cellItem, final String componentId, - final IModel model) { - cellItem.add(getActionPanel(componentId, model)); - } - }); - - add(dataTable); - } - - protected int getPageSize() { - return PAGE_SIZE; - } - - public ActionPanel getActionPanel(final String id, final IModel model) { - return new ActionPanel(id, model); - } - - public class ActionPanel extends GenericPanel { - private static final long serialVersionUID = 5821419128121941939L; - - protected BootstrapBookmarkablePageLink editItemPageLink; - - /** - * @param id - * @param model - */ - public ActionPanel(final String id, final IModel model) { - super(id, model); - - final PageParameters pageParameters = new PageParameters(); - - @SuppressWarnings("unchecked") - ServiceDimension entity = (ServiceDimension) ActionPanel.this.getDefaultModelObject(); - if (entity != null) { - pageParameters.set(WebConstants.PARAM_ID, entity.getId()); - } - pageParameters.set(WebConstants.PARAM_SERVICE, getPageParameters().get(WebConstants.PARAM_SERVICE)); - - editItemPageLink = - new BootstrapBookmarkablePageLink<>("edit", EditServiceDimensionPage.class, pageParameters, Buttons.Type.Info); - editItemPageLink.setIconType(FontAwesome5IconType.edit_s).setSize(Buttons.Size.Small) - .setLabel(new StringResourceModel("edit", this, null)); - add(editItemPageLink); - } - } - - protected Label getPageTitle() { - String service = getPageParameters().get("service").toString(); - return new Label("pageTitle", Model.of(MessageFormat.format(getString("page.title"), service))); - } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties index c6bf6a36..b7369f94 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties @@ -1,3 +1 @@ -page.title={0} Dimensions -actionsColumn=Edit -edit=Edit \ No newline at end of file +page.title={0} Dimensions \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage$ActionPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage$ActionPanel.html deleted file mode 100644 index ad387fd1..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage$ActionPanel.html +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.html deleted file mode 100644 index da324d7e..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - -
-
-
-
-
-
- - \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java index 75e71237..0b260742 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java @@ -12,60 +12,38 @@ package org.devgateway.toolkit.forms.wicket.page.lists.admin; import de.agilecoders.wicket.core.markup.html.bootstrap.behavior.CssClassNameAppender; -import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapBookmarkablePageLink; -import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.AttributeModifier; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; -import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; -import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; -import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityConstants; -import org.devgateway.toolkit.forms.service.DatasetClientService; -import org.devgateway.toolkit.forms.wicket.components.table.AjaxFallbackBootstrapDataTable; -import org.devgateway.toolkit.forms.wicket.page.BasePage; +import org.devgateway.toolkit.forms.service.admin.ServiceMeasureService; import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServiceMeasurePage; import org.devgateway.toolkit.persistence.dto.ServiceMeasure; import org.wicketstuff.annotation.mount.MountPath; -import java.text.MessageFormat; import java.util.ArrayList; -import java.util.List; - -import static org.devgateway.toolkit.forms.WebConstants.PAGE_SIZE; @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) @MountPath(value = "/measures") -public class ListServiceMeasuresPage extends BasePage { +public class ListServiceMeasuresPage extends AbstractListServiceEntityPage { private static final long serialVersionUID = -6132847935476573446L; - protected AjaxFallbackBootstrapDataTable dataTable; - - protected ServiceMeasureProvider dataProvider; - - protected List> columns; - @SpringBean - private DatasetClientService datasetClientService; - - protected int pageRowNo = 0; + private ServiceMeasureService serviceMeasureService; public ListServiceMeasuresPage(final PageParameters pageParameters) { super(pageParameters); - String service = pageParameters.get(WebConstants.PARAM_SERVICE).toString(); - dataProvider = new ServiceMeasureProvider(datasetClientService, service); + this.serviceEntityService = serviceMeasureService; + this.editPageClass = EditServiceMeasurePage.class; columns = new ArrayList<>(); columns.add(new PropertyColumn<>(new Model<>("Code"), "code", "code")); @@ -82,73 +60,4 @@ public void populateItem(final Item> item, final } }); } - - @Override - protected void onInitialize() { - super.onInitialize(); - - dataTable = new AjaxFallbackBootstrapDataTable( - "table", columns, dataProvider, getPageSize()) { - private static final long serialVersionUID = -7263599298497560059L; - - @Override - protected void onPageChanged() { - pageRowNo = 0; - } - }; - - columns.add(new AbstractColumn(new StringResourceModel("actionsColumn", this, null)) { - private static final long serialVersionUID = -7447601118569862123L; - - @Override - public void populateItem(final Item> cellItem, final String componentId, - final IModel model) { - cellItem.add(getActionPanel(componentId, model)); - } - }); - - add(dataTable); - } - - protected int getPageSize() { - return PAGE_SIZE; - } - - public ActionPanel getActionPanel(final String id, final IModel model) { - return new ActionPanel(id, model); - } - - public class ActionPanel extends GenericPanel { - private static final long serialVersionUID = -4547406060736744071L; - - protected BootstrapBookmarkablePageLink editItemPageLink; - - /** - * @param id - * @param model - */ - public ActionPanel(final String id, final IModel model) { - super(id, model); - - final PageParameters pageParameters = new PageParameters(); - - @SuppressWarnings("unchecked") - ServiceMeasure entity = (ServiceMeasure) ActionPanel.this.getDefaultModelObject(); - if (entity != null) { - pageParameters.set(WebConstants.PARAM_ID, entity.getId()); - } - pageParameters.set(WebConstants.PARAM_SERVICE, getPageParameters().get(WebConstants.PARAM_SERVICE)); - - editItemPageLink = - new BootstrapBookmarkablePageLink<>("edit", EditServiceMeasurePage.class, pageParameters, Buttons.Type.Info); - editItemPageLink.setIconType(FontAwesome5IconType.edit_s).setSize(Buttons.Size.Small) - .setLabel(new StringResourceModel("edit", this, null)); - add(editItemPageLink); - } - } - - protected Label getPageTitle() { - String service = getPageParameters().get("service").toString(); - return new Label("pageTitle", Model.of(MessageFormat.format(getString("page.title"), service))); - } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties index 1d1c08e8..d628026c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties @@ -1,3 +1 @@ -page.title={0} Measures -actionsColumn=Edit -edit=Edit \ No newline at end of file +page.title={0} Measures \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceCategoryProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceCategoryProvider.java new file mode 100644 index 00000000..c0a74991 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceCategoryProvider.java @@ -0,0 +1,33 @@ +package org.devgateway.toolkit.forms.wicket.page.lists.admin; + +import org.devgateway.toolkit.forms.service.admin.BaseServiceEntityService; +import org.devgateway.toolkit.persistence.dto.ServiceCategory; + +import java.util.Comparator; + +/** + * Data provider used to provide information about the services + * + * @author Viorel Chihai + */ +public class ServiceCategoryProvider extends SortableServiceEntityProvider { + private static final long serialVersionUID = 3067952110482080616L; + + public ServiceCategoryProvider(final BaseServiceEntityService serviceEntityService, + final String serviceName) { + super(serviceEntityService, serviceName); + } + + @Override + protected Comparator getServiceEntityComparator() { + return new ServiceCategoryComparator(); + } + + protected class ServiceCategoryComparator implements Comparator { + @Override + public int compare(final ServiceCategory s1, final ServiceCategory s2) { + return String.CASE_INSENSITIVE_ORDER.compare(s1.getCode(), s2.getCode()); + } + } + +} \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDimensionProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDimensionProvider.java index 482c28e7..27b40f4d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDimensionProvider.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDimensionProvider.java @@ -5,6 +5,7 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.devgateway.toolkit.forms.service.DatasetClientService; +import org.devgateway.toolkit.forms.service.admin.BaseServiceEntityService; import org.devgateway.toolkit.persistence.dto.ServiceDimension; import java.util.Collections; @@ -17,52 +18,17 @@ * * @author Viorel Chihai */ -public class ServiceDimensionProvider extends SortableDataProvider { - private static final long serialVersionUID = 1858130875067823547L; +public class ServiceDimensionProvider extends SortableServiceEntityProvider { + private static final long serialVersionUID = 3067952110482080616L; - protected DatasetClientService datasetClientService; - - private final String serviceName; - - public ServiceDimensionProvider(final DatasetClientService datasetClientService, final String serviceName) { - this.datasetClientService = datasetClientService; - this.serviceName = serviceName; - } - - @Override - public Iterator iterator(final long first, final long count) { - List services = datasetClientService.getDimensions(serviceName); - - if (first > services.size()) { - return Collections.emptyIterator(); - } - - if (getSort() == null || getSort().getProperty().equals("label")) { - Comparator comparator = new ServiceDimensionComparator(); - - if (getSort() != null && getSort().isAscending()) { - comparator = comparator.reversed(); - } - - Collections.sort(services, comparator); - } - - return services.subList((int) first, (int) Math.min(first + count, services.size())).iterator(); - } - - @Override - public SortParam getSort() { - return super.getSort(); - } - - @Override - public long size() { - return datasetClientService.getDimensions(serviceName).size(); + public ServiceDimensionProvider(final BaseServiceEntityService serviceEntityService, + final String serviceName) { + super(serviceEntityService, serviceName); } @Override - public IModel model(final ServiceDimension serviceDimension) { - return Model.of(serviceDimension); + protected Comparator getServiceEntityComparator() { + return new ServiceDimensionComparator(); } protected class ServiceDimensionComparator implements Comparator { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/SortableServiceEntityProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/SortableServiceEntityProvider.java new file mode 100644 index 00000000..48843ab3 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/SortableServiceEntityProvider.java @@ -0,0 +1,69 @@ +package org.devgateway.toolkit.forms.wicket.page.lists.admin; + +import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; +import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.devgateway.toolkit.forms.service.DatasetClientService; +import org.devgateway.toolkit.forms.service.admin.BaseServiceEntityService; +import org.devgateway.toolkit.persistence.dto.ServiceDimension; +import org.devgateway.toolkit.persistence.dto.ServiceEntity; +import org.devgateway.toolkit.persistence.service.BaseJpaService; + +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + +/** + * Data provider used to provide information about the services + * + * @author Viorel Chihai + */ +public class SortableServiceEntityProvider extends SortableDataProvider { + private static final long serialVersionUID = 1858130875067823547L; + + protected final String serviceName; + + private final BaseServiceEntityService serviceEntityService; + + public SortableServiceEntityProvider(final BaseServiceEntityService serviceEntityService, final String serviceName) { + this.serviceEntityService = serviceEntityService; + this.serviceName = serviceName; + } + + @Override + public Iterator iterator(final long first, final long count) { + List entities = serviceEntityService.findAll(serviceName); + + if (first > entities.size()) { + return Collections.emptyIterator(); + } + + if (getSort() == null || getSort().getProperty().equals("label")) { + Comparator comparator = getServiceEntityComparator(); + + if (getSort() != null && getSort().isAscending()) { + comparator = comparator.reversed(); + } + + Collections.sort(entities, comparator); + } + + return entities.subList((int) first, (int) Math.min(first + count, entities.size())).iterator(); + } + + @Override + public long size() { + return serviceEntityService.findAll(serviceName).size(); + } + + @Override + public IModel model(final T object) { + return Model.of(object); + } + + protected Comparator getServiceEntityComparator() { + return Comparator.comparingLong(ServiceEntity::getId); + } +} \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java index 549c37c0..1f9c9f01 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java @@ -13,6 +13,8 @@ public class ServiceCategory extends ServiceEntity { private CssStyle categoryStyle; + private String type; + public String getCode() { return code; } @@ -45,4 +47,11 @@ public void setCategoryStyle(final CssStyle categoryStyle) { this.categoryStyle = categoryStyle; } + public String getType() { + return type; + } + + public void setType(final String type) { + this.type = type; + } } From 5c33b319c12b342b32bcb309839fd9c9e8df16ad Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 6 Oct 2022 14:02:47 +0300 Subject: [PATCH 086/137] TOBACCO-1036: Update tetsim output exports --- .../persistence/dto/TetsimExportOutput.java | 337 ++++++++++++++++++ .../service/tetsim/TetsimOutputService.java | 25 +- .../web/rest/controller/TetsimController.java | 6 +- 3 files changed, 356 insertions(+), 12 deletions(-) create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java new file mode 100644 index 00000000..2c4aa5d5 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java @@ -0,0 +1,337 @@ +package org.devgateway.toolkit.persistence.dto; + +import java.io.Serializable; + +/** + * + * + * @author vchihai + */ +public class TetsimExportOutput implements Serializable { + + private Integer year; + + private Integer taxChange; + + private String tobaccoProduct; + + private Double legalConsumptionOvershift; + + private Double legalConsumptionChangeOvershift; + + private Double consumptionIllicitOvershift; + + private Double exciseRevOvershift; + + private Double exciseRevChangeOvershift; + + private Double totalGovRevOvershift; + + private Double exciseBurdenOvershift; + + private Double totalTaxBurdenOvershift; + + private Double retailPriceOvershift; + + private Double notOvershift; + + private Double exciseTaxOvershift; + + private Double vatOvershift; + + private Double levyOvershift; + + private Double legalConsumptionUndershift; + + private Double legalConsumptionChangeUndershift; + + private Double consumptionIllicitUndershift; + + private Double exciseRevUndershift; + + private Double exciseRevChangeUndershift; + + private Double totalGovRevUndershift; + + private Double exciseBurdenUndershift; + + private Double totalTaxBurdenUndershift; + + private Double retailPriceUndershift; + + private Double notUndershift; + + private Double exciseTaxUndershift; + + private Double vatUndershift; + + private Double levyUndershift; + + public TetsimExportOutput() { + } + + public TetsimExportOutput(TetsimOutput overShfit, TetsimOutput underShift) { + this.year = overShfit.getYear(); + this.taxChange = overShfit.getTaxChange(); + this.tobaccoProduct = overShfit.getTobaccoProduct(); + this.legalConsumptionOvershift = overShfit.getLegalConsumption(); + this.legalConsumptionChangeOvershift = overShfit.getLegalConsumptionChange(); + this.consumptionIllicitOvershift = overShfit.getConsumptionIllicit(); + this.exciseRevOvershift = overShfit.getExciseRev(); + this.exciseRevChangeOvershift = overShfit.getExciseRevChange(); + this.totalGovRevOvershift = overShfit.getTotalGovRev(); + this.exciseBurdenOvershift = overShfit.getExciseBurden(); + this.totalTaxBurdenOvershift = overShfit.getTotalTaxBurden(); + this.retailPriceOvershift = overShfit.getRetailPrice(); + this.notOvershift = overShfit.getNot(); + this.exciseTaxOvershift = overShfit.getExciseTax(); + this.vatOvershift = overShfit.getVat(); + this.levyOvershift = overShfit.getLevy(); + this.legalConsumptionUndershift = underShift.getLegalConsumption(); + this.legalConsumptionChangeUndershift = underShift.getLegalConsumptionChange(); + this.consumptionIllicitUndershift = underShift.getConsumptionIllicit(); + this.exciseRevUndershift = underShift.getExciseRev(); + this.exciseRevChangeUndershift = underShift.getExciseRevChange(); + this.totalGovRevUndershift = underShift.getTotalGovRev(); + this.exciseBurdenUndershift = underShift.getExciseBurden(); + this.totalTaxBurdenUndershift = underShift.getTotalTaxBurden(); + this.retailPriceUndershift = underShift.getRetailPrice(); + this.notUndershift = underShift.getNot(); + this.exciseTaxUndershift = underShift.getExciseTax(); + this.vatUndershift = underShift.getVat(); + this.levyUndershift = underShift.getLevy(); + } + + public Integer getYear() { + return year; + } + + public void setYear(final Integer year) { + this.year = year; + } + + public Integer getTaxChange() { + return taxChange; + } + + public void setTaxChange(final Integer taxChange) { + this.taxChange = taxChange; + } + + public String getTobaccoProduct() { + return tobaccoProduct; + } + + public void setTobaccoProduct(final String tobaccoProduct) { + this.tobaccoProduct = tobaccoProduct; + } + + public Double getLegalConsumptionOvershift() { + return legalConsumptionOvershift; + } + + public void setLegalConsumptionOvershift(final Double legalConsumptionOvershift) { + this.legalConsumptionOvershift = legalConsumptionOvershift; + } + + public Double getLegalConsumptionChangeOvershift() { + return legalConsumptionChangeOvershift; + } + + public void setLegalConsumptionChangeOvershift(final Double legalConsumptionChangeOvershift) { + this.legalConsumptionChangeOvershift = legalConsumptionChangeOvershift; + } + + public Double getConsumptionIllicitOvershift() { + return consumptionIllicitOvershift; + } + + public void setConsumptionIllicitOvershift(final Double consumptionIllicitOvershift) { + this.consumptionIllicitOvershift = consumptionIllicitOvershift; + } + + public Double getExciseRevOvershift() { + return exciseRevOvershift; + } + + public void setExciseRevOvershift(final Double exciseRevOvershift) { + this.exciseRevOvershift = exciseRevOvershift; + } + + public Double getExciseRevChangeOvershift() { + return exciseRevChangeOvershift; + } + + public void setExciseRevChangeOvershift(final Double exciseRevChangeOvershift) { + this.exciseRevChangeOvershift = exciseRevChangeOvershift; + } + + public Double getTotalGovRevOvershift() { + return totalGovRevOvershift; + } + + public void setTotalGovRevOvershift(final Double totalGovRevOvershift) { + this.totalGovRevOvershift = totalGovRevOvershift; + } + + public Double getExciseBurdenOvershift() { + return exciseBurdenOvershift; + } + + public void setExciseBurdenOvershift(final Double exciseBurdenOvershift) { + this.exciseBurdenOvershift = exciseBurdenOvershift; + } + + public Double getTotalTaxBurdenOvershift() { + return totalTaxBurdenOvershift; + } + + public void setTotalTaxBurdenOvershift(final Double totalTaxBurdenOvershift) { + this.totalTaxBurdenOvershift = totalTaxBurdenOvershift; + } + + public Double getRetailPriceOvershift() { + return retailPriceOvershift; + } + + public void setRetailPriceOvershift(final Double retailPriceOvershift) { + this.retailPriceOvershift = retailPriceOvershift; + } + + public Double getNotOvershift() { + return notOvershift; + } + + public void setNotOvershift(final Double notOvershift) { + this.notOvershift = notOvershift; + } + + public Double getExciseTaxOvershift() { + return exciseTaxOvershift; + } + + public void setExciseTaxOvershift(final Double exciseTaxOvershift) { + this.exciseTaxOvershift = exciseTaxOvershift; + } + + public Double getVatOvershift() { + return vatOvershift; + } + + public void setVatOvershift(final Double vatOvershift) { + this.vatOvershift = vatOvershift; + } + + public Double getLevyOvershift() { + return levyOvershift; + } + + public void setLevyOvershift(final Double levyOvershift) { + this.levyOvershift = levyOvershift; + } + + public Double getLegalConsumptionUndershift() { + return legalConsumptionUndershift; + } + + public void setLegalConsumptionUndershift(final Double legalConsumptionUndershift) { + this.legalConsumptionUndershift = legalConsumptionUndershift; + } + + public Double getLegalConsumptionChangeUndershift() { + return legalConsumptionChangeUndershift; + } + + public void setLegalConsumptionChangeUndershift(final Double legalConsumptionChangeUndershift) { + this.legalConsumptionChangeUndershift = legalConsumptionChangeUndershift; + } + + public Double getConsumptionIllicitUndershift() { + return consumptionIllicitUndershift; + } + + public void setConsumptionIllicitUndershift(final Double consumptionIllicitUndershift) { + this.consumptionIllicitUndershift = consumptionIllicitUndershift; + } + + public Double getExciseRevUndershift() { + return exciseRevUndershift; + } + + public void setExciseRevUndershift(final Double exciseRevUndershift) { + this.exciseRevUndershift = exciseRevUndershift; + } + + public Double getExciseRevChangeUndershift() { + return exciseRevChangeUndershift; + } + + public void setExciseRevChangeUndershift(final Double exciseRevChangeUndershift) { + this.exciseRevChangeUndershift = exciseRevChangeUndershift; + } + + public Double getTotalGovRevUndershift() { + return totalGovRevUndershift; + } + + public void setTotalGovRevUndershift(final Double totalGovRevUndershift) { + this.totalGovRevUndershift = totalGovRevUndershift; + } + + public Double getExciseBurdenUndershift() { + return exciseBurdenUndershift; + } + + public void setExciseBurdenUndershift(final Double exciseBurdenUndershift) { + this.exciseBurdenUndershift = exciseBurdenUndershift; + } + + public Double getTotalTaxBurdenUndershift() { + return totalTaxBurdenUndershift; + } + + public void setTotalTaxBurdenUndershift(final Double totalTaxBurdenUndershift) { + this.totalTaxBurdenUndershift = totalTaxBurdenUndershift; + } + + public Double getRetailPriceUndershift() { + return retailPriceUndershift; + } + + public void setRetailPriceUndershift(final Double retailPriceUndershift) { + this.retailPriceUndershift = retailPriceUndershift; + } + + public Double getNotUndershift() { + return notUndershift; + } + + public void setNotUndershift(final Double notUndershift) { + this.notUndershift = notUndershift; + } + + public Double getExciseTaxUndershift() { + return exciseTaxUndershift; + } + + public void setExciseTaxUndershift(final Double exciseTaxUndershift) { + this.exciseTaxUndershift = exciseTaxUndershift; + } + + public Double getVatUndershift() { + return vatUndershift; + } + + public void setVatUndershift(final Double vatUndershift) { + this.vatUndershift = vatUndershift; + } + + public Double getLevyUndershift() { + return levyUndershift; + } + + public void setLevyUndershift(final Double levyUndershift) { + this.levyUndershift = levyUndershift; + } + +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java index fec208f7..b31ab4a4 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java @@ -8,6 +8,7 @@ import com.opencsv.exceptions.CsvDataTypeMismatchException; import com.opencsv.exceptions.CsvRequiredFieldEmptyException; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dto.TetsimExportOutput; import org.devgateway.toolkit.persistence.dto.TetsimOutput; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; @@ -33,9 +34,14 @@ public class TetsimOutputService { .build(); public static final List TETSIM_CSV_FIELDS = new ImmutableList.Builder() - .add("year", "taxChange", "tobaccoProduct", "shifting", "legalConsumption", "legalConsumptionChange", - "consumptionIllicit", "exciseRev", "exciseRevChange", "totalGovRev", "exciseBurden", - "totalTaxBurden", "retailPrice", "not", "exciseTax", "vat", "levy") + .add("year", "taxChange", "tobaccoProduct", "legalConsumptionOvershift", "legalConsumptionChangeOvershift", + "consumptionIllicitOvershift", "exciseRevOvershift", "exciseRevChangeOvershift", + "totalGovRevOvershift", "exciseBurdenOvershift", "totalTaxBurdenOvershift", "retailPriceOvershift", + "notOvershift", "exciseTaxOvershift", "vatOvershift", "levyOvershift", + "legalConsumptionUndershift", "legalConsumptionChangeUndershift","consumptionIllicitUndershift", + "exciseRevUndershift", "exciseRevChangeUndershift", "totalGovRevUndershift", "exciseBurdenUndershift", + "totalTaxBurdenUndershift", "retailPriceUndershift", "notUndershift", "exciseTaxUndershift", + "vatUndershift", "levyUndershift") .build(); @Autowired private TetsimDatasetService tetsimDatasetService; @@ -46,14 +52,15 @@ public class TetsimOutputService { * @param datasetId * @return */ - public List getTetsimOutputs(Long datasetId) { + public List getTetsimOutputs(Long datasetId) { TetsimDataset dataset = tetsimDatasetService.findById(datasetId).get(); - List outputs = new ArrayList<>(); + List outputs = new ArrayList<>(); for (int i = 0; i <= MAX_TAX_CHANGE; i++) { for (String t : TOBACCO_PRODUCTS) { - outputs.add(new TetsimOutputOvershiftCalculator(dataset, i).calculate(t)); - outputs.add(new TetsimOutputUndershiftCalculator(dataset, i).calculate(t)); + TetsimOutput overShift = new TetsimOutputOvershiftCalculator(dataset, i).calculate(t); + TetsimOutput underShift = new TetsimOutputUndershiftCalculator(dataset, i).calculate(t); + outputs.add(new TetsimExportOutput(overShift, underShift)); } } @@ -79,8 +86,8 @@ public byte[] getTetsimCSVDatasetOutputs(Long datasetId) throws IOException, Csv .map(String::toUpperCase) .collect(Collectors.toList()); - HeaderColumnNameMappingStrategy columnStrategy = new HeaderColumnNameMappingStrategy<>(); - columnStrategy.setType(TetsimOutput.class); + HeaderColumnNameMappingStrategy columnStrategy = new HeaderColumnNameMappingStrategy<>(); + columnStrategy.setType(TetsimExportOutput.class); columnStrategy.setColumnOrderOnWrite(Comparator.comparingInt(columns::indexOf)); StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(streamWriter) diff --git a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java index 657b85e8..a2fe8920 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java +++ b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java @@ -3,7 +3,7 @@ import com.opencsv.exceptions.CsvDataTypeMismatchException; import com.opencsv.exceptions.CsvRequiredFieldEmptyException; import io.swagger.annotations.ApiOperation; -import org.devgateway.toolkit.persistence.dto.TetsimOutput; +import org.devgateway.toolkit.persistence.dto.TetsimExportOutput; import org.devgateway.toolkit.persistence.service.tetsim.TetsimOutputService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,8 +34,8 @@ public TetsimController(final TetsimOutputService tetsimOutputService) { @ApiOperation(value = "TETSIM Output API") @GetMapping(value = "/output", produces = "application/json") - public List getTetsimOutput(@RequestParam() final Long id) { - List outputs = tetsimOutputService.getTetsimOutputs(id); + public List getTetsimOutput(@RequestParam() final Long id) { + List outputs = tetsimOutputService.getTetsimOutputs(id); return outputs; } From ad33e274dfd64346e2d5fdc660cb6c119e865623 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 12 Oct 2022 12:56:52 +0300 Subject: [PATCH 087/137] TOBACCO-1054: Add tobacco products to menu and configurations --- .../devgateway/toolkit/forms/wicket/page/BasePage.java | 8 +++++++- .../toolkit/forms/wicket/page/BasePage.properties | 1 - .../toolkit/forms/wicket/page/ConfigurationsHomepage.java | 2 ++ .../forms/wicket/page/ConfigurationsHomepage.properties | 5 ++++- 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 7035d415..26044b59 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -51,8 +51,8 @@ import org.devgateway.toolkit.forms.security.SecurityUtil; import org.devgateway.toolkit.forms.wicket.page.lists.ListGroupPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListTestFormPage; +import org.devgateway.toolkit.forms.wicket.page.lists.ListTobaccoProductPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListUserPage; -import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServicePage; import org.devgateway.toolkit.forms.wicket.page.user.EditUserPage; import org.devgateway.toolkit.forms.wicket.page.user.LogoutPage; import org.devgateway.toolkit.forms.wicket.styles.BaseStyles; @@ -265,6 +265,12 @@ protected List newSubMenuButtons(final String arg0) { list.add(new MenuDivider()); + list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, + new StringResourceModel("navbar.tobaccoproducts", this, null)) + .setIconType(FontAwesome5IconType.smoking_s)); + + list.add(new MenuDivider()); + list.add(new MenuBookmarkablePageLink(EditAdminSettingsPage.class, new StringResourceModel("navbar.adminSettings", BasePage.this, null)) .setIconType(FontAwesome5IconType.cogs_s)); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties index dd4fb2f5..84e48074 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties @@ -20,7 +20,6 @@ navbar.tetsim=TETSIM navbar.prevalence=Prevalence navbar.policy=Policy navbar.ecigarettes=E-cigarette -navbar.categories=Categories navbar.tobaccoproducts=Tobacco Products navbar.testcomponents=Test Components navbar.swagger=Swagger diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java index d9f1a17a..bf903941 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java @@ -12,6 +12,7 @@ import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; import org.devgateway.toolkit.forms.wicket.page.lists.ListGroupPage; +import org.devgateway.toolkit.forms.wicket.page.lists.ListTobaccoProductPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListUserPage; import org.devgateway.toolkit.web.util.SettingsUtils; @@ -30,6 +31,7 @@ public class ConfigurationsHomepage extends BasePage { private static final List LINKS = new ImmutableList.Builder() .add(new BigLinkDefinition("users", ListUserPage.class, FontAwesome5IconType.users_s)) .add(new BigLinkDefinition("groups", ListGroupPage.class, FontAwesome5IconType.tags_s)) + .add(new BigLinkDefinition("tobaccoProducts", ListTobaccoProductPage.class, FontAwesome5IconType.smoking_s)) .add(new BigLinkDefinition("settings", EditAdminSettingsPage.class, FontAwesome5IconType.cogs_s)) .build(); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.properties index 086d7c46..0e4641f1 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.properties @@ -7,4 +7,7 @@ groups.label=Groups groups.desc=Manage the Groups settings.label=Settings -settings.desc=Manage the general settings of the system \ No newline at end of file +settings.desc=Manage the general settings of the system + +tobaccoProducts.label=Tobacco Products +tobaccoProducts.desc=Manage the Tobacco Products \ No newline at end of file From 518e275a4aaa205c181c5c33f4a4b3214f889cad Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 13 Oct 2022 16:27:46 +0300 Subject: [PATCH 088/137] TOBACCO-1021: Add label translations for measures, categories, dimensions --- .../edit/admin/EditServiceCategoryPage.html | 8 + .../edit/admin/EditServiceCategoryPage.java | 4 + .../admin/EditServiceCategoryPage.properties | 3 +- .../edit/admin/EditServiceDimensionPage.html | 9 ++ .../edit/admin/EditServiceDimensionPage.java | 4 + .../admin/EditServiceDimensionPage.properties | 3 +- .../edit/admin/EditServiceMeasurePage.html | 8 + .../edit/admin/EditServiceMeasurePage.java | 3 + .../admin/EditServiceMeasurePage.properties | 3 +- .../ListViewTextTranslationSectionPanel.html | 33 +++++ .../ListViewTextTranslationSectionPanel.java | 137 ++++++++++++++++++ ...ViewTextTranslationSectionPanel.properties | 4 + .../forms/wicket/styles/BaseStyles.css | 9 ++ .../persistence/dto/ServiceCategory.java | 18 +++ .../dto/ServiceTextTranslation.java | 33 +++++ .../ServiceTextTranslationDeserializer.java | 47 ++++++ .../ServiceTextTranslationSerializer.java | 35 +++++ 17 files changed, 358 insertions(+), 3 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.properties create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceTextTranslation.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/serializer/ServiceTextTranslationDeserializer.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/serializer/ServiceTextTranslationSerializer.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.html index ebe7c3ce..846a89cb 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.html @@ -22,6 +22,14 @@
+
+
+
+ +
+
+
+ diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java index 317c9eb7..cb6dc3ff 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java @@ -6,6 +6,8 @@ import org.devgateway.toolkit.forms.service.admin.ServiceCategoryService; import org.devgateway.toolkit.forms.wicket.components.form.ColorPickerBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.page.edit.admin.panel.ListViewTextTranslationSectionPanel; +import org.devgateway.toolkit.forms.wicket.page.edit.panel.TestFormChildPanel; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceCategoriesPage; import org.devgateway.toolkit.persistence.dto.ServiceCategory; import org.hibernate.envers.Audited; @@ -60,6 +62,8 @@ protected void onInitialize() { ColorPickerBootstrapFormComponent bckColorPicker = new ColorPickerBootstrapFormComponent("backgroundColor", new PropertyModel<>(editForm.getModelObject(), "categoryStyle.backgroundColor")); editForm.add(bckColorPicker); + + editForm.add(new ListViewTextTranslationSectionPanel("labels")); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties index 5d30c46e..6ffaeea6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties @@ -19,4 +19,5 @@ color.label=Color className.label=CSS Class Name textColor.label=Text Color backgroundColor.label=Background Color -type.label=Type \ No newline at end of file +type.label=Type +labels.label=Labels \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.html index dd815028..f88ef4b5 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.html @@ -11,6 +11,15 @@
+ +
+
+
+ +
+
+
+ diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java index ecfcf58b..38f1828d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java @@ -4,6 +4,7 @@ import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.service.admin.ServiceDimensionService; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.page.edit.admin.panel.ListViewTextTranslationSectionPanel; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceDimensionsPage; import org.devgateway.toolkit.persistence.dto.ServiceDimension; import org.springframework.beans.factory.annotation.Autowired; @@ -37,6 +38,9 @@ protected void onInitialize() { final TextFieldBootstrapFormComponent position = new TextFieldBootstrapFormComponent<>("position"); position.getField().setRequired(true); editForm.add(position); + + editForm.add(new ListViewTextTranslationSectionPanel("labels")); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties index 07e531c8..f98a8430 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties @@ -14,4 +14,5 @@ page.title.add=Add {0} Dimension page.title.edit=Edit {0} Dimension code.label=Code value.label=Value -position.label=Position \ No newline at end of file +position.label=Position +labels.label=Labels \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html index 6a20430d..d1039004 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html @@ -22,6 +22,14 @@
+
+
+
+ +
+
+
+ diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java index 1114a26f..0c1c137e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java @@ -6,6 +6,7 @@ import org.devgateway.toolkit.forms.service.admin.ServiceMeasureService; import org.devgateway.toolkit.forms.wicket.components.form.ColorPickerBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.page.edit.admin.panel.ListViewTextTranslationSectionPanel; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceMeasuresPage; import org.devgateway.toolkit.persistence.dto.ServiceMeasure; import org.springframework.beans.factory.annotation.Autowired; @@ -59,6 +60,8 @@ protected void onInitialize() { ColorPickerBootstrapFormComponent bckColorPicker = new ColorPickerBootstrapFormComponent("backgroundColor", new PropertyModel<>(editForm.getModelObject(), "categoryStyle.backgroundColor")); editForm.add(bckColorPicker); + + editForm.add(new ListViewTextTranslationSectionPanel("labels")); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties index 6f5227df..899cfc1c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties @@ -19,4 +19,5 @@ expression.label=Expression color.label=Color className.label=CSS Class Name textColor.label=Text Color -backgroundColor.label=Background Color \ No newline at end of file +backgroundColor.label=Background Color +labels.label=Labels \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.html new file mode 100644 index 00000000..e99fa653 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.html @@ -0,0 +1,33 @@ + + + ListSectionPanel + + + +
+
+
+

[[title]]

+
+
+ +
+
+
+
+
+ +
+
+
+
+ +
+
+ +
+
+ +
+ + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.java new file mode 100644 index 00000000..f8049653 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.java @@ -0,0 +1,137 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.admin.panel; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.TransparentWebMarkupContainer; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.list.ListItem; +import org.apache.wicket.markup.html.list.ListView; +import org.apache.wicket.model.CompoundPropertyModel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.ResourceModel; +import org.devgateway.toolkit.forms.wicket.components.CompoundSectionPanel; +import org.devgateway.toolkit.forms.wicket.components.form.BootstrapAddButton; +import org.devgateway.toolkit.forms.wicket.components.form.BootstrapDeleteButton; +import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.components.util.ComponentUtil; +import org.devgateway.toolkit.persistence.dto.ServiceCategory; +import org.devgateway.toolkit.persistence.dto.ServiceTextTranslation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +public class ListViewTextTranslationSectionPanel extends CompoundSectionPanel> { + private static final Logger logger = LoggerFactory.getLogger(ListViewTextTranslationSectionPanel.class); + + protected WebMarkupContainer listWrapper; + + protected ListView listView; + + public ListViewTextTranslationSectionPanel(final String id) { + super(id); + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + setOutputMarkupId(true); + setOutputMarkupPlaceholderTag(true); + + listWrapper = new TransparentWebMarkupContainer("listWrapper"); + listWrapper.setOutputMarkupId(true); + add(listWrapper); + + listWrapper.add(new Label("panelTitle", title)); + + listView = new ListView("list", getModel()) { + @Override + protected void populateItem(final ListItem item) { + item.setOutputMarkupId(true); + item.setOutputMarkupPlaceholderTag(true); + + // we wrap the item model on a compound model so we can use the field ids as property models + final CompoundPropertyModel compoundPropertyModel = new CompoundPropertyModel<>(item.getModel()); + + // we set back the model as the compound model, thus ensures the rest of the items added will benefit + item.setModel(compoundPropertyModel); + + // we add the rest of the items in the listItem + populateCompoundListItem(item); + + addItemContainer(item); + } + }; + + listView.setReuseItems(true); + listView.setOutputMarkupId(true); + listWrapper.add(listView); + + final BootstrapAddButton addButton = getAddNewChildButton(); + add(addButton); + } + + private void addItemContainer(final ListItem item) { + // we add the remove button + final BootstrapDeleteButton removeButton = getRemoveChildButton(item.getModelObject()); + item.add(removeButton); + } + + /** + * Removes a child based on its index + * + * @param item + * @return + */ + private BootstrapDeleteButton getRemoveChildButton(final ServiceTextTranslation item) { + final BootstrapDeleteButton removeButton = new BootstrapDeleteButton("remove", + new ResourceModel("removeButton")) { + @Override + protected void onSubmit(final AjaxRequestTarget target) { + ListViewTextTranslationSectionPanel.this.getModelObject().remove(item); + listView.removeAll(); + target.add(listWrapper); + } + }; + + removeButton.setOutputMarkupPlaceholderTag(true); + return removeButton; + } + + /** + * Returns the new child button. + */ + final BootstrapAddButton getAddNewChildButton() { + final BootstrapAddButton newButton = new BootstrapAddButton("newButton", new ResourceModel("newButton")) { + @Override + protected void onSubmit(final AjaxRequestTarget target) { + final ServiceTextTranslation newChild = createNewChild( + (IModel) ListViewTextTranslationSectionPanel.this.getParent().getDefaultModel()); + ListViewTextTranslationSectionPanel.this.getModel().getObject().add(newChild); + + listView.removeAll(); + target.add(listWrapper); + } + + }; + + newButton.setOutputMarkupPlaceholderTag(true); + return newButton; + } + + public ServiceTextTranslation createNewChild(IModel parentModel) { + ServiceTextTranslation textTranslation = new ServiceTextTranslation(); + textTranslation.setParent(parentModel.getObject()); + + return textTranslation; + } + + public void populateCompoundListItem(ListItem item) { + final TextFieldBootstrapFormComponent header = ComponentUtil.addTextField(item, "language"); + header.required(); + + final TextFieldBootstrapFormComponent value = ComponentUtil.addTextField(item, "text"); + value.required(); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.properties new file mode 100644 index 00000000..8c90b370 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.properties @@ -0,0 +1,4 @@ +newButton=New Item +removeButton=Remove Entry +language.label=Language +text.label=Text diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css index 13bb937b..45370ddf 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css @@ -294,4 +294,13 @@ button .btn-home-label { height: 30px; display: inline-block; margin-right: 5px; +} + +.row-list-item-button { + min-height: 58px; +} + +.pull-down { + position: absolute; + bottom: 0; } \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java index 1f9c9f01..b4dddbfb 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java @@ -1,6 +1,12 @@ package org.devgateway.toolkit.persistence.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import org.devgateway.toolkit.persistence.serializer.ServiceTextTranslationDeserializer; +import org.devgateway.toolkit.persistence.serializer.ServiceTextTranslationSerializer; + +import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class ServiceCategory extends ServiceEntity { @@ -15,6 +21,10 @@ public class ServiceCategory extends ServiceEntity { private String type; + @JsonDeserialize(using = ServiceTextTranslationDeserializer.class) + @JsonSerialize(using = ServiceTextTranslationSerializer.class) + private List labels; + public String getCode() { return code; } @@ -54,4 +64,12 @@ public String getType() { public void setType(final String type) { this.type = type; } + + public List getLabels() { + return labels; + } + + public void setLabels(final List labels) { + this.labels = labels; + } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceTextTranslation.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceTextTranslation.java new file mode 100644 index 00000000..5b4ad357 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceTextTranslation.java @@ -0,0 +1,33 @@ +package org.devgateway.toolkit.persistence.dto; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.io.Serializable; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServiceTextTranslation implements Serializable { + private String text; + private String language; + + private ServiceCategory parent; + + public String getText() { + return text; + } + + public void setText(final String text) { + this.text = text; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(final String language) { + this.language = language; + } + + public void setParent(final ServiceCategory parent) { + this.parent = parent; + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/serializer/ServiceTextTranslationDeserializer.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/serializer/ServiceTextTranslationDeserializer.java new file mode 100644 index 00000000..c919c21b --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/serializer/ServiceTextTranslationDeserializer.java @@ -0,0 +1,47 @@ +package org.devgateway.toolkit.persistence.serializer; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer; +import org.devgateway.toolkit.persistence.dto.ServiceTextTranslation; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * @author Viorel Chihai + */ +public class ServiceTextTranslationDeserializer extends StdScalarDeserializer> { + + protected ServiceTextTranslationDeserializer(Class> t) { + super(t); + } + + ServiceTextTranslationDeserializer() { + this(null); + } + + @Override + public List deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { + if (jp.getCurrentToken() == JsonToken.START_OBJECT) { + JsonDeserializer deserializer = ctxt.findRootValueDeserializer(ctxt.constructType(Map.class)); + Map translations = (Map) deserializer.deserialize(jp, ctxt); + List textTranslations = new ArrayList<>(); + translations.forEach((key, value) -> { + ServiceTextTranslation translation = new ServiceTextTranslation(); + translation.setLanguage(key); + translation.setText(value); + textTranslations.add(translation); + }); + return textTranslations; + } + + return null; + } + +} + diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/serializer/ServiceTextTranslationSerializer.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/serializer/ServiceTextTranslationSerializer.java new file mode 100644 index 00000000..c28643bf --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/serializer/ServiceTextTranslationSerializer.java @@ -0,0 +1,35 @@ +package org.devgateway.toolkit.persistence.serializer; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import org.devgateway.toolkit.persistence.dto.ServiceTextTranslation; + +import java.io.IOException; +import java.util.List; + +/** + * @author Viorel Chihai + */ +public class ServiceTextTranslationSerializer extends StdSerializer> { + + protected ServiceTextTranslationSerializer(Class> t) { + super(t); + } + + ServiceTextTranslationSerializer() { + this(null); + } + + @Override + public void serialize(final List localeTexts, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException { + + jsonGenerator.writeStartObject(); + for (ServiceTextTranslation localeText : localeTexts) { + jsonGenerator.writeStringField(localeText.getLanguage(), localeText.getText()); + } + jsonGenerator.writeEndObject(); + } + +} + From 97032ba5fcb5393995701513b9b4fab96b12f6ba Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 14 Oct 2022 10:00:15 +0300 Subject: [PATCH 089/137] TOBACCO-1021: Add unique validator for labels --- .../UniqueLanguageTranslationValidator.java | 30 +++++++++++++++++++ .../edit/admin/EditServiceCategoryPage.java | 5 ++-- .../edit/admin/EditServiceDimensionPage.java | 3 +- .../edit/admin/EditServiceMeasurePage.java | 2 ++ 4 files changed, 36 insertions(+), 4 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueLanguageTranslationValidator.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueLanguageTranslationValidator.java b/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueLanguageTranslationValidator.java new file mode 100644 index 00000000..bd650695 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueLanguageTranslationValidator.java @@ -0,0 +1,30 @@ +package org.devgateway.toolkit.forms.validators; + +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.form.FormComponent; +import org.apache.wicket.markup.html.form.validation.AbstractFormValidator; +import org.devgateway.toolkit.persistence.dto.ServiceCategory; +import org.devgateway.toolkit.persistence.dto.ServiceTextTranslation; + +import java.util.stream.Collectors; + +public class UniqueLanguageTranslationValidator extends AbstractFormValidator { + + @Override + public FormComponent[] getDependentFormComponents() { + return new FormComponent[0]; + } + + @Override + public void validate(final Form form) { + ServiceCategory serviceCategory = (ServiceCategory) form.getModelObject(); + serviceCategory.getLabels().stream() + .filter(label -> label.getLanguage() != null) + .collect(Collectors.groupingBy(ServiceTextTranslation::getLanguage)) + .entrySet().stream() + .filter(entry -> entry.getValue().size() > 1) + .forEach(entry -> { + form.error("Language " + entry.getKey() + " is duplicated"); + }); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java index cb6dc3ff..01c08188 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java @@ -4,14 +4,12 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.service.admin.ServiceCategoryService; +import org.devgateway.toolkit.forms.validators.UniqueLanguageTranslationValidator; import org.devgateway.toolkit.forms.wicket.components.form.ColorPickerBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.admin.panel.ListViewTextTranslationSectionPanel; -import org.devgateway.toolkit.forms.wicket.page.edit.panel.TestFormChildPanel; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceCategoriesPage; import org.devgateway.toolkit.persistence.dto.ServiceCategory; -import org.hibernate.envers.Audited; -import org.springframework.beans.factory.annotation.Autowired; import org.wicketstuff.annotation.mount.MountPath; @MountPath(value = "/editServiceCategory") @@ -64,6 +62,7 @@ protected void onInitialize() { editForm.add(bckColorPicker); editForm.add(new ListViewTextTranslationSectionPanel("labels")); + editForm.add(new UniqueLanguageTranslationValidator()); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java index 38f1828d..a36c4e55 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java @@ -3,6 +3,7 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.service.admin.ServiceDimensionService; +import org.devgateway.toolkit.forms.validators.UniqueLanguageTranslationValidator; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.admin.panel.ListViewTextTranslationSectionPanel; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceDimensionsPage; @@ -40,7 +41,7 @@ protected void onInitialize() { editForm.add(position); editForm.add(new ListViewTextTranslationSectionPanel("labels")); - + editForm.add(new UniqueLanguageTranslationValidator()); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java index 0c1c137e..d9316ba3 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java @@ -4,6 +4,7 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.service.admin.ServiceMeasureService; +import org.devgateway.toolkit.forms.validators.UniqueLanguageTranslationValidator; import org.devgateway.toolkit.forms.wicket.components.form.ColorPickerBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.admin.panel.ListViewTextTranslationSectionPanel; @@ -62,6 +63,7 @@ protected void onInitialize() { editForm.add(bckColorPicker); editForm.add(new ListViewTextTranslationSectionPanel("labels")); + editForm.add(new UniqueLanguageTranslationValidator()); } } From c222a693257deb9cc7b905c4838affc679cd218c Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 19 Oct 2022 13:40:28 +0300 Subject: [PATCH 090/137] TOBACCO-1057: Update data icon description in home page --- .../devgateway/toolkit/forms/wicket/page/Homepage.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties index bafcdb2f..fcaafc7c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties @@ -1,7 +1,7 @@ page.title=${countryName} TCDI Admin Module data.label=Data -data.desc=Upload, edit, revert to draft and validate Data +data.desc=Upload and edit data, manage the measures, dimensions and categories for each dataset configurations.label=Configurations configurations.desc=Manage the general configurations of the system \ No newline at end of file From 8daf7dbbac447f19f74efac38bb85605cf21d48e Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 19 Oct 2022 14:49:58 +0300 Subject: [PATCH 091/137] TOBACCO-1058: Remove groups --- .../toolkit/forms/wicket/page/BasePage.java | 12 ------------ .../forms/wicket/page/ConfigurationsHomepage.java | 4 ---- .../wicket/page/ConfigurationsHomepage.properties | 8 +------- .../forms/wicket/page/lists/ListUserPage.java | 1 - .../forms/wicket/page/user/ChangePasswordPage.java | 1 - .../toolkit/forms/wicket/page/user/EditUserPage.html | 1 - .../toolkit/forms/wicket/page/user/EditUserPage.java | 12 ------------ .../forms/wicket/page/user/EditUserPage.properties | 1 - 8 files changed, 1 insertion(+), 39 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 26044b59..40ebed25 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -49,9 +49,7 @@ import org.apache.wicket.util.string.StringValue; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityUtil; -import org.devgateway.toolkit.forms.wicket.page.lists.ListGroupPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListTestFormPage; -import org.devgateway.toolkit.forms.wicket.page.lists.ListTobaccoProductPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListUserPage; import org.devgateway.toolkit.forms.wicket.page.user.EditUserPage; import org.devgateway.toolkit.forms.wicket.page.user.LogoutPage; @@ -259,16 +257,6 @@ protected List newSubMenuButtons(final String arg0) { new StringResourceModel("navbar.users", this, null)) .setIconType(FontAwesome5IconType.users_s)); - list.add(new MenuBookmarkablePageLink(ListGroupPage.class, null, - new StringResourceModel("navbar.groups", this, null)) - .setIconType(FontAwesome5IconType.tags_s)); - - list.add(new MenuDivider()); - - list.add(new MenuBookmarkablePageLink(ListTobaccoProductPage.class, null, - new StringResourceModel("navbar.tobaccoproducts", this, null)) - .setIconType(FontAwesome5IconType.smoking_s)); - list.add(new MenuDivider()); list.add(new MenuBookmarkablePageLink(EditAdminSettingsPage.class, diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java index bf903941..91a501d4 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java @@ -11,8 +11,6 @@ import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; -import org.devgateway.toolkit.forms.wicket.page.lists.ListGroupPage; -import org.devgateway.toolkit.forms.wicket.page.lists.ListTobaccoProductPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListUserPage; import org.devgateway.toolkit.web.util.SettingsUtils; @@ -30,8 +28,6 @@ public class ConfigurationsHomepage extends BasePage { private static final List LINKS = new ImmutableList.Builder() .add(new BigLinkDefinition("users", ListUserPage.class, FontAwesome5IconType.users_s)) - .add(new BigLinkDefinition("groups", ListGroupPage.class, FontAwesome5IconType.tags_s)) - .add(new BigLinkDefinition("tobaccoProducts", ListTobaccoProductPage.class, FontAwesome5IconType.smoking_s)) .add(new BigLinkDefinition("settings", EditAdminSettingsPage.class, FontAwesome5IconType.cogs_s)) .build(); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.properties index 0e4641f1..a23e62ad 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.properties @@ -3,11 +3,5 @@ page.title=Configurations users.label=Users users.desc=Manage the Users -groups.label=Groups -groups.desc=Manage the Groups - settings.label=Settings -settings.desc=Manage the general settings of the system - -tobaccoProducts.label=Tobacco Products -tobaccoProducts.desc=Manage the Tobacco Products \ No newline at end of file +settings.desc=Manage the general settings of the system \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListUserPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListUserPage.java index 3514a40e..9008e40b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListUserPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListUserPage.java @@ -38,7 +38,6 @@ public ListUserPage(final PageParameters pageParameters) { this.editPageClass = EditUserPageElevated.class; columns.add(new PropertyColumn<>(new Model<>("Name"), "username", "username")); - columns.add(new PropertyColumn<>(new Model<>("Group"), "group", "group")); columns.add(new PropertyColumn<>(new Model<>("Roles"), "roles", "roles")); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/ChangePasswordPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/ChangePasswordPage.java index 8780844e..d7449bfe 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/ChangePasswordPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/ChangePasswordPage.java @@ -25,7 +25,6 @@ protected void onInitialize() { lastName.setVisibilityAllowed(false); email.setVisibilityAllowed(false); title.setVisibilityAllowed(false); - group.setVisibilityAllowed(false); roles.setVisibilityAllowed(false); enabled.setVisibilityAllowed(false); changePasswordNextSignIn.setVisibilityAllowed(false); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.html index 1dd64a9f..8193306c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.html @@ -16,7 +16,6 @@
-
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.java index f27fcd87..d34014a3 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.java @@ -34,7 +34,6 @@ import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; import org.devgateway.toolkit.forms.wicket.components.form.CheckBoxToggleBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.PasswordFieldBootstrapFormComponent; -import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.Select2MultiChoiceBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.util.ComponentUtil; @@ -43,10 +42,8 @@ import org.devgateway.toolkit.forms.wicket.page.lists.ListUserPage; import org.devgateway.toolkit.persistence.dao.Person; import org.devgateway.toolkit.persistence.dao.Role; -import org.devgateway.toolkit.persistence.dao.categories.Group; import org.devgateway.toolkit.persistence.service.PersonService; import org.devgateway.toolkit.persistence.service.RoleService; -import org.devgateway.toolkit.persistence.service.category.GroupService; import org.springframework.security.crypto.password.PasswordEncoder; import org.wicketstuff.annotation.mount.MountPath; @@ -60,9 +57,6 @@ public class EditUserPage extends AbstractEditPage { @SpringBean private PersonService personService; - @SpringBean - private GroupService groupService; - @SpringBean private RoleService roleService; @@ -82,8 +76,6 @@ public class EditUserPage extends AbstractEditPage { protected TextFieldBootstrapFormComponent title; - protected Select2ChoiceBootstrapFormComponent group; - protected Select2MultiChoiceBootstrapFormComponent roles; protected CheckBoxToggleBootstrapFormComponent enabled; @@ -150,10 +142,6 @@ protected void onInitialize() { title = ComponentUtil.addTextField(editForm, "title"); title.getField().add(MAXIMUM_LENGTH_VALIDATOR_STD_DEFAULT_TEXT); - group = ComponentUtil.addSelect2ChoiceField(editForm, "group", groupService); - group.required(); - MetaDataRoleAuthorizationStrategy.authorize(group, Component.RENDER, SecurityConstants.Roles.ROLE_ADMIN); - roles = ComponentUtil.addSelect2MultiChoiceField(editForm, "roles", roleService); roles.required(); MetaDataRoleAuthorizationStrategy.authorize(roles, Component.RENDER, SecurityConstants.Roles.ROLE_ADMIN); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.properties index dc97e47c..744aa813 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.properties @@ -19,7 +19,6 @@ firstName.label=First name lastName.label=Last name email.label=Email address title.label=Title -group.label=Group roles.label=Roles plainPassword.label=Password plainPasswordCheck.label=Repeat password From d643c858d80bb4530870c235b031973c4e58b4ec Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 19 Oct 2022 18:16:08 +0300 Subject: [PATCH 092/137] TOBACCO-1059: Add asterisk to required fields --- .../devgateway/toolkit/forms/wicket/styles/BaseStyles.css | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css index 13bb937b..4c1403c7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css @@ -294,4 +294,11 @@ button .btn-home-label { height: 30px; display: inline-block; margin-right: 5px; +} + +.required .control-label:before { + content: "*"; + color: #a94442; + display: inline; + margin-right: 5px; } \ No newline at end of file From 4d12ff69ec2f91410dd7fc4bfc4e6e514aec5dae Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 19 Oct 2022 20:25:44 +0300 Subject: [PATCH 093/137] TOBACCO-1061: Update data page icons --- .../org/devgateway/toolkit/forms/wicket/page/DataPage.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java index c79029e3..56e244d1 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java @@ -84,9 +84,9 @@ public IModel getDescModel() { private FontAwesome5IconType getServiceIcon(final String type) { if (type.equals(WebConstants.SERVICE_TETSIM_TYPE)) { - return FontAwesome5IconType.wpforms; + return FontAwesome5IconType.list_alt_r; } else if (type.equals(WebConstants.SERVICE_DATA_TYPE)) { - return FontAwesome5IconType.table_s; + return FontAwesome5IconType.file_csv_s; } throw new IllegalArgumentException("Unknown service type: " + type); From 40604b44b6f09f76bf98a8c519b9ea5d3bc11a68 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 19 Oct 2022 20:59:17 +0300 Subject: [PATCH 094/137] TOBACCO-1060: Update currency field in admin settings --- .../wicket/page/EditAdminSettingsPage.html | 2 +- .../wicket/page/EditAdminSettingsPage.java | 16 ++----- .../page/EditAdminSettingsPage.properties | 2 +- .../dataset/TetsimBaselineNumbersPanel.java | 2 +- .../dataset/TetsimPriceAnalysisPanel.java | 2 +- .../persistence/dao/AdminSettings.java | 11 +++-- .../persistence/dao/categories/Currency.java | 11 ----- .../category/CurrencyRepository.java | 9 ---- .../service/category/CurrencyService.java | 9 ---- .../service/category/CurrencyServiceImpl.java | 42 ------------------- .../main/resources/liquibase-changelog.xml | 20 +++++++++ 11 files changed, 32 insertions(+), 94 deletions(-) delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Currency.java delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/CurrencyRepository.java delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyService.java delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyServiceImpl.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html index 7318bee7..74d5bb30 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html @@ -29,7 +29,7 @@
-
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java index d28910d6..8f5f5234 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java @@ -8,15 +8,10 @@ import org.apache.wicket.validation.validator.RangeValidator; import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.wicket.components.form.CheckBoxToggleBootstrapFormComponent; -import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; -import org.devgateway.toolkit.forms.wicket.providers.GenericPersistableJpaTextChoiceProvider; import org.devgateway.toolkit.persistence.dao.AdminSettings; -import org.devgateway.toolkit.persistence.dao.categories.Currency; import org.devgateway.toolkit.persistence.service.AdminSettingsService; -import org.devgateway.toolkit.persistence.service.category.CurrencyService; -import org.springframework.data.domain.Sort; import org.wicketstuff.annotation.mount.MountPath; import java.util.List; @@ -31,9 +26,6 @@ public class EditAdminSettingsPage extends AbstractEditPage { private static final long serialVersionUID = 5742724046825803877L; - @SpringBean - private CurrencyService currencyService; - private CheckBoxToggleBootstrapFormComponent rebootServer; private TextFieldBootstrapFormComponent autosaveTime; @@ -67,11 +59,9 @@ protected void onInitialize() { editForm.add(new Label("appSettingsTitle", new StringResourceModel("appSettingsTitle", this, null))); - Select2ChoiceBootstrapFormComponent currency = new Select2ChoiceBootstrapFormComponent<>( - "defaultCurrency", - new GenericPersistableJpaTextChoiceProvider<>(currencyService).setSort(Sort.Direction.ASC, "label")); - currency.required(); - editForm.add(currency); + TextFieldBootstrapFormComponent tetsimCurrency = new TextFieldBootstrapFormComponent<>("tetsimCurrency"); + tetsimCurrency.required(); + editForm.add(tetsimCurrency); editForm.add(new TextFieldBootstrapFormComponent<>("countryName")); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties index 9a5818fe..fa2dcb85 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties @@ -5,5 +5,5 @@ appSettingsTitle=Application Settings rebootServer.label=Enable server reboot warning autosaveTime.label=Autosave Time (minutes) autosaveTime.help=Set to 0 to disable -defaultCurrency.label=Default Currency +tetsimCurrency.label=Currency for TETSIM countryName.label=Country Name \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java index 01e20f69..0d4ef33d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimBaselineNumbersPanel.java @@ -97,7 +97,7 @@ private TetsimBaselineDecimalVariable getSmokingPrevalenceVariable(final String } private String getDefaultCurrency() { - return adminSettingsService.get().getDefaultCurrency().getLabel(); + return adminSettingsService.get().getTetsimCurrency(); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java index f88f29dd..62dfc693 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java @@ -265,7 +265,7 @@ private TetsimTobaccoProductsVariable getChangeInIllicitNot(final String id) { } private String getDefaultCurrency() { - return adminSettingsService.get().getDefaultCurrency().getLabel(); + return adminSettingsService.get().getTetsimCurrency(); } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java index de73ca52..b49430bc 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java @@ -1,6 +1,5 @@ package org.devgateway.toolkit.persistence.dao; -import org.devgateway.toolkit.persistence.dao.categories.Currency; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; @@ -28,7 +27,7 @@ public class AdminSettings extends AbstractAuditableEntity { private Integer autosaveTime = AUTOSAVE_TIME_DEFAULT; - private Currency defaultCurrency; + private String tetsimCurrency; private String countryName; @@ -65,12 +64,12 @@ public void setAutosaveTime(Integer autosaveTime) { this.autosaveTime = autosaveTime; } - public Currency getDefaultCurrency() { - return defaultCurrency; + public String getTetsimCurrency() { + return tetsimCurrency; } - public void setDefaultCurrency(final Currency defaultCurrency) { - this.defaultCurrency = defaultCurrency; + public void setTetsimCurrency(String tetsimCurrency) { + this.tetsimCurrency = tetsimCurrency; } public String getCountryName() { diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Currency.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Currency.java deleted file mode 100644 index ed0fddf6..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Currency.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.devgateway.toolkit.persistence.dao.categories; - -import org.hibernate.envers.Audited; - -import javax.persistence.Entity; - -@Entity -@Audited -public class Currency extends Category { - -} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/CurrencyRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/CurrencyRepository.java deleted file mode 100644 index 659ffb35..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/CurrencyRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.devgateway.toolkit.persistence.repository.category; - -import org.devgateway.toolkit.persistence.dao.categories.Currency; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public interface CurrencyRepository extends CategoryRepository { - -} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyService.java deleted file mode 100644 index 44b25338..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyService.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.devgateway.toolkit.persistence.service.category; - -import org.devgateway.toolkit.persistence.dao.categories.Currency; -import org.devgateway.toolkit.persistence.service.BaseJpaService; -import org.devgateway.toolkit.persistence.service.TextSearchableService; - -public interface CurrencyService extends BaseJpaService, TextSearchableService { - -} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyServiceImpl.java deleted file mode 100644 index cf9aa93b..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/CurrencyServiceImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.devgateway.toolkit.persistence.service.category; - -import org.devgateway.toolkit.persistence.dao.categories.Currency; -import org.devgateway.toolkit.persistence.repository.category.CurrencyRepository; -import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; -import org.devgateway.toolkit.persistence.repository.norepository.TextSearchableRepository; -import org.devgateway.toolkit.persistence.service.BaseJpaServiceImpl; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.CacheConfig; -import org.springframework.data.domain.Sort; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@CacheConfig(cacheNames = "servicesCache") -@Transactional(readOnly = true) -public class CurrencyServiceImpl extends BaseJpaServiceImpl implements CurrencyService { - - @Autowired - private CurrencyRepository currencyRepository; - - @Override - public Currency newInstance() { - return new Currency(); - } - - @Override - protected BaseJpaRepository repository() { - return currencyRepository; - } - - @Override - public TextSearchableRepository textRepository() { - return currencyRepository; - } - - @Override - public Sort getSort() { - return Sort.by(Sort.Direction.ASC, "label"); - } - -} diff --git a/persistence/src/main/resources/liquibase-changelog.xml b/persistence/src/main/resources/liquibase-changelog.xml index 524b48bb..669acbcf 100644 --- a/persistence/src/main/resources/liquibase-changelog.xml +++ b/persistence/src/main/resources/liquibase-changelog.xml @@ -150,4 +150,24 @@ + + + + + + DTYPE = 'Currency' + + + + + + + + + + + + + + \ No newline at end of file From f4f589877ce0be69ab9a1efb42509179be6383ca Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 20 Oct 2022 13:47:56 +0300 Subject: [PATCH 095/137] TOBACCO-1062: Remove tobacco product category --- .../UniqueTobaccoProductIllicitValidator.java | 64 -------- ...eTobaccoProductIllicitValidator.properties | 1 - .../filter/TobaccoProductFilterState.java | 39 ----- .../forms/wicket/page/CategoriesHomepage.html | 12 -- .../forms/wicket/page/CategoriesHomepage.java | 47 ------ .../wicket/page/CategoriesHomepage.properties | 4 - .../edit/category/EditTobaccoProductPage.html | 15 -- .../edit/category/EditTobaccoProductPage.java | 64 -------- .../EditTobaccoProductPage.properties | 5 - .../page/edit/dataset/EditCSVDatasetPage.java | 4 - .../edit/dataset/EditTetsimDatasetPage.java | 30 ---- .../edit/dataset/NoTobaccoProductsPanel.html | 15 -- .../edit/dataset/NoTobaccoProductsPanel.java | 22 --- .../dataset/NoTobaccoProductsPanel.properties | 2 - .../dataset/TetsimIndustryResponsesPanel.java | 10 +- .../dataset/TetsimPriceAnalysisPanel.java | 9 +- .../TetsimTobaccoProductsVariable.java | 12 +- .../page/lists/ListTobaccoProductPage.java | 67 -------- .../lists/ListTobaccoProductPage.properties | 3 - .../dao/categories/TobaccoProduct.java | 23 --- .../dao/data/TetsimTobaccoProductValue.java | 2 - .../persistence/dao/data/TobaccoProduct.java | 35 ++++ .../persistence/dto/TetsimExportOutput.java | 8 +- .../toolkit/persistence/dto/TetsimOutput.java | 8 +- .../category/TobaccoProductRepository.java | 11 -- .../category/TobaccoProductService.java | 10 -- .../category/TobaccoProductServiceImpl.java | 47 ------ .../service/tetsim/TetsimOutputService.java | 7 +- .../tetsim/TetsimOutputBaseCalculator.java | 149 +++++++++--------- .../util/tetsim/TetsimOutputCalculator.java | 3 +- .../TetsimOutputOvershiftCalculator.java | 3 +- .../TetsimOutputUndershiftCalculator.java | 3 +- .../persistence/util/tetsim/TetsimUtil.java | 20 ++- .../main/resources/liquibase-changelog.xml | 9 +- .../TetsimOutputBaseCalculatorTest.java | 45 ++---- .../TetsimOutputCalculatorAbsChangeTest.java | 28 ++-- ...imOutputCalculatorBaselineNumbersTest.java | 28 ++-- ...utputCalculatorQuantityAndRevenueTest.java | 14 +- ...mOutputOvershiftCalculatorNumbersTest.java | 14 +- ...mOutputOvershiftCalculatorOverallTest.java | 6 +- .../TetsimOutputOvershiftCalculatorTest.java | 52 +++--- ...OutputUndershiftCalculatorOverallTest.java | 6 +- .../TetsimTobaccoProductValueBuilder.java | 2 +- .../tetsim/builder/TobaccoProductBuilder.java | 26 --- 44 files changed, 268 insertions(+), 716 deletions(-) delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.java delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.properties delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TobaccoProductFilterState.java delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.html delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.java delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.html delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.properties delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.html delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.java delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.properties delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.java delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.properties delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/TobaccoProduct.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TobaccoProduct.java delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/TobaccoProductRepository.java delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductService.java delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java delete mode 100644 persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TobaccoProductBuilder.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.java b/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.java deleted file mode 100644 index 97c384bb..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.devgateway.toolkit.forms.validators; - -import org.apache.wicket.Component; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.validation.IValidatable; -import org.apache.wicket.validation.IValidator; -import org.apache.wicket.validation.ValidationError; -import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; - -import java.util.Collection; -import java.util.Collections; - -/** - * @author Viorel Chihai - */ -public class UniqueTobaccoProductIllicitValidator implements IValidator { - private static final long serialVersionUID = -695597033541103492L; - - protected final TobaccoProductService tobaccoProductService; - - protected final Collection entityIdsToIgnore; - - protected final String propertyName; - - protected final IModel propertyLabel; - - public UniqueTobaccoProductIllicitValidator(final TobaccoProductService tobaccoProductService, - final long entityIdToIgnore, final String propertyName, - final Component component) { - this(tobaccoProductService, Collections.singleton(entityIdToIgnore), propertyName, component); - } - - public UniqueTobaccoProductIllicitValidator(final TobaccoProductService uniquePropertyService, - final Collection entityIdsToIgnore, final String propertyName, - final Component component) { - this(uniquePropertyService, entityIdsToIgnore, propertyName, - new StringResourceModel(propertyName + ".label", component)); - } - - public UniqueTobaccoProductIllicitValidator(final TobaccoProductService tobaccoProductService, - final Collection entityIdsToIgnore, final String propertyName, - final IModel propertyLabel) { - if (entityIdsToIgnore.isEmpty()) { - entityIdsToIgnore.add(-1L); - } - - this.tobaccoProductService = tobaccoProductService; - this.entityIdsToIgnore = entityIdsToIgnore; - this.propertyName = propertyName; - this.propertyLabel = propertyLabel; - } - - @Override - public void validate(final IValidatable validatable) { - final Boolean value = validatable.getValue(); - if (Boolean.TRUE.equals(value) - && tobaccoProductService.existsByProperty(propertyName, value, entityIdsToIgnore)) { - ValidationError error = new ValidationError(this); - validatable.error(error); - } - } - -} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.properties b/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.properties deleted file mode 100644 index e0e3cc89..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueTobaccoProductIllicitValidator.properties +++ /dev/null @@ -1 +0,0 @@ -UniqueTobaccoProductIllicitValidator=There is already another product marked as illicit. diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TobaccoProductFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TobaccoProductFilterState.java deleted file mode 100644 index 6c1e5445..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TobaccoProductFilterState.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.devgateway.toolkit.forms.wicket.components.table.filter; - -import org.apache.commons.lang3.StringUtils; -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct_; -import org.devgateway.toolkit.persistence.repository.SpecificationContext; -import org.springframework.data.jpa.domain.Specification; - -import javax.persistence.criteria.Predicate; -import java.util.ArrayList; -import java.util.List; - -public class TobaccoProductFilterState extends JpaFilterState { - - private static final long serialVersionUID = 6916178929560942055L; - - private String label; - - @Override - public Specification getSpecification() { - return (root, query, cb) -> { - List predicates = new ArrayList<>(); - SpecificationContext sc = new SpecificationContext<>(root, query, cb); - - if (StringUtils.isNotBlank(label)) { - predicates.add(cb.like(root.get(TobaccoProduct_.label), "%" + label + "%")); - } - return cb.and(predicates.toArray(new Predicate[predicates.size()])); - }; - } - - public String getLabel() { - return label; - } - - public void setLabel(final String label) { - this.label = label; - } -} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.html deleted file mode 100644 index eaa6cdfb..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - Categories Homepage - - - -
-
- - diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.java deleted file mode 100644 index fca31d61..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.devgateway.toolkit.forms.wicket.page; - -import com.google.common.collect.ImmutableList; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; -import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.ResourceModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.devgateway.toolkit.forms.security.SecurityConstants; -import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; -import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; -import org.devgateway.toolkit.forms.wicket.page.lists.ListTobaccoProductPage; -import org.devgateway.toolkit.web.util.SettingsUtils; -import org.wicketstuff.annotation.mount.MountPath; - -import java.util.List; - -/** - * @author Viorel Chihai - */ -@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) -@MountPath -public class CategoriesHomepage extends BasePage { - - @SpringBean - protected SettingsUtils settingsUtils; - - private static final List LINKS = new ImmutableList.Builder() - .add(new BigLinkDefinition("tobaccoProducts", ListTobaccoProductPage.class, - FontAwesome5IconType.smoking_s)) - .build(); - - public CategoriesHomepage(final PageParameters parameters) { - super(parameters); - - add(new BigLinksPanel("links", Model.ofList(LINKS))); - } - - @Override - protected Label getPageTitle() { - return new Label("pageTitle", new StringResourceModel("page.title", this, - Model.of(settingsUtils.getSetting()))); - } -} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties deleted file mode 100644 index 8e44e1eb..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/CategoriesHomepage.properties +++ /dev/null @@ -1,4 +0,0 @@ -page.title=${countryName} Categories - -tobaccoProducts.label=Tobacco Products -tobaccoProducts.desc=Manage the tobacco products used in the system \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.html deleted file mode 100644 index 929b3043..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - - Edit Tobacco Product - - - -
-
-
-
-
- - diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java deleted file mode 100644 index fe6f3f49..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.java +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Development Gateway, Inc and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the MIT License (MIT) - * which accompanies this distribution, and is available at - * https://opensource.org/licenses/MIT - * - * Contributors: - * Development Gateway - initial API and implementation - *******************************************************************************/ -package org.devgateway.toolkit.forms.wicket.page.edit.category; - -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.util.string.StringValue; -import org.devgateway.toolkit.forms.WebConstants; -import org.devgateway.toolkit.forms.validators.UniquePropertyValidator; -import org.devgateway.toolkit.forms.validators.UniqueTobaccoProductIllicitValidator; -import org.devgateway.toolkit.forms.wicket.components.form.CheckBoxYesNoToggleBootstrapFormComponent; -import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; -import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; -import org.devgateway.toolkit.forms.wicket.page.lists.ListTobaccoProductPage; -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; -import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; -import org.wicketstuff.annotation.mount.MountPath; - -/** - * @author vchihai - */ -@MountPath(value = "/editTobaccoProduct") -public class EditTobaccoProductPage extends AbstractEditPage { - - private static final long serialVersionUID = 8165480663853267637L; - - @SpringBean - protected TobaccoProductService tobaccoProductService; - - public EditTobaccoProductPage(final PageParameters parameters) { - super(parameters); - this.jpaService = tobaccoProductService; - this.listPageClass = ListTobaccoProductPage.class; - } - - @Override - protected void onInitialize() { - super.onInitialize(); - final StringValue id = getPageParameters().get(WebConstants.PARAM_ID); - - final TextFieldBootstrapFormComponent name = new TextFieldBootstrapFormComponent<>("label"); - name.required(); - - name.getField().add(new UniquePropertyValidator<>(tobaccoProductService, id.toLong(-1L), - "label", this)); - name.getField().add(WebConstants.StringValidators.MAXIMUM_LENGTH_VALIDATOR_STD_DEFAULT_TEXT); - editForm.add(name); - - final CheckBoxYesNoToggleBootstrapFormComponent illicit = - new CheckBoxYesNoToggleBootstrapFormComponent("illicit"); - illicit.getField().add(new UniqueTobaccoProductIllicitValidator(tobaccoProductService, id.toLong(-1L), - "illicit", this)); - editForm.add(illicit); - } -} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.properties deleted file mode 100644 index 05e8b238..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/EditTobaccoProductPage.properties +++ /dev/null @@ -1,5 +0,0 @@ -page.title.add=Add Tobacco Product -page.title.edit=Edit Tobacco Product -label.label=Product Name -illicit.label=Is it an illicit product? -uniqueLabel=Name should be unique! \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java index 7383d32c..633bdfb9 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java @@ -19,7 +19,6 @@ import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; import org.devgateway.toolkit.persistence.dao.FileMetadata; import org.devgateway.toolkit.persistence.dao.data.CSVDataset; -import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; import org.devgateway.toolkit.persistence.service.data.CSVDatasetService; import org.devgateway.toolkit.web.util.SettingsUtils; import org.slf4j.Logger; @@ -57,9 +56,6 @@ public class EditCSVDatasetPage extends AbstractEditStatusEntityPage @SpringBean protected SettingsUtils settingsUtils; - @SpringBean - protected TobaccoProductService tobaccoProductService; - public EditCSVDatasetPage(final PageParameters parameters) { super(parameters); this.jpaService = csvDatasetService; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index f42ab263..0d2bc12d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -1,6 +1,5 @@ package org.devgateway.toolkit.forms.wicket.page.edit.dataset; -import org.apache.commons.lang3.StringUtils; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.form.Form; @@ -23,8 +22,6 @@ import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; -import org.devgateway.toolkit.persistence.dto.ServiceMetadata; -import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.devgateway.toolkit.persistence.service.tetsim.TetsimOutputService; import org.devgateway.toolkit.web.util.SettingsUtils; @@ -34,13 +31,11 @@ import org.wicketstuff.annotation.mount.MountPath; import java.math.BigDecimal; -import java.util.stream.Collectors; import static org.devgateway.toolkit.forms.WebConstants.MAXIMUM_PERCENTAGE; import static org.devgateway.toolkit.forms.WebConstants.PARAM_YEAR; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; -import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.SAVED; /** * @author vchihai @@ -71,9 +66,6 @@ public class EditTetsimDatasetPage extends AbstractEditStatusEntityPage form) { } } - private boolean tobaccoProductsNotDefined() { - return tobaccoProductService.count() == 0; - } - @Override protected void enableDisableAutosaveFields(final AjaxRequestTarget target) { super.enableDisableAutosaveFields(target); - - if (tobaccoProductsNotDefined()) { - saveDraftContinueButton.setEnabled(false); - saveButton.setEnabled(false); - submitAndNext.setEnabled(false); - saveSubmitButton.setEnabled(false); - saveApproveButton.setEnabled(false); - approveButton.setEnabled(false); - revertToDraftPageButton.setEnabled(false); - } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.html deleted file mode 100644 index 84387025..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - - Edit TETSIM Datasets - - - -
- - -
-
- - diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.java deleted file mode 100644 index b4469533..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.devgateway.toolkit.forms.wicket.page.edit.dataset; - -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.link.BookmarkablePageLink; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.StringResourceModel; -import org.devgateway.toolkit.forms.wicket.page.lists.ListTobaccoProductPage; - -public class NoTobaccoProductsPanel extends Panel { - - public NoTobaccoProductsPanel(final String id) { - super(id); - } - - @Override - protected void onInitialize() { - super.onInitialize(); - add(new Label("message", getString("message"))); - add(new BookmarkablePageLink<>("link", ListTobaccoProductPage.class, null) - .setBody(new StringResourceModel("linkText"))); - } -} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.properties deleted file mode 100644 index 0f242097..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/NoTobaccoProductsPanel.properties +++ /dev/null @@ -1,2 +0,0 @@ -message=Please configure the -linkText=Tobacco Products \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.java index f587ff4e..ea940b12 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimIndustryResponsesPanel.java @@ -8,12 +8,11 @@ import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; -import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import java.util.List; +import java.util.stream.Collectors; /** * @author Viorel Chihai @@ -22,9 +21,6 @@ public class TetsimIndustryResponsesPanel extends Panel { protected final IModel tetsimDatasetIModel; - @SpringBean - protected TobaccoProductService tobaccoProductService; - public TetsimIndustryResponsesPanel(final String id, final IModel tetsimDatasetIModel) { super(id); this.tetsimDatasetIModel = tetsimDatasetIModel; @@ -43,7 +39,7 @@ private Component getIndustryResponsesHeaders() { Model.of("Industry responses to the change in taxation"))); analysisHeaders.add(new Label(analysisHeaders.newChildId(), Model.of("Unit"))); - List tobaccoProducts = tobaccoProductService.findAllSorted(); + List tobaccoProducts = TobaccoProduct.ALL.stream().collect(Collectors.toList()); for (TobaccoProduct tobaccoProduct : tobaccoProducts) { analysisHeaders.add(new Label(analysisHeaders.newChildId(), new PropertyModel<>(tobaccoProduct, "label"))); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java index 62dfc693..3849cd08 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimPriceAnalysisPanel.java @@ -12,13 +12,13 @@ import org.apache.wicket.validation.validator.RangeValidator; import org.devgateway.toolkit.forms.validators.PositiveBigDecimalValidator; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import org.devgateway.toolkit.persistence.service.AdminSettingsService; -import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; import java.math.BigDecimal; import java.util.List; +import java.util.stream.Collectors; import static org.devgateway.toolkit.forms.WebConstants.MAXIMUM_PERCENTAGE; @@ -29,9 +29,6 @@ public class TetsimPriceAnalysisPanel extends Panel { protected final IModel tetsimDatasetIModel; - @SpringBean - protected TobaccoProductService tobaccoProductService; - @SpringBean protected AdminSettingsService adminSettingsService; @@ -52,7 +49,7 @@ private Component getPriceAnalysisHeaders() { analysisHeaders.add(new Label(analysisHeaders.newChildId(), Model.of("Price Variable"))); analysisHeaders.add(new Label(analysisHeaders.newChildId(), Model.of("Unit"))); - List tobaccoProducts = tobaccoProductService.findAllSorted(); + List tobaccoProducts = TobaccoProduct.ALL.stream().collect(Collectors.toList()); for (TobaccoProduct tobaccoProduct : tobaccoProducts) { analysisHeaders.add(new Label(analysisHeaders.newChildId(), new PropertyModel<>(tobaccoProduct, "label"))); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.java index 1137ae04..a3bae716 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/TetsimTobaccoProductsVariable.java @@ -7,16 +7,15 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; -import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.stream.Collectors; /** * @author Viorel Chihai @@ -33,9 +32,6 @@ public class TetsimTobaccoProductsVariable extends Panel { protected final IModel variableModel; - @SpringBean - protected TobaccoProductService tobaccoProductService; - protected RepeatingView inputFields; public TetsimTobaccoProductsVariable(final String id, final IModel labelModel, @@ -75,7 +71,7 @@ protected void onInitialize() { protected RepeatingView createInputFields() { RepeatingView fields = new RepeatingView("tobaccoProducts"); - List tobaccoProducts = tobaccoProductService.findAllSorted(); + List tobaccoProducts = TobaccoProduct.ALL.stream().collect(Collectors.toList()); TetsimPriceVariable priceVariable = variableModel.getObject(); for (TobaccoProduct tobaccoProduct: tobaccoProducts) { @@ -104,7 +100,7 @@ public TetsimTobaccoProductValue getTobaccoProductValue(final TetsimPriceVariabl : priceVariable.getValues(); TetsimTobaccoProductValue productValue = tobaccoProductValues.stream() - .filter(t -> t.getProduct().getId().equals(product.getId())).findAny() + .filter(t -> t.getProduct().getLabel().equals(product.getLabel())).findAny() .orElse(null); if (productValue == null) { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.java deleted file mode 100644 index 97393dde..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Development Gateway, Inc and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the MIT License (MIT) - * which accompanies this distribution, and is available at - * https://opensource.org/licenses/MIT - * - * Contributors: - * Development Gateway - initial API and implementation - *******************************************************************************/ -package org.devgateway.toolkit.forms.wicket.page.lists; - -import org.apache.wicket.Component; -import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; -import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; -import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.devgateway.toolkit.forms.security.SecurityConstants; -import org.devgateway.toolkit.forms.wicket.components.table.TextFilteredBootstrapPropertyColumn; -import org.devgateway.toolkit.forms.wicket.components.table.filter.JpaFilterState; -import org.devgateway.toolkit.forms.wicket.components.table.filter.TobaccoProductFilterState; -import org.devgateway.toolkit.forms.wicket.page.edit.category.EditTobaccoProductPage; -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; -import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; -import org.wicketstuff.annotation.mount.MountPath; - -@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) -@MountPath(value = "/listTobaccoProduct") -public class ListTobaccoProductPage extends AbstractListPage { - private static final long serialVersionUID = -324298525712620234L; - - @SpringBean - private TobaccoProductService tobaccoProductService; - - public ListTobaccoProductPage(final PageParameters pageParameters) { - super(pageParameters); - this.jpaService = tobaccoProductService; - this.editPageClass = EditTobaccoProductPage.class; - - columns.add(new TextFilteredBootstrapPropertyColumn<>(new StringResourceModel("label"), "label", "label")); - columns.add(new PropertyColumn<>(new StringResourceModel("illicit"), "illicit", "illicit")); - } - - - @Override - protected void onInitialize() { - super.onInitialize(); - - dataProvider.setSort("label", SortOrder.ASCENDING); - - excelForm.setVisibilityAllowed(false); - } - - @Override - protected Component getRevisionsLink(final TobaccoProduct entity) { - return new WebMarkupContainer("revisions").setVisibilityAllowed(false); - } - - @Override - public JpaFilterState newFilterState() { - return new TobaccoProductFilterState(); - } -} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.properties deleted file mode 100644 index bd5dc168..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListTobaccoProductPage.properties +++ /dev/null @@ -1,3 +0,0 @@ -page.title=Tobacco Products -label=Product Name -illicit=Is it an illicit product? \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/TobaccoProduct.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/TobaccoProduct.java deleted file mode 100644 index 2fde075d..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/TobaccoProduct.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.devgateway.toolkit.persistence.dao.categories; - -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; -import org.hibernate.envers.Audited; - -import javax.persistence.Entity; - -@Entity -@Audited -@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) -public class TobaccoProduct extends Category { - - private Boolean illicit; - - public Boolean isIllicit() { - return illicit; - } - - public void setIllicit(final Boolean illicit) { - this.illicit = illicit; - } -} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java index 0e31a9f4..d7b03206 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java @@ -1,7 +1,6 @@ package org.devgateway.toolkit.persistence.dao.data; import org.devgateway.toolkit.persistence.dao.AbstractAuditableEntity; -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; @@ -19,7 +18,6 @@ public class TetsimTobaccoProductValue extends AbstractAuditableEntity { @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private TetsimPriceVariable priceVariable; - @ManyToOne @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private TobaccoProduct product; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TobaccoProduct.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TobaccoProduct.java new file mode 100644 index 00000000..adf8b856 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TobaccoProduct.java @@ -0,0 +1,35 @@ +package org.devgateway.toolkit.persistence.dao.data; + +import java.util.EnumSet; +import java.util.List; + +public enum TobaccoProduct { + + IMPORTED("Imported"), + PREMIUM("Premium"), + POPULAR("Popular"), + DISCOUNT("Discount"), + ILLICIT("Illicit", true); + + public static final EnumSet ALL = EnumSet.of(IMPORTED, PREMIUM, POPULAR, DISCOUNT, ILLICIT); + + private final String label; + private final Boolean illicit; + + TobaccoProduct(String label) { + this(label, false); + } + + TobaccoProduct(String label, Boolean illicit) { + this.label = label; + this.illicit = illicit; + } + + public String getLabel() { + return label; + } + + public Boolean isIllicit() { + return illicit; + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java index 2c4aa5d5..579c6f1c 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java @@ -1,5 +1,7 @@ package org.devgateway.toolkit.persistence.dto; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; + import java.io.Serializable; /** @@ -13,7 +15,7 @@ public class TetsimExportOutput implements Serializable { private Integer taxChange; - private String tobaccoProduct; + private TobaccoProduct tobaccoProduct; private Double legalConsumptionOvershift; @@ -118,11 +120,11 @@ public void setTaxChange(final Integer taxChange) { this.taxChange = taxChange; } - public String getTobaccoProduct() { + public TobaccoProduct getTobaccoProduct() { return tobaccoProduct; } - public void setTobaccoProduct(final String tobaccoProduct) { + public void setTobaccoProduct(final TobaccoProduct tobaccoProduct) { this.tobaccoProduct = tobaccoProduct; } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java index daf3a964..edc5d339 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java @@ -1,5 +1,7 @@ package org.devgateway.toolkit.persistence.dto; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; + import java.io.Serializable; /** @@ -13,7 +15,7 @@ public class TetsimOutput implements Serializable { private Integer taxChange; - private String tobaccoProduct; + private TobaccoProduct tobaccoProduct; private String shifting; @@ -59,11 +61,11 @@ public void setTaxChange(final Integer taxChange) { this.taxChange = taxChange; } - public String getTobaccoProduct() { + public TobaccoProduct getTobaccoProduct() { return tobaccoProduct; } - public void setTobaccoProduct(final String tobaccoProduct) { + public void setTobaccoProduct(final TobaccoProduct tobaccoProduct) { this.tobaccoProduct = tobaccoProduct; } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/TobaccoProductRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/TobaccoProductRepository.java deleted file mode 100644 index 72581fa0..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/category/TobaccoProductRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.devgateway.toolkit.persistence.repository.category; - -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; -import org.devgateway.toolkit.persistence.repository.norepository.UniquePropertyRepository; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public interface TobaccoProductRepository extends CategoryRepository, - UniquePropertyRepository { - -} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductService.java deleted file mode 100644 index 7180b018..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductService.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.devgateway.toolkit.persistence.service.category; - -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; -import org.devgateway.toolkit.persistence.service.BaseJpaService; -import org.devgateway.toolkit.persistence.service.TextSearchableService; -import org.devgateway.toolkit.persistence.service.UniquePropertyService; - -public interface TobaccoProductService extends BaseJpaService, TextSearchableService, - UniquePropertyService { -} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java deleted file mode 100644 index 26241424..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/category/TobaccoProductServiceImpl.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.devgateway.toolkit.persistence.service.category; - -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; -import org.devgateway.toolkit.persistence.repository.category.TobaccoProductRepository; -import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; -import org.devgateway.toolkit.persistence.repository.norepository.TextSearchableRepository; -import org.devgateway.toolkit.persistence.repository.norepository.UniquePropertyRepository; -import org.devgateway.toolkit.persistence.service.BaseJpaServiceImpl; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.CacheConfig; -import org.springframework.data.domain.Sort; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@CacheConfig(cacheNames = "servicesCache") -@Transactional(readOnly = true) -public class TobaccoProductServiceImpl extends BaseJpaServiceImpl implements TobaccoProductService { - - @Autowired - private TobaccoProductRepository tobaccoProductRepository; - - @Override - public TobaccoProduct newInstance() { - return new TobaccoProduct(); - } - - @Override - protected BaseJpaRepository repository() { - return tobaccoProductRepository; - } - - @Override - public TextSearchableRepository textRepository() { - return tobaccoProductRepository; - } - - @Override - public UniquePropertyRepository uniquePropertyRepository() { - return tobaccoProductRepository; - } - - @Override - public Sort getSort() { - return Sort.by(Sort.Direction.ASC, "label"); - } -} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java index b31ab4a4..c00013c9 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java @@ -8,6 +8,7 @@ import com.opencsv.exceptions.CsvDataTypeMismatchException; import com.opencsv.exceptions.CsvRequiredFieldEmptyException; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import org.devgateway.toolkit.persistence.dto.TetsimExportOutput; import org.devgateway.toolkit.persistence.dto.TetsimOutput; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; @@ -29,10 +30,6 @@ public class TetsimOutputService { public static final int MAX_TAX_CHANGE = 100; - public static final List TOBACCO_PRODUCTS = new ImmutableList.Builder() - .add("Imported", "Premium", "Popular", "Discount", "Illicit") - .build(); - public static final List TETSIM_CSV_FIELDS = new ImmutableList.Builder() .add("year", "taxChange", "tobaccoProduct", "legalConsumptionOvershift", "legalConsumptionChangeOvershift", "consumptionIllicitOvershift", "exciseRevOvershift", "exciseRevChangeOvershift", @@ -57,7 +54,7 @@ public List getTetsimOutputs(Long datasetId) { List outputs = new ArrayList<>(); for (int i = 0; i <= MAX_TAX_CHANGE; i++) { - for (String t : TOBACCO_PRODUCTS) { + for (TobaccoProduct t : TobaccoProduct.values()) { TetsimOutput overShift = new TetsimOutputOvershiftCalculator(dataset, i).calculate(t); TetsimOutput underShift = new TetsimOutputUndershiftCalculator(dataset, i).calculate(t); outputs.add(new TetsimExportOutput(overShift, underShift)); diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java index fcd3c446..6d3d9b23 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java @@ -2,10 +2,12 @@ import com.google.common.collect.ImmutableMap; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import org.devgateway.toolkit.persistence.dto.TetsimOutput; import java.math.BigDecimal; import java.math.MathContext; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -13,6 +15,12 @@ import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static java.math.BigDecimal.ZERO; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.DISCOUNT; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.ILLICIT; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.IMPORTED; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.POPULAR; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.PREMIUM; +import static org.devgateway.toolkit.persistence.util.tetsim.TetsimUtil.getLegalTobaccoProducts; import static org.devgateway.toolkit.persistence.util.tetsim.TetsimUtil.getTobaccoProductValueFromVariable; /** @@ -34,17 +42,17 @@ public abstract class TetsimOutputBaseCalculator implements TetsimOutputCalculat protected final Double changeInTheDeclaredCustomValue = 0.0; - public static final Map GAIN_SWITCH_TOBACCO_PRODUCT = new ImmutableMap.Builder() - .put("Popular", "Premium") - .put("Discount", "Popular") - .put("Illicit", "Discount") + public static final Map GAIN_SWITCH_TOBACCO_PRODUCT = new ImmutableMap.Builder() + .put(POPULAR, PREMIUM) + .put(DISCOUNT, POPULAR) + .put(ILLICIT, DISCOUNT) .build(); - public static final Map CONSUMPTION_DEPENDENT_TOBACCO_PRODUCT = new ImmutableMap.Builder() - .put("Imported", "Premium") - .put("Premium", "Popular") - .put("Popular", "Discount") - .put("Discount", "Illicit") + public static final Map CONSUMPTION_DEPENDENT_TOBACCO_PRODUCT = new ImmutableMap.Builder() + .put(IMPORTED, PREMIUM) + .put(PREMIUM, POPULAR) + .put(POPULAR, DISCOUNT) + .put(DISCOUNT, ILLICIT) .build(); public TetsimOutputBaseCalculator(TetsimDataset dataset, Integer percentageChange) { @@ -61,10 +69,10 @@ public TetsimOutputBaseCalculator(TetsimDataset dataset, Integer percentageChang protected abstract String getShifting(); - protected abstract BigDecimal calculateAbsChangeShift(String tobaccoProduct); + protected abstract BigDecimal calculateAbsChangeShift(TobaccoProduct tobaccoProduct); @Override - public TetsimOutput calculate(String tobaccoProduct) { + public TetsimOutput calculate(TobaccoProduct tobaccoProduct) { TetsimOutput tetsimOutput = new TetsimOutput(); tetsimOutput.setYear(this.dataset.getYear()); @@ -98,7 +106,7 @@ public Double calculateOutputLegalConsumptionChange() { } private Double calculateOutputConsumptionIllicit() { - return calculateConsumption("Illicit").doubleValue(); + return calculateConsumption(ILLICIT).doubleValue(); } private Double calculateOutputExciseRev() { @@ -116,49 +124,49 @@ private Double calculateOutputTotalGovRev() { /** * Calculate the Output Excise Burden */ - private Double calculateOutputExciseBurden(String tobaccoProduct) { + private Double calculateOutputExciseBurden(TobaccoProduct tobaccoProduct) { return calculateExciseBurden(tobaccoProduct).doubleValue(); } /** * Calculate the Output Total Tax Burden */ - private Double calculateOutputTotalTaxBurden(String tobaccoProduct) { + private Double calculateOutputTotalTaxBurden(TobaccoProduct tobaccoProduct) { return calculateTotalTaxBurden(tobaccoProduct).doubleValue(); } /** * Calculate the Output Retail Price */ - public Double calculateOutputRetailPrice(String tobaccoProduct) { + public Double calculateOutputRetailPrice(TobaccoProduct tobaccoProduct) { return calculateRetailPrice(tobaccoProduct).doubleValue(); } /** * Calculate the Output NOT */ - public Double calculateOutputNot(String tobaccoProduct) { + public Double calculateOutputNot(TobaccoProduct tobaccoProduct) { return calculateNetTaxPrice(tobaccoProduct).doubleValue(); } /** * Calculate the Output Excise Tax */ - public Double calculateOutputExciseTax(String tobaccoProduct) { + public Double calculateOutputExciseTax(TobaccoProduct tobaccoProduct) { return calculateExciseTaxDomesticProduction(tobaccoProduct).doubleValue(); } /** * Calculate the Output VAT */ - public Double calculateOutputVat(String tobaccoProduct) { + public Double calculateOutputVat(TobaccoProduct tobaccoProduct) { return calculateVat(tobaccoProduct).doubleValue(); } /** * Calculate the Output Levy */ - public Double calculateOutputLevy(String tobaccoProduct) { + public Double calculateOutputLevy(TobaccoProduct tobaccoProduct) { return calculateTobaccoLevy(tobaccoProduct).doubleValue(); } @@ -167,13 +175,13 @@ public Double calculateOutputLevy(String tobaccoProduct) { * * @param tobaccoProduct */ - public BigDecimal calculateNetTaxPrice(String tobaccoProduct) { + public BigDecimal calculateNetTaxPrice(TobaccoProduct tobaccoProduct) { BigDecimal netTaxPrice = calculateBaselineNetTaxPrice(tobaccoProduct); - if (tobaccoProduct.equals("Illicit")) { + if (tobaccoProduct.equals(ILLICIT)) { BigDecimal shift = getTobaccoProductValueFromVariable(dataset.getChangeInIllicitNot(), tobaccoProduct); - BigDecimal discountRetailPriceDifference = calculateRetailPrice("Discount") - .subtract(calculateBaselineRetailPrice("Discount")); + BigDecimal discountRetailPriceDifference = calculateRetailPrice(DISCOUNT) + .subtract(calculateBaselineRetailPrice(DISCOUNT)); return netTaxPrice.add(shift.multiply(discountRetailPriceDifference)); } @@ -191,7 +199,7 @@ private BigDecimal calculateAdditionalCharges() { * Calculate Tobacco levy * CIF per pack * (levy rate + percentage change in levy) / 100 */ - protected BigDecimal calculateTobaccoLevy(String tobaccoProduct) { + protected BigDecimal calculateTobaccoLevy(TobaccoProduct tobaccoProduct) { BigDecimal cif = getTobaccoProductValueFromVariable(dataset.getCif(), tobaccoProduct); BigDecimal levy = getTobaccoProductValueFromVariable(dataset.getTobaccoLevy(), tobaccoProduct); @@ -205,7 +213,7 @@ protected BigDecimal calculateTobaccoLevy(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateExciseTaxDomesticProduction(String tobaccoProduct) { + public BigDecimal calculateExciseTaxDomesticProduction(TobaccoProduct tobaccoProduct) { return calculateBaselineExciseTaxOnDomesticProduction(tobaccoProduct) .multiply(ONE.add(BigDecimal.valueOf(percentageChange).divide(HUNDRED, DEFAULT_CONTEXT))); } @@ -216,8 +224,8 @@ public BigDecimal calculateExciseTaxDomesticProduction(String tobaccoProduct) { * @param tobaccoProduct * @return */ - protected BigDecimal calculateExciseTaxImportedCigarettes(String tobaccoProduct) { - if (tobaccoProduct.equals("Imported")) { + protected BigDecimal calculateExciseTaxImportedCigarettes(TobaccoProduct tobaccoProduct) { + if (tobaccoProduct.equals(IMPORTED)) { return calculateBaselineExciseTaxOnImported(tobaccoProduct) .multiply(ONE.add(BigDecimal.valueOf(percentageChange).divide(HUNDRED, DEFAULT_CONTEXT))); } @@ -231,8 +239,8 @@ protected BigDecimal calculateExciseTaxImportedCigarettes(String tobaccoProduct) * @param tobaccoProduct * @return */ - protected BigDecimal calculateCustomsDutyImportedCigarettes(String tobaccoProduct) { - if (tobaccoProduct.equals("Imported")) { + protected BigDecimal calculateCustomsDutyImportedCigarettes(TobaccoProduct tobaccoProduct) { + if (tobaccoProduct.equals(IMPORTED)) { return calculateBaselineCustomsDuty(tobaccoProduct) .multiply( ONE.add(BigDecimal.valueOf(changeInTheDeclaredCustomValue).divide(HUNDRED, DEFAULT_CONTEXT)) @@ -248,8 +256,8 @@ protected BigDecimal calculateCustomsDutyImportedCigarettes(String tobaccoProduc * @param tobaccoProduct * @return */ - public BigDecimal calculateVat(String tobaccoProduct) { - if (tobaccoProduct.equals("Illicit")) { + public BigDecimal calculateVat(TobaccoProduct tobaccoProduct) { + if (tobaccoProduct.equals(ILLICIT)) { return ZERO; } @@ -271,7 +279,7 @@ public BigDecimal calculateVat(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateRetailPrice(String tobaccoProduct) { + public BigDecimal calculateRetailPrice(TobaccoProduct tobaccoProduct) { return calculateNetTaxPrice(tobaccoProduct) .add(calculateAdditionalCharges()) .add(calculateTobaccoLevy(tobaccoProduct)) @@ -288,7 +296,7 @@ public BigDecimal calculateRetailPrice(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateExciseBurden(String tobaccoProduct) { + public BigDecimal calculateExciseBurden(TobaccoProduct tobaccoProduct) { return calculateTobaccoLevy(tobaccoProduct) .add(calculateExciseTaxDomesticProduction(tobaccoProduct)) .add(calculateExciseTaxImportedCigarettes(tobaccoProduct)) @@ -303,7 +311,7 @@ public BigDecimal calculateExciseBurden(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateTotalTaxBurden(String tobaccoProduct) { + public BigDecimal calculateTotalTaxBurden(TobaccoProduct tobaccoProduct) { return calculateTobaccoLevy(tobaccoProduct) .add(calculateExciseTaxDomesticProduction(tobaccoProduct)) .add(calculateExciseTaxImportedCigarettes(tobaccoProduct)) @@ -320,7 +328,7 @@ public BigDecimal calculateTotalTaxBurden(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculatePreConsumption(String tobaccoProduct) { + public BigDecimal calculatePreConsumption(TobaccoProduct tobaccoProduct) { BigDecimal baselineConsumption = calculateBaselineConsumption(tobaccoProduct); BigDecimal priceElasticity = getTobaccoProductValueFromVariable(dataset.getElasticityOfDemandPrice(), tobaccoProduct); @@ -347,9 +355,9 @@ public BigDecimal calculatePreConsumption(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateGainFromPrice(String tobaccoProduct) { + public BigDecimal calculateGainFromPrice(TobaccoProduct tobaccoProduct) { if (GAIN_SWITCH_TOBACCO_PRODUCT.containsKey(tobaccoProduct)) { - String switchProduct = GAIN_SWITCH_TOBACCO_PRODUCT.get(tobaccoProduct); + TobaccoProduct switchProduct = GAIN_SWITCH_TOBACCO_PRODUCT.get(tobaccoProduct); BigDecimal consumption = calculatePreConsumption(tobaccoProduct); BigDecimal crossElasticity = getTobaccoProductValueFromVariable(dataset.getElasticityOfDemandCrossPrice(), @@ -378,7 +386,7 @@ public BigDecimal calculateGainFromPrice(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateConsumption(String tobaccoProduct) { + public BigDecimal calculateConsumption(TobaccoProduct tobaccoProduct) { BigDecimal consumption = calculatePreConsumption(tobaccoProduct); BigDecimal gainFromPrice = calculateGainFromPrice(tobaccoProduct); @@ -396,7 +404,7 @@ public BigDecimal calculateConsumption(String tobaccoProduct) { * @return */ public BigDecimal calculateTotalLegalConsumption() { - return getTetsimLegalTobaccoProducts().stream() + return getLegalTobaccoProducts().stream() .map(tobaccoProduct -> calculateConsumption(tobaccoProduct)) .reduce(BigDecimal.ZERO, BigDecimal::add); } @@ -414,7 +422,7 @@ public BigDecimal calculateTotalLegalConsumptionChange() { * @param tobaccoProduct * @return */ - public BigDecimal calculateRevenueTobaccoLevy(String tobaccoProduct) { + public BigDecimal calculateRevenueTobaccoLevy(TobaccoProduct tobaccoProduct) { return calculateConsumption(tobaccoProduct).multiply(calculateTobaccoLevy(tobaccoProduct)); } @@ -425,16 +433,16 @@ public BigDecimal calculateRevenueTobaccoLevy(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateRevenueExciseTaxDomesticProduction(String tobaccoProduct) { + public BigDecimal calculateRevenueExciseTaxDomesticProduction(TobaccoProduct tobaccoProduct) { return calculateConsumption(tobaccoProduct).multiply(calculateExciseTaxDomesticProduction(tobaccoProduct)); } - public BigDecimal calculateBaselineExciseRevenueDomesticProduction(String tobaccoProduct) { + public BigDecimal calculateBaselineExciseRevenueDomesticProduction(TobaccoProduct tobaccoProduct) { return calculateBaselineConsumption(tobaccoProduct) .multiply(calculateBaselineExciseTaxOnDomesticProduction(tobaccoProduct)); } - public BigDecimal calculateBaselineExciseRevenueImportedCigarettes(String tobaccoProduct) { + public BigDecimal calculateBaselineExciseRevenueImportedCigarettes(TobaccoProduct tobaccoProduct) { return calculateBaselineConsumption(tobaccoProduct) .multiply(calculateBaselineExciseTaxOnImported(tobaccoProduct)); } @@ -445,7 +453,7 @@ public BigDecimal calculateBaselineExciseRevenueImportedCigarettes(String tobacc * @param tobaccoProduct * @return */ - public BigDecimal calculateRevenueExciseTaxImportedCigarettes(String tobaccoProduct) { + public BigDecimal calculateRevenueExciseTaxImportedCigarettes(TobaccoProduct tobaccoProduct) { return calculateConsumption(tobaccoProduct).multiply(calculateExciseTaxImportedCigarettes(tobaccoProduct)); } @@ -455,7 +463,7 @@ public BigDecimal calculateRevenueExciseTaxImportedCigarettes(String tobaccoProd * @param tobaccoProduct * @return */ - public BigDecimal calculateRevenueCustomsDutyImportedCigarettes(String tobaccoProduct) { + public BigDecimal calculateRevenueCustomsDutyImportedCigarettes(TobaccoProduct tobaccoProduct) { return calculateConsumption(tobaccoProduct).multiply(calculateCustomsDutyImportedCigarettes(tobaccoProduct)); } @@ -465,7 +473,7 @@ public BigDecimal calculateRevenueCustomsDutyImportedCigarettes(String tobaccoPr * @param tobaccoProduct * @return */ - public BigDecimal calculateRevenueVat(String tobaccoProduct) { + public BigDecimal calculateRevenueVat(TobaccoProduct tobaccoProduct) { return calculateConsumption(tobaccoProduct).multiply(calculateVat(tobaccoProduct)); } @@ -474,12 +482,12 @@ public BigDecimal calculateRevenueVat(String tobaccoProduct) { * * @param tobaccoProduct */ - public BigDecimal calculateTotalExciseTaxesRevenue(String tobaccoProduct) { + public BigDecimal calculateTotalExciseTaxesRevenue(TobaccoProduct tobaccoProduct) { return calculateRevenueExciseTaxDomesticProduction(tobaccoProduct) .add(calculateRevenueExciseTaxImportedCigarettes(tobaccoProduct)); } - public BigDecimal calculateBaselineTotalExciseTaxesRevenue(String tobaccoProduct) { + public BigDecimal calculateBaselineTotalExciseTaxesRevenue(TobaccoProduct tobaccoProduct) { return calculateBaselineExciseRevenueDomesticProduction(tobaccoProduct) .add(calculateBaselineExciseRevenueImportedCigarettes(tobaccoProduct)); } @@ -488,7 +496,7 @@ public BigDecimal calculateBaselineTotalExciseTaxesRevenue(String tobaccoProduct * Calculate Total Excise Revenue: sum of excise tax */ public BigDecimal calculateTotalExciseRevenue() { - return getTetsimLegalTobaccoProducts().stream() + return getLegalTobaccoProducts().stream() .map(tobaccoProduct -> calculateTotalExciseTaxesRevenue(tobaccoProduct)) .reduce(BigDecimal.ZERO, BigDecimal::add); } @@ -506,7 +514,7 @@ public BigDecimal calculateTotalExciseRevenueChange() { * * @param tobaccoProduct */ - public BigDecimal calculateTotalRevenue(String tobaccoProduct) { + public BigDecimal calculateTotalRevenue(TobaccoProduct tobaccoProduct) { return calculateRevenueTobaccoLevy(tobaccoProduct) .add(calculateRevenueExciseTaxDomesticProduction(tobaccoProduct)) .add(calculateRevenueExciseTaxImportedCigarettes(tobaccoProduct)) @@ -518,13 +526,13 @@ public BigDecimal calculateTotalRevenue(String tobaccoProduct) { * Calculate Total Government Revenue: excise tax + VAT + levy + customs */ public BigDecimal calculateTotalLegalGovernmentRevenue() { - return getTetsimLegalTobaccoProducts().stream() + return getLegalTobaccoProducts().stream() .map(tobaccoProduct -> calculateTotalRevenue(tobaccoProduct)) .reduce(BigDecimal.ZERO, BigDecimal::add); } - public BigDecimal calculateBaselineTobaccoLevy(String tobaccoProduct) { + public BigDecimal calculateBaselineTobaccoLevy(TobaccoProduct tobaccoProduct) { BigDecimal cif = getTobaccoProductValueFromVariable(dataset.getCif(), tobaccoProduct); BigDecimal levy = getTobaccoProductValueFromVariable(dataset.getTobaccoLevy(), tobaccoProduct); @@ -538,8 +546,8 @@ public BigDecimal calculateBaselineTobaccoLevy(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateBaselineExciseTaxOnDomesticProduction(String tobaccoProduct) { - if (tobaccoProduct.equals("Imported")) { + public BigDecimal calculateBaselineExciseTaxOnDomesticProduction(TobaccoProduct tobaccoProduct) { + if (tobaccoProduct.equals(IMPORTED)) { return ZERO; } @@ -552,8 +560,8 @@ public BigDecimal calculateBaselineExciseTaxOnDomesticProduction(String tobaccoP * @param tobaccoProduct * @return */ - public BigDecimal calculateBaselineExciseTaxOnImported(String tobaccoProduct) { - if (tobaccoProduct.equals("Imported")) { + public BigDecimal calculateBaselineExciseTaxOnImported(TobaccoProduct tobaccoProduct) { + if (tobaccoProduct.equals(IMPORTED)) { return getTobaccoProductValueFromVariable(dataset.getExciseTax(), tobaccoProduct); } @@ -566,8 +574,8 @@ public BigDecimal calculateBaselineExciseTaxOnImported(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateBaselineCustomsDuty(String tobaccoProduct) { - if (tobaccoProduct.equals("Imported")) { + public BigDecimal calculateBaselineCustomsDuty(TobaccoProduct tobaccoProduct) { + if (tobaccoProduct.equals(IMPORTED)) { BigDecimal cif = getTobaccoProductValueFromVariable(dataset.getCif(), tobaccoProduct); BigDecimal duty = getTobaccoProductValueFromVariable(dataset.getCustomsDuty(), tobaccoProduct); @@ -588,7 +596,7 @@ public BigDecimal calculateBaselineCustomsDuty(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateBaselineRetailPrice(String tobaccoProduct) { + public BigDecimal calculateBaselineRetailPrice(TobaccoProduct tobaccoProduct) { return getTobaccoProductValueFromVariable(dataset.getRetailPrice(), tobaccoProduct); } @@ -597,7 +605,7 @@ public BigDecimal calculateBaselineRetailPrice(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateBaselineVAT(String tobaccoProduct) { + public BigDecimal calculateBaselineVAT(TobaccoProduct tobaccoProduct) { BigDecimal baselineRetailPrice = calculateBaselineRetailPrice(tobaccoProduct); BigDecimal vatRate = dataset.getVatRate(); @@ -615,10 +623,10 @@ public BigDecimal calculateBaselineVAT(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateBaselineNetTaxPrice(String tobaccoProduct) { + public BigDecimal calculateBaselineNetTaxPrice(TobaccoProduct tobaccoProduct) { BigDecimal baselineRetailPrice = calculateBaselineRetailPrice(tobaccoProduct); - if (tobaccoProduct.equals("Illicit")) { + if (tobaccoProduct.equals(ILLICIT)) { return baselineRetailPrice; } @@ -636,7 +644,7 @@ public BigDecimal calculateBaselineNetTaxPrice(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateBaselineExciseBurden(String tobaccoProduct) { + public BigDecimal calculateBaselineExciseBurden(TobaccoProduct tobaccoProduct) { BigDecimal baselineTobaccoLevy = calculateBaselineTobaccoLevy(tobaccoProduct); return baselineTobaccoLevy @@ -652,7 +660,7 @@ public BigDecimal calculateBaselineExciseBurden(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateBaselineTotalTaxBurden(String tobaccoProduct) { + public BigDecimal calculateBaselineTotalTaxBurden(TobaccoProduct tobaccoProduct) { BigDecimal baselineTobaccoLevy = calculateBaselineTobaccoLevy(tobaccoProduct); return baselineTobaccoLevy @@ -670,7 +678,7 @@ public BigDecimal calculateBaselineTotalTaxBurden(String tobaccoProduct) { * @param tobaccoProduct * @return */ - public BigDecimal calculateBaselineConsumption(String tobaccoProduct) { + public BigDecimal calculateBaselineConsumption(TobaccoProduct tobaccoProduct) { BigDecimal consumption = dataset.getCigaretteConsumption(); BigDecimal marketShare = getTobaccoProductValueFromVariable(dataset.getMarketShare(), tobaccoProduct); @@ -684,22 +692,15 @@ public BigDecimal calculateBaselineConsumption(String tobaccoProduct) { * @return */ public BigDecimal calculateBaselineTotalLegalConsumption() { - return getTetsimLegalTobaccoProducts().stream() + return getLegalTobaccoProducts().stream() .map(tobaccoProduct -> calculateBaselineConsumption(tobaccoProduct)) .reduce(BigDecimal.ZERO, BigDecimal::add); } public BigDecimal calculateBaselineTotalExciseRevenue() { - return getTetsimLegalTobaccoProducts().stream() + return getLegalTobaccoProducts().stream() .map(tobaccoProduct -> calculateBaselineTotalExciseTaxesRevenue(tobaccoProduct)) .reduce(BigDecimal.ZERO, BigDecimal::add); } - private List getTetsimLegalTobaccoProducts() { - return dataset.getRetailPrice().getValues().stream() - .filter(pv -> !pv.getProduct().isIllicit()) - .map(pv -> pv.getProduct().getLabel()) - .collect(Collectors.toList()); - } - } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputCalculator.java index 6489176b..278f5ca8 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputCalculator.java @@ -1,9 +1,10 @@ package org.devgateway.toolkit.persistence.util.tetsim; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import org.devgateway.toolkit.persistence.dto.TetsimOutput; public interface TetsimOutputCalculator { - TetsimOutput calculate(String tobaccoProduct); + TetsimOutput calculate(TobaccoProduct tobaccoProduct); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputOvershiftCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputOvershiftCalculator.java index 0552834c..26baef8a 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputOvershiftCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputOvershiftCalculator.java @@ -1,6 +1,7 @@ package org.devgateway.toolkit.persistence.util.tetsim; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import java.math.BigDecimal; @@ -21,7 +22,7 @@ protected String getShifting() { } @Override - public BigDecimal calculateAbsChangeShift(final String tobaccoProduct) { + public BigDecimal calculateAbsChangeShift(final TobaccoProduct tobaccoProduct) { BigDecimal exciseTax = getTobaccoProductValueFromVariable(dataset.getExciseTax(), tobaccoProduct); BigDecimal overshifting = getTobaccoProductValueFromVariable(dataset.getOvershifting(), tobaccoProduct); diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputUndershiftCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputUndershiftCalculator.java index 8ecef8ec..bfe53a2c 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputUndershiftCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputUndershiftCalculator.java @@ -1,6 +1,7 @@ package org.devgateway.toolkit.persistence.util.tetsim; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import java.math.BigDecimal; @@ -21,7 +22,7 @@ protected String getShifting() { } @Override - public BigDecimal calculateAbsChangeShift(final String tobaccoProduct) { + public BigDecimal calculateAbsChangeShift(final TobaccoProduct tobaccoProduct) { BigDecimal exciseTax = getTobaccoProductValueFromVariable(dataset.getExciseTax(), tobaccoProduct); BigDecimal undershifting = getTobaccoProductValueFromVariable(dataset.getUndershifting(), tobaccoProduct); diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimUtil.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimUtil.java index e9f4ac2f..c8c5e0a9 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimUtil.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimUtil.java @@ -1,8 +1,15 @@ package org.devgateway.toolkit.persistence.util.tetsim; import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.ILLICIT; public final class TetsimUtil { @@ -11,9 +18,18 @@ private TetsimUtil() { } public static BigDecimal getTobaccoProductValueFromVariable(TetsimPriceVariable variable, - String tobaccoProductLabel) { + TobaccoProduct tobaccoProduct) { return variable.getValues().stream() - .filter(t -> t.getProduct().getLabel().equalsIgnoreCase(tobaccoProductLabel)) + .filter(t -> t.getProduct().equals(tobaccoProduct)) .findFirst().get().getValue(); } + + public static List getLegalTobaccoProducts() { + return Arrays.asList(TobaccoProduct.values()) + .stream() + .filter(tobaccoProduct -> !tobaccoProduct.equals(ILLICIT)) + .collect(Collectors.toList()); + } + + } diff --git a/persistence/src/main/resources/liquibase-changelog.xml b/persistence/src/main/resources/liquibase-changelog.xml index 669acbcf..08321477 100644 --- a/persistence/src/main/resources/liquibase-changelog.xml +++ b/persistence/src/main/resources/liquibase-changelog.xml @@ -168,6 +168,13 @@ - + + + + + + DTYPE = 'TobaccoProduct' + + \ No newline at end of file diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputBaseCalculatorTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputBaseCalculatorTest.java index 1061d67f..821524b3 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputBaseCalculatorTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputBaseCalculatorTest.java @@ -1,52 +1,33 @@ package org.devgateway.toolkit.persistence.tetsim; +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import org.devgateway.toolkit.persistence.tetsim.builder.TetsimDatasetBuilder; import org.devgateway.toolkit.persistence.tetsim.builder.TetsimPriceVariableBuilder; import org.devgateway.toolkit.persistence.tetsim.builder.TetsimTobaccoProductValueBuilder; -import org.devgateway.toolkit.persistence.tetsim.builder.TobaccoProductBuilder; -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; -import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; -import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; import org.junit.Before; import java.math.BigDecimal; import static java.math.BigDecimal.ZERO; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.DISCOUNT; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.ILLICIT; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.IMPORTED; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.POPULAR; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.PREMIUM; public class TetsimOutputBaseCalculatorTest { - protected TobaccoProduct tobaccoProductImported; - - protected TobaccoProduct tobaccoProductPremium; - - protected TobaccoProduct tobaccoProductPopular; - - protected TobaccoProduct tobaccoProductDiscount; - - protected TobaccoProduct tobaccoProductIllicit; - protected TetsimDataset datasetWithAllTobaccoProducts; double delta = 0.01; @Before public void setUp() { - this.tobaccoProductImported = createTobaccoProduct("Imported", false); - this.tobaccoProductPremium = createTobaccoProduct("Premium", false); - this.tobaccoProductPopular = createTobaccoProduct("Popular", false); - this.tobaccoProductDiscount = createTobaccoProduct("Discount", false); - this.tobaccoProductIllicit = createTobaccoProduct("Illicit", true); - this.datasetWithAllTobaccoProducts = createTetsimDatasetWithAllTobaccoProducts(); } - protected TobaccoProduct createTobaccoProduct(String label, Boolean illicit) { - return new TobaccoProductBuilder() - .withLabel(label) - .withIllicit(illicit) - .build(); - } - protected TetsimDataset createTetsimDatasetWithAllTobaccoProducts() { return new TetsimDatasetBuilder() .withCigaretteConsumption(BigDecimal.valueOf(1150.0)) @@ -72,23 +53,23 @@ protected TetsimPriceVariable createPriceVariable(BigDecimal imported, BigDecima BigDecimal discount, BigDecimal illicit) { return new TetsimPriceVariableBuilder() .add(new TetsimTobaccoProductValueBuilder() - .withTobaccoProduct(tobaccoProductImported) + .withTobaccoProduct(IMPORTED) .withValue(imported) .build()) .add(new TetsimTobaccoProductValueBuilder() - .withTobaccoProduct(tobaccoProductPremium) + .withTobaccoProduct(PREMIUM) .withValue(premium) .build()) .add(new TetsimTobaccoProductValueBuilder() - .withTobaccoProduct(tobaccoProductPopular) + .withTobaccoProduct(POPULAR) .withValue(popular) .build()) .add(new TetsimTobaccoProductValueBuilder() - .withTobaccoProduct(tobaccoProductDiscount) + .withTobaccoProduct(DISCOUNT) .withValue(discount) .build()) .add(new TetsimTobaccoProductValueBuilder() - .withTobaccoProduct(tobaccoProductIllicit) + .withTobaccoProduct(ILLICIT) .withValue(illicit) .build()) .build(); diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorAbsChangeTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorAbsChangeTest.java index 6e246a26..cbcabb9c 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorAbsChangeTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorAbsChangeTest.java @@ -1,10 +1,16 @@ package org.devgateway.toolkit.persistence.tetsim; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputUndershiftCalculator; import org.junit.Before; import org.junit.Test; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.DISCOUNT; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.ILLICIT; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.IMPORTED; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.POPULAR; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.PREMIUM; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -18,21 +24,21 @@ public void setUp() { @Test public void testOvershiftAbsChangeBaseline() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Imported").doubleValue(), - delta, "Check Abs change overshift imported baseline"); - assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Premium").doubleValue(), + assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift(IMPORTED).doubleValue(), delta, "Check Abs change overshift imported baseline"); + assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift(PREMIUM).doubleValue(), + delta, "Check Abs change overshift premium baseline"); } @Test public void testOvershiftAbsChange() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); assertAll("TETSIM Overshift Abs Change", - () -> assertEquals(0.75, tetsimOutputCalculator.calculateAbsChangeShift("Popular").doubleValue(), + () -> assertEquals(0.75, tetsimOutputCalculator.calculateAbsChangeShift(POPULAR).doubleValue(), delta, "Check Abs change overshift popular"), - () -> assertEquals(0.38, tetsimOutputCalculator.calculateAbsChangeShift("Discount").doubleValue(), + () -> assertEquals(0.38, tetsimOutputCalculator.calculateAbsChangeShift(DISCOUNT).doubleValue(), delta, "Check Abs change overshift discount"), - () -> assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Illicit").doubleValue(), + () -> assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift(ILLICIT).doubleValue(), delta, "Check Abs change overshift illicit") ); } @@ -40,9 +46,9 @@ public void testOvershiftAbsChange() { @Test public void testUndershiftAbsChangeBaseline() { TetsimOutputUndershiftCalculator tetsimOutputCalculator = new TetsimOutputUndershiftCalculator(datasetWithAllTobaccoProducts, 0); - assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Imported").doubleValue(), + assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift(IMPORTED).doubleValue(), delta, "Check Abs change undershift imported baseline"); - assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Premium").doubleValue(), + assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift(PREMIUM).doubleValue(), delta, "Check Abs change undershift premium baseline"); } @@ -50,11 +56,11 @@ public void testUndershiftAbsChangeBaseline() { public void testUndershiftAbsChange() { TetsimOutputUndershiftCalculator tetsimOutputCalculator = new TetsimOutputUndershiftCalculator(datasetWithAllTobaccoProducts, 20); assertAll("TETSIM Undershift Abs Change", - () -> assertEquals(-1.13, tetsimOutputCalculator.calculateAbsChangeShift("Popular").doubleValue(), + () -> assertEquals(-1.13, tetsimOutputCalculator.calculateAbsChangeShift(POPULAR).doubleValue(), delta, "Check Abs change undershift popular"), - () -> assertEquals(-1.88, tetsimOutputCalculator.calculateAbsChangeShift("Discount").doubleValue(), + () -> assertEquals(-1.88, tetsimOutputCalculator.calculateAbsChangeShift(DISCOUNT).doubleValue(), delta, "Check Abs change undershift discount"), - () -> assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift("Illicit").doubleValue(), + () -> assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift(ILLICIT).doubleValue(), delta, "Check Abs change undershift illicit") ); } diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java index 1b939c07..32b60e54 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorBaselineNumbersTest.java @@ -1,10 +1,16 @@ package org.devgateway.toolkit.persistence.tetsim; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; import org.junit.Before; import org.junit.Test; import static java.math.BigDecimal.ROUND_HALF_UP; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.DISCOUNT; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.ILLICIT; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.IMPORTED; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.POPULAR; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.PREMIUM; import static org.junit.jupiter.api.Assertions.assertEquals; public class TetsimOutputCalculatorBaselineNumbersTest extends TetsimOutputBaseCalculatorTest { @@ -17,77 +23,77 @@ public void setUp() { @Test public void testBaselineNetOfTaxPrice() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - assertEquals(19.43, tetsimOutputCalculator.calculateBaselineNetTaxPrice("Imported") + assertEquals(19.43, tetsimOutputCalculator.calculateBaselineNetTaxPrice(IMPORTED) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Net of Tax for Imported Product"); } @Test public void testBaselineNetOfTaxPriceWithPercentageChange() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - assertEquals(16.00, tetsimOutputCalculator.calculateBaselineNetTaxPrice("Popular") + assertEquals(16.00, tetsimOutputCalculator.calculateBaselineNetTaxPrice(POPULAR) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Net of Tax for Popular Product with percentage change"); } @Test public void testBaselineIllicitNetOfTaxPriceWithPercentageChange() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - assertEquals(20.00, tetsimOutputCalculator.calculateBaselineNetTaxPrice("Illicit") + assertEquals(20.00, tetsimOutputCalculator.calculateBaselineNetTaxPrice(ILLICIT) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Net of Tax Price for Illicit Product with percentage change"); } @Test public void testBaselineIllicitRetailPrice() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - assertEquals(20.00, tetsimOutputCalculator.calculateBaselineRetailPrice("Illicit") + assertEquals(20.00, tetsimOutputCalculator.calculateBaselineRetailPrice(ILLICIT) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Retail Price for Illicit Product"); } @Test public void testBaselineRetailPriceWithPercentageChange() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - assertEquals(40.00, tetsimOutputCalculator.calculateBaselineRetailPrice("Popular") + assertEquals(40.00, tetsimOutputCalculator.calculateBaselineRetailPrice(POPULAR) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Retail Price for Popular Product with percentage change"); } @Test public void testBaselineIllicitExciseTaxOnDomestic() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - assertEquals(0, tetsimOutputCalculator.calculateBaselineExciseTaxOnDomesticProduction("Illicit") + assertEquals(0, tetsimOutputCalculator.calculateBaselineExciseTaxOnDomesticProduction(ILLICIT) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Excise Tax for Illicit Product"); } @Test public void testBaselineImportedExciseTaxOnDomestic() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - assertEquals(0, tetsimOutputCalculator.calculateBaselineExciseTaxOnDomesticProduction("Imported") + assertEquals(0, tetsimOutputCalculator.calculateBaselineExciseTaxOnDomesticProduction(IMPORTED) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Excise Tax for Imported Product"); } @Test public void testBaselinePopularExciseTaxOnDomestic() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - assertEquals(18.78, tetsimOutputCalculator.calculateBaselineExciseTaxOnDomesticProduction("Popular") + assertEquals(18.78, tetsimOutputCalculator.calculateBaselineExciseTaxOnDomesticProduction(POPULAR) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Excise Tax for Popular Product"); } @Test public void testBaselinePopularVAT() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - assertEquals(5.22, tetsimOutputCalculator.calculateBaselineVAT("Popular") + assertEquals(5.22, tetsimOutputCalculator.calculateBaselineVAT(POPULAR) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline VAT for Popular Product"); } @Test public void testBaselineDiscountExciseBurden() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - assertEquals(67.07, tetsimOutputCalculator.calculateBaselineExciseBurden("Discount") + assertEquals(67.07, tetsimOutputCalculator.calculateBaselineExciseBurden(DISCOUNT) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Excise Burden for Discount Product"); } @Test public void testBaselinePremiumTotalTaxBurden() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - assertEquals(52.17, tetsimOutputCalculator.calculateBaselineTotalTaxBurden("Premium") + assertEquals(52.17, tetsimOutputCalculator.calculateBaselineTotalTaxBurden(PREMIUM) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check baseline Total Tax Burden for Premium Product"); } diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java index 2133fc84..86bcf9d1 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorQuantityAndRevenueTest.java @@ -1,10 +1,14 @@ package org.devgateway.toolkit.persistence.tetsim; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; import org.junit.Before; import org.junit.Test; import static java.math.BigDecimal.ROUND_HALF_UP; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.ILLICIT; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.IMPORTED; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.POPULAR; import static org.junit.jupiter.api.Assertions.assertEquals; public class TetsimOutputCalculatorQuantityAndRevenueTest extends TetsimOutputBaseCalculatorTest { @@ -24,35 +28,35 @@ public void testBaselineTotalConsumption() { @Test public void testPreConsumption() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - assertEquals(54.9, tetsimOutputCalculator.calculatePreConsumption("Imported") + assertEquals(54.9, tetsimOutputCalculator.calculatePreConsumption(IMPORTED) .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Pre Consumption for Imported Tobacco Product"); } @Test public void testPreConsumptionIllicit() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - assertEquals(369.9, tetsimOutputCalculator.calculatePreConsumption("Illicit") + assertEquals(369.9, tetsimOutputCalculator.calculatePreConsumption(ILLICIT) .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Pre Consumption for Illicit Tobacco Product"); } @Test public void testGainFromPrice() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - assertEquals(17.8, tetsimOutputCalculator.calculateGainFromPrice("Illicit") + assertEquals(17.8, tetsimOutputCalculator.calculateGainFromPrice(ILLICIT) .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Gain From Price for Illicit Tobacco Product"); } @Test public void testConsumptionPopular() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - assertEquals(432.2, tetsimOutputCalculator.calculateConsumption("Popular") + assertEquals(432.2, tetsimOutputCalculator.calculateConsumption(POPULAR) .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption for Popular Tobacco Product"); } @Test public void testConsumptionIllicit() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - assertEquals(387.6, tetsimOutputCalculator.calculateConsumption("Illicit") + assertEquals(387.6, tetsimOutputCalculator.calculateConsumption(ILLICIT) .setScale(1, ROUND_HALF_UP).doubleValue(), "Check Consumption for Illicit Tobacco Product"); } diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java index 5416a561..ed13a469 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorNumbersTest.java @@ -5,6 +5,10 @@ import org.junit.Test; import static java.math.BigDecimal.ROUND_HALF_UP; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.ILLICIT; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.IMPORTED; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.POPULAR; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.PREMIUM; import static org.junit.jupiter.api.Assertions.assertEquals; public class TetsimOutputOvershiftCalculatorNumbersTest extends TetsimOutputBaseCalculatorTest { @@ -17,35 +21,35 @@ public void setUp() { @Test public void testPopularNetTaxPrice() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - assertEquals(16.75, tetsimOutputCalculator.calculateNetTaxPrice("Popular") + assertEquals(16.75, tetsimOutputCalculator.calculateNetTaxPrice(POPULAR) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift Net of Tax for Popular Product"); } @Test public void testIllicitNetTaxPrice() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - assertEquals(22.38, tetsimOutputCalculator.calculateNetTaxPrice("Illicit") + assertEquals(22.38, tetsimOutputCalculator.calculateNetTaxPrice(ILLICIT) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift Net of Tax for Illicit Product"); } @Test public void testPopularExciseTaxOnDomesticProduction() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - assertEquals(22.54, tetsimOutputCalculator.calculateExciseTaxDomesticProduction("Popular") + assertEquals(22.54, tetsimOutputCalculator.calculateExciseTaxDomesticProduction(POPULAR) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift Excise Tax on domestic production for Popular Product"); } @Test public void testPremiumVat() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - assertEquals(6.99, tetsimOutputCalculator.calculateVat("Premium") + assertEquals(6.99, tetsimOutputCalculator.calculateVat(PREMIUM) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift VAT for Premium Product"); } @Test public void testImportedRetailPrice() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - assertEquals(50.62, tetsimOutputCalculator.calculateRetailPrice("Imported") + assertEquals(50.62, tetsimOutputCalculator.calculateRetailPrice(IMPORTED) .setScale(2, ROUND_HALF_UP).doubleValue(), "Check Overshift Retail Price for Imported Product"); } diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java index 287e3eb8..7aabf15e 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorOverallTest.java @@ -1,10 +1,12 @@ package org.devgateway.toolkit.persistence.tetsim; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import org.devgateway.toolkit.persistence.dto.TetsimOutput; import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; import org.junit.Before; import org.junit.Test; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.POPULAR; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -18,7 +20,7 @@ public void setUp() { @Test public void testOverallOutputBaseline() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertAll("TETSIM Overshift Baseline", () -> assertEquals(754.40, output.getLegalConsumption(), delta, "TETSIM Overshift - Consumption Legal"), @@ -39,7 +41,7 @@ public void testOverallOutputBaseline() { @Test public void testOverallOutputWithTaxChange() { TetsimOutputOvershiftCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 30); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertAll("TETSIM Overshift With 30% Tax Change", () -> assertEquals(648.79, output.getLegalConsumption(), delta, "TETSIM Overshift - Consumption Legal"), diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java index ecb72bf6..06d1111d 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputOvershiftCalculatorTest.java @@ -6,6 +6,7 @@ import org.junit.Before; import org.junit.Test; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.POPULAR; import static org.junit.jupiter.api.Assertions.assertEquals; public class TetsimOutputOvershiftCalculatorTest extends TetsimOutputBaseCalculatorTest { @@ -18,154 +19,161 @@ public void setUp() { @Test public void testConsumptionLegalNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(754.4, output.getLegalConsumption(), delta, "Check Consumption Legal TETSIM Output Overshift"); } @Test public void testConsumptionLegalWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(680.19, output.getLegalConsumption(), delta, "Check Consumption Legal TETSIM Output Overshift (Tax Change)"); } + @Test + public void testConsumptionLegalWithTaxChange1() { + TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 1); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); + assertEquals(750.27, output.getLegalConsumption(), delta, "Check Consumption Legal TETSIM Output Overshift (Tax Change)"); + } + @Test public void testConsumptionIllicitNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(395.6, output.getConsumptionIllicit(), delta, "Check Consumption Illicit TETSIM Output Overshift"); } @Test public void testConsumptionIllicitWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(387.62, output.getConsumptionIllicit(), delta, "Check Consumption Illicit TETSIM Output Overshift (Tax Change)"); } @Test public void testTotalExciseRevenueNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(14167.63, output.getExciseRev(), delta, "Check Total Legal Excise Revenue TETSIM Output Overshift"); } @Test public void testTotalExciseRevenueWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(15328.9, output.getExciseRev(), delta, "Check Total Legal Excise Revenue TETSIM Output Overshift (Tax Change)"); } @Test public void testTotalLegalGovRevenueNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(18051.37, output.getTotalGovRev(), delta, "Check Total Legal Government Revenue TETSIM Output Overshift"); } @Test public void testTotalLegalGovRevenueWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(19315.54, output.getTotalGovRev(), delta, "Check Total Legal Government Revenue TETSIM Output Overshift (Tax Change)"); } @Test public void testExciseBurdenNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(46.95, output.getExciseBurden(), delta, "Check Excise Burden TETSIM Output Overshift"); } @Test public void testExciseBurdenWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(49.87, output.getExciseBurden(), delta, "Check Excise Burden TETSIM Output Overshift (Tax Change)"); } @Test public void testTotalTaxBurdenNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(60.0, output.getTotalTaxBurden(), delta, "Check Total Tax Burden TETSIM Output Overshift"); } @Test public void testTotalTaxBurdenWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(62.92, output.getTotalTaxBurden(), delta, "Check Total Tax Burden TETSIM Output Overshift (Tax Change)"); } @Test public void testRetailPriceNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(40.0, output.getRetailPrice(), delta, "Check Retail Price TETSIM Output Overshift (Baseline)"); } @Test public void testRetailPriceWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(45.18, output.getRetailPrice(), delta, "Check Retail Price TETSIM Output Overshift (Tax Change)"); } @Test public void testNOTNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(16.0, output.getNot(), delta, "Check NOT TETSIM Output Overshift"); } @Test public void testNOTWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(16.75, output.getNot(), delta, "Check NOT TETSIM Output Overshift (Tax Change)"); } @Test public void testExciseTaxNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(18.78, output.getExciseTax(), delta, "Check Excise Tax TETSIM Output Overshift"); } @Test public void testExciseTaxWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(22.54, output.getExciseTax(), delta, "Check Excise Tax TETSIM Output Overshift (Tax Change)"); } @Test public void testVatNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(5.22, output.getVat(), delta, "Check VAT TETSIM Output Overshift"); } @Test public void testVatWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(5.89, output.getVat(), delta, "Check VAT TETSIM Output Overshift (Tax Change)"); } @Test public void testLevyNoTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(0.00, output.getLevy(), delta, "Check Levy TETSIM Output Overshift"); } @Test public void testLevyWithTaxChange() { TetsimOutputCalculator tetsimOutputCalculator = new TetsimOutputOvershiftCalculator(datasetWithAllTobaccoProducts, 20); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertEquals(0.00, output.getLevy(), delta, "Check Levy TETSIM Output Overshift (Tax Change)"); } diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java index e6f3632b..89aedf7b 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java @@ -1,10 +1,12 @@ package org.devgateway.toolkit.persistence.tetsim; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import org.devgateway.toolkit.persistence.dto.TetsimOutput; import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputUndershiftCalculator; import org.junit.Before; import org.junit.Test; +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.POPULAR; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -18,7 +20,7 @@ public void setUp() { @Test public void testOverallOutputBaseline() { TetsimOutputUndershiftCalculator tetsimOutputCalculator = new TetsimOutputUndershiftCalculator(datasetWithAllTobaccoProducts, 0); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertAll("TETSIM Undershift Baseline", () -> assertEquals(754.40, output.getLegalConsumption(), delta, "TETSIM Undershift - Consumption Legal"), @@ -39,7 +41,7 @@ public void testOverallOutputBaseline() { @Test public void testOverallOutputWithTaxChange() { TetsimOutputUndershiftCalculator tetsimOutputCalculator = new TetsimOutputUndershiftCalculator(datasetWithAllTobaccoProducts, 30); - TetsimOutput output = tetsimOutputCalculator.calculate("Popular"); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertAll("TETSIM Undershift With 30% Tax Change", () -> assertEquals(694.62, output.getLegalConsumption(), delta, "TETSIM Undershift - Consumption Legal"), diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TetsimTobaccoProductValueBuilder.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TetsimTobaccoProductValueBuilder.java index 994abe9f..a665da59 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TetsimTobaccoProductValueBuilder.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TetsimTobaccoProductValueBuilder.java @@ -1,7 +1,7 @@ package org.devgateway.toolkit.persistence.tetsim.builder; -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import java.math.BigDecimal; diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TobaccoProductBuilder.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TobaccoProductBuilder.java deleted file mode 100644 index 7032c666..00000000 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/builder/TobaccoProductBuilder.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.devgateway.toolkit.persistence.tetsim.builder; - -import org.devgateway.toolkit.persistence.dao.categories.TobaccoProduct; - -public class TobaccoProductBuilder { - - private TobaccoProduct product; - - public TobaccoProductBuilder() { - this.product = new TobaccoProduct(); - } - - public TobaccoProductBuilder withLabel(String label) { - this.product.setLabel(label); - return this; - } - - public TobaccoProductBuilder withIllicit(Boolean illicit) { - this.product.setIllicit(illicit); - return this; - } - - public TobaccoProduct build() { - return this.product; - } -} From 880ece17746e6c8b4df2b165619e4d1e67e8d67d Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 21 Oct 2022 16:52:26 +0300 Subject: [PATCH 096/137] TOBACCO-1069: Detect the tetsim service by name --- .../toolkit/forms/wicket/page/DataPage.java | 16 ++++++++-------- .../forms/wicket/page/DataServicePage.java | 13 +++++++------ .../util/tetsim/TetsimOutputBaseCalculator.java | 3 --- 3 files changed, 15 insertions(+), 17 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java index 56e244d1..3bd5c801 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java @@ -14,7 +14,6 @@ */ package org.devgateway.toolkit.forms.wicket.page; -import com.google.common.collect.ImmutableList; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.markup.html.basic.Label; @@ -28,8 +27,6 @@ import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; -import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListCSVDatasetPage; -import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; import org.devgateway.toolkit.persistence.dto.ServiceMetadata; import org.devgateway.toolkit.web.util.SettingsUtils; import org.wicketstuff.annotation.mount.MountPath; @@ -37,6 +34,9 @@ import java.util.ArrayList; import java.util.List; +import static org.devgateway.toolkit.forms.WebConstants.SERVICE_DATA_TYPE; +import static org.devgateway.toolkit.forms.WebConstants.SERVICE_TETSIM_TYPE; + /** * @author Viorel Chihai */ @@ -60,7 +60,7 @@ public DataPage(final PageParameters parameters) { PageParameters pageParameters = new PageParameters(); pageParameters.add("service", service.getName()); - FontAwesome5IconType serviceIcon = getServiceIcon(service.getType()); + FontAwesome5IconType serviceIcon = getServiceIcon(service); links.add(new BigLinkDefinition(service.getId(), DataServicePage.class, pageParameters, serviceIcon) { @@ -82,14 +82,14 @@ public IModel getDescModel() { add(noServiceError); } - private FontAwesome5IconType getServiceIcon(final String type) { - if (type.equals(WebConstants.SERVICE_TETSIM_TYPE)) { + private FontAwesome5IconType getServiceIcon(final ServiceMetadata serviceMetadata) { + if (serviceMetadata.getType().equals(SERVICE_TETSIM_TYPE) || serviceMetadata.getName().equalsIgnoreCase(SERVICE_TETSIM_TYPE)) { return FontAwesome5IconType.list_alt_r; - } else if (type.equals(WebConstants.SERVICE_DATA_TYPE)) { + } else if (serviceMetadata.getType().equals(SERVICE_DATA_TYPE)) { return FontAwesome5IconType.file_csv_s; } - throw new IllegalArgumentException("Unknown service type: " + type); + throw new IllegalArgumentException("Unknown service type: " + serviceMetadata.getType()); } protected Label getPageTitle() { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java index dcf2b251..047d4bfc 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java @@ -21,7 +21,6 @@ import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; -import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; @@ -42,6 +41,8 @@ import static de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType.layer_group_s; import static de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType.ruler_s; import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; +import static org.devgateway.toolkit.forms.WebConstants.SERVICE_DATA_TYPE; +import static org.devgateway.toolkit.forms.WebConstants.SERVICE_TETSIM_TYPE; /** * @author Viorel Chihai @@ -59,7 +60,7 @@ public DataServicePage(final PageParameters parameters) { ServiceMetadata serviceMetadata = eurekaClientService.findByName(parameters.get(PARAM_SERVICE).toString()); List links = new ArrayList<>(); - links.add(getEntityLink("datasets", getServicePageClass(serviceMetadata.getType()), database_s)); + links.add(getEntityLink("datasets", getServicePageClass(serviceMetadata), database_s)); links.add(getEntityLink("measures", ListServiceMeasuresPage.class, ruler_s)); links.add(getEntityLink("dimensions", ListServiceDimensionsPage.class, chart_bar_s)); links.add(getEntityLink("categories", ListServiceCategoriesPage.class, layer_group_s)); @@ -74,14 +75,14 @@ private BigLinkDefinition getEntityLink(final String entity, Class getServicePageClass(final String type) { - if (type.equals(WebConstants.SERVICE_TETSIM_TYPE)) { + private Class getServicePageClass(final ServiceMetadata serviceMetadata) { + if (serviceMetadata.getType().equals(SERVICE_TETSIM_TYPE) || serviceMetadata.getName().equalsIgnoreCase(SERVICE_TETSIM_TYPE)) { return ListTetsimDatasetPage.class; - } else if (type.equals(WebConstants.SERVICE_DATA_TYPE)) { + } else if (serviceMetadata.getType().equals(SERVICE_DATA_TYPE)) { return ListCSVDatasetPage.class; } - throw new IllegalArgumentException("Unknown service type: " + type); + throw new IllegalArgumentException("Unknown service type: " + serviceMetadata.getType()); } protected Label getPageTitle() { diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java index 6d3d9b23..a537a9bf 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java @@ -7,10 +7,7 @@ import java.math.BigDecimal; import java.math.MathContext; -import java.util.Arrays; -import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; From 8e981f4a013e6cfbf37ef2db489bbe2b7ad94a27 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Sat, 22 Oct 2022 10:06:42 +0300 Subject: [PATCH 097/137] TOBACCO-1065: Update csv list page --- .../forms/wicket/page/lists/dataset/ListCSVDatasetPage.java | 4 +++- .../wicket/page/lists/dataset/ListCSVDatasetPage.properties | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java index b25a0d30..151fb1dd 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java @@ -58,6 +58,8 @@ public ListCSVDatasetPage(final PageParameters pageParameters) { columns.clear(); columns.add(new PropertyColumn<>(new StringResourceModel("year"), "year", "year")); + columns.add(new PropertyColumn<>(new StringResourceModel("status"), "status", "status")); + columns.add(new PropertyColumn<>(new StringResourceModel("description"), "description", "description")); columns.add(new PropertyColumn<>(new StringResourceModel("lastModifiedBy"), "lastModifiedBy", "lastModifiedBy.get")); columns.add(new PropertyColumn(new StringResourceModel("lastModifiedDate"), @@ -71,7 +73,7 @@ public IModel getDataModel(final IModel rowModel) { return Model.of(modifiedDate.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"))); } }); - columns.add(new PropertyColumn<>(new StringResourceModel("status"), "status", "status")); + filterState = new CSVDatasetFilterState(); filterState.setService(service); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties index ed13b069..7feb1946 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties @@ -3,6 +3,7 @@ year=Year lastModifiedBy=Editor lastModifiedDate=Latest Modification status=Status +description=Dataset Description actionsColumn=Action new=Add new dataset \ No newline at end of file From c33ff47e7c6f85efadfde354fac33fa45cee6b61 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 26 Oct 2022 13:54:07 +0300 Subject: [PATCH 098/137] TOBACCO-1064: Update the configurations icon --- .../org/devgateway/toolkit/forms/wicket/page/BasePage.java | 6 +++--- .../org/devgateway/toolkit/forms/wicket/page/Homepage.java | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 40ebed25..be1dd7a0 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -244,7 +244,7 @@ protected NavbarButton newHomeMenu() { return homeMenu; } - protected NavbarDropDownButton newConifugrationsMenu() { + protected NavbarDropDownButton newConfigurationsMenu() { // admin menu NavbarDropDownButton configurationsMenu = new NavbarDropDownButton(new StringResourceModel("navbar.configurations", this, null)) { @@ -267,7 +267,7 @@ protected List newSubMenuButtons(final String arg0) { } }; - configurationsMenu.setIconType(FontAwesome5IconType.cog_s); + configurationsMenu.setIconType(FontAwesome5IconType.tools_s); MetaDataRoleAuthorizationStrategy.authorize(configurationsMenu, RENDER, ROLE_USER); return configurationsMenu; @@ -303,7 +303,7 @@ protected Navbar newNavbar(final String markupId) { navbar.setBrandImage(new PackageResourceReference(BaseStyles.class, "assets/img/tcdi-horizontal-logo.svg"), new StringResourceModel("brandImageAltText", this, null)); - navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.RIGHT, newHomeMenu(), newConifugrationsMenu(), + navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.RIGHT, newHomeMenu(), newConfigurationsMenu(), newDataMenu(), newAccountMenu(), newLogoutMenu())); // navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.RIGHT, newLanguageMenu())); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java index 891e021a..17704020 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java @@ -27,7 +27,7 @@ public class Homepage extends BasePage { protected SettingsUtils settingsUtils; private static final List LINKS = new ImmutableList.Builder() .add(new BigLinkDefinition("data", DataPage.class, FontAwesome5IconType.table_s)) - .add(new BigLinkDefinition("configurations", ConfigurationsHomepage.class, FontAwesome5IconType.cogs_s)) + .add(new BigLinkDefinition("configurations", ConfigurationsHomepage.class, FontAwesome5IconType.tools_s)) .build(); /** From beda4b51ed0c2adab4674c58bf9587a249aaadc0 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 28 Oct 2022 11:44:21 +0300 Subject: [PATCH 099/137] TOBACCO-1066: Update data entry form --- .../forms/service/DatasetClientService.java | 7 ++-- .../edit/AbstractEditStatusEntityPage.html | 7 +++- .../edit/AbstractEditStatusEntityPage.java | 38 ++++++++++++++----- .../AbstractEditStatusEntityPage.properties | 8 +--- .../toolkit/persistence/dao/DBConstants.java | 4 +- 5 files changed, 40 insertions(+), 24 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java index 46aa14e2..839fb613 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java @@ -20,13 +20,12 @@ import java.io.File; import java.io.IOException; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import static org.devgateway.toolkit.forms.client.ClientConstants.CODE_PREFIX; import static org.devgateway.toolkit.forms.client.ClientConstants.JobStatus.COMPLETED; import static org.devgateway.toolkit.forms.client.ClientConstants.JobStatus.ERROR; -import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.NOT_PUBLISHED; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.ERROR_IN_PUBLISHING; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; @@ -64,9 +63,9 @@ private void checkDatasetJobs(List datasets) { logger.info(String.format("The dataset with id %s changed the status from %s to %s", d.getId(), PUBLISHING, PUBLISHED)); } else if (ERROR.equals(status)) { - d.setStatus(NOT_PUBLISHED); + d.setStatus(ERROR_IN_PUBLISHING); logger.info(String.format("The dataset with id %s changed the status from %s to %s", - d.getId(), PUBLISHING, NOT_PUBLISHED)); + d.getId(), PUBLISHING, ERROR_IN_PUBLISHING)); } if (!PUBLISHING.equals(d.getStatus())) { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html index aa4fdff4..465470e4 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html @@ -3,6 +3,12 @@ +
+
+ ErrorInPublishing +
+
+
@@ -74,7 +80,6 @@ - diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index 22f05ff5..dc773fc6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -63,7 +63,7 @@ import static org.devgateway.toolkit.forms.WebConstants.PARAM_AUTO_SAVE; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DRAFT; -import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.NOT_PUBLISHED; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.ERROR_IN_PUBLISHING; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.SAVED; @@ -286,6 +286,8 @@ protected void onInitialize() { statusCommentsWrapper.add(statusComments); editForm.add(newStatusComment); + editForm.add(getErrorInPublishingLabel()); + entityButtonsFragment = new Fragment("extraButtons", "entityButtons", this); editForm.replace(entityButtonsFragment); @@ -326,6 +328,15 @@ protected void onInitialize() { enableDisableAutosaveFields(null); } + private Label getErrorInPublishingLabel() { + Label errorInPublishingLabel = new Label("errorInPublishing", + new StringResourceModel("errorInPublishing", this, null)); + errorInPublishingLabel.setOutputMarkupId(true); + errorInPublishingLabel.setOutputMarkupPlaceholderTag(true); + errorInPublishingLabel.setVisibilityAllowed(ERROR_IN_PUBLISHING.equals(editForm.getModelObject().getStatus())); + return errorInPublishingLabel; + } + @Override protected void afterSaveEntity(final T saveable) { super.afterSaveEntity(saveable); @@ -362,8 +373,6 @@ public boolean isDisableEditingEvent() { protected boolean isViewMode() { return false; -// return SecurityConstants.Action.VIEW -// .equals(permissionEntityRenderableService.getAllowedAccess(this, editForm.getModelObject())); } private void addCheckedOutTo() { @@ -477,7 +486,7 @@ private String getStatusLabelClass() { case PUBLISHED: return "label-success"; case DRAFT: - case NOT_PUBLISHED: + case ERROR_IN_PUBLISHING: return "label-danger"; case SAVED: return "label-primary"; @@ -771,7 +780,7 @@ protected void setButtonsPermissions() { addSaveButtonsPermissions(saveButton); addSaveButtonsPermissions(saveDraftContinueButton); addSaveButtonsPermissions(submitAndNext); - addSaveButtonsPermissions(saveSubmitButton); + addSaveSubmitButtonPermissions(saveSubmitButton); addSaveApproveButtonPermissions(saveApproveButton); addApproveButtonPermissions(approveButton); addSaveRevertButtonPermissions(revertToDraftPageButton); @@ -791,8 +800,9 @@ protected void setButtonsPermissions() { protected void addDeleteButtonPermissions(final Component button) { MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, SecurityConstants.Roles.ROLE_ADMIN); button.setVisibilityAllowed(entityId != null && !isViewMode() - && (!PUBLISHING.equals(editForm.getModelObject().getStatus()) - || !PUBLISHED.equals(editForm.getModelObject().getStatus()))); + && !(PUBLISHING.equals(editForm.getModelObject().getStatus()) + || ERROR_IN_PUBLISHING.equals(editForm.getModelObject().getStatus()) + || PUBLISHED.equals(editForm.getModelObject().getStatus()))); MetaDataRoleAuthorizationStrategy.authorize( button, Component.RENDER, getCommaCombinedRoles()); } @@ -802,7 +812,7 @@ protected void addSaveRevertButtonPermissions(final Component button) { MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, getValidatorRole()); MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, getCommaCombinedRoles()); button.setVisibilityAllowed(button.isVisibilityAllowed() - && (NOT_PUBLISHED.equals(editForm.getModelObject().getStatus()) + && (ERROR_IN_PUBLISHING.equals(editForm.getModelObject().getStatus()) || PUBLISHED.equals(editForm.getModelObject().getStatus()))); } @@ -820,16 +830,24 @@ protected void addApproveButtonPermissions(final Component button) { button, Component.RENDER, getValidatorRole()); button.setVisibilityAllowed(button.isVisibilityAllowed() && (SAVED.equals(editForm.getModelObject().getStatus()) - || NOT_PUBLISHED.equals(editForm.getModelObject().getStatus()))); + || ERROR_IN_PUBLISHING.equals(editForm.getModelObject().getStatus()))); } - protected void addSaveButtonsPermissions(final Component button) { + protected void addSaveSubmitButtonPermissions(final Component button) { addDefaultAllButtonsPermissions(button); MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, getCommaCombinedRoles()); button.setVisibilityAllowed(button.isVisibilityAllowed() && DRAFT.equals(editForm.getModelObject().getStatus())); } + protected void addSaveButtonsPermissions(final Component button) { + addDefaultAllButtonsPermissions(button); + MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, getCommaCombinedRoles()); + button.setVisibilityAllowed(button.isVisibilityAllowed() + && (DRAFT.equals(editForm.getModelObject().getStatus()) + || SAVED.equals(editForm.getModelObject().getStatus()))); + } + protected void addDefaultAllButtonsPermissions(final Component button) { MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, SecurityConstants.Roles.ROLE_ADMIN); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties index eb4bc9d7..16d425da 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties @@ -16,13 +16,7 @@ saveSubmit=Save saveApprove=Save and Publish submitAndNext=Save and Next saveContinue=Save Draft & Continue -newStatusComment.label=Update Comment -newStatusComment.help=Add a comment to describe this update during validation or data entry. This comment can be useful for other people editing or validating this form. \ - PLEASE NOTE, text entered here will be viewable by anyone with access to this page. -visibleStatusComments.label=View comments and form history autosave_message=Form is saving autoSaveLabelMessage=Form auto-saved less than {0,number} minutes ago. checkedOutToMessage=Checked out to user {0}. -removeLock.label=Force form check in -removeLock.help=This will check back in a form that has been checked out by another user. Use this only if you know \ - the user is no longer editing the form and you want to allow other users access to the form. +errorInPublishing=There was an error during publishing. Please check the data and try to republish it. If it doesn't work please contact the admin. diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java index ec73a100..2d203f99 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java @@ -26,9 +26,9 @@ public static final class Status { public static final String SAVED = "SAVED"; public static final String PUBLISHING = "PUBLISHING"; public static final String PUBLISHED = "PUBLISHED"; - public static final String NOT_PUBLISHED = "NOT_PUBLISHED"; + public static final String ERROR_IN_PUBLISHING = "ERROR_IN_PUBLISHING"; public static final String DELETED = "DELETED"; - public static final String[] ALL = {DRAFT, SAVED, PUBLISHING, PUBLISHED, NOT_PUBLISHED}; + public static final String[] ALL = {DRAFT, SAVED, PUBLISHING, PUBLISHED, ERROR_IN_PUBLISHING}; public static final List ALL_LIST = Collections.unmodifiableList(Arrays.asList(ALL)); } From 859b967e617ca45b3dd4138b7593e1728f171047 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 28 Oct 2022 12:21:49 +0300 Subject: [PATCH 100/137] TOBACCO-1068: Update measures page --- .../edit/admin/EditServiceMeasurePage.html | 8 ------ .../edit/admin/EditServiceMeasurePage.java | 27 +++++-------------- .../admin/EditServiceMeasurePage.properties | 10 +++---- .../lists/admin/ListServiceMeasuresPage.java | 4 +-- 4 files changed, 11 insertions(+), 38 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html index 6a20430d..e1bc98af 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html @@ -11,16 +11,8 @@
-
-
-
-
-
-
-
-
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java index 1114a26f..3219f118 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java @@ -28,37 +28,22 @@ public EditServiceMeasurePage(final PageParameters parameters) { protected void onInitialize() { super.onInitialize(); - final TextFieldBootstrapFormComponent code = new TextFieldBootstrapFormComponent<>("code"); - code.setEnabled(false); - editForm.add(code); - - final TextFieldBootstrapFormComponent value = new TextFieldBootstrapFormComponent<>("value"); - value.getField().setRequired(true); + final TextFieldBootstrapFormComponent value = new TextFieldBootstrapFormComponent<>("code"); + value.setEnabled(false); editForm.add(value); + final TextFieldBootstrapFormComponent label = new TextFieldBootstrapFormComponent<>("value"); + label.getField().setRequired(true); + editForm.add(label); + final TextFieldBootstrapFormComponent position = new TextFieldBootstrapFormComponent<>("position"); position.getField().setRequired(true); editForm.add(position); - final TextFieldBootstrapFormComponent expression = new TextFieldBootstrapFormComponent<>("expression"); - expression.setEnabled(false); - editForm.add(expression); - ColorPickerBootstrapFormComponent colorPicker = new ColorPickerBootstrapFormComponent("color", new PropertyModel<>(editForm.getModelObject(), "categoryStyle.color")); editForm.add(colorPicker); - final TextFieldBootstrapFormComponent className = new TextFieldBootstrapFormComponent<>("className", - new PropertyModel<>(editForm.getModelObject(), "categoryStyle.className")); - editForm.add(className); - - ColorPickerBootstrapFormComponent textColorPicker = new ColorPickerBootstrapFormComponent("textColor", - new PropertyModel<>(editForm.getModelObject(), "categoryStyle.textColor")); - editForm.add(textColorPicker); - - ColorPickerBootstrapFormComponent bckColorPicker = new ColorPickerBootstrapFormComponent("backgroundColor", - new PropertyModel<>(editForm.getModelObject(), "categoryStyle.backgroundColor")); - editForm.add(bckColorPicker); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties index 6f5227df..15e64415 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties @@ -12,11 +12,7 @@ page.title=Edit {0} Measure page.title.add=Add {0} Measure page.title.edit=Edit {0} Measure -code.label=Code -value.label=Value +code.label=Value +value.label=Label position.label=Position -expression.label=Expression -color.label=Color -className.label=CSS Class Name -textColor.label=Text Color -backgroundColor.label=Background Color \ No newline at end of file +color.label=Color in graphic \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java index 0b260742..d5f17903 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java @@ -46,8 +46,8 @@ public ListServiceMeasuresPage(final PageParameters pageParameters) { this.editPageClass = EditServiceMeasurePage.class; columns = new ArrayList<>(); - columns.add(new PropertyColumn<>(new Model<>("Code"), "code", "code")); - columns.add(new PropertyColumn<>(new Model<>("Value"), "value", "value")); + columns.add(new PropertyColumn<>(new Model<>("Value"), "code", "code")); + columns.add(new PropertyColumn<>(new Model<>("Label"), "value", "value")); columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); columns.add(new PropertyColumn(new Model<>("Color"), "categoryStyle.color", "categoryStyle.color") { From c3053f8e7f9553b8d1fecd095267d3c5d9308a3a Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 28 Oct 2022 12:59:07 +0300 Subject: [PATCH 101/137] TOBACCO-1078: Update dimensions page --- .../page/edit/admin/EditServiceDimensionPage.properties | 4 ++-- .../wicket/page/lists/admin/ListServiceDimensionsPage.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties index 07e531c8..5caa1243 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties @@ -12,6 +12,6 @@ page.title=Edit {0} Dimension page.title.add=Add {0} Dimension page.title.edit=Edit {0} Dimension -code.label=Code -value.label=Value +code.label=Value +value.label=Label position.label=Position \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java index 3640aabd..14d64146 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java @@ -45,8 +45,8 @@ public ListServiceDimensionsPage(final PageParameters pageParameters) { dataProvider = new ServiceDimensionProvider(serviceDimensionService, service); columns = new ArrayList<>(); - columns.add(new PropertyColumn<>(new Model<>("Code"), "code", "code")); - columns.add(new PropertyColumn<>(new Model<>("Value"), "value", "value")); + columns.add(new PropertyColumn<>(new Model<>("Value"), "code", "code")); + columns.add(new PropertyColumn<>(new Model<>("Label"), "value", "value")); columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); } From 5202f89eb9476f92b3492c7be8e4019540be5b50 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 28 Oct 2022 13:07:58 +0300 Subject: [PATCH 102/137] TOBACCO-1079: Update categories page --- .../edit/admin/EditServiceCategoryPage.html | 11 ++------ .../edit/admin/EditServiceCategoryPage.java | 28 ++++++------------- .../admin/EditServiceCategoryPage.properties | 17 +++++------ .../edit/admin/EditServiceMeasurePage.html | 2 +- .../admin/ListServiceCategoriesPage.java | 4 +-- 5 files changed, 21 insertions(+), 41 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.html index ebe7c3ce..6d2cdb01 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.html @@ -2,9 +2,6 @@ -
-
-
@@ -12,15 +9,13 @@
-
+
-
-
+
-
-
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java index 317c9eb7..1d2967b9 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java @@ -29,18 +29,18 @@ public EditServiceCategoryPage(final PageParameters parameters) { protected void onInitialize() { super.onInitialize(); + final TextFieldBootstrapFormComponent value = new TextFieldBootstrapFormComponent<>("code"); + value.setEnabled(false); + editForm.add(value); + + final TextFieldBootstrapFormComponent label = new TextFieldBootstrapFormComponent<>("value"); + label.getField().setRequired(true); + editForm.add(label); + final TextFieldBootstrapFormComponent type = new TextFieldBootstrapFormComponent<>("type"); type.setEnabled(false); editForm.add(type); - final TextFieldBootstrapFormComponent code = new TextFieldBootstrapFormComponent<>("code"); - code.setEnabled(false); - editForm.add(code); - - final TextFieldBootstrapFormComponent value = new TextFieldBootstrapFormComponent<>("value"); - value.getField().setRequired(true); - editForm.add(value); - final TextFieldBootstrapFormComponent position = new TextFieldBootstrapFormComponent<>("position"); position.getField().setRequired(true); editForm.add(position); @@ -48,18 +48,6 @@ protected void onInitialize() { ColorPickerBootstrapFormComponent colorPicker = new ColorPickerBootstrapFormComponent("color", new PropertyModel<>(editForm.getModelObject(), "categoryStyle.color")); editForm.add(colorPicker); - - final TextFieldBootstrapFormComponent className = new TextFieldBootstrapFormComponent<>("className", - new PropertyModel<>(editForm.getModelObject(), "categoryStyle.className")); - editForm.add(className); - - ColorPickerBootstrapFormComponent textColorPicker = new ColorPickerBootstrapFormComponent("textColor", - new PropertyModel<>(editForm.getModelObject(), "categoryStyle.textColor")); - editForm.add(textColorPicker); - - ColorPickerBootstrapFormComponent bckColorPicker = new ColorPickerBootstrapFormComponent("backgroundColor", - new PropertyModel<>(editForm.getModelObject(), "categoryStyle.backgroundColor")); - editForm.add(bckColorPicker); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties index 5d30c46e..6d6c8100 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties @@ -9,14 +9,11 @@ # Contributors: # Development Gateway - initial API and implementation ############################################################################### -page.title=Edit {0} Measure -page.title.add=Add {0} Measure -page.title.edit=Edit {0} Measure -code.label=Code -value.label=Value +page.title=Edit {0} Category +page.title.add=Add {0} Category +page.title.edit=Edit {0} Category +code.label=Value +value.label=Label position.label=Position -color.label=Color -className.label=CSS Class Name -textColor.label=Text Color -backgroundColor.label=Background Color -type.label=Type \ No newline at end of file +type.label=Type +color.label=Color in graphic \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html index e1bc98af..4629be05 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html @@ -12,7 +12,7 @@
-
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java index 98593598..2393b922 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java @@ -51,9 +51,9 @@ public ListServiceCategoriesPage(final PageParameters pageParameters) { dataProvider = new ServiceCategoryProvider(serviceCategoryService, service); columns = new ArrayList<>(); + columns.add(new PropertyColumn<>(new Model<>("Value"), "code", "code")); + columns.add(new PropertyColumn<>(new Model<>("Label"), "value", "value")); columns.add(new PropertyColumn<>(new Model<>("Type"), "type", "type")); - columns.add(new PropertyColumn<>(new Model<>("Code"), "code", "code")); - columns.add(new PropertyColumn<>(new Model<>("Value"), "value", "value")); columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); columns.add(new PropertyColumn(new Model<>("Color"), "categoryStyle.color", "categoryStyle.color") { From 3862cde03b82ee8a4f358fce4a868b7646fbe43f Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 28 Oct 2022 13:50:03 +0300 Subject: [PATCH 103/137] TOBACCO-1021: Update labels in form --- .../validators/UniqueLanguageTranslationValidator.java | 2 +- .../page/edit/admin/EditServiceCategoryPage.properties | 2 +- .../page/edit/admin/EditServiceMeasurePage.properties | 2 +- .../panel/ListViewTextTranslationSectionPanel.html | 3 ++- .../panel/ListViewTextTranslationSectionPanel.java | 5 +++-- .../ListViewTextTranslationSectionPanel.properties | 5 +++-- .../toolkit/forms/wicket/styles/BaseStyles.css | 10 ++++++++++ 7 files changed, 21 insertions(+), 8 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueLanguageTranslationValidator.java b/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueLanguageTranslationValidator.java index bd650695..0442b788 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueLanguageTranslationValidator.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/validators/UniqueLanguageTranslationValidator.java @@ -20,7 +20,7 @@ public void validate(final Form form) { ServiceCategory serviceCategory = (ServiceCategory) form.getModelObject(); serviceCategory.getLabels().stream() .filter(label -> label.getLanguage() != null) - .collect(Collectors.groupingBy(ServiceTextTranslation::getLanguage)) + .collect(Collectors.groupingBy(s -> s.getLanguage().toUpperCase())) .entrySet().stream() .filter(entry -> entry.getValue().size() > 1) .forEach(entry -> { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties index aa826232..208eb123 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties @@ -17,4 +17,4 @@ value.label=Label position.label=Position type.label=Type color.label=Color in graphic -labels.label=Labels \ No newline at end of file +labels.label=Label Translations \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties index 0fa5b2ae..65d35251 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties @@ -16,4 +16,4 @@ code.label=Value value.label=Label position.label=Position color.label=Color in graphic -labels.label=Labels \ No newline at end of file +labels.label=Label Translations \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.html index e99fa653..a8163c55 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.html @@ -7,7 +7,8 @@
-

[[title]]

+

[[title]]

+
(Please use the Wordpress Language Local Code - for example FR for French.)
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.java index f8049653..747dc838 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.java @@ -128,8 +128,9 @@ public ServiceTextTranslation createNewChild(IModel parentModel } public void populateCompoundListItem(ListItem item) { - final TextFieldBootstrapFormComponent header = ComponentUtil.addTextField(item, "language"); - header.required(); + final TextFieldBootstrapFormComponent language = ComponentUtil.addTextField(item, "language"); + language.setShowTooltip(true); + language.required(); final TextFieldBootstrapFormComponent value = ComponentUtil.addTextField(item, "text"); value.required(); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.properties index 8c90b370..3fa6ed59 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/panel/ListViewTextTranslationSectionPanel.properties @@ -1,4 +1,5 @@ -newButton=New Item -removeButton=Remove Entry +newButton=New Translation +removeButton=Remove Translation language.label=Language +language.help=Please use the Wordpress Language Local Code - for example FR for French. text.label=Text diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css index 8e17a0bb..9742e9ee 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css @@ -310,4 +310,14 @@ button .btn-home-label { .pull-down { position: absolute; bottom: 0; +} + +.label-translation-margin { + margin-right: 5px; +} + +.label-translation-description { + margin-top: 10px; + margin-bottom: 10px; + font-style: italic; } \ No newline at end of file From 86ee0058b889496909d0e1865f0f470041cde0a1 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Tue, 1 Nov 2022 19:11:52 +0200 Subject: [PATCH 104/137] TOBACCO-1082: Add country name to data service page --- .../toolkit/forms/wicket/page/DataServicePage.java | 11 ++++++++++- .../forms/wicket/page/DataServicePage.properties | 2 +- .../page/edit/AbstractEditStatusEntityPage.html | 6 ++---- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java index 047d4bfc..73ab37b2 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java @@ -31,8 +31,10 @@ import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListCSVDatasetPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; import org.devgateway.toolkit.persistence.dto.ServiceMetadata; +import org.devgateway.toolkit.web.util.SettingsUtils; import org.wicketstuff.annotation.mount.MountPath; +import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; @@ -51,6 +53,9 @@ @MountPath public class DataServicePage extends BasePage { + @SpringBean + protected SettingsUtils settingsUtils; + @SpringBean private EurekaClientService eurekaClientService; @@ -87,7 +92,11 @@ private Class getServicePageClass(final ServiceMetadata serv protected Label getPageTitle() { String service = getPageParameters().get("service").toString(); - return new Label("pageTitle", Model.of(service)); + String countryName = settingsUtils.getSetting().getCountryName(); + + return new Label("pageTitle", + Model.of(MessageFormat.format(getString("page.title"), countryName, service))); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties index 47f6d542..95e9e29a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties @@ -1,4 +1,4 @@ -page.title=${serviceName} +page.title={0} {1} datasets.label=Data entry or upload datasets.desc=Manage datasets diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html index 465470e4..7e6f6c7f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html @@ -4,9 +4,7 @@
-
- ErrorInPublishing -
+ ErrorInPublishing
@@ -15,7 +13,7 @@

-
+
From 2966bc1bb57ab7acc2d8235c5fa118be5a118a77 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Tue, 1 Nov 2022 19:29:34 +0200 Subject: [PATCH 105/137] TOBACCO-1084: Replace Label with System Label --- .../wicket/page/edit/admin/EditServiceCategoryPage.properties | 2 +- .../wicket/page/edit/admin/EditServiceDimensionPage.properties | 2 +- .../wicket/page/edit/admin/EditServiceMeasurePage.properties | 2 +- .../page/edit/category/AbstractCategoryEditPage.properties | 2 +- .../wicket/page/lists/admin/ListServiceCategoriesPage.java | 2 +- .../wicket/page/lists/admin/ListServiceDimensionsPage.java | 2 +- .../forms/wicket/page/lists/admin/ListServiceMeasuresPage.java | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties index 208eb123..5500cc95 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties @@ -13,7 +13,7 @@ page.title=Edit {0} Category page.title.add=Add {0} Category page.title.edit=Edit {0} Category code.label=Value -value.label=Label +value.label=System Label position.label=Position type.label=Type color.label=Color in graphic diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties index 952de06e..4ed66b55 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties @@ -13,6 +13,6 @@ page.title=Edit {0} Dimension page.title.add=Add {0} Dimension page.title.edit=Edit {0} Dimension code.label=Value -value.label=Label +value.label=System Label position.label=Position labels.label=Labels \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties index 65d35251..70ba7e9a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties @@ -13,7 +13,7 @@ page.title=Edit {0} Measure page.title.add=Add {0} Measure page.title.edit=Edit {0} Measure code.label=Value -value.label=Label +value.label=System Label position.label=Position color.label=Color in graphic labels.label=Label Translations \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/AbstractCategoryEditPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/AbstractCategoryEditPage.properties index a8303a9b..ed39bbbb 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/AbstractCategoryEditPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/category/AbstractCategoryEditPage.properties @@ -10,4 +10,4 @@ # Development Gateway - initial API and implementation ############################################################################### page.title=Edit Category -label.label=Label \ No newline at end of file +label.label=System Label \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java index 2393b922..937f746d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java @@ -52,7 +52,7 @@ public ListServiceCategoriesPage(final PageParameters pageParameters) { columns = new ArrayList<>(); columns.add(new PropertyColumn<>(new Model<>("Value"), "code", "code")); - columns.add(new PropertyColumn<>(new Model<>("Label"), "value", "value")); + columns.add(new PropertyColumn<>(new Model<>("System Label"), "value", "value")); columns.add(new PropertyColumn<>(new Model<>("Type"), "type", "type")); columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); columns.add(new PropertyColumn(new Model<>("Color"), "categoryStyle.color", diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java index 14d64146..a0f1442c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java @@ -46,7 +46,7 @@ public ListServiceDimensionsPage(final PageParameters pageParameters) { columns = new ArrayList<>(); columns.add(new PropertyColumn<>(new Model<>("Value"), "code", "code")); - columns.add(new PropertyColumn<>(new Model<>("Label"), "value", "value")); + columns.add(new PropertyColumn<>(new Model<>("System Label"), "value", "value")); columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java index d5f17903..57638f4f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java @@ -47,7 +47,7 @@ public ListServiceMeasuresPage(final PageParameters pageParameters) { columns = new ArrayList<>(); columns.add(new PropertyColumn<>(new Model<>("Value"), "code", "code")); - columns.add(new PropertyColumn<>(new Model<>("Label"), "value", "value")); + columns.add(new PropertyColumn<>(new Model<>("System Label"), "value", "value")); columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); columns.add(new PropertyColumn(new Model<>("Color"), "categoryStyle.color", "categoryStyle.color") { From 0ee07dcc19f1656bdce09bddfe48644b62cb6c5c Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 3 Nov 2022 17:51:35 +0200 Subject: [PATCH 106/137] TOBACCO-1083: Add filters page --- .../toolkit/forms/client/ClientConstants.java | 2 + .../forms/client/ServiceFilterClient.java | 29 ++++++++++++ .../service/admin/ServiceFilterService.java | 6 +++ .../admin/ServiceFilterServiceImpl.java | 25 ++++++++++ .../forms/wicket/page/DataServicePage.java | 3 ++ .../wicket/page/DataServicePage.properties | 5 +- .../edit/admin/EditServiceFilterPage.html | 25 ++++++++++ .../edit/admin/EditServiceFilterPage.java | 46 +++++++++++++++++++ .../admin/EditServiceFilterPage.properties | 18 ++++++++ .../lists/admin/ListServiceFiltersPage.java | 41 +++++++++++++++++ .../admin/ListServiceFiltersPage.properties | 1 + .../lists/admin/ServiceFilterProvider.java | 34 ++++++++++++++ .../persistence/dto/ServiceFilter.java | 17 +++++++ 13 files changed, 251 insertions(+), 1 deletion(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceFilterClient.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceFilterService.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceFilterServiceImpl.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceFilterProvider.java create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceFilter.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java index 536a0e11..7cf30f2b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java @@ -17,6 +17,8 @@ public static final class JobStatus { public static final String PATH_CATEGORIES = "/admin/categories"; + public final static String PATH_FILTERS = "/admin/filters"; + public final static String PATH_CODE = "/code"; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceFilterClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceFilterClient.java new file mode 100644 index 00000000..1c2e0e43 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceFilterClient.java @@ -0,0 +1,29 @@ +package org.devgateway.toolkit.forms.client; + +import org.devgateway.toolkit.persistence.dto.ServiceFilter; + +import javax.ws.rs.core.GenericType; +import java.util.List; + +public class ServiceFilterClient extends ServiceEntityClient { + + public ServiceFilterClient(final String baseUrl) { + super(baseUrl); + } + + @Override + public String getEntitiesPath() { + return ClientConstants.PATH_FILTERS; + } + + @Override + protected GenericType getGenericType() { + return new GenericType() {}; + } + + @Override + protected GenericType> getGenericListType() { + return new GenericType>() {}; + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceFilterService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceFilterService.java new file mode 100644 index 00000000..24152e9f --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceFilterService.java @@ -0,0 +1,6 @@ +package org.devgateway.toolkit.forms.service.admin; + +import org.devgateway.toolkit.persistence.dto.ServiceFilter; + +public interface ServiceFilterService extends BaseServiceEntityService { +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceFilterServiceImpl.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceFilterServiceImpl.java new file mode 100644 index 00000000..372afac5 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceFilterServiceImpl.java @@ -0,0 +1,25 @@ +package org.devgateway.toolkit.forms.service.admin; + +import org.devgateway.toolkit.forms.client.ServiceEntityClient; +import org.devgateway.toolkit.forms.client.ServiceFilterClient; +import org.devgateway.toolkit.forms.service.EurekaClientService; +import org.devgateway.toolkit.persistence.dto.ServiceFilter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ServiceFilterServiceImpl extends BaseServiceEntityServiceImpl implements ServiceFilterService { + + @Autowired + private EurekaClientService eurekaClientService; + + @Override + public ServiceFilter newInstance() { + return new ServiceFilter(); + } + + @Override + protected ServiceEntityClient serviceEntityClient(final String serviceName) { + return new ServiceFilterClient(eurekaClientService.findByName(serviceName).getUrl()); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java index 73ab37b2..c6130d4b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java @@ -27,6 +27,7 @@ import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceCategoriesPage; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceDimensionsPage; +import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceFiltersPage; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceMeasuresPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListCSVDatasetPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; @@ -40,6 +41,7 @@ import static de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType.chart_bar_s; import static de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType.database_s; +import static de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType.filter_s; import static de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType.layer_group_s; import static de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType.ruler_s; import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; @@ -69,6 +71,7 @@ public DataServicePage(final PageParameters parameters) { links.add(getEntityLink("measures", ListServiceMeasuresPage.class, ruler_s)); links.add(getEntityLink("dimensions", ListServiceDimensionsPage.class, chart_bar_s)); links.add(getEntityLink("categories", ListServiceCategoriesPage.class, layer_group_s)); + links.add(getEntityLink("filters", ListServiceFiltersPage.class, filter_s)); add(new BigLinksPanel("links", Model.ofList(links))); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties index 95e9e29a..c154f2d7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties @@ -10,4 +10,7 @@ dimensions.label=Dimensions dimensions.desc=Manage dimensions categories.label=Categories -categories.desc=Manage categories \ No newline at end of file +categories.desc=Manage categories + +filters.label=Filters +filters.desc=Manage filters \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.html new file mode 100644 index 00000000..f259b5b8 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.html @@ -0,0 +1,25 @@ + + + + +
+
+
+
+
+
+
+
+
+ +
+
+
+ +
+
+
+ + + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.java new file mode 100644 index 00000000..6c9fbd5d --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.java @@ -0,0 +1,46 @@ +package org.devgateway.toolkit.forms.wicket.page.edit.admin; + +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.service.admin.ServiceFilterService; +import org.devgateway.toolkit.forms.validators.UniqueLanguageTranslationValidator; +import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.page.edit.admin.panel.ListViewTextTranslationSectionPanel; +import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceFiltersPage; +import org.devgateway.toolkit.persistence.dto.ServiceFilter; +import org.wicketstuff.annotation.mount.MountPath; + +@MountPath(value = "/editServiceFilter") +public class EditServiceFilterPage extends AbstractEditServiceEntityPage { + private static final long serialVersionUID = -8409084805556720923L; + + @SpringBean + private ServiceFilterService serviceFilterService; + + public EditServiceFilterPage(final PageParameters parameters) { + super(parameters); + this.listPageClass = ListServiceFiltersPage.class; + this.entityService = serviceFilterService; + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + final TextFieldBootstrapFormComponent code = new TextFieldBootstrapFormComponent<>("code"); + code.setEnabled(false); + editForm.add(code); + + final TextFieldBootstrapFormComponent value = new TextFieldBootstrapFormComponent<>("value"); + value.getField().setRequired(true); + editForm.add(value); + + final TextFieldBootstrapFormComponent fieldType = new TextFieldBootstrapFormComponent<>("fieldType"); + fieldType.setEnabled(false); + editForm.add(fieldType); + + editForm.add(new ListViewTextTranslationSectionPanel("labels")); + editForm.add(new UniqueLanguageTranslationValidator()); + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.properties new file mode 100644 index 00000000..d700d798 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.properties @@ -0,0 +1,18 @@ +############################################################################### +# Copyright (c) 2015 Development Gateway, Inc and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the MIT License (MIT) +# which accompanies this distribution, and is available at +# https://opensource.org/licenses/MIT +# +# Contributors: +# Development Gateway - initial API and implementation +############################################################################### +page.title=Edit {0} Filter +page.title.add=Add {0} Filter +page.title.edit=Edit {0} Filter +code.label=Value +value.label=System Label +fieldType.label=Type +labels.label=Labels \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java new file mode 100644 index 00000000..99d1e183 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java @@ -0,0 +1,41 @@ +package org.devgateway.toolkit.forms.wicket.page.lists.admin; + +import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.WebConstants; +import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.service.admin.ServiceFilterService; +import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServiceFilterPage; +import org.devgateway.toolkit.persistence.dto.ServiceFilter; +import org.wicketstuff.annotation.mount.MountPath; + +import java.util.ArrayList; + +@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) +@MountPath(value = "/filters") +public class ListServiceFiltersPage extends AbstractListServiceEntityPage { + + private static final long serialVersionUID = -6619848875255960857L; + + @SpringBean + private ServiceFilterService serviceFilterService; + + public ListServiceFiltersPage(final PageParameters pageParameters) { + super(pageParameters); + + this.serviceEntityService = serviceFilterService; + this.editPageClass = EditServiceFilterPage.class; + + String service = pageParameters.get(WebConstants.PARAM_SERVICE).toString(); + dataProvider = new ServiceFilterProvider(serviceFilterService, service); + + columns = new ArrayList<>(); + columns.add(new PropertyColumn<>(new Model<>("Value"), "code", "code")); + columns.add(new PropertyColumn<>(new Model<>("System Label"), "value", "value")); + columns.add(new PropertyColumn<>(new Model<>("Type"), "fieldType", "fieldType")); + } + +} \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.properties new file mode 100644 index 00000000..5fc86658 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.properties @@ -0,0 +1 @@ +page.title={0} Filters \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceFilterProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceFilterProvider.java new file mode 100644 index 00000000..dcc53085 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceFilterProvider.java @@ -0,0 +1,34 @@ +package org.devgateway.toolkit.forms.wicket.page.lists.admin; + +import org.devgateway.toolkit.forms.service.admin.BaseServiceEntityService; +import org.devgateway.toolkit.persistence.dto.ServiceDimension; +import org.devgateway.toolkit.persistence.dto.ServiceFilter; + +import java.util.Comparator; + +/** + * Data provider used to provide information about the services + * + * @author Viorel Chihai + */ +public class ServiceFilterProvider extends SortableServiceEntityProvider { + private static final long serialVersionUID = 3067952110482080616L; + + public ServiceFilterProvider(final BaseServiceEntityService serviceEntityService, + final String serviceName) { + super(serviceEntityService, serviceName); + } + + @Override + protected Comparator getServiceEntityComparator() { + return new ServiceFilterComparator(); + } + + protected class ServiceFilterComparator implements Comparator { + @Override + public int compare(final ServiceFilter s1, final ServiceFilter s2) { + return String.CASE_INSENSITIVE_ORDER.compare(s1.getCode(), s2.getCode()); + } + } + +} \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceFilter.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceFilter.java new file mode 100644 index 00000000..1dafd366 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceFilter.java @@ -0,0 +1,17 @@ +package org.devgateway.toolkit.persistence.dto; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServiceFilter extends ServiceCategory { + + private String fieldType; + + public String getFieldType() { + return fieldType; + } + + public void setFieldType(final String fieldType) { + this.fieldType = fieldType; + } +} From f8c3b665e0b245b97bd7d48ba91fe8ccd5ef4375 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 7 Nov 2022 14:00:30 +0200 Subject: [PATCH 107/137] TOBACCO-1067: Update csv upload page --- .../wicket/page/edit/AbstractEditPage.java | 4 +- .../edit/AbstractEditStatusEntityPage.html | 6 ++- .../edit/AbstractEditStatusEntityPage.java | 37 ++++++++++--------- .../AbstractEditStatusEntityPage.properties | 2 +- .../page/edit/dataset/EditCSVDatasetPage.java | 12 +----- .../edit/dataset/EditTetsimDatasetPage.java | 3 +- .../admin/AbstractListServiceEntityPage.java | 1 - .../admin/ListServiceCategoriesPage.java | 1 - .../admin/ListServiceDimensionsPage.java | 1 - .../lists/admin/ListServiceFiltersPage.java | 1 - .../lists/admin/ListServiceMeasuresPage.java | 1 - .../page/lists/admin/ListServicePage.java | 1 - 12 files changed, 29 insertions(+), 41 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java index 187ca943..1d97b4bd 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java @@ -204,7 +204,7 @@ protected TextContentModal createDeleteFailedModal() { final LaddaAjaxButton deleteButton = new LaddaAjaxButton("button", Buttons.Type.Info) { @Override protected void onSubmit(final AjaxRequestTarget target) { - setResponsePage(listPageClass); + setResponsePage(listPageClass, getCancelPageParameters()); } }; deleteButton.setDefaultFormProcessing(false); @@ -214,7 +214,7 @@ protected void onSubmit(final AjaxRequestTarget target) { modal.add(new AjaxEventBehavior("hidden.bs.modal") { @Override protected void onEvent(final AjaxRequestTarget target) { - setResponsePage(listPageClass); + setResponsePage(listPageClass, getCancelPageParameters()); } }); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html index 7e6f6c7f..a18649bd 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.html @@ -3,8 +3,10 @@ -
- ErrorInPublishing +
+
+ ErrorInPublishing +
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index dc773fc6..3719e2b8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -286,7 +286,7 @@ protected void onInitialize() { statusCommentsWrapper.add(statusComments); editForm.add(newStatusComment); - editForm.add(getErrorInPublishingLabel()); + editForm.add(getErrorInPublishing()); entityButtonsFragment = new Fragment("extraButtons", "entityButtons", this); editForm.replace(entityButtonsFragment); @@ -328,13 +328,16 @@ protected void onInitialize() { enableDisableAutosaveFields(null); } - private Label getErrorInPublishingLabel() { - Label errorInPublishingLabel = new Label("errorInPublishing", - new StringResourceModel("errorInPublishing", this, null)); - errorInPublishingLabel.setOutputMarkupId(true); - errorInPublishingLabel.setOutputMarkupPlaceholderTag(true); - errorInPublishingLabel.setVisibilityAllowed(ERROR_IN_PUBLISHING.equals(editForm.getModelObject().getStatus())); - return errorInPublishingLabel; + private TransparentWebMarkupContainer getErrorInPublishing() { + TransparentWebMarkupContainer errorInPublishing = new TransparentWebMarkupContainer("errorInPublishingPanel"); + Label errorInPublishingLabel = new Label("errorInPublishingTitle", + new StringResourceModel("errorInPublishingTitle", this, null)); + errorInPublishing.setOutputMarkupId(true); + errorInPublishing.setOutputMarkupPlaceholderTag(true); + errorInPublishing.setVisibilityAllowed(ERROR_IN_PUBLISHING.equals(editForm.getModelObject().getStatus())); + errorInPublishing.add(errorInPublishingLabel); + + return errorInPublishing; } @Override @@ -798,22 +801,15 @@ protected void setButtonsPermissions() { } protected void addDeleteButtonPermissions(final Component button) { - MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, SecurityConstants.Roles.ROLE_ADMIN); button.setVisibilityAllowed(entityId != null && !isViewMode() && !(PUBLISHING.equals(editForm.getModelObject().getStatus()) - || ERROR_IN_PUBLISHING.equals(editForm.getModelObject().getStatus()) || PUBLISHED.equals(editForm.getModelObject().getStatus()))); - MetaDataRoleAuthorizationStrategy.authorize( - button, Component.RENDER, getCommaCombinedRoles()); } protected void addSaveRevertButtonPermissions(final Component button) { addDefaultAllButtonsPermissions(button); - MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, getValidatorRole()); - MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, getCommaCombinedRoles()); button.setVisibilityAllowed(button.isVisibilityAllowed() - && (ERROR_IN_PUBLISHING.equals(editForm.getModelObject().getStatus()) - || PUBLISHED.equals(editForm.getModelObject().getStatus()))); + && PUBLISHED.equals(editForm.getModelObject().getStatus())); } protected void addSaveApproveButtonPermissions(final Component button) { @@ -845,12 +841,13 @@ protected void addSaveButtonsPermissions(final Component button) { MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, getCommaCombinedRoles()); button.setVisibilityAllowed(button.isVisibilityAllowed() && (DRAFT.equals(editForm.getModelObject().getStatus()) - || SAVED.equals(editForm.getModelObject().getStatus()))); + || SAVED.equals(editForm.getModelObject().getStatus()) + || ERROR_IN_PUBLISHING.equals(editForm.getModelObject().getStatus()))); } protected void addDefaultAllButtonsPermissions(final Component button) { - MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, SecurityConstants.Roles.ROLE_ADMIN); + MetaDataRoleAuthorizationStrategy.authorize(button, Component.RENDER, SecurityConstants.Roles.ROLE_USER); } @@ -863,6 +860,10 @@ private void scrollToPreviousPosition(final IHeaderResponse response) { ))); } + protected PageParameters getParamsWithServiceInformation() { + return null; + } + @Override public void renderHead(final IHeaderResponse response) { super.renderHead(response); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties index 16d425da..1c188262 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties @@ -19,4 +19,4 @@ saveContinue=Save Draft & Continue autosave_message=Form is saving autoSaveLabelMessage=Form auto-saved less than {0,number} minutes ago. checkedOutToMessage=Checked out to user {0}. -errorInPublishing=There was an error during publishing. Please check the data and try to republish it. If it doesn't work please contact the admin. +errorInPublishingTitle=There was an error during publishing. Please check the data and try to republish it. If it doesn't work please contact the admin. diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java index 633bdfb9..6bdedb59 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java @@ -28,7 +28,6 @@ import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; -import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.SAVED; /** * @author vchihai @@ -125,7 +124,7 @@ protected void onDelete(final AjaxRequestTarget target) { deleteFailedModal.show(target); target.add(deleteFailedModal); } - setResponsePage(listPageClass); + setResponsePage(listPageClass, getSaveEditParameters()); } @Override @@ -172,15 +171,6 @@ protected void onSubmit(final AjaxRequestTarget target) { } } - @Override - protected void onBeforeRender() { - super.onBeforeRender(); - - if (SAVED.equals(editForm.getModelObject().getStatus())) { - destinationService.setEnabled(true); - } - } - @Override protected void enableDisableAutosaveFields(final AjaxRequestTarget target) { super.enableDisableAutosaveFields(target); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index 0d2bc12d..abc2e8fb 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -131,7 +131,7 @@ protected void onDelete(final AjaxRequestTarget target) { deleteFailedModal.show(target); target.add(deleteFailedModal); } - setResponsePage(listPageClass); + setResponsePage(listPageClass, getParamsWithServiceInformation()); } @Override @@ -230,6 +230,7 @@ protected PageParameters getCancelPageParameters() { return getParamsWithServiceInformation(); } + protected PageParameters getParamsWithServiceInformation() { PageParameters pageParams = new PageParameters(); // add service to the page parameters diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java index 1ef1bde4..3fc181ab 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java @@ -30,7 +30,6 @@ import static org.devgateway.toolkit.forms.WebConstants.PAGE_SIZE; -@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) public class AbstractListServiceEntityPage extends BasePage { private static final long serialVersionUID = 652587400391540726L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java index 937f746d..b4012e98 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java @@ -32,7 +32,6 @@ import java.util.ArrayList; -@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) @MountPath(value = "/categories") public class ListServiceCategoriesPage extends AbstractListServiceEntityPage { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java index a0f1442c..ef906031 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java @@ -26,7 +26,6 @@ import java.util.ArrayList; -@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) @MountPath(value = "/dimensions") public class ListServiceDimensionsPage extends AbstractListServiceEntityPage { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java index 99d1e183..53545e5c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java @@ -14,7 +14,6 @@ import java.util.ArrayList; -@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) @MountPath(value = "/filters") public class ListServiceFiltersPage extends AbstractListServiceEntityPage { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java index 57638f4f..24c6529e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java @@ -30,7 +30,6 @@ import java.util.ArrayList; -@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) @MountPath(value = "/measures") public class ListServiceMeasuresPage extends AbstractListServiceEntityPage { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java index 9e6c891d..ce007ef9 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java @@ -44,7 +44,6 @@ import static org.devgateway.toolkit.forms.WebConstants.PAGE_SIZE; -@AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) @MountPath(value = "/listservices") public class ListServicePage extends BasePage { From 8fe6d98b050dcab28d38dc17bf8bd74b82afc104 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 7 Nov 2022 14:38:16 +0200 Subject: [PATCH 108/137] TOBACCO-1087: Add configuration for number of items in a table --- .../toolkit/forms/WebConstants.java | 2 +- .../wicket/components/PageableTablePanel.java | 17 +++++++++------- .../components/form/EditableTablePanel.java | 2 +- .../wicket/page/EditAdminSettingsPage.html | 5 +++++ .../wicket/page/EditAdminSettingsPage.java | 16 ++++++++++++++- .../page/EditAdminSettingsPage.properties | 4 +++- .../wicket/page/lists/AbstractListPage.java | 12 +++++++++-- .../admin/AbstractListServiceEntityPage.java | 11 +++++----- .../page/lists/admin/ListServicePage.java | 10 +++++----- .../SortableJpaServiceDataProvider.java | 20 +++++++++++++++---- .../persistence/dao/AdminSettings.java | 12 +++++++++++ .../main/resources/liquibase-changelog.xml | 9 +++++++++ 12 files changed, 93 insertions(+), 27 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java index 9629b3c8..1194afd6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java @@ -26,7 +26,7 @@ private WebConstants() { } - public static final int PAGE_SIZE = 10; + public static final Integer DEFAULT_PAGE_SIZE = 20; public static final int SELECT_PAGE_SIZE = 25; public static final int PAGE_SIZE_NO_LIMIT = 999999; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/PageableTablePanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/PageableTablePanel.java index a28cadde..7b8831a8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/PageableTablePanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/PageableTablePanel.java @@ -8,9 +8,11 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.wicket.components.table.AjaxFallbackBootstrapDataTable; import org.devgateway.toolkit.forms.wicket.providers.ListDataProvider; +import org.devgateway.toolkit.persistence.service.AdminSettingsService; import java.io.Serializable; import java.util.ArrayList; @@ -29,12 +31,13 @@ public class PageableTablePanel parentModel; + @SpringBean + AdminSettingsService adminSettingsService; + protected AjaxFallbackBootstrapDataTable dataTable; protected ISortableDataProvider dataProvider; - protected int rowsPerPage = WebConstants.PAGE_SIZE; - protected List> columns = new ArrayList<>(); public PageableTablePanel(final String id, final IModel parentModel) { @@ -57,10 +60,14 @@ protected void onInitialize() { } protected AjaxFallbackBootstrapDataTable buildDataTable() { - dataTable = new AjaxFallbackBootstrapDataTable("table", columns, dataProvider, rowsPerPage); + dataTable = new AjaxFallbackBootstrapDataTable("table", columns, dataProvider, getPageSize()); return dataTable; } + private Integer getPageSize() { + return adminSettingsService.get().getPageSize(); + } + public AjaxFallbackBootstrapDataTable getDataTable() { return dataTable; } @@ -69,10 +76,6 @@ public void setSort(final Object property, final SortOrder sortOrder) { ((ListDataProvider) dataProvider).setSort(property, SortOrder.ASCENDING); } - public void setPageSize(final int pageSize) { - rowsPerPage = pageSize; - } - protected List getItems() { return getModelObject(); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/EditableTablePanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/EditableTablePanel.java index 45561a12..bf4e5f82 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/EditableTablePanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/EditableTablePanel.java @@ -65,7 +65,7 @@ public EditableTablePanel(final String id, final IModel parentModel) { protected AjaxFallbackBootstrapDataTable buildDataTable() { AjaxFallbackBootstrapDataTable dataTable = super.buildDataTable(); - if (this.rowsPerPage != WebConstants.PAGE_SIZE_NO_LIMIT && usePagingWithErrors) { + if (usePagingWithErrors) { AjaxBootstrapNavigationToolbar navToolbar = dataTable.getNavigationToolbar(); navToolbar.withPagingNavFactory(new PagingNavigationFactory(EditableTablePagination.class, this)); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html index 74d5bb30..2d7730a0 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.html @@ -37,6 +37,11 @@
+
+
+
+
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java index 8f5f5234..974c1d95 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java @@ -8,12 +8,15 @@ import org.apache.wicket.validation.validator.RangeValidator; import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.wicket.components.form.CheckBoxToggleBootstrapFormComponent; +import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; +import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; import org.devgateway.toolkit.persistence.dao.AdminSettings; import org.devgateway.toolkit.persistence.service.AdminSettingsService; import org.wicketstuff.annotation.mount.MountPath; +import java.util.Arrays; import java.util.List; /** @@ -30,6 +33,8 @@ public class EditAdminSettingsPage extends AbstractEditPage { private TextFieldBootstrapFormComponent autosaveTime; + private Select2ChoiceBootstrapFormComponent pageSize; + @SpringBean private AdminSettingsService adminSettingsService; @@ -37,7 +42,7 @@ public EditAdminSettingsPage(final PageParameters parameters) { super(parameters); this.jpaService = adminSettingsService; - this.listPageClass = Homepage.class; + this.listPageClass = ConfigurationsHomepage.class; if (entityId == null) { final List listSettings = adminSettingsService.findAll(); @@ -71,5 +76,14 @@ protected void onInitialize() { autosaveTime.setShowTooltip(true); editForm.add(autosaveTime); + pageSize = new Select2ChoiceBootstrapFormComponent<>("pageSize", + new GenericChoiceProvider<>(getPageSizeRange())); + pageSize.required(); + editForm.add(pageSize); + + } + + public List getPageSizeRange() { + return Arrays.asList(5, 10, 15, 20, 25, 50, 100); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties index fa2dcb85..54e451f0 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties @@ -6,4 +6,6 @@ rebootServer.label=Enable server reboot warning autosaveTime.label=Autosave Time (minutes) autosaveTime.help=Set to 0 to disable tetsimCurrency.label=Currency for TETSIM -countryName.label=Country Name \ No newline at end of file +countryName.label=Country Name +pageSize.label=Default items in list +pageSize.help=The default number of items that will appear in lists \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java index 11da8f7b..d26d9e14 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java @@ -52,6 +52,7 @@ import org.devgateway.toolkit.forms.wicket.providers.SortableJpaServiceDataProvider; import org.devgateway.toolkit.persistence.dao.GenericPersistable; import org.devgateway.toolkit.persistence.excel.service.ExcelGeneratorService; +import org.devgateway.toolkit.persistence.service.AdminSettingsService; import org.devgateway.toolkit.persistence.service.BaseJpaService; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; @@ -74,6 +75,9 @@ public abstract class AbstractListPage extends BasePage { private static final long serialVersionUID = 1958350868666244087L; + @SpringBean + AdminSettingsService adminSettingsService; + protected Class> editPageClass; protected AjaxFallbackBootstrapDataTable dataTable; @@ -118,7 +122,7 @@ protected void onInitialize() { throw new NullEditPageClassException(); } - dataProvider = new SortableJpaServiceDataProvider<>(jpaService); + dataProvider = new SortableJpaServiceDataProvider<>(jpaService, getPageSize()); dataProvider.setFilterState(newFilterState()); // create the excel download form; by default this form is hidden and we should make it visible only to pages @@ -137,7 +141,7 @@ public void populateItem(final Item> cellItem, final String co cellItem.add(getActionPanel(componentId, model)); } }); - dataTable = new AjaxFallbackBootstrapDataTable<>("table", columns, dataProvider, WebConstants.PAGE_SIZE); + dataTable = new AjaxFallbackBootstrapDataTable<>("table", columns, dataProvider, getPageSize()); ResettingFilterForm> filterForm = new ResettingFilterForm<>("filterForm", dataProvider, dataTable); @@ -166,6 +170,10 @@ public void populateItem(final Item> cellItem, final String co add(editPageLink); } + private Integer getPageSize() { + return adminSettingsService.get().getPageSize(); + } + protected PageParameters getEditPageParameters() { PageParameters pageParameters = new PageParameters(); pageParameters.set(WebConstants.PARAM_ID, null); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java index 3fc181ab..98adfcda 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java @@ -3,7 +3,6 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapBookmarkablePageLink; import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; -import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; @@ -15,27 +14,29 @@ import org.apache.wicket.model.Model; import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.exceptions.NullServiceEntityServiceException; -import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.service.admin.BaseServiceEntityService; import org.devgateway.toolkit.forms.wicket.components.table.AjaxFallbackBootstrapDataTable; import org.devgateway.toolkit.forms.wicket.page.BasePage; import org.devgateway.toolkit.forms.wicket.page.edit.admin.AbstractEditServiceEntityPage; import org.devgateway.toolkit.persistence.dto.ServiceEntity; +import org.devgateway.toolkit.persistence.service.AdminSettingsService; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; -import static org.devgateway.toolkit.forms.WebConstants.PAGE_SIZE; - public class AbstractListServiceEntityPage extends BasePage { private static final long serialVersionUID = 652587400391540726L; protected Class> editPageClass; + @SpringBean + protected AdminSettingsService adminSettingsService; + protected AjaxFallbackBootstrapDataTable dataTable; protected SortableServiceEntityProvider dataProvider; @@ -90,7 +91,7 @@ public void populateItem(final Item> cellItem, final String co } protected int getPageSize() { - return PAGE_SIZE; + return adminSettingsService.get().getPageSize(); } public ActionPanel getActionPanel(final String id, final IModel model) { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java index ce007ef9..e35b58d1 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java @@ -15,7 +15,6 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.Component; -import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; @@ -31,24 +30,25 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.WebConstants; -import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.LinkTargetBlankPanel; import org.devgateway.toolkit.forms.wicket.components.table.AjaxFallbackBootstrapDataTable; import org.devgateway.toolkit.forms.wicket.page.BasePage; import org.devgateway.toolkit.persistence.dto.ServiceMetadata; +import org.devgateway.toolkit.persistence.service.AdminSettingsService; import org.wicketstuff.annotation.mount.MountPath; import java.util.ArrayList; import java.util.List; -import static org.devgateway.toolkit.forms.WebConstants.PAGE_SIZE; - @MountPath(value = "/listservices") public class ListServicePage extends BasePage { private static final long serialVersionUID = -6132847935476573446L; + @SpringBean + AdminSettingsService adminSettingsService; + protected AjaxFallbackBootstrapDataTable dataTable; protected ServiceMetadataProvider dataProvider; @@ -117,7 +117,7 @@ public void populateItem(final Item> cellItem, f } protected int getPageSize() { - return PAGE_SIZE; + return adminSettingsService.get().getPageSize(); } public ActionPanel getActionPanel(final String id, final IModel model) { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/providers/SortableJpaServiceDataProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/providers/SortableJpaServiceDataProvider.java index 578845a1..6677537c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/providers/SortableJpaServiceDataProvider.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/providers/SortableJpaServiceDataProvider.java @@ -20,6 +20,7 @@ import org.devgateway.toolkit.forms.models.PersistableJpaRepositoryModel; import org.devgateway.toolkit.forms.wicket.components.table.filter.JpaFilterState; import org.devgateway.toolkit.persistence.dao.GenericPersistable; +import org.devgateway.toolkit.persistence.service.AdminSettingsService; import org.devgateway.toolkit.persistence.service.BaseJpaService; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -38,17 +39,24 @@ public class SortableJpaServiceDataProvider implements IFilterStateLocator> { private static final long serialVersionUID = 6507887810859971417L; + private final Integer pageSize; + private final BaseJpaService jpaService; private JpaFilterState filterState; + public SortableJpaServiceDataProvider(final BaseJpaService jpaService) { + this(jpaService, WebConstants.DEFAULT_PAGE_SIZE); + } + /** * Always provide a proxy jpaService here! For example one coming from a {@link SpringBean} * * @param jpaService */ - public SortableJpaServiceDataProvider(final BaseJpaService jpaService) { + public SortableJpaServiceDataProvider(final BaseJpaService jpaService, final Integer pageSize) { this.jpaService = jpaService; + this.pageSize = pageSize; } /** @@ -68,14 +76,18 @@ protected Sort translateSort() { */ @Override public Iterator iterator(final long first, final long count) { - int page = (int) ((double) first / WebConstants.PAGE_SIZE); + int page = (int) ((double) first / getPageSize()); final Page findAll = jpaService.findAll(filterState.getSpecification(), translateSort() == null - ? PageRequest.of(page, WebConstants.PAGE_SIZE) - : PageRequest.of(page, WebConstants.PAGE_SIZE, translateSort())); + ? PageRequest.of(page, getPageSize()) + : PageRequest.of(page, getPageSize(), translateSort())); return findAll.iterator(); } + private Integer getPageSize() { + return pageSize; + } + @Override public long size() { return jpaService.count(filterState.getSpecification()); diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java index b49430bc..fed9346d 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java @@ -8,6 +8,8 @@ import java.time.Duration; import java.time.LocalDateTime; +import static org.springframework.beans.support.PagedListHolder.DEFAULT_PAGE_SIZE; + /** * @author idobre * @since 6/22/16 @@ -27,6 +29,8 @@ public class AdminSettings extends AbstractAuditableEntity { private Integer autosaveTime = AUTOSAVE_TIME_DEFAULT; + private Integer pageSize = DEFAULT_PAGE_SIZE; + private String tetsimCurrency; private String countryName; @@ -79,4 +83,12 @@ public String getCountryName() { public void setCountryName(final String countryName) { this.countryName = countryName; } + + public Integer getPageSize() { + return pageSize; + } + + public void setPageSize(final Integer pageSize) { + this.pageSize = pageSize; + } } diff --git a/persistence/src/main/resources/liquibase-changelog.xml b/persistence/src/main/resources/liquibase-changelog.xml index 08321477..8a4e8742 100644 --- a/persistence/src/main/resources/liquibase-changelog.xml +++ b/persistence/src/main/resources/liquibase-changelog.xml @@ -177,4 +177,13 @@ + + + + + + + + + \ No newline at end of file From 3b075f43e4b3f6fec60c093d0d6b8de1e52b8b15 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 7 Nov 2022 17:04:48 +0200 Subject: [PATCH 109/137] TOBACCO-1091: Add group and expression fields to measure --- .../wicket/page/edit/admin/EditServiceMeasurePage.html | 6 ++++++ .../wicket/page/edit/admin/EditServiceMeasurePage.java | 8 ++++++++ .../page/edit/admin/EditServiceMeasurePage.properties | 4 +++- .../page/lists/admin/ListServiceMeasuresPage.java | 1 + .../toolkit/persistence/dto/ServiceCategory.java | 10 ++++++++++ 5 files changed, 28 insertions(+), 1 deletion(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html index 1bc546a2..ccc8559d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.html @@ -8,6 +8,12 @@
+
+
+
+
+
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java index 3752bce7..c21408cd 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java @@ -37,6 +37,14 @@ protected void onInitialize() { label.getField().setRequired(true); editForm.add(label); + final TextFieldBootstrapFormComponent parent = new TextFieldBootstrapFormComponent<>("parent"); + parent.setEnabled(false); + editForm.add(parent); + + final TextFieldBootstrapFormComponent expression = new TextFieldBootstrapFormComponent<>("expression"); + expression.setEnabled(false); + editForm.add(expression); + final TextFieldBootstrapFormComponent position = new TextFieldBootstrapFormComponent<>("position"); position.getField().setRequired(true); editForm.add(position); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties index 70ba7e9a..15f3e3a3 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties @@ -16,4 +16,6 @@ code.label=Value value.label=System Label position.label=Position color.label=Color in graphic -labels.label=Label Translations \ No newline at end of file +labels.label=Label Translations +parent.label=Group +expression.label=Expression \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java index 24c6529e..de655093 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java @@ -47,6 +47,7 @@ public ListServiceMeasuresPage(final PageParameters pageParameters) { columns = new ArrayList<>(); columns.add(new PropertyColumn<>(new Model<>("Value"), "code", "code")); columns.add(new PropertyColumn<>(new Model<>("System Label"), "value", "value")); + columns.add(new PropertyColumn<>(new Model<>("Group"), "parent", "parent")); columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); columns.add(new PropertyColumn(new Model<>("Color"), "categoryStyle.color", "categoryStyle.color") { diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java index b4dddbfb..5bd56cd5 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceCategory.java @@ -21,6 +21,8 @@ public class ServiceCategory extends ServiceEntity { private String type; + private String parent; + @JsonDeserialize(using = ServiceTextTranslationDeserializer.class) @JsonSerialize(using = ServiceTextTranslationSerializer.class) private List labels; @@ -72,4 +74,12 @@ public List getLabels() { public void setLabels(final List labels) { this.labels = labels; } + + public String getParent() { + return parent; + } + + public void setParent(String parent) { + this.parent = parent; + } } From fe513d57376961b4e46bac2a1ec99bd65c25b864 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 7 Nov 2022 17:11:29 +0200 Subject: [PATCH 110/137] TOBACCO-1067: Update upload button label --- .../wicket/page/edit/dataset/EditCSVDatasetPage.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.properties index 35b3f180..65eafd6a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.properties @@ -4,6 +4,6 @@ year.label=Year destinationService.label=Destination Service description.label=Description -files.label=Dataset File +files.label=Upload Dataset File uploadedFilesTitle=Uploaded File note=* The uploaded document can be accessed by admin, neiti, and auditor users. \ No newline at end of file From 1f6d35bb71bf8c11497b20b4472c3ca62a608830 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 9 Nov 2022 17:11:02 +0200 Subject: [PATCH 111/137] TOBACCO-1090: Add unpublishing status --- .../toolkit/forms/client/DatasetClient.java | 8 ++- .../forms/service/DatasetClientService.java | 63 ++++++------------- .../wicket/page/edit/AbstractEditPage.html | 2 +- .../wicket/page/edit/AbstractEditPage.java | 20 +++--- .../page/edit/AbstractEditPage.properties | 1 + .../edit/AbstractEditStatusEntityPage.java | 16 ++--- .../page/edit/dataset/EditCSVDatasetPage.java | 8 ++- .../edit/dataset/EditTetsimDatasetPage.java | 5 +- .../forms/client/DatasetClientTest.java | 2 +- .../toolkit/persistence/dao/DBConstants.java | 9 ++- .../repository/data/CSVDatasetRepository.java | 5 +- .../data/TetsimDatasetRepository.java | 4 +- .../service/data/CSVDatasetServiceImpl.java | 4 +- .../service/data/DatasetService.java | 2 +- .../data/TetsimDatasetServiceImpl.java | 4 +- 15 files changed, 74 insertions(+), 79 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java index 114a6b7c..830e8131 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java @@ -61,7 +61,7 @@ public DatasetJobStatus getDatasetStatus(String jobId) throws DataSetClientExcep throw new RuntimeException(("Service is not up")); } - public void unpublishDataset(String code) throws DataSetClientException { + public DatasetJobStatus unpublishDataset(String code) throws DataSetClientException { if (isUp()) { Response jobStatusResponse = client.target(baseUrl) .path(PATH_DATASETS) @@ -69,9 +69,11 @@ public void unpublishDataset(String code) throws DataSetClientException { .request() .delete(); - if (jobStatusResponse.getStatusInfo().getFamily() != SUCCESSFUL) { - throw new DataSetClientException("Error in unpublishing a dataset with code " + code); + if (jobStatusResponse.getStatusInfo().getFamily() == SUCCESSFUL) { + return jobStatusResponse.readEntity(DatasetJobStatus.class); } + + throw new DataSetClientException(jobStatusResponse.toString()); } else { throw new RuntimeException(("Service is not up")); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java index 839fb613..0c0800da 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java @@ -8,7 +8,6 @@ import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.dto.ServiceMeasure; import org.devgateway.toolkit.persistence.dto.ServiceMetadata; -import org.devgateway.toolkit.persistence.dto.ServiceDimension; import org.devgateway.toolkit.persistence.service.data.CSVDatasetService; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.slf4j.Logger; @@ -25,7 +24,9 @@ import static org.devgateway.toolkit.forms.client.ClientConstants.CODE_PREFIX; import static org.devgateway.toolkit.forms.client.ClientConstants.JobStatus.COMPLETED; import static org.devgateway.toolkit.forms.client.ClientConstants.JobStatus.ERROR; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DRAFT; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.ERROR_IN_PUBLISHING; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.ERROR_IN_UNPUBLISHING; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; @@ -47,8 +48,8 @@ public class DatasetClientService { public void triggerCheckDatasetsJob() { logger.debug("Fired triggerCheckDatasetsJob"); List datasets = new ArrayList<>(); - datasets.addAll(tetsimDatasetService.findAllPublishing()); - datasets.addAll(csvDatasetService.findAllPublishing()); + datasets.addAll(tetsimDatasetService.findAllInProgress()); + datasets.addAll(csvDatasetService.findAllInProgress()); checkDatasetJobs(datasets); } @@ -58,17 +59,20 @@ private void checkDatasetJobs(List datasets) { ServiceMetadata serviceMetadata = eurekaClientService.findByName(d.getDestinationService()); DatasetClient client = new DatasetClient(serviceMetadata.getUrl()); String status = client.getDatasetJobStatus(CODE_PREFIX + d.getId()).getStatus(); + String initialStatus = d.getStatus(); if (COMPLETED.equals(status)) { - d.setStatus(PUBLISHED); + String completedStatus = getCompletedStatus(initialStatus); + d.setStatus(completedStatus); logger.info(String.format("The dataset with id %s changed the status from %s to %s", - d.getId(), PUBLISHING, PUBLISHED)); + d.getId(), initialStatus, completedStatus)); } else if (ERROR.equals(status)) { - d.setStatus(ERROR_IN_PUBLISHING); + String errorStatus = getErrorStatus(initialStatus); + d.setStatus(errorStatus); logger.info(String.format("The dataset with id %s changed the status from %s to %s", - d.getId(), PUBLISHING, ERROR_IN_PUBLISHING)); + d.getId(), initialStatus, errorStatus)); } - if (!PUBLISHING.equals(d.getStatus())) { + if (!initialStatus.equals(d.getStatus())) { if (d instanceof TetsimDataset) { tetsimDatasetService.save((TetsimDataset) d); } else if (d instanceof CSVDataset) { @@ -80,6 +84,14 @@ private void checkDatasetJobs(List datasets) { }); } + private String getCompletedStatus(final String status) { + return PUBLISHING.equals(status) ? PUBLISHED : DRAFT; + } + + private String getErrorStatus(final String status) { + return PUBLISHING.equals(status) ? ERROR_IN_PUBLISHING : ERROR_IN_UNPUBLISHING; + } + public void publishDataset(Dataset dataset, String fileName, byte[] content) throws DataSetClientException { String serviceURL = getDestinationService(dataset).getUrl(); DatasetClient client = new DatasetClient(serviceURL); @@ -111,44 +123,9 @@ private ServiceMetadata getDestinationService(Dataset dataset) { return eurekaClientService.findByName(destinationService); } - public List getDimensions(final String serviceName) { - ServiceMetadata service = eurekaClientService.findByName(serviceName); - return new DatasetClient(service.getUrl()).getDimensions(); - } - - public ServiceDimension getDimensionById(final String serviceName, final long id) { - ServiceMetadata service = eurekaClientService.findByName(serviceName); - return new DatasetClient(service.getUrl()).getDimensionById(id); - } - - public void updateDimension(final String serviceName, final ServiceDimension dimension) { - ServiceMetadata service = eurekaClientService.findByName(serviceName); - new DatasetClient(service.getUrl()).updateDimension(dimension); - } - - public void addDimensionToService(final String service, final ServiceDimension serviceDimension) { - ServiceMetadata serviceMetadata = eurekaClientService.findByName(service); - new DatasetClient(serviceMetadata.getUrl()).addDimension(serviceDimension); - } - public List getMeasures(final String serviceName) { ServiceMetadata service = eurekaClientService.findByName(serviceName); return new DatasetClient(service.getUrl()).getMeasures(); } - public ServiceMeasure getMeasureById(final String serviceName, final long id) { - ServiceMetadata service = eurekaClientService.findByName(serviceName); - return new DatasetClient(service.getUrl()).getMeasureById(id); - } - - public void updateMeasure(final String serviceName, final ServiceMeasure measure) { - ServiceMetadata service = eurekaClientService.findByName(serviceName); - new DatasetClient(service.getUrl()).updateMeasure(measure); - } - - public void addMeasureToService(final String service, final ServiceMeasure serviceMeasure) { - ServiceMetadata serviceMetadata = eurekaClientService.findByName(service); - new DatasetClient(serviceMetadata.getUrl()).addMeasure(serviceMeasure); - } - } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html index 21253cb9..dbe4625e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html @@ -20,7 +20,7 @@
-
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java index 1d97b4bd..3bdd3707 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java @@ -121,7 +121,7 @@ private T newInstance() { protected TextContentModal saveFailedModal; - protected TextContentModal approveFailedModal; + protected TextContentModal failedModal; @SpringBean protected EntityManager entityManager; @@ -238,21 +238,21 @@ protected void onSubmit(final AjaxRequestTarget target) { modal.add(new AjaxEventBehavior("hidden.bs.modal") { @Override protected void onEvent(final AjaxRequestTarget target) { - setResponsePage(listPageClass); + setResponsePage(listPageClass, getPageParameters()); } }); return modal; } - protected TextContentModal createApproveFailedModal() { - final TextContentModal modal = new TextContentModal("approveFailedModal", - new ResourceModel("optimistic_lock_error_message")); + protected TextContentModal createFailedModal() { + final TextContentModal modal = new TextContentModal("failedModal", + new ResourceModel("failedMessage")); modal.header(new ResourceModel("error")); final LaddaAjaxButton okButton = new LaddaAjaxButton("button", Buttons.Type.Info) { @Override protected void onSubmit(final AjaxRequestTarget target) { - setResponsePage(listPageClass); + setResponsePage(listPageClass, getPageParameters()); } }; okButton.setDefaultFormProcessing(false); @@ -262,7 +262,7 @@ protected void onSubmit(final AjaxRequestTarget target) { modal.add(new AjaxEventBehavior("hidden.bs.modal") { @Override protected void onEvent(final AjaxRequestTarget target) { - setResponsePage(listPageClass); + setResponsePage(listPageClass, getPageParameters()); } }); @@ -314,8 +314,8 @@ public EditForm(final String id) { saveFailedModal = createSaveFailedModal(); add(saveFailedModal); - approveFailedModal = createApproveFailedModal(); - add(approveFailedModal); + failedModal = createFailedModal(); + add(failedModal); // don't display the delete button if we just create a new entity if (entityId == null) { @@ -332,7 +332,7 @@ protected BootstrapCancelButton getCancelButton(final String id) { @Override protected void onSubmit(final AjaxRequestTarget target) { - setResponsePage(listPageClass); + setResponsePage(listPageClass, getPageParameters()); } }; } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.properties index d75a9e2d..72f13965 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.properties @@ -29,3 +29,4 @@ formHasErrors=The form has errors or is missing information and cannot be submit error=Error delete_error_message=Cannot delete entity, it is in use by the system optimistic_lock_error_message=Changes were not saved. This object was modified by someone else. +failedMessage=The request failed. Please try again later. diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index 3719e2b8..215180db 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -64,9 +64,11 @@ import static org.devgateway.toolkit.forms.WebConstants.PARAM_AUTO_SAVE; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DRAFT; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.ERROR_IN_PUBLISHING; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.ERROR_IN_UNPUBLISHING; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.SAVED; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.UNPUBLISHING; /** * @author mpostelnicu @@ -199,12 +201,8 @@ protected String getOnClickScript() { @Override protected void onSubmit(final AjaxRequestTarget target) { - setStatusAppendComment(DRAFT); - editForm.getModelObject().setRemoveLock(true); - super.onSubmit(target); - target.add(editForm); - setButtonsPermissions(); onAfterRevertToDraft(target); + super.onSubmit(target); } }; unpublishButton.setType(Buttons.Type.Warning); @@ -490,10 +488,12 @@ private String getStatusLabelClass() { return "label-success"; case DRAFT: case ERROR_IN_PUBLISHING: + case ERROR_IN_UNPUBLISHING: return "label-danger"; case SAVED: return "label-primary"; case PUBLISHING: + case UNPUBLISHING: return "label-warning"; default: return ""; @@ -809,7 +809,8 @@ protected void addDeleteButtonPermissions(final Component button) { protected void addSaveRevertButtonPermissions(final Component button) { addDefaultAllButtonsPermissions(button); button.setVisibilityAllowed(button.isVisibilityAllowed() - && PUBLISHED.equals(editForm.getModelObject().getStatus())); + && (PUBLISHED.equals(editForm.getModelObject().getStatus()) + || ERROR_IN_UNPUBLISHING.equals(editForm.getModelObject().getStatus()))); } protected void addSaveApproveButtonPermissions(final Component button) { @@ -842,7 +843,8 @@ protected void addSaveButtonsPermissions(final Component button) { button.setVisibilityAllowed(button.isVisibilityAllowed() && (DRAFT.equals(editForm.getModelObject().getStatus()) || SAVED.equals(editForm.getModelObject().getStatus()) - || ERROR_IN_PUBLISHING.equals(editForm.getModelObject().getStatus()))); + || ERROR_IN_PUBLISHING.equals(editForm.getModelObject().getStatus()) + || ERROR_IN_UNPUBLISHING.equals(editForm.getModelObject().getStatus()))); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java index 6bdedb59..49904b00 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java @@ -28,6 +28,7 @@ import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.UNPUBLISHING; /** * @author vchihai @@ -127,13 +128,16 @@ protected void onDelete(final AjaxRequestTarget target) { setResponsePage(listPageClass, getSaveEditParameters()); } - @Override protected void onAfterRevertToDraft(final AjaxRequestTarget target) { try { + CSVDataset dataset = editForm.getModelObject(); datasetClientService.unpublishDataset(editForm.getModelObject()); + dataset.setStatus(UNPUBLISHING); } catch (DataSetClientException | Exception e) { logger.error(e.getMessage(), e); + failedModal.show(target); } + setResponsePage(listPageClass); } protected void onApprove(final AjaxRequestTarget target) { @@ -148,7 +152,7 @@ protected void onApprove(final AjaxRequestTarget target) { dataset.setStatus(PUBLISHING); } catch (DataSetClientException | Exception e) { logger.error(e.getMessage(), e); - approveFailedModal.show(target); + failedModal.show(target); } setResponsePage(listPageClass); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index abc2e8fb..d7ee5ea8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -36,6 +36,7 @@ import static org.devgateway.toolkit.forms.WebConstants.PARAM_YEAR; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.UNPUBLISHING; /** * @author vchihai @@ -138,9 +139,11 @@ protected void onDelete(final AjaxRequestTarget target) { protected void onAfterRevertToDraft(final AjaxRequestTarget target) { try { datasetClientService.unpublishDataset(editForm.getModelObject()); + editForm.getModelObject().setStatus(UNPUBLISHING); } catch (DataSetClientException | Exception e) { logger.error(e.getMessage(), e); } + setResponsePage(listPageClass); } protected void onApprove(final AjaxRequestTarget target) { @@ -154,7 +157,7 @@ protected void onApprove(final AjaxRequestTarget target) { dataset.setStatus(PUBLISHING); } catch (DataSetClientException | Exception e) { logger.error(e.getMessage(), e); - approveFailedModal.show(target); + failedModal.show(target); } setResponsePage(listPageClass); } diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/client/DatasetClientTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/client/DatasetClientTest.java index 7f4a6bb8..75cba8e2 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/client/DatasetClientTest.java +++ b/forms/src/test/java/org/devgateway/toolkit/forms/client/DatasetClientTest.java @@ -33,7 +33,7 @@ public void testTetsimDataset() { TetsimDataset dataset = new TetsimDataset(); dataset.setYear(2020); try { - System.out.println(client.publishDataset(dataset, Files.readAllBytes(Paths.get("./src/test/resources/2020_tetsim.csv")))); + client.publishDataset(dataset, Files.readAllBytes(Paths.get("./src/test/resources/2020_tetsim.csv"))); } catch (DataSetClientException e) { throw new RuntimeException(e); } catch (FileNotFoundException e) { diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java index 2d203f99..90ffa1b8 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/DBConstants.java @@ -28,7 +28,14 @@ public static final class Status { public static final String PUBLISHED = "PUBLISHED"; public static final String ERROR_IN_PUBLISHING = "ERROR_IN_PUBLISHING"; public static final String DELETED = "DELETED"; - public static final String[] ALL = {DRAFT, SAVED, PUBLISHING, PUBLISHED, ERROR_IN_PUBLISHING}; + + public static final String UNPUBLISHING = "UNPUBLISHING"; + + public static final String ERROR_IN_UNPUBLISHING = "ERROR_IN_UNPUBLISHING"; + + + public static final String[] ALL = {DRAFT, SAVED, PUBLISHING, PUBLISHED, ERROR_IN_PUBLISHING, UNPUBLISHING, + ERROR_IN_UNPUBLISHING, DELETED}; public static final List ALL_LIST = Collections.unmodifiableList(Arrays.asList(ALL)); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java index e83f89ee..13b7d981 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java @@ -1,7 +1,6 @@ package org.devgateway.toolkit.persistence.repository.data; import org.devgateway.toolkit.persistence.dao.data.CSVDataset; -import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.repository.norepository.UniquePropertyRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; @@ -16,8 +15,8 @@ public interface CSVDatasetRepository extends DatasetRepository, @Query("select td from CSVDataset td where td.status like 'DELETED'") List findAllDeleted(); - @Query("select td from CSVDataset td where td.status like 'PUBLISHING'") - List findAllPublishing(); + @Query("select td from CSVDataset td where td.status like 'PUBLISHING' or td.status like 'UNPUBLISHING'") + List findAllInProgress(); @Query ("select count(e) from #{#entityName} e where (:year is null or e.year=:year) " + "and e.status not in ('DELETED')") diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java index 35128777..5f93d112 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java @@ -15,8 +15,8 @@ public interface TetsimDatasetRepository extends DatasetRepository findAllDeleted(); - @Query("select td from TetsimDataset td where td.status like 'PUBLISHING'") - List findAllPublishing(); + @Query("select td from TetsimDataset td where td.status like 'PUBLISHING' or td.status like 'UNPUBLISHING'") + List findAllInProgress(); @Query ("select count(e) from #{#entityName} e where (:year is null or e.year=:year) " + "and e.status not in ('DELETED')") diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetServiceImpl.java index 77519019..ffe5e42c 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetServiceImpl.java @@ -41,8 +41,8 @@ public List findAllDeleted() { } @Override - public List findAllPublishing() { - return csvDatasetRepository.findAllPublishing(); + public List findAllInProgress() { + return csvDatasetRepository.findAllInProgress(); } @Override diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/DatasetService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/DatasetService.java index 9e5ee796..29c730be 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/DatasetService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/DatasetService.java @@ -10,7 +10,7 @@ public interface DatasetService extends BaseJpaService, Un List findAllDeleted(); - List findAllPublishing(); + List findAllInProgress(); long countByNonPublished(Integer year); diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java index a236872a..1b83ff44 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java @@ -41,8 +41,8 @@ public List findAllDeleted() { } @Override - public List findAllPublishing() { - return tetsimDatasetRepository.findAllPublishing(); + public List findAllInProgress() { + return tetsimDatasetRepository.findAllInProgress(); } @Override From 9749c1ed1aa66901b0c029ed1e6b0454bf565da1 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 11 Nov 2022 13:20:19 +0200 Subject: [PATCH 112/137] TOBACCO-1090: Update the error message for publishing/unpublishing --- .../page/edit/AbstractEditStatusEntityPage.java | 17 ++++++++++++++--- .../AbstractEditStatusEntityPage.properties | 2 +- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index 215180db..d659c266 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -61,6 +61,8 @@ import org.wicketstuff.datetime.markup.html.basic.DateLabel; import org.wicketstuff.select2.Select2Choice; +import java.text.MessageFormat; + import static org.devgateway.toolkit.forms.WebConstants.PARAM_AUTO_SAVE; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DRAFT; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.ERROR_IN_PUBLISHING; @@ -328,16 +330,25 @@ protected void onInitialize() { private TransparentWebMarkupContainer getErrorInPublishing() { TransparentWebMarkupContainer errorInPublishing = new TransparentWebMarkupContainer("errorInPublishingPanel"); - Label errorInPublishingLabel = new Label("errorInPublishingTitle", - new StringResourceModel("errorInPublishingTitle", this, null)); + Label errorInPublishingLabel = new Label("errorInPublishingTitle", getErrorInPublishingMessage()); errorInPublishing.setOutputMarkupId(true); errorInPublishing.setOutputMarkupPlaceholderTag(true); - errorInPublishing.setVisibilityAllowed(ERROR_IN_PUBLISHING.equals(editForm.getModelObject().getStatus())); + errorInPublishing.setVisibilityAllowed(isErrorInPublishingVisible()); errorInPublishing.add(errorInPublishingLabel); return errorInPublishing; } + private IModel getErrorInPublishingMessage() { + String status = ERROR_IN_PUBLISHING.equals(editForm.getModelObject().getStatus()) ? "publishing" : "unpublishing"; + return Model.of(MessageFormat.format(getString("errorInPublishingTitle"), status)); + } + + private boolean isErrorInPublishingVisible() { + String status = editForm.getModelObject().getStatus(); + return ERROR_IN_PUBLISHING.equals(status) || ERROR_IN_UNPUBLISHING.equals(status); + } + @Override protected void afterSaveEntity(final T saveable) { super.afterSaveEntity(saveable); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties index 1c188262..14e2e466 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.properties @@ -19,4 +19,4 @@ saveContinue=Save Draft & Continue autosave_message=Form is saving autoSaveLabelMessage=Form auto-saved less than {0,number} minutes ago. checkedOutToMessage=Checked out to user {0}. -errorInPublishingTitle=There was an error during publishing. Please check the data and try to republish it. If it doesn't work please contact the admin. +errorInPublishingTitle=There was an error during {0}. Please check the data and try to republish it. If it doesn't work please contact the admin. From ea87a8644244c7c2b29b3c82de07f944876b867f Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 11 Nov 2022 16:51:42 +0200 Subject: [PATCH 113/137] TOBACCO-1098: Add the template download feature --- .../toolkit/forms/client/ClientConstants.java | 2 + .../toolkit/forms/client/DatasetClient.java | 19 ++++++ .../forms/service/DatasetClientService.java | 4 ++ .../page/edit/dataset/EditCSVDatasetPage.html | 8 +++ .../page/edit/dataset/EditCSVDatasetPage.java | 67 +++++++++++++++++++ 5 files changed, 100 insertions(+) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java index 7cf30f2b..0ceccbe5 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java @@ -19,6 +19,8 @@ public static final class JobStatus { public final static String PATH_FILTERS = "/admin/filters"; + public final static String PATH_TEMPLATE_DOWNLOAD = "/admin/template/download"; + public final static String PATH_CODE = "/code"; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java index 830e8131..964de18a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java @@ -19,6 +19,7 @@ import java.util.List; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM; import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM_TYPE; import static javax.ws.rs.core.MediaType.MULTIPART_FORM_DATA_TYPE; import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE; @@ -30,6 +31,7 @@ import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_HEALTH; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_JOBS; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_MEASURES; +import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_TEMPLATE_DOWNLOAD; public class DatasetClient { @@ -294,4 +296,21 @@ public List getMeasures() { throw new RuntimeException(("Service is not up")); } + + public byte[] getTemplateDownload() { + if (isUp()) { + Response response = client.target(baseUrl) + .path(PATH_TEMPLATE_DOWNLOAD) + .request(APPLICATION_OCTET_STREAM) + .get(); + + if (response.getStatusInfo().getFamily() == SUCCESSFUL) { + return response.readEntity(byte[].class); + } + + return null; + } + + throw new RuntimeException(("Service is not up")); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java index 0c0800da..93aa0fa4 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java @@ -128,4 +128,8 @@ public List getMeasures(final String serviceName) { return new DatasetClient(service.getUrl()).getMeasures(); } + public byte[] getTemplateDownload(final String serviceName) { + ServiceMetadata service = eurekaClientService.findByName(serviceName); + return new DatasetClient(service.getUrl()).getTemplateDownload(); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.html index 10bea360..72cfbb87 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.html @@ -15,6 +15,14 @@
+
+
+ +
+
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java index 49904b00..ca9fe4b7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java @@ -1,15 +1,24 @@ package org.devgateway.toolkit.forms.wicket.page.edit.dataset; +import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapAjaxButton; +import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; import org.apache.commons.lang3.StringUtils; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.IRequestCycle; +import org.apache.wicket.request.IRequestHandler; +import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.client.DataSetClientException; import org.devgateway.toolkit.forms.service.DatasetClientService; import org.devgateway.toolkit.forms.service.EurekaClientService; +import org.devgateway.toolkit.forms.wicket.components.form.AJAXDownload; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; import org.devgateway.toolkit.forms.wicket.components.form.FileInputBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; @@ -26,6 +35,9 @@ import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.wicketstuff.annotation.mount.MountPath; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.UNPUBLISHING; @@ -86,6 +98,61 @@ protected void onInitialize() { editForm.add(files); editForm.add(getService()); + AJAXDownload downloadTemplateBehaviour = getDownloadTemplateBehaviour(); + editForm.add(downloadTemplateBehaviour); + editForm.add(getDownloadTemplateButton(downloadTemplateBehaviour)); + + } + + private AJAXDownload getDownloadTemplateBehaviour() { + final AJAXDownload download = new AJAXDownload() { + @Override + protected IRequestHandler getHandler() { + return new IRequestHandler() { + @Override + public void respond(final IRequestCycle requestCycle) { + final HttpServletResponse response = (HttpServletResponse) requestCycle.getResponse().getContainerResponse(); + try { + String serviceName = editForm.getModelObject().getDestinationService(); + + final byte[] bytes = datasetClientService.getTemplateDownload(serviceName); + + response.setContentType("text/csv"); + response.setHeader("Content-Disposition", "attachment; filename=" + serviceName + "-template.csv"); + response.getOutputStream().write(bytes); + } catch (IOException e) { + logger.error("Download Template error", e); + } + + RequestCycle.get().scheduleRequestHandlerAfterCurrent(null); + } + + @Override + public void detach(final IRequestCycle requestCycle) { + // do nothing; + } + }; + } + }; + + return download; + } + + private BootstrapAjaxButton getDownloadTemplateButton(final AJAXDownload downloadTemplateBehaviour) { + final LaddaAjaxButton templateDownloadButton = new LaddaAjaxButton("templateDownloadButton", + new Model<>("Template Download"), + Buttons.Type.Warning) { + @Override + protected void onSubmit(final AjaxRequestTarget target) { + super.onSubmit(target); + + // initiate the file download + downloadTemplateBehaviour.initiate(target); + } + }; + templateDownloadButton.setDefaultFormProcessing(false); + templateDownloadButton.setIconType(FontAwesome5IconType.file_csv_s); + return templateDownloadButton; } private Select2ChoiceBootstrapFormComponent getYear() { From d754453ed1a0a79597bd4377e217b7de11470317 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 14 Nov 2022 16:14:42 +0200 Subject: [PATCH 114/137] TOBACCO-1088: Add filters to datasets tables --- .../table/filter/CSVDatasetFilterState.java | 28 +++++++++++++++ .../filter/TetsimDatasetFilterState.java | 36 +++++++++++++++++-- .../lists/dataset/ListCSVDatasetPage.java | 21 +++++++++-- .../lists/dataset/ListTetsimDatasetPage.java | 22 ++++++++++-- .../repository/data/CSVDatasetRepository.java | 3 ++ .../repository/data/DatasetRepository.java | 3 +- .../data/TetsimDatasetRepository.java | 3 ++ .../service/data/CSVDatasetServiceImpl.java | 5 +++ .../service/data/DatasetService.java | 2 ++ .../data/TetsimDatasetServiceImpl.java | 5 +++ 10 files changed, 117 insertions(+), 11 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java index 3a9af2b4..695f9d6b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java @@ -20,6 +20,10 @@ public class CSVDatasetFilterState extends JpaFilterState { private static final long serialVersionUID = -3419455862012018431L; + private Integer year; + + private String status; + private String service; @Override @@ -34,10 +38,34 @@ public Specification getSpecification() { predicates.add(sc.cb().equal(sc.cb().lower(sc.root().get(CSVDataset_.destinationService)), service.toLowerCase())); } + if (year != null) { + predicates.add(sc.cb().equal(sc.root().get(CSVDataset_.year), year)); + } + + if (StringUtils.isNotBlank(status)) { + predicates.add(sc.cb().like(sc.root().get(CSVDataset_.status), status)); + } + return cb.and(predicates.toArray(new Predicate[predicates.size()])); }; } + public Integer getYear() { + return year; + } + + public void setYear(final Integer year) { + this.year = year; + } + + public String getStatus() { + return status; + } + + public void setStatus(final String status) { + this.status = status; + } + public String getService() { return service; } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java index ca895278..b41d09e0 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java @@ -2,8 +2,8 @@ import org.apache.commons.lang3.StringUtils; import org.devgateway.toolkit.persistence.dao.AbstractStatusAuditableEntity_; -import org.devgateway.toolkit.persistence.dao.data.CSVDataset_; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset_; import org.devgateway.toolkit.persistence.repository.SpecificationContext; import org.springframework.data.jpa.domain.Specification; @@ -20,6 +20,10 @@ public class TetsimDatasetFilterState extends JpaFilterState { private static final long serialVersionUID = 6655165533257383853L; + private Integer year; + + private String status; + private String service; @Override @@ -28,11 +32,19 @@ public Specification getSpecification() { List predicates = new ArrayList<>(); SpecificationContext sc = new SpecificationContext<>(root, query, cb); + predicates.add(sc.cb().notLike(sc.root().get(AbstractStatusAuditableEntity_.status), DELETED)); + if (StringUtils.isNotBlank(service)) { - predicates.add(sc.cb().equal(sc.cb().lower(sc.root().get(CSVDataset_.destinationService)), service.toLowerCase())); + predicates.add(sc.cb().equal(sc.cb().lower(sc.root().get(TetsimDataset_.destinationService)), service.toLowerCase())); } - predicates.add(sc.cb().notLike(sc.root().get(AbstractStatusAuditableEntity_.status), DELETED)); + if (year != null) { + predicates.add(sc.cb().equal(sc.root().get(TetsimDataset_.year), year)); + } + + if (StringUtils.isNotBlank(status)) { + predicates.add(sc.cb().like(sc.root().get(TetsimDataset_.status), status)); + } return cb.and(predicates.toArray(new Predicate[predicates.size()])); }; @@ -45,4 +57,22 @@ public String getService() { public void setService(final String service) { this.service = service; } + + public Integer getYear() { + return year; + } + + public void setYear(final Integer year) { + this.year = year; + } + + @Override + public String getStatus() { + return status; + } + + @Override + public void setStatus(final String status) { + this.status = status; + } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java index 151fb1dd..8e527e79 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java @@ -11,6 +11,8 @@ *******************************************************************************/ package org.devgateway.toolkit.forms.wicket.page.lists.dataset; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.filter.BootstrapChoiceFilteredPropertyColumn; +import nl.dries.wicket.hibernate.dozer.DozerListModel; import org.apache.wicket.Component; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; @@ -34,6 +36,8 @@ import java.text.MessageFormat; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.stream.Collectors; import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; @@ -57,9 +61,20 @@ public ListCSVDatasetPage(final PageParameters pageParameters) { columns.clear(); - columns.add(new PropertyColumn<>(new StringResourceModel("year"), "year", "year")); - columns.add(new PropertyColumn<>(new StringResourceModel("status"), "status", "status")); - columns.add(new PropertyColumn<>(new StringResourceModel("description"), "description", "description")); + List datasets = datasetService.findAllNotDeletedForService(service); + List years = datasets.stream() + .map(CSVDataset::getYear).distinct().sorted() + .collect(Collectors.toList()); + columns.add(new BootstrapChoiceFilteredPropertyColumn<>(new StringResourceModel("year"), "year", "year", + new DozerListModel<>(years), "year")); + + List statuses = datasets.stream() + .map(CSVDataset::getStatus).distinct().sorted() + .collect(Collectors.toList()); + columns.add(new BootstrapChoiceFilteredPropertyColumn<>(new StringResourceModel("status"), "status", "status", + new DozerListModel<>(statuses), "status")); + + columns.add(new PropertyColumn<>(new StringResourceModel("description"), "description")); columns.add(new PropertyColumn<>(new StringResourceModel("lastModifiedBy"), "lastModifiedBy", "lastModifiedBy.get")); columns.add(new PropertyColumn(new StringResourceModel("lastModifiedDate"), diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java index fd8d0058..81e0c1b8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java @@ -11,6 +11,8 @@ *******************************************************************************/ package org.devgateway.toolkit.forms.wicket.page.lists.dataset; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.filter.BootstrapChoiceFilteredPropertyColumn; +import nl.dries.wicket.hibernate.dozer.DozerListModel; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; @@ -32,6 +34,7 @@ import org.devgateway.toolkit.forms.wicket.page.edit.dataset.EditTetsimDatasetPage; import org.devgateway.toolkit.forms.wicket.page.lists.AbstractListPage; import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; +import org.devgateway.toolkit.persistence.dao.data.CSVDataset; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.devgateway.toolkit.web.util.SettingsUtils; @@ -43,6 +46,7 @@ import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; import static org.devgateway.toolkit.forms.WebConstants.PARAM_YEAR; @@ -68,9 +72,23 @@ public ListTetsimDatasetPage(final PageParameters pageParameters) { this.jpaService = tetsimDatasetService; this.editPageClass = EditTetsimDatasetPage.class; + String service = pageParameters.get("service").toString(); + columns.clear(); - columns.add(new PropertyColumn<>(new StringResourceModel("year"), "year", "year")); + List datasets = tetsimDatasetService.findAllNotDeletedForService(service); + List years = datasets.stream() + .map(TetsimDataset::getYear).distinct().sorted() + .collect(Collectors.toList()); + columns.add(new BootstrapChoiceFilteredPropertyColumn<>(new StringResourceModel("year"), "year", "year", + new DozerListModel<>(years), "year")); + + List statuses = datasets.stream() + .map(TetsimDataset::getStatus).distinct().sorted() + .collect(Collectors.toList()); + columns.add(new BootstrapChoiceFilteredPropertyColumn<>(new StringResourceModel("status"), "status", "status", + new DozerListModel<>(statuses), "status")); + columns.add(new PropertyColumn<>(new StringResourceModel("lastModifiedBy"), "lastModifiedBy", "lastModifiedBy.get")); columns.add(new PropertyColumn(new StringResourceModel("lastModifiedDate"), @@ -84,10 +102,8 @@ public IModel getDataModel(final IModel rowModel) { return Model.of(modifiedDate.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"))); } }); - columns.add(new PropertyColumn<>(new StringResourceModel("status"), "status", "status")); - String service = pageParameters.get(PARAM_SERVICE).toString(); filterState = new TetsimDatasetFilterState(); filterState.setService(service); diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java index 13b7d981..f1b29d96 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java @@ -21,4 +21,7 @@ public interface CSVDatasetRepository extends DatasetRepository, @Query ("select count(e) from #{#entityName} e where (:year is null or e.year=:year) " + "and e.status not in ('DELETED')") long countByNonPublished(@Param("year") Integer year); + + @Query("select td from CSVDataset td where td.status not like 'DELETED' and td.destinationService like :service") + List findAllNotDeletedForService(@Param("service") String service); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java index b5247d10..411af89d 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/DatasetRepository.java @@ -1,9 +1,7 @@ package org.devgateway.toolkit.persistence.repository.data; import org.devgateway.toolkit.persistence.dao.data.Dataset; -import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; -import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.NoRepositoryBean; import java.util.List; @@ -11,4 +9,5 @@ @NoRepositoryBean public interface DatasetRepository extends BaseJpaRepository { + List findAllNotDeletedForService(String service); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java index 5f93d112..29408d8a 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java @@ -21,4 +21,7 @@ public interface TetsimDatasetRepository extends DatasetRepository findAllNotDeletedForService(@Param("service") String service); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetServiceImpl.java index ffe5e42c..66af8e14 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/CSVDatasetServiceImpl.java @@ -40,6 +40,11 @@ public List findAllDeleted() { return csvDatasetRepository.findAllDeleted(); } + @Override + public List findAllNotDeletedForService(final String service) { + return csvDatasetRepository.findAllNotDeletedForService(service); + } + @Override public List findAllInProgress() { return csvDatasetRepository.findAllInProgress(); diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/DatasetService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/DatasetService.java index 29c730be..e5273ccd 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/DatasetService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/DatasetService.java @@ -10,6 +10,8 @@ public interface DatasetService extends BaseJpaService, Un List findAllDeleted(); + List findAllNotDeletedForService(String service); + List findAllInProgress(); long countByNonPublished(Integer year); diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java index 1b83ff44..1d337037 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java @@ -50,4 +50,9 @@ public long countByNonPublished(final Integer year) { return tetsimDatasetRepository.countByNonPublished(year); } + @Override + public List findAllNotDeletedForService(final String service) { + return tetsimDatasetRepository.findAllNotDeletedForService(service); + } + } From 9ecbfb2d4126eaa31bc7871a75cfadbe7c2cf4b8 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 16 Nov 2022 12:38:58 +0200 Subject: [PATCH 115/137] TOBACCO-1088: Add filters to data lists --- .../admin/BaseServiceEntityService.java | 3 + .../admin/BaseServiceEntityServiceImpl.java | 9 +++ .../filter/ServiceCategoryFilterState.java | 57 ++++++++++++++++ .../filter/ServiceDimensionFilterState.java | 43 ++++++++++++ .../filter/ServiceEntityFilterState.java | 14 ++++ .../filter/ServiceFilterFilterState.java | 57 ++++++++++++++++ .../filter/ServiceMeasureFilterState.java | 57 ++++++++++++++++ .../admin/AbstractListServiceEntityPage.html | 5 +- .../admin/AbstractListServiceEntityPage.java | 47 +++++++++++-- .../admin/ListServiceCategoriesPage.java | 19 ++++-- .../admin/ListServiceDimensionsPage.java | 14 ++-- .../lists/admin/ListServiceFiltersPage.java | 16 +++-- .../lists/admin/ListServiceMeasuresPage.java | 18 +++-- .../lists/admin/ServiceCategoryProvider.java | 12 ---- .../lists/admin/ServiceDimensionProvider.java | 13 ---- .../lists/admin/ServiceFilterProvider.java | 13 ---- .../lists/admin/ServiceMeasureProvider.java | 66 ++----------------- .../admin/SortableServiceEntityProvider.java | 41 +++++++----- 18 files changed, 356 insertions(+), 148 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceCategoryFilterState.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceDimensionFilterState.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceEntityFilterState.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceFilterFilterState.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceMeasureFilterState.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityService.java index 2c016e59..cd8ae903 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityService.java @@ -4,12 +4,15 @@ import org.springframework.stereotype.Service; import java.util.List; +import java.util.function.Predicate; @Service public interface BaseServiceEntityService { List findAll(String serviceName); + List findAll(String serviceName, Predicate spec); + T findOne(String serviceName, Long id); void save(String serviceName, T entity); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityServiceImpl.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityServiceImpl.java index df2ee4de..e493cc03 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityServiceImpl.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityServiceImpl.java @@ -6,6 +6,8 @@ import org.springframework.beans.factory.annotation.Autowired; import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; public abstract class BaseServiceEntityServiceImpl implements BaseServiceEntityService { @@ -14,6 +16,13 @@ public List findAll(final String serviceName) { return serviceEntityClient(serviceName).findAll(); } + @Override + public List findAll(final String serviceName, final Predicate spec) { + return findAll(serviceName).stream() + .filter(spec) + .collect(Collectors.toList()); + } + @Override public T findOne(final String serviceName, final Long id) { return serviceEntityClient(serviceName).findOne(id); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceCategoryFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceCategoryFilterState.java new file mode 100644 index 00000000..3f471e47 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceCategoryFilterState.java @@ -0,0 +1,57 @@ +package org.devgateway.toolkit.forms.wicket.components.table.filter; + +import org.apache.commons.lang3.StringUtils; +import org.devgateway.toolkit.persistence.dto.ServiceCategory; + +import java.util.function.Predicate; + +public class ServiceCategoryFilterState extends ServiceEntityFilterState { + + private String code; + + private String value; + + private String type; + + @Override + public Predicate spec() { + Predicate filter = super.spec(); + if (StringUtils.isNotBlank(code)) { + filter = filter.and((ServiceCategory) -> StringUtils.containsIgnoreCase(ServiceCategory.getCode(), code)); + } + + if (StringUtils.isNotBlank(value)) { + filter = filter.and((ServiceCategory) -> StringUtils.containsIgnoreCase(ServiceCategory.getValue(), value)); + } + + if (StringUtils.isNotBlank(type)) { + filter = filter.and((ServiceCategory) -> StringUtils.containsIgnoreCase(ServiceCategory.getType(), type)); + } + + return filter; + } + + public String getCode() { + return code; + } + + public void setCode(final String code) { + this.code = code; + } + + public String getValue() { + return value; + } + + public void setValue(final String value) { + this.value = value; + } + + public String getType() { + return type; + } + + public void setType(final String type) { + this.type = type; + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceDimensionFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceDimensionFilterState.java new file mode 100644 index 00000000..dace0c96 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceDimensionFilterState.java @@ -0,0 +1,43 @@ +package org.devgateway.toolkit.forms.wicket.components.table.filter; + +import org.apache.commons.lang3.StringUtils; +import org.devgateway.toolkit.persistence.dto.ServiceDimension; + +import java.util.function.Predicate; + +public class ServiceDimensionFilterState extends ServiceEntityFilterState { + + private String code; + + private String value; + + @Override + public Predicate spec() { + Predicate filter = super.spec(); + if (StringUtils.isNotBlank(code)) { + filter = filter.and((ServiceDimension) -> StringUtils.containsIgnoreCase(ServiceDimension.getCode(), code)); + } + + if (StringUtils.isNotBlank(value)) { + filter = filter.and((ServiceDimension) -> StringUtils.containsIgnoreCase(ServiceDimension.getValue(), value)); + } + + return filter; + } + + public String getCode() { + return code; + } + + public void setCode(final String code) { + this.code = code; + } + + public String getValue() { + return value; + } + + public void setValue(final String value) { + this.value = value; + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceEntityFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceEntityFilterState.java new file mode 100644 index 00000000..0dd19673 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceEntityFilterState.java @@ -0,0 +1,14 @@ +package org.devgateway.toolkit.forms.wicket.components.table.filter; + +import org.devgateway.toolkit.persistence.dto.ServiceEntity; + +import java.io.Serializable; +import java.util.function.Predicate; + +public class ServiceEntityFilterState implements Serializable { + + public Predicate spec() { + return (T) -> true; + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceFilterFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceFilterFilterState.java new file mode 100644 index 00000000..8b9d4896 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceFilterFilterState.java @@ -0,0 +1,57 @@ +package org.devgateway.toolkit.forms.wicket.components.table.filter; + +import org.apache.commons.lang3.StringUtils; +import org.devgateway.toolkit.persistence.dto.ServiceFilter; + +import java.util.function.Predicate; + +public class ServiceFilterFilterState extends ServiceEntityFilterState { + + private String code; + + private String value; + + private String fieldType; + + @Override + public Predicate spec() { + Predicate filter = super.spec(); + if (StringUtils.isNotBlank(code)) { + filter = filter.and((ServiceFilter) -> StringUtils.containsIgnoreCase(ServiceFilter.getCode(), code)); + } + + if (StringUtils.isNotBlank(value)) { + filter = filter.and((ServiceFilter) -> StringUtils.containsIgnoreCase(ServiceFilter.getValue(), value)); + } + + if (StringUtils.isNotBlank(fieldType)) { + filter = filter.and((ServiceFilter) -> StringUtils.containsIgnoreCase(ServiceFilter.getFieldType(), fieldType)); + } + + return filter; + } + + public String getCode() { + return code; + } + + public void setCode(final String code) { + this.code = code; + } + + public String getValue() { + return value; + } + + public void setValue(final String value) { + this.value = value; + } + + public String getFieldType() { + return fieldType; + } + + public void setFieldType(final String fieldType) { + this.fieldType = fieldType; + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceMeasureFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceMeasureFilterState.java new file mode 100644 index 00000000..deb19d4d --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceMeasureFilterState.java @@ -0,0 +1,57 @@ +package org.devgateway.toolkit.forms.wicket.components.table.filter; + +import org.apache.commons.lang3.StringUtils; +import org.devgateway.toolkit.persistence.dto.ServiceMeasure; + +import java.util.function.Predicate; + +public class ServiceMeasureFilterState extends ServiceEntityFilterState { + + private String code; + + private String value; + + private String parent; + + @Override + public Predicate spec() { + Predicate filter = super.spec(); + if (StringUtils.isNotBlank(code)) { + filter = filter.and((ServiceMeasure) -> StringUtils.containsIgnoreCase(ServiceMeasure.getCode(), code)); + } + + if (StringUtils.isNotBlank(value)) { + filter = filter.and((ServiceMeasure) -> StringUtils.containsIgnoreCase(ServiceMeasure.getValue(), value)); + } + + if (StringUtils.isNotBlank(parent)) { + filter = filter.and((ServiceCategory) -> StringUtils.containsIgnoreCase(ServiceCategory.getParent(), parent)); + } + + return filter; + } + + public String getCode() { + return code; + } + + public void setCode(final String code) { + this.code = code; + } + + public String getValue() { + return value; + } + + public void setValue(final String value) { + this.value = value; + } + + public String getParent() { + return parent; + } + + public void setParent(final String parent) { + this.parent = parent; + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.html index da324d7e..a83ccfcd 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.html @@ -4,7 +4,10 @@
-
+
+ +
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java index 98adfcda..b8a6df83 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java @@ -7,6 +7,8 @@ import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.FilterToolbar; +import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.IFilteredColumn; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.markup.repeater.Item; @@ -19,6 +21,9 @@ import org.devgateway.toolkit.forms.exceptions.NullServiceEntityServiceException; import org.devgateway.toolkit.forms.service.admin.BaseServiceEntityService; import org.devgateway.toolkit.forms.wicket.components.table.AjaxFallbackBootstrapDataTable; +import org.devgateway.toolkit.forms.wicket.components.table.DataTableAware; +import org.devgateway.toolkit.forms.wicket.components.table.ResettingFilterForm; +import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceEntityFilterState; import org.devgateway.toolkit.forms.wicket.page.BasePage; import org.devgateway.toolkit.forms.wicket.page.edit.admin.AbstractEditServiceEntityPage; import org.devgateway.toolkit.persistence.dto.ServiceEntity; @@ -28,7 +33,7 @@ import java.util.ArrayList; import java.util.List; -public class AbstractListServiceEntityPage extends BasePage { +public abstract class AbstractListServiceEntityPage extends BasePage { private static final long serialVersionUID = 652587400391540726L; @@ -49,11 +54,6 @@ public class AbstractListServiceEntityPage extends Base public AbstractListServiceEntityPage(final PageParameters pageParameters) { super(pageParameters); - - columns = new ArrayList<>(); - columns.add(new PropertyColumn<>(new Model<>("Code"), "code", "code")); - columns.add(new PropertyColumn<>(new Model<>("Value"), "value", "value")); - columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); } @Override @@ -66,6 +66,7 @@ protected void onInitialize() { String serviceName = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); dataProvider = new SortableServiceEntityProvider<>(serviceEntityService, serviceName); + dataProvider.setFilterState(newFilterState()); dataTable = new AjaxFallbackBootstrapDataTable( "table", columns, dataProvider, getPageSize()) { @@ -77,6 +78,17 @@ protected void onPageChanged() { } }; + ResettingFilterForm> filterForm = + new ResettingFilterForm<>("filterForm", dataProvider, dataTable); + filterForm.add(dataTable); + add(filterForm); + + if (hasFilteredColumns()) { + FilterToolbar filterToolbar = new FilterToolbar(dataTable, filterForm); + dataTable.addTopToolbar(filterToolbar); + setDataTableForFilteredColumns(); + } + columns.add(new AbstractColumn(new StringResourceModel("actionsColumn", this, null)) { private static final long serialVersionUID = -7447601118569862123L; @@ -86,8 +98,10 @@ public void populateItem(final Item> cellItem, final String co cellItem.add(getActionPanel(componentId, model)); } }); + } - add(dataTable); + protected ServiceEntityFilterState newFilterState() { + return new ServiceEntityFilterState<>(); } protected int getPageSize() { @@ -131,4 +145,23 @@ protected Label getPageTitle() { String service = getPageParameters().get("service").toString(); return new Label("pageTitle", Model.of(MessageFormat.format(getString("page.title"), service))); } + + private boolean hasFilteredColumns() { + for (IColumn column : columns) { + if (column instanceof IFilteredColumn) { + return true; + } + } + return false; + } + + private void setDataTableForFilteredColumns() { + for (IColumn column : columns) { + if (column instanceof IFilteredColumn && column instanceof DataTableAware) { + if (((DataTableAware) column).getDataTable() == null) { + ((DataTableAware) column).setDataTable(dataTable); + } + } + } + } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java index b4012e98..c2058d03 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java @@ -12,8 +12,8 @@ package org.devgateway.toolkit.forms.wicket.page.lists.admin; import de.agilecoders.wicket.core.markup.html.bootstrap.behavior.CssClassNameAppender; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.filter.BootstrapTextFilteredPropertyColumn; import org.apache.wicket.AttributeModifier; -import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.markup.html.basic.Label; @@ -23,11 +23,11 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.WebConstants; -import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.service.admin.ServiceCategoryService; +import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceCategoryFilterState; +import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceEntityFilterState; import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServiceCategoryPage; import org.devgateway.toolkit.persistence.dto.ServiceCategory; -import org.devgateway.toolkit.persistence.dto.ServiceMeasure; import org.wicketstuff.annotation.mount.MountPath; import java.util.ArrayList; @@ -50,11 +50,11 @@ public ListServiceCategoriesPage(final PageParameters pageParameters) { dataProvider = new ServiceCategoryProvider(serviceCategoryService, service); columns = new ArrayList<>(); - columns.add(new PropertyColumn<>(new Model<>("Value"), "code", "code")); - columns.add(new PropertyColumn<>(new Model<>("System Label"), "value", "value")); - columns.add(new PropertyColumn<>(new Model<>("Type"), "type", "type")); + columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Value"), "code", "code", "code")); + columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("System Label"), "value", "value", "value")); + columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Type"), "type", "type", "type")); columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); - columns.add(new PropertyColumn(new Model<>("Color"), "categoryStyle.color", + columns.add(new PropertyColumn(new Model<>("Color"), null, "categoryStyle.color") { @Override public void populateItem(final Item> item, final String componentId, final IModel rowModel) { @@ -67,4 +67,9 @@ public void populateItem(final Item> item, final }); } + @Override + public ServiceEntityFilterState newFilterState() { + return new ServiceCategoryFilterState(); + } + } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java index ef906031..b822a193 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java @@ -11,16 +11,16 @@ *******************************************************************************/ package org.devgateway.toolkit.forms.wicket.page.lists.admin; -import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.filter.BootstrapTextFilteredPropertyColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.WebConstants; -import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.service.admin.ServiceDimensionService; +import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceDimensionFilterState; +import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceEntityFilterState; import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServiceDimensionPage; -import org.devgateway.toolkit.forms.wicket.page.edit.dataset.EditCSVDatasetPage; import org.devgateway.toolkit.persistence.dto.ServiceDimension; import org.wicketstuff.annotation.mount.MountPath; @@ -44,9 +44,13 @@ public ListServiceDimensionsPage(final PageParameters pageParameters) { dataProvider = new ServiceDimensionProvider(serviceDimensionService, service); columns = new ArrayList<>(); - columns.add(new PropertyColumn<>(new Model<>("Value"), "code", "code")); - columns.add(new PropertyColumn<>(new Model<>("System Label"), "value", "value")); + columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Value"), "code", "code", "code")); + columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("System Label"), "value", "value", "value")); columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); } + @Override + public ServiceEntityFilterState newFilterState() { + return new ServiceDimensionFilterState(); + } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java index 53545e5c..b8648bb5 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java @@ -1,13 +1,14 @@ package org.devgateway.toolkit.forms.wicket.page.lists.admin; -import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.filter.BootstrapTextFilteredPropertyColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.WebConstants; -import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.service.admin.ServiceFilterService; +import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceEntityFilterState; +import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceFilterFilterState; import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServiceFilterPage; import org.devgateway.toolkit.persistence.dto.ServiceFilter; import org.wicketstuff.annotation.mount.MountPath; @@ -32,9 +33,14 @@ public ListServiceFiltersPage(final PageParameters pageParameters) { dataProvider = new ServiceFilterProvider(serviceFilterService, service); columns = new ArrayList<>(); - columns.add(new PropertyColumn<>(new Model<>("Value"), "code", "code")); - columns.add(new PropertyColumn<>(new Model<>("System Label"), "value", "value")); - columns.add(new PropertyColumn<>(new Model<>("Type"), "fieldType", "fieldType")); + columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Value"), "code", "code", "code")); + columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("System Label"), "value", "value", "value")); + columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Type"), "fieldType", "fieldType", "fieldType")); + } + + @Override + public ServiceEntityFilterState newFilterState() { + return new ServiceFilterFilterState(); } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java index de655093..9ffc3640 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java @@ -12,8 +12,8 @@ package org.devgateway.toolkit.forms.wicket.page.lists.admin; import de.agilecoders.wicket.core.markup.html.bootstrap.behavior.CssClassNameAppender; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.filter.BootstrapTextFilteredPropertyColumn; import org.apache.wicket.AttributeModifier; -import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.markup.html.basic.Label; @@ -22,8 +22,9 @@ import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; -import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.service.admin.ServiceMeasureService; +import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceEntityFilterState; +import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceMeasureFilterState; import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServiceMeasurePage; import org.devgateway.toolkit.persistence.dto.ServiceMeasure; import org.wicketstuff.annotation.mount.MountPath; @@ -45,11 +46,11 @@ public ListServiceMeasuresPage(final PageParameters pageParameters) { this.editPageClass = EditServiceMeasurePage.class; columns = new ArrayList<>(); - columns.add(new PropertyColumn<>(new Model<>("Value"), "code", "code")); - columns.add(new PropertyColumn<>(new Model<>("System Label"), "value", "value")); - columns.add(new PropertyColumn<>(new Model<>("Group"), "parent", "parent")); + columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Value"), "code", "code", "code")); + columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("System Label"), "value", "value", "value")); + columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Group"), "parent", "parent", "parent")); columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); - columns.add(new PropertyColumn(new Model<>("Color"), "categoryStyle.color", + columns.add(new PropertyColumn(new Model<>("Color"), null, "categoryStyle.color") { @Override public void populateItem(final Item> item, final String componentId, final IModel rowModel) { @@ -60,4 +61,9 @@ public void populateItem(final Item> item, final } }); } + + @Override + public ServiceEntityFilterState newFilterState() { + return new ServiceMeasureFilterState(); + } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceCategoryProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceCategoryProvider.java index c0a74991..6e73c0fd 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceCategoryProvider.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceCategoryProvider.java @@ -18,16 +18,4 @@ public ServiceCategoryProvider(final BaseServiceEntityService s super(serviceEntityService, serviceName); } - @Override - protected Comparator getServiceEntityComparator() { - return new ServiceCategoryComparator(); - } - - protected class ServiceCategoryComparator implements Comparator { - @Override - public int compare(final ServiceCategory s1, final ServiceCategory s2) { - return String.CASE_INSENSITIVE_ORDER.compare(s1.getCode(), s2.getCode()); - } - } - } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDimensionProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDimensionProvider.java index 27b40f4d..8b7541e8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDimensionProvider.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDimensionProvider.java @@ -25,17 +25,4 @@ public ServiceDimensionProvider(final BaseServiceEntityService final String serviceName) { super(serviceEntityService, serviceName); } - - @Override - protected Comparator getServiceEntityComparator() { - return new ServiceDimensionComparator(); - } - - protected class ServiceDimensionComparator implements Comparator { - @Override - public int compare(final ServiceDimension s1, final ServiceDimension s2) { - return String.CASE_INSENSITIVE_ORDER.compare(s1.getCode(), s2.getCode()); - } - } - } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceFilterProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceFilterProvider.java index dcc53085..b89d93c4 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceFilterProvider.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceFilterProvider.java @@ -18,17 +18,4 @@ public ServiceFilterProvider(final BaseServiceEntityService servi final String serviceName) { super(serviceEntityService, serviceName); } - - @Override - protected Comparator getServiceEntityComparator() { - return new ServiceFilterComparator(); - } - - protected class ServiceFilterComparator implements Comparator { - @Override - public int compare(final ServiceFilter s1, final ServiceFilter s2) { - return String.CASE_INSENSITIVE_ORDER.compare(s1.getCode(), s2.getCode()); - } - } - } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMeasureProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMeasureProvider.java index 47eb8238..72648992 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMeasureProvider.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMeasureProvider.java @@ -1,76 +1,18 @@ package org.devgateway.toolkit.forms.wicket.page.lists.admin; -import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; -import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.devgateway.toolkit.forms.service.DatasetClientService; -import org.devgateway.toolkit.persistence.dto.ServiceDimension; +import org.devgateway.toolkit.forms.service.admin.BaseServiceEntityService; import org.devgateway.toolkit.persistence.dto.ServiceMeasure; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; - /** * Data provider used to provide information about the services * * @author Viorel Chihai */ -public class ServiceMeasureProvider extends SortableDataProvider { +public class ServiceMeasureProvider extends SortableServiceEntityProvider { private static final long serialVersionUID = 1858130875067823547L; - protected DatasetClientService datasetClientService; - - private final String serviceName; - - public ServiceMeasureProvider(final DatasetClientService datasetClientService, final String serviceName) { - this.datasetClientService = datasetClientService; - this.serviceName = serviceName; - } - - @Override - public Iterator iterator(final long first, final long count) { - List services = datasetClientService.getMeasures(serviceName); - - if (first > services.size()) { - return Collections.emptyIterator(); - } - - if (getSort() == null || getSort().getProperty().equals("label")) { - Comparator comparator = new ServiceMeasureComparator(); - - if (getSort() != null && getSort().isAscending()) { - comparator = comparator.reversed(); - } - - Collections.sort(services, comparator); - } - - return services.subList((int) first, (int) Math.min(first + count, services.size())).iterator(); - } - - @Override - public SortParam getSort() { - return super.getSort(); - } - - @Override - public long size() { - return datasetClientService.getMeasures(serviceName).size(); - } - - @Override - public IModel model(final ServiceMeasure serviceMeasure) { - return Model.of(serviceMeasure); - } - - protected class ServiceMeasureComparator implements Comparator { - @Override - public int compare(final ServiceMeasure s1, final ServiceMeasure s2) { - return String.CASE_INSENSITIVE_ORDER.compare(s1.getCode(), s2.getCode()); - } + public ServiceMeasureProvider(BaseServiceEntityService serviceEntityService, final String serviceName) { + super(serviceEntityService, serviceName); } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/SortableServiceEntityProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/SortableServiceEntityProvider.java index 48843ab3..bfcb1ab6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/SortableServiceEntityProvider.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/SortableServiceEntityProvider.java @@ -1,17 +1,16 @@ package org.devgateway.toolkit.forms.wicket.page.lists.admin; -import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; +import org.apache.commons.beanutils.BeanComparator; +import org.apache.commons.collections4.comparators.NullComparator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.IFilterStateLocator; import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; -import org.devgateway.toolkit.forms.service.DatasetClientService; import org.devgateway.toolkit.forms.service.admin.BaseServiceEntityService; -import org.devgateway.toolkit.persistence.dto.ServiceDimension; +import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceEntityFilterState; import org.devgateway.toolkit.persistence.dto.ServiceEntity; -import org.devgateway.toolkit.persistence.service.BaseJpaService; import java.util.Collections; -import java.util.Comparator; import java.util.Iterator; import java.util.List; @@ -20,13 +19,16 @@ * * @author Viorel Chihai */ -public class SortableServiceEntityProvider extends SortableDataProvider { +public class SortableServiceEntityProvider extends SortableDataProvider + implements IFilterStateLocator> { private static final long serialVersionUID = 1858130875067823547L; protected final String serviceName; private final BaseServiceEntityService serviceEntityService; + private ServiceEntityFilterState filterState; + public SortableServiceEntityProvider(final BaseServiceEntityService serviceEntityService, final String serviceName) { this.serviceEntityService = serviceEntityService; this.serviceName = serviceName; @@ -34,20 +36,19 @@ public SortableServiceEntityProvider(final BaseServiceEntityService serviceEn @Override public Iterator iterator(final long first, final long count) { - List entities = serviceEntityService.findAll(serviceName); + List entities = serviceEntityService.findAll(serviceName, filterState.spec()); if (first > entities.size()) { return Collections.emptyIterator(); } - if (getSort() == null || getSort().getProperty().equals("label")) { - Comparator comparator = getServiceEntityComparator(); - - if (getSort() != null && getSort().isAscending()) { - comparator = comparator.reversed(); + if (getSort() != null) { + BeanComparator comparator = new BeanComparator(getSort().getProperty(), new NullComparator(false)); + if (getSort().isAscending()) { + Collections.sort(entities, comparator); + } else { + Collections.sort(entities, comparator.reversed()); } - - Collections.sort(entities, comparator); } return entities.subList((int) first, (int) Math.min(first + count, entities.size())).iterator(); @@ -55,7 +56,7 @@ public Iterator iterator(final long first, final long count) { @Override public long size() { - return serviceEntityService.findAll(serviceName).size(); + return serviceEntityService.findAll(serviceName, filterState.spec()).size(); } @Override @@ -63,7 +64,13 @@ public IModel model(final T object) { return Model.of(object); } - protected Comparator getServiceEntityComparator() { - return Comparator.comparingLong(ServiceEntity::getId); + @Override + public ServiceEntityFilterState getFilterState() { + return filterState; + } + + @Override + public void setFilterState(final ServiceEntityFilterState filterState) { + this.filterState = filterState; } } \ No newline at end of file From 1c437a37d2c971d090711f6b31061111703d34c5 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 24 Nov 2022 18:11:58 +0200 Subject: [PATCH 116/137] TCDIKE-412: Detect testim service based on eureka metadata --- .../org/devgateway/toolkit/forms/WebConstants.java | 3 --- .../toolkit/forms/service/EurekaClientService.java | 5 +++-- .../devgateway/toolkit/forms/wicket/page/DataPage.java | 7 ++----- .../toolkit/forms/wicket/page/DataServicePage.java | 6 ++---- .../toolkit/persistence/dto/ServiceMetadata.java | 10 ++++++++++ 5 files changed, 17 insertions(+), 14 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java index 9629b3c8..485deb3b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/WebConstants.java @@ -71,7 +71,4 @@ public static final class StringValidators { // to change the src code anyway. public static final List AVAILABLE_LOCALES = Collections.unmodifiableList(Arrays.asList(new Locale("en"))); - public static final List ALLOWED_SERVICES_TYPES = Collections.unmodifiableList( - Arrays.asList(SERVICE_DATA_TYPE, SERVICE_TETSIM_TYPE)); - } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java index cbd4cf90..9c78a3fc 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java @@ -11,7 +11,7 @@ import java.util.List; import java.util.stream.Collectors; -import static org.devgateway.toolkit.forms.WebConstants.ALLOWED_SERVICES_TYPES; +import static org.devgateway.toolkit.forms.WebConstants.SERVICE_DATA_TYPE; @Service public class EurekaClientService { @@ -30,6 +30,7 @@ public List findAll() { service.setId(instanceInfo.getId()); service.setType(instance.getMetadata().getOrDefault("type", null)); service.setStatus(instanceInfo.getStatus().toString()); + service.setTetsim(Boolean.valueOf(instanceInfo.getMetadata().getOrDefault("tetsim", "false"))); services.add(service); }); }); @@ -39,7 +40,7 @@ public List findAll() { public List findAllWithData() { return findAll().stream() - .filter(s -> ALLOWED_SERVICES_TYPES.contains(s.getType())) + .filter(s -> SERVICE_DATA_TYPE.equalsIgnoreCase(s.getType())) .collect(Collectors.toList()); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java index 3bd5c801..ce9d7ebe 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java @@ -22,7 +22,6 @@ import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; -import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; @@ -83,13 +82,11 @@ public IModel getDescModel() { } private FontAwesome5IconType getServiceIcon(final ServiceMetadata serviceMetadata) { - if (serviceMetadata.getType().equals(SERVICE_TETSIM_TYPE) || serviceMetadata.getName().equalsIgnoreCase(SERVICE_TETSIM_TYPE)) { + if (serviceMetadata.isTetsim()) { return FontAwesome5IconType.list_alt_r; - } else if (serviceMetadata.getType().equals(SERVICE_DATA_TYPE)) { - return FontAwesome5IconType.file_csv_s; } - throw new IllegalArgumentException("Unknown service type: " + serviceMetadata.getType()); + return FontAwesome5IconType.file_csv_s; } protected Label getPageTitle() { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java index 047d4bfc..3e80d898 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java @@ -76,13 +76,11 @@ private BigLinkDefinition getEntityLink(final String entity, Class getServicePageClass(final ServiceMetadata serviceMetadata) { - if (serviceMetadata.getType().equals(SERVICE_TETSIM_TYPE) || serviceMetadata.getName().equalsIgnoreCase(SERVICE_TETSIM_TYPE)) { + if (serviceMetadata.isTetsim()) { return ListTetsimDatasetPage.class; - } else if (serviceMetadata.getType().equals(SERVICE_DATA_TYPE)) { - return ListCSVDatasetPage.class; } - throw new IllegalArgumentException("Unknown service type: " + serviceMetadata.getType()); + return ListCSVDatasetPage.class; } protected Label getPageTitle() { diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java index b93b8fdd..66d79f4b 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java @@ -18,6 +18,8 @@ public class ServiceMetadata implements Serializable { private String status; + private Boolean tetsim; + private List dimensions = new ArrayList<>(); public String getId() { @@ -80,4 +82,12 @@ public List getDimensions() { public void setDimensions(final List dimensions) { this.dimensions = dimensions; } + + public Boolean isTetsim() { + return tetsim; + } + + public void setTetsim(final Boolean tetsim) { + this.tetsim = tetsim; + } } From 8169e0fa206b21746d9b0f4e080cdaf015556354 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 24 Nov 2022 17:32:18 +0200 Subject: [PATCH 117/137] TOBACCO-1086: Add breadcrumbs --- .../breadcrumbs/BreadCrumbPage.java | 28 ++++ .../breadcrumbs/BreadCrumbPanel.html | 12 ++ .../breadcrumbs/BreadCrumbPanel.java | 135 ++++++++++++++++++ .../components/breadcrumbs/Breadcrumb.java | 72 ++++++++++ .../toolkit/forms/wicket/page/BasePage.html | 1 + .../toolkit/forms/wicket/page/BasePage.java | 50 ++++++- .../forms/wicket/page/BasePage.properties | 13 ++ .../wicket/page/ConfigurationsHomepage.java | 2 + .../toolkit/forms/wicket/page/DataPage.java | 17 ++- .../forms/wicket/page/DataPage.properties | 4 +- .../forms/wicket/page/DataServicePage.java | 7 + .../wicket/page/DataServicePage.properties | 4 +- .../wicket/page/EditAdminSettingsPage.java | 2 + .../page/EditAdminSettingsPage.properties | 4 +- .../toolkit/forms/wicket/page/Homepage.java | 8 ++ .../forms/wicket/page/Homepage.properties | 4 +- .../admin/AbstractEditServiceEntityPage.java | 4 + .../edit/admin/EditServiceCategoryPage.java | 2 + .../edit/admin/EditServiceDimensionPage.java | 3 +- .../edit/admin/EditServiceFilterPage.java | 2 + .../edit/admin/EditServiceMeasurePage.java | 2 + .../page/edit/dataset/EditCSVDatasetPage.java | 6 + .../edit/dataset/EditTetsimDatasetPage.java | 6 + .../wicket/page/lists/AbstractListPage.java | 5 + .../forms/wicket/page/lists/ListUserPage.java | 3 + .../wicket/page/lists/ListUserPage.properties | 2 +- .../admin/AbstractListServiceEntityPage.java | 13 +- .../admin/ListServiceCategoriesPage.java | 3 + .../admin/ListServiceDimensionsPage.java | 3 + .../lists/admin/ListServiceFiltersPage.java | 3 + .../lists/admin/ListServiceMeasuresPage.java | 3 + .../lists/dataset/ListCSVDatasetPage.java | 21 ++- .../lists/dataset/ListTetsimDatasetPage.java | 20 ++- .../forms/wicket/page/user/EditUserPage.java | 2 + .../page/user/EditUserPageElevated.java | 7 + .../forms/wicket/styles/BaseStyles.css | 30 ++++ 36 files changed, 488 insertions(+), 15 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPanel.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPanel.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/Breadcrumb.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPage.java new file mode 100644 index 00000000..7a95c689 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPage.java @@ -0,0 +1,28 @@ +package org.devgateway.toolkit.forms.wicket.components.breadcrumbs; + +import org.devgateway.toolkit.forms.wicket.page.BasePage; +import org.devgateway.toolkit.forms.wicket.page.Homepage; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Used to declare a breadcrumb on a class. + * + * @author Viorel Chihai + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface BreadCrumbPage { + + /** + * The upper level in breadcrumb hierarchy + */ + Class parent() default Homepage.class; + + boolean isRoot() default false; + + String[] params() default {}; +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPanel.html new file mode 100644 index 00000000..6fbd67f5 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPanel.html @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPanel.java new file mode 100644 index 00000000..ac95c982 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPanel.java @@ -0,0 +1,135 @@ +package org.devgateway.toolkit.forms.wicket.components.breadcrumbs; + +import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapBookmarkablePageLink; +import org.apache.wicket.markup.html.WebPage; +import org.apache.wicket.markup.html.list.ListItem; +import org.apache.wicket.markup.html.list.ListView; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.devgateway.toolkit.forms.wicket.page.BasePage; + +import java.util.ArrayList; +import java.util.List; + +import static de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons.Type.Link; + +/** + * A component that renders bread crumbs. + * + *
+ * first / second / third
+ * 
+ * + * @author Viorel Chihai + */ +public abstract class BreadCrumbPanel extends Panel { + + private List breadcrumbs; + + public BreadCrumbPanel(final String id) { + super(id); + } + + @Override + protected void onInitialize() { + super.onInitialize(); + getBreadcrumbs().clear(); + createBreadcrumb(); + + IModel> breadcrumbsModel = new IModel>() { + private static final long serialVersionUID = 1L; + + @Override + public List getObject() { + return getBreadcrumbs(); + } + }; + + ListView breadcrumbList = new ListView("breadcrumb", breadcrumbsModel) { + private static final long serialVersionUID = 1L; + + @Override + protected void populateItem(final ListItem item) { + final Breadcrumb dto = item.getModelObject(); + BootstrapBookmarkablePageLink link = new BootstrapBookmarkablePageLink("bcLink", dto.getPage(), dto.getPageParameters(), Link); + link.setLabel(dto.getLabel()); + item.add(link); + link.setEnabled(dto.isUseLink()); + } + }; + add(breadcrumbList); + } + + public List getBreadcrumbs() { + if (breadcrumbs == null) { + breadcrumbs = new ArrayList<>(); + } + + return breadcrumbs; + } + + public void addBreadcrumb(final Breadcrumb breadcrumb) { + getBreadcrumbs().add(breadcrumb); + } + + protected void createBreadcrumb() { + BreadCrumbPage breadCrumbAnnotation = getPageClass().getDeclaredAnnotation(BreadCrumbPage.class); + if (breadCrumbAnnotation != null) { + if (!breadCrumbAnnotation.isRoot()) { + createParentBreadcrumb(breadCrumbAnnotation.parent()); + } + + Breadcrumb bc = new Breadcrumb(new IModel() { + private static final long serialVersionUID = 1L; + + @Override + public String getObject() { + return getLabelModel().getObject(); + } + }, getPageClass()); + bc.setUseLink(false); + addBreadcrumb(bc); + } + } + + protected void createParentBreadcrumb(final Class clazz) { + if (clazz != null && clazz.getDeclaredAnnotation(BreadCrumbPage.class) != null) { + if (!clazz.getDeclaredAnnotation(BreadCrumbPage.class).isRoot()) { + createParentBreadcrumb(clazz.getDeclaredAnnotation(BreadCrumbPage.class).parent()); + } + + Breadcrumb bc = new Breadcrumb(new IModel() { + private static final long serialVersionUID = 1L; + + @Override + public String getObject() { + return getLabelModel(clazz).getObject(); + } + }, clazz, getBreadcrumbPageParameters(clazz)); + addBreadcrumb(bc); + } + } + + private PageParameters getBreadcrumbPageParameters(final Class clazz) { + String[] params = clazz.getDeclaredAnnotation(BreadCrumbPage.class).params(); + + if (params.length > 0) { + PageParameters pageParameters = new PageParameters(); + String paramValue = this.getPage().getPageParameters().get(params[0]).toString(); + pageParameters.set(params[0], paramValue); + return pageParameters; + } + + return new PageParameters(); + + } + + protected abstract Class getPageClass(); + + protected abstract IModel getLabelModel(); + + protected abstract IModel getLabelModel(Class clazz); + + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/Breadcrumb.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/Breadcrumb.java new file mode 100644 index 00000000..f354dd80 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/Breadcrumb.java @@ -0,0 +1,72 @@ +package org.devgateway.toolkit.forms.wicket.components.breadcrumbs; + +import org.apache.wicket.markup.html.WebPage; +import org.apache.wicket.model.IModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; + +import java.io.Serializable; + +/** + * @author Viorel Chihai + */ +public class Breadcrumb implements Serializable { + + private static final long serialVersionUID = 1L; + + private IModel labelModel; + + private boolean useLink = true; + + private boolean visible = true; + + private Class page; + + PageParameters pageParameters; + + public Breadcrumb(final IModel labelModel, final Class page) { + this(labelModel, page, new PageParameters()); + } + + public Breadcrumb(final IModel labelModel, final Class page, final PageParameters pageParameters) { + this.labelModel = labelModel; + this.page = page; + this.pageParameters = pageParameters; + } + + public IModel getLabel() { + return labelModel; + } + + public void setLabel(final IModel labelModel) { + this.labelModel = labelModel; + } + + public boolean isUseLink() { + return useLink; + } + + public void setUseLink(final boolean useLink) { + this.useLink = useLink; + } + + public boolean isVisible() { + return visible; + } + + public void setVisible(final boolean visible) { + this.visible = visible; + } + + public void setPage(final Class page) { + this.page = page; + } + + public Class getPage() { + return page; + } + + public PageParameters getPageParameters() { + return pageParameters; + } + +} \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.html index 43ccfe44..343eed39 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.html @@ -10,6 +10,7 @@
+
[BREADCRUMB]

[PAGE-TITLE]

diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index be1dd7a0..b0932138 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -34,9 +34,11 @@ import org.apache.wicket.markup.head.filter.HeaderResponseContainer; import org.apache.wicket.markup.html.GenericWebPage; import org.apache.wicket.markup.html.TransparentWebMarkupContainer; +import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.AbstractLink; import org.apache.wicket.markup.html.pages.RedirectPage; +import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.ResourceModel; import org.apache.wicket.model.StringResourceModel; @@ -49,6 +51,8 @@ import org.apache.wicket.util.string.StringValue; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityUtil; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPanel; import org.devgateway.toolkit.forms.wicket.page.lists.ListTestFormPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListUserPage; import org.devgateway.toolkit.forms.wicket.page.user.EditUserPage; @@ -58,6 +62,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -84,6 +89,8 @@ public abstract class BasePage extends GenericWebPage { private Navbar navbar; + protected BreadCrumbPanel breadcrumbPanel; + protected NotificationPanel feedbackPanel; /** @@ -149,6 +156,9 @@ public BasePage(final PageParameters parameters) { navbar = newNavbar("navbar"); mainHeader.add(navbar); + breadcrumbPanel = createBreadcrumbPanel("breadcrumb"); + mainContainer.add(breadcrumbPanel); + // Add information about navbar position on mainHeader element. if (navbar.getPosition().equals(Navbar.Position.DEFAULT)) { mainHeader.add(new CssClassNameAppender("with-navbar-default")); @@ -245,7 +255,6 @@ protected NavbarButton newHomeMenu() { } protected NavbarDropDownButton newConfigurationsMenu() { - // admin menu NavbarDropDownButton configurationsMenu = new NavbarDropDownButton(new StringResourceModel("navbar.configurations", this, null)) { private static final long serialVersionUID = 1L; @@ -330,4 +339,43 @@ public void renderHead(final IHeaderResponse response) { response.render(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(BaseStyles.class, "assets/js/fileupload.js"))); } + + protected BreadCrumbPanel createBreadcrumbPanel(final String markupId) { + return new BreadCrumbPanel(markupId) { + @Override + protected IModel getLabelModel() { + return getBreadcrumbTitleModel(); + } + + @Override + protected IModel getLabelModel(final Class clazz) { + return getBreadcrumbTitleModel(clazz); + } + + @Override + protected Class getPageClass() { + return BasePage.this.getClass(); + } + }; + } + + protected IModel getBreadcrumbTitleModel() { + return new StringResourceModel("page.title", this, null); + } + + protected IModel getBreadcrumbTitleModel(final Class clazz) { + String[] params = clazz.getDeclaredAnnotation(BreadCrumbPage.class).params(); + + if (params.length > 0) { + String paramValue = getPageParameters().get(params[0]).toString(); + return Model.of(MessageFormat.format(getString("breadcrumb." + clazz.getSimpleName()), paramValue)); + } + + return new StringResourceModel("breadcrumb." + clazz.getSimpleName(), this, null) + .setDefaultValue(getBreadcrumbTitleModel()); + } + + private boolean hasBreadcrumbPanel() { + return this.getClass().getDeclaredAnnotation(BreadCrumbPage.class) != null; + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties index 84e48074..7817cc7b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties @@ -36,3 +36,16 @@ fileUnit.KB=KB fileUnit.MB=MB fileUnit.GB=GB fileUnit.TB=TB + +breadcrumb.Homepage=Home +breadcrumb.ConfigurationsHomepage=Configurations +breadcrumb.ListUserPage=Users +breadcrumb.EditAdminSettingsPage=Settings +breadcrumb.DataPage=Data +breadcrumb.DataServicePage={0} +breadcrumb.ListServiceMeasuresPage={0} Measures +breadcrumb.ListServiceDimensionsPage={0} Dimensions +breadcrumb.ListServiceCategoriesPage={0} Categories +breadcrumb.ListServiceFiltersPage={0} Filters +breadcrumb.ListCSVDatasetPage={0} Datasets +breadcrumb.ListTetsimDatasetPage={0} Datasets diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java index 91a501d4..9290477b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/ConfigurationsHomepage.java @@ -11,6 +11,7 @@ import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.page.lists.ListUserPage; import org.devgateway.toolkit.web.util.SettingsUtils; @@ -21,6 +22,7 @@ * */ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) +@BreadCrumbPage public class ConfigurationsHomepage extends BasePage { @SpringBean diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java index 3bd5c801..43354b42 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java @@ -27,6 +27,8 @@ import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; +import org.devgateway.toolkit.persistence.dao.AdminSettings; import org.devgateway.toolkit.persistence.dto.ServiceMetadata; import org.devgateway.toolkit.web.util.SettingsUtils; import org.wicketstuff.annotation.mount.MountPath; @@ -41,7 +43,8 @@ * @author Viorel Chihai */ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) -@MountPath +@MountPath(value = "/dataPage") +@BreadCrumbPage public class DataPage extends BasePage { @SpringBean @@ -93,8 +96,16 @@ private FontAwesome5IconType getServiceIcon(final ServiceMetadata serviceMetadat } protected Label getPageTitle() { - return new Label("pageTitle", new StringResourceModel("page.title", this, - Model.of(settingsUtils.getSetting()))); + return new Label("pageTitle", getPageTitleResourceModel()); + } + + private StringResourceModel getPageTitleResourceModel() { + return new StringResourceModel("page.title", this, (Model.of(settingsUtils.getSetting()))); + } + + @Override + protected IModel getBreadcrumbTitleModel() { + return new StringResourceModel("breadcrumb.title", this); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.properties index f33f4276..201e02ad 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.properties @@ -1,3 +1,5 @@ page.title=${countryName} Data -noServiceError=No data service available. \ No newline at end of file +noServiceError=No data service available. + +breadcrumb.title=Data \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java index c6130d4b..01f275f5 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java @@ -18,6 +18,7 @@ import org.apache.wicket.Page; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; @@ -25,6 +26,7 @@ import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceCategoriesPage; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceDimensionsPage; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceFiltersPage; @@ -53,6 +55,7 @@ */ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) @MountPath +@BreadCrumbPage(parent = DataPage.class, params = {"service"}) public class DataServicePage extends BasePage { @SpringBean @@ -102,4 +105,8 @@ protected Label getPageTitle() { } + protected Model getBreadcrumbTitleModel() { + String service = getPageParameters().get("service").toString(); + return Model.of(MessageFormat.format(getString("breadcrumb.title"), service)); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties index c154f2d7..5874d729 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.properties @@ -13,4 +13,6 @@ categories.label=Categories categories.desc=Manage categories filters.label=Filters -filters.desc=Manage filters \ No newline at end of file +filters.desc=Manage filters + +breadcrumb.title={0} \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java index 974c1d95..2c8f844c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.java @@ -7,6 +7,7 @@ import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.validation.validator.RangeValidator; import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.form.CheckBoxToggleBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; @@ -25,6 +26,7 @@ */ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) @MountPath(value = "/adminsettings") +@BreadCrumbPage(parent = ConfigurationsHomepage.class) public class EditAdminSettingsPage extends AbstractEditPage { private static final long serialVersionUID = 5742724046825803877L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties index 54e451f0..1ea13fb2 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/EditAdminSettingsPage.properties @@ -1,5 +1,5 @@ -page.title=Admin settings -page.title.add=Admin settings +page.title=Settings +page.title.add=Settings systemTitle=System Settings appSettingsTitle=Application Settings rebootServer.label=Enable server reboot warning diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java index 17704020..291d49cf 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.java @@ -4,6 +4,7 @@ import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -11,6 +12,7 @@ import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.wicket.components.BigLinkDefinition; import org.devgateway.toolkit.forms.wicket.components.BigLinksPanel; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServicePage; import org.devgateway.toolkit.web.util.SettingsUtils; @@ -21,6 +23,7 @@ * */ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) +@BreadCrumbPage(isRoot = true) public class Homepage extends BasePage { @SpringBean @@ -43,4 +46,9 @@ protected Label getPageTitle() { return new Label("pageTitle", new StringResourceModel("page.title", this, Model.of(settingsUtils.getSetting()))); } + + @Override + protected IModel getBreadcrumbTitleModel() { + return new StringResourceModel("breadcrumb.title", this, null); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties index fcaafc7c..a091d0ee 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Homepage.properties @@ -4,4 +4,6 @@ data.label=Data data.desc=Upload and edit data, manage the measures, dimensions and categories for each dataset configurations.label=Configurations -configurations.desc=Manage the general configurations of the system \ No newline at end of file +configurations.desc=Manage the general configurations of the system + +breadcrumb.title=Home \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java index 41adb81a..05e5fb00 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java @@ -369,4 +369,8 @@ protected PageParameters getParamsWithServiceInformation() { return pageParams; } + protected IModel getBreadcrumbTitleModel() { + return getTitleModel(); + } + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java index 09665632..5a37a468 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java @@ -5,6 +5,7 @@ import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.service.admin.ServiceCategoryService; import org.devgateway.toolkit.forms.validators.UniqueLanguageTranslationValidator; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.form.ColorPickerBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.admin.panel.ListViewTextTranslationSectionPanel; @@ -13,6 +14,7 @@ import org.wicketstuff.annotation.mount.MountPath; @MountPath(value = "/editServiceCategory") +@BreadCrumbPage(parent = ListServiceCategoriesPage.class, params = {"service"}) public class EditServiceCategoryPage extends AbstractEditServiceEntityPage { private static final long serialVersionUID = -9013029067860834250L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java index a36c4e55..78dcdbb4 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java @@ -4,14 +4,15 @@ import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.service.admin.ServiceDimensionService; import org.devgateway.toolkit.forms.validators.UniqueLanguageTranslationValidator; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.admin.panel.ListViewTextTranslationSectionPanel; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceDimensionsPage; import org.devgateway.toolkit.persistence.dto.ServiceDimension; -import org.springframework.beans.factory.annotation.Autowired; import org.wicketstuff.annotation.mount.MountPath; @MountPath(value = "/editServiceDimension") +@BreadCrumbPage(parent = ListServiceDimensionsPage.class, params = {"service"}) public class EditServiceDimensionPage extends AbstractEditServiceEntityPage { private static final long serialVersionUID = -1594571319284288551L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.java index 6c9fbd5d..7ea9d681 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.java @@ -4,6 +4,7 @@ import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.service.admin.ServiceFilterService; import org.devgateway.toolkit.forms.validators.UniqueLanguageTranslationValidator; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.admin.panel.ListViewTextTranslationSectionPanel; import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServiceFiltersPage; @@ -11,6 +12,7 @@ import org.wicketstuff.annotation.mount.MountPath; @MountPath(value = "/editServiceFilter") +@BreadCrumbPage(parent = ListServiceFiltersPage.class, params = {"service"}) public class EditServiceFilterPage extends AbstractEditServiceEntityPage { private static final long serialVersionUID = -8409084805556720923L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java index c21408cd..c5407afa 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java @@ -5,6 +5,7 @@ import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.service.admin.ServiceMeasureService; import org.devgateway.toolkit.forms.validators.UniqueLanguageTranslationValidator; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.form.ColorPickerBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.admin.panel.ListViewTextTranslationSectionPanel; @@ -13,6 +14,7 @@ import org.wicketstuff.annotation.mount.MountPath; @MountPath(value = "/editServiceMeasure") +@BreadCrumbPage(parent = ListServiceMeasuresPage.class, params = {"service"}) public class EditServiceMeasurePage extends AbstractEditServiceEntityPage { private static final long serialVersionUID = -9013029067860834250L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java index ca9fe4b7..fe60b398 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java @@ -18,6 +18,7 @@ import org.devgateway.toolkit.forms.client.DataSetClientException; import org.devgateway.toolkit.forms.service.DatasetClientService; import org.devgateway.toolkit.forms.service.EurekaClientService; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.form.AJAXDownload; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; import org.devgateway.toolkit.forms.wicket.components.form.FileInputBootstrapFormComponent; @@ -46,6 +47,7 @@ * @author vchihai */ @MountPath(value = "/editCSVDataset") +@BreadCrumbPage(parent = ListCSVDatasetPage.class, params = {"service"}) public class EditCSVDatasetPage extends AbstractEditStatusEntityPage { private static final long serialVersionUID = -5231470856974604314L; @@ -269,4 +271,8 @@ protected PageParameters getParamsWithServiceInformation() { return pageParams; } + + protected IModel getBreadcrumbTitleModel() { + return getTitleModel(); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index d7ee5ea8..2a850f98 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -13,6 +13,7 @@ import org.devgateway.toolkit.forms.client.DataSetClientException; import org.devgateway.toolkit.forms.service.DatasetClientService; import org.devgateway.toolkit.forms.service.EurekaClientService; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; @@ -42,6 +43,7 @@ * @author vchihai */ @MountPath(value = "/editTetsimDataset") +@BreadCrumbPage(parent = ListTetsimDatasetPage.class, params = {"service"}) public class EditTetsimDatasetPage extends AbstractEditStatusEntityPage { private static final long serialVersionUID = -8460878260874111506L; @@ -242,4 +244,8 @@ protected PageParameters getParamsWithServiceInformation() { return pageParams; } + protected IModel getBreadcrumbTitleModel() { + return getTitleModel(); + } + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java index d26d9e14..78d355bb 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java @@ -199,6 +199,7 @@ public ActionPanel(final String id, final IModel model) { if (entity != null) { pageParameters.set(WebConstants.PARAM_ID, entity.getId()); } + addEditLinkPageParameters(pageParameters); editItemPageLink = new BootstrapBookmarkablePageLink<>("edit", editPageClass, pageParameters, Buttons.Type.Info); @@ -212,6 +213,10 @@ public ActionPanel(final String id, final IModel model) { } } + protected void addEditLinkPageParameters(final PageParameters pageParameters) { + + } + protected Component getRevisionsLink(final T entity) { PageParameters revisionsPageParameters = new PageParameters(); revisionsPageParameters.set(WebConstants.PARAM_ID, entity.getId()); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListUserPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListUserPage.java index 9008e40b..c7385734 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListUserPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListUserPage.java @@ -17,6 +17,8 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; +import org.devgateway.toolkit.forms.wicket.page.ConfigurationsHomepage; import org.devgateway.toolkit.forms.wicket.page.user.EditUserPageElevated; import org.devgateway.toolkit.persistence.dao.Person; import org.devgateway.toolkit.persistence.service.PersonService; @@ -24,6 +26,7 @@ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) @MountPath(value = "/listusers") +@BreadCrumbPage(parent = ConfigurationsHomepage.class) public class ListUserPage extends AbstractListPage { private static final long serialVersionUID = 3529738250403399032L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListUserPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListUserPage.properties index e3160c8f..335b2d54 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListUserPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/ListUserPage.properties @@ -9,4 +9,4 @@ # Contributors: # Development Gateway - initial API and implementation ############################################################################### -page.title=User List \ No newline at end of file +page.title=Users \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java index b8a6df83..7397cdec 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java @@ -142,8 +142,7 @@ public ActionPanel(final String id, final IModel model) { } protected Label getPageTitle() { - String service = getPageParameters().get("service").toString(); - return new Label("pageTitle", Model.of(MessageFormat.format(getString("page.title"), service))); + return new Label("pageTitle", getPageTitleModel()); } private boolean hasFilteredColumns() { @@ -164,4 +163,14 @@ private void setDataTableForFilteredColumns() { } } } + + @Override + protected IModel getBreadcrumbTitleModel() { + return getPageTitleModel(); + } + + private Model getPageTitleModel() { + String service = getPageParameters().get("service").toString(); + return Model.of(MessageFormat.format(getString("page.title"), service)); + } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java index c2058d03..eff98f5a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java @@ -24,8 +24,10 @@ import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.service.admin.ServiceCategoryService; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceCategoryFilterState; import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceEntityFilterState; +import org.devgateway.toolkit.forms.wicket.page.DataServicePage; import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServiceCategoryPage; import org.devgateway.toolkit.persistence.dto.ServiceCategory; import org.wicketstuff.annotation.mount.MountPath; @@ -33,6 +35,7 @@ import java.util.ArrayList; @MountPath(value = "/categories") +@BreadCrumbPage(parent = DataServicePage.class, params = {"service"}) public class ListServiceCategoriesPage extends AbstractListServiceEntityPage { private static final long serialVersionUID = -6132847935476573446L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java index b822a193..4db7d13b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java @@ -18,8 +18,10 @@ import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.service.admin.ServiceDimensionService; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceDimensionFilterState; import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceEntityFilterState; +import org.devgateway.toolkit.forms.wicket.page.DataServicePage; import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServiceDimensionPage; import org.devgateway.toolkit.persistence.dto.ServiceDimension; import org.wicketstuff.annotation.mount.MountPath; @@ -27,6 +29,7 @@ import java.util.ArrayList; @MountPath(value = "/dimensions") +@BreadCrumbPage(parent = DataServicePage.class, params = {"service"}) public class ListServiceDimensionsPage extends AbstractListServiceEntityPage { private static final long serialVersionUID = -6132847935476573446L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java index b8648bb5..3efd9731 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java @@ -7,8 +7,10 @@ import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.service.admin.ServiceFilterService; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceEntityFilterState; import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceFilterFilterState; +import org.devgateway.toolkit.forms.wicket.page.DataServicePage; import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServiceFilterPage; import org.devgateway.toolkit.persistence.dto.ServiceFilter; import org.wicketstuff.annotation.mount.MountPath; @@ -16,6 +18,7 @@ import java.util.ArrayList; @MountPath(value = "/filters") +@BreadCrumbPage(parent = DataServicePage.class, params = {"service"}) public class ListServiceFiltersPage extends AbstractListServiceEntityPage { private static final long serialVersionUID = -6619848875255960857L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java index 9ffc3640..da5071a6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java @@ -23,8 +23,10 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.service.admin.ServiceMeasureService; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceEntityFilterState; import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceMeasureFilterState; +import org.devgateway.toolkit.forms.wicket.page.DataServicePage; import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServiceMeasurePage; import org.devgateway.toolkit.persistence.dto.ServiceMeasure; import org.wicketstuff.annotation.mount.MountPath; @@ -32,6 +34,7 @@ import java.util.ArrayList; @MountPath(value = "/measures") +@BreadCrumbPage(parent = DataServicePage.class, params = {"service"}) public class ListServiceMeasuresPage extends AbstractListServiceEntityPage { private static final long serialVersionUID = -6132847935476573446L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java index 8e527e79..8e7ed306 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java @@ -24,9 +24,12 @@ import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.table.filter.CSVDatasetFilterState; import org.devgateway.toolkit.forms.wicket.components.table.filter.JpaFilterState; +import org.devgateway.toolkit.forms.wicket.page.DataServicePage; import org.devgateway.toolkit.forms.wicket.page.edit.dataset.EditCSVDatasetPage; import org.devgateway.toolkit.forms.wicket.page.lists.AbstractListPage; import org.devgateway.toolkit.persistence.dao.data.CSVDataset; @@ -43,6 +46,7 @@ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) @MountPath(value = "/listCSVDataset") +@BreadCrumbPage(parent = DataServicePage.class, params = {"service"}) public class ListCSVDatasetPage extends AbstractListPage { private static final long serialVersionUID = -7425220174797515101L; @@ -123,7 +127,22 @@ public JpaFilterState newFilterState() { protected Label getPageTitle() { String service = getPageParameters().get("service").toString(); - return new Label("pageTitle", Model.of(MessageFormat.format(getString("page.title"), service))); + return new Label("pageTitle", getPageTitleModel()); + } + + @Override + protected IModel getBreadcrumbTitleModel() { + return getPageTitleModel(); + } + + private Model getPageTitleModel() { + String service = getPageParameters().get("service").toString(); + return Model.of(MessageFormat.format(getString("page.title"), service)); + } + + @Override + protected void addEditLinkPageParameters(final PageParameters pageParameters) { + pageParameters.set(WebConstants.PARAM_SERVICE, getPageParameters().get(WebConstants.PARAM_SERVICE)); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java index 81e0c1b8..8b7592d3 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java @@ -27,10 +27,13 @@ import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.table.filter.JpaFilterState; import org.devgateway.toolkit.forms.wicket.components.table.filter.TetsimDatasetFilterState; +import org.devgateway.toolkit.forms.wicket.page.DataServicePage; import org.devgateway.toolkit.forms.wicket.page.edit.dataset.EditTetsimDatasetPage; import org.devgateway.toolkit.forms.wicket.page.lists.AbstractListPage; import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; @@ -53,6 +56,7 @@ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) @MountPath(value = "/listTetsimDataset") +@BreadCrumbPage(parent = DataServicePage.class, params = {"service"}) public class ListTetsimDatasetPage extends AbstractListPage { private static final long serialVersionUID = -324298525712620234L; @SpringBean @@ -229,7 +233,21 @@ public JpaFilterState newFilterState() { protected Label getPageTitle() { String service = getPageParameters().get("service").toString(); - return new Label("pageTitle", Model.of(MessageFormat.format(getString("page.title"), service))); + return new Label("pageTitle", getPageTitleModel()); } + @Override + protected IModel getBreadcrumbTitleModel() { + return getPageTitleModel(); + } + + private Model getPageTitleModel() { + String service = getPageParameters().get("service").toString(); + return Model.of(MessageFormat.format(getString("page.title"), service)); + } + + @Override + protected void addEditLinkPageParameters(final PageParameters pageParameters) { + pageParameters.set(WebConstants.PARAM_SERVICE, getPageParameters().get(WebConstants.PARAM_SERVICE)); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.java index d34014a3..19e4ac0e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPage.java @@ -31,6 +31,7 @@ import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.security.SecurityUtil; import org.devgateway.toolkit.forms.service.SendEmailService; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; import org.devgateway.toolkit.forms.wicket.components.form.CheckBoxToggleBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.components.form.PasswordFieldBootstrapFormComponent; @@ -51,6 +52,7 @@ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) @MountPath(value = "/account") +@BreadCrumbPage public class EditUserPage extends AbstractEditPage { private static final long serialVersionUID = 5208480049061989277L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPageElevated.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPageElevated.java index b7271fa0..08b3cbbf 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPageElevated.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/EditUserPageElevated.java @@ -14,10 +14,13 @@ import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.devgateway.toolkit.forms.security.SecurityConstants; +import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; +import org.devgateway.toolkit.forms.wicket.page.lists.ListUserPage; import org.wicketstuff.annotation.mount.MountPath; @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) @MountPath(value = "/user") +@BreadCrumbPage(parent = ListUserPage.class) public class EditUserPageElevated extends EditUserPage { private static final long serialVersionUID = -5372177614898411737L; @@ -25,4 +28,8 @@ public EditUserPageElevated(final PageParameters parameters) { super(parameters); } + private boolean hasBreadcrumbPanel() { + return this.getClass().getDeclaredAnnotation(BreadCrumbPage.class) != null; + } + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css index 9742e9ee..87f0c704 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BaseStyles.css @@ -320,4 +320,34 @@ button .btn-home-label { margin-top: 10px; margin-bottom: 10px; font-style: italic; +} + +.breadcrumb { + background-color: #ffffff; + padding-top: 20px; + padding-bottom: 0px; + padding-left: 12px; + margin-bottom: 0px; +} + +.breadcrumb .btn-link { + padding-left: 0px; + padding-right: 0px; + font-size: 12px; + font-weight: 700; + margin-left: -7px; + color: #aaaaaa; +} + +.breadcrumb a[disabled=disabled] { + color: #000000; + font-weight: 800; + margin-bottom: 1px; +} + +.breadcrumb > li + li:before { + padding: 0 2px; + color: #aaaaaa; + content: "/\00a0"; + font-weight: 700; } \ No newline at end of file From f178eb557557e31a5e502113b312684fe84aa057 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 7 Dec 2022 14:05:15 +0200 Subject: [PATCH 118/137] TOBACCO-1119: Add a friendly name to the APIs --- .../forms/service/EurekaClientService.java | 1 + .../breadcrumbs/BreadCrumbPage.java | 2 +- .../breadcrumbs/BreadCrumbPanel.java | 9 ++++---- .../toolkit/forms/wicket/page/BasePage.java | 18 ++++++++++++---- .../forms/wicket/page/BasePage.properties | 12 +++++------ .../toolkit/forms/wicket/page/DataPage.java | 5 +++-- .../forms/wicket/page/DataServicePage.java | 9 +++----- .../admin/AbstractEditServiceEntityPage.java | 17 +++++++++++---- .../AbstractEditServiceEntityPage.properties | 6 +++++- .../edit/admin/EditServiceCategoryPage.java | 2 +- .../admin/EditServiceCategoryPage.properties | 6 +++++- .../edit/admin/EditServiceDimensionPage.java | 2 +- .../admin/EditServiceDimensionPage.properties | 6 +++++- .../edit/admin/EditServiceFilterPage.java | 2 +- .../admin/EditServiceFilterPage.properties | 6 +++++- .../edit/admin/EditServiceMeasurePage.java | 2 +- .../admin/EditServiceMeasurePage.properties | 6 +++++- .../page/edit/dataset/EditCSVDatasetPage.java | 2 +- .../edit/dataset/EditTetsimDatasetPage.java | 8 +++---- .../admin/AbstractListServiceEntityPage.java | 21 +++++++++---------- .../admin/ListServiceCategoriesPage.java | 2 +- .../ListServiceCategoriesPage.properties | 3 ++- .../admin/ListServiceDimensionsPage.java | 2 +- .../ListServiceDimensionsPage.properties | 3 ++- .../lists/admin/ListServiceFiltersPage.java | 3 +-- .../admin/ListServiceFiltersPage.properties | 3 ++- .../lists/admin/ListServiceMeasuresPage.java | 2 +- .../admin/ListServiceMeasuresPage.properties | 3 ++- .../lists/dataset/ListCSVDatasetPage.java | 13 +++++------- .../dataset/ListCSVDatasetPage.properties | 3 ++- .../lists/dataset/ListTetsimDatasetPage.java | 12 +++++------ .../dataset/ListTetsimDatasetPage.properties | 4 +++- .../persistence/dto/ServiceMetadata.java | 10 +++++++++ 33 files changed, 127 insertions(+), 78 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java index cbd4cf90..fe7f57f7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java @@ -29,6 +29,7 @@ public List findAll() { service.setUrl(instanceInfo.getHomePageUrl()); service.setId(instanceInfo.getId()); service.setType(instance.getMetadata().getOrDefault("type", null)); + service.setLabel(instance.getMetadata().getOrDefault("label", instanceInfo.getAppName())); service.setStatus(instanceInfo.getStatus().toString()); services.add(service); }); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPage.java index 7a95c689..4dc28322 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPage.java @@ -24,5 +24,5 @@ boolean isRoot() default false; - String[] params() default {}; + boolean hasServiceParam() default false; } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPanel.java index ac95c982..fe1690c1 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPanel.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/breadcrumbs/BreadCrumbPanel.java @@ -13,6 +13,7 @@ import java.util.List; import static de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons.Type.Link; +import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; /** * A component that renders bread crumbs. @@ -112,12 +113,12 @@ public String getObject() { } private PageParameters getBreadcrumbPageParameters(final Class clazz) { - String[] params = clazz.getDeclaredAnnotation(BreadCrumbPage.class).params(); + boolean hasServiceLabel = clazz.getDeclaredAnnotation(BreadCrumbPage.class).hasServiceParam(); - if (params.length > 0) { + if (hasServiceLabel) { PageParameters pageParameters = new PageParameters(); - String paramValue = this.getPage().getPageParameters().get(params[0]).toString(); - pageParameters.set(params[0], paramValue); + String service = this.getPage().getPageParameters().get(PARAM_SERVICE).toString(); + pageParameters.set(PARAM_SERVICE, service); return pageParameters; } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index b0932138..a1b12bc9 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -48,9 +48,11 @@ import org.apache.wicket.request.resource.JavaScriptResourceReference; import org.apache.wicket.request.resource.PackageResourceReference; import org.apache.wicket.resource.JQueryResourceReference; +import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.util.string.StringValue; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityUtil; +import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPanel; import org.devgateway.toolkit.forms.wicket.page.lists.ListTestFormPage; @@ -67,6 +69,7 @@ import java.util.List; import java.util.Locale; +import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; import static org.devgateway.toolkit.forms.security.SecurityConstants.Roles.ROLE_USER; /** @@ -79,6 +82,9 @@ public abstract class BasePage extends GenericWebPage { protected static final Logger logger = LoggerFactory.getLogger(BasePage.class); + @SpringBean + private EurekaClientService eurekaClientService; + private TransparentWebMarkupContainer mainContainer; private Header mainHeader; @@ -364,11 +370,10 @@ protected IModel getBreadcrumbTitleModel() { } protected IModel getBreadcrumbTitleModel(final Class clazz) { - String[] params = clazz.getDeclaredAnnotation(BreadCrumbPage.class).params(); + boolean hasServiceLabel = clazz.getDeclaredAnnotation(BreadCrumbPage.class).hasServiceParam(); - if (params.length > 0) { - String paramValue = getPageParameters().get(params[0]).toString(); - return Model.of(MessageFormat.format(getString("breadcrumb." + clazz.getSimpleName()), paramValue)); + if (hasServiceLabel) { + return Model.of(MessageFormat.format(getString("breadcrumb." + clazz.getSimpleName()), getServiceLabel())); } return new StringResourceModel("breadcrumb." + clazz.getSimpleName(), this, null) @@ -378,4 +383,9 @@ protected IModel getBreadcrumbTitleModel(final Class private boolean hasBreadcrumbPanel() { return this.getClass().getDeclaredAnnotation(BreadCrumbPage.class) != null; } + + protected String getServiceLabel() { + String service = getPageParameters().get(PARAM_SERVICE).toString(); + return eurekaClientService.findByName(service).getLabel(); + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties index 7817cc7b..9a47fb19 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.properties @@ -43,9 +43,9 @@ breadcrumb.ListUserPage=Users breadcrumb.EditAdminSettingsPage=Settings breadcrumb.DataPage=Data breadcrumb.DataServicePage={0} -breadcrumb.ListServiceMeasuresPage={0} Measures -breadcrumb.ListServiceDimensionsPage={0} Dimensions -breadcrumb.ListServiceCategoriesPage={0} Categories -breadcrumb.ListServiceFiltersPage={0} Filters -breadcrumb.ListCSVDatasetPage={0} Datasets -breadcrumb.ListTetsimDatasetPage={0} Datasets +breadcrumb.ListServiceMeasuresPage=Measures +breadcrumb.ListServiceDimensionsPage=Dimensions +breadcrumb.ListServiceCategoriesPage=Categories +breadcrumb.ListServiceFiltersPage=Filters +breadcrumb.ListCSVDatasetPage=Datasets +breadcrumb.ListTetsimDatasetPage=Datasets diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java index 43354b42..fb2c77f4 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataPage.java @@ -36,6 +36,7 @@ import java.util.ArrayList; import java.util.List; +import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; import static org.devgateway.toolkit.forms.WebConstants.SERVICE_DATA_TYPE; import static org.devgateway.toolkit.forms.WebConstants.SERVICE_TETSIM_TYPE; @@ -61,7 +62,7 @@ public DataPage(final PageParameters parameters) { List links = new ArrayList<>(); for (ServiceMetadata service : services) { PageParameters pageParameters = new PageParameters(); - pageParameters.add("service", service.getName()); + pageParameters.add(PARAM_SERVICE, service.getName()); FontAwesome5IconType serviceIcon = getServiceIcon(service); @@ -69,7 +70,7 @@ public DataPage(final PageParameters parameters) { @Override public IModel getLabelModel() { - return Model.of(service.getName()); + return Model.of(service.getLabel()); } @Override diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java index 01f275f5..84bc864b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/DataServicePage.java @@ -18,7 +18,6 @@ import org.apache.wicket.Page; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; @@ -55,7 +54,7 @@ */ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) @MountPath -@BreadCrumbPage(parent = DataPage.class, params = {"service"}) +@BreadCrumbPage(parent = DataPage.class, hasServiceParam = true) public class DataServicePage extends BasePage { @SpringBean @@ -97,16 +96,14 @@ private Class getServicePageClass(final ServiceMetadata serv } protected Label getPageTitle() { - String service = getPageParameters().get("service").toString(); String countryName = settingsUtils.getSetting().getCountryName(); return new Label("pageTitle", - Model.of(MessageFormat.format(getString("page.title"), countryName, service))); + Model.of(MessageFormat.format(getString("page.title"), countryName, getServiceLabel()))); } protected Model getBreadcrumbTitleModel() { - String service = getPageParameters().get("service").toString(); - return Model.of(MessageFormat.format(getString("breadcrumb.title"), service)); + return Model.of(MessageFormat.format(getString("breadcrumb.title"), getServiceLabel())); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java index 05e5fb00..25a45fa2 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java @@ -19,6 +19,7 @@ import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.exceptions.NullListPageClassException; import org.devgateway.toolkit.forms.service.DatasetClientService; +import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.service.admin.BaseServiceEntityService; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapSubmitButton; @@ -80,6 +81,9 @@ public abstract class AbstractEditServiceEntityPage ext protected TextContentModal saveFailedModal; + @SpringBean + protected EurekaClientService eurekaClientService; + public EditForm getEditForm() { return editForm; } @@ -352,11 +356,11 @@ protected void onInitialize() { } protected Model getTitleModel() { - String service = getPageParameters().get(PARAM_SERVICE).toString(); + String serviceLabel = getServiceLabel(); if (entityId == null) { - return Model.of(MessageFormat.format(getString("page.title.add"), service)); + return Model.of(MessageFormat.format(getString("page.title.add"), serviceLabel)); } else { - return Model.of(MessageFormat.format(getString("page.title.edit"), service)); + return Model.of(MessageFormat.format(getString("page.title.edit"), serviceLabel)); } } @@ -370,7 +374,12 @@ protected PageParameters getParamsWithServiceInformation() { } protected IModel getBreadcrumbTitleModel() { - return getTitleModel(); + String serviceLabel = getServiceLabel(); + if (entityId == null) { + return Model.of(MessageFormat.format(getString("breadcrumb.title.add"), serviceLabel)); + } else { + return Model.of(MessageFormat.format(getString("breadcrumb.title.edit"), serviceLabel)); + } } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.properties index 7e2a62e7..9eaa6963 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.properties @@ -15,4 +15,8 @@ page.title.edit=Edit {0} Entity cancelButton=Cancel saveButton=Save formHasErrors=The form has errors or is missing information and cannot be submitted. Please scroll up, fix all the errors (highlighted in red) and re-submit! -error=Error \ No newline at end of file +error=Error + +breadcrumb.title=Edit Entity +breadcrumb.title.add=Add Entity +breadcrumb.title.edit=Edit Entity \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java index 5a37a468..bbff0164 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.java @@ -14,7 +14,7 @@ import org.wicketstuff.annotation.mount.MountPath; @MountPath(value = "/editServiceCategory") -@BreadCrumbPage(parent = ListServiceCategoriesPage.class, params = {"service"}) +@BreadCrumbPage(parent = ListServiceCategoriesPage.class, hasServiceParam = true) public class EditServiceCategoryPage extends AbstractEditServiceEntityPage { private static final long serialVersionUID = -9013029067860834250L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties index 5500cc95..1a62ad81 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceCategoryPage.properties @@ -17,4 +17,8 @@ value.label=System Label position.label=Position type.label=Type color.label=Color in graphic -labels.label=Label Translations \ No newline at end of file +labels.label=Label Translations + +breadcrumb.title=Edit Category +breadcrumb.title.add=Add Category +breadcrumb.title.edit=Edit Category \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java index 78dcdbb4..4eede891 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.java @@ -12,7 +12,7 @@ import org.wicketstuff.annotation.mount.MountPath; @MountPath(value = "/editServiceDimension") -@BreadCrumbPage(parent = ListServiceDimensionsPage.class, params = {"service"}) +@BreadCrumbPage(parent = ListServiceDimensionsPage.class, hasServiceParam = true) public class EditServiceDimensionPage extends AbstractEditServiceEntityPage { private static final long serialVersionUID = -1594571319284288551L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties index 4ed66b55..a2807f26 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceDimensionPage.properties @@ -15,4 +15,8 @@ page.title.edit=Edit {0} Dimension code.label=Value value.label=System Label position.label=Position -labels.label=Labels \ No newline at end of file +labels.label=Labels + +breadcrumb.title=Edit Dimension +breadcrumb.title.add=Add Dimension +breadcrumb.title.edit=Edit Dimension \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.java index 7ea9d681..9a71ee5f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.java @@ -12,7 +12,7 @@ import org.wicketstuff.annotation.mount.MountPath; @MountPath(value = "/editServiceFilter") -@BreadCrumbPage(parent = ListServiceFiltersPage.class, params = {"service"}) +@BreadCrumbPage(parent = ListServiceFiltersPage.class, hasServiceParam = true) public class EditServiceFilterPage extends AbstractEditServiceEntityPage { private static final long serialVersionUID = -8409084805556720923L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.properties index d700d798..a965ce9b 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceFilterPage.properties @@ -15,4 +15,8 @@ page.title.edit=Edit {0} Filter code.label=Value value.label=System Label fieldType.label=Type -labels.label=Labels \ No newline at end of file +labels.label=Labels + +breadcrumb.title=Edit Filter +breadcrumb.title.add=Add Filter +breadcrumb.title.edit=Edit Filter \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java index c5407afa..5c70b3ae 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.java @@ -14,7 +14,7 @@ import org.wicketstuff.annotation.mount.MountPath; @MountPath(value = "/editServiceMeasure") -@BreadCrumbPage(parent = ListServiceMeasuresPage.class, params = {"service"}) +@BreadCrumbPage(parent = ListServiceMeasuresPage.class, hasServiceParam = true) public class EditServiceMeasurePage extends AbstractEditServiceEntityPage { private static final long serialVersionUID = -9013029067860834250L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties index 15f3e3a3..4ce271b3 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServiceMeasurePage.properties @@ -18,4 +18,8 @@ position.label=Position color.label=Color in graphic labels.label=Label Translations parent.label=Group -expression.label=Expression \ No newline at end of file +expression.label=Expression + +breadcrumb.title=Edit Measure +breadcrumb.title.add=Add Measure +breadcrumb.title.edit=Edit Measure \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java index fe60b398..5c692106 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java @@ -47,7 +47,7 @@ * @author vchihai */ @MountPath(value = "/editCSVDataset") -@BreadCrumbPage(parent = ListCSVDatasetPage.class, params = {"service"}) +@BreadCrumbPage(parent = ListCSVDatasetPage.class, hasServiceParam = true) public class EditCSVDatasetPage extends AbstractEditStatusEntityPage { private static final long serialVersionUID = -5231470856974604314L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index 2a850f98..7c9ee99c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -9,7 +9,6 @@ import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; -import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.client.DataSetClientException; import org.devgateway.toolkit.forms.service.DatasetClientService; import org.devgateway.toolkit.forms.service.EurekaClientService; @@ -34,6 +33,7 @@ import java.math.BigDecimal; import static org.devgateway.toolkit.forms.WebConstants.MAXIMUM_PERCENTAGE; +import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; import static org.devgateway.toolkit.forms.WebConstants.PARAM_YEAR; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; @@ -43,7 +43,7 @@ * @author vchihai */ @MountPath(value = "/editTetsimDataset") -@BreadCrumbPage(parent = ListTetsimDatasetPage.class, params = {"service"}) +@BreadCrumbPage(parent = ListTetsimDatasetPage.class, hasServiceParam = true) public class EditTetsimDatasetPage extends AbstractEditStatusEntityPage { private static final long serialVersionUID = -8460878260874111506L; @@ -88,7 +88,7 @@ protected void onInitialize() { editForm.add(new TetsimMarketSharePercentageValidator()); if (editForm.getModelObject().getDestinationService() == null) { - String service = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + String service = getPageParameters().get(PARAM_SERVICE).toString(); editForm.getModelObject().setDestinationService(service); } @@ -239,7 +239,7 @@ protected PageParameters getCancelPageParameters() { protected PageParameters getParamsWithServiceInformation() { PageParameters pageParams = new PageParameters(); // add service to the page parameters - pageParams.add(WebConstants.PARAM_SERVICE, editForm.getModelObject().getDestinationService()); + pageParams.add(PARAM_SERVICE, editForm.getModelObject().getDestinationService()); return pageParams; } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java index 7397cdec..de8a11bf 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java @@ -6,7 +6,6 @@ import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.FilterToolbar; import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.IFilteredColumn; import org.apache.wicket.markup.html.basic.Label; @@ -19,6 +18,7 @@ import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.exceptions.NullServiceEntityServiceException; +import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.service.admin.BaseServiceEntityService; import org.devgateway.toolkit.forms.wicket.components.table.AjaxFallbackBootstrapDataTable; import org.devgateway.toolkit.forms.wicket.components.table.DataTableAware; @@ -30,9 +30,10 @@ import org.devgateway.toolkit.persistence.service.AdminSettingsService; import java.text.MessageFormat; -import java.util.ArrayList; import java.util.List; +import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; + public abstract class AbstractListServiceEntityPage extends BasePage { private static final long serialVersionUID = 652587400391540726L; @@ -42,6 +43,9 @@ public abstract class AbstractListServiceEntityPage ext @SpringBean protected AdminSettingsService adminSettingsService; + @SpringBean + EurekaClientService eurekaClientService; + protected AjaxFallbackBootstrapDataTable dataTable; protected SortableServiceEntityProvider dataProvider; @@ -64,7 +68,7 @@ protected void onInitialize() { throw new NullServiceEntityServiceException(); } - String serviceName = getPageParameters().get(WebConstants.PARAM_SERVICE).toString(); + String serviceName = getPageParameters().get(PARAM_SERVICE).toString(); dataProvider = new SortableServiceEntityProvider<>(serviceEntityService, serviceName); dataProvider.setFilterState(newFilterState()); @@ -131,7 +135,7 @@ public ActionPanel(final String id, final IModel model) { if (entity != null) { pageParameters.set(WebConstants.PARAM_ID, entity.getId()); } - pageParameters.set(WebConstants.PARAM_SERVICE, getPageParameters().get(WebConstants.PARAM_SERVICE)); + pageParameters.set(PARAM_SERVICE, getPageParameters().get(PARAM_SERVICE)); editItemPageLink = new BootstrapBookmarkablePageLink<>("edit", editPageClass, pageParameters, Buttons.Type.Info); @@ -142,7 +146,7 @@ public ActionPanel(final String id, final IModel model) { } protected Label getPageTitle() { - return new Label("pageTitle", getPageTitleModel()); + return new Label("pageTitle", Model.of(MessageFormat.format(getString("page.title"), getServiceLabel()))); } private boolean hasFilteredColumns() { @@ -166,11 +170,6 @@ private void setDataTableForFilteredColumns() { @Override protected IModel getBreadcrumbTitleModel() { - return getPageTitleModel(); - } - - private Model getPageTitleModel() { - String service = getPageParameters().get("service").toString(); - return Model.of(MessageFormat.format(getString("page.title"), service)); + return new StringResourceModel("breadcrumb.title", this); } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java index eff98f5a..64fa3fc7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java @@ -35,7 +35,7 @@ import java.util.ArrayList; @MountPath(value = "/categories") -@BreadCrumbPage(parent = DataServicePage.class, params = {"service"}) +@BreadCrumbPage(parent = DataServicePage.class, hasServiceParam = true) public class ListServiceCategoriesPage extends AbstractListServiceEntityPage { private static final long serialVersionUID = -6132847935476573446L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.properties index 177202fd..bce2fc76 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.properties @@ -1 +1,2 @@ -page.title={0} Categories \ No newline at end of file +page.title={0} Categories +breadcrumb.title=Categories \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java index 4db7d13b..e17a87cb 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java @@ -29,7 +29,7 @@ import java.util.ArrayList; @MountPath(value = "/dimensions") -@BreadCrumbPage(parent = DataServicePage.class, params = {"service"}) +@BreadCrumbPage(parent = DataServicePage.class, hasServiceParam = true) public class ListServiceDimensionsPage extends AbstractListServiceEntityPage { private static final long serialVersionUID = -6132847935476573446L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties index b7369f94..fd533006 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.properties @@ -1 +1,2 @@ -page.title={0} Dimensions \ No newline at end of file +page.title={0} Dimensions +breadcrumb.title=Dimensions \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java index 3efd9731..cace93e7 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java @@ -1,7 +1,6 @@ package org.devgateway.toolkit.forms.wicket.page.lists.admin; import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.filter.BootstrapTextFilteredPropertyColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; @@ -18,7 +17,7 @@ import java.util.ArrayList; @MountPath(value = "/filters") -@BreadCrumbPage(parent = DataServicePage.class, params = {"service"}) +@BreadCrumbPage(parent = DataServicePage.class, hasServiceParam = true) public class ListServiceFiltersPage extends AbstractListServiceEntityPage { private static final long serialVersionUID = -6619848875255960857L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.properties index 5fc86658..82c32ecd 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.properties @@ -1 +1,2 @@ -page.title={0} Filters \ No newline at end of file +page.title={0} Filters +breadcrumb.title=Filters \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java index da5071a6..9919cd2c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java @@ -34,7 +34,7 @@ import java.util.ArrayList; @MountPath(value = "/measures") -@BreadCrumbPage(parent = DataServicePage.class, params = {"service"}) +@BreadCrumbPage(parent = DataServicePage.class, hasServiceParam = true) public class ListServiceMeasuresPage extends AbstractListServiceEntityPage { private static final long serialVersionUID = -6132847935476573446L; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties index d628026c..7ec1e8a8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.properties @@ -1 +1,2 @@ -page.title={0} Measures \ No newline at end of file +page.title={0} Measures +breadcrumb.title=Measures \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java index 8e7ed306..14831bef 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java @@ -24,7 +24,6 @@ import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; -import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityConstants; import org.devgateway.toolkit.forms.wicket.components.breadcrumbs.BreadCrumbPage; import org.devgateway.toolkit.forms.wicket.components.table.filter.CSVDatasetFilterState; @@ -46,7 +45,7 @@ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) @MountPath(value = "/listCSVDataset") -@BreadCrumbPage(parent = DataServicePage.class, params = {"service"}) +@BreadCrumbPage(parent = DataServicePage.class, hasServiceParam = true) public class ListCSVDatasetPage extends AbstractListPage { private static final long serialVersionUID = -7425220174797515101L; @@ -58,7 +57,7 @@ public class ListCSVDatasetPage extends AbstractListPage { public ListCSVDatasetPage(final PageParameters pageParameters) { super(pageParameters); - String service = pageParameters.get("service").toString(); + String service = pageParameters.get(PARAM_SERVICE).toString(); this.jpaService = datasetService; this.editPageClass = EditCSVDatasetPage.class; @@ -126,23 +125,21 @@ public JpaFilterState newFilterState() { } protected Label getPageTitle() { - String service = getPageParameters().get("service").toString(); return new Label("pageTitle", getPageTitleModel()); } @Override protected IModel getBreadcrumbTitleModel() { - return getPageTitleModel(); + return Model.of(MessageFormat.format(getString("breadcrumb.title"), getServiceLabel())); } private Model getPageTitleModel() { - String service = getPageParameters().get("service").toString(); - return Model.of(MessageFormat.format(getString("page.title"), service)); + return Model.of(MessageFormat.format(getString("page.title"), getServiceLabel())); } @Override protected void addEditLinkPageParameters(final PageParameters pageParameters) { - pageParameters.set(WebConstants.PARAM_SERVICE, getPageParameters().get(WebConstants.PARAM_SERVICE)); + pageParameters.set(PARAM_SERVICE, getPageParameters().get(PARAM_SERVICE)); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties index 7feb1946..ebca1222 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.properties @@ -6,4 +6,5 @@ status=Status description=Dataset Description actionsColumn=Action -new=Add new dataset \ No newline at end of file +new=Add new dataset +breadcrumb.title=Datasets \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java index 8b7592d3..d0811113 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java @@ -37,7 +37,6 @@ import org.devgateway.toolkit.forms.wicket.page.edit.dataset.EditTetsimDatasetPage; import org.devgateway.toolkit.forms.wicket.page.lists.AbstractListPage; import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; -import org.devgateway.toolkit.persistence.dao.data.CSVDataset; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.devgateway.toolkit.web.util.SettingsUtils; @@ -56,9 +55,10 @@ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) @MountPath(value = "/listTetsimDataset") -@BreadCrumbPage(parent = DataServicePage.class, params = {"service"}) +@BreadCrumbPage(parent = DataServicePage.class, hasServiceParam = true) public class ListTetsimDatasetPage extends AbstractListPage { private static final long serialVersionUID = -324298525712620234L; + @SpringBean protected SettingsUtils settingsUtils; @@ -76,7 +76,7 @@ public ListTetsimDatasetPage(final PageParameters pageParameters) { this.jpaService = tetsimDatasetService; this.editPageClass = EditTetsimDatasetPage.class; - String service = pageParameters.get("service").toString(); + String service = pageParameters.get(PARAM_SERVICE).toString(); columns.clear(); @@ -232,18 +232,16 @@ public JpaFilterState newFilterState() { } protected Label getPageTitle() { - String service = getPageParameters().get("service").toString(); return new Label("pageTitle", getPageTitleModel()); } @Override protected IModel getBreadcrumbTitleModel() { - return getPageTitleModel(); + return Model.of(MessageFormat.format(getString("breadcrumb.title"), getServiceLabel())); } private Model getPageTitleModel() { - String service = getPageParameters().get("service").toString(); - return Model.of(MessageFormat.format(getString("page.title"), service)); + return Model.of(MessageFormat.format(getString("page.title"), getServiceLabel())); } @Override diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties index 7bb3c79c..ef3cce4c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.properties @@ -8,4 +8,6 @@ actionsColumn=Action year.label=Select Year new=Add new dataset helperTextYear=Select the year and then click on Add new dataset -existingData=There is already a dataset for the selected period. \ No newline at end of file +existingData=There is already a dataset for the selected period. + +breadcrumb.title=Datasets \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java index b93b8fdd..5b85e7da 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java @@ -18,6 +18,8 @@ public class ServiceMetadata implements Serializable { private String status; + private String label; + private List dimensions = new ArrayList<>(); public String getId() { @@ -80,4 +82,12 @@ public List getDimensions() { public void setDimensions(final List dimensions) { this.dimensions = dimensions; } + + public String getLabel() { + return label; + } + + public void setLabel(final String label) { + this.label = label; + } } From d7cc302b8914ddfbc3f4cb04eff329d9e5d766a0 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Fri, 16 Dec 2022 15:08:39 +0200 Subject: [PATCH 119/137] TOBACCO-1095: Configure mail sender when sending mails --- .../forms/service/SendEmailService.java | 28 +++++++++++++++---- .../toolkit/web/application.properties | 3 +- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/SendEmailService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/SendEmailService.java index 06baf338..c9e24aae 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/SendEmailService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/SendEmailService.java @@ -11,8 +11,13 @@ *******************************************************************************/ package org.devgateway.toolkit.forms.service; +import org.apache.commons.lang3.StringUtils; import org.devgateway.toolkit.persistence.dao.Person; +import org.devgateway.toolkit.persistence.service.AdminSettingsService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.MailException; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; @@ -28,10 +33,20 @@ @Component public class SendEmailService { + private static final Logger logger = LoggerFactory.getLogger(SendEmailService.class); + + private final static String DEFAULT_EMAIL_FROM_ADDRESS = "tcdisupport@developmentgateway.org"; + + @Value("${spring.mail.sender}") + private String from; + @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") @Autowired private JavaMailSender javaMailSender; + @Autowired + private AdminSettingsService adminSettingsService; + private SimpleMailMessage templateMessage; /** @@ -43,19 +58,22 @@ public class SendEmailService { * @param newPassword */ public void sendEmailResetPassword(final Person person, final String newPassword) { + String country = adminSettingsService.get().getCountryName(); final SimpleMailMessage msg = new SimpleMailMessage(); + String fromEmail = StringUtils.isNotBlank(from) ? from : DEFAULT_EMAIL_FROM_ADDRESS; msg.setTo(person.getEmail()); - msg.setFrom("support@developmentgateway.org"); - msg.setSubject("Recover your password"); + msg.setFrom(fromEmail); + msg.setSubject("TCDI " + country + " - Recover your password"); msg.setText("Dear " + person.getFirstName() + " " + person.getLastName() + ",\n\n" - + "These are your new login credentials for DGToolkit.\n\n" + "Username: " + person.getUsername() + "\n" + + "These are your new login credentials for TCDI Admin " + country+ ".\n\n" + + "Username: " + person.getUsername() + "\n" + "Password: " + newPassword + "\n\n" + "At login, you will be prompted to change your password to one of your choice.\n\n" + "Thank you,\n" - + "DG Team"); + + "TCDI Team."); try { javaMailSender.send(msg); } catch (MailException e) { - e.printStackTrace(); + logger.error(e.getMessage(), e); } } diff --git a/web/src/main/java/org/devgateway/toolkit/web/application.properties b/web/src/main/java/org/devgateway/toolkit/web/application.properties index 0cb8232d..c1d1b9e5 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/application.properties +++ b/web/src/main/java/org/devgateway/toolkit/web/application.properties @@ -14,11 +14,12 @@ server.port = 8080 management.endpoints.web.base-path=/manage management.endpoints.web.expose=* management.endpoint.shutdown.enabled=true -server.servlet.application-display-name=DG-Toolkit +server.servlet.application-display-name=TCDI-Admin spring.profiles.active=default spring.mail.host=localhost spring.mail.port=25 +spring.mail.sender=tcdisupport@developmentgateway.org # Defines role hierarchy. # Hierarchy is specified as a string. Newline separates rules and > symbol has the meaning of 'includes'. From 6a44285e010c03b1618e9c38ae60458af76cb7fd Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 11 Jan 2023 14:29:56 +0200 Subject: [PATCH 120/137] TOBACCO-1089: Display remote datasets --- .../toolkit/forms/client/DatasetClient.java | 97 ------------ .../forms/client/ServiceDatasetClient.java | 49 +++++++ .../forms/client/ServiceEntityClient.java | 20 ++- .../forms/service/DatasetClientService.java | 5 - .../admin/BaseServiceEntityService.java | 2 + .../admin/BaseServiceEntityServiceImpl.java | 4 + .../service/admin/ServiceDatasetService.java | 6 + .../admin/ServiceDatasetServiceImpl.java | 25 ++++ .../components/modal/ConfirmationModal.java | 2 +- .../filter/ServiceDatasetFilterState.java | 43 ++++++ .../wicket/page/lists/AbstractListPage.html | 6 + .../wicket/page/lists/AbstractListPage.java | 4 + .../lists/admin/ServiceDatasetProvider.java | 18 +++ .../dataset/AbstractListDatasetPage.html | 29 ++++ .../dataset/AbstractListDatasetPage.java | 46 ++++++ .../AbstractListDatasetPage.properties | 2 + .../lists/dataset/ListCSVDatasetPage.java | 10 +- .../dataset/ListRemoteDatasetsPanel.html | 13 ++ .../dataset/ListRemoteDatasetsPanel.java | 138 ++++++++++++++++++ .../ListRemoteDatasetsPanel.properties | 4 + .../lists/dataset/ListTetsimDatasetPage.java | 7 +- .../dataset/RemoteDatasetActionPanel.html | 10 ++ .../dataset/RemoteDatasetActionPanel.java | 53 +++++++ .../RemoteDatasetActionPanel.properties | 2 + .../dataset/RemoveRemoteDatasetModal.java | 11 ++ .../RemoveRemoteDatasetModal.properties | 4 + .../persistence/dto/ServiceDataset.java | 19 +++ 27 files changed, 509 insertions(+), 120 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDatasetClient.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDatasetService.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDatasetServiceImpl.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceDatasetFilterState.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDatasetProvider.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/AbstractListDatasetPage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/AbstractListDatasetPage.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/AbstractListDatasetPage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListRemoteDatasetsPanel.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListRemoteDatasetsPanel.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListRemoteDatasetsPanel.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoteDatasetActionPanel.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoteDatasetActionPanel.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoteDatasetActionPanel.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoveRemoteDatasetModal.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoveRemoteDatasetModal.properties create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceDataset.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java index 964de18a..1d027d63 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java @@ -184,103 +184,6 @@ public List getDimensions() { throw new RuntimeException(("Service is not up")); } - public ServiceDimension getDimensionById(final Long id) { - if (isUp()) { - Response dimensionsResponse = client.target(baseUrl) - .path(PATH_DIMENSIONS) - .path(id.toString()) - .request(APPLICATION_JSON).get(); - - if (dimensionsResponse.getStatusInfo().getFamily() == SUCCESSFUL) { - return dimensionsResponse.readEntity(new GenericType() {}); - } - - return null; - } - - throw new RuntimeException(("Service is not up")); - } - - public void addDimension(final ServiceDimension dimension) { - if (isUp()) { - Response dimensionsResponse = client.target(baseUrl) - .path(PATH_DIMENSIONS) - .request(APPLICATION_JSON) - .post(Entity.entity(dimension, APPLICATION_JSON)); - - if (dimensionsResponse.getStatusInfo().getFamily() != SUCCESSFUL) { - throw new RuntimeException("Error in adding dimension"); - } - } else { - throw new RuntimeException(("Service is not up")); - } - } - - - public void updateDimension(final ServiceDimension dimension) { - if (isUp()) { - Response dimensionsResponse = client.target(baseUrl) - .path(PATH_DIMENSIONS) - .path(dimension.getId().toString()) - .request(APPLICATION_JSON) - .put(Entity.entity(dimension, APPLICATION_JSON)); - - if (dimensionsResponse.getStatusInfo().getFamily() != SUCCESSFUL) { - throw new RuntimeException("Error in updating dimension"); - } - } else { - throw new RuntimeException(("Service is not up")); - } - } - - public ServiceMeasure getMeasureById(final Long id) { - if (isUp()) { - Response measuresResponse = client.target(baseUrl) - .path(PATH_MEASURES) - .path(id.toString()) - .request(APPLICATION_JSON).get(); - - if (measuresResponse.getStatusInfo().getFamily() == SUCCESSFUL) { - return measuresResponse.readEntity(new GenericType() {}); - } - - return null; - } - - throw new RuntimeException(("Service is not up")); - } - - public void addMeasure(final ServiceMeasure measure) { - if (isUp()) { - Response measuresResponse = client.target(baseUrl) - .path(PATH_MEASURES) - .request(APPLICATION_JSON) - .post(Entity.entity(measure, APPLICATION_JSON)); - - if (measuresResponse.getStatusInfo().getFamily() != SUCCESSFUL) { - throw new RuntimeException("Error in adding measure"); - } - } else { - throw new RuntimeException(("Service is not up")); - } - } - - public void updateMeasure(final ServiceMeasure measure) { - if (isUp()) { - Response measuresResponse = client.target(baseUrl) - .path(PATH_MEASURES) - .path(measure.getId().toString()) - .request(APPLICATION_JSON) - .put(Entity.entity(measure, APPLICATION_JSON)); - - if (measuresResponse.getStatusInfo().getFamily() != SUCCESSFUL) { - throw new RuntimeException("Error in updating measure"); - } - } else { - throw new RuntimeException(("Service is not up")); - } - } - public List getMeasures() { if (isUp()) { Response measuresResponse = client.target(baseUrl) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDatasetClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDatasetClient.java new file mode 100644 index 00000000..2d410a55 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDatasetClient.java @@ -0,0 +1,49 @@ +package org.devgateway.toolkit.forms.client; + +import org.devgateway.toolkit.persistence.dto.ServiceDataset; + +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.Response; +import java.util.List; + +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL; + +public class ServiceDatasetClient extends ServiceEntityClient { + + public ServiceDatasetClient(final String baseUrl) { + super(baseUrl); + } + + @Override + public String getEntitiesPath() { + return ClientConstants.PATH_DATASETS; + } + + @Override + protected GenericType getGenericType() { + return new GenericType() {}; + } + + @Override + protected GenericType> getGenericListType() { + return new GenericType>() {}; + } + + public void delete(final ServiceDataset entity) { + if (isUp()) { + Response response = client.target(baseUrl) + .path(getEntitiesPath()) + .path(entity.getCode().toString()) + .request(APPLICATION_JSON) + .delete(); + + if (response.getStatusInfo().getFamily() != SUCCESSFUL) { + throw new RuntimeException("Error in deleting the dataset"); + } + } else { + throw new RuntimeException(("Service is not up")); + } + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceEntityClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceEntityClient.java index 9fd025fb..932d6345 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceEntityClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceEntityClient.java @@ -16,9 +16,9 @@ public abstract class ServiceEntityClient { - private final JerseyClient client; + protected final JerseyClient client; - private final String baseUrl; + protected final String baseUrl; public ServiceEntityClient(final String baseUrl) { this.baseUrl = baseUrl; @@ -91,6 +91,22 @@ public void update(final T entity) { } } + public void delete(final T entity) { + if (isUp()) { + Response response = client.target(baseUrl) + .path(getEntitiesPath()) + .path(entity.getId().toString()) + .request(APPLICATION_JSON) + .delete(); + + if (response.getStatusInfo().getFamily() != SUCCESSFUL) { + throw new RuntimeException("Error in deleting the entity"); + } + } else { + throw new RuntimeException(("Service is not up")); + } + } + public boolean isUp() { Response healthResponse = client.target(baseUrl).path(PATH_HEALTH) .request(APPLICATION_JSON).get(); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java index 93aa0fa4..0bbfcd2c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetClientService.java @@ -123,11 +123,6 @@ private ServiceMetadata getDestinationService(Dataset dataset) { return eurekaClientService.findByName(destinationService); } - public List getMeasures(final String serviceName) { - ServiceMetadata service = eurekaClientService.findByName(serviceName); - return new DatasetClient(service.getUrl()).getMeasures(); - } - public byte[] getTemplateDownload(final String serviceName) { ServiceMetadata service = eurekaClientService.findByName(serviceName); return new DatasetClient(service.getUrl()).getTemplateDownload(); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityService.java index cd8ae903..60ff63ad 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityService.java @@ -19,6 +19,8 @@ public interface BaseServiceEntityService { void update(String serviceName, T entity); + void delete(String serviceName, T entity); + long count(String serviceName); T newInstance(); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityServiceImpl.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityServiceImpl.java index e493cc03..7e82acf5 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityServiceImpl.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/BaseServiceEntityServiceImpl.java @@ -37,6 +37,10 @@ public void update(final String serviceName, final T entity) { serviceEntityClient(serviceName).update(entity); } + public void delete(final String serviceName, final T entity) { + serviceEntityClient(serviceName).delete(entity); + } + @Override public long count(String serviceName) { return 0; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDatasetService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDatasetService.java new file mode 100644 index 00000000..e543ab7f --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDatasetService.java @@ -0,0 +1,6 @@ +package org.devgateway.toolkit.forms.service.admin; + +import org.devgateway.toolkit.persistence.dto.ServiceDataset; + +public interface ServiceDatasetService extends BaseServiceEntityService { +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDatasetServiceImpl.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDatasetServiceImpl.java new file mode 100644 index 00000000..5625fb6d --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/admin/ServiceDatasetServiceImpl.java @@ -0,0 +1,25 @@ +package org.devgateway.toolkit.forms.service.admin; + +import org.devgateway.toolkit.forms.client.ServiceDatasetClient; +import org.devgateway.toolkit.forms.client.ServiceEntityClient; +import org.devgateway.toolkit.forms.service.EurekaClientService; +import org.devgateway.toolkit.persistence.dto.ServiceDataset; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ServiceDatasetServiceImpl extends BaseServiceEntityServiceImpl implements ServiceDatasetService { + + @Autowired + private EurekaClientService eurekaClientService; + + @Override + public ServiceDataset newInstance() { + return new ServiceDataset(); + } + + @Override + protected ServiceEntityClient serviceEntityClient(final String serviceName) { + return new ServiceDatasetClient(eurekaClientService.findByName(serviceName).getUrl()); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/modal/ConfirmationModal.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/modal/ConfirmationModal.java index 5b8b92f7..b880a994 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/modal/ConfirmationModal.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/modal/ConfirmationModal.java @@ -33,7 +33,7 @@ public ConfirmationModal(String markupId, IModel model) { setFadeIn(false); form = new Form("confirmationForm"); - description = new Label("description", new StringResourceModel("description")); + description = new Label("description", new StringResourceModel("description", this).getString()); form.add(description); form.add(getSubmitButton()); form.add(getCancelButton()); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceDatasetFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceDatasetFilterState.java new file mode 100644 index 00000000..8c0095a8 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/ServiceDatasetFilterState.java @@ -0,0 +1,43 @@ +package org.devgateway.toolkit.forms.wicket.components.table.filter; + +import org.apache.commons.lang3.StringUtils; +import org.devgateway.toolkit.persistence.dto.ServiceDataset; + +import java.util.function.Predicate; + +public class ServiceDatasetFilterState extends ServiceEntityFilterState { + + private String code; + + private String value; + + @Override + public Predicate spec() { + Predicate filter = super.spec(); + if (StringUtils.isNotBlank(code)) { + filter = filter.and((ServiceDataset) -> StringUtils.containsIgnoreCase(ServiceDataset.getCode(), code)); + } + + if (StringUtils.isNotBlank(value)) { + filter = filter.and((ServiceDataset) -> StringUtils.containsIgnoreCase(ServiceDataset.getValue(), value)); + } + + return filter; + } + + public String getCode() { + return code; + } + + public void setCode(final String code) { + this.code = code; + } + + public String getValue() { + return value; + } + + public void setValue(final String value) { + this.value = value; + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.html index d7829743..45cf5e15 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.html @@ -2,6 +2,9 @@ + + +
@@ -41,6 +44,9 @@ + + + \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java index 78d355bb..b07bdb27 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java @@ -112,9 +112,13 @@ public ActionPanel getActionPanel(final String id, final IModel model) { protected void onInitialize() { super.onInitialize(); + add(new Fragment("topPage", "topPageTitleFragment", this)); + Fragment fragment = new Fragment("bottomPageFragment", "noBottomPageFragment", this); add(fragment); + add(new Fragment("bottomPage", "bottomPageTitleFragment", this)); + if (jpaService == null) { throw new NullJpaServiceException(); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDatasetProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDatasetProvider.java new file mode 100644 index 00000000..0ce93b6e --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceDatasetProvider.java @@ -0,0 +1,18 @@ +package org.devgateway.toolkit.forms.wicket.page.lists.admin; + +import org.devgateway.toolkit.forms.service.admin.BaseServiceEntityService; +import org.devgateway.toolkit.persistence.dto.ServiceDataset; + +/** + * Data provider used to provide information about the services + * + * @author Viorel Chihai + */ +public class ServiceDatasetProvider extends SortableServiceEntityProvider { + private static final long serialVersionUID = 5486671831226922079L; + + public ServiceDatasetProvider(final BaseServiceEntityService serviceEntityService, + final String serviceName) { + super(serviceEntityService, serviceName); + } +} \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/AbstractListDatasetPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/AbstractListDatasetPage.html new file mode 100644 index 00000000..47866312 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/AbstractListDatasetPage.html @@ -0,0 +1,29 @@ + + + + + + + +
+
+

Local Datasets

+
+
+
+ + +
+
+

Remote Datasets

+
+
+
+
+
+
+
+ + + + \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/AbstractListDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/AbstractListDatasetPage.java new file mode 100644 index 00000000..1761cda3 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/AbstractListDatasetPage.java @@ -0,0 +1,46 @@ +package org.devgateway.toolkit.forms.wicket.page.lists.dataset; + +import org.apache.wicket.Component; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.panel.Fragment; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.devgateway.toolkit.forms.wicket.page.lists.AbstractListPage; +import org.devgateway.toolkit.persistence.dao.GenericPersistable; +import org.devgateway.toolkit.persistence.dao.data.Dataset; + +import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; + +public abstract class AbstractListDatasetPage extends AbstractListPage { + private static final long serialVersionUID = -7637952537702961987L; + + protected Fragment titleFragment; + + public AbstractListDatasetPage(final PageParameters pageParameters) { + super(pageParameters); + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + addTitleFragment(); + } + + protected void addTitleFragment() { + String serviceName = getPageParameters().get(PARAM_SERVICE).toString(); + + titleFragment = new Fragment("topPage", "localDatasetsTitleFragment", + AbstractListDatasetPage.this); + replace(titleFragment); + + titleFragment = new Fragment("bottomPage", "remoteDatasetsTitleFragment", + AbstractListDatasetPage.this); + titleFragment.add(new ListRemoteDatasetsPanel("remoteDatasetsPanel", serviceName)); + replace(titleFragment); + } + + @Override + protected Component getRevisionsLink(final GenericPersistable entity) { + return new WebMarkupContainer("revisions").setVisibilityAllowed(false); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/AbstractListDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/AbstractListDatasetPage.properties new file mode 100644 index 00000000..7a2d6c90 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/AbstractListDatasetPage.properties @@ -0,0 +1,2 @@ +local.datasets=Local Datasets +remote.datasets=Remote Datasets \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java index 14831bef..25055b39 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListCSVDatasetPage.java @@ -13,11 +13,9 @@ import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.filter.BootstrapChoiceFilteredPropertyColumn; import nl.dries.wicket.hibernate.dozer.DozerListModel; -import org.apache.wicket.Component; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; -import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; @@ -30,7 +28,6 @@ import org.devgateway.toolkit.forms.wicket.components.table.filter.JpaFilterState; import org.devgateway.toolkit.forms.wicket.page.DataServicePage; import org.devgateway.toolkit.forms.wicket.page.edit.dataset.EditCSVDatasetPage; -import org.devgateway.toolkit.forms.wicket.page.lists.AbstractListPage; import org.devgateway.toolkit.persistence.dao.data.CSVDataset; import org.devgateway.toolkit.persistence.service.data.CSVDatasetService; import org.wicketstuff.annotation.mount.MountPath; @@ -46,7 +43,7 @@ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) @MountPath(value = "/listCSVDataset") @BreadCrumbPage(parent = DataServicePage.class, hasServiceParam = true) -public class ListCSVDatasetPage extends AbstractListPage { +public class ListCSVDatasetPage extends AbstractListDatasetPage { private static final long serialVersionUID = -7425220174797515101L; @SpringBean @@ -114,11 +111,6 @@ protected void onInitialize() { excelForm.setVisibilityAllowed(false); } - @Override - protected Component getRevisionsLink(final CSVDataset entity) { - return new WebMarkupContainer("revisions").setVisibilityAllowed(false); - } - @Override public JpaFilterState newFilterState() { return filterState; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListRemoteDatasetsPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListRemoteDatasetsPanel.html new file mode 100644 index 00000000..59346424 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListRemoteDatasetsPanel.html @@ -0,0 +1,13 @@ + + + + +
+ +
+
+ +
+ + + \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListRemoteDatasetsPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListRemoteDatasetsPanel.java new file mode 100644 index 00000000..f8e29625 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListRemoteDatasetsPanel.java @@ -0,0 +1,138 @@ +package org.devgateway.toolkit.forms.wicket.page.lists.dataset; + +import de.agilecoders.wicket.core.markup.html.bootstrap.dialog.Modal; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.filter.BootstrapTextFilteredPropertyColumn; +import org.apache.commons.lang3.StringUtils; +import org.apache.wicket.Component; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.service.admin.ServiceDatasetService; +import org.devgateway.toolkit.forms.wicket.components.table.AjaxFallbackBootstrapDataTable; +import org.devgateway.toolkit.forms.wicket.components.table.ResettingFilterForm; +import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceDatasetFilterState; +import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceEntityFilterState; +import org.devgateway.toolkit.forms.wicket.page.lists.admin.ServiceDatasetProvider; +import org.devgateway.toolkit.persistence.dao.data.CSVDataset; +import org.devgateway.toolkit.persistence.dto.ServiceDataset; +import org.devgateway.toolkit.persistence.service.AdminSettingsService; + +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +public class ListRemoteDatasetsPanel extends Panel { + + private String serviceName; + + @SpringBean + protected AdminSettingsService adminSettingsService; + + protected AjaxFallbackBootstrapDataTable dataTable; + + protected ServiceDatasetProvider dataProvider; + + protected List> columns; + + @SpringBean + private ServiceDatasetService serviceDatasetService; + + protected int pageRowNo = 0; + + private Component dialogModalComponent; + + public ListRemoteDatasetsPanel(final String id) { + super(id); + } + + public ListRemoteDatasetsPanel(final String id, final String serviceName) { + super(id); + this.serviceName = serviceName; + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + columns = new ArrayList<>(); + columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Name"), "value", "value", "value")); + columns.add(new PropertyColumn(new Model<>("Date created"), "createdDate", "createdDate") { + @Override + public IModel getDataModel(final IModel rowModel) { + IModel model = super.getDataModel(rowModel); + ZonedDateTime createdDate = (ZonedDateTime) model.getObject(); + return Model.of(createdDate.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"))); + } + }); + columns.add(new AbstractColumn(new StringResourceModel("actionsColumn", this, null)) { + private static final long serialVersionUID = -6185373434402515868L; + + @Override + public void populateItem(final Item> cellItem, final String componentId, + final IModel model) { + cellItem.add(new RemoteDatasetActionPanel(componentId, model) { + @Override + protected void onConfirmationSubmit(final AjaxRequestTarget target) { + serviceDatasetService.delete(serviceName, model.getObject()); + target.add(dataTable); + } + + @Override + protected void onOpenModal(final AjaxRequestTarget target, final Modal modal) { + dialogModalComponent = dialogModalComponent.replaceWith(modal); + target.add(dialogModalComponent); + } + }); + } + + @Override + public String getCssClass() { + return (StringUtils.isNotBlank(super.getCssClass()) ? super.getCssClass() : "") + " col-md-1"; + } + }); + + dataProvider = new ServiceDatasetProvider(serviceDatasetService, serviceName); + dataProvider.setFilterState(new ServiceDatasetFilterState()); + + dataTable = new AjaxFallbackBootstrapDataTable( + "table", columns, dataProvider, getPageSize()) { + private static final long serialVersionUID = 632539691822305263L; + + @Override + protected void onPageChanged() { + pageRowNo = 0; + } + }; + + ResettingFilterForm> filterForm = + new ResettingFilterForm<>("filterForm", dataProvider, dataTable); + filterForm.add(dataTable); + add(filterForm); + + addDialogModal(); + } + + protected void addDialogModal() { + dialogModalComponent = new WebMarkupContainer("dialogModal"); + dialogModalComponent.setOutputMarkupPlaceholderTag(true); + add(this.dialogModalComponent); + } + + protected int getPageSize() { + return adminSettingsService.get().getPageSize(); + } + + public ServiceEntityFilterState newFilterServiceDatasetState() { + return new ServiceDatasetFilterState(); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListRemoteDatasetsPanel.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListRemoteDatasetsPanel.properties new file mode 100644 index 00000000..c9088b90 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListRemoteDatasetsPanel.properties @@ -0,0 +1,4 @@ +name=Name +code=Date Created +remove=Remove +actionsColumn=Action \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java index d0811113..fdac234c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/ListTetsimDatasetPage.java @@ -56,7 +56,7 @@ @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_USER) @MountPath(value = "/listTetsimDataset") @BreadCrumbPage(parent = DataServicePage.class, hasServiceParam = true) -public class ListTetsimDatasetPage extends AbstractListPage { +public class ListTetsimDatasetPage extends AbstractListDatasetPage { private static final long serialVersionUID = -324298525712620234L; @SpringBean @@ -221,11 +221,6 @@ void attachYearParameters(PageParameters pageParameters, Integer year) { } } - @Override - protected Component getRevisionsLink(final TetsimDataset entity) { - return new WebMarkupContainer("revisions").setVisibilityAllowed(false); - } - @Override public JpaFilterState newFilterState() { return new TetsimDatasetFilterState(); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoteDatasetActionPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoteDatasetActionPanel.html new file mode 100644 index 00000000..cfe64654 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoteDatasetActionPanel.html @@ -0,0 +1,10 @@ + + + + +
+ +
+
+ + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoteDatasetActionPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoteDatasetActionPanel.java new file mode 100644 index 00000000..66a4295f --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoteDatasetActionPanel.java @@ -0,0 +1,53 @@ +package org.devgateway.toolkit.forms.wicket.page.lists.dataset; + +import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapAjaxButton; +import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; +import de.agilecoders.wicket.core.markup.html.bootstrap.dialog.Modal; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.StringResourceModel; +import org.devgateway.toolkit.persistence.dto.ServiceDataset; + +public abstract class RemoteDatasetActionPanel extends Panel { + + public RemoteDatasetActionPanel(final String id, final IModel model) { + super(id, model); + + Form form = new Form("actionForm"); + add(form); + + BootstrapAjaxButton reject = new BootstrapAjaxButton("remove", + new StringResourceModel("remove"), Buttons.Type.Danger) { + @Override + public void onSubmit(final AjaxRequestTarget target) { + openRemoveModal(target, model); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + } + }; + form.add(reject); + } + + private void openRemoveModal(final AjaxRequestTarget target, final IModel model) { + Modal removeModal = new RemoveRemoteDatasetModal("dialogModal", model) { + @Override + protected void onSubmit(final AjaxRequestTarget target) { + super.onSubmit(target); + onConfirmationSubmit(target); + } + }; + removeModal.show(true); + + onOpenModal(target, removeModal); + } + + protected abstract void onConfirmationSubmit(AjaxRequestTarget target); + + protected abstract void onOpenModal(AjaxRequestTarget target, Modal modal); + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoteDatasetActionPanel.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoteDatasetActionPanel.properties new file mode 100644 index 00000000..c856d125 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoteDatasetActionPanel.properties @@ -0,0 +1,2 @@ +createdDate=Created Date +remove=Remove \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoveRemoteDatasetModal.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoveRemoteDatasetModal.java new file mode 100644 index 00000000..f47ac6ff --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoveRemoteDatasetModal.java @@ -0,0 +1,11 @@ +package org.devgateway.toolkit.forms.wicket.page.lists.dataset; + +import org.apache.wicket.model.IModel; +import org.devgateway.toolkit.forms.wicket.components.modal.ConfirmationModal; +import org.devgateway.toolkit.persistence.dto.ServiceDataset; + +public class RemoveRemoteDatasetModal extends ConfirmationModal { + public RemoveRemoteDatasetModal(final String markupId, final IModel model) { + super(markupId, model); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoveRemoteDatasetModal.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoveRemoteDatasetModal.properties new file mode 100644 index 00000000..4f8a9374 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/dataset/RemoveRemoteDatasetModal.properties @@ -0,0 +1,4 @@ +header=Remove Dataset +description=Are you sure you want to remove it? The dataset will no longer be visible in wordpress. +submit=Yes +cancel=No diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceDataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceDataset.java new file mode 100644 index 00000000..a704f5ca --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceDataset.java @@ -0,0 +1,19 @@ +package org.devgateway.toolkit.persistence.dto; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.time.ZonedDateTime; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServiceDataset extends ServiceCategory { + + private ZonedDateTime createdDate; + + public ZonedDateTime getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(final ZonedDateTime createdDate) { + this.createdDate = createdDate; + } +} From 5ded93ac5ea475b6c6c1a3d00ce98907be8cf56e Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 18 Jan 2023 15:34:57 +0200 Subject: [PATCH 121/137] TOBACCO-1162: Add Baseline Tax Burden as a separate measure --- .../persistence/dto/TetsimExportOutput.java | 55 +++++++++++++------ .../toolkit/persistence/dto/TetsimOutput.java | 10 ++++ .../service/tetsim/TetsimOutputService.java | 11 ++-- .../tetsim/TetsimOutputBaseCalculator.java | 5 ++ 4 files changed, 59 insertions(+), 22 deletions(-) diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java index 579c6f1c..9178ad4e 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java @@ -33,6 +33,8 @@ public class TetsimExportOutput implements Serializable { private Double totalTaxBurdenOvershift; + private Double baselineTotalTaxBurdenOvershift; + private Double retailPriceOvershift; private Double notOvershift; @@ -59,6 +61,8 @@ public class TetsimExportOutput implements Serializable { private Double totalTaxBurdenUndershift; + private Double baselineTotalTaxBurdenUndershift; + private Double retailPriceUndershift; private Double notUndershift; @@ -72,23 +76,24 @@ public class TetsimExportOutput implements Serializable { public TetsimExportOutput() { } - public TetsimExportOutput(TetsimOutput overShfit, TetsimOutput underShift) { - this.year = overShfit.getYear(); - this.taxChange = overShfit.getTaxChange(); - this.tobaccoProduct = overShfit.getTobaccoProduct(); - this.legalConsumptionOvershift = overShfit.getLegalConsumption(); - this.legalConsumptionChangeOvershift = overShfit.getLegalConsumptionChange(); - this.consumptionIllicitOvershift = overShfit.getConsumptionIllicit(); - this.exciseRevOvershift = overShfit.getExciseRev(); - this.exciseRevChangeOvershift = overShfit.getExciseRevChange(); - this.totalGovRevOvershift = overShfit.getTotalGovRev(); - this.exciseBurdenOvershift = overShfit.getExciseBurden(); - this.totalTaxBurdenOvershift = overShfit.getTotalTaxBurden(); - this.retailPriceOvershift = overShfit.getRetailPrice(); - this.notOvershift = overShfit.getNot(); - this.exciseTaxOvershift = overShfit.getExciseTax(); - this.vatOvershift = overShfit.getVat(); - this.levyOvershift = overShfit.getLevy(); + public TetsimExportOutput(TetsimOutput overShift, TetsimOutput underShift) { + this.year = overShift.getYear(); + this.taxChange = overShift.getTaxChange(); + this.tobaccoProduct = overShift.getTobaccoProduct(); + this.legalConsumptionOvershift = overShift.getLegalConsumption(); + this.legalConsumptionChangeOvershift = overShift.getLegalConsumptionChange(); + this.consumptionIllicitOvershift = overShift.getConsumptionIllicit(); + this.exciseRevOvershift = overShift.getExciseRev(); + this.exciseRevChangeOvershift = overShift.getExciseRevChange(); + this.totalGovRevOvershift = overShift.getTotalGovRev(); + this.exciseBurdenOvershift = overShift.getExciseBurden(); + this.totalTaxBurdenOvershift = overShift.getTotalTaxBurden(); + this.baselineTotalTaxBurdenOvershift = overShift.getTotalTaxBurdenBaseline(); + this.retailPriceOvershift = overShift.getRetailPrice(); + this.notOvershift = overShift.getNot(); + this.exciseTaxOvershift = overShift.getExciseTax(); + this.vatOvershift = overShift.getVat(); + this.levyOvershift = overShift.getLevy(); this.legalConsumptionUndershift = underShift.getLegalConsumption(); this.legalConsumptionChangeUndershift = underShift.getLegalConsumptionChange(); this.consumptionIllicitUndershift = underShift.getConsumptionIllicit(); @@ -97,6 +102,7 @@ public TetsimExportOutput(TetsimOutput overShfit, TetsimOutput underShift) { this.totalGovRevUndershift = underShift.getTotalGovRev(); this.exciseBurdenUndershift = underShift.getExciseBurden(); this.totalTaxBurdenUndershift = underShift.getTotalTaxBurden(); + this.baselineTotalTaxBurdenUndershift = underShift.getTotalTaxBurdenBaseline(); this.retailPriceUndershift = underShift.getRetailPrice(); this.notUndershift = underShift.getNot(); this.exciseTaxUndershift = underShift.getExciseTax(); @@ -336,4 +342,19 @@ public void setLevyUndershift(final Double levyUndershift) { this.levyUndershift = levyUndershift; } + public Double getBaselineTotalTaxBurdenOvershift() { + return baselineTotalTaxBurdenOvershift; + } + + public void setBaselineTotalTaxBurdenOvershift(final Double baselineTotalTaxBurdenOvershift) { + this.baselineTotalTaxBurdenOvershift = baselineTotalTaxBurdenOvershift; + } + + public Double getBaselineTotalTaxBurdenUndershift() { + return baselineTotalTaxBurdenUndershift; + } + + public void setBaselineTotalTaxBurdenUndershift(final Double baselineTotalTaxBurdenUndershift) { + this.baselineTotalTaxBurdenUndershift = baselineTotalTaxBurdenUndershift; + } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java index edc5d339..1c38fc0d 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimOutput.java @@ -35,6 +35,8 @@ public class TetsimOutput implements Serializable { private Double totalTaxBurden; + private Double totalTaxBurdenBaseline; + private Double retailPrice; private Double not; @@ -180,4 +182,12 @@ public Double getExciseRevChange() { public void setExciseRevChange(final Double exciseRevChange) { this.exciseRevChange = exciseRevChange; } + + public Double getTotalTaxBurdenBaseline() { + return totalTaxBurdenBaseline; + } + + public void setTotalTaxBurdenBaseline(final Double totalTaxBurdenBaseline) { + this.totalTaxBurdenBaseline = totalTaxBurdenBaseline; + } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java index c00013c9..05717b59 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java @@ -33,11 +33,12 @@ public class TetsimOutputService { public static final List TETSIM_CSV_FIELDS = new ImmutableList.Builder() .add("year", "taxChange", "tobaccoProduct", "legalConsumptionOvershift", "legalConsumptionChangeOvershift", "consumptionIllicitOvershift", "exciseRevOvershift", "exciseRevChangeOvershift", - "totalGovRevOvershift", "exciseBurdenOvershift", "totalTaxBurdenOvershift", "retailPriceOvershift", - "notOvershift", "exciseTaxOvershift", "vatOvershift", "levyOvershift", - "legalConsumptionUndershift", "legalConsumptionChangeUndershift","consumptionIllicitUndershift", - "exciseRevUndershift", "exciseRevChangeUndershift", "totalGovRevUndershift", "exciseBurdenUndershift", - "totalTaxBurdenUndershift", "retailPriceUndershift", "notUndershift", "exciseTaxUndershift", + "totalGovRevOvershift", "exciseBurdenOvershift", "totalTaxBurdenOvershift", + "baselineTotalTaxBurdenOvershift", "retailPriceOvershift", "notOvershift", "exciseTaxOvershift", + "vatOvershift", "levyOvershift", "legalConsumptionUndershift", "legalConsumptionChangeUndershift", + "consumptionIllicitUndershift", "exciseRevUndershift", "exciseRevChangeUndershift", + "totalGovRevUndershift", "exciseBurdenUndershift", "totalTaxBurdenUndershift", + "baselineTotalTaxBurdenUndershift", "retailPriceUndershift", "notUndershift", "exciseTaxUndershift", "vatUndershift", "levyUndershift") .build(); @Autowired diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java index a537a9bf..5753e5e0 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputBaseCalculator.java @@ -85,6 +85,7 @@ public TetsimOutput calculate(TobaccoProduct tobaccoProduct) { tetsimOutput.setExciseBurden(calculateOutputExciseBurden(tobaccoProduct)); tetsimOutput.setTotalTaxBurden(calculateOutputTotalTaxBurden(tobaccoProduct)); + tetsimOutput.setTotalTaxBurdenBaseline(calculateOutputBaselineTotalTaxBurden(tobaccoProduct)); tetsimOutput.setRetailPrice(calculateOutputRetailPrice(tobaccoProduct)); tetsimOutput.setNot(calculateOutputNot(tobaccoProduct)); tetsimOutput.setExciseTax(calculateOutputExciseTax(tobaccoProduct)); @@ -94,6 +95,10 @@ public TetsimOutput calculate(TobaccoProduct tobaccoProduct) { return tetsimOutput; } + private double calculateOutputBaselineTotalTaxBurden(final TobaccoProduct tobaccoProduct) { + return calculateBaselineTotalTaxBurden(tobaccoProduct).doubleValue(); + } + public Double calculateOutputLegalConsumption() { return calculateTotalLegalConsumption().doubleValue(); } From 4163c46be20d4efb8fe58c00149e6bd4b237dada Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Sat, 18 Feb 2023 17:10:48 +0200 Subject: [PATCH 122/137] TCDIDRC-86: Add tranlations columns to the entities tables --- .../admin/AbstractListServiceEntityPage.java | 17 +++++++++++++++-- .../lists/admin/ListServiceCategoriesPage.java | 11 ++++++++++- .../lists/admin/ListServiceDimensionsPage.java | 11 ++++++++++- .../lists/admin/ListServiceFiltersPage.java | 10 ++++++++++ .../lists/admin/ListServiceMeasuresPage.java | 9 ++++++++- 5 files changed, 53 insertions(+), 5 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java index de8a11bf..8f6c48e6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/AbstractListServiceEntityPage.java @@ -11,6 +11,7 @@ import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.markup.repeater.RepeatingView; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.StringResourceModel; @@ -26,15 +27,17 @@ import org.devgateway.toolkit.forms.wicket.components.table.filter.ServiceEntityFilterState; import org.devgateway.toolkit.forms.wicket.page.BasePage; import org.devgateway.toolkit.forms.wicket.page.edit.admin.AbstractEditServiceEntityPage; -import org.devgateway.toolkit.persistence.dto.ServiceEntity; +import org.devgateway.toolkit.persistence.dto.ServiceCategory; +import org.devgateway.toolkit.persistence.dto.ServiceTextTranslation; import org.devgateway.toolkit.persistence.service.AdminSettingsService; import java.text.MessageFormat; import java.util.List; +import static java.util.Comparator.comparing; import static org.devgateway.toolkit.forms.WebConstants.PARAM_SERVICE; -public abstract class AbstractListServiceEntityPage extends BasePage { +public abstract class AbstractListServiceEntityPage extends BasePage { private static final long serialVersionUID = 652587400391540726L; @@ -168,6 +171,16 @@ private void setDataTableForFilteredColumns() { } } + protected RepeatingView getLableTranslations(final String componentId, final IModel rowModel) { + RepeatingView labelsList = new RepeatingView(componentId); + rowModel.getObject().getLabels().stream().sorted(comparing(ServiceTextTranslation::getLanguage)) + .forEach(label -> { + Label labelItem = new Label(labelsList.newChildId(), label.getLanguage() + ": " + label.getText()); + labelsList.add(labelItem); + }); + return labelsList; + } + @Override protected IModel getBreadcrumbTitleModel() { return new StringResourceModel("breadcrumb.title", this); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java index 64fa3fc7..87514b14 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceCategoriesPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2015 Development Gateway, Inc and others. + * Copyright (c) 2023 Development Gateway, Inc and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) @@ -55,8 +55,17 @@ public ListServiceCategoriesPage(final PageParameters pageParameters) { columns = new ArrayList<>(); columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Value"), "code", "code", "code")); columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("System Label"), "value", "value", "value")); + + columns.add(new PropertyColumn(new Model<>("Label Translations"), null, "labels") { + @Override + public void populateItem(final Item> item, final String componentId, final IModel rowModel) { + item.add(getLableTranslations(componentId, rowModel)); + } + }); + columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Type"), "type", "type", "type")); columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); + columns.add(new PropertyColumn(new Model<>("Color"), null, "categoryStyle.color") { @Override diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java index e17a87cb..e0623cb9 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceDimensionsPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2015 Development Gateway, Inc and others. + * Copyright (c) 2023 Development Gateway, Inc and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) @@ -12,7 +12,10 @@ package org.devgateway.toolkit.forms.wicket.page.lists.admin; import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.filter.BootstrapTextFilteredPropertyColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; @@ -49,6 +52,12 @@ public ListServiceDimensionsPage(final PageParameters pageParameters) { columns = new ArrayList<>(); columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Value"), "code", "code", "code")); columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("System Label"), "value", "value", "value")); + columns.add(new PropertyColumn(new Model<>("Label Translations"), null, "labels") { + @Override + public void populateItem(final Item> item, final String componentId, final IModel rowModel) { + item.add(getLableTranslations(componentId, rowModel)); + } + }); columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java index cace93e7..742fc4c6 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceFiltersPage.java @@ -1,6 +1,10 @@ package org.devgateway.toolkit.forms.wicket.page.lists.admin; import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.filter.BootstrapTextFilteredPropertyColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; @@ -37,6 +41,12 @@ public ListServiceFiltersPage(final PageParameters pageParameters) { columns = new ArrayList<>(); columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Value"), "code", "code", "code")); columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("System Label"), "value", "value", "value")); + columns.add(new PropertyColumn(new Model<>("Label Translations"), null, "labels") { + @Override + public void populateItem(final Item> item, final String componentId, final IModel rowModel) { + item.add(getLableTranslations(componentId, rowModel)); + } + }); columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Type"), "fieldType", "fieldType", "fieldType")); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java index 9919cd2c..d19d7a0a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServiceMeasuresPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2015 Development Gateway, Inc and others. + * Copyright (c) 2023 Development Gateway, Inc and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) @@ -51,6 +51,13 @@ public ListServiceMeasuresPage(final PageParameters pageParameters) { columns = new ArrayList<>(); columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Value"), "code", "code", "code")); columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("System Label"), "value", "value", "value")); + columns.add(new PropertyColumn(new Model<>("Label Translations"), null, "labels") { + @Override + public void populateItem(final Item> item, final String componentId, final IModel rowModel) { + item.add(getLableTranslations(componentId, rowModel)); + } + }); + columns.add(new BootstrapTextFilteredPropertyColumn<>(new Model<>("Group"), "parent", "parent", "parent")); columns.add(new PropertyColumn<>(new Model<>("Position"), "position", "position")); columns.add(new PropertyColumn(new Model<>("Color"), null, From 4fd54bae5f67a4d83360b8c625ab5e19a934f487 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Mon, 13 Mar 2023 09:56:15 +0200 Subject: [PATCH 123/137] TOBACCO-1168: Add Perfectshift to tetsim model --- .../persistence/dto/TetsimExportOutput.java | 156 +++++++++++++++++- .../service/tetsim/TetsimOutputService.java | 10 +- .../TetsimOutputPerfectshiftCalculator.java | 28 ++++ .../TetsimOutputBaseCalculatorTest.java | 2 +- .../TetsimOutputCalculatorAbsChangeTest.java | 16 +- ...tputPerfectshiftCalculatorOverallTest.java | 61 +++++++ ...OutputUndershiftCalculatorOverallTest.java | 12 +- 7 files changed, 274 insertions(+), 11 deletions(-) create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputPerfectshiftCalculator.java create mode 100644 persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputPerfectshiftCalculatorOverallTest.java diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java index 9178ad4e..c2367e19 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/TetsimExportOutput.java @@ -73,10 +73,38 @@ public class TetsimExportOutput implements Serializable { private Double levyUndershift; + private Double legalConsumptionPerfectshift; + + private Double legalConsumptionChangePerfectshift; + + private Double consumptionIllicitPerfectshift; + + private Double exciseRevPerfectshift; + + private Double exciseRevChangePerfectshift; + + private Double totalGovRevPerfectshift; + + private Double exciseBurdenPerfectshift; + + private Double totalTaxBurdenPerfectshift; + + private Double baselineTotalTaxBurdenPerfectshift; + + private Double retailPricePerfectshift; + + private Double notPerfectshift; + + private Double exciseTaxPerfectshift; + + private Double vatPerfectshift; + + private Double levyPerfectshift; + public TetsimExportOutput() { } - public TetsimExportOutput(TetsimOutput overShift, TetsimOutput underShift) { + public TetsimExportOutput(TetsimOutput overShift, TetsimOutput underShift, TetsimOutput perfectShift) { this.year = overShift.getYear(); this.taxChange = overShift.getTaxChange(); this.tobaccoProduct = overShift.getTobaccoProduct(); @@ -108,6 +136,20 @@ public TetsimExportOutput(TetsimOutput overShift, TetsimOutput underShift) { this.exciseTaxUndershift = underShift.getExciseTax(); this.vatUndershift = underShift.getVat(); this.levyUndershift = underShift.getLevy(); + this.legalConsumptionPerfectshift = perfectShift.getLegalConsumption(); + this.legalConsumptionChangePerfectshift = perfectShift.getLegalConsumptionChange(); + this.consumptionIllicitPerfectshift = perfectShift.getConsumptionIllicit(); + this.exciseRevPerfectshift = perfectShift.getExciseRev(); + this.exciseRevChangePerfectshift = perfectShift.getExciseRevChange(); + this.totalGovRevPerfectshift = perfectShift.getTotalGovRev(); + this.exciseBurdenPerfectshift = perfectShift.getExciseBurden(); + this.totalTaxBurdenPerfectshift = perfectShift.getTotalTaxBurden(); + this.baselineTotalTaxBurdenPerfectshift = perfectShift.getTotalTaxBurdenBaseline(); + this.retailPricePerfectshift = perfectShift.getRetailPrice(); + this.notPerfectshift = perfectShift.getNot(); + this.exciseTaxPerfectshift = perfectShift.getExciseTax(); + this.vatPerfectshift = perfectShift.getVat(); + this.levyPerfectshift = perfectShift.getLevy(); } public Integer getYear() { @@ -357,4 +399,116 @@ public Double getBaselineTotalTaxBurdenUndershift() { public void setBaselineTotalTaxBurdenUndershift(final Double baselineTotalTaxBurdenUndershift) { this.baselineTotalTaxBurdenUndershift = baselineTotalTaxBurdenUndershift; } + + public Double getLegalConsumptionPerfectshift() { + return legalConsumptionPerfectshift; + } + + public void setLegalConsumptionPerfectshift(final Double legalConsumptionPerfectshift) { + this.legalConsumptionPerfectshift = legalConsumptionPerfectshift; + } + + public Double getLegalConsumptionChangePerfectshift() { + return legalConsumptionChangePerfectshift; + } + + public void setLegalConsumptionChangePerfectshift(final Double legalConsumptionChangePerfectshift) { + this.legalConsumptionChangePerfectshift = legalConsumptionChangePerfectshift; + } + + public Double getConsumptionIllicitPerfectshift() { + return consumptionIllicitPerfectshift; + } + + public void setConsumptionIllicitPerfectshift(final Double consumptionIllicitPerfectshift) { + this.consumptionIllicitPerfectshift = consumptionIllicitPerfectshift; + } + + public Double getExciseRevPerfectshift() { + return exciseRevPerfectshift; + } + + public void setExciseRevPerfectshift(final Double exciseRevPerfectshift) { + this.exciseRevPerfectshift = exciseRevPerfectshift; + } + + public Double getExciseRevChangePerfectshift() { + return exciseRevChangePerfectshift; + } + + public void setExciseRevChangePerfectshift(final Double exciseRevChangePerfectshift) { + this.exciseRevChangePerfectshift = exciseRevChangePerfectshift; + } + + public Double getTotalGovRevPerfectshift() { + return totalGovRevPerfectshift; + } + + public void setTotalGovRevPerfectshift(final Double totalGovRevPerfectshift) { + this.totalGovRevPerfectshift = totalGovRevPerfectshift; + } + + public Double getExciseBurdenPerfectshift() { + return exciseBurdenPerfectshift; + } + + public void setExciseBurdenPerfectshift(final Double exciseBurdenPerfectshift) { + this.exciseBurdenPerfectshift = exciseBurdenPerfectshift; + } + + public Double getTotalTaxBurdenPerfectshift() { + return totalTaxBurdenPerfectshift; + } + + public void setTotalTaxBurdenPerfectshift(final Double totalTaxBurdenPerfectshift) { + this.totalTaxBurdenPerfectshift = totalTaxBurdenPerfectshift; + } + + public Double getBaselineTotalTaxBurdenPerfectshift() { + return baselineTotalTaxBurdenPerfectshift; + } + + public void setBaselineTotalTaxBurdenPerfectshift(final Double baselineTotalTaxBurdenPerfectshift) { + this.baselineTotalTaxBurdenPerfectshift = baselineTotalTaxBurdenPerfectshift; + } + + public Double getRetailPricePerfectshift() { + return retailPricePerfectshift; + } + + public void setRetailPricePerfectshift(final Double retailPricePerfectshift) { + this.retailPricePerfectshift = retailPricePerfectshift; + } + + public Double getNotPerfectshift() { + return notPerfectshift; + } + + public void setNotPerfectshift(final Double notPerfectshift) { + this.notPerfectshift = notPerfectshift; + } + + public Double getExciseTaxPerfectshift() { + return exciseTaxPerfectshift; + } + + public void setExciseTaxPerfectshift(final Double exciseTaxPerfectshift) { + this.exciseTaxPerfectshift = exciseTaxPerfectshift; + } + + public Double getVatPerfectshift() { + return vatPerfectshift; + } + + public void setVatPerfectshift(final Double vatPerfectshift) { + this.vatPerfectshift = vatPerfectshift; + } + + public Double getLevyPerfectshift() { + return levyPerfectshift; + } + + public void setLevyPerfectshift(final Double levyPerfectshift) { + this.levyPerfectshift = levyPerfectshift; + } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java index 05717b59..1337df26 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/tetsim/TetsimOutputService.java @@ -13,6 +13,7 @@ import org.devgateway.toolkit.persistence.dto.TetsimOutput; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; +import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputPerfectshiftCalculator; import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputUndershiftCalculator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -39,7 +40,11 @@ public class TetsimOutputService { "consumptionIllicitUndershift", "exciseRevUndershift", "exciseRevChangeUndershift", "totalGovRevUndershift", "exciseBurdenUndershift", "totalTaxBurdenUndershift", "baselineTotalTaxBurdenUndershift", "retailPriceUndershift", "notUndershift", "exciseTaxUndershift", - "vatUndershift", "levyUndershift") + "vatUndershift", "levyUndershift", "legalConsumptionPerfectshift", + "legalConsumptionChangePerfectshift", "consumptionIllicitPerfectshift", "exciseRevPerfectshift", + "exciseRevChangePerfectshift", "totalGovRevPerfectshift", "exciseBurdenPerfectshift", + "totalTaxBurdenPerfectshift", "baselineTotalTaxBurdenPerfectshift", "retailPricePerfectshift", + "notPerfectshift", "exciseTaxPerfectshift", "vatPerfectshift", "levyPerfectshift") .build(); @Autowired private TetsimDatasetService tetsimDatasetService; @@ -58,7 +63,8 @@ public List getTetsimOutputs(Long datasetId) { for (TobaccoProduct t : TobaccoProduct.values()) { TetsimOutput overShift = new TetsimOutputOvershiftCalculator(dataset, i).calculate(t); TetsimOutput underShift = new TetsimOutputUndershiftCalculator(dataset, i).calculate(t); - outputs.add(new TetsimExportOutput(overShift, underShift)); + TetsimOutput perfectShift = new TetsimOutputPerfectshiftCalculator(dataset, i).calculate(t); + outputs.add(new TetsimExportOutput(overShift, underShift, perfectShift)); } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputPerfectshiftCalculator.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputPerfectshiftCalculator.java new file mode 100644 index 00000000..fc4d61dc --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/util/tetsim/TetsimOutputPerfectshiftCalculator.java @@ -0,0 +1,28 @@ +package org.devgateway.toolkit.persistence.util.tetsim; + +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; + +import java.math.BigDecimal; + +import static org.devgateway.toolkit.persistence.util.tetsim.TetsimUtil.getTobaccoProductValueFromVariable; + +/** + * @author vchihai + */ +public class TetsimOutputPerfectshiftCalculator extends TetsimOutputBaseCalculator { + + public TetsimOutputPerfectshiftCalculator(TetsimDataset dataset, Integer percentageChange) { + super(dataset, percentageChange); + } + + @Override + protected String getShifting() { + return "Perfectshift"; + } + + @Override + public BigDecimal calculateAbsChangeShift(final TobaccoProduct tobaccoProduct) { + return BigDecimal.ZERO; + } +} diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputBaseCalculatorTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputBaseCalculatorTest.java index 821524b3..51668e69 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputBaseCalculatorTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputBaseCalculatorTest.java @@ -45,7 +45,7 @@ protected TetsimDataset createTetsimDatasetWithAllTobaccoProducts() { .withCrossElasticityPrice(createPriceVariable(ZERO, ZERO, BigDecimal.valueOf(0.2), BigDecimal.valueOf(0.3), BigDecimal.valueOf(0.3))) .withChangeInIllicitNot(createPriceVariable(null, null,null, null, BigDecimal.valueOf(0.5))) .withOvershifting(createPriceVariable(BigDecimal.valueOf(0.3), BigDecimal.valueOf(0.3), BigDecimal.valueOf(0.2), BigDecimal.valueOf(0.1), ZERO)) - .withUndershifting(createPriceVariable(BigDecimal.valueOf(-0.2), BigDecimal.valueOf(-0.2), BigDecimal.valueOf(-0.3), BigDecimal.valueOf(-0.5), ZERO)) + .withUndershifting(createPriceVariable(BigDecimal.valueOf(-0.2), BigDecimal.valueOf(-0.2), BigDecimal.valueOf(-0.3), BigDecimal.valueOf(-0.15), ZERO)) .build(); } diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorAbsChangeTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorAbsChangeTest.java index cbcabb9c..fe1c2096 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorAbsChangeTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputCalculatorAbsChangeTest.java @@ -2,6 +2,7 @@ import org.devgateway.toolkit.persistence.dao.data.TobaccoProduct; import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputOvershiftCalculator; +import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputPerfectshiftCalculator; import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputUndershiftCalculator; import org.junit.Before; import org.junit.Test; @@ -58,7 +59,20 @@ public void testUndershiftAbsChange() { assertAll("TETSIM Undershift Abs Change", () -> assertEquals(-1.13, tetsimOutputCalculator.calculateAbsChangeShift(POPULAR).doubleValue(), delta, "Check Abs change undershift popular"), - () -> assertEquals(-1.88, tetsimOutputCalculator.calculateAbsChangeShift(DISCOUNT).doubleValue(), + () -> assertEquals(-0.56, tetsimOutputCalculator.calculateAbsChangeShift(DISCOUNT).doubleValue(), + delta, "Check Abs change undershift discount"), + () -> assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift(ILLICIT).doubleValue(), + delta, "Check Abs change undershift illicit") + ); + } + + @Test + public void testPerfectshiftAbsChange() { + TetsimOutputPerfectshiftCalculator tetsimOutputCalculator = new TetsimOutputPerfectshiftCalculator(datasetWithAllTobaccoProducts, 20); + assertAll("TETSIM Perfectshift Abs Change", + () -> assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift(POPULAR).doubleValue(), + delta, "Check Abs change undershift popular"), + () -> assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift(DISCOUNT).doubleValue(), delta, "Check Abs change undershift discount"), () -> assertEquals(0.00, tetsimOutputCalculator.calculateAbsChangeShift(ILLICIT).doubleValue(), delta, "Check Abs change undershift illicit") diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputPerfectshiftCalculatorOverallTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputPerfectshiftCalculatorOverallTest.java new file mode 100644 index 00000000..7f3a016a --- /dev/null +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputPerfectshiftCalculatorOverallTest.java @@ -0,0 +1,61 @@ +package org.devgateway.toolkit.persistence.tetsim; + +import org.devgateway.toolkit.persistence.dto.TetsimOutput; +import org.devgateway.toolkit.persistence.util.tetsim.TetsimOutputPerfectshiftCalculator; +import org.junit.Before; +import org.junit.Test; + +import static org.devgateway.toolkit.persistence.dao.data.TobaccoProduct.POPULAR; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TetsimOutputPerfectshiftCalculatorOverallTest extends TetsimOutputBaseCalculatorTest { + + @Before + public void setUp() { + super.setUp(); + } + + @Test + public void testOverallOutputBaseline() { + TetsimOutputPerfectshiftCalculator tetsimOutputCalculator = new TetsimOutputPerfectshiftCalculator(datasetWithAllTobaccoProducts, 0); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); + + assertAll("TETSIM Perfectshift Baseline", + () -> assertEquals(754.40, output.getLegalConsumption(), delta, "TETSIM Perfectshift - Consumption Legal"), + () -> assertEquals(0, output.getLegalConsumptionChange(), delta, "TETSIM Perfectshift - Consumption Legal Change"), + () -> assertEquals(395.60, output.getConsumptionIllicit(), delta, "TETSIM Perfectshift - Consumption Illicit"), + () -> assertEquals(14167.63, output.getExciseRev(), delta, "TETSIM Perfectshift - Excise Revenue"), + () -> assertEquals(0, output.getExciseRevChange(), delta, "TETSIM Perfectshift - Excise Revenue Change"), + () -> assertEquals(18051.37, output.getTotalGovRev(), delta, "TETSIM Perfectshift - Government Revenue"), + () -> assertEquals(46.95, output.getExciseBurden(), delta, "TETSIM Perfectshift - Excise Burden"), + () -> assertEquals(60.00, output.getTotalTaxBurden(), delta, "TETSIM Perfectshift - Total Tax Burden"), + () -> assertEquals(40.00, output.getRetailPrice(), delta, "TETSIM Perfectshift - Retail Price"), + () -> assertEquals(16.00, output.getNot(), delta, "TETSIM Perfectshift - NOT"), + () -> assertEquals(18.78, output.getExciseTax(), delta, "TETSIM Perfectshift - Excise Tax"), + () -> assertEquals(5.21, output.getVat(), delta, "TETSIM Perfectshift - VAT"), + () -> assertEquals(0.00, output.getLevy(), delta, "TETSIM Perfectshift - Levy")); + } + + @Test + public void testOverallOutputWithTaxChange() { + TetsimOutputPerfectshiftCalculator tetsimOutputCalculator = new TetsimOutputPerfectshiftCalculator(datasetWithAllTobaccoProducts, 30); + TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); + + assertAll("TETSIM Perfectshift With 30% Tax Change", + () -> assertEquals(661.37, output.getLegalConsumption(), delta, "TETSIM Perfectshift - Consumption Legal"), + () -> assertEquals(-12.33, output.getLegalConsumptionChange(), delta, "TETSIM Perfectshift - Consumption Legal Change"), + () -> assertEquals(384.78, output.getConsumptionIllicit(), delta, "TETSIM Perfectshift - Consumption Illicit"), + () -> assertEquals(16146.9, output.getExciseRev(), delta, "TETSIM Perfectshift - Excise Revenue"), + () -> assertEquals(13.97, output.getExciseRevChange(), delta, "TETSIM Perfectshift - Excise Revenue Change"), + () -> assertEquals(20146.86, output.getTotalGovRev(), delta, "TETSIM Perfectshift - Government Revenue"), + () -> assertEquals(52.53, output.getExciseBurden(), delta, "TETSIM Perfectshift - Excise Burden"), + () -> assertEquals(65.57, output.getTotalTaxBurden(), delta, "TETSIM Perfectshift - Total Tax Burden"), + () -> assertEquals(46.48, output.getRetailPrice(), delta, "TETSIM Perfectshift - Retail Price"), + () -> assertEquals(16.00, output.getNot(), delta, "TETSIM Perfectshift - NOT"), + () -> assertEquals(24.41, output.getExciseTax(), delta, "TETSIM Perfectshift - Excise Tax"), + () -> assertEquals(6.06, output.getVat(), delta, "TETSIM Perfectshift - VAT"), + () -> assertEquals(0.00, output.getLevy(), delta, "TETSIM Perfectshift - Levy")); + } + +} \ No newline at end of file diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java index 89aedf7b..0fac5cdc 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/tetsim/TetsimOutputUndershiftCalculatorOverallTest.java @@ -44,12 +44,12 @@ public void testOverallOutputWithTaxChange() { TetsimOutput output = tetsimOutputCalculator.calculate(POPULAR); assertAll("TETSIM Undershift With 30% Tax Change", - () -> assertEquals(694.62, output.getLegalConsumption(), delta, "TETSIM Undershift - Consumption Legal"), - () -> assertEquals(-7.92, output.getLegalConsumptionChange(), delta, "TETSIM Undershift - Consumption Legal Change"), - () -> assertEquals(390.14, output.getConsumptionIllicit(), delta, "TETSIM Undershift - Consumption Illicit"), - () -> assertEquals(16958.46, output.getExciseRev(), delta, "TETSIM Undershift - Excise Revenue"), - () -> assertEquals(19.69, output.getExciseRevChange(), delta, "TETSIM Undershift - Excise Revenue Change"), - () -> assertEquals(20945.90, output.getTotalGovRev(), delta, "TETSIM Undershift - Government Revenue"), + () -> assertEquals(679.54, output.getLegalConsumption(), delta, "TETSIM Undershift - Consumption Legal"), + () -> assertEquals(-9.92, output.getLegalConsumptionChange(), delta, "TETSIM Undershift - Consumption Legal Change"), + () -> assertEquals(386.38, output.getConsumptionIllicit(), delta, "TETSIM Undershift - Consumption Illicit"), + () -> assertEquals(16590.46, output.getExciseRev(), delta, "TETSIM Undershift - Excise Revenue"), + () -> assertEquals(17.10, output.getExciseRevChange(), delta, "TETSIM Undershift - Excise Revenue Change"), + () -> assertEquals(20550.49, output.getTotalGovRev(), delta, "TETSIM Undershift - Government Revenue"), () -> assertEquals(54.82, output.getExciseBurden(), delta, "TETSIM Undershift - Excise Burden"), () -> assertEquals(67.86, output.getTotalTaxBurden(), delta, "TETSIM Undershift - Total Tax Burden"), () -> assertEquals(44.54, output.getRetailPrice(), delta, "TETSIM Undershift - Retail Price"), From 1aa9a4aeb0119e696048a29cdb2a1a5abbc8a0f6 Mon Sep 17 00:00:00 2001 From: sdimuzio Date: Tue, 4 Apr 2023 15:48:46 -0300 Subject: [PATCH 124/137] fixing wpm programmatic config --- ui/_.env | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 ui/_.env diff --git a/ui/_.env b/ui/_.env new file mode 100644 index 00000000..5b0e37a3 --- /dev/null +++ b/ui/_.env @@ -0,0 +1,12 @@ +PROTOCOL=http +DOMAIN=localhost +ISO=za +REACT_APP_TITLE=Tobacco Control Data Initiative +REACT_APP_WP_API=$PROTOCOL://localhost/wp/wp-json +REACT_APP_WP_STYLES=$PROTOCOL://localhost/wp/wp-admin/load-styles.php?c=1&dir=ltr&load%5Bchunk_0%5D=dashicons,admin-bar,buttons,media-views,editor-buttons,wp-components,wp-block-editor,wp-nux,wp-editor,wp-block-library,wp-block-&load%5Bchunk_1%5D=library-theme,wp-edit-blocks,wp-edit-post,wp-format-library,wp-block-directory,common,forms,admin-menu,dashboard,list-tables,edi&load%5Bchunk_2%5D=t,revisions,media,themes,about,nav-menus,wp-pointer,widgets,site-icon,l10n,wp-auth-check&ver=5.5.6' id='wp-block-library-css +REACT_APP_GA_CODE= +REACT_APP_DEFAULT_LOCALE=en +REACT_APP_WP_HOSTS=http://localhost +REACT_APP_USE_HASH_LINKS=false +REACT_APP_THEME=za +REACT_APP_API_ROOT=$PROTOCOL://localhost% \ No newline at end of file From 89e77937c1f7cac8968afd12e613fbd21307301a Mon Sep 17 00:00:00 2001 From: Denis Mbugua <60645043+dynamodenis@users.noreply.github.com> Date: Fri, 18 Oct 2024 10:41:12 +0300 Subject: [PATCH 125/137] DVIZ-12 upgraded persistence --- persistence/pom.xml | 22 ++++++-- .../persistence/application-dev.properties | 4 +- ...ValidateCacheableHibernateQueryResult.java | 2 +- .../dao/AbstractStatusAuditableEntity.java | 16 +++--- .../toolkit/persistence/dao/FileContent.java | 11 ++-- .../persistence/dao/GenericPersistable.java | 6 +-- .../toolkit/persistence/dao/data/Dataset.java | 4 +- .../persistence/derby/CustomDerbyDialect.java | 28 ++++++++++ .../persistence/derby/DerbyDialect.java | 18 ------- .../excel/reader/XExcelFileReader.java | 4 +- .../repository/CacheHibernateQueryResult.java | 2 +- .../norepository/SpecificationUtils.java | 8 +-- .../UniquePropertyRepository.java | 4 +- .../spring/DatabaseConfiguration.java | 35 ------------- .../excel/ExcelFileImportDefaultTest.java | 21 ++++++++ .../excel/test/TestAddressRepository.java | 52 +++++++++++++++++++ pom.xml | 24 ++++----- web/pom.xml | 21 +++++++- .../web/excelcharts/ExcelChartSheet.java | 1 + 19 files changed, 184 insertions(+), 99 deletions(-) create mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/derby/CustomDerbyDialect.java delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/derby/DerbyDialect.java diff --git a/persistence/pom.xml b/persistence/pom.xml index 9c275168..eedc1050 100644 --- a/persistence/pom.xml +++ b/persistence/pom.xml @@ -18,8 +18,8 @@ UTF-8 org.devgateway.toolkit.persistence.spring.PersistenceApplication - 1.8 - 3.8.1 + 17 + 3.10.8 0.3.8 3.2.1 30.0-jre @@ -111,6 +111,7 @@ org.hibernate hibernate-jcache + 7.0.0.Beta1 @@ -121,11 +122,13 @@ org.hibernate hibernate-entitymanager + 6.0.0.Alpha7 org.hibernate hibernate-envers + 6.6.1.Final hibernate-entitymanager @@ -137,6 +140,8 @@ org.hibernate hibernate-jpamodelgen + 6.6.1.Final + provided @@ -155,7 +160,7 @@ org.postgresql postgresql - ${pgsql.version} + @@ -212,6 +217,17 @@ opencsv 5.6 + + + jakarta.xml.bind + jakarta.xml.bind-api + 3.0.1 + + + org.glassfish.jaxb + jaxb-runtime + 3.0.1 + diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties index dccb755e..17786696 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties @@ -11,8 +11,8 @@ ############################################################################### spring.config.activate.on-profile=dev spring.datasource.username=postgres -spring.datasource.password=postgres -spring.datasource.jdbc-url=jdbc:postgresql://localhost:5432/tcdi-admin +spring.datasource.password=admin +spring.datasource.jdbc-url=jdbc:postgresql://localhost:5432/data_viz_admin management.health.mail.enabled=false dg-toolkit.forms.base-path=/admin diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/checks/ValidateCacheableHibernateQueryResult.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/checks/ValidateCacheableHibernateQueryResult.java index c4a7e619..b471153d 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/checks/ValidateCacheableHibernateQueryResult.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/checks/ValidateCacheableHibernateQueryResult.java @@ -4,7 +4,7 @@ import org.reflections.Reflections; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import java.util.HashSet; import java.util.Set; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractStatusAuditableEntity.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractStatusAuditableEntity.java index 4f423a9d..7b08428d 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractStatusAuditableEntity.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractStatusAuditableEntity.java @@ -6,14 +6,14 @@ import org.hibernate.annotations.OptimisticLock; import org.hibernate.envers.Audited; -import javax.persistence.CascadeType; -import javax.persistence.FetchType; -import javax.persistence.ManyToOne; -import javax.persistence.MappedSuperclass; -import javax.persistence.OneToMany; -import javax.persistence.OrderColumn; -import javax.persistence.Transient; -import javax.validation.constraints.NotNull; +import jakarta.persistence.CascadeType; +import jakarta.persistence.FetchType; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.MappedSuperclass; +import jakarta.persistence.OneToMany; +import jakarta.persistence.OrderColumn; +import jakarta.persistence.Transient; +import jakarta.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileContent.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileContent.java index dc78144b..41c13845 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileContent.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileContent.java @@ -11,11 +11,12 @@ *******************************************************************************/ package org.devgateway.toolkit.persistence.dao; -import org.hibernate.annotations.Type; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Lob; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Lob; /** * @author idobre @@ -30,7 +31,7 @@ public class FileContent extends AbstractAuditableEntity { @Lob @Column(length = LOB_LENGTH) - @Type(type = "org.hibernate.type.BinaryType") + @JdbcTypeCode(SqlTypes.BLOB) private byte[] bytes; public byte[] getBytes() { diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/GenericPersistable.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/GenericPersistable.java index d5eee8f0..bbed2822 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/GenericPersistable.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/GenericPersistable.java @@ -24,9 +24,9 @@ import nl.dries.wicket.hibernate.dozer.proxy.Proxied; import org.springframework.data.jpa.domain.AbstractPersistable; -import javax.persistence.Column; -import javax.persistence.MappedSuperclass; -import javax.persistence.Version; +import jakarta.persistence.Column; +import jakarta.persistence.MappedSuperclass; +import jakarta.persistence.Version; /** * @author mpostelnicu diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java index 4af2bf54..28db48a5 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java @@ -4,8 +4,8 @@ import org.devgateway.toolkit.persistence.dao.AbstractStatusAuditableEntity; import org.hibernate.envers.Audited; -import javax.persistence.MappedSuperclass; -import javax.validation.constraints.NotNull; +import jakarta.persistence.MappedSuperclass; +import jakarta.validation.constraints.NotNull; import java.io.Serializable; @MappedSuperclass diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/derby/CustomDerbyDialect.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/derby/CustomDerbyDialect.java new file mode 100644 index 00000000..c6af8cd6 --- /dev/null +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/derby/CustomDerbyDialect.java @@ -0,0 +1,28 @@ +package org.devgateway.toolkit.persistence.derby; + +import org.hibernate.dialect.DerbyDialect; +import org.hibernate.boot.model.TypeContributions; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.type.descriptor.jdbc.BlobJdbcType; +import org.hibernate.type.spi.TypeConfiguration; + +import static java.sql.Types.VARBINARY; + +/** + * Setup non-default derby configurations. + * + * @author Nadejda Mandrescu + */ +public class CustomDerbyDialect extends DerbyDialect { + + public CustomDerbyDialect() { + super(); + } + + @Override + public void contributeTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) { + super.contributeTypes(typeContributions, serviceRegistry); + typeContributions.getTypeConfiguration().getJdbcTypeRegistry() + .addDescriptor(VARBINARY, BlobJdbcType.BLOB_BINDING); + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/derby/DerbyDialect.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/derby/DerbyDialect.java deleted file mode 100644 index 609a22e9..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/derby/DerbyDialect.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.devgateway.toolkit.persistence.derby; - -import org.hibernate.dialect.DerbyTenSevenDialect; - -import static java.sql.Types.VARBINARY; - -/** - * Setup non-default derby configurations. - * - * @author Nadejda Mandrescu - */ -public class DerbyDialect extends DerbyTenSevenDialect { - - public DerbyDialect() { - super(); - registerColumnType(VARBINARY, "BLOB($l)"); - } -} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/excel/reader/XExcelFileReader.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/excel/reader/XExcelFileReader.java index f65ef6e9..75de2237 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/excel/reader/XExcelFileReader.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/excel/reader/XExcelFileReader.java @@ -1,6 +1,6 @@ package org.devgateway.toolkit.persistence.excel.reader; -import org.apache.poi.hssf.util.CellReference; +import org.apache.poi.ss.util.CellReference; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable; import org.apache.poi.xssf.eventusermodel.XSSFReader; @@ -141,7 +141,7 @@ private String getCellValue(final String cellType) throws XMLStreamException { if (xmlReader.getLocalName().equals("v")) { if (cellType != null && cellType.equals("s")) { final int idx = Integer.parseInt(xmlReader.getElementText()); - return new XSSFRichTextString(stringsTable.getEntryAt(idx)).toString(); + return stringsTable.getItemAt(idx).toString(); } else { return xmlReader.getElementText(); } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/CacheHibernateQueryResult.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/CacheHibernateQueryResult.java index 2ccc0b22..62db4a56 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/CacheHibernateQueryResult.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/CacheHibernateQueryResult.java @@ -5,7 +5,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import javax.persistence.QueryHint; +import jakarta.persistence.QueryHint; import org.springframework.data.jpa.repository.QueryHints; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/norepository/SpecificationUtils.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/norepository/SpecificationUtils.java index cc0d5fa0..ff213865 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/norepository/SpecificationUtils.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/norepository/SpecificationUtils.java @@ -2,10 +2,10 @@ import org.apache.commons.lang3.StringUtils; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.Expression; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.Expression; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; /** * @author Nadejda Mandrescu diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/norepository/UniquePropertyRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/norepository/UniquePropertyRepository.java index 6853ac8a..deacd49b 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/norepository/UniquePropertyRepository.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/norepository/UniquePropertyRepository.java @@ -5,8 +5,8 @@ import org.springframework.data.repository.NoRepositoryBean; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.criteria.Path; -import javax.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Path; +import jakarta.persistence.criteria.Predicate; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java index a28fd523..6917ca26 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java @@ -26,9 +26,7 @@ import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; -import org.springframework.mock.jndi.SimpleNamingContextBuilder; -import javax.naming.NamingException; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; @@ -47,39 +45,6 @@ public class DatabaseConfiguration { private static final Logger logger = LoggerFactory.getLogger(DatabaseConfiguration.class); - @Value("${dg-toolkit.datasource.jndi-name}") - private String datasourceJndiName; - - /** - * This bean creates the JNDI tree and registers the - * {@link javax.sql.DataSource} to this tree. This allows Pentaho Classic - * Engine to use a {@link javax.sql.DataSource} ,in our case backed by a - * connection pool instead of always opening up JDBC connections. Should - * significantly improve performance of all classic reports. In PRD use - * connection type=JNDI and name toolkitDS. To use it in PRD you need to add - * the configuration to the local PRD. Edit - * ~/.pentaho/simple-jndi/default.properties and add the following: - * toolkitDS/type=javax.sql.DataSource - * toolkitDS/driver=org.apache.derby.jdbc.ClientDriver toolkitDS/user=app - * toolkitDS/password=app - * toolkitDS/url=jdbc:derby://localhost//derby/toolkit - * - * @return - */ - @Bean - public SimpleNamingContextBuilder jndiBuilder() { - SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder(); - builder.bind(datasourceJndiName, dataSource()); - try { - builder.activate(); - } catch (IllegalStateException e) { - e.printStackTrace(); - } catch (NamingException e) { - e.printStackTrace(); - } - return builder; - } - /** * Creates a {@link javax.sql.DataSource} based on HikariCP {@link HikariDataSource} * diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/excel/ExcelFileImportDefaultTest.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/excel/ExcelFileImportDefaultTest.java index d5e642a1..4cc01705 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/excel/ExcelFileImportDefaultTest.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/excel/ExcelFileImportDefaultTest.java @@ -27,6 +27,7 @@ import java.lang.annotation.Annotation; import java.util.Locale; import java.util.Map; +import java.util.Set; import static org.slf4j.Logger.ROOT_LOGGER_NAME; @@ -120,6 +121,16 @@ public String[] getBeanDefinitionNames() { return new String[0]; } + @Override + public ObjectProvider getBeanProvider(Class requiredType, boolean allowEagerInit) { + return null; + } + + @Override + public ObjectProvider getBeanProvider(ResolvableType requiredType, boolean allowEagerInit) { + return null; + } + @Override public String[] getBeanNamesForType(ResolvableType resolvableType) { return new String[0]; @@ -165,6 +176,16 @@ public A findAnnotationOnBean(String s, Class aClass) return null; } + @Override + public A findAnnotationOnBean(String beanName, Class annotationType, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException { + return null; + } + + @Override + public Set findAllAnnotationsOnBean(String beanName, Class annotationType, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException { + return null; + } + @Override public Object getBean(String s) throws BeansException { return null; diff --git a/persistence/src/test/java/org/devgateway/toolkit/persistence/excel/test/TestAddressRepository.java b/persistence/src/test/java/org/devgateway/toolkit/persistence/excel/test/TestAddressRepository.java index 247ace28..0e16290f 100644 --- a/persistence/src/test/java/org/devgateway/toolkit/persistence/excel/test/TestAddressRepository.java +++ b/persistence/src/test/java/org/devgateway/toolkit/persistence/excel/test/TestAddressRepository.java @@ -6,9 +6,11 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.repository.query.FluentQuery; import java.util.List; import java.util.Optional; +import java.util.function.Function; /** * @author idobre @@ -68,6 +70,11 @@ public void delete(TestAddress entity) { } + @Override + public void deleteAllById(Iterable longs) { + + } + @Override public void deleteAll(Iterable entities) { @@ -98,6 +105,16 @@ public TestAddress getOne(Long aLong) { return null; } + @Override + public TestAddress getById(Long aLong) { + return null; + } + + @Override + public TestAddress getReferenceById(Long aLong) { + return null; + } + @Override public List findAll(Example example, Sort sort) { return null; @@ -113,6 +130,21 @@ public S saveAndFlush(S entity) { return null; } + @Override + public List saveAllAndFlush(Iterable entities) { + return null; + } + + @Override + public void deleteAllInBatch(Iterable entities) { + + } + + @Override + public void deleteAllByIdInBatch(Iterable longs) { + + } + @Override public List saveAll(Iterable entities) { return null; @@ -162,4 +194,24 @@ public long count(Example example) { public boolean exists(Example example) { return false; } + + @Override + public boolean exists(Specification spec) { + return false; + } + + @Override + public long delete(Specification spec) { + return 0; + } + + @Override + public R findBy(Specification spec, Function, R> queryFunction) { + return null; + } + + @Override + public R findBy(Example example, Function, R> queryFunction) { + return null; + } } diff --git a/pom.xml b/pom.xml index 57c94fc7..afa533b8 100644 --- a/pom.xml +++ b/pom.xml @@ -21,18 +21,18 @@ UTF-8 - 1.8 - 3.8.9 - 2.2.11.RELEASE - 42.2.5 - 10.14.2.0 - 4.0.1 + 17 + 4.29.0 + 3.2.10 + + 10.17.1.0 + 5.3.0 devgateway/toolkit - 0.4.13 - 3.1.2 - 2.22.1 - 2.5.3 - 3.27.0-GA + 1.2.2 + 3.5.0 + 3.5.1 + 3.1.1 + 3.30.2-GA @@ -114,7 +114,7 @@ org.reflections reflections - 0.9.12 + 0.10.2 diff --git a/web/pom.xml b/web/pom.xml index 14e9ecc3..783073a5 100644 --- a/web/pom.xml +++ b/web/pom.xml @@ -16,7 +16,7 @@ UTF-8 org.devgateway.toolkit.web.spring.WebApplication - 1.8 + 17 1.4 3.0.0 @@ -80,6 +80,7 @@ de.flapdoodle.embed de.flapdoodle.embed.mongo + 4.17.0 test @@ -134,6 +135,24 @@ springfox-swagger-ui ${swagger.version} + + + org.apache.poi + poi + ${poi.version} + + + + org.apache.poi + poi-ooxml + ${poi.version} + + + + org.apache.poi + poi-ooxml-schemas + 4.1.2 + diff --git a/web/src/main/java/org/devgateway/toolkit/web/excelcharts/ExcelChartSheet.java b/web/src/main/java/org/devgateway/toolkit/web/excelcharts/ExcelChartSheet.java index 255a0aeb..4477f9eb 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/excelcharts/ExcelChartSheet.java +++ b/web/src/main/java/org/devgateway/toolkit/web/excelcharts/ExcelChartSheet.java @@ -3,6 +3,7 @@ import org.apache.poi.ss.usermodel.Chart; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.charts.ChartDataSource; +import org.apache.poi.xddf.usermodel.chart.XDDFDataSource; import java.util.List; From 0aed9ef834777debe6195162ae400204e93f76e9 Mon Sep 17 00:00:00 2001 From: Denis Mbugua <60645043+dynamodenis@users.noreply.github.com> Date: Tue, 22 Oct 2024 16:16:05 +0300 Subject: [PATCH 126/137] DVIZ-12 upgrade tcdi-admin --- forms/Dockerfile | 2 +- forms/pom.xml | 68 +++++++--- .../toolkit/forms/FormsSecurityConfig.java | 126 ++++++++++++------ .../forms/JavaMelodyConfiguration.java | 4 +- .../toolkit/forms/client/DatasetClient.java | 18 +-- .../forms/client/ServiceCategoryClient.java | 2 +- .../forms/client/ServiceDatasetClient.java | 8 +- .../forms/client/ServiceDimensionClient.java | 2 +- .../forms/client/ServiceEntityClient.java | 10 +- .../forms/client/ServiceFilterClient.java | 2 +- .../forms/client/ServiceMeasureClient.java | 2 +- .../forms/service/SessionFinderService.java | 4 +- .../forms/wicket/FormsWebApplication.java | 15 ++- .../wicket/SSAuthenticatedWebSession.java | 4 +- .../toolkit/forms/wicket/WebInitializer.java | 6 +- .../form/FileInputBootstrapFormComponent.java | 2 +- .../form/GenericBootstrapFormComponent.java | 2 +- .../Select2ChoiceBootstrapFormComponent.java | 2 +- ...ect2MultiChoiceBootstrapFormComponent.java | 2 +- .../form/ToolkitSummernoteEditor.java | 4 +- .../table/filter/CSVDatasetFilterState.java | 2 +- .../table/filter/JpaFilterState.java | 2 +- .../table/filter/TestFormFilterState.java | 2 +- .../filter/TetsimDatasetFilterState.java | 2 +- .../toolkit/forms/wicket/page/BasePage.java | 6 +- .../toolkit/forms/wicket/page/Header.java | 2 +- .../forms/wicket/page/RevisionsPage.java | 2 +- .../wicket/page/edit/AbstractEditPage.java | 2 +- .../edit/AbstractEditStatusEntityPage.java | 4 +- .../page/edit/dataset/EditCSVDatasetPage.java | 2 +- .../wicket/page/lists/AbstractListPage.java | 2 +- .../forms/wicket/page/user/LoginPage.java | 8 +- .../forms/wicket/page/user/LogoutPage.java | 4 +- .../wicket/styles/BlockUiJavaScript.java | 2 +- .../styles/BlockUiReportsJavaScript.java | 2 +- .../forms/client/DatasetClientTest.java | 6 +- persistence/pom.xml | 23 ++-- .../dao/AbstractAuditableEntity.java | 6 +- .../persistence/dao/AdminSettings.java | 2 +- .../toolkit/persistence/dao/FileMetadata.java | 12 +- .../toolkit/persistence/dao/Person.java | 14 +- .../toolkit/persistence/dao/Role.java | 8 +- .../persistence/dao/StatusChangedComment.java | 8 +- .../toolkit/persistence/dao/TestForm.java | 16 +-- .../persistence/dao/TestFormChild.java | 8 +- .../persistence/dao/categories/Category.java | 8 +- .../persistence/dao/categories/Group.java | 6 +- .../persistence/dao/data/CSVDataset.java | 6 +- .../persistence/dao/data/TetsimDataset.java | 8 +- .../dao/data/TetsimPriceVariable.java | 8 +- .../dao/data/TetsimTobaccoProductValue.java | 4 +- .../repository/SpecificationContext.java | 6 +- .../repository/data/CSVDatasetRepository.java | 2 +- .../data/TetsimDatasetRepository.java | 2 +- .../spring/DatabaseConfiguration.java | 2 +- pom.xml | 16 ++- .../web/excelcharts/ExcelChartSheet.java | 1 + .../rest/controller/HTTPErrorController.java | 11 +- .../web/rest/controller/TetsimController.java | 2 +- .../spring/CustomRestMvcConfiguration.java | 22 +-- .../toolkit/web/spring/WebSecurityConfig.java | 77 ++++++++--- .../AbstractSpringDataRestControllerTest.java | 2 +- 62 files changed, 369 insertions(+), 246 deletions(-) diff --git a/forms/Dockerfile b/forms/Dockerfile index 527a99e5..71b58f2b 100644 --- a/forms/Dockerfile +++ b/forms/Dockerfile @@ -1,4 +1,4 @@ -FROM openjdk:11-jre-slim +FROM openjdk:17-jdk-slim WORKDIR /opt/devgateway/tcdi/admin COPY target/deps/BOOT-INF/lib lib COPY target/deps/META-INF META-INF diff --git a/forms/pom.xml b/forms/pom.xml index c2d52c4e..d9d81ceb 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -29,18 +29,20 @@ UTF-8 - 1.8 - 8.10.0 - 8.10.0 - 2.0.11 + 17 + 10.0.0 + 10.0.0 + 4.0.4 + 1.13 2.0.19 v20200406 3.1 2.4.8 - 1.86.0 - 5.15.3 - 2.36 + 2.2.0 + 6.5.2 + 3.1.9 + 4.1.3 @@ -186,7 +188,8 @@ de.agilecoders.wicket wicket-bootstrap-core - ${wicket.bootstrap.version} + 6.0.0 + javassist @@ -232,16 +235,16 @@ ${yuicompressor.version} - - de.agilecoders.wicket - wicket-bootstrap-themes - ${wicket.bootstrap.version} - + + + + + de.agilecoders.wicket wicket-bootstrap-less - ${wicket.bootstrap.version} + 4.0.4 @@ -297,9 +300,28 @@ org.springframework.cloud spring-cloud-starter-netflix-eureka-client - 2.2.10.RELEASE + ${netflix.eureka.version} + + + + com.sun.mail + jakarta.mail + 2.0.1 + + jakarta.servlet + jakarta.servlet-api + 6.1.0 + provided + + + + javax.servlet + javax.servlet-api + 4.0.1 + provided + @@ -380,10 +402,17 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + 3.11.0 ${java.version} ${java.version} + + + org.hibernate.orm + hibernate-jpamodelgen + ${hibernate.version} + + @@ -392,6 +421,13 @@ + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java b/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java index c9d97c36..071e91f1 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java @@ -20,10 +20,12 @@ import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.RememberMeAuthenticationProvider; +import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices; import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices; @@ -47,26 +49,26 @@ public class FormsSecurityConfig extends WebSecurityConfig { * and ignore security for css/js/images resources, and wicket mounted * resources */ - @Override - public void configure(final WebSecurity web) throws Exception { - super.configure(web); - String formsBasePath = settingsUtils.getFormsBasePath(); - web.ignoring().antMatchers(formsBasePath + "/img/**", - formsBasePath + "/css*/**", - formsBasePath + "/js*/**", - formsBasePath + "/assets*/**", formsBasePath + "/favicon.ico", formsBasePath + "/resources/**", - formsBasePath + "/resources/public/**"); - web.ignoring().antMatchers( - formsBasePath + "/wicket/resource/**/*.js", - formsBasePath + "/wicket/resource/**/*.css", - formsBasePath + "/wicket/resource/**/*.png", - formsBasePath + "/wicket/resource/**/*.jpg", - formsBasePath + "/wicket/resource/**/*.woff", - formsBasePath + "/wicket/resource/**/*.woff2", - formsBasePath + "/wicket/resource/**/*.ttf", - formsBasePath + "/wicket/resource/**/*.svg", - formsBasePath + "/wicket/resource/**/*.gif"); - } +// @Override +// public void configure(final WebSecurity web) throws Exception { +// super.configure(web); +// String formsBasePath = settingsUtils.getFormsBasePath(); +// web.ignoring().antMatchers(formsBasePath + "/img/**", +// formsBasePath + "/css*/**", +// formsBasePath + "/js*/**", +// formsBasePath + "/assets*/**", formsBasePath + "/favicon.ico", formsBasePath + "/resources/**", +// formsBasePath + "/resources/public/**"); +// web.ignoring().antMatchers( +// formsBasePath + "/wicket/resource/**/*.js", +// formsBasePath + "/wicket/resource/**/*.css", +// formsBasePath + "/wicket/resource/**/*.png", +// formsBasePath + "/wicket/resource/**/*.jpg", +// formsBasePath + "/wicket/resource/**/*.woff", +// formsBasePath + "/wicket/resource/**/*.woff2", +// formsBasePath + "/wicket/resource/**/*.ttf", +// formsBasePath + "/wicket/resource/**/*.svg", +// formsBasePath + "/wicket/resource/**/*.gif"); +// } /** * This bean defines the same key in the @@ -93,26 +95,74 @@ public AbstractRememberMeServices rememberMeServices() { return rememberMeServices; } - @Override - protected void configure(final HttpSecurity http) throws Exception { - super.configure(http); - - // we do not allow anyonymous token. When - // enabled this basically means any guest - // user will have an annoymous default role - http.anonymous().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER). - // we let Wicket create and manage sessions, so we disable - // session creation by spring - and().csrf().disable(); // csrf protection interferes with some - // wicket stuff +// @Override +// protected void configure(final HttpSecurity http) throws Exception { +// super.configure(http); +// +// // we do not allow anyonymous token. When +// // enabled this basically means any guest +// // user will have an annoymous default role +// http.anonymous().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER). +// // we let Wicket create and manage sessions, so we disable +// // session creation by spring +// and().csrf().disable(); // csrf protection interferes with some +// // wicket stuff +// +// // we enable http rememberMe cookie for autologin +// // http.rememberMe().key(UNIQUE_SECRET_REMEMBER_ME_KEY); +// +// // resolved the error Refused to display * in a frame because it set +// // 'X-Frame-Options' to 'DENY'. +// http.headers().contentTypeOptions().and().xssProtection().and().cacheControl().and() +// .httpStrictTransportSecurity().and().frameOptions().sameOrigin(); +// +// } - // we enable http rememberMe cookie for autologin - // http.rememberMe().key(UNIQUE_SECRET_REMEMBER_ME_KEY); + /** + * We ensure the superclass configuration is being applied Take note the + * {@link FormsSecurityConfig} extends {@link WebSecurityConfig} which has + * configuration for the dg-toolkit/web module. We then apply ant matchers + * and ignore security for css/js/images resources, and wicket mounted + * resources + */ + @Bean + public SecurityFilterChain formsSecurityFilterChain(HttpSecurity http) throws Exception { + String formsBasePath = settingsUtils.getFormsBasePath(); - // resolved the error Refused to display * in a frame because it set - // 'X-Frame-Options' to 'DENY'. - http.headers().contentTypeOptions().and().xssProtection().and().cacheControl().and() - .httpStrictTransportSecurity().and().frameOptions().sameOrigin(); + http.securityContext(securityContext -> + securityContext.securityContextRepository(httpSessionSecurityContextRepository()) + ) + .authorizeHttpRequests(authz -> authz + .requestMatchers(formsBasePath + "/monitoring/**").hasRole("ROLE_ADMIN") + .requestMatchers(formsBasePath + "/img/**", formsBasePath + "/css*/**", + formsBasePath + "/js*/**", formsBasePath + "/assets*/**", + formsBasePath + "/favicon.ico", formsBasePath + "/resources/**", + formsBasePath + "/wicket/resource/**/*.js", formsBasePath + "/wicket/resource/**/*.css", + formsBasePath + "/wicket/resource/**/*.png", formsBasePath + "/wicket/resource/**/*.jpg", + formsBasePath + "/wicket/resource/**/*.woff", formsBasePath + "/wicket/resource/**/*.woff2", + formsBasePath + "/wicket/resource/**/*.ttf", formsBasePath + "/wicket/resource/**/*.svg", + formsBasePath + "/wicket/resource/**/*.gif" + ).permitAll() // Ignore static resources + .requestMatchers(formsBasePath + "/**").authenticated() + ) + .formLogin(form -> + form.loginPage(formsBasePath + "/login").permitAll() + ) + .rememberMe(rememberMe -> + rememberMe.key(UNIQUE_SECRET_REMEMBER_ME_KEY).alwaysRemember(true) + ) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.NEVER)) + .csrf(csrf -> csrf.disable()) + .anonymous(anonymous -> anonymous.disable()) // Disable anonymous users + .headers(headers -> + headers.frameOptions(frameOptions -> frameOptions.sameOrigin()) + .contentTypeOptions(Customizer.withDefaults()) + .xssProtection(Customizer.withDefaults()) + .contentSecurityPolicy(csp -> csp + .policyDirectives("default-src 'self'; script-src 'self'; object-src 'none'")) + .cacheControl(Customizer.withDefaults()) + ); + return http.build(); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/JavaMelodyConfiguration.java b/forms/src/main/java/org/devgateway/toolkit/forms/JavaMelodyConfiguration.java index 2d714e31..574aff10 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/JavaMelodyConfiguration.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/JavaMelodyConfiguration.java @@ -29,8 +29,8 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; -import javax.servlet.DispatcherType; -import javax.servlet.ServletContext; +import jakarta.servlet.DispatcherType; +import jakarta.servlet.ServletContext; import java.util.Arrays; import java.util.EventListener; import java.util.HashSet; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java index 1d027d63..66514d9e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java @@ -11,19 +11,19 @@ import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import java.io.File; import java.io.IOException; import java.util.List; -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; -import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM; -import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM_TYPE; -import static javax.ws.rs.core.MediaType.MULTIPART_FORM_DATA_TYPE; -import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE; -import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL; +import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON; +import static jakarta.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM; +import static jakarta.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM_TYPE; +import static jakarta.ws.rs.core.MediaType.MULTIPART_FORM_DATA_TYPE; +import static jakarta.ws.rs.core.MediaType.TEXT_PLAIN_TYPE; +import static jakarta.ws.rs.core.Response.Status.Family.SUCCESSFUL; import static org.devgateway.toolkit.forms.client.ClientConstants.CODE_PREFIX; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_CODE; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_DATASETS; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceCategoryClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceCategoryClient.java index 53701cfb..129e0471 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceCategoryClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceCategoryClient.java @@ -2,7 +2,7 @@ import org.devgateway.toolkit.persistence.dto.ServiceCategory; -import javax.ws.rs.core.GenericType; +import jakarta.ws.rs.core.GenericType; import java.util.List; public class ServiceCategoryClient extends ServiceEntityClient { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDatasetClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDatasetClient.java index 2d410a55..fc02833c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDatasetClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDatasetClient.java @@ -2,12 +2,12 @@ import org.devgateway.toolkit.persistence.dto.ServiceDataset; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import java.util.List; -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; -import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL; +import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON; +import static jakarta.ws.rs.core.Response.Status.Family.SUCCESSFUL; public class ServiceDatasetClient extends ServiceEntityClient { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDimensionClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDimensionClient.java index 2e8a8002..e5f4e06f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDimensionClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceDimensionClient.java @@ -2,7 +2,7 @@ import org.devgateway.toolkit.persistence.dto.ServiceDimension; -import javax.ws.rs.core.GenericType; +import jakarta.ws.rs.core.GenericType; import java.util.List; public class ServiceDimensionClient extends ServiceEntityClient { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceEntityClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceEntityClient.java index 932d6345..ec5c6122 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceEntityClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceEntityClient.java @@ -5,13 +5,13 @@ import org.glassfish.jersey.client.JerseyClientBuilder; import org.glassfish.jersey.media.multipart.MultiPartFeature; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import java.util.List; -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; -import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL; +import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON; +import static jakarta.ws.rs.core.Response.Status.Family.SUCCESSFUL; import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_HEALTH; public abstract class ServiceEntityClient { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceFilterClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceFilterClient.java index 1c2e0e43..6479a138 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceFilterClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceFilterClient.java @@ -2,7 +2,7 @@ import org.devgateway.toolkit.persistence.dto.ServiceFilter; -import javax.ws.rs.core.GenericType; +import jakarta.ws.rs.core.GenericType; import java.util.List; public class ServiceFilterClient extends ServiceEntityClient { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceMeasureClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceMeasureClient.java index 274d29d4..bc325d27 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceMeasureClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ServiceMeasureClient.java @@ -2,7 +2,7 @@ import org.devgateway.toolkit.persistence.dto.ServiceMeasure; -import javax.ws.rs.core.GenericType; +import jakarta.ws.rs.core.GenericType; import java.util.List; public class ServiceMeasureClient extends ServiceEntityClient { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/SessionFinderService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/SessionFinderService.java index 760f5c35..c9f0ee71 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/SessionFinderService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/SessionFinderService.java @@ -16,8 +16,8 @@ import org.hibernate.Session; import org.springframework.stereotype.Component; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; /** * Spring Service allowing access to hibernate session. This is needed by diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java index aa6ba764..d5b3a122 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java @@ -32,7 +32,7 @@ import org.apache.wicket.ajax.AjaxNewWindowNotifyingBehavior; import org.apache.wicket.authroles.authentication.AuthenticatedWebApplication; import org.apache.wicket.authroles.authentication.AuthenticatedWebSession; -import org.apache.wicket.devutils.diskstore.DebugDiskDataStore; +//import org.apache.wicket.devutils.diskstore.DebugDiskDataStore; import org.apache.wicket.markup.html.IPackageResourceGuard; import org.apache.wicket.markup.html.SecurePackageResourceGuard; import org.apache.wicket.markup.html.WebPage; @@ -59,7 +59,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +//import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; @@ -81,7 +82,7 @@ @EnableScheduling @SpringBootApplication(exclude = {org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration.class}) @ComponentScan("org.devgateway.toolkit") -@EnableEurekaClient +@EnableDiscoveryClient @PropertySource("classpath:/org/devgateway/toolkit/forms/application.properties") public class FormsWebApplication extends AuthenticatedWebApplication { @@ -168,7 +169,7 @@ private void configureBootstrap() { */ private void optimizeForWebPerformance() { // add javascript files at the bottom of the page - setHeaderResponseDecorator(new RenderJavaScriptToFooterHeaderResponseDecorator("scripts-bucket")); +// setHeaderResponseDecorator(new RenderJavaScriptToFooterHeaderResponseDecorator("scripts-bucket")); // This is only enabled for deployment configuration // -Dwicket.configuration=deployment @@ -243,9 +244,9 @@ protected void init() { // watch this using the URL // http://.../wicket/internal/debug/diskDataStore - if (usesDevelopmentConfig()) { - DebugDiskDataStore.register(this); - } +// if (usesDevelopmentConfig()) { +// DebugDiskDataStore.register(this); +// } SessionFinderHolder.setSessionFinder(sessionFinderService); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/SSAuthenticatedWebSession.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/SSAuthenticatedWebSession.java index e77c261e..b01c0a10 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/SSAuthenticatedWebSession.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/SSAuthenticatedWebSession.java @@ -29,8 +29,8 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.RememberMeServices; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.util.Collection; /** diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/WebInitializer.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/WebInitializer.java index 395699b6..960d2b59 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/WebInitializer.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/WebInitializer.java @@ -19,9 +19,9 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.web.session.HttpSessionEventPublisher; -import javax.servlet.FilterRegistration; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; +import jakarta.servlet.FilterRegistration; +import jakarta.servlet.ServletContext; +import jakarta.servlet.ServletException; /** * This class is the replacement of the web.xml. It registers the wicket filter diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/FileInputBootstrapFormComponent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/FileInputBootstrapFormComponent.java index 954dc58d..bbd62cd0 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/FileInputBootstrapFormComponent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/FileInputBootstrapFormComponent.java @@ -19,7 +19,7 @@ import org.devgateway.toolkit.persistence.dao.FileMetadata; import org.devgateway.toolkit.persistence.dao.GenericPersistable; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.util.Arrays; import java.util.Collection; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/GenericBootstrapFormComponent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/GenericBootstrapFormComponent.java index f02095a0..b2b84fd1 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/GenericBootstrapFormComponent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/GenericBootstrapFormComponent.java @@ -41,7 +41,7 @@ import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.query.AuditQuery; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.util.ArrayList; import java.util.List; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/Select2ChoiceBootstrapFormComponent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/Select2ChoiceBootstrapFormComponent.java index c6f1ec7b..b9e0206a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/Select2ChoiceBootstrapFormComponent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/Select2ChoiceBootstrapFormComponent.java @@ -21,7 +21,7 @@ import org.wicketstuff.select2.Select2BootstrapTheme; import org.wicketstuff.select2.Select2Choice; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; /** * @author mpostelnicu diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/Select2MultiChoiceBootstrapFormComponent.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/Select2MultiChoiceBootstrapFormComponent.java index 2f1fa64a..ac62bc69 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/Select2MultiChoiceBootstrapFormComponent.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/Select2MultiChoiceBootstrapFormComponent.java @@ -21,7 +21,7 @@ import org.wicketstuff.select2.Select2BootstrapTheme; import org.wicketstuff.select2.Select2MultiChoice; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.util.Collection; /** diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/ToolkitSummernoteEditor.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/ToolkitSummernoteEditor.java index e2e72f71..5e930af0 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/ToolkitSummernoteEditor.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/ToolkitSummernoteEditor.java @@ -12,8 +12,8 @@ import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeCssReference; import de.agilecoders.wicket.extensions.markup.html.bootstrap.references.SpinJsReference; import de.agilecoders.wicket.jquery.IKey; -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload2.core.FileItem; +import org.apache.commons.fileupload2.core.FileUploadException; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java index 695f9d6b..2ddd08c3 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/CSVDatasetFilterState.java @@ -7,7 +7,7 @@ import org.devgateway.toolkit.persistence.repository.SpecificationContext; import org.springframework.data.jpa.domain.Specification; -import javax.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Predicate; import java.util.ArrayList; import java.util.List; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/JpaFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/JpaFilterState.java index b9739a76..8ae6207d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/JpaFilterState.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/JpaFilterState.java @@ -7,7 +7,7 @@ import org.devgateway.toolkit.persistence.repository.SpecificationContext; import org.springframework.data.jpa.domain.Specification; -import javax.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Predicate; import java.io.Serializable; import java.util.List; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TestFormFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TestFormFilterState.java index 36596736..18889902 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TestFormFilterState.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TestFormFilterState.java @@ -6,7 +6,7 @@ import org.devgateway.toolkit.persistence.repository.SpecificationContext; import org.springframework.data.jpa.domain.Specification; -import javax.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Predicate; import java.util.ArrayList; import java.util.List; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java index b41d09e0..77f2be4a 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/table/filter/TetsimDatasetFilterState.java @@ -7,7 +7,7 @@ import org.devgateway.toolkit.persistence.repository.SpecificationContext; import org.springframework.data.jpa.domain.Specification; -import javax.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Predicate; import java.util.ArrayList; import java.util.List; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index a1b12bc9..4592d18d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -20,7 +20,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.NavbarButton; import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.NavbarComponents; import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.NavbarDropDownButton; -import de.agilecoders.wicket.core.markup.html.references.RespondJavaScriptReference; +//import de.agilecoders.wicket.core.markup.html.references.RespondJavaScriptReference; import de.agilecoders.wicket.core.markup.html.themes.bootstrap.BootstrapCssReference; import de.agilecoders.wicket.core.util.CssClassNames; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5CssReference; @@ -339,8 +339,8 @@ public void renderHead(final IHeaderResponse response) { response.render(CssHeaderItem.forReference(BaseStyles.INSTANCE)); // Load Scripts. - response.render(RespondJavaScriptReference.headerItem()); - response.render(JavaScriptHeaderItem.forReference(JQueryResourceReference.getV2())); +// response.render(RespondJavaScriptReference.headerItem()); + response.render(JavaScriptHeaderItem.forReference(JQueryResourceReference.getV3())); response.render(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(BaseStyles.class, "assets/js/fileupload.js"))); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Header.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Header.java index 13870ee4..cf356de2 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Header.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/Header.java @@ -97,7 +97,7 @@ protected void onConfigure() { add(rebootAlert); MetaDataRoleAuthorizationStrategy.authorize(rebootAlert, Component.RENDER, SecurityConstants.Roles.ROLE_USER); - add(new AbstractAjaxTimerBehavior(org.apache.wicket.util.time.Duration.seconds(ALERT_UPDATE_INTERVAL_SECONDS)) { + add(new AbstractAjaxTimerBehavior(Duration.ofSeconds(ALERT_UPDATE_INTERVAL_SECONDS)) { private static final long serialVersionUID = -1168209018766325709L; @Override diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/RevisionsPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/RevisionsPage.java index 93b52985..1bb66b56 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/RevisionsPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/RevisionsPage.java @@ -28,7 +28,7 @@ import org.wicketstuff.annotation.mount.MountPath; import org.wicketstuff.datetime.markup.html.basic.DateLabel; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.util.ArrayList; import java.util.List; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java index 3bdd3707..58561ab1 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java @@ -50,7 +50,7 @@ import org.springframework.dao.DataIntegrityViolationException; import org.springframework.orm.ObjectOptimisticLockingFailureException; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.io.Serializable; /** diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index d659c266..56412327 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -40,7 +40,6 @@ import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.util.string.Strings; -import org.apache.wicket.util.time.Duration; import org.apache.wicket.util.visit.IVisit; import org.apache.wicket.util.visit.IVisitor; import org.devgateway.toolkit.forms.WebConstants; @@ -62,6 +61,7 @@ import org.wicketstuff.select2.Select2Choice; import java.text.MessageFormat; +import java.time.Duration; import static org.devgateway.toolkit.forms.WebConstants.PARAM_AUTO_SAVE; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DRAFT; @@ -457,7 +457,7 @@ private void addAutosaveBehavior(final AjaxRequestTarget target) { private AbstractAjaxTimerBehavior getAutosaveBehavior() { final AbstractAjaxTimerBehavior ajaxTimerBehavior = new AbstractAjaxTimerBehavior( - Duration.minutes(adminSettingsService.getAutosaveTime())) { + Duration.ofMinutes(adminSettingsService.getAutosaveTime())) { @Override protected void onTimer(final AjaxRequestTarget target) { // display block UI message until the page is reloaded diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java index 5c692106..dcc56bad 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java @@ -36,7 +36,7 @@ import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.wicketstuff.annotation.mount.MountPath; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.DELETED; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java index b07bdb27..e400c844 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java @@ -57,7 +57,7 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.Serializable; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LoginPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LoginPage.java index 28d37ec8..a6ed56fa 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LoginPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LoginPage.java @@ -28,7 +28,7 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.util.string.StringValue; -import org.apache.wicket.util.time.Duration; +//import org.apache.wicket.util.time.Duration; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityUtil; import org.devgateway.toolkit.forms.wicket.SSAuthenticatedWebSession; @@ -42,8 +42,9 @@ import org.springframework.security.web.savedrequest.SavedRequest; import org.wicketstuff.annotation.mount.MountPath; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.io.Serializable; +import java.time.Duration; /** * @author mpostelnicu @@ -124,7 +125,8 @@ protected void onInitialize() { retrieveReferrerFromSavedRequestIfPresent(); final NotificationPanel notificationPanel = new NotificationPanel("loginFeedback"); - notificationPanel.hideAfter(Duration.seconds(HIDE_NOTIFICATION_SECONDS)); +// notificationPanel.hideAfter(Duration.seconds(HIDE_NOTIFICATION_SECONDS)); + notificationPanel.hideAfter(Duration.ofSeconds(HIDE_NOTIFICATION_SECONDS)); notificationPanel.setOutputMarkupId(true); add(notificationPanel); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LogoutPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LogoutPage.java index 633ac913..d96496b8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LogoutPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LogoutPage.java @@ -21,8 +21,8 @@ import org.springframework.security.web.authentication.RememberMeServices; import org.wicketstuff.annotation.mount.MountPath; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; /** * @author mpostelnicu diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BlockUiJavaScript.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BlockUiJavaScript.java index ef16b8a6..62612529 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BlockUiJavaScript.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BlockUiJavaScript.java @@ -39,7 +39,7 @@ public BlockUiJavaScript() { public List getDependencies() { final List dependencies = Lists.newArrayList(super.getDependencies()); - dependencies.add(JavaScriptHeaderItem.forReference(JQueryResourceReference.getV2())); + dependencies.add(JavaScriptHeaderItem.forReference(JQueryResourceReference.getV3())); dependencies.add(JavaScriptHeaderItem .forReference(new JavaScriptResourceReference(EmptyCss.class, "/assets/js/jquery.blockUI.js"))); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BlockUiReportsJavaScript.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BlockUiReportsJavaScript.java index e9cfe8ea..55e20ea8 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BlockUiReportsJavaScript.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/styles/BlockUiReportsJavaScript.java @@ -39,7 +39,7 @@ public BlockUiReportsJavaScript() { public List getDependencies() { final List dependencies = Lists.newArrayList(super.getDependencies()); - dependencies.add(JavaScriptHeaderItem.forReference(JQueryResourceReference.getV2())); + dependencies.add(JavaScriptHeaderItem.forReference(JQueryResourceReference.getV3())); dependencies.add(JavaScriptHeaderItem .forReference(new JavaScriptResourceReference(EmptyCss.class, "/assets/js/jquery.blockUI.js"))); diff --git a/forms/src/test/java/org/devgateway/toolkit/forms/client/DatasetClientTest.java b/forms/src/test/java/org/devgateway/toolkit/forms/client/DatasetClientTest.java index 75cba8e2..412dfc37 100644 --- a/forms/src/test/java/org/devgateway/toolkit/forms/client/DatasetClientTest.java +++ b/forms/src/test/java/org/devgateway/toolkit/forms/client/DatasetClientTest.java @@ -2,8 +2,8 @@ import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.FileNotFoundException; import java.io.IOException; @@ -18,7 +18,7 @@ public class DatasetClientTest { private String baseUrl = "http://localhost:8084/"; - @Before + @BeforeEach public void initClient() { this.client = new DatasetClient(baseUrl); } diff --git a/persistence/pom.xml b/persistence/pom.xml index eedc1050..30ebe6bb 100644 --- a/persistence/pom.xml +++ b/persistence/pom.xml @@ -111,7 +111,7 @@ org.hibernate hibernate-jcache - 7.0.0.Beta1 + ${hibernate.version} @@ -121,14 +121,14 @@ org.hibernate - hibernate-entitymanager - 6.0.0.Alpha7 + hibernate-core + ${hibernate.version} org.hibernate hibernate-envers - 6.6.1.Final + ${hibernate.version} hibernate-entitymanager @@ -140,7 +140,7 @@ org.hibernate hibernate-jpamodelgen - 6.6.1.Final + ${hibernate.version} provided @@ -262,18 +262,25 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + 3.11.0 ${java.version} ${java.version} -proc:none + + + org.hibernate + hibernate-jpamodelgen + ${hibernate.version} + + org.bsc.maven maven-processor-plugin - 3.3.3 + 5.1 process @@ -291,7 +298,7 @@ org.codehaus.mojo build-helper-maven-plugin - 1.3 + 3.6.0 add-source diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractAuditableEntity.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractAuditableEntity.java index edb52902..349391db 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractAuditableEntity.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AbstractAuditableEntity.java @@ -16,9 +16,9 @@ import org.springframework.data.domain.Auditable; import org.springframework.data.jpa.domain.support.AuditingEntityListener; -import javax.persistence.EntityListeners; -import javax.persistence.MappedSuperclass; -import javax.persistence.PreUpdate; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import jakarta.persistence.PreUpdate; import java.time.ZonedDateTime; import java.util.Optional; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java index fed9346d..8f671f1f 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/AdminSettings.java @@ -4,7 +4,7 @@ import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; -import javax.persistence.Entity; +import jakarta.persistence.Entity; import java.time.Duration; import java.time.LocalDateTime; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileMetadata.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileMetadata.java index 3e9dbd8f..9ff43c2c 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileMetadata.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileMetadata.java @@ -14,12 +14,12 @@ import org.hibernate.envers.Audited; import org.hibernate.envers.RelationTargetAuditMode; -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.Index; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Index; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; /** * @author idobre diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Person.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Person.java index ba2abe0a..3859d1f1 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Person.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Person.java @@ -20,13 +20,13 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.Index; -import javax.persistence.ManyToMany; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.persistence.Transient; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Index; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; import java.util.Collection; import java.util.List; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Role.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Role.java index 75640f78..7a382448 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Role.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/Role.java @@ -15,10 +15,10 @@ import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Index; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Index; +import jakarta.persistence.Table; /** * @author mpostelnicu diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/StatusChangedComment.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/StatusChangedComment.java index f3cd6a2a..a430e8cc 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/StatusChangedComment.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/StatusChangedComment.java @@ -4,10 +4,10 @@ import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Index; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Index; +import jakarta.persistence.Table; @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @Entity diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/TestForm.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/TestForm.java index 3015b9cc..bba0a256 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/TestForm.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/TestForm.java @@ -20,14 +20,14 @@ import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ManyToMany; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.OrderColumn; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.OrderColumn; import java.util.ArrayList; import java.util.Date; import java.util.List; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/TestFormChild.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/TestFormChild.java index ea43d796..e683445e 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/TestFormChild.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/TestFormChild.java @@ -4,10 +4,10 @@ import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; -import javax.persistence.Entity; -import javax.persistence.Index; -import javax.persistence.ManyToOne; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.Index; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; /** * @author idobre diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Category.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Category.java index b102119b..51bd6a36 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Category.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Category.java @@ -17,10 +17,10 @@ import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; -import javax.persistence.DiscriminatorColumn; -import javax.persistence.Entity; -import javax.persistence.Index; -import javax.persistence.Table; +import jakarta.persistence.DiscriminatorColumn; +import jakarta.persistence.Entity; +import jakarta.persistence.Index; +import jakarta.persistence.Table; /** * @author idobre diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Group.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Group.java index aeca60f2..3850016d 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Group.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Group.java @@ -16,9 +16,9 @@ import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.OneToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.OneToMany; import java.util.HashSet; import java.util.Set; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/CSVDataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/CSVDataset.java index d1bd1758..fa9301a4 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/CSVDataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/CSVDataset.java @@ -5,9 +5,9 @@ import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.OneToMany; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.OneToMany; import java.util.Set; @Entity diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java index 9c21b41e..68f1276d 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimDataset.java @@ -4,10 +4,10 @@ import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.OneToOne; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.OneToOne; import java.math.BigDecimal; @Entity diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimPriceVariable.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimPriceVariable.java index aeb53876..fb015e94 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimPriceVariable.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimPriceVariable.java @@ -5,10 +5,10 @@ import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; import java.util.HashSet; import java.util.Set; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java index d7b03206..8cce7e60 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/TetsimTobaccoProductValue.java @@ -5,8 +5,8 @@ import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.envers.Audited; -import javax.persistence.Entity; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.ManyToOne; import java.math.BigDecimal; @Entity diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/SpecificationContext.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/SpecificationContext.java index ea6b044b..93ea2d9c 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/SpecificationContext.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/SpecificationContext.java @@ -1,8 +1,8 @@ package org.devgateway.toolkit.persistence.repository; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; /** * @author Nadejda Mandrescu diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java index f1b29d96..c1b3244a 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/CSVDatasetRepository.java @@ -5,7 +5,7 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import java.util.List; @Transactional diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java index 29408d8a..ab9c87b2 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/data/TetsimDatasetRepository.java @@ -5,7 +5,7 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import java.util.List; @Transactional diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java index 6917ca26..4375d178 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/DatabaseConfiguration.java @@ -27,7 +27,7 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; -import javax.persistence.EntityManagerFactory; +import jakarta.persistence.EntityManagerFactory; import javax.sql.DataSource; /** diff --git a/pom.xml b/pom.xml index afa533b8..5b247af5 100644 --- a/pom.xml +++ b/pom.xml @@ -26,13 +26,15 @@ 3.2.10 10.17.1.0 - 5.3.0 + 4.1.2 devgateway/toolkit 1.2.2 3.5.0 3.5.1 3.1.1 3.30.2-GA + 6.6.1.Final + 2023.0.3 @@ -125,6 +127,14 @@ mongo-java-driver ${mongo.version} + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + @@ -190,8 +200,8 @@ org.apache.maven.plugins maven-compiler-plugin - 1.8 - 1.8 + 17 + 17 diff --git a/web/src/main/java/org/devgateway/toolkit/web/excelcharts/ExcelChartSheet.java b/web/src/main/java/org/devgateway/toolkit/web/excelcharts/ExcelChartSheet.java index 4477f9eb..f7dc3c59 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/excelcharts/ExcelChartSheet.java +++ b/web/src/main/java/org/devgateway/toolkit/web/excelcharts/ExcelChartSheet.java @@ -4,6 +4,7 @@ import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.charts.ChartDataSource; import org.apache.poi.xddf.usermodel.chart.XDDFDataSource; +import org.apache.poi.xssf.usermodel.XSSFChart; import java.util.List; diff --git a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/HTTPErrorController.java b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/HTTPErrorController.java index 840c09c4..3a85b99b 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/HTTPErrorController.java +++ b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/HTTPErrorController.java @@ -7,9 +7,9 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import javax.servlet.RequestDispatcher; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; /** @@ -21,11 +21,6 @@ public class HTTPErrorController implements ErrorController { @Autowired private SettingsUtils settingsUtils; - @Override - public String getErrorPath() { - return null; - } - @RequestMapping("/error") public void handleError(final HttpServletRequest request, final HttpServletResponse response) throws IOException { Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); diff --git a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java index a2fe8920..be8deb38 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java +++ b/web/src/main/java/org/devgateway/toolkit/web/rest/controller/TetsimController.java @@ -12,7 +12,7 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; diff --git a/web/src/main/java/org/devgateway/toolkit/web/spring/CustomRestMvcConfiguration.java b/web/src/main/java/org/devgateway/toolkit/web/spring/CustomRestMvcConfiguration.java index 160ab216..383947a5 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/spring/CustomRestMvcConfiguration.java +++ b/web/src/main/java/org/devgateway/toolkit/web/spring/CustomRestMvcConfiguration.java @@ -1,28 +1,16 @@ package org.devgateway.toolkit.web.spring; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.core.mapping.RepositoryDetectionStrategy.RepositoryDetectionStrategies; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer; +import org.springframework.web.servlet.config.annotation.CorsRegistry; -/** - * We only allow to expose repositories that are annotated - * - * @author mpostelnicu - * http://docs.spring.io/spring-data/rest/docs/current/reference/html/#_which_repositories_get_exposed_by_defaults - */ @Configuration -public class CustomRestMvcConfiguration { +public class CustomRestMvcConfiguration implements RepositoryRestConfigurer { - @Bean - public RepositoryRestConfigurer repositoryRestConfigurer() { - return new RepositoryRestConfigurer() { - - @Override - public void configureRepositoryRestConfiguration(final RepositoryRestConfiguration config) { - config.setRepositoryDetectionStrategy(RepositoryDetectionStrategies.ANNOTATED); - } - }; + @Override + public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) { + config.setRepositoryDetectionStrategy(RepositoryDetectionStrategies.ANNOTATED); } } \ No newline at end of file diff --git a/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java b/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java index b7f88982..b4fe01b4 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java +++ b/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java @@ -25,13 +25,16 @@ import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.FilterInvocation; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.security.web.context.SecurityContextPersistenceFilter; import org.springframework.security.web.firewall.HttpFirewall; @@ -51,7 +54,7 @@ // them overlayed, it must pick that one first) @PropertySource("classpath:allowedApiEndpoints.properties") @EnableWebSecurity -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { +public class WebSecurityConfig { @Autowired protected CustomJPAUserDetailsService customJPAUserDetailsService; @@ -89,14 +92,14 @@ public SecurityContextPersistenceFilter securityContextPersistenceFilter() { return securityContextPersistenceFilter; } - @Override - public void configure(final WebSecurity web) throws Exception { - web.httpFirewall(allowUrlEncodedSlashHttpFirewall()) - .ignoring().antMatchers(getAllowedAPIEndpointsWithBasePath()).and() - .ignoring().antMatchers( - settingsUtils.getFormsBasePath() + "/login", - settingsUtils.getFormsBasePath() + "/forgotPassword/**"); - } +// @Override +// public void configure(final WebSecurity web) throws Exception { +// web.httpFirewall(allowUrlEncodedSlashHttpFirewall()) +// .ignoring().antMatchers(getAllowedAPIEndpointsWithBasePath()).and() +// .ignoring().antMatchers( +// settingsUtils.getFormsBasePath() + "/login", +// settingsUtils.getFormsBasePath() + "/forgotPassword/**"); +// } private String[] getAllowedAPIEndpointsWithBasePath() { if (allowedApiEndpoints != null) { @@ -108,15 +111,46 @@ private String[] getAllowedAPIEndpointsWithBasePath() { return new String[]{}; } - @Override - protected void configure(final HttpSecurity http) throws Exception { - http.authorizeRequests().expressionHandler(webExpressionHandler()) // inject role hierarchy - .antMatchers(settingsUtils.getFormsBasePath() + "/monitoring/**").access("hasRole('ROLE_ADMIN')") - .antMatchers(settingsUtils.getFormsBasePath() + "/**").authenticated().and() - .formLogin().loginPage(settingsUtils.getFormsBasePath() + "/login").permitAll().and() - .requestCache().and().logout().permitAll().and() - .sessionManagement().and().csrf().disable(); - http.addFilter(securityContextPersistenceFilter()); +// @Override +// protected void configure(final HttpSecurity http) throws Exception { +// http.authorizeRequests().expressionHandler(webExpressionHandler()) // inject role hierarchy +// .antMatchers(settingsUtils.getFormsBasePath() + "/monitoring/**").access("hasRole('ROLE_ADMIN')") +// .antMatchers(settingsUtils.getFormsBasePath() + "/**").authenticated().and() +// .formLogin().loginPage(settingsUtils.getFormsBasePath() + "/login").permitAll().and() +// .requestCache().and().logout().permitAll().and() +// .sessionManagement().and().csrf().disable(); +// http.addFilter(securityContextPersistenceFilter()); +// } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http.securityContext(securityContext -> securityContext.securityContextRepository(httpSessionSecurityContextRepository())) + .authorizeHttpRequests(authz -> authz + .requestMatchers(settingsUtils.getFormsBasePath() + "/monitoring/**").hasRole("ROLE_ADMIN") + .requestMatchers(settingsUtils.getFormsBasePath() + "/**").authenticated() + ) + .formLogin(form -> form + .loginPage(settingsUtils.getFormsBasePath() + "/login").permitAll() + ) + .requestCache(requestCache -> requestCache.disable()) + .logout(logout -> logout.permitAll()) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)) + .csrf(csrf -> csrf.disable()); + + // Apply the custom SecurityExpressionHandler here + http.setSharedObject(SecurityExpressionHandler.class, webExpressionHandler()); + + // Firewall configuration, equivalent to 'allowUrlEncodedSlashHttpFirewall' + http.getSharedObject(WebSecurity.class) + .httpFirewall(allowUrlEncodedSlashHttpFirewall()); + + // Ignoring paths (migrated from 'configure(WebSecurity web)') + http.getSharedObject(WebSecurity.class) + .ignoring() + .requestMatchers(getAllowedAPIEndpointsWithBasePath()) + .requestMatchers(settingsUtils.getFormsBasePath() + "/login", settingsUtils.getFormsBasePath() + "/forgotPassword/**"); + + return http.build(); } /** @@ -143,9 +177,8 @@ RoleHierarchy roleHierarchy() { } @Bean - @Override - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); + public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { + return authenticationConfiguration.getAuthenticationManager(); } @Autowired diff --git a/web/src/test/java/org/devgateway/toolkit/web/AbstractSpringDataRestControllerTest.java b/web/src/test/java/org/devgateway/toolkit/web/AbstractSpringDataRestControllerTest.java index cc9809b5..3021373e 100644 --- a/web/src/test/java/org/devgateway/toolkit/web/AbstractSpringDataRestControllerTest.java +++ b/web/src/test/java/org/devgateway/toolkit/web/AbstractSpringDataRestControllerTest.java @@ -8,7 +8,7 @@ import java.util.Collections; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.junit.Before; From 7e7ab3728d8c42a86cb823fc5f21ff8eb35e82ce Mon Sep 17 00:00:00 2001 From: Denis Mbugua <60645043+dynamodenis@users.noreply.github.com> Date: Tue, 29 Oct 2024 13:09:09 +0300 Subject: [PATCH 127/137] DVIZ-12 upgraded persistent and forms --- forms/pom.xml | 38 ++- .../toolkit/forms/FormsSecurityConfig.java | 2 +- .../toolkit/forms/application-dev.properties | 5 +- .../toolkit/forms/application.properties | 5 +- .../forms/util/MarkupCacheService.java | 28 +- .../forms/wicket/FormsWebApplication.java | 4 +- .../buttons/ladda/LaddaAjaxButton.java | 62 ++++ .../buttons/ladda/LaddaAjaxCallListener.java | 10 + .../buttons/ladda/LaddaBehavior.java | 80 +++++ .../buttons/ladda/LaddaCssReference.java | 11 + .../buttons/ladda/LaddaJsReference.java | 11 + .../buttons/ladda/css/ladda-themeless.css | 314 ++++++++++++++++++ .../buttons/ladda/css/ladda-themeless.min.css | 1 + .../components/buttons/ladda/js/ladda.js | 160 +++++++++ .../components/buttons/ladda/js/ladda.min.js | 1 + .../components/form/BootstrapAddButton.java | 2 +- .../form/BootstrapCancelButton.java | 2 +- .../form/BootstrapDeleteButton.java | 2 +- .../form/BootstrapSubmitButton.java | 2 +- .../form/ToolkitSummernoteEditor.java | 4 +- .../wicket/page/edit/AbstractEditPage.java | 2 +- .../edit/AbstractEditStatusEntityPage.java | 2 +- .../admin/AbstractEditServiceEntityPage.java | 2 +- .../page/edit/dataset/EditCSVDatasetPage.java | 2 +- .../wicket/page/lists/AbstractListPage.java | 2 +- .../forms/wicket/page/user/LoginPage.java | 1 - persistence/pom.xml | 18 +- .../persistence/application-dev.properties | 4 +- .../persistence/application.properties | 7 +- .../toolkit/persistence/dao/FileContent.java | 4 +- .../spring/CacheConfiguration.java | 22 +- persistence/src/main/resources/ehcache.xml | 9 +- pom.xml | 2 +- .../toolkit/web/spring/WebSecurityConfig.java | 32 +- 34 files changed, 785 insertions(+), 68 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaAjaxButton.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaAjaxCallListener.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaBehavior.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaCssReference.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaJsReference.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/css/ladda-themeless.css create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/css/ladda-themeless.min.css create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/js/ladda.js create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/js/ladda.min.js diff --git a/forms/pom.xml b/forms/pom.xml index d9d81ceb..cecb342a 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -32,10 +32,10 @@ 17 10.0.0 10.0.0 - 4.0.4 - + + 7.0.0 1.13 - 2.0.19 + 4.0.5 v20200406 3.1 2.4.8 @@ -189,7 +189,6 @@ de.agilecoders.wicket wicket-bootstrap-core 6.0.0 - javassist @@ -235,11 +234,11 @@ ${yuicompressor.version} - - - - - + + de.agilecoders.wicket + wicket-bootstrap-themes + ${wicket.bootstrap.version} + de.agilecoders.wicket @@ -322,6 +321,27 @@ 4.0.1 provided + + + com.sun.jersey.contribs + jersey-apache-client4 + 1.19.4 + + + + + + + + + + + + + + + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java b/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java index 071e91f1..46e499c0 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java @@ -133,7 +133,7 @@ public SecurityFilterChain formsSecurityFilterChain(HttpSecurity http) throws Ex securityContext.securityContextRepository(httpSessionSecurityContextRepository()) ) .authorizeHttpRequests(authz -> authz - .requestMatchers(formsBasePath + "/monitoring/**").hasRole("ROLE_ADMIN") + .requestMatchers(formsBasePath + "/monitoring/**").hasRole("ADMIN") .requestMatchers(formsBasePath + "/img/**", formsBasePath + "/css*/**", formsBasePath + "/js*/**", formsBasePath + "/assets*/**", formsBasePath + "/favicon.ico", formsBasePath + "/resources/**", diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/application-dev.properties b/forms/src/main/java/org/devgateway/toolkit/forms/application-dev.properties index 131b8f0a..ad7b5d54 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/application-dev.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/application-dev.properties @@ -1 +1,4 @@ -eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ \ No newline at end of file +eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ +eureka.client.registerWithEureka=true +eureka.client.fetchRegistry=true +eureka.instance.metadata-map.type=data \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/application.properties b/forms/src/main/java/org/devgateway/toolkit/forms/application.properties index 29b258a3..ee2baf37 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/application.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/application.properties @@ -24,4 +24,7 @@ spring.aop.proxy-target-class=true server.tomcat.remote-ip-header=x-forwarded-for server.tomcat.protocol-header=x-forwarded-proto -eureka.client.serviceUrl.defaultZone=http://eureka:8761/eureka/ \ No newline at end of file +eureka.client.serviceUrl.defaultZone=http://eureka:8761/eureka/ +eureka.instance.preferIpAddress=true +eureka.client.registerWithEureka=true +eureka.client.fetchRegistry=true \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/util/MarkupCacheService.java b/forms/src/main/java/org/devgateway/toolkit/forms/util/MarkupCacheService.java index 0d668aa8..7b55513d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/util/MarkupCacheService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/util/MarkupCacheService.java @@ -17,8 +17,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import javax.cache.Cache; -import javax.cache.CacheManager; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; + import java.util.Collection; /** @@ -68,7 +69,7 @@ public void addPentahoReportToCache(final String outputType, final String report final byte[] buffer) { // get the reports cache "reportsCache", declared in ehcache.xml - final Cache cache = cm.getCache("reportsCache", String.class, byte[].class); + final Cache cache = cm.getCache("reportsCache"); cache.put(createCacheKey(outputType, reportName, parameters), buffer); } @@ -84,12 +85,11 @@ public void addPentahoReportToCache(final String outputType, final String report public byte[] getPentahoReportFromCache(final String outputType, final String reportName, final String parameters) { // get the reports cache "reportsCache", declared in ehcache.xml - final Cache cache = cm.getCache("reportsCache", String.class, byte[].class); - - final String key = createCacheKey(outputType, reportName, parameters); + final Cache cache = cm.getCache("reportsCache"); - if (cache.containsKey(key)) { - return cache.get(key); + if (cache != null) { + String key = createCacheKey(outputType, reportName, parameters); + return cache.get(key, byte[].class); } return null; @@ -101,10 +101,10 @@ public byte[] getPentahoReportFromCache(final String outputType, final String re public void clearPentahoReportsCache() { // get the reports cache "reportsCache", declared in ehcache.xml - final Cache cache = cm.getCache("reportsCache"); + final Cache cache = cm.getCache("reportsCache"); if (cache != null) { - cache.removeAll(); + cache.clear(); } } @@ -114,15 +114,15 @@ public void clearPentahoReportsCache() { public void clearAllCaches() { // get the reports cache "reportsApiCache", declared in ehcache.xml - final Cache cache = cm.getCache("reportsApiCache"); + final Cache cache = cm.getCache("reportsApiCache"); if (cache != null) { - cache.removeAll(); + cache.clear(); } // get the reports cache "excelExportCache", declared in ehcache.xml - final Cache excelExportCache = cm.getCache("excelExportCache"); + final Cache excelExportCache = cm.getCache("excelExportCache"); if (excelExportCache != null) { - excelExportCache.removeAll(); + excelExportCache.clear(); } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java index d5b3a122..bbd7f04c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java @@ -59,7 +59,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -//import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; @@ -79,10 +78,11 @@ * * @author Stefan Kloe, mpostelnicu */ + +@EnableDiscoveryClient(autoRegister = true) @EnableScheduling @SpringBootApplication(exclude = {org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration.class}) @ComponentScan("org.devgateway.toolkit") -@EnableDiscoveryClient @PropertySource("classpath:/org/devgateway/toolkit/forms/application.properties") public class FormsWebApplication extends AuthenticatedWebApplication { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaAjaxButton.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaAjaxButton.java new file mode 100644 index 00000000..2ef0cf21 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaAjaxButton.java @@ -0,0 +1,62 @@ +package org.devgateway.toolkit.forms.wicket.components.buttons.ladda; + +import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapAjaxButton; +import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; +import java.io.Serializable; +import org.apache.wicket.AttributeModifier; +import org.apache.wicket.Component; +import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; +import org.apache.wicket.behavior.Behavior; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.model.IModel; + +public class LaddaAjaxButton extends BootstrapAjaxButton { + private final LaddaBehavior laddaBehavior = new LaddaBehavior(); + + public LaddaAjaxButton(String id, Buttons.Type type) { + super(id, type); + } + + public LaddaAjaxButton(String id, IModel model, Buttons.Type type) { + super(id, model, type); + } + + public LaddaAjaxButton(String id, Form form, Buttons.Type type) { + super(id, form, type); + } + + public LaddaAjaxButton(String id, IModel model, Form form, Buttons.Type type) { + super(id, model, form, type); + } + + protected void onInitialize() { + super.onInitialize(); + this.add(new Behavior[]{this.laddaBehavior}); + } + + public LaddaAjaxButton setEffect(LaddaBehavior.Effect effect) { + this.laddaBehavior.withEffect(effect); + return this; + } + + public LaddaAjaxButton setSpinnerColor(String color) { + this.laddaBehavior.withSpinnerColor(color); + return this; + } + + public LaddaAjaxButton setSpinnerSize(int size) { + this.laddaBehavior.withSpinnerSize(size); + return this; + } + + protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { + super.updateAjaxAttributes(attributes); + attributes.getAjaxCallListeners().add(new LaddaAjaxCallListener()); + } + + protected Component newLabel(String markupId, IModel model) { + Component label = super.newLabel(markupId, model); + label.add(new Behavior[]{AttributeModifier.append("class", "ladda-label")}); + return label; + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaAjaxCallListener.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaAjaxCallListener.java new file mode 100644 index 00000000..93e2963e --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaAjaxCallListener.java @@ -0,0 +1,10 @@ +package org.devgateway.toolkit.forms.wicket.components.buttons.ladda; + +import org.apache.wicket.ajax.attributes.AjaxCallListener; + +public class LaddaAjaxCallListener extends AjaxCallListener { + public LaddaAjaxCallListener() { + this.onBeforeSend("var $this = jQuery('#'+attrs.c); var l = Ladda.create($this[0]); l.start(); $this.data('ladda', l)"); + this.onComplete("var $this = jQuery('#'+attrs.c); var l = $this.data('ladda'); if (l) {l.stop(); $this.removeData('ladda');}"); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaBehavior.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaBehavior.java new file mode 100644 index 00000000..6a71a7ca --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaBehavior.java @@ -0,0 +1,80 @@ +package org.devgateway.toolkit.forms.wicket.components.buttons.ladda; + +import de.agilecoders.wicket.core.markup.html.bootstrap.behavior.ICssClassNameProvider; +import de.agilecoders.wicket.core.util.Attributes; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.references.SpinJsReference; +import org.apache.wicket.Component; +import org.apache.wicket.behavior.Behavior; +import org.apache.wicket.markup.ComponentTag; +import org.apache.wicket.markup.head.CssHeaderItem; +import org.apache.wicket.markup.head.IHeaderResponse; +import org.apache.wicket.markup.head.JavaScriptHeaderItem; +import org.apache.wicket.util.lang.Args; +import org.apache.wicket.util.string.Strings; + +public class LaddaBehavior extends Behavior { + private Effect effect; + private String spinnerColor; + private int spinnerSize; + + public LaddaBehavior() { + this.effect = LaddaBehavior.Effect.ZOOM_OUT; + } + + public LaddaBehavior withEffect(Effect effect) { + this.effect = (Effect)Args.notNull(effect, "effect"); + return this; + } + + public LaddaBehavior withSpinnerColor(String color) { + this.spinnerColor = color; + return this; + } + + public LaddaBehavior withSpinnerSize(int size) { + this.spinnerSize = size; + return this; + } + + public void onComponentTag(Component component, ComponentTag tag) { + super.onComponentTag(component, tag); + Attributes.addClass(tag, new String[]{"ladda-button"}); + Attributes.set(tag, "data-style", this.effect.cssClassName()); + if (!Strings.isEmpty(this.spinnerColor)) { + Attributes.set(tag, "data-spinner-color", this.spinnerColor); + } + + if (this.spinnerSize > 0) { + Attributes.set(tag, "data-spinner-size", String.valueOf(this.spinnerSize)); + } + + } + + public void renderHead(Component component, IHeaderResponse response) { + super.renderHead(component, response); + response.render(CssHeaderItem.forReference(LaddaCssReference.INSTANCE)); + response.render(JavaScriptHeaderItem.forReference(SpinJsReference.INSTANCE)); + response.render(JavaScriptHeaderItem.forReference(LaddaJsReference.INSTANCE)); + } + + public static enum Effect implements ICssClassNameProvider { + EXPAND_LEFT, + EXPAND_RIGHT, + EXPAND_UP, + EXPAND_DOWN, + ZOOM_IN, + ZOOM_OUT, + SLIDE_LEFT, + SLIDE_RIGHT, + SLIDE_UP, + SLIDE_DOWN, + CONTRACT; + + private Effect() { + } + + public String cssClassName() { + return this.name().toLowerCase().replace('_', '-'); + } + } +} \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaCssReference.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaCssReference.java new file mode 100644 index 00000000..86d0421c --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaCssReference.java @@ -0,0 +1,11 @@ +package org.devgateway.toolkit.forms.wicket.components.buttons.ladda; + +import org.apache.wicket.request.resource.CssResourceReference; + +public class LaddaCssReference extends CssResourceReference { + public static final LaddaCssReference INSTANCE = new LaddaCssReference(); + + public LaddaCssReference() { + super(LaddaCssReference.class, "css/ladda-themeless.css"); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaJsReference.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaJsReference.java new file mode 100644 index 00000000..96f6c2ca --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/LaddaJsReference.java @@ -0,0 +1,11 @@ +package org.devgateway.toolkit.forms.wicket.components.buttons.ladda; + +import org.apache.wicket.request.resource.JavaScriptResourceReference; + +public class LaddaJsReference extends JavaScriptResourceReference { + public static final LaddaJsReference INSTANCE = new LaddaJsReference(); + + public LaddaJsReference() { + super(LaddaJsReference.class, "js/ladda.js"); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/css/ladda-themeless.css b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/css/ladda-themeless.css new file mode 100644 index 00000000..880c9ff8 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/css/ladda-themeless.css @@ -0,0 +1,314 @@ +.ladda-button { + position: relative; } + +/* Spinner animation */ +.ladda-button .ladda-spinner { + position: absolute; + z-index: 2; + display: inline-block; + width: 32px; + height: 32px; + top: 50%; + margin-top: -16px; + opacity: 0; + pointer-events: none; } + +/* Button label */ +.ladda-button .ladda-label { + position: relative; + z-index: 3; } + +/* Progress bar */ +.ladda-button .ladda-progress { + position: absolute; + width: 0; + height: 100%; + left: 0; + top: 0; + background: rgba(0, 0, 0, 0.2); + visibility: hidden; + opacity: 0; + -webkit-transition: 0.1s linear all !important; + -moz-transition: 0.1s linear all !important; + -ms-transition: 0.1s linear all !important; + -o-transition: 0.1s linear all !important; + transition: 0.1s linear all !important; } + +.ladda-button[data-loading] .ladda-progress { + opacity: 1; + visibility: visible; } + +/************************************* + * EASING + */ +.ladda-button, +.ladda-button .ladda-spinner, +.ladda-button .ladda-label { + -webkit-transition: 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) all !important; + -moz-transition: 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) all !important; + -ms-transition: 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) all !important; + -o-transition: 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) all !important; + transition: 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) all !important; } + +.ladda-button[data-style=zoom-in], +.ladda-button[data-style=zoom-in] .ladda-spinner, +.ladda-button[data-style=zoom-in] .ladda-label, +.ladda-button[data-style=zoom-out], +.ladda-button[data-style=zoom-out] .ladda-spinner, +.ladda-button[data-style=zoom-out] .ladda-label { + -webkit-transition: 0.3s ease all !important; + -moz-transition: 0.3s ease all !important; + -ms-transition: 0.3s ease all !important; + -o-transition: 0.3s ease all !important; + transition: 0.3s ease all !important; } + +/************************************* + * EXPAND LEFT + */ +.ladda-button[data-style=expand-right] .ladda-spinner { + right: 14px; } +.ladda-button[data-style=expand-right][data-size="s"] .ladda-spinner, .ladda-button[data-style=expand-right][data-size="xs"] .ladda-spinner { + right: 4px; } +.ladda-button[data-style=expand-right][data-loading] { + padding-right: 56px; } +.ladda-button[data-style=expand-right][data-loading] .ladda-spinner { + opacity: 1; } +.ladda-button[data-style=expand-right][data-loading][data-size="s"], .ladda-button[data-style=expand-right][data-loading][data-size="xs"] { + padding-right: 40px; } + +/************************************* + * EXPAND RIGHT + */ +.ladda-button[data-style=expand-left] .ladda-spinner { + left: 14px; } +.ladda-button[data-style=expand-left][data-size="s"] .ladda-spinner, .ladda-button[data-style=expand-left][data-size="xs"] .ladda-spinner { + left: 4px; } +.ladda-button[data-style=expand-left][data-loading] { + padding-left: 56px; } +.ladda-button[data-style=expand-left][data-loading] .ladda-spinner { + opacity: 1; } +.ladda-button[data-style=expand-left][data-loading][data-size="s"], .ladda-button[data-style=expand-left][data-loading][data-size="xs"] { + padding-left: 40px; } + +/************************************* + * EXPAND UP + */ +.ladda-button[data-style=expand-up] { + overflow: hidden; } +.ladda-button[data-style=expand-up] .ladda-spinner { + top: -32px; + left: 50%; + margin-left: -16px; } +.ladda-button[data-style=expand-up][data-loading] { + padding-top: 54px; } +.ladda-button[data-style=expand-up][data-loading] .ladda-spinner { + opacity: 1; + top: 14px; + margin-top: 0; } +.ladda-button[data-style=expand-up][data-loading][data-size="s"], .ladda-button[data-style=expand-up][data-loading][data-size="xs"] { + padding-top: 32px; } +.ladda-button[data-style=expand-up][data-loading][data-size="s"] .ladda-spinner, .ladda-button[data-style=expand-up][data-loading][data-size="xs"] .ladda-spinner { + top: 4px; } + +/************************************* + * EXPAND DOWN + */ +.ladda-button[data-style=expand-down] { + overflow: hidden; } +.ladda-button[data-style=expand-down] .ladda-spinner { + top: 62px; + left: 50%; + margin-left: -16px; } +.ladda-button[data-style=expand-down][data-size="s"] .ladda-spinner, .ladda-button[data-style=expand-down][data-size="xs"] .ladda-spinner { + top: 40px; } +.ladda-button[data-style=expand-down][data-loading] { + padding-bottom: 54px; } +.ladda-button[data-style=expand-down][data-loading] .ladda-spinner { + opacity: 1; } +.ladda-button[data-style=expand-down][data-loading][data-size="s"], .ladda-button[data-style=expand-down][data-loading][data-size="xs"] { + padding-bottom: 32px; } + +/************************************* + * SLIDE LEFT + */ +.ladda-button[data-style=slide-left] { + overflow: hidden; } +.ladda-button[data-style=slide-left] .ladda-label { + position: relative; } +.ladda-button[data-style=slide-left] .ladda-spinner { + left: 100%; + margin-left: -16px; } +.ladda-button[data-style=slide-left][data-loading] .ladda-label { + opacity: 0; + left: -100%; } +.ladda-button[data-style=slide-left][data-loading] .ladda-spinner { + opacity: 1; + left: 50%; } + +/************************************* + * SLIDE RIGHT + */ +.ladda-button[data-style=slide-right] { + overflow: hidden; } +.ladda-button[data-style=slide-right] .ladda-label { + position: relative; } +.ladda-button[data-style=slide-right] .ladda-spinner { + right: 100%; + margin-left: -16px; } +.ladda-button[data-style=slide-right][data-loading] .ladda-label { + opacity: 0; + left: 100%; } +.ladda-button[data-style=slide-right][data-loading] .ladda-spinner { + opacity: 1; + left: 50%; } + +/************************************* + * SLIDE UP + */ +.ladda-button[data-style=slide-up] { + overflow: hidden; } +.ladda-button[data-style=slide-up] .ladda-label { + position: relative; } +.ladda-button[data-style=slide-up] .ladda-spinner { + left: 50%; + margin-left: -16px; + margin-top: 1em; } +.ladda-button[data-style=slide-up][data-loading] .ladda-label { + opacity: 0; + top: -1em; } +.ladda-button[data-style=slide-up][data-loading] .ladda-spinner { + opacity: 1; + margin-top: -16px; } + +/************************************* + * SLIDE DOWN + */ +.ladda-button[data-style=slide-down] { + overflow: hidden; } +.ladda-button[data-style=slide-down] .ladda-label { + position: relative; } +.ladda-button[data-style=slide-down] .ladda-spinner { + left: 50%; + margin-left: -16px; + margin-top: -2em; } +.ladda-button[data-style=slide-down][data-loading] .ladda-label { + opacity: 0; + top: 1em; } +.ladda-button[data-style=slide-down][data-loading] .ladda-spinner { + opacity: 1; + margin-top: -16px; } + +/************************************* + * ZOOM-OUT + */ +.ladda-button[data-style=zoom-out] { + overflow: hidden; } + +.ladda-button[data-style=zoom-out] .ladda-spinner { + left: 50%; + margin-left: -16px; + -webkit-transform: scale(2.5); + -moz-transform: scale(2.5); + -ms-transform: scale(2.5); + -o-transform: scale(2.5); + transform: scale(2.5); } + +.ladda-button[data-style=zoom-out] .ladda-label { + position: relative; + display: inline-block; } + +.ladda-button[data-style=zoom-out][data-loading] .ladda-label { + opacity: 0; + -webkit-transform: scale(0.5); + -moz-transform: scale(0.5); + -ms-transform: scale(0.5); + -o-transform: scale(0.5); + transform: scale(0.5); } + +.ladda-button[data-style=zoom-out][data-loading] .ladda-spinner { + opacity: 1; + -webkit-transform: none; + -moz-transform: none; + -ms-transform: none; + -o-transform: none; + transform: none; } + +/************************************* + * ZOOM-IN + */ +.ladda-button[data-style=zoom-in] { + overflow: hidden; } + +.ladda-button[data-style=zoom-in] .ladda-spinner { + left: 50%; + margin-left: -16px; + -webkit-transform: scale(0.2); + -moz-transform: scale(0.2); + -ms-transform: scale(0.2); + -o-transform: scale(0.2); + transform: scale(0.2); } + +.ladda-button[data-style=zoom-in] .ladda-label { + position: relative; + display: inline-block; } + +.ladda-button[data-style=zoom-in][data-loading] .ladda-label { + opacity: 0; + -webkit-transform: scale(2.2); + -moz-transform: scale(2.2); + -ms-transform: scale(2.2); + -o-transform: scale(2.2); + transform: scale(2.2); } + +.ladda-button[data-style=zoom-in][data-loading] .ladda-spinner { + opacity: 1; + -webkit-transform: none; + -moz-transform: none; + -ms-transform: none; + -o-transform: none; + transform: none; } + +/************************************* + * CONTRACT + */ +.ladda-button[data-style=contract] { + overflow: hidden; + width: 100px; } + +.ladda-button[data-style=contract] .ladda-spinner { + left: 50%; + margin-left: -16px; } + +.ladda-button[data-style=contract][data-loading] { + border-radius: 50%; + width: 52px; } + +.ladda-button[data-style=contract][data-loading] .ladda-label { + opacity: 0; } + +.ladda-button[data-style=contract][data-loading] .ladda-spinner { + opacity: 1; } + +/************************************* + * OVERLAY + */ +.ladda-button[data-style=contract-overlay] { + overflow: hidden; + width: 100px; + box-shadow: 0px 0px 0px 3000px transparent; } + +.ladda-button[data-style=contract-overlay] .ladda-spinner { + left: 50%; + margin-left: -16px; } + +.ladda-button[data-style=contract-overlay][data-loading] { + border-radius: 50%; + width: 52px; + /*outline: 10000px solid rgba( 0, 0, 0, 0.5 );*/ + box-shadow: 0px 0px 0px 3000px rgba(0, 0, 0, 0.8); } + +.ladda-button[data-style=contract-overlay][data-loading] .ladda-label { + opacity: 0; } + +.ladda-button[data-style=contract-overlay][data-loading] .ladda-spinner { + opacity: 1; } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/css/ladda-themeless.min.css b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/css/ladda-themeless.min.css new file mode 100644 index 00000000..389d208e --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/css/ladda-themeless.min.css @@ -0,0 +1 @@ +.ladda-button{position:relative}.ladda-button .ladda-spinner{position:absolute;z-index:2;display:inline-block;width:32px;height:32px;top:50%;margin-top:0;opacity:0;pointer-events:none}.ladda-button .ladda-label{position:relative;z-index:3}.ladda-button .ladda-progress{position:absolute;width:0;height:100%;left:0;top:0;background:rgba(0,0,0,0.2);visibility:hidden;opacity:0;-webkit-transition:0.1s linear all !important;-moz-transition:0.1s linear all !important;-ms-transition:0.1s linear all !important;-o-transition:0.1s linear all !important;transition:0.1s linear all !important}.ladda-button[data-loading] .ladda-progress{opacity:1;visibility:visible}.ladda-button,.ladda-button .ladda-spinner,.ladda-button .ladda-label{-webkit-transition:0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) all !important;-moz-transition:0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) all !important;-ms-transition:0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) all !important;-o-transition:0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) all !important;transition:0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) all !important}.ladda-button[data-style=zoom-in],.ladda-button[data-style=zoom-in] .ladda-spinner,.ladda-button[data-style=zoom-in] .ladda-label,.ladda-button[data-style=zoom-out],.ladda-button[data-style=zoom-out] .ladda-spinner,.ladda-button[data-style=zoom-out] .ladda-label{-webkit-transition:0.3s ease all !important;-moz-transition:0.3s ease all !important;-ms-transition:0.3s ease all !important;-o-transition:0.3s ease all !important;transition:0.3s ease all !important}.ladda-button[data-style=expand-right] .ladda-spinner{right:-6px}.ladda-button[data-style=expand-right][data-size="s"] .ladda-spinner,.ladda-button[data-style=expand-right][data-size="xs"] .ladda-spinner{right:-12px}.ladda-button[data-style=expand-right][data-loading]{padding-right:56px}.ladda-button[data-style=expand-right][data-loading] .ladda-spinner{opacity:1}.ladda-button[data-style=expand-right][data-loading][data-size="s"],.ladda-button[data-style=expand-right][data-loading][data-size="xs"]{padding-right:40px}.ladda-button[data-style=expand-left] .ladda-spinner{left:26px}.ladda-button[data-style=expand-left][data-size="s"] .ladda-spinner,.ladda-button[data-style=expand-left][data-size="xs"] .ladda-spinner{left:4px}.ladda-button[data-style=expand-left][data-loading]{padding-left:56px}.ladda-button[data-style=expand-left][data-loading] .ladda-spinner{opacity:1}.ladda-button[data-style=expand-left][data-loading][data-size="s"],.ladda-button[data-style=expand-left][data-loading][data-size="xs"]{padding-left:40px}.ladda-button[data-style=expand-up]{overflow:hidden}.ladda-button[data-style=expand-up] .ladda-spinner{top:-32px;left:50%;margin-left:0}.ladda-button[data-style=expand-up][data-loading]{padding-top:54px}.ladda-button[data-style=expand-up][data-loading] .ladda-spinner{opacity:1;top:26px;margin-top:0}.ladda-button[data-style=expand-up][data-loading][data-size="s"],.ladda-button[data-style=expand-up][data-loading][data-size="xs"]{padding-top:32px}.ladda-button[data-style=expand-up][data-loading][data-size="s"] .ladda-spinner,.ladda-button[data-style=expand-up][data-loading][data-size="xs"] .ladda-spinner{top:4px}.ladda-button[data-style=expand-down]{overflow:hidden}.ladda-button[data-style=expand-down] .ladda-spinner{top:62px;left:50%;margin-left:0}.ladda-button[data-style=expand-down][data-size="s"] .ladda-spinner,.ladda-button[data-style=expand-down][data-size="xs"] .ladda-spinner{top:40px}.ladda-button[data-style=expand-down][data-loading]{padding-bottom:54px}.ladda-button[data-style=expand-down][data-loading] .ladda-spinner{opacity:1}.ladda-button[data-style=expand-down][data-loading][data-size="s"],.ladda-button[data-style=expand-down][data-loading][data-size="xs"]{padding-bottom:32px}.ladda-button[data-style=slide-left]{overflow:hidden}.ladda-button[data-style=slide-left] .ladda-label{position:relative}.ladda-button[data-style=slide-left] .ladda-spinner{left:100%;margin-left:0}.ladda-button[data-style=slide-left][data-loading] .ladda-label{opacity:0;left:-100%}.ladda-button[data-style=slide-left][data-loading] .ladda-spinner{opacity:1;left:50%}.ladda-button[data-style=slide-right]{overflow:hidden}.ladda-button[data-style=slide-right] .ladda-label{position:relative}.ladda-button[data-style=slide-right] .ladda-spinner{right:100%;margin-left:0;left:16px}.ladda-button[data-style=slide-right][data-loading] .ladda-label{opacity:0;left:100%}.ladda-button[data-style=slide-right][data-loading] .ladda-spinner{opacity:1;left:50%}.ladda-button[data-style=slide-up]{overflow:hidden}.ladda-button[data-style=slide-up] .ladda-label{position:relative}.ladda-button[data-style=slide-up] .ladda-spinner{left:50%;margin-left:0;margin-top:1em}.ladda-button[data-style=slide-up][data-loading] .ladda-label{opacity:0;top:-1em}.ladda-button[data-style=slide-up][data-loading] .ladda-spinner{opacity:1;margin-top:0}.ladda-button[data-style=slide-down]{overflow:hidden}.ladda-button[data-style=slide-down] .ladda-label{position:relative}.ladda-button[data-style=slide-down] .ladda-spinner{left:50%;margin-left:0;margin-top:-2em}.ladda-button[data-style=slide-down][data-loading] .ladda-label{opacity:0;top:1em}.ladda-button[data-style=slide-down][data-loading] .ladda-spinner{opacity:1;margin-top:0}.ladda-button[data-style=zoom-out]{overflow:hidden}.ladda-button[data-style=zoom-out] .ladda-spinner{left:50%;margin-left:32px;-webkit-transform:scale(2.5);-moz-transform:scale(2.5);-ms-transform:scale(2.5);-o-transform:scale(2.5);transform:scale(2.5)}.ladda-button[data-style=zoom-out] .ladda-label{position:relative;display:inline-block}.ladda-button[data-style=zoom-out][data-loading] .ladda-label{opacity:0;-webkit-transform:scale(0.5);-moz-transform:scale(0.5);-ms-transform:scale(0.5);-o-transform:scale(0.5);transform:scale(0.5)}.ladda-button[data-style=zoom-out][data-loading] .ladda-spinner{opacity:1;margin-left:0;-webkit-transform:none;-moz-transform:none;-ms-transform:none;-o-transform:none;transform:none}.ladda-button[data-style=zoom-in]{overflow:hidden}.ladda-button[data-style=zoom-in] .ladda-spinner{left:50%;margin-left:-16px;-webkit-transform:scale(0.2);-moz-transform:scale(0.2);-ms-transform:scale(0.2);-o-transform:scale(0.2);transform:scale(0.2)}.ladda-button[data-style=zoom-in] .ladda-label{position:relative;display:inline-block}.ladda-button[data-style=zoom-in][data-loading] .ladda-label{opacity:0;-webkit-transform:scale(2.2);-moz-transform:scale(2.2);-ms-transform:scale(2.2);-o-transform:scale(2.2);transform:scale(2.2)}.ladda-button[data-style=zoom-in][data-loading] .ladda-spinner{opacity:1;margin-left:0;-webkit-transform:none;-moz-transform:none;-ms-transform:none;-o-transform:none;transform:none}.ladda-button[data-style=contract]{overflow:hidden;width:100px}.ladda-button[data-style=contract] .ladda-spinner{left:50%;margin-left:0}.ladda-button[data-style=contract][data-loading]{border-radius:50%;width:52px}.ladda-button[data-style=contract][data-loading] .ladda-label{opacity:0}.ladda-button[data-style=contract][data-loading] .ladda-spinner{opacity:1}.ladda-button[data-style=contract-overlay]{overflow:hidden;width:100px;box-shadow:0px 0px 0px 2000px transparent}.ladda-button[data-style=contract-overlay] .ladda-spinner{left:50%;margin-left:0}.ladda-button[data-style=contract-overlay][data-loading]{border-radius:50%;width:52px;box-shadow:0px 0px 0px 2000px rgba(0,0,0,0.8)}.ladda-button[data-style=contract-overlay][data-loading] .ladda-label{opacity:0}.ladda-button[data-style=contract-overlay][data-loading] .ladda-spinner{opacity:1} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/js/ladda.js b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/js/ladda.js new file mode 100644 index 00000000..5f4af9c7 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/js/ladda.js @@ -0,0 +1,160 @@ +(function(root, factory) { + if (typeof exports === "object") { + module.exports = factory(); + } else if (typeof define === "function" && define.amd) { + define([ "./spin" ], factory); + } else { + root.Ladda = factory(root.Spinner); + } +})(this, function(Spinner) { + "use strict"; + var ALL_INSTANCES = []; + function create(button) { + if (typeof button === "undefined") { + console.warn("Ladda button target must be defined."); + return; + } + if (!button.querySelector(".ladda-label")) { + button.innerHTML = '' + button.innerHTML + ""; + } + var spinner = createSpinner(button); + var spinnerWrapper = document.createElement("span"); + spinnerWrapper.className = "ladda-spinner"; + button.appendChild(spinnerWrapper); + var timer; + var instance = { + start: function() { + button.setAttribute("disabled", ""); + button.setAttribute("data-loading", ""); + clearTimeout(timer); + spinner.spin(spinnerWrapper); + this.setProgress(0); + return this; + }, + startAfter: function(delay) { + clearTimeout(timer); + timer = setTimeout(function() { + instance.start(); + }, delay); + return this; + }, + stop: function() { + button.removeAttribute("disabled"); + button.removeAttribute("data-loading"); + clearTimeout(timer); + timer = setTimeout(function() { + spinner.stop(); + }, 1e3); + return this; + }, + toggle: function() { + if (this.isLoading()) { + this.stop(); + } else { + this.start(); + } + return this; + }, + setProgress: function(progress) { + progress = Math.max(Math.min(progress, 1), 0); + var progressElement = button.querySelector(".ladda-progress"); + if (progress === 0 && progressElement && progressElement.parentNode) { + progressElement.parentNode.removeChild(progressElement); + } else { + if (!progressElement) { + progressElement = document.createElement("div"); + progressElement.className = "ladda-progress"; + button.appendChild(progressElement); + } + progressElement.style.width = (progress || 0) * button.offsetWidth + "px"; + } + }, + enable: function() { + this.stop(); + return this; + }, + disable: function() { + this.stop(); + button.setAttribute("disabled", ""); + return this; + }, + isLoading: function() { + return button.hasAttribute("data-loading"); + }, + getTarget: function() { + return button; + } + }; + ALL_INSTANCES.push(instance); + return instance; + } + function bind(target, options) { + options = options || {}; + var targets = []; + if (typeof target === "string") { + targets = toArray(document.querySelectorAll(target)); + } else if (typeof target === "object" && typeof target.nodeName === "string") { + targets = [ target ]; + } + for (var i = 0, len = targets.length; i < len; i++) { + (function() { + var element = targets[i]; + if (typeof element.addEventListener === "function") { + var instance = create(element); + var timeout = -1; + element.addEventListener("click", function() { + instance.startAfter(1); + if (typeof options.timeout === "number") { + clearTimeout(timeout); + timeout = setTimeout(instance.stop, options.timeout); + } + if (typeof options.callback === "function") { + options.callback.apply(null, [ instance ]); + } + }, false); + } + })(); + } + } + function stopAll() { + for (var i = 0, len = ALL_INSTANCES.length; i < len; i++) { + ALL_INSTANCES[i].stop(); + } + } + function createSpinner(button) { + var height = button.offsetHeight, spinnerColor; + if (height > 32) { + height *= .8; + } + if (button.hasAttribute("data-spinner-size")) { + height = parseInt(button.getAttribute("data-spinner-size"), 10); + } + if (button.hasAttribute("data-spinner-color")) { + spinnerColor = button.getAttribute("data-spinner-color"); + } + var lines = 12, radius = height * .2, length = radius * .6, width = radius < 7 ? 2 : 3; + return new Spinner({ + color: spinnerColor || "#fff", + lines: lines, + radius: radius, + length: length, + width: width, + zIndex: "auto", + top: "50%", + left: "50%", + className: "" + }); + } + function toArray(nodes) { + var a = []; + for (var i = 0; i < nodes.length; i++) { + a.push(nodes[i]); + } + return a; + } + return { + bind: bind, + create: create, + stopAll: stopAll + }; +}); \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/js/ladda.min.js b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/js/ladda.min.js new file mode 100644 index 00000000..7d8e22a9 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/buttons/ladda/js/ladda.min.js @@ -0,0 +1 @@ +(function(t,e){"object"==typeof exports?module.exports=e(require("spin.js")):"function"==typeof define&&define.amd?define(["spin"],e):t.Ladda=e(t.Spinner)})(this,function(t){"use strict";function e(t){if(t===void 0)return console.warn("Ladda button target must be defined."),void 0;t.querySelector(".ladda-label")||(t.innerHTML=''+t.innerHTML+"");var e,n=document.createElement("span");n.className="ladda-spinner",t.appendChild(n);var r,a={start:function(){return e||(e=o(t)),t.setAttribute("disabled",""),t.setAttribute("data-loading",""),clearTimeout(r),e.spin(n),this.setProgress(0),this},startAfter:function(t){return clearTimeout(r),r=setTimeout(function(){a.start()},t),this},stop:function(){return t.removeAttribute("disabled"),t.removeAttribute("data-loading"),clearTimeout(r),e&&(r=setTimeout(function(){e.stop()},1e3)),this},toggle:function(){return this.isLoading()?this.stop():this.start(),this},setProgress:function(e){e=Math.max(Math.min(e,1),0);var n=t.querySelector(".ladda-progress");0===e&&n&&n.parentNode?n.parentNode.removeChild(n):(n||(n=document.createElement("div"),n.className="ladda-progress",t.appendChild(n)),n.style.width=(e||0)*t.offsetWidth+"px")},enable:function(){return this.stop(),this},disable:function(){return this.stop(),t.setAttribute("disabled",""),this},isLoading:function(){return t.hasAttribute("data-loading")},remove:function(){clearTimeout(r),t.removeAttribute("disabled",""),t.removeAttribute("data-loading",""),e&&(e.stop(),e=null);for(var n=0,i=u.length;i>n;n++)if(a===u[n]){u.splice(n,1);break}}};return u.push(a),a}function n(t,e){for(;t.parentNode&&t.tagName!==e;)t=t.parentNode;return e===t.tagName?t:void 0}function r(t){for(var e=["input","textarea"],n=[],r=0;e.length>r;r++)for(var a=t.getElementsByTagName(e[r]),i=0;a.length>i;i++)a[i].hasAttribute("required")&&n.push(a[i]);return n}function a(t,a){a=a||{};var i=[];"string"==typeof t?i=s(document.querySelectorAll(t)):"object"==typeof t&&"string"==typeof t.nodeName&&(i=[t]);for(var o=0,u=i.length;u>o;o++)(function(){var t=i[o];if("function"==typeof t.addEventListener){var s=e(t),u=-1;t.addEventListener("click",function(){var e=!0,i=n(t,"FORM");if(i!==void 0)for(var o=r(i),d=0;o.length>d;d++)""===o[d].value.replace(/^\s+|\s+$/g,"")&&(e=!1);e&&(s.startAfter(1),"number"==typeof a.timeout&&(clearTimeout(u),u=setTimeout(s.stop,a.timeout)),"function"==typeof a.callback&&a.callback.apply(null,[s]))},!1)}})()}function i(){for(var t=0,e=u.length;e>t;t++)u[t].stop()}function o(e){var n,r=e.offsetHeight;0===r&&(r=parseFloat(window.getComputedStyle(e).height)),r>32&&(r*=.8),e.hasAttribute("data-spinner-size")&&(r=parseInt(e.getAttribute("data-spinner-size"),10)),e.hasAttribute("data-spinner-color")&&(n=e.getAttribute("data-spinner-color"));var a=12,i=.2*r,o=.6*i,s=7>i?2:3;return new t({color:n||"#fff",lines:a,radius:i,length:o,width:s,zIndex:"auto",top:"auto",left:"auto",className:""})}function s(t){for(var e=[],n=0;t.length>n;n++)e.push(t[n]);return e}var u=[];return{bind:a,create:e,stopAll:i}}); \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapAddButton.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapAddButton.java index b380deef..341bd610 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapAddButton.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapAddButton.java @@ -17,7 +17,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons.Size; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; +import org.devgateway.toolkit.forms.wicket.components.buttons.ladda.LaddaAjaxButton; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.event.IEvent; import org.apache.wicket.model.IModel; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapCancelButton.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapCancelButton.java index 9d41f521..ddbbffdd 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapCancelButton.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapCancelButton.java @@ -16,7 +16,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; +import org.devgateway.toolkit.forms.wicket.components.buttons.ladda.LaddaAjaxButton; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.IModel; import org.devgateway.toolkit.forms.wicket.components.ComponentUtil; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapDeleteButton.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapDeleteButton.java index 046bd525..af65c591 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapDeleteButton.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapDeleteButton.java @@ -16,7 +16,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; +import org.devgateway.toolkit.forms.wicket.components.buttons.ladda.LaddaAjaxButton; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxCallListener; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapSubmitButton.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapSubmitButton.java index 4f5793cd..22e9dd56 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapSubmitButton.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/BootstrapSubmitButton.java @@ -16,7 +16,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; +import org.devgateway.toolkit.forms.wicket.components.buttons.ladda.LaddaAjaxButton; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.model.IModel; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/ToolkitSummernoteEditor.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/ToolkitSummernoteEditor.java index 5e930af0..4216477c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/ToolkitSummernoteEditor.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/ToolkitSummernoteEditor.java @@ -9,7 +9,7 @@ import de.agilecoders.wicket.extensions.markup.html.bootstrap.editor.SummernoteEditorOverlayCssReference; import de.agilecoders.wicket.extensions.markup.html.bootstrap.editor.SummernoteStorage; import de.agilecoders.wicket.extensions.markup.html.bootstrap.editor.SummernoteStoredImageResourceReference; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeCssReference; +import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5CssReference; import de.agilecoders.wicket.extensions.markup.html.bootstrap.references.SpinJsReference; import de.agilecoders.wicket.jquery.IKey; import org.apache.commons.fileupload2.core.FileItem; @@ -159,7 +159,7 @@ public void renderHead(final IHeaderResponse response) { return; } response.render(CssHeaderItem.forReference(SummernoteEditorCssReference.instance())); - response.render(CssHeaderItem.forReference(FontAwesomeCssReference.instance())); + response.render(CssHeaderItem.forReference(FontAwesome5CssReference.instance())); response.render(CssHeaderItem.forReference(SummernoteEditorOverlayCssReference.instance())); response.render(JavaScriptHeaderItem.forReference(SummernoteEditorJavaScriptReference.instance())); response.render(JavaScriptHeaderItem.forReference(SummernoteEditorFormDataReference.instance())); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java index 58561ab1..3e2ec297 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.java @@ -15,7 +15,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.dialog.TextContentModal; import de.agilecoders.wicket.core.markup.html.bootstrap.form.BootstrapForm; import de.agilecoders.wicket.core.util.Attributes; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; +import org.devgateway.toolkit.forms.wicket.components.buttons.ladda.LaddaAjaxButton; import nl.dries.wicket.hibernate.dozer.DozerModel; import org.apache.wicket.Page; import org.apache.wicket.ajax.AjaxEventBehavior; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java index 56412327..c0ced96e 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditStatusEntityPage.java @@ -15,7 +15,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.dialog.TextContentModal; import de.agilecoders.wicket.core.markup.html.bootstrap.form.BootstrapCheckbox; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; +import org.devgateway.toolkit.forms.wicket.components.buttons.ladda.LaddaAjaxButton; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.ajax.AbstractAjaxTimerBehavior; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java index 25a45fa2..194159cc 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/AbstractEditServiceEntityPage.java @@ -3,7 +3,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.core.markup.html.bootstrap.dialog.TextContentModal; import de.agilecoders.wicket.core.markup.html.bootstrap.form.BootstrapForm; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; +import org.devgateway.toolkit.forms.wicket.components.buttons.ladda.LaddaAjaxButton; import org.apache.wicket.Page; import org.apache.wicket.ajax.AjaxEventBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java index dcc56bad..08bebd9f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditCSVDatasetPage.java @@ -3,7 +3,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapAjaxButton; import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; +import org.devgateway.toolkit.forms.wicket.components.buttons.ladda.LaddaAjaxButton; import org.apache.commons.lang3.StringUtils; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.IModel; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java index e400c844..9a8502f3 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/AbstractListPage.java @@ -15,7 +15,7 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons; import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons.Size; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; -import de.agilecoders.wicket.extensions.markup.html.bootstrap.ladda.LaddaAjaxButton; +import org.devgateway.toolkit.forms.wicket.components.buttons.ladda.LaddaAjaxButton; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LoginPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LoginPage.java index a6ed56fa..3642e0fa 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LoginPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LoginPage.java @@ -28,7 +28,6 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.util.string.StringValue; -//import org.apache.wicket.util.time.Duration; import org.devgateway.toolkit.forms.WebConstants; import org.devgateway.toolkit.forms.security.SecurityUtil; import org.devgateway.toolkit.forms.wicket.SSAuthenticatedWebSession; diff --git a/persistence/pom.xml b/persistence/pom.xml index 30ebe6bb..dc3f76a1 100644 --- a/persistence/pom.xml +++ b/persistence/pom.xml @@ -75,6 +75,7 @@ org.ehcache ehcache ${ehcache.version} + jakarta @@ -82,6 +83,11 @@ spring-boot-starter-cache + + org.springframework.boot + spring-boot-starter-web + + org.springframework spring-context-support @@ -114,10 +120,10 @@ ${hibernate.version} - - javax.cache - cache-api - + + + + org.hibernate @@ -221,12 +227,12 @@ jakarta.xml.bind jakarta.xml.bind-api - 3.0.1 + 4.0.2 org.glassfish.jaxb jaxb-runtime - 3.0.1 + 4.0.5 diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties index 17786696..a79f63d2 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties @@ -16,5 +16,5 @@ spring.datasource.jdbc-url=jdbc:postgresql://localhost:5432/data_viz_admin management.health.mail.enabled=false dg-toolkit.forms.base-path=/admin - -eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ \ No newline at end of file +eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ +spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties index 16ee44ce..392a6d0d 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties @@ -16,7 +16,7 @@ spring.liquibase.enabled=true spring.liquibase.change-log=classpath:liquibase-changelog.xml #spring.jpa.show-sql=true -spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL95Dialect +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect #performance tunning for hibernate spring.jpa.hibernate.max_fetch_depth=0 @@ -44,8 +44,8 @@ spring.datasource.min-idle=8 spring.datasource.initial-size=20 spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.username=postgres -spring.datasource.password=postgres -spring.datasource.jdbc-url=jdbc:postgresql://postgresql:5432/tcdi-admin +spring.datasource.password=admin +spring.datasource.jdbc-url=jdbc:postgresql://localhost:5432/data_viz_admin spring.datasource.transaction-isolation=2 dg-toolkit.datasource.jndi-name=toolkitDS dg-toolkit.derby.port=1527 @@ -58,3 +58,4 @@ spring.profiles.active=integration eureka.client.serviceUrl.defaultZone=http://eureka:8761/eureka/ dg-toolkit.forms.base-path=/admin +spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileContent.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileContent.java index 41c13845..08c6533f 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileContent.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/FileContent.java @@ -18,6 +18,8 @@ import jakarta.persistence.Entity; import jakarta.persistence.Lob; +import java.sql.Types; + /** * @author idobre * @since 11/13/14 @@ -31,7 +33,7 @@ public class FileContent extends AbstractAuditableEntity { @Lob @Column(length = LOB_LENGTH) - @JdbcTypeCode(SqlTypes.BLOB) + @JdbcTypeCode(Types.VARBINARY) private byte[] bytes; public byte[] getBytes() { diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/CacheConfiguration.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/CacheConfiguration.java index d97a3de2..4cab53b7 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/CacheConfiguration.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/spring/CacheConfiguration.java @@ -14,7 +14,10 @@ */ package org.devgateway.toolkit.persistence.spring; +import org.ehcache.jsr107.EhcacheCachingProvider; import org.hibernate.cache.jcache.ConfigSettings; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer; import org.springframework.cache.annotation.EnableCaching; @@ -24,7 +27,10 @@ import org.springframework.data.auditing.DateTimeProvider; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; -import javax.management.MBeanServer; +//import javax.cache.Caching; +//import javax.cache.CacheManager; +//import javax.management.MBeanServer; +import java.net.URISyntaxException; import java.time.ZonedDateTime; import java.util.Optional; @@ -36,19 +42,29 @@ @EnableCaching @EnableJpaAuditing(dateTimeProviderRef = "auditingDateTimeProvider") public class CacheConfiguration { + + private static final Logger logger = LoggerFactory.getLogger(CacheConfiguration.class); @Bean(name = "auditingDateTimeProvider") public DateTimeProvider dateTimeProvider() { return () -> Optional.of(ZonedDateTime.now()); } - @Autowired(required = false) - private MBeanServer mbeanServer; +// @Autowired(required = false) +// private MBeanServer mbeanServer; @Bean public HibernatePropertiesCustomizer hibernateSecondLevelCacheCustomizer(final JCacheCacheManager cacheManager) { return (properties) -> properties.put(ConfigSettings.CACHE_MANAGER, cacheManager.getCacheManager()); } +// @Bean +// public JCacheCacheManager cacheManager() throws URISyntaxException { +// logger.info("Location of ehcache.xml " + getClass().getResource("/ehcache.xml")); +// CacheManager cacheManager = Caching.getCachingProvider(EhcacheCachingProvider.class.getName()) +// .getCacheManager(getClass().getResource("/ehcache.xml").toURI(), getClass().getClassLoader()); +// return new JCacheCacheManager(cacheManager); +// } + } diff --git a/persistence/src/main/resources/ehcache.xml b/persistence/src/main/resources/ehcache.xml index f2a54102..fee00ffe 100644 --- a/persistence/src/main/resources/ehcache.xml +++ b/persistence/src/main/resources/ehcache.xml @@ -1,13 +1,14 @@ + xmlns:jcache="http://www.ehcache.org/v3/jsr107"> - + + 100000 - + 100000 @@ -20,4 +21,4 @@ - \ No newline at end of file + diff --git a/pom.xml b/pom.xml index 5b247af5..38c6dce7 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ UTF-8 17 - 4.29.0 + 4.29.2 3.2.10 10.17.1.0 diff --git a/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java b/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java index b4fe01b4..7211360b 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java +++ b/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java @@ -29,6 +29,7 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.FilterInvocation; @@ -126,7 +127,7 @@ private String[] getAllowedAPIEndpointsWithBasePath() { public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.securityContext(securityContext -> securityContext.securityContextRepository(httpSessionSecurityContextRepository())) .authorizeHttpRequests(authz -> authz - .requestMatchers(settingsUtils.getFormsBasePath() + "/monitoring/**").hasRole("ROLE_ADMIN") + .requestMatchers(settingsUtils.getFormsBasePath() + "/monitoring/**").hasRole("ADMIN") .requestMatchers(settingsUtils.getFormsBasePath() + "/**").authenticated() ) .formLogin(form -> form @@ -140,19 +141,34 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // Apply the custom SecurityExpressionHandler here http.setSharedObject(SecurityExpressionHandler.class, webExpressionHandler()); - // Firewall configuration, equivalent to 'allowUrlEncodedSlashHttpFirewall' - http.getSharedObject(WebSecurity.class) - .httpFirewall(allowUrlEncodedSlashHttpFirewall()); +// http.setSharedObject(HttpFirewall.class, allowUrlEncodedSlashHttpFirewall()); +// +// http.ignoring() +// .requestMatchers(getAllowedAPIEndpointsWithBasePath()) +// .requestMatchers(settingsUtils.getFormsBasePath() + "/login", settingsUtils.getFormsBasePath() + "/forgotPassword/**"); +// // Firewall configuration, equivalent to 'allowUrlEncodedSlashHttpFirewall' +// http.getSharedObject(WebSecurity.class) +// .httpFirewall(allowUrlEncodedSlashHttpFirewall()); // Ignoring paths (migrated from 'configure(WebSecurity web)') - http.getSharedObject(WebSecurity.class) - .ignoring() - .requestMatchers(getAllowedAPIEndpointsWithBasePath()) - .requestMatchers(settingsUtils.getFormsBasePath() + "/login", settingsUtils.getFormsBasePath() + "/forgotPassword/**"); +// http.getSharedObject(WebSecurity.class) +// .ignoring() +// .requestMatchers(getAllowedAPIEndpointsWithBasePath()) +// .requestMatchers(settingsUtils.getFormsBasePath() + "/login", settingsUtils.getFormsBasePath() + "/forgotPassword/**"); return http.build(); } + @Bean + public WebSecurityCustomizer webSecurityCustomizer() { + return (web) -> { + web.httpFirewall(allowUrlEncodedSlashHttpFirewall()); + web.ignoring() + .requestMatchers(getAllowedAPIEndpointsWithBasePath()) + .requestMatchers(settingsUtils.getFormsBasePath() + "/login", settingsUtils.getFormsBasePath() + "/forgotPassword/**"); + }; + } + /** * Instantiates {@see DefaultWebSecurityExpressionHandler} and assigns to it * role hierarchy. From 7f23b8e6bef50f6b7bc0331837040083225bd007 Mon Sep 17 00:00:00 2001 From: Denis Mbugua <60645043+dynamodenis@users.noreply.github.com> Date: Fri, 1 Nov 2024 13:32:01 +0300 Subject: [PATCH 128/137] DVIZ-12 fix eureka client issue --- forms/pom.xml | 44 +++++- .../toolkit/forms/EurekaClientConfig.java | 31 ++++ .../toolkit/forms/FormsSecurityConfig.java | 147 +++++++++++------- .../toolkit/forms/application-dev.properties | 6 +- .../toolkit/forms/application.properties | 5 +- .../forms/wicket/FormsWebApplication.java | 19 +++ .../toolkit/forms/wicket/page/BasePage.java | 10 +- web/pom.xml | 27 +++- .../toolkit/web/application.properties | 5 + .../toolkit/web/spring/SwaggerConfig.java | 2 - 10 files changed, 223 insertions(+), 73 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/EurekaClientConfig.java diff --git a/forms/pom.xml b/forms/pom.xml index cecb342a..4f648401 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -37,7 +37,7 @@ 1.13 4.0.5 v20200406 - 3.1 + 3.3.0 2.4.8 2.2.0 6.5.2 @@ -300,6 +300,30 @@ org.springframework.cloud spring-cloud-starter-netflix-eureka-client ${netflix.eureka.version} + + + org.glassfish.jersey.core + jersey-client + + + + org.glassfish.jersey.core + jersey-common + + + + org.glassfish.jersey.inject + jersey-hk2 + + + org.glassfish.jersey.media + jersey-media-json-jackson + + + org.glassfish.jersey.media + jersey-media-multipart + + @@ -323,11 +347,23 @@ - com.sun.jersey.contribs - jersey-apache-client4 - 1.19.4 + org.springframework.boot + spring-boot-starter-jersey + 3.3.4 + + + + + + + + + + + + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/EurekaClientConfig.java b/forms/src/main/java/org/devgateway/toolkit/forms/EurekaClientConfig.java new file mode 100644 index 00000000..2256c2b7 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/EurekaClientConfig.java @@ -0,0 +1,31 @@ +package org.devgateway.toolkit.forms; + +import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs; +import com.netflix.discovery.shared.transport.jersey.TransportClientFactories; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.SearchStrategy; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.netflix.eureka.http.EurekaClientHttpRequestFactorySupplier; +import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClientOptionalArgs; +import org.springframework.cloud.netflix.eureka.http.RestTemplateTransportClientFactories; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@EnableDiscoveryClient +@Configuration +public class EurekaClientConfig { + @Bean + @ConditionalOnClass(name = { "org.springframework.web.client.RestTemplate", "org.glassfish.jersey.client.JerseyClient" }) + @ConditionalOnMissingBean(value = { AbstractDiscoveryClientOptionalArgs.class }, search = SearchStrategy.CURRENT) + public RestTemplateDiscoveryClientOptionalArgs restTemplateDiscoveryClientOptionalArgs(EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier) { + return new RestTemplateDiscoveryClientOptionalArgs(eurekaClientHttpRequestFactorySupplier); + } + + @Bean + @ConditionalOnClass(name = { "org.springframework.web.client.RestTemplate", "org.glassfish.jersey.client.JerseyClient" }) + @ConditionalOnMissingBean(value = { TransportClientFactories.class }, search = SearchStrategy.CURRENT) + public RestTemplateTransportClientFactories restTemplateTransportClientFactories(RestTemplateDiscoveryClientOptionalArgs optionalArgs) { + return new RestTemplateTransportClientFactories(optionalArgs); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java b/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java index 46e499c0..b3c49adc 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java @@ -15,24 +15,40 @@ import org.devgateway.toolkit.web.spring.WebSecurityConfig; import org.devgateway.toolkit.web.util.SettingsUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; +import org.springframework.security.access.expression.SecurityExpressionHandler; +import org.springframework.security.access.hierarchicalroles.RoleHierarchy; +import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl; +import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.RememberMeAuthenticationProvider; import org.springframework.security.config.Customizer; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler; import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices; import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices; +import org.springframework.security.web.context.HttpSessionSecurityContextRepository; +import org.springframework.security.web.firewall.HttpFirewall; +import org.springframework.security.web.firewall.StrictHttpFirewall; + +import java.util.Arrays; +import java.util.stream.Collectors; @Configuration @EnableWebSecurity -@Order(1) // this ensures the forms security comes first -public class FormsSecurityConfig extends WebSecurityConfig { +public class FormsSecurityConfig { /** * Remember me key for {@link TokenBasedRememberMeServices} @@ -42,33 +58,78 @@ public class FormsSecurityConfig extends WebSecurityConfig { @Autowired private SettingsUtils settingsUtils; + @Autowired + protected CustomJPAUserDetailsService customJPAUserDetailsService; + + @Value("${allowedApiEndpoints}") + private String[] allowedApiEndpoints; + + @Value("${roleHierarchy}") + private String roleHierarchyStringRepresentation; + + @Autowired + private PasswordEncoder passwordEncoder; + + private String[] getAllowedAPIEndpointsWithBasePath() { + if (allowedApiEndpoints != null) { + return Arrays.stream(allowedApiEndpoints) + .map(s -> settingsUtils.getFormsBasePath() + s) + .collect(Collectors.toList()).toArray(new String[allowedApiEndpoints.length]); + } + + return new String[]{}; + } + + @Bean + public HttpFirewall allowUrlEncodedSlashHttpFirewall() { + final StrictHttpFirewall firewall = new StrictHttpFirewall(); + firewall.setAllowUrlEncodedSlash(true); + firewall.setAllowSemicolon(true); + firewall.setAllowUrlEncodedDoubleSlash(true); + return firewall; + } + @Bean + public WebSecurityCustomizer webSecurityCustomizer() { + return (web) -> { + web.httpFirewall(allowUrlEncodedSlashHttpFirewall()); + web.ignoring() + .requestMatchers(getAllowedAPIEndpointsWithBasePath()); + }; + } + /** - * We ensure the superclass configuration is being applied Take note the - * {@link FormsSecurityConfig} extends {@link WebSecurityConfig} which has - * configuration for the dg-toolkit/web module. We then apply ant matchers - * and ignore security for css/js/images resources, and wicket mounted - * resources + * Instantiates {@see DefaultWebSecurityExpressionHandler} and assigns to it + * role hierarchy. + * + * @return */ -// @Override -// public void configure(final WebSecurity web) throws Exception { -// super.configure(web); -// String formsBasePath = settingsUtils.getFormsBasePath(); -// web.ignoring().antMatchers(formsBasePath + "/img/**", -// formsBasePath + "/css*/**", -// formsBasePath + "/js*/**", -// formsBasePath + "/assets*/**", formsBasePath + "/favicon.ico", formsBasePath + "/resources/**", -// formsBasePath + "/resources/public/**"); -// web.ignoring().antMatchers( -// formsBasePath + "/wicket/resource/**/*.js", -// formsBasePath + "/wicket/resource/**/*.css", -// formsBasePath + "/wicket/resource/**/*.png", -// formsBasePath + "/wicket/resource/**/*.jpg", -// formsBasePath + "/wicket/resource/**/*.woff", -// formsBasePath + "/wicket/resource/**/*.woff2", -// formsBasePath + "/wicket/resource/**/*.ttf", -// formsBasePath + "/wicket/resource/**/*.svg", -// formsBasePath + "/wicket/resource/**/*.gif"); -// } + private SecurityExpressionHandler webExpressionHandler() { + final DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler(); + handler.setRoleHierarchy(roleHierarchy()); + return handler; + } + + /** + * Enable hierarchical roles. This bean can be used to extract all effective + * roles. + */ + @Bean + RoleHierarchy roleHierarchy() { + final RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl(); + roleHierarchy.setHierarchy(roleHierarchyStringRepresentation); + return roleHierarchy; + } + + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { + return authenticationConfiguration.getAuthenticationManager(); + } + + @Autowired + public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(customJPAUserDetailsService).passwordEncoder(passwordEncoder); + } + /** * This bean defines the same key in the @@ -95,28 +156,10 @@ public AbstractRememberMeServices rememberMeServices() { return rememberMeServices; } -// @Override -// protected void configure(final HttpSecurity http) throws Exception { -// super.configure(http); -// -// // we do not allow anyonymous token. When -// // enabled this basically means any guest -// // user will have an annoymous default role -// http.anonymous().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER). -// // we let Wicket create and manage sessions, so we disable -// // session creation by spring -// and().csrf().disable(); // csrf protection interferes with some -// // wicket stuff -// -// // we enable http rememberMe cookie for autologin -// // http.rememberMe().key(UNIQUE_SECRET_REMEMBER_ME_KEY); -// -// // resolved the error Refused to display * in a frame because it set -// // 'X-Frame-Options' to 'DENY'. -// http.headers().contentTypeOptions().and().xssProtection().and().cacheControl().and() -// .httpStrictTransportSecurity().and().frameOptions().sameOrigin(); -// -// } + @Bean + public HttpSessionSecurityContextRepository httpSessionSecurityContextRepository() { + return new HttpSessionSecurityContextRepository(); + } /** * We ensure the superclass configuration is being applied Take note the @@ -137,11 +180,12 @@ public SecurityFilterChain formsSecurityFilterChain(HttpSecurity http) throws Ex .requestMatchers(formsBasePath + "/img/**", formsBasePath + "/css*/**", formsBasePath + "/js*/**", formsBasePath + "/assets*/**", formsBasePath + "/favicon.ico", formsBasePath + "/resources/**", + formsBasePath + "/resources/public/**", formsBasePath + "/wicket/resource/**/*.js", formsBasePath + "/wicket/resource/**/*.css", formsBasePath + "/wicket/resource/**/*.png", formsBasePath + "/wicket/resource/**/*.jpg", formsBasePath + "/wicket/resource/**/*.woff", formsBasePath + "/wicket/resource/**/*.woff2", formsBasePath + "/wicket/resource/**/*.ttf", formsBasePath + "/wicket/resource/**/*.svg", - formsBasePath + "/wicket/resource/**/*.gif" + formsBasePath + "/wicket/resource/**/*.gif", formsBasePath + "/forgotPassword/**" ).permitAll() // Ignore static resources .requestMatchers(formsBasePath + "/**").authenticated() ) @@ -158,8 +202,7 @@ public SecurityFilterChain formsSecurityFilterChain(HttpSecurity http) throws Ex headers.frameOptions(frameOptions -> frameOptions.sameOrigin()) .contentTypeOptions(Customizer.withDefaults()) .xssProtection(Customizer.withDefaults()) - .contentSecurityPolicy(csp -> csp - .policyDirectives("default-src 'self'; script-src 'self'; object-src 'none'")) + .contentSecurityPolicy(csp -> csp.policyDirectives("script-src 'self'; style-src 'self'")) .cacheControl(Customizer.withDefaults()) ); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/application-dev.properties b/forms/src/main/java/org/devgateway/toolkit/forms/application-dev.properties index ad7b5d54..16915911 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/application-dev.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/application-dev.properties @@ -1,4 +1,8 @@ +server.port = 8080 eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ eureka.client.registerWithEureka=true eureka.client.fetchRegistry=true -eureka.instance.metadata-map.type=data \ No newline at end of file +logging.level.org.springframework=DEBUG +eureka.instance.metadata-map.type=data + +spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/application.properties b/forms/src/main/java/org/devgateway/toolkit/forms/application.properties index ee2baf37..2ccb1823 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/application.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/application.properties @@ -25,6 +25,7 @@ server.tomcat.remote-ip-header=x-forwarded-for server.tomcat.protocol-header=x-forwarded-proto eureka.client.serviceUrl.defaultZone=http://eureka:8761/eureka/ -eureka.instance.preferIpAddress=true eureka.client.registerWithEureka=true -eureka.client.fetchRegistry=true \ No newline at end of file +eureka.client.fetchRegistry=true + +spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java index bbd7f04c..5c6e0ce5 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java @@ -33,6 +33,8 @@ import org.apache.wicket.authroles.authentication.AuthenticatedWebApplication; import org.apache.wicket.authroles.authentication.AuthenticatedWebSession; //import org.apache.wicket.devutils.diskstore.DebugDiskDataStore; +import org.apache.wicket.csp.CSPDirective; +import org.apache.wicket.csp.CSPDirectiveSrcValue; import org.apache.wicket.markup.html.IPackageResourceGuard; import org.apache.wicket.markup.html.SecurePackageResourceGuard; import org.apache.wicket.markup.html.WebPage; @@ -239,6 +241,7 @@ protected void init() { getApplicationSettings().setAccessDeniedPage(AccessDeniedPage.class); configureBootstrap(); + configureCsp(); configureSummernote(); optimizeForWebPerformance(); @@ -253,6 +256,22 @@ protected void init() { useCustomizedSelect2Version(); } + private void configureCsp() { + getCspSettings().blocking() + .add(CSPDirective.SCRIPT_SRC, CSPDirectiveSrcValue.SELF) + .add(CSPDirective.SCRIPT_SRC, CSPDirectiveSrcValue.UNSAFE_INLINE) + .add(CSPDirective.STYLE_SRC, CSPDirectiveSrcValue.SELF) + .add(CSPDirective.STYLE_SRC, CSPDirectiveSrcValue.UNSAFE_INLINE) + .add(CSPDirective.IMG_SRC, CSPDirectiveSrcValue.SELF) + .add(CSPDirective.CONNECT_SRC, CSPDirectiveSrcValue.SELF) + .add(CSPDirective.FONT_SRC, CSPDirectiveSrcValue.SELF) + .add(CSPDirective.MANIFEST_SRC, CSPDirectiveSrcValue.SELF) + .add(CSPDirective.CHILD_SRC, CSPDirectiveSrcValue.SELF) + .add(CSPDirective.BASE_URI, CSPDirectiveSrcValue.SELF) + .add(CSPDirective.FRAME_SRC, CSPDirectiveSrcValue.SELF) + .add(CSPDirective.DEFAULT_SRC, CSPDirectiveSrcValue.NONE); + } + /** * see https://github.com/devgateway/dg-toolkit/issues/228 */ diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 4592d18d..d01db0c2 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -27,10 +27,7 @@ import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; import org.apache.wicket.Page; import org.apache.wicket.authroles.authorization.strategies.role.metadata.MetaDataRoleAuthorizationStrategy; -import org.apache.wicket.markup.head.CssHeaderItem; -import org.apache.wicket.markup.head.IHeaderResponse; -import org.apache.wicket.markup.head.JavaScriptHeaderItem; -import org.apache.wicket.markup.head.MetaDataHeaderItem; +import org.apache.wicket.markup.head.*; import org.apache.wicket.markup.head.filter.HeaderResponseContainer; import org.apache.wicket.markup.html.GenericWebPage; import org.apache.wicket.markup.html.TransparentWebMarkupContainer; @@ -344,6 +341,11 @@ public void renderHead(final IHeaderResponse response) { response.render(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(BaseStyles.class, "assets/js/fileupload.js"))); + + response.render(JavaScriptHeaderItem.forReference(getApplication().getJavaScriptLibrarySettings().getWicketAjaxReference())); + + response.render(JavaScriptHeaderItem.forReference(getApplication().getJavaScriptLibrarySettings().getJQueryReference())); + } protected BreadCrumbPanel createBreadcrumbPanel(final String markupId) { diff --git a/web/pom.xml b/web/pom.xml index 783073a5..f16a11fb 100644 --- a/web/pom.xml +++ b/web/pom.xml @@ -118,21 +118,32 @@ + + + + + + + + + + + + + + + + + io.springfox - springfox-swagger2 - ${swagger.version} - - - - io.springfox - springfox-spring-webmvc + springfox-swagger-ui ${swagger.version} io.springfox - springfox-swagger-ui + springfox-boot-starter ${swagger.version} diff --git a/web/src/main/java/org/devgateway/toolkit/web/application.properties b/web/src/main/java/org/devgateway/toolkit/web/application.properties index c1d1b9e5..f80ad51e 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/application.properties +++ b/web/src/main/java/org/devgateway/toolkit/web/application.properties @@ -21,6 +21,8 @@ spring.mail.host=localhost spring.mail.port=25 spring.mail.sender=tcdisupport@developmentgateway.org +spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER + # Defines role hierarchy. # Hierarchy is specified as a string. Newline separates rules and > symbol has the meaning of 'includes'. # Example: @@ -31,3 +33,6 @@ spring.mail.sender=tcdisupport@developmentgateway.org # Important: spring-security-core 4.x used space or new line to separate rules, since 5.x only new line can separate # new lines. Please make sure to update your rules. roleHierarchy=ROLE_ADMIN > ROLE_USER + +allowedApiEndpoints=/api/testAPI** + diff --git a/web/src/main/java/org/devgateway/toolkit/web/spring/SwaggerConfig.java b/web/src/main/java/org/devgateway/toolkit/web/spring/SwaggerConfig.java index eaeedab5..2a341ee7 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/spring/SwaggerConfig.java +++ b/web/src/main/java/org/devgateway/toolkit/web/spring/SwaggerConfig.java @@ -7,12 +7,10 @@ import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; import static springfox.documentation.builders.PathSelectors.regex; @Configuration -@EnableSwagger2WebMvc public class SwaggerConfig { @Bean public Docket yaliApi() { From 49936169b8ccf9288afb3ac3a3ba1968aeac116c Mon Sep 17 00:00:00 2001 From: Denis Mbugua <60645043+dynamodenis@users.noreply.github.com> Date: Tue, 5 Nov 2024 15:29:20 +0300 Subject: [PATCH 129/137] DVIZ-12 replace addPostProcessingDecorator --- .../forms/wicket/FormsWebApplication.java | 26 +++++++++++++++++-- .../toolkit/forms/wicket/page/BasePage.java | 8 ++---- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java index 5c6e0ce5..3edaf7ab 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java @@ -23,6 +23,7 @@ import de.agilecoders.wicket.extensions.markup.html.bootstrap.editor.SummernoteStoredImageResourceReference; import de.agilecoders.wicket.less.BootstrapLess; import de.agilecoders.wicket.webjars.WicketWebjars; +import de.agilecoders.wicket.webjars.request.resource.WebjarsJavaScriptResourceReference; import nl.dries.wicket.hibernate.dozer.DozerRequestCycleListener; import nl.dries.wicket.hibernate.dozer.SessionFinderHolder; import org.apache.wicket.Application; @@ -35,6 +36,9 @@ //import org.apache.wicket.devutils.diskstore.DebugDiskDataStore; import org.apache.wicket.csp.CSPDirective; import org.apache.wicket.csp.CSPDirectiveSrcValue; +import org.apache.wicket.markup.head.IHeaderResponse; +import org.apache.wicket.markup.head.filter.JavaScriptFilteredIntoFooterHeaderResponse; +import org.apache.wicket.markup.html.IHeaderResponseDecorator; import org.apache.wicket.markup.html.IPackageResourceGuard; import org.apache.wicket.markup.html.SecurePackageResourceGuard; import org.apache.wicket.markup.html.WebPage; @@ -42,6 +46,7 @@ import org.apache.wicket.request.resource.ResourceReference; import org.apache.wicket.request.resource.caching.FilenameWithVersionResourceCachingStrategy; import org.apache.wicket.request.resource.caching.version.CachingResourceVersion; +import org.apache.wicket.resource.JQueryResourceReference; import org.apache.wicket.settings.RequestCycleSettings.RenderStrategy; import org.apache.wicket.spring.injection.annot.SpringComponentInjector; import org.apache.wicket.util.file.Folder; @@ -70,8 +75,10 @@ import org.wicketstuff.select2.ApplicationSettings; import java.math.BigDecimal; +import java.time.Duration; import java.time.LocalDate; import java.time.ZonedDateTime; +import java.util.Iterator; /** * The web application class also serves as spring boot starting point by using @@ -171,7 +178,14 @@ private void configureBootstrap() { */ private void optimizeForWebPerformance() { // add javascript files at the bottom of the page -// setHeaderResponseDecorator(new RenderJavaScriptToFooterHeaderResponseDecorator("scripts-bucket")); + getHeaderResponseDecorators().addPostProcessingDecorator(new RenderJavaScriptToFooterHeaderResponseDecorator("scripts-bucket")); + // Replace all decorators with our footer JavaScript decorator +// getHeaderResponseDecorators().addPostProcessingDecorator(new IHeaderResponseDecorator() { +// @Override +// public IHeaderResponse decorate(IHeaderResponse response) { +// return new JavaScriptFilteredIntoFooterHeaderResponse(response, "scripts-bucket"); +// } +// }); // This is only enabled for deployment configuration // -Dwicket.configuration=deployment @@ -191,6 +205,12 @@ private void optimizeForWebPerformance() { new CachingResourceVersion(new Adler32ResourceVersion()))); getRequestCycleSettings().setRenderStrategy(RenderStrategy.ONE_PASS_RENDER); + + + // Prevent unnecessary resource polling + getResourceSettings().setResourcePollFrequency(null); + getResourceSettings().setThrowExceptionOnMissingResource(false); + // be sure that we have added Dozer Listener getRequestCycleListeners().add(new DozerRequestCycleListener()); @@ -220,6 +240,8 @@ protected Class getWebSessionClass() { protected void init() { super.init(); + getJavaScriptLibrarySettings().setJQueryReference(JQueryResourceReference.getV3()); + // add allowed woff2 extension IPackageResourceGuard packageResourceGuard = getResourceSettings().getPackageResourceGuard(); if (packageResourceGuard instanceof SecurePackageResourceGuard) { @@ -257,7 +279,7 @@ protected void init() { } private void configureCsp() { - getCspSettings().blocking() + getCspSettings().blocking().clear() .add(CSPDirective.SCRIPT_SRC, CSPDirectiveSrcValue.SELF) .add(CSPDirective.SCRIPT_SRC, CSPDirectiveSrcValue.UNSAFE_INLINE) .add(CSPDirective.STYLE_SRC, CSPDirectiveSrcValue.SELF) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index d01db0c2..6848f786 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -25,6 +25,7 @@ import de.agilecoders.wicket.core.util.CssClassNames; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5CssReference; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5IconType; +import org.apache.wicket.Application; import org.apache.wicket.Page; import org.apache.wicket.authroles.authorization.strategies.role.metadata.MetaDataRoleAuthorizationStrategy; import org.apache.wicket.markup.head.*; @@ -336,16 +337,11 @@ public void renderHead(final IHeaderResponse response) { response.render(CssHeaderItem.forReference(BaseStyles.INSTANCE)); // Load Scripts. -// response.render(RespondJavaScriptReference.headerItem()); + // response.render(RespondJavaScriptReference.headerItem()); response.render(JavaScriptHeaderItem.forReference(JQueryResourceReference.getV3())); response.render(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(BaseStyles.class, "assets/js/fileupload.js"))); - - response.render(JavaScriptHeaderItem.forReference(getApplication().getJavaScriptLibrarySettings().getWicketAjaxReference())); - - response.render(JavaScriptHeaderItem.forReference(getApplication().getJavaScriptLibrarySettings().getJQueryReference())); - } protected BreadCrumbPanel createBreadcrumbPanel(final String markupId) { From fb8f855cc4e696fd2975ae22c5d4d2801cb98ccd Mon Sep 17 00:00:00 2001 From: Denis Mbugua <60645043+dynamodenis@users.noreply.github.com> Date: Tue, 5 Nov 2024 22:12:01 +0300 Subject: [PATCH 130/137] DVIZ-12 updared FormWebApplication --- .../forms/wicket/FormsWebApplication.java | 18 +++++------------- .../toolkit/forms/wicket/page/BasePage.java | 1 - 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java index 3edaf7ab..d342b212 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java @@ -178,14 +178,8 @@ private void configureBootstrap() { */ private void optimizeForWebPerformance() { // add javascript files at the bottom of the page - getHeaderResponseDecorators().addPostProcessingDecorator(new RenderJavaScriptToFooterHeaderResponseDecorator("scripts-bucket")); - // Replace all decorators with our footer JavaScript decorator -// getHeaderResponseDecorators().addPostProcessingDecorator(new IHeaderResponseDecorator() { -// @Override -// public IHeaderResponse decorate(IHeaderResponse response) { -// return new JavaScriptFilteredIntoFooterHeaderResponse(response, "scripts-bucket"); -// } -// }); + getHeaderResponseDecorators().add(response -> + new JavaScriptFilteredIntoFooterHeaderResponse(response, "scripts-bucket")); // This is only enabled for deployment configuration // -Dwicket.configuration=deployment @@ -240,8 +234,6 @@ protected Class getWebSessionClass() { protected void init() { super.init(); - getJavaScriptLibrarySettings().setJQueryReference(JQueryResourceReference.getV3()); - // add allowed woff2 extension IPackageResourceGuard packageResourceGuard = getResourceSettings().getPackageResourceGuard(); if (packageResourceGuard instanceof SecurePackageResourceGuard) { @@ -269,9 +261,9 @@ protected void init() { // watch this using the URL // http://.../wicket/internal/debug/diskDataStore -// if (usesDevelopmentConfig()) { -// DebugDiskDataStore.register(this); -// } + if (usesDevelopmentConfig()) { + getDebugSettings().setDevelopmentUtilitiesEnabled(true); + } SessionFinderHolder.setSessionFinder(sessionFinderService); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java index 6848f786..bc9fe9e0 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/BasePage.java @@ -337,7 +337,6 @@ public void renderHead(final IHeaderResponse response) { response.render(CssHeaderItem.forReference(BaseStyles.INSTANCE)); // Load Scripts. - // response.render(RespondJavaScriptReference.headerItem()); response.render(JavaScriptHeaderItem.forReference(JQueryResourceReference.getV3())); response.render(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(BaseStyles.class, From fcb06e2d6c2515609ec424a20f7e24d3d20093c9 Mon Sep 17 00:00:00 2001 From: Denis Mbugua <60645043+dynamodenis@users.noreply.github.com> Date: Tue, 5 Nov 2024 23:38:40 +0300 Subject: [PATCH 131/137] DVIZ-12 updare forms web application --- forms/pom.xml | 10 +++++----- .../toolkit/forms/wicket/FormsWebApplication.java | 8 ++------ 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/forms/pom.xml b/forms/pom.xml index 4f648401..d7e86b55 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -33,10 +33,10 @@ 10.0.0 10.0.0 - 7.0.0 - 1.13 - 4.0.5 - v20200406 + 5.0.4 + 1.14 + 3.0.3 + v20210406 3.3.0 2.4.8 2.2.0 @@ -188,7 +188,7 @@ de.agilecoders.wicket wicket-bootstrap-core - 6.0.0 + ${wicket.bootstrap.version} javassist diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java index d342b212..61855469 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java @@ -200,11 +200,6 @@ private void optimizeForWebPerformance() { getRequestCycleSettings().setRenderStrategy(RenderStrategy.ONE_PASS_RENDER); - - // Prevent unnecessary resource polling - getResourceSettings().setResourcePollFrequency(null); - getResourceSettings().setThrowExceptionOnMissingResource(false); - // be sure that we have added Dozer Listener getRequestCycleListeners().add(new DozerRequestCycleListener()); @@ -255,7 +250,6 @@ protected void init() { getApplicationSettings().setAccessDeniedPage(AccessDeniedPage.class); configureBootstrap(); - configureCsp(); configureSummernote(); optimizeForWebPerformance(); @@ -268,6 +262,8 @@ protected void init() { SessionFinderHolder.setSessionFinder(sessionFinderService); useCustomizedSelect2Version(); + + configureCsp(); } private void configureCsp() { From 3d6e52255b9194923eea1c81c54518d751365748 Mon Sep 17 00:00:00 2001 From: Denis Mbugua <60645043+dynamodenis@users.noreply.github.com> Date: Fri, 8 Nov 2024 12:21:10 +0300 Subject: [PATCH 132/137] DVIZ-12 upgraded to wicket 10.2.0 --- forms/pom.xml | 12 +++--- .../forms/wicket/page/user/LoginPage.java | 1 - persistence/pom.xml | 4 +- web/pom.xml | 42 +++++-------------- 4 files changed, 18 insertions(+), 41 deletions(-) diff --git a/forms/pom.xml b/forms/pom.xml index d7e86b55..d8d5569c 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -30,13 +30,13 @@ UTF-8 17 - 10.0.0 + 10.2.0 10.0.0 5.0.4 - 1.14 + 1.17 3.0.3 - v20210406 + v20240317 3.3.0 2.4.8 2.2.0 @@ -67,7 +67,7 @@ com.thoughtworks.xstream xstream - 1.4.18 + 1.4.20 @@ -260,12 +260,12 @@ org.apache.tika tika-core - 2.0.0 + 3.0.0 org.apache.tika tika-parsers - 2.0.0 + 3.0.0 pom diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LoginPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LoginPage.java index 3642e0fa..e4e7bdad 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LoginPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/user/LoginPage.java @@ -124,7 +124,6 @@ protected void onInitialize() { retrieveReferrerFromSavedRequestIfPresent(); final NotificationPanel notificationPanel = new NotificationPanel("loginFeedback"); -// notificationPanel.hideAfter(Duration.seconds(HIDE_NOTIFICATION_SECONDS)); notificationPanel.hideAfter(Duration.ofSeconds(HIDE_NOTIFICATION_SECONDS)); notificationPanel.setOutputMarkupId(true); add(notificationPanel); diff --git a/persistence/pom.xml b/persistence/pom.xml index dc3f76a1..8bed90fe 100644 --- a/persistence/pom.xml +++ b/persistence/pom.xml @@ -21,7 +21,7 @@ 17 3.10.8 0.3.8 - 3.2.1 + 3.17.0 30.0-jre 1.9.4 @@ -221,7 +221,7 @@ com.opencsv opencsv - 5.6 + 5.9 diff --git a/web/pom.xml b/web/pom.xml index f16a11fb..1c086a9c 100644 --- a/web/pom.xml +++ b/web/pom.xml @@ -17,7 +17,7 @@ UTF-8 org.devgateway.toolkit.web.spring.WebApplication 17 - 1.4 + 5.3.0 3.0.0 @@ -77,6 +77,13 @@ test + + org.junit.jupiter + junit-jupiter-api + 5.11.3 + test + + de.flapdoodle.embed de.flapdoodle.embed.mongo @@ -106,35 +113,6 @@ - - org.apache.poi - ooxml-schemas - ${ooxml-schemas.version} - - - org.apache.xmlbeans - xmlbeans - - - - - - - - - - - - - - - - - - - - - io.springfox springfox-swagger-ui @@ -161,8 +139,8 @@ org.apache.poi - poi-ooxml-schemas - 4.1.2 + poi-ooxml-full + ${ooxml-schemas.version} From 352a5f57aa852a5bab0c47e717c7e87fc8f6b62a Mon Sep 17 00:00:00 2001 From: mpostelnicu Date: Fri, 8 Nov 2024 13:08:53 +0200 Subject: [PATCH 133/137] DVIZ-12 made login page load and login work --- .../toolkit/forms/FormsSecurityConfig.java | 57 +------------------ .../wicket/SSAuthenticatedWebSession.java | 15 ++++- .../wicket/components/util/PageUtil.java | 23 ++++++++ .../toolkit/web/spring/WebSecurityConfig.java | 9 +++ 4 files changed, 46 insertions(+), 58 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/util/PageUtil.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java b/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java index b3c49adc..6dbe25b2 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java @@ -48,7 +48,7 @@ @Configuration @EnableWebSecurity -public class FormsSecurityConfig { +public class FormsSecurityConfig extends WebSecurityConfig { /** * Remember me key for {@link TokenBasedRememberMeServices} @@ -80,56 +80,6 @@ private String[] getAllowedAPIEndpointsWithBasePath() { return new String[]{}; } - @Bean - public HttpFirewall allowUrlEncodedSlashHttpFirewall() { - final StrictHttpFirewall firewall = new StrictHttpFirewall(); - firewall.setAllowUrlEncodedSlash(true); - firewall.setAllowSemicolon(true); - firewall.setAllowUrlEncodedDoubleSlash(true); - return firewall; - } - @Bean - public WebSecurityCustomizer webSecurityCustomizer() { - return (web) -> { - web.httpFirewall(allowUrlEncodedSlashHttpFirewall()); - web.ignoring() - .requestMatchers(getAllowedAPIEndpointsWithBasePath()); - }; - } - - /** - * Instantiates {@see DefaultWebSecurityExpressionHandler} and assigns to it - * role hierarchy. - * - * @return - */ - private SecurityExpressionHandler webExpressionHandler() { - final DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler(); - handler.setRoleHierarchy(roleHierarchy()); - return handler; - } - - /** - * Enable hierarchical roles. This bean can be used to extract all effective - * roles. - */ - @Bean - RoleHierarchy roleHierarchy() { - final RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl(); - roleHierarchy.setHierarchy(roleHierarchyStringRepresentation); - return roleHierarchy; - } - - @Bean - public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { - return authenticationConfiguration.getAuthenticationManager(); - } - - @Autowired - public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(customJPAUserDetailsService).passwordEncoder(passwordEncoder); - } - /** * This bean defines the same key in the @@ -156,11 +106,6 @@ public AbstractRememberMeServices rememberMeServices() { return rememberMeServices; } - @Bean - public HttpSessionSecurityContextRepository httpSessionSecurityContextRepository() { - return new HttpSessionSecurityContextRepository(); - } - /** * We ensure the superclass configuration is being applied Take note the * {@link FormsSecurityConfig} extends {@link WebSecurityConfig} which has diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/SSAuthenticatedWebSession.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/SSAuthenticatedWebSession.java index b01c0a10..f30e1a37 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/SSAuthenticatedWebSession.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/SSAuthenticatedWebSession.java @@ -11,6 +11,8 @@ *******************************************************************************/ package org.devgateway.toolkit.forms.wicket; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.wicket.Session; import org.apache.wicket.authroles.authentication.AuthenticatedWebSession; import org.apache.wicket.authroles.authorization.strategies.role.Roles; @@ -18,6 +20,7 @@ import org.apache.wicket.request.Request; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.wicket.components.util.PageUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.hierarchicalroles.RoleHierarchy; @@ -29,8 +32,8 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.RememberMeServices; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.web.context.HttpSessionSecurityContextRepository; + import java.util.Collection; /** @@ -55,6 +58,9 @@ public class SSAuthenticatedWebSession extends AuthenticatedWebSession { @SpringBean private AuthenticationManager authenticationManager; + @SpringBean + private HttpSessionSecurityContextRepository securityContextRepository; + @SpringBean private RoleHierarchy roleHierarchy; @@ -98,6 +104,11 @@ public boolean authenticate(final String username, final String password) { Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); SecurityContextHolder.getContext().setAuthentication(authentication); + + // (since Spring Security 5.7) explicitly save context, no longer done by security filter + securityContextRepository.saveContext(SecurityContextHolder.getContext(), PageUtil.getHttpServletRequest(), + PageUtil.getHttpServletResponse()); + // httpSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, // SecurityContextHolder.getContext()); authenticated = authentication.isAuthenticated(); diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/util/PageUtil.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/util/PageUtil.java new file mode 100644 index 00000000..48591001 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/util/PageUtil.java @@ -0,0 +1,23 @@ +package org.devgateway.toolkit.forms.wicket.components.util; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.apache.wicket.request.cycle.RequestCycle; + + +/** + * @author Nadejda Mandrescu + */ +public final class PageUtil { + private PageUtil() { + } + + public static HttpServletRequest getHttpServletRequest() { + return (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest(); + } + + public static HttpServletResponse getHttpServletResponse() { + return (HttpServletResponse) RequestCycle.get().getResponse().getContainerResponse(); + } + +} diff --git a/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java b/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java index 7211360b..8f3c702b 100644 --- a/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java +++ b/web/src/main/java/org/devgateway/toolkit/web/spring/WebSecurityConfig.java @@ -24,6 +24,7 @@ import org.springframework.security.access.hierarchicalroles.RoleHierarchy; import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl; import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; @@ -197,6 +198,14 @@ public AuthenticationManager authenticationManager(AuthenticationConfiguration a return authenticationConfiguration.getAuthenticationManager(); } + @Bean + public DaoAuthenticationProvider authenticationProvider() { + DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); + authenticationProvider.setUserDetailsService(customJPAUserDetailsService); + authenticationProvider.setPasswordEncoder(passwordEncoder); + return authenticationProvider; + } + @Autowired public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(customJPAUserDetailsService).passwordEncoder(passwordEncoder); From 912f00c31151e7db8ebe91b7a80bddfb372d1f4d Mon Sep 17 00:00:00 2001 From: Denis Mbugua <60645043+dynamodenis@users.noreply.github.com> Date: Tue, 12 Nov 2024 14:23:06 +0300 Subject: [PATCH 134/137] DVIZ-12 added custom css --- forms/pom.xml | 3 +- .../toolkit/forms/FormsSecurityConfig.java | 1 + .../wicket/components/BigLinksPanel.html | 4 +-- .../toolkit/forms/wicket/page/BasePage.java | 1 + .../toolkit/forms/wicket/page/Footer.html | 2 +- .../toolkit/forms/wicket/page/Homepage.html | 10 ++++-- .../wicket/page/edit/AbstractEditPage.java | 6 ++-- .../page/user/ForgotYourPasswordPage.html | 2 +- .../forms/wicket/page/user/LoginPage.html | 2 +- .../forms/wicket/page/user/LoginPage.java | 3 ++ .../forms/wicket/styles/BaseStyles.css | 34 ++++++++++++++++++- 11 files changed, 55 insertions(+), 13 deletions(-) diff --git a/forms/pom.xml b/forms/pom.xml index d8d5569c..1f2460c4 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -34,6 +34,7 @@ 10.0.0 5.0.4 + 4.0.4 1.17 3.0.3 v20240317 @@ -243,7 +244,7 @@ de.agilecoders.wicket wicket-bootstrap-less - 4.0.4 + ${wicket.bootstrap.less.version} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java b/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java index 6dbe25b2..e2afa78d 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/FormsSecurityConfig.java @@ -48,6 +48,7 @@ @Configuration @EnableWebSecurity +@Order(1) public class FormsSecurityConfig extends WebSecurityConfig { /** diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.html index a124266a..b4a37c42 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/BigLinksPanel.html @@ -2,9 +2,9 @@ -
+
+
+
+
diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index f62160d3..bd56c8a9 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -14,15 +14,18 @@ import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditStatusEntityPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; +import org.devgateway.toolkit.persistence.dao.ServiceMetadata; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; +import org.devgateway.toolkit.persistence.service.ServiceMetadataService; import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.devgateway.toolkit.web.util.SettingsUtils; import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.wicketstuff.annotation.mount.MountPath; +import javax.xml.ws.Service; import java.math.BigDecimal; import static org.devgateway.toolkit.forms.WebConstants.MAXIMUM_PERCENTAGE; @@ -39,9 +42,14 @@ public class EditTetsimDatasetPage extends AbstractEditStatusEntityPage year; + protected Select2ChoiceBootstrapFormComponent service; + @SpringBean protected TetsimDatasetService tetsimDatasetService; + @SpringBean + protected ServiceMetadataService serviceMetadataService; + @SpringBean protected SettingsUtils settingsUtils; @@ -62,6 +70,7 @@ protected void onInitialize() { editForm.add(getBaseLineNumbers()); editForm.add(getPriceAnalysisNumbers()); editForm.add(getIndustryResponsesNumbers()); + editForm.add(getService()); editForm.add(new TetsimMarketSharePercentageValidator()); @@ -80,6 +89,14 @@ private Select2ChoiceBootstrapFormComponent getYear() { return year; } + private Select2ChoiceBootstrapFormComponent getService() { + service = new Select2ChoiceBootstrapFormComponent<>("service", + new GenericChoiceProvider<>(serviceMetadataService.findAll())); + editForm.add(service); + + return service; + } + @Override protected void onDelete(final AjaxRequestTarget target) { try { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties index b83fab3f..6fc82052 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.properties @@ -1,5 +1,6 @@ page.title.add=Add TETSIM Dataset page.title.edit=Edit TETSIM Dataset year.label=Year +service.label=Service error.form.validation.marketShare.percentage=The total of all the market share values should add up to 100 \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/ServiceMetadata.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/ServiceMetadata.java index 682ea242..9b777b8f 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/ServiceMetadata.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/ServiceMetadata.java @@ -27,4 +27,33 @@ public class ServiceMetadata extends AbstractStatusAuditableEntity implements Se public AbstractAuditableEntity getParent() { return null; } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(final String description) { + this.description = description; + } + + public String getUrl() { + return url; + } + + public void setUrl(final String url) { + this.url = url; + } + + @Override + public String toString() { + return getName(); + } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java index 5b967868..bd2ba8c4 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java @@ -2,8 +2,10 @@ import org.devgateway.toolkit.persistence.dao.AbstractAuditableEntity; import org.devgateway.toolkit.persistence.dao.AbstractStatusAuditableEntity; +import org.devgateway.toolkit.persistence.dao.ServiceMetadata; import org.hibernate.envers.Audited; +import javax.persistence.ManyToOne; import javax.persistence.MappedSuperclass; import javax.validation.constraints.NotNull; import java.io.Serializable; @@ -15,6 +17,14 @@ public abstract class Dataset extends AbstractStatusAuditableEntity implements S @Audited private Integer year; + @ManyToOne + @Audited + private ServiceMetadata service; + + public ServiceMetadata getService() { + return service; + } + @Override public AbstractAuditableEntity getParent() { return null; @@ -28,4 +38,7 @@ public void setYear(final Integer year) { this.year = year; } + public void setService(final ServiceMetadata service) { + this.service = service; + } } From a42e20830198fa90463a4ca3e269dd49ee8fb35d Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Thu, 7 Jul 2022 15:46:47 +0300 Subject: [PATCH 069/137] TOBACCO-945: Add eureka discovery client and use the registered services --- forms/pom.xml | 6 ++ .../toolkit/forms/application-dev.properties | 1 + .../toolkit/forms/application.properties | 4 +- .../forms/service/EurekaClientService.java | 61 ++++++++++++++++ .../forms/wicket/FormsWebApplication.java | 2 + .../components/LinkTargetBlankPanel.html | 10 +++ .../components/LinkTargetBlankPanel.java | 26 +++++++ .../page/edit/admin/EditServicePage.html | 16 ---- .../page/edit/admin/EditServicePage.java | 32 -------- .../edit/admin/EditServicePage.properties | 5 -- .../edit/dataset/EditTetsimDatasetPage.java | 46 ++++++++++-- .../page/lists/admin/ListServicePage.html | 15 ++++ .../page/lists/admin/ListServicePage.java | 73 ++++++++++++++++--- .../lists/admin/ServiceMetadataProvider.java | 72 ++++++++++++++++++ .../persistence/application-dev.properties | 4 +- .../persistence/application.properties | 2 + .../toolkit/persistence/dao/data/Dataset.java | 13 ---- .../{dao => dto}/ServiceMetadata.java | 48 +++++++----- .../repository/ServiceMetadataRepository.java | 12 --- .../service/ServiceMetadataService.java | 8 -- .../service/ServiceMetadataServiceImpl.java | 30 -------- 21 files changed, 331 insertions(+), 155 deletions(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/application-dev.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/LinkTargetBlankPanel.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/LinkTargetBlankPanel.java delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.html delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.java delete mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.properties create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.html create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMetadataProvider.java rename persistence/src/main/java/org/devgateway/toolkit/persistence/{dao => dto}/ServiceMetadata.java (52%) delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/repository/ServiceMetadataRepository.java delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataService.java delete mode 100644 persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataServiceImpl.java diff --git a/forms/pom.xml b/forms/pom.xml index f2c121ca..f16ca30d 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -282,6 +282,12 @@ jersey-media-json-jackson ${jersey.version} + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + 2.2.10.RELEASE + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/application-dev.properties b/forms/src/main/java/org/devgateway/toolkit/forms/application-dev.properties new file mode 100644 index 00000000..131b8f0a --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/application-dev.properties @@ -0,0 +1 @@ +eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/application.properties b/forms/src/main/java/org/devgateway/toolkit/forms/application.properties index 8667675a..29b258a3 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/application.properties +++ b/forms/src/main/java/org/devgateway/toolkit/forms/application.properties @@ -22,4 +22,6 @@ spring.aop.proxy-target-class=true # The presence of either of those properties switches on the RemoteIpValve. # This presence of valve will fix issue with reverse proxy server.tomcat.remote-ip-header=x-forwarded-for -server.tomcat.protocol-header=x-forwarded-proto \ No newline at end of file +server.tomcat.protocol-header=x-forwarded-proto + +eureka.client.serviceUrl.defaultZone=http://eureka:8761/eureka/ \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java new file mode 100644 index 00000000..c01a8d92 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java @@ -0,0 +1,61 @@ +package org.devgateway.toolkit.forms.service; + +import com.netflix.appinfo.InstanceInfo; +import org.devgateway.toolkit.persistence.dto.ServiceMetadata; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.netflix.eureka.EurekaServiceInstance; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +public class EurekaClientService { + + @Autowired + private DiscoveryClient discoveryClient; + + public List findAll() { + List services = new ArrayList<>(); + discoveryClient.getServices().forEach(s -> { + discoveryClient.getInstances(s).stream().forEach(instance -> { + InstanceInfo instanceInfo = ((EurekaServiceInstance) instance).getInstanceInfo(); + ServiceMetadata service = new ServiceMetadata(); + service.setName(instanceInfo.getAppName()); + service.setUrl(instanceInfo.getHomePageUrl()); + service.setId(instanceInfo.getId()); + service.setType(instance.getMetadata().getOrDefault("type", null)); + service.setStatus(instanceInfo.getStatus().toString()); + services.add(service); + }); + }); + + return services; + } + + public List findAllWithData() { + return findAll().stream() + .filter(s -> "data".equals(s.getType())) + .collect(Collectors.toList()); + } + + + public Set getServiceByMetadataType(String type) { + Set services = new HashSet<>(); + discoveryClient.getServices().forEach(s -> { + System.out.print(s + "-"); + discoveryClient.getInstances(s).stream().forEach(instance -> { + if ("data".equals(instance.getMetadata().getOrDefault("type", ""))) { + services.add(s); + } + }); + }); + + return services; + } + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java index fa850d6c..aa6ba764 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/FormsWebApplication.java @@ -59,6 +59,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; @@ -80,6 +81,7 @@ @EnableScheduling @SpringBootApplication(exclude = {org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration.class}) @ComponentScan("org.devgateway.toolkit") +@EnableEurekaClient @PropertySource("classpath:/org/devgateway/toolkit/forms/application.properties") public class FormsWebApplication extends AuthenticatedWebApplication { diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/LinkTargetBlankPanel.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/LinkTargetBlankPanel.html new file mode 100644 index 00000000..b8fd141d --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/LinkTargetBlankPanel.html @@ -0,0 +1,10 @@ + + + LinkTargetBlankPanel + + + +
+ + + \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/LinkTargetBlankPanel.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/LinkTargetBlankPanel.java new file mode 100644 index 00000000..db866676 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/LinkTargetBlankPanel.java @@ -0,0 +1,26 @@ +package org.devgateway.toolkit.forms.wicket.components; + +import org.apache.wicket.markup.ComponentTag; +import org.apache.wicket.markup.html.link.ExternalLink; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; + +public class LinkTargetBlankPanel extends Panel { + + public LinkTargetBlankPanel(String id, IModel url) { + this(id, url, url); + } + + public LinkTargetBlankPanel(String id, IModel url, IModel label) { + super(id); + add(new ExternalLink("link", url, label) { + private static final long serialVersionUID = -8010560272317354356L; + + @Override + protected void onComponentTag(ComponentTag tag) { + super.onComponentTag(tag); + tag.put("target", "_blank"); + } + }); + } +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.html deleted file mode 100644 index 2a7b9e1c..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - Edit Service - - - -
-
-
-
-
-
- - diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.java deleted file mode 100644 index 6e993048..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.devgateway.toolkit.forms.wicket.page.edit.admin; - -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.devgateway.toolkit.forms.wicket.components.form.TextFieldBootstrapFormComponent; -import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditPage; -import org.devgateway.toolkit.forms.wicket.page.lists.admin.ListServicePage; -import org.devgateway.toolkit.persistence.dao.ServiceMetadata; -import org.devgateway.toolkit.persistence.service.ServiceMetadataService; - -public class EditServicePage extends AbstractEditPage { - - @SpringBean - protected ServiceMetadataService serviceMetadataService; - - public EditServicePage(final PageParameters parameters) { - super(parameters); - this.jpaService = serviceMetadataService; - this.listPageClass = ListServicePage.class; - - } - - @Override - protected void onInitialize() { - super.onInitialize(); - - editForm.add(new TextFieldBootstrapFormComponent<>("name").required()); - editForm.add(new TextFieldBootstrapFormComponent<>("description")); - editForm.add(new TextFieldBootstrapFormComponent<>("url")); - } - -} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.properties b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.properties deleted file mode 100644 index 5ffb9d1a..00000000 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/admin/EditServicePage.properties +++ /dev/null @@ -1,5 +0,0 @@ -page.title.add=Add Service -page.title.edit=Edit Service -name.label=Name -description.label=Description -url.label=URL \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java index bd56c8a9..5113a79f 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/dataset/EditTetsimDatasetPage.java @@ -1,32 +1,34 @@ package org.devgateway.toolkit.forms.wicket.page.edit.dataset; +import org.apache.commons.lang3.StringUtils; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.form.validation.AbstractFormValidator; import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; +import org.devgateway.toolkit.forms.service.EurekaClientService; import org.devgateway.toolkit.forms.wicket.components.form.BootstrapCancelButton; import org.devgateway.toolkit.forms.wicket.components.form.Select2ChoiceBootstrapFormComponent; import org.devgateway.toolkit.forms.wicket.page.edit.AbstractEditStatusEntityPage; import org.devgateway.toolkit.forms.wicket.page.lists.dataset.ListTetsimDatasetPage; import org.devgateway.toolkit.forms.wicket.providers.GenericChoiceProvider; -import org.devgateway.toolkit.persistence.dao.ServiceMetadata; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.devgateway.toolkit.persistence.dao.data.TetsimPriceVariable; import org.devgateway.toolkit.persistence.dao.data.TetsimTobaccoProductValue; -import org.devgateway.toolkit.persistence.service.ServiceMetadataService; +import org.devgateway.toolkit.persistence.dto.ServiceMetadata; import org.devgateway.toolkit.persistence.service.category.TobaccoProductService; import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; import org.devgateway.toolkit.web.util.SettingsUtils; import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.wicketstuff.annotation.mount.MountPath; -import javax.xml.ws.Service; import java.math.BigDecimal; +import java.util.stream.Collectors; import static org.devgateway.toolkit.forms.WebConstants.MAXIMUM_PERCENTAGE; import static org.devgateway.toolkit.forms.WebConstants.PARAM_YEAR; @@ -42,13 +44,15 @@ public class EditTetsimDatasetPage extends AbstractEditStatusEntityPage year; - protected Select2ChoiceBootstrapFormComponent service; + protected Select2ChoiceBootstrapFormComponent service; + + private Model serviceModel = Model.of(""); @SpringBean protected TetsimDatasetService tetsimDatasetService; @SpringBean - protected ServiceMetadataService serviceMetadataService; + protected EurekaClientService eurekaClientService; @SpringBean protected SettingsUtils settingsUtils; @@ -89,9 +93,29 @@ private Select2ChoiceBootstrapFormComponent getYear() { return year; } - private Select2ChoiceBootstrapFormComponent getService() { - service = new Select2ChoiceBootstrapFormComponent<>("service", - new GenericChoiceProvider<>(serviceMetadataService.findAll())); + private Select2ChoiceBootstrapFormComponent getService() { + service = new Select2ChoiceBootstrapFormComponent("service", + new GenericChoiceProvider<>(eurekaClientService.findAllWithData().stream() + .map(ServiceMetadata::getName) + .collect(Collectors.toList())), serviceModel) { + @Override + protected void onUpdate(final AjaxRequestTarget target) { + super.onUpdate(target); + if (serviceModel.getObject() != null) { + saveApproveButton.setEnabled(true); + approveButton.setEnabled(true); + } else { + saveApproveButton.setEnabled(false); + approveButton.setEnabled(false); + } + + target.add(approveButton); + target.add(saveApproveButton); + } + + + }; + service.setEnabled(true); editForm.add(service); return service; @@ -197,8 +221,14 @@ protected void enableDisableAutosaveFields(final AjaxRequestTarget target) { approveButton.setEnabled(false); revertToDraftPageButton.setEnabled(false); } + + if (StringUtils.isBlank(serviceModel.getObject())) { + saveApproveButton.setEnabled(false); + approveButton.setEnabled(false); + } } + protected Integer getYearParam() { return getPageParameters().get(PARAM_YEAR).toOptionalInteger(); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.html new file mode 100644 index 00000000..3eaf2050 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.html @@ -0,0 +1,15 @@ + + + + + + +
+
+
+
+
+ +
+ + \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java index f88935c2..d4870985 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ListServicePage.java @@ -12,41 +12,92 @@ package org.devgateway.toolkit.forms.wicket.page.lists.admin; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.behavior.AttributeAppender; +import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.devgateway.toolkit.forms.security.SecurityConstants; -import org.devgateway.toolkit.forms.wicket.page.edit.admin.EditServicePage; -import org.devgateway.toolkit.forms.wicket.page.lists.AbstractListPage; -import org.devgateway.toolkit.persistence.dao.ServiceMetadata; -import org.devgateway.toolkit.persistence.service.ServiceMetadataService; +import org.devgateway.toolkit.forms.service.EurekaClientService; +import org.devgateway.toolkit.forms.wicket.components.LinkTargetBlankPanel; +import org.devgateway.toolkit.forms.wicket.components.table.AjaxFallbackBootstrapDataTable; +import org.devgateway.toolkit.forms.wicket.page.BasePage; +import org.devgateway.toolkit.persistence.dto.ServiceMetadata; import org.wicketstuff.annotation.mount.MountPath; +import java.util.ArrayList; +import java.util.List; + +import static org.devgateway.toolkit.forms.WebConstants.PAGE_SIZE; + @AuthorizeInstantiation(SecurityConstants.Roles.ROLE_ADMIN) @MountPath(value = "/listservices") -public class ListServicePage extends AbstractListPage { +public class ListServicePage extends BasePage { private static final long serialVersionUID = -6132847935476573446L; + protected AjaxFallbackBootstrapDataTable dataTable; + + protected ServiceMetadataProvider dataProvider; + + protected List> columns; + @SpringBean - private ServiceMetadataService serviceMetadataService; + private EurekaClientService eurekaClientService; + + protected int pageRowNo = 0; public ListServicePage(final PageParameters pageParameters) { super(pageParameters); - this.jpaService = serviceMetadataService; + dataProvider = new ServiceMetadataProvider(eurekaClientService); - this.editPageClass = EditServicePage.class; + columns = new ArrayList<>(); columns.add(new PropertyColumn<>(new Model<>("Name"), "name", "name")); - columns.add(new PropertyColumn<>(new Model<>("Description"), "description", "description")); - columns.add(new PropertyColumn<>(new Model<>("URL"), "url", "url")); + columns.add(new PropertyColumn<>(new Model<>("ID"), "id", "id")); + columns.add(new PropertyColumn(new Model<>("URL"), "url", "url") { + @Override + public void populateItem(final Item> item, final String componentId, + final IModel rowModel) { + item.add(new LinkTargetBlankPanel(componentId, new PropertyModel<>(rowModel, "url"))); + } + }); + columns.add(new PropertyColumn<>(new Model<>("Type"), "type", "type")); + columns.add(new PropertyColumn(new Model<>("Status"), "status", "status") { + @Override + public void populateItem(final Item> item, final String componentId, + final IModel rowModel) { + String cssClass = rowModel.getObject().getStatus().equals("UP") ? "label-success" : "label-danger"; + Label label = new Label(componentId, this.getDataModel(rowModel)); + label.add(AttributeAppender.append("class", "label " + cssClass)); + item.add(label); + } + }); } @Override protected void onInitialize() { super.onInitialize(); - excelForm.setVisibilityAllowed(false); + dataTable = new AjaxFallbackBootstrapDataTable( + "table", columns, dataProvider, getPageSize()) { + private static final long serialVersionUID = -7263599298497560059L; + + @Override + protected void onPageChanged() { + pageRowNo = 0; + } + }; + add(dataTable); + } + + protected int getPageSize() { + return PAGE_SIZE; } } \ No newline at end of file diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMetadataProvider.java b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMetadataProvider.java new file mode 100644 index 00000000..cba6abfe --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/lists/admin/ServiceMetadataProvider.java @@ -0,0 +1,72 @@ +package org.devgateway.toolkit.forms.wicket.page.lists.admin; + +import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; +import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.devgateway.toolkit.forms.service.EurekaClientService; +import org.devgateway.toolkit.persistence.dto.ServiceMetadata; + +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + +/** + * Data provider used to provide information about the data submissions + * + * @author Viorel Chihai + */ +public class ServiceMetadataProvider extends SortableDataProvider { + private static final long serialVersionUID = 1858130875067823547L; + + protected EurekaClientService eurekaClientService; + + public ServiceMetadataProvider(final EurekaClientService eurekaClientService) { + this.eurekaClientService = eurekaClientService; + } + + @Override + public Iterator iterator(final long first, final long count) { + List services = eurekaClientService.findAll(); + + if (first > services.size()) { + return Collections.emptyIterator(); + } + + if (getSort() == null || getSort().getProperty().equals("label")) { + Comparator comparator = new ServiceMetadataComparator(); + + if (getSort() != null && getSort().isAscending()) { + comparator = comparator.reversed(); + } + + Collections.sort(services, comparator); + } + + return services.subList((int) first, (int) Math.min(first + count, services.size())).iterator(); + } + + @Override + public SortParam getSort() { + return super.getSort(); + } + + @Override + public long size() { + return eurekaClientService.findAll().size(); + } + + @Override + public IModel model(final ServiceMetadata serviceMetadata) { + return Model.of(serviceMetadata); + } + + protected class ServiceMetadataComparator implements Comparator { + @Override + public int compare(final ServiceMetadata s1, final ServiceMetadata s2) { + return String.CASE_INSENSITIVE_ORDER.compare(s1.getName(), s2.getName()); + } + } + +} \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties index 26d0ffb2..dccb755e 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application-dev.properties @@ -15,4 +15,6 @@ spring.datasource.password=postgres spring.datasource.jdbc-url=jdbc:postgresql://localhost:5432/tcdi-admin management.health.mail.enabled=false -dg-toolkit.forms.base-path=/admin \ No newline at end of file +dg-toolkit.forms.base-path=/admin + +eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ \ No newline at end of file diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties index 19095afc..6549bea8 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/application.properties @@ -55,4 +55,6 @@ spring.cache.jcache.config=classpath:ehcache.xml spring.data.rest.base-path=/rest spring.profiles.active=integration +eureka.client.serviceUrl.defaultZone=http://eureka:8761/eureka/ + dg-toolkit.forms.base-path=/admin diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java index bd2ba8c4..5b967868 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/data/Dataset.java @@ -2,10 +2,8 @@ import org.devgateway.toolkit.persistence.dao.AbstractAuditableEntity; import org.devgateway.toolkit.persistence.dao.AbstractStatusAuditableEntity; -import org.devgateway.toolkit.persistence.dao.ServiceMetadata; import org.hibernate.envers.Audited; -import javax.persistence.ManyToOne; import javax.persistence.MappedSuperclass; import javax.validation.constraints.NotNull; import java.io.Serializable; @@ -17,14 +15,6 @@ public abstract class Dataset extends AbstractStatusAuditableEntity implements S @Audited private Integer year; - @ManyToOne - @Audited - private ServiceMetadata service; - - public ServiceMetadata getService() { - return service; - } - @Override public AbstractAuditableEntity getParent() { return null; @@ -38,7 +28,4 @@ public void setYear(final Integer year) { this.year = year; } - public void setService(final ServiceMetadata service) { - this.service = service; - } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/ServiceMetadata.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java similarity index 52% rename from persistence/src/main/java/org/devgateway/toolkit/persistence/dao/ServiceMetadata.java rename to persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java index 9b777b8f..d0f596e7 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/dao/ServiceMetadata.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/dto/ServiceMetadata.java @@ -1,31 +1,27 @@ -package org.devgateway.toolkit.persistence.dao; +package org.devgateway.toolkit.persistence.dto; -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; -import org.hibernate.envers.Audited; - -import javax.persistence.Entity; -import javax.validation.constraints.NotNull; import java.io.Serializable; -@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) -@Entity -@Audited -public class ServiceMetadata extends AbstractStatusAuditableEntity implements Serializable { +public class ServiceMetadata implements Serializable { + + private String id; - @NotNull - @Audited private String name; - @Audited private String description; - @Audited private String url; - @Override - public AbstractAuditableEntity getParent() { - return null; + private String type; + + private String status; + + public String getId() { + return id; + } + + public void setId(final String id) { + this.id = id; } public String getName() { @@ -52,8 +48,24 @@ public void setUrl(final String url) { this.url = url; } + public String getType() { + return type; + } + + public void setType(final String type) { + this.type = type; + } + @Override public String toString() { return getName(); } + + public String getStatus() { + return status; + } + + public void setStatus(final String status) { + this.status = status; + } } diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/ServiceMetadataRepository.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/ServiceMetadataRepository.java deleted file mode 100644 index 378f1a9b..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/repository/ServiceMetadataRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.devgateway.toolkit.persistence.repository; - -import org.devgateway.toolkit.persistence.dao.ServiceMetadata; -import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public interface ServiceMetadataRepository extends BaseJpaRepository { - - ServiceMetadata findByName(String name); - -} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataService.java deleted file mode 100644 index 1e7cd1d2..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataService.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.devgateway.toolkit.persistence.service; - -import org.devgateway.toolkit.persistence.dao.ServiceMetadata; - -public interface ServiceMetadataService extends BaseJpaService { - - ServiceMetadata findByName(String name); -} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataServiceImpl.java deleted file mode 100644 index 71250137..00000000 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/ServiceMetadataServiceImpl.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.devgateway.toolkit.persistence.service; - -import org.devgateway.toolkit.persistence.dao.ServiceMetadata; -import org.devgateway.toolkit.persistence.repository.ServiceMetadataRepository; -import org.devgateway.toolkit.persistence.repository.norepository.BaseJpaRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional(readOnly = true) -public class ServiceMetadataServiceImpl extends BaseJpaServiceImpl implements ServiceMetadataService { - @Autowired - private ServiceMetadataRepository serviceMetadataRepository; - - @Override - public ServiceMetadata findByName(final String name) { - return serviceMetadataRepository.findByName(name); - } - - @Override - protected BaseJpaRepository repository() { - return serviceMetadataRepository; - } - - @Override - public ServiceMetadata newInstance() { - return new ServiceMetadata(); - } -} From 391f256ee4f390a0248b11f0bbe8715652cd1296 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 13 Jul 2022 10:41:35 +0300 Subject: [PATCH 070/137] TOBACCO-941: Check the tetsim dataset in publishing mode --- .../toolkit/forms/client/ClientConstants.java | 17 +++++ .../service/DatasetPublishingService.java | 71 +++++++++++++++++++ .../service/data/TetsimDatasetService.java | 1 + .../data/TetsimDatasetServiceImpl.java | 2 +- 4 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java create mode 100644 forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java new file mode 100644 index 00000000..3369c1d4 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/ClientConstants.java @@ -0,0 +1,17 @@ +package org.devgateway.toolkit.forms.client; + +public class ClientConstants { + + public static final class JobStatus { + public static final String COMPLETED = "COMPLETED"; + public static final String ERROR = "ERROR"; + } + + public final static String PATH_HEALTH = "/actuator/health"; + public final static String PATH_JOBS = "/admin/jobs"; + public final static String PATH_DATASETS = "/admin/datasets"; + public final static String PATH_EXTERNAL = "/external"; + + public final static String EXTERNAL_ID_PREFIX = "tcdi-"; + +} diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java new file mode 100644 index 00000000..70952eb4 --- /dev/null +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/DatasetPublishingService.java @@ -0,0 +1,71 @@ +package org.devgateway.toolkit.forms.service; + +import com.opencsv.exceptions.CsvDataTypeMismatchException; +import com.opencsv.exceptions.CsvRequiredFieldEmptyException; +import org.devgateway.toolkit.forms.client.DataSetClientException; +import org.devgateway.toolkit.forms.client.DatasetClient; +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dto.ServiceMetadata; +import org.devgateway.toolkit.persistence.service.data.TetsimDatasetService; +import org.devgateway.toolkit.persistence.service.tetsim.TetsimOutputService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.io.IOException; + +import static org.devgateway.toolkit.forms.client.ClientConstants.EXTERNAL_ID_PREFIX; +import static org.devgateway.toolkit.forms.client.ClientConstants.JobStatus.COMPLETED; +import static org.devgateway.toolkit.forms.client.ClientConstants.JobStatus.ERROR; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.NOT_PUBLISHED; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHED; +import static org.devgateway.toolkit.persistence.dao.DBConstants.Status.PUBLISHING; + +@Service +public class DatasetPublishingService { + + private static final Logger logger = LoggerFactory.getLogger(DatasetPublishingService.class); + + @Autowired + private TetsimOutputService tetsimOutputService; + + @Autowired + private TetsimDatasetService tetsimDatasetService; + + @Autowired + private EurekaClientService eurekaClientService; + + @Scheduled(cron = "0 * * * * *") + public void triggerCheckDatasetsJob() { + logger.info("Fired triggerCheckDatasetsJob"); + + tetsimDatasetService.findAllPublishing().forEach(d -> { + ServiceMetadata serviceMetadata = eurekaClientService.getServiceByName(d.getDestinationService()); + DatasetClient client = new DatasetClient(serviceMetadata.getUrl()); + String status = client.getDatasetJobStatus(EXTERNAL_ID_PREFIX + d.getId()).getStatus(); + if (COMPLETED.equals(status)) { + d.setStatus(PUBLISHED); + logger.info(String.format("The dataset with id %s changed the status from %s to %s", + d.getId(), PUBLISHING, PUBLISHED)); + } else if (ERROR.equals(status)) { + d.setStatus(NOT_PUBLISHED); + logger.info(String.format("The dataset with id %s changed the status from %s to %s", + d.getId(), PUBLISHING, NOT_PUBLISHED)); + } + + if (!PUBLISHING.equals(d.getStatus())) { + tetsimDatasetService.save(d); + } + }); + + } + + public void publish(ServiceMetadata service, TetsimDataset dataset) throws DataSetClientException, CsvRequiredFieldEmptyException, CsvDataTypeMismatchException, IOException { + byte[] tetsimCSVDatasetOutputs = tetsimOutputService.getTetsimCSVDatasetOutputs(dataset.getId()); + + DatasetClient client = new DatasetClient(service.getUrl()); + client.publishDataset(dataset, tetsimCSVDatasetOutputs); + } +} diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java index dbfb1f66..99a44d1d 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetService.java @@ -1,6 +1,7 @@ package org.devgateway.toolkit.persistence.service.data; import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; +import org.devgateway.toolkit.persistence.dto.ServiceMetadata; import org.devgateway.toolkit.persistence.service.BaseJpaService; import org.devgateway.toolkit.persistence.service.UniquePropertyService; diff --git a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java index a334e7de..69ebf968 100644 --- a/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java +++ b/persistence/src/main/java/org/devgateway/toolkit/persistence/service/data/TetsimDatasetServiceImpl.java @@ -42,7 +42,7 @@ public List findAllDeleted() { @Override public List findAllPublishing() { - return null; + return tetsimDatasetRepository.findAllPublishing(); } @Override From 9b4e3bee9efee55e5fdbe329764042b67a050e31 Mon Sep 17 00:00:00 2001 From: Viorel Chihai Date: Wed, 13 Jul 2022 10:47:26 +0300 Subject: [PATCH 071/137] TOBACCO-946: Publish the tetsim dataset to the microservice --- forms/pom.xml | 6 ++ .../toolkit/forms/client/DatasetClient.java | 80 ++++++++++++++++--- .../forms/client/DatasetJobStatus.java | 73 +++++++++++++++++ .../forms/service/EurekaClientService.java | 6 ++ .../wicket/page/edit/AbstractEditPage.html | 1 + .../wicket/page/edit/AbstractEditPage.java | 29 +++++++ .../edit/AbstractEditStatusEntityPage.java | 16 +++- .../edit/dataset/EditTetsimDatasetPage.html | 2 +- .../edit/dataset/EditTetsimDatasetPage.java | 55 ++++++++++--- .../dataset/EditTetsimDatasetPage.properties | 2 +- .../toolkit/persistence/dao/data/Dataset.java | 10 +++ .../toolkit/persistence/dto/TetsimOutput.java | 10 +++ .../service/tetsim/TetsimOutputService.java | 2 +- .../tetsim/TetsimOutputBaseCalculator.java | 1 + 14 files changed, 264 insertions(+), 29 deletions(-) diff --git a/forms/pom.xml b/forms/pom.xml index f16ca30d..6868b0ab 100644 --- a/forms/pom.xml +++ b/forms/pom.xml @@ -282,12 +282,18 @@ jersey-media-json-jackson ${jersey.version} + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey.version} + org.springframework.cloud spring-cloud-starter-netflix-eureka-client 2.2.10.RELEASE + diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java index cb700e23..ee30e2db 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetClient.java @@ -1,12 +1,29 @@ package org.devgateway.toolkit.forms.client; +import org.apache.commons.io.FileUtils; +import org.devgateway.toolkit.persistence.dao.data.TetsimDataset; import org.glassfish.jersey.client.JerseyClient; import org.glassfish.jersey.client.JerseyClientBuilder; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; +import javax.ws.rs.client.Entity; import javax.ws.rs.core.Response; +import java.io.File; +import java.io.IOException; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM_TYPE; +import static javax.ws.rs.core.MediaType.MULTIPART_FORM_DATA_TYPE; +import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE; import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL; +import static org.devgateway.toolkit.forms.client.ClientConstants.EXTERNAL_ID_PREFIX; +import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_DATASETS; +import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_EXTERNAL; +import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_HEALTH; +import static org.devgateway.toolkit.forms.client.ClientConstants.PATH_JOBS; public class DatasetClient { @@ -15,13 +32,9 @@ public class DatasetClient { private final String baseUrl; - private final static String PATH_HEALTH = "actuator/health"; - - private final static String PATH_JOBS = "admin/jobs/"; - public DatasetClient(final String baseUrl) { this.baseUrl = baseUrl; - this.client = JerseyClientBuilder.createClient(); + this.client = JerseyClientBuilder.createClient().register(MultiPartFeature.class); } public DatasetJobStatus getDatasetStatus(String jobId) throws DataSetClientException { @@ -42,6 +55,56 @@ public DatasetJobStatus getDatasetStatus(String jobId) throws DataSetClientExcep throw new RuntimeException(("Service is not up")); } + public DatasetJobStatus publishDataset(TetsimDataset dataset, byte[] datasetContent) throws DataSetClientException { + if (isUp()) { + File tempUploadFile; + try { + tempUploadFile = File.createTempFile(dataset.getYear() + "_tetsim.csv", ".csv"); + tempUploadFile.deleteOnExit(); + + FileUtils.writeByteArrayToFile(tempUploadFile, datasetContent); + FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file", tempUploadFile, APPLICATION_OCTET_STREAM_TYPE); + fileDataBodyPart.setContentDisposition(FormDataContentDisposition.name("file").fileName(tempUploadFile.getName()).build()); + + FormDataMultiPart multiPart = new FormDataMultiPart(); + multiPart.field("name", "TETSIM dataset " + dataset.getYear()); + multiPart.field("externalId", EXTERNAL_ID_PREFIX + dataset.getId()); + multiPart.field("year", dataset.getYear().toString()); + multiPart.field("file", tempUploadFile.getName(), TEXT_PLAIN_TYPE) + .bodyPart(fileDataBodyPart); + + Response jobStatusResponse = client.target(baseUrl) + .path(PATH_DATASETS) + .request() + .post(Entity.entity(multiPart, MULTIPART_FORM_DATA_TYPE)); + + if (jobStatusResponse.getStatusInfo().getFamily() == SUCCESSFUL) { + return jobStatusResponse.readEntity(DatasetJobStatus.class); + } + + throw new DataSetClientException(jobStatusResponse.toString()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + throw new RuntimeException(("Service is not up")); + } + + public DatasetJobStatus getDatasetJobStatus(String externalId) { + Response jobStatusResponse = client.target(baseUrl) + .path(PATH_JOBS) + .path(PATH_EXTERNAL) + .path(externalId) + .request(APPLICATION_JSON).get(); + + if (jobStatusResponse.getStatusInfo().getFamily() == SUCCESSFUL) { + return jobStatusResponse.readEntity(DatasetJobStatus.class); + } + + return null; + } + public boolean isUp() { Response healthResponse = client.target(baseUrl).path(PATH_HEALTH) .request(APPLICATION_JSON).get(); @@ -52,11 +115,4 @@ public boolean isUp() { return false; } - -// List> response = client.resource(uri) -// .type(MediaType.APPLICATION_JSON_TYPE) -// .accept(MediaType.APPLICATION_JSON_TYPE) -// .post(new GenericType>>() { }, jsonActivities); -// -// List queueIds = new ArrayList<>(); } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetJobStatus.java b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetJobStatus.java index fe24755f..5910b143 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetJobStatus.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/client/DatasetJobStatus.java @@ -1,5 +1,78 @@ package org.devgateway.toolkit.forms.client; +import java.time.ZonedDateTime; + public class DatasetJobStatus { + private Long id; + + private ZonedDateTime createdDate; + + private ZonedDateTime endDate; + + private String status; + + private String externalId; + + private String message; + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public ZonedDateTime getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(final ZonedDateTime createdDate) { + this.createdDate = createdDate; + } + + public ZonedDateTime getEndDate() { + return endDate; + } + + public void setEndDate(final ZonedDateTime endDate) { + this.endDate = endDate; + } + + public String getStatus() { + return status; + } + + public void setStatus(final String status) { + this.status = status; + } + + public String getExternalId() { + return externalId; + } + + public void setExternalId(final String externalId) { + this.externalId = externalId; + } + + public String getMessage() { + return message; + } + + public void setMessage(final String message) { + this.message = message; + } + + @Override + public String toString() { + return "DatasetJobStatus{" + + "id=" + id + + ", createdDate=" + createdDate + + ", endDate=" + endDate + + ", status='" + status + '\'' + + ", externalId='" + externalId + '\'' + + ", message='" + message + '\'' + + '}'; + } } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java b/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java index c01a8d92..5daf700c 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java +++ b/forms/src/main/java/org/devgateway/toolkit/forms/service/EurekaClientService.java @@ -58,4 +58,10 @@ public Set getServiceByMetadataType(String type) { return services; } + public ServiceMetadata getServiceByName(String name) { + return findAll().stream() + .filter(s -> s.getName().equals(name)) + .findFirst().get(); + } + } diff --git a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html index 247b7fa4..21253cb9 100644 --- a/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html +++ b/forms/src/main/java/org/devgateway/toolkit/forms/wicket/page/edit/AbstractEditPage.html @@ -20,6 +20,7 @@
+